Previous 15994 Revisions Next

r11451 Friday 6th May, 2011 at 12:48:23 UTC by Miodrag Milanović
Sync with MAME (r12440) (no whatsnew)
[src/emu]emu.mak hashfile.c* hashfile.h*
[src/emu/machine]6840ptm.c ctronics.c* ctronics.h* msm8251.c* msm8251.h* serial.c* serial.h* upd765.c* upd765.h*
[src/mame]mame.lst mame.mak
[src/mame/audio]dcs.c
[src/mame/drivers]champbwl.c dc.c* mpu4.c mpu4drvr.c segasms.c* seta.c sg1000.c*
[src/mame/formats]basicdsk.c* basicdsk.h*
[src/mame/includes]segasms.h* seta.h sg1000.h*
[src/mame/layout]sms1.lay*
[src/mame/machine]dccons.c* gdrom.c* gdrom.h* segasms.c*
[src/mame/video]seta.c seta001.c seta001.h smsvdp.c* smsvdp.h*
[src/mess]hashfile.c hashfile.h mess.mak messcore.mak
[src/mess/formats]basicdsk.c basicdsk.h
[src/mess/includes]sg1000.h sms.h
[src/mess/machine]ctronics.c ctronics.h dc.c gdrom.c gdrom.h msm8251.c msm8251.h serial.c serial.h sms.c upd765.c upd765.h
[src/mess/video]smsvdp.c smsvdp.h

src/mame/mame.lst
r11450r11451
1071510715m_gmball
1071610716m_grtecp      // 199?
1071710717m_blsbys      // BwB
10718m_frkstn
1071810719
1071910720// MPU5
1072010721m_honmon
src/mame/audio/dcs.c
r11450r11451
17591759   /* compute the absolute cycle when the next one should fire */
17601760   /* we do this to avoid drifting */
17611761   dcs.timers_fired++;
1762   target_cycles = dcs.timer_start_cycles + dcs.timer_scale * (dcs.timer_start_count + 1 + dcs.timers_fired * (dcs.timer_period + 1));
1762   target_cycles = dcs.timer_start_cycles + dcs.timer_scale * (dcs.timer_start_count + 1 + dcs.timers_fired * (UINT64)(dcs.timer_period + 1));
17631763   target_cycles -= dcs.cpu->total_cycles();
17641764
17651765   /* set the next timer, but only if it's for a reasonable number */
src/mame/machine/gdrom.c
r0r11451
1/***************************************************************************
2
3 gdrom.c - Implementation of the Sega GD-ROM device
4
5***************************************************************************/
6
7#include "emu.h"
8#include "machine/scsidev.h"
9#include "cdrom.h"
10#include "sound/cdda.h"
11#include "imagedev/chd_cd.h"
12#include "gdrom.h"
13
14typedef struct
15{
16   UINT32 lba;
17   UINT32 blocks;
18   UINT32 last_lba;
19   UINT32 bytes_per_sector;
20   UINT32 num_subblocks;
21   UINT32 cur_subblock;
22   UINT32 play_err_flag;
23   UINT32 read_type;   // for command 0x30 only
24   UINT32 data_select;   // for command 0x30 only
25   cdrom_file *cdrom;
26   bool is_file;
27} SCSIGd;
28
29static const UINT8 GDROM_Cmd11_Reply[32] =
30{
31   0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x19, 0x00, 0x00, 0x08, 0x53, 0x45, 0x20, 0x20, 0x20, 0x20,
32   0x20, 0x20, 0x52, 0x65, 0x76, 0x20, 0x36, 0x2E, 0x34, 0x32, 0x39, 0x39, 0x30, 0x33, 0x31, 0x36
33};
34
35static void phys_frame_to_msf(int phys_frame, int *m, int *s, int *f)
36{
37   *m = phys_frame / (60*75);
38   phys_frame -= (*m * 60 * 75);
39   *s = phys_frame / 75;
40   *f = phys_frame % 75;
41}
42
43
44// scsicd_exec_command
45//
46// Execute a SCSI command.
47
48static int scsicd_exec_command( SCSIInstance *scsiInstance, UINT8 *statusCode )
49{
50   UINT8 *command;
51   int commandLength;
52   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
53
54   cdrom_file *cdrom = our_this->cdrom;
55   device_t *cdda;
56   int trk;
57
58   SCSIGetCommand( scsiInstance, &command, &commandLength );
59
60   switch ( command[0] )
61   {
62
63
64      case 0x03: // REQUEST SENSE
65         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
66         return SCSILengthFromUINT8( &command[ 4 ] );
67
68      case 0x11: // REQ_MODE
69         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
70         printf("REQ_MODE %02x %02x %02x %02x %02x %02x\n",
71            command[0], command[1],
72            command[2], command[3],
73            command[4], command[5]);
74//          if (SCSILengthFromUINT8( &command[ 4 ] ) < 32) return -1;
75         return 32; //SCSILengthFromUINT8( &command[ 4 ] );
76
77      case 0x12: // INQUIRY
78         logerror("GDROM: REQUEST SENSE\n");
79         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
80         return SCSILengthFromUINT8( &command[ 4 ] );
81
82      case 0x15: // MODE SELECT(6)
83         logerror("GDROM: MODE SELECT(6) length %x control %x\n", command[4], command[5]);
84         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAOUT );
85         return SCSILengthFromUINT8( &command[ 4 ] );
86
87      case 0x1a: // MODE SENSE(6)
88         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
89         return SCSILengthFromUINT8( &command[ 4 ] );
90
91      case 0x1b: // START STOP UNIT
92         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
93         if (cdda != NULL)
94         {
95            cdda_stop_audio(cdda);
96         }
97         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
98         return 0;
99
100      case 0x1e: // PREVENT ALLOW MEDIUM REMOVAL
101         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
102         return 0;
103
104      case 0x25: // READ CAPACITY
105         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
106         return 8;
107
108      case 0x28: // READ(10)
109
110         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
111         our_this->blocks = SCSILengthFromUINT16( &command[7] );
112
113         logerror("GDROM: READ(10) at LBA %x for %d blocks (%d bytes)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector);
114
115         if (our_this->num_subblocks > 1)
116         {
117            our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
118            our_this->lba /= our_this->num_subblocks;
119         }
120         else
121         {
122            our_this->cur_subblock = 0;
123         }
124
125         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
126         if (cdda != NULL)
127         {
128            cdda_stop_audio(cdda);
129         }
130
131         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
132         return our_this->blocks * our_this->bytes_per_sector;
133
134      case 0x30: // CD_READ
135         if (command[1] & 1)
136         {
137            fatalerror("GDROM: MSF mode used for CD_READ, unsupported");
138            return 0;
139         }
140         else
141         {
142            our_this->lba = (command[2]<<16 | command[3]<<8 | command[4]) - 150;
143            our_this->blocks = command[8]<<16 | command[9]<<8 | command[10];
144
145            our_this->read_type = (command[1] >> 1) & 7;
146            our_this->data_select = (command[1]>>4) & 0xf;
147
148            if (our_this->read_type != 2)   // mode 1
149            {
150               fatalerror("GDROM: Unhandled read_type %d", our_this->read_type);
151            }
152
153            if (our_this->data_select != 2)   // just sector data
154            {
155               fatalerror("GDROM: Unhandled data_select %d", our_this->data_select);
156            }
157
158            printf("GDROM: CD_READ at LBA %x for %d blocks (%d bytes, read type %d, data select %d)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector, our_this->read_type, our_this->data_select);
159
160            if (our_this->num_subblocks > 1)
161            {
162               our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
163               our_this->lba /= our_this->num_subblocks;
164            }
165            else
166            {
167               our_this->cur_subblock = 0;
168            }
169
170            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
171            if (cdda != NULL)
172            {
173               cdda_stop_audio(cdda);
174            }
175
176            SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
177            return our_this->blocks * our_this->bytes_per_sector;
178         }
179
180      case 0x42: // READ SUB-CHANNEL
181//                      logerror("GDROM: READ SUB-CHANNEL type %d\n", command[3]);
182         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
183         return SCSILengthFromUINT16( &command[ 7 ] );
184
185      case 0x43: // READ TOC
186      {
187         int start_trk = command[6];
188         int end_trk = cdrom_get_last_track(cdrom);
189         int length;
190         int allocation_length = SCSILengthFromUINT16( &command[ 7 ] );
191
192         if( start_trk == 0 )
193         {
194            start_trk = 1;
195         }
196         if( start_trk == 0xaa )
197         {
198            end_trk = start_trk;
199         }
200
201         length = 4 + ( 8 * ( ( end_trk - start_trk ) + 1 ) );
202         if( length > allocation_length )
203         {
204            length = allocation_length;
205         }
206         else if( length < 4 )
207         {
208            length = 4;
209         }
210
211         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
212         if (cdda != NULL)
213         {
214            cdda_stop_audio(cdda);
215         }
216
217         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
218         return length;
219      }
220      case 0x45: // PLAY AUDIO(10)
221         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
222         our_this->blocks = SCSILengthFromUINT16( &command[7] );
223
224         // special cases: lba of 0 means MSF of 00:02:00
225         if (our_this->lba == 0)
226         {
227            our_this->lba = 150;
228         }
229         else if (our_this->lba == 0xffffffff)
230         {
231            logerror("GDROM: play audio from current not implemented!\n");
232         }
233
234         logerror("GDROM: PLAY AUDIO(10) at LBA %x for %x blocks\n", our_this->lba, our_this->blocks);
235
236         trk = cdrom_get_track(cdrom, our_this->lba);
237
238         if (cdrom_get_track_type(cdrom, trk) == CD_TRACK_AUDIO)
239         {
240            our_this->play_err_flag = 0;
241            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
242            if (cdda != NULL)
243               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
244         }
245         else
246         {
247            logerror("GDROM: track is NOT audio!\n");
248            our_this->play_err_flag = 1;
249         }
250
251         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
252         return 0;
253
254      case 0x48: // PLAY AUDIO TRACK/INDEX
255         // be careful: tracks here are zero-based, but the SCSI command
256         // uses the real CD track number which is 1-based!
257         our_this->lba = cdrom_get_track_start(cdrom, command[4]-1);
258         our_this->blocks = cdrom_get_track_start(cdrom, command[7]-1) - our_this->lba;
259         if (command[4] > command[7])
260         {
261            our_this->blocks = 0;
262         }
263
264         if (command[4] == command[7])
265         {
266            our_this->blocks = cdrom_get_track_start(cdrom, command[4]) - our_this->lba;
267         }
268
269         if (our_this->blocks && cdrom)
270         {
271            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
272            if (cdda != NULL)
273               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
274         }
275
276         logerror("GDROM: PLAY AUDIO T/I: strk %d idx %d etrk %d idx %d frames %d\n", command[4], command[5], command[7], command[8], our_this->blocks);
277         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
278         return 0;
279
280      case 0x4b: // PAUSE/RESUME
281         if (cdrom)
282         {
283            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
284            if (cdda != NULL)
285               cdda_pause_audio(cdda, (command[8] & 0x01) ^ 0x01);
286         }
287
288         logerror("GDROM: PAUSE/RESUME: %s\n", command[8]&1 ? "RESUME" : "PAUSE");
289         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
290         return 0;
291
292      case 0x55: // MODE SELECT(10)
293         logerror("GDROM: MODE SELECT length %x control %x\n", command[7]<<8 | command[8], command[1]);
294         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAOUT );
295         return SCSILengthFromUINT16( &command[ 7 ] );
296
297      case 0x5a: // MODE SENSE(10)
298         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
299         return SCSILengthFromUINT16( &command[ 7 ] );
300
301      case 0xa5: // PLAY AUDIO(12)
302         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
303         our_this->blocks = command[6]<<24 | command[7]<<16 | command[8]<<8 | command[9];
304
305         // special cases: lba of 0 means MSF of 00:02:00
306         if (our_this->lba == 0)
307         {
308            our_this->lba = 150;
309         }
310         else if (our_this->lba == 0xffffffff)
311         {
312            logerror("GDROM: play audio from current not implemented!\n");
313         }
314
315         logerror("GDROM: PLAY AUDIO(12) at LBA %x for %x blocks\n", our_this->lba, our_this->blocks);
316
317         trk = cdrom_get_track(cdrom, our_this->lba);
318
319         if (cdrom_get_track_type(cdrom, trk) == CD_TRACK_AUDIO)
320         {
321            our_this->play_err_flag = 0;
322            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
323            if (cdda != NULL)
324               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
325         }
326         else
327         {
328            logerror("GDROM: track is NOT audio!\n");
329            our_this->play_err_flag = 1;
330         }
331         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
332         return 0;
333
334      case 0xa8: // READ(12)
335         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
336         our_this->blocks = command[7]<<16 | command[8]<<8 | command[9];
337
338         logerror("GDROM: READ(12) at LBA %x for %x blocks (%x bytes)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector);
339
340         if (our_this->num_subblocks > 1)
341         {
342            our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
343            our_this->lba /= our_this->num_subblocks;
344         }
345         else
346         {
347            our_this->cur_subblock = 0;
348         }
349
350         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
351         if (cdda != NULL)
352         {
353            cdda_stop_audio(cdda);
354         }
355
356         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
357         return our_this->blocks * our_this->bytes_per_sector;
358
359      case 0xbb: // SET CD SPEED
360         logerror("GDROM: SET CD SPEED to %d kbytes/sec.\n", command[2]<<8 | command[3]);
361         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
362         return 0;
363
364      default:
365         return SCSIBase( &SCSIClassGDROM, SCSIOP_EXEC_COMMAND, scsiInstance, 0, NULL );
366   }
367}
368
369// scsicd_read_data
370//
371// Read data from the device resulting from the execution of a command
372
373static void scsicd_read_data( SCSIInstance *scsiInstance, UINT8 *data, int dataLength )
374{
375   UINT8 *command;
376   int commandLength;
377   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
378
379   int i;
380   UINT32 last_phys_frame;
381   cdrom_file *cdrom = our_this->cdrom;
382   UINT32 temp;
383   UINT8 tmp_buffer[2048];
384   device_t *cdda;
385
386   SCSIGetCommand( scsiInstance, &command, &commandLength );
387
388   switch ( command[0] )
389   {
390      case 0x03: // REQUEST SENSE
391         logerror("GDROM: Reading REQUEST SENSE data\n");
392
393         memset( data, 0, dataLength );
394
395         data[0] = 0x71;   // deferred error
396
397         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
398         if (cdda != NULL && cdda_audio_active(cdda))
399         {
400            data[12] = 0x00;
401            data[13] = 0x11;   // AUDIO PLAY OPERATION IN PROGRESS
402         }
403         else if (our_this->play_err_flag)
404         {
405            our_this->play_err_flag = 0;
406            data[12] = 0x64;   // ILLEGAL MODE FOR THIS TRACK
407            data[13] = 0x00;
408         }
409         // (else 00/00 means no error to report)
410         break;
411
412      case 0x11: // REQ_MODE
413         printf("REQ_MODE: dataLength %d\n", dataLength);
414         memcpy(data, &GDROM_Cmd11_Reply[0], (dataLength >= 32) ? 32 : dataLength);
415         break;
416
417      case 0x12: // INQUIRY
418         memset( data, 0, dataLength );
419         data[0] = 0x05; // device is present, device is CD/DVD (MMC-3)
420         data[1] = 0x80; // media is removable
421         data[2] = 0x05; // device complies with SPC-3 standard
422         data[3] = 0x02; // response data format = SPC-3 standard
423         // some Konami games freak out if this isn't "Sony", so we'll lie
424         // this is the actual drive on my Nagano '98 board
425         strcpy((char *)&data[8], "Sony");
426         strcpy((char *)&data[16], "CDU-76S");
427         strcpy((char *)&data[32], "1.0");
428         break;
429
430      case 0x25: // READ CAPACITY
431         logerror("GDROM: READ CAPACITY\n");
432
433         temp = cdrom_get_track_start(cdrom, 0xaa);
434         temp--;   // return the last used block on the disc
435
436         data[0] = (temp>>24) & 0xff;
437         data[1] = (temp>>16) & 0xff;
438         data[2] = (temp>>8) & 0xff;
439         data[3] = (temp & 0xff);
440         data[4] = 0;
441         data[5] = 0;
442         data[6] = (our_this->bytes_per_sector>>8)&0xff;
443         data[7] = (our_this->bytes_per_sector & 0xff);
444         break;
445
446      case 0x28: // READ(10)
447      case 0xa8: // READ(12)
448         logerror("GDROM: read %x dataLength, \n", dataLength);
449         if ((our_this->cdrom) && (our_this->blocks))
450         {
451            while (dataLength > 0)
452            {
453               if (!cdrom_read_data(our_this->cdrom, our_this->lba, tmp_buffer, CD_TRACK_MODE1))
454               {
455                  logerror("GDROM: CD read error!\n");
456               }
457
458               logerror("True LBA: %d, buffer half: %d\n", our_this->lba, our_this->cur_subblock * our_this->bytes_per_sector);
459
460               memcpy(data, &tmp_buffer[our_this->cur_subblock * our_this->bytes_per_sector], our_this->bytes_per_sector);
461
462               our_this->cur_subblock++;
463               if (our_this->cur_subblock >= our_this->num_subblocks)
464               {
465                  our_this->cur_subblock = 0;
466
467                  our_this->lba++;
468                  our_this->blocks--;
469               }
470
471               our_this->last_lba = our_this->lba;
472               dataLength -= our_this->bytes_per_sector;
473               data += our_this->bytes_per_sector;
474            }
475         }
476         break;
477
478      case 0x30: // CD_READ
479         logerror("GDROM: read %x dataLength, \n", dataLength);
480         if ((our_this->cdrom) && (our_this->blocks))
481         {
482            while (dataLength > 0)
483            {
484               if (!cdrom_read_data(our_this->cdrom, our_this->lba, tmp_buffer, CD_TRACK_MODE1))
485               {
486                  logerror("GDROM: CD read error!\n");
487               }
488
489               logerror("True LBA: %d, buffer half: %d\n", our_this->lba, our_this->cur_subblock * our_this->bytes_per_sector);
490
491               memcpy(data, &tmp_buffer[our_this->cur_subblock * our_this->bytes_per_sector], our_this->bytes_per_sector);
492
493               our_this->cur_subblock++;
494               if (our_this->cur_subblock >= our_this->num_subblocks)
495               {
496                  our_this->cur_subblock = 0;
497
498                  our_this->lba++;
499                  our_this->blocks--;
500               }
501
502               our_this->last_lba = our_this->lba;
503               dataLength -= our_this->bytes_per_sector;
504               data += our_this->bytes_per_sector;
505            }
506         }
507
508      case 0x42: // READ SUB-CHANNEL
509         switch (command[3])
510         {
511            case 1:   // return current position
512            {
513               int audio_active;
514               int msf;
515
516               if (!cdrom)
517               {
518                  return;
519               }
520
521               logerror("GDROM: READ SUB-CHANNEL Time = %x, SUBQ = %x\n", command[1], command[2]);
522
523               msf = command[1] & 0x2;
524
525               cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
526               audio_active = cdda != NULL && cdda_audio_active(cdda);
527               if (audio_active)
528               {
529                  if (cdda_audio_paused(cdda))
530                  {
531                     data[1] = 0x12;      // audio is paused
532                  }
533                  else
534                  {
535                     data[1] = 0x11;      // audio in progress
536                  }
537               }
538               else
539               {
540                  if (cdda != NULL && cdda_audio_ended(cdda))
541                  {
542                     data[1] = 0x13;   // ended successfully
543                  }
544                  else
545                  {
546//                          data[1] = 0x14;    // stopped due to error
547                     data[1] = 0x15;   // No current audio status to return
548                  }
549               }
550
551               // if audio is playing, get the latest LBA from the CDROM layer
552               if (audio_active)
553               {
554                  our_this->last_lba = cdda_get_audio_lba(cdda);
555               }
556               else
557               {
558                  our_this->last_lba = 0;
559               }
560
561               data[2] = 0;
562               data[3] = 12;      // data length
563               data[4] = 0x01;   // sub-channel format code
564               data[5] = 0x10 | (audio_active ? 0 : 4);
565               data[6] = cdrom_get_track(cdrom, our_this->last_lba) + 1;   // track
566               data[7] = 0;   // index
567
568               last_phys_frame = our_this->last_lba;
569
570               if (msf)
571               {
572                  int m,s,f;
573                  phys_frame_to_msf(last_phys_frame, &m, &s, &f);
574                  data[8] = 0;
575                  data[9] = m;
576                  data[10] = s;
577                  data[11] = f;
578               }
579               else
580               {
581                  data[8] = last_phys_frame>>24;
582                  data[9] = (last_phys_frame>>16)&0xff;
583                  data[10] = (last_phys_frame>>8)&0xff;
584                  data[11] = last_phys_frame&0xff;
585               }
586
587               last_phys_frame -= cdrom_get_track_start(cdrom, data[6] - 1);
588
589               if (msf)
590               {
591                  int m,s,f;
592                  phys_frame_to_msf(last_phys_frame, &m, &s, &f);
593                  data[12] = 0;
594                  data[13] = m;
595                  data[14] = s;
596                  data[15] = f;
597               }
598               else
599               {
600                  data[12] = last_phys_frame>>24;
601                  data[13] = (last_phys_frame>>16)&0xff;
602                  data[14] = (last_phys_frame>>8)&0xff;
603                  data[15] = last_phys_frame&0xff;
604               }
605               break;
606            }
607            default:
608               logerror("GDROM: Unknown subchannel type %d requested\n", command[3]);
609         }
610         break;
611
612      case 0x43: // READ TOC
613         /*
614                Track numbers are problematic here: 0 = lead-in, 0xaa = lead-out.
615                That makes sense in terms of how real-world CDs are referred to, but
616                our internal routines for tracks use "0" as track 1.  That probably
617                should be fixed...
618            */
619         logerror("GDROM: READ TOC, format = %d time=%d\n", command[2]&0xf,(command[1]>>1)&1);
620         switch (command[2] & 0x0f)
621         {
622            case 0:      // normal
623               {
624                  int start_trk;
625                  int end_trk;
626                  int len;
627                  int in_len;
628                  int dptr;
629                  UINT32 tstart;
630
631                  start_trk = command[6];
632                  if( start_trk == 0 )
633                  {
634                     start_trk = 1;
635                  }
636
637                  end_trk = cdrom_get_last_track(cdrom);
638                  len = (end_trk * 8) + 2;
639
640                  // the returned TOC DATA LENGTH must be the full amount,
641                  // regardless of how much we're able to pass back due to in_len
642                  dptr = 0;
643                  data[dptr++] = (len>>8) & 0xff;
644                  data[dptr++] = (len & 0xff);
645                  data[dptr++] = 1;
646                  data[dptr++] = end_trk;
647
648                  if( start_trk == 0xaa )
649                  {
650                     end_trk = 0xaa;
651                  }
652
653                  in_len = command[7]<<8 | command[8];
654
655                  for (i = start_trk; i <= end_trk; i++)
656                  {
657                     int cdrom_track = i;
658                     if( cdrom_track != 0xaa )
659                     {
660                        cdrom_track--;
661                     }
662
663                     if( dptr >= in_len )
664                     {
665                        break;
666                     }
667
668                     data[dptr++] = 0;
669                     data[dptr++] = cdrom_get_adr_control(cdrom, cdrom_track);
670                     data[dptr++] = i;
671                     data[dptr++] = 0;
672
673                     tstart = cdrom_get_track_start(cdrom, cdrom_track);
674                     if ((command[1]&2)>>1)
675                        tstart = lba_to_msf(tstart);
676                     data[dptr++] = (tstart>>24) & 0xff;
677                     data[dptr++] = (tstart>>16) & 0xff;
678                     data[dptr++] = (tstart>>8) & 0xff;
679                     data[dptr++] = (tstart & 0xff);
680                  }
681               }
682               break;
683            default:
684               logerror("GDROM: Unhandled READ TOC format %d\n", command[2]&0xf);
685               break;
686         }
687         break;
688
689      case 0x1a: // MODE SENSE(6)
690      case 0x5a: // MODE SENSE(10)
691         logerror("GDROM: MODE SENSE page code = %x, PC = %x\n", command[2] & 0x3f, (command[2]&0xc0)>>6);
692
693         switch (command[2] & 0x3f)
694         {
695            case 0xe:   // CD Audio control page
696               data[0] = 0x8e;   // page E, parameter is savable
697               data[1] = 0x0e;   // page length
698               data[2] = 0x04;   // IMMED = 1, SOTC = 0
699               data[3] = data[4] = data[5] = data[6] = data[7] = 0; // reserved
700
701               // connect each audio channel to 1 output port
702               data[8] = 1;
703               data[10] = 2;
704               data[12] = 4;
705               data[14] = 8;
706
707               // indicate max volume
708               data[9] = data[11] = data[13] = data[15] = 0xff;
709               break;
710
711            default:
712               logerror("GDROM: MODE SENSE unknown page %x\n", command[2] & 0x3f);
713               break;
714         }
715         break;
716
717      default:
718         SCSIBase( &SCSIClassGDROM, SCSIOP_READ_DATA, scsiInstance, dataLength, data );
719         break;
720   }
721}
722
723// scsicd_write_data
724//
725// Write data to the CD-ROM device as part of the execution of a command
726
727static void scsicd_write_data( SCSIInstance *scsiInstance, UINT8 *data, int dataLength )
728{
729   UINT8 *command;
730   int commandLength;
731   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
732   SCSIGetCommand( scsiInstance, &command, &commandLength );
733
734   switch (command[ 0 ])
735   {
736      case 0x15: // MODE SELECT(6)
737      case 0x55: // MODE SELECT(10)
738         logerror("GDROM: MODE SELECT page %x\n", data[0] & 0x3f);
739
740         switch (data[0] & 0x3f)
741         {
742            case 0x0:   // vendor-specific
743               // check for SGI extension to force 512-byte blocks
744               if ((data[3] == 8) && (data[10] == 2))
745               {
746                  logerror("GDROM: Experimental SGI 512-byte block extension enabled\n");
747
748                  our_this->bytes_per_sector = 512;
749                  our_this->num_subblocks = 4;
750               }
751               else
752               {
753                  logerror("GDROM: Unknown vendor-specific page!\n");
754               }
755               break;
756
757            case 0xe:   // audio page
758               logerror("Ch 0 route: %x vol: %x\n", data[8], data[9]);
759               logerror("Ch 1 route: %x vol: %x\n", data[10], data[11]);
760               logerror("Ch 2 route: %x vol: %x\n", data[12], data[13]);
761               logerror("Ch 3 route: %x vol: %x\n", data[14], data[15]);
762               break;
763         }
764         break;
765
766      default:
767         SCSIBase( &SCSIClassGDROM, SCSIOP_WRITE_DATA, scsiInstance, dataLength, data );
768         break;
769   }
770}
771
772static void scsicd_alloc_instance( SCSIInstance *scsiInstance, const char *diskregion )
773{
774   running_machine &machine = scsiInstance->machine();
775   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
776
777   our_this->lba = 0;
778   our_this->blocks = 0;
779   our_this->last_lba = 0;
780   our_this->bytes_per_sector = 2048;
781   our_this->num_subblocks = 1;
782   our_this->cur_subblock = 0;
783   our_this->play_err_flag = 0;
784
785   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->lba );
786   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->blocks );
787   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->last_lba );
788   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->bytes_per_sector );
789   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->num_subblocks );
790   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->cur_subblock );
791   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->play_err_flag );
792
793   if (machine.device( diskregion )) {
794      our_this->is_file = TRUE;
795      our_this->cdrom = cd_get_cdrom_file( machine.device( diskregion ) );
796   } else {
797      our_this->is_file = FALSE;
798      our_this->cdrom = cdrom_open(get_disk_handle( machine, diskregion ));
799   }
800
801   if (!our_this->cdrom)
802   {
803      logerror("GDROM: no CD found!\n");
804   }
805}
806
807static void scsicd_delete_instance( SCSIInstance *scsiInstance )
808{
809   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
810   if (!our_this->is_file) {
811      if( our_this->cdrom )
812      {
813         cdrom_close( our_this->cdrom );
814      }
815   }
816}
817
818static void scsicd_get_device( SCSIInstance *scsiInstance, cdrom_file **cdrom )
819{
820   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
821   *cdrom = our_this->cdrom;
822}
823
824static void scsicd_set_device( SCSIInstance *scsiInstance, cdrom_file *cdrom )
825{
826   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
827   our_this->cdrom = cdrom;
828}
829
830static int scsigd_dispatch(int operation, void *file, INT64 intparm, void *ptrparm)
831{
832   SCSIAllocInstanceParams *params;
833
834   switch (operation)
835   {
836      case SCSIOP_EXEC_COMMAND:
837         return scsicd_exec_command( (SCSIInstance *)file, (UINT8 *)ptrparm );
838
839      case SCSIOP_READ_DATA:
840         scsicd_read_data( (SCSIInstance *)file, (UINT8 *)ptrparm, intparm );
841         return 0;
842
843      case SCSIOP_WRITE_DATA:
844         scsicd_write_data( (SCSIInstance *)file, (UINT8 *)ptrparm, intparm );
845         return 0;
846
847      case SCSIOP_ALLOC_INSTANCE:
848         params = (SCSIAllocInstanceParams *)ptrparm;
849         SCSIBase( &SCSIClassGDROM, operation, (SCSIInstance *)file, intparm, (UINT8 *)ptrparm );
850         scsicd_alloc_instance( params->instance, params->diskregion );
851         return 0;
852
853      case SCSIOP_DELETE_INSTANCE:
854         scsicd_delete_instance( (SCSIInstance *)file );
855         break;
856
857      case SCSIOP_GET_DEVICE:
858         scsicd_get_device( (SCSIInstance *)file, (cdrom_file **)ptrparm );
859         return 0;
860
861      case SCSIOP_SET_DEVICE:
862         scsicd_set_device( (SCSIInstance *)file, (cdrom_file *)ptrparm );
863         return 0;
864   }
865
866   return SCSIBase( &SCSIClassGDROM, operation, (SCSIInstance *)file, intparm, (UINT8 *)ptrparm );
867}
868
869const SCSIClass SCSIClassGDROM =
870{
871   &SCSIClassDevice,
872   scsigd_dispatch,
873   sizeof( SCSIGd )
874};
src/mame/machine/gdrom.h
r0r11451
1/***************************************************************************
2
3 gdrom.h
4
5***************************************************************************/
6
7#ifndef _GDROM_H_
8#define _GDROM_H_
9
10#include "machine/scsi.h"
11
12// Sega GD-ROM handler
13extern const SCSIClass SCSIClassGDROM;
14#define SCSI_DEVICE_GDROM &SCSIClassGDROM
15
16#endif
17
src/mame/machine/segasms.c
r0r11451
1#include "emu.h"
2#include "crsshair.h"
3#include "image.h"
4#include "includes/segasms.h"
5#include "video/smsvdp.h"
6#include "sound/2413intf.h"
7#include "imagedev/cartslot.h"
8#include "hashfile.h"
9
10#define VERBOSE 0
11#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
12
13#define CF_CODEMASTERS_MAPPER    0x01
14#define CF_KOREAN_MAPPER         0x02
15#define CF_KOREAN_ZEMINA_MAPPER  0x04
16#define CF_KOREAN_NOBANK_MAPPER  0x08
17#define CF_93C46_EEPROM          0x10
18#define CF_ONCART_RAM            0x20
19#define CF_GG_SMS_MODE           0x40
20
21#define LGUN_RADIUS           6
22#define LGUN_X_INTERVAL       4
23
24
25static void setup_rom(address_space *space);
26
27
28static TIMER_CALLBACK( rapid_fire_callback )
29{
30   sms_state *state = machine.driver_data<sms_state>();
31   state->m_rapid_fire_state_1 ^= 0xff;
32   state->m_rapid_fire_state_2 ^= 0xff;
33}
34
35
36static WRITE8_HANDLER( sms_input_write )
37{
38   sms_state *state = space->machine().driver_data<sms_state>();
39
40   switch (offset)
41   {
42   case 0:
43      switch (input_port_read_safe(space->machine(), "CTRLSEL", 0x00) & 0x0f)
44      {
45      case 0x03:   /* Sports Pad */
46         if (data != state->m_sports_pad_last_data_1)
47         {
48            UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
49
50            state->m_sports_pad_last_data_1 = data;
51            if (cpu_cycles - state->m_last_sports_pad_time_1 > 512)
52            {
53               state->m_sports_pad_state_1 = 3;
54               state->m_sports_pad_1_x = input_port_read(space->machine(), "SPORT0");
55               state->m_sports_pad_1_y = input_port_read(space->machine(), "SPORT1");
56            }
57            state->m_last_sports_pad_time_1 = cpu_cycles;
58            state->m_sports_pad_state_1 = (state->m_sports_pad_state_1 + 1) & 3;
59         }
60         break;
61      }
62      break;
63
64   case 1:
65      switch (input_port_read_safe(space->machine(), "CTRLSEL", 0x00) >> 4)
66      {
67      case 0x03:   /* Sports Pad */
68         if (data != state->m_sports_pad_last_data_2)
69         {
70            UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
71
72            state->m_sports_pad_last_data_2 = data;
73            if (cpu_cycles - state->m_last_sports_pad_time_2 > 2048)
74            {
75               state->m_sports_pad_state_2 = 3;
76               state->m_sports_pad_2_x = input_port_read(space->machine(), "SPORT2");
77               state->m_sports_pad_2_y = input_port_read(space->machine(), "SPORT3");
78            }
79            state->m_last_sports_pad_time_2 = cpu_cycles;
80            state->m_sports_pad_state_2 = (state->m_sports_pad_state_2 + 1) & 3;
81         }
82         break;
83      }
84      break;
85   }
86}
87
88/* FIXME: this function is a hack for Light Phaser emulation. Theoretically
89   sms_vdp_hcount_latch() should be used instead, but it returns incorrect
90   position for unknown reason (timing?) */
91static void sms_vdp_hcount_lphaser( running_machine &machine, int hpos )
92{
93   sms_state *state = machine.driver_data<sms_state>();
94   int hpos_tmp = hpos + state->m_lphaser_x_offs;
95   UINT8 tmp = ((hpos_tmp - 46) >> 1) & 0xff;
96
97   //printf ("sms_vdp_hcount_lphaser: hpos %3d hpos_tmp %3d => hcount %2X\n", hpos, hpos_tmp, tmp);
98   sms_vdp_hcount_latch_w(state->m_vdp, 0, tmp);
99}
100
101
102/*
103    Light Phaser (light gun) emulation notes:
104    - The sensor is activated based on color brightness of some individual
105      pixels being drawn by the beam, at circular area where the gun is aiming.
106    - Currently, brightness is calculated based only on single pixels.
107    - In general, after the trigger is pressed, games draw the next frame using
108      a light color pattern, to make sure sensor will be activated. If emulation
109      skips that frame, sensor may stay deactivated. Frameskip set to 0 (no skip) is
110      recommended to avoid problems.
111    - When sensor switches from off to on, a value is latched for HCount register
112      and a flag is set. The emulation uses the flag to avoid sequential latches and
113      to signal that TH line is activated when the status of the input port is read.
114      When the status is read, the flag is cleared, or else it is cleared later when
115      the Pause status is read (end of a frame). This is necessary because the
116      "Color & Switch Test" ROM only reads the TH bit after the VINT line.
117    - The gun test of "Color & Switch Test" is an example that requires checks
118      of sensor status independent of other events, like trigger press or TH bit
119      reads. Another example is the title screen of "Hang-On & Safari Hunt", where
120      the game only reads HCount register in a loop, expecting a latch by the gun.
121    - The whole procedure is managed by a timer callback, that always reschedule
122      itself to run in some intervals when the beam is at the circular area.
123*/
124static int lgun_bright_aim_area( running_machine &machine, emu_timer *timer, int lgun_x, int lgun_y )
125{
126   sms_state *state = machine.driver_data<sms_state>();
127   const int r_x_r = LGUN_RADIUS * LGUN_RADIUS;
128   screen_device *screen = machine.first_screen();
129   const rectangle &visarea = screen->visible_area();
130   int beam_x = screen->hpos();
131   int beam_y = screen->vpos();
132   int dx, dy;
133   int result = 0;
134   int pos_changed = 0;
135   double dx_circ;
136
137    while (1)
138   {
139      dy = abs(beam_y - lgun_y);
140
141      if (dy > LGUN_RADIUS || beam_y < visarea.min_y || beam_y > visarea.max_y)
142      {
143         beam_y = lgun_y - LGUN_RADIUS;
144         if (beam_y < visarea.min_y)
145            beam_y = visarea.min_y;
146         dy = abs(beam_y - lgun_y);
147         pos_changed = 1;
148      }
149      /* step 1: r^2 = dx^2 + dy^2 */
150      /* step 2: dx^2 = r^2 - dy^2 */
151      /* step 3: dx = sqrt(r^2 - dy^2) */
152      dx_circ = ceil((float) sqrt((float) (r_x_r - (dy * dy))));
153      dx = abs(beam_x - lgun_x);
154
155      if (dx > dx_circ || beam_x < visarea.min_x || beam_x > visarea.max_x)
156      {
157         if (beam_x > lgun_x)
158         {
159            beam_x = 0;
160            beam_y++;
161            continue;
162         }
163         beam_x = lgun_x - dx_circ;
164         if (beam_x < visarea.min_x)
165            beam_x = visarea.min_x;
166         pos_changed = 1;
167      }
168
169      if (!pos_changed)
170      {
171         result = sms_vdp_check_brightness(state->m_vdp, beam_x, beam_y);
172         /* next check at same line */
173         beam_x += LGUN_X_INTERVAL;
174         pos_changed = 1;
175      }
176      else
177         break;
178   }
179   timer->adjust(machine.first_screen()->time_until_pos(beam_y, beam_x));
180
181   return result;
182}
183
184static UINT8 sms_vdp_hcount( running_machine &machine )
185{
186   UINT8 tmp;
187   screen_device *screen = machine.first_screen();
188   int hpos = screen->hpos();
189
190   /* alternative method: pass HCounter test, but some others fail */
191   //int hpos_tmp = hpos;
192   //if ((hpos + 2) % 6 == 0) hpos_tmp--;
193   //tmp = ((hpos_tmp - 46) >> 1) & 0xff;
194
195   UINT64 calc_cycles;
196   attotime time_end;
197   int vpos = screen->vpos();
198   int max_hpos = screen->width() - 1;
199
200   if (hpos == max_hpos)
201      time_end = attotime::zero;
202   else
203      time_end = screen->time_until_pos(vpos, max_hpos);
204   calc_cycles = machine.device<cpu_device>("maincpu")->attotime_to_clocks(time_end);
205
206   /* equation got from SMSPower forum, posted by Flubba. */
207   tmp = ((590 - (calc_cycles * 3)) / 4) & 0xff;
208
209   //printf ("sms_vdp_hcount: hpos %3d => hcount %2X\n", hpos, tmp);
210   return tmp;
211}
212
213
214static void sms_vdp_hcount_latch( running_machine &machine )
215{
216   sms_state *state = machine.driver_data<sms_state>();
217   UINT8 value = sms_vdp_hcount(machine);
218
219   sms_vdp_hcount_latch_w(state->m_vdp, 0, value);
220}
221
222
223static UINT16 screen_hpos_nonscaled( screen_device *screen, int scaled_hpos )
224{
225   const rectangle &visarea = screen->visible_area();
226   int offset_x = (scaled_hpos * (visarea.max_x - visarea.min_x)) / 255;
227   return visarea.min_x + offset_x;
228}
229
230
231static UINT16 screen_vpos_nonscaled( screen_device *screen, int scaled_vpos )
232{
233   const rectangle &visarea = screen->visible_area();
234   int offset_y = (scaled_vpos * (visarea.max_y - visarea.min_y)) / 255;
235   return visarea.min_y + offset_y;
236}
237
238
239static void lphaser1_sensor_check( running_machine &machine )
240{
241   sms_state *state = machine.driver_data<sms_state>();
242   const int x = screen_hpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER0"));
243   const int y = screen_vpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER1"));
244
245   if (lgun_bright_aim_area(machine, state->m_lphaser_1_timer, x, y))
246   {
247      if (state->m_lphaser_1_latch == 0)
248      {
249         state->m_lphaser_1_latch = 1;
250         sms_vdp_hcount_lphaser(machine, x);
251      }
252   }
253}
254
255static void lphaser2_sensor_check( running_machine &machine )
256{
257   sms_state *state = machine.driver_data<sms_state>();
258   const int x = screen_hpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER2"));
259   const int y = screen_vpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER3"));
260
261   if (lgun_bright_aim_area(machine, state->m_lphaser_2_timer, x, y))
262   {
263      if (state->m_lphaser_2_latch == 0)
264      {
265         state->m_lphaser_2_latch = 1;
266         sms_vdp_hcount_lphaser(machine, x);
267      }
268   }
269}
270
271
272// at each input port read we check if lightguns are enabled in one of the ports:
273// if so, we turn on crosshair and the lightgun timer
274static TIMER_CALLBACK( lightgun_tick )
275{
276   sms_state *state = machine.driver_data<sms_state>();
277
278   if ((input_port_read_safe(machine, "CTRLSEL", 0x00) & 0x0f) == 0x01)
279   {
280      /* enable crosshair */
281      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_ALL);
282      if (!state->m_lphaser_1_timer->enabled())
283         lphaser1_sensor_check(machine);
284   }
285   else
286   {
287      /* disable crosshair */
288      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_NONE);
289      state->m_lphaser_1_timer->enable(0);
290   }
291
292   if ((input_port_read_safe(machine, "CTRLSEL", 0x00) & 0xf0) == 0x10)
293   {
294      /* enable crosshair */
295      crosshair_set_screen(machine, 1, CROSSHAIR_SCREEN_ALL);
296      if (!state->m_lphaser_2_timer->enabled())
297         lphaser2_sensor_check(machine);
298   }
299   else
300   {
301      /* disable crosshair */
302      crosshair_set_screen(machine, 1, CROSSHAIR_SCREEN_NONE);
303      state->m_lphaser_2_timer->enable(0);
304   }
305}
306
307
308static TIMER_CALLBACK( lphaser_1_callback )
309{
310   lphaser1_sensor_check(machine);
311}
312
313
314static TIMER_CALLBACK( lphaser_2_callback )
315{
316   lphaser2_sensor_check(machine);
317}
318
319
320INPUT_CHANGED( lgun1_changed )
321{
322   sms_state *state = field->port->machine().driver_data<sms_state>();
323   if (!state->m_lphaser_1_timer ||
324      (input_port_read_safe(field->port->machine(), "CTRLSEL", 0x00) & 0x0f) != 0x01)
325      return;
326
327   if (newval != oldval)
328      lphaser1_sensor_check(field->port->machine());
329}
330
331INPUT_CHANGED( lgun2_changed )
332{
333   sms_state *state = field->port->machine().driver_data<sms_state>();
334   if (!state->m_lphaser_2_timer ||
335      (input_port_read_safe(field->port->machine(), "CTRLSEL", 0x00) & 0xf0) != 0x10)
336      return;
337
338   if (newval != oldval)
339      lphaser2_sensor_check(field->port->machine());
340}
341
342
343static void sms_get_inputs( address_space *space )
344{
345   sms_state *state = space->machine().driver_data<sms_state>();
346   UINT8 data = 0x00;
347   UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
348   running_machine &machine = space->machine();
349
350   state->m_input_port0 = 0xff;
351   state->m_input_port1 = 0xff;
352
353   if (cpu_cycles - state->m_last_paddle_read_time > 256)
354   {
355      state->m_paddle_read_state ^= 0xff;
356      state->m_last_paddle_read_time = cpu_cycles;
357   }
358
359   /* Check if lightgun has been chosen as input: if so, enable crosshair */
360   machine.scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
361
362   /* Player 1 */
363   switch (input_port_read_safe(machine, "CTRLSEL", 0x00) & 0x0f)
364   {
365   case 0x00:  /* Joystick */
366      data = input_port_read(machine, "PORT_DC");
367      /* Check Rapid Fire setting for Button A */
368      if (!(data & 0x10) && (input_port_read(machine, "RFU") & 0x01))
369         data |= state->m_rapid_fire_state_1 & 0x10;
370
371      /* Check Rapid Fire setting for Button B */
372      if (!(data & 0x20) && (input_port_read(machine, "RFU") & 0x02))
373         data |= state->m_rapid_fire_state_1 & 0x20;
374
375      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x3f);
376      break;
377
378   case 0x01:  /* Light Phaser */
379      data = (input_port_read(machine, "CTRLIPT") & 0x01) << 4;
380      if (!(data & 0x10))
381      {
382         if (input_port_read(machine, "RFU") & 0x01)
383            data |= state->m_rapid_fire_state_1 & 0x10;
384      }
385      /* just consider the button (trigger) bit */
386      data |= ~0x10;
387      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x3f);
388      break;
389
390   case 0x02:  /* Paddle Control */
391      /* Get button A state */
392      data = input_port_read(machine, "PADDLE0");
393
394      if (state->m_paddle_read_state)
395         data = data >> 4;
396
397      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x0f) | (state->m_paddle_read_state & 0x20)
398                      | ((input_port_read(machine, "CTRLIPT") & 0x02) << 3);
399      break;
400
401   case 0x03:   /* Sega Sports Pad */
402      switch (state->m_sports_pad_state_1)
403      {
404      case 0:
405         data = (state->m_sports_pad_1_x >> 4) & 0x0f;
406         break;
407      case 1:
408         data = state->m_sports_pad_1_x & 0x0f;
409         break;
410      case 2:
411         data = (state->m_sports_pad_1_y >> 4) & 0x0f;
412         break;
413      case 3:
414         data = state->m_sports_pad_1_y & 0x0f;
415         break;
416      }
417      state->m_input_port0 = (state->m_input_port0 & 0xc0) | data | ((input_port_read(machine, "CTRLIPT") & 0x0c) << 2);
418      break;
419   }
420
421   /* Player 2 */
422   switch (input_port_read_safe(machine, "CTRLSEL", 0x00)  & 0xf0)
423   {
424   case 0x00:   /* Joystick */
425      data = input_port_read(machine, "PORT_DC");
426      state->m_input_port0 = (state->m_input_port0 & 0x3f) | (data & 0xc0);
427
428      data = input_port_read(machine, "PORT_DD");
429      /* Check Rapid Fire setting for Button A */
430      if (!(data & 0x04) && (input_port_read(machine, "RFU") & 0x04))
431         data |= state->m_rapid_fire_state_2 & 0x04;
432
433      /* Check Rapid Fire setting for Button B */
434      if (!(data & 0x08) && (input_port_read(machine, "RFU") & 0x08))
435         data |= state->m_rapid_fire_state_2 & 0x08;
436
437      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data & 0x0f);
438      break;
439
440   case 0x10:   /* Light Phaser */
441      data = (input_port_read(machine, "CTRLIPT") & 0x10) >> 2;
442      if (!(data & 0x04))
443      {
444         if (input_port_read(machine, "RFU") & 0x04)
445            data |= state->m_rapid_fire_state_2 & 0x04;
446      }
447      /* just consider the button (trigger) bit */
448      data |= ~0x04;
449      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data & 0x0f);
450      break;
451
452   case 0x20:   /* Paddle Control */
453      /* Get button A state */
454      data = input_port_read(machine, "PADDLE1");
455      if (state->m_paddle_read_state)
456         data = data >> 4;
457
458      state->m_input_port0 = (state->m_input_port0 & 0x3f) | ((data & 0x03) << 6);
459      state->m_input_port1 = (state->m_input_port1 & 0xf0) | ((data & 0x0c) >> 2) | (state->m_paddle_read_state & 0x08)
460                      | ((input_port_read(machine, "CTRLIPT") & 0x20) >> 3);
461      break;
462
463   case 0x30:   /* Sega Sports Pad */
464      switch (state->m_sports_pad_state_2)
465      {
466      case 0:
467         data = state->m_sports_pad_2_x & 0x0f;
468         break;
469      case 1:
470         data = (state->m_sports_pad_2_x >> 4) & 0x0f;
471         break;
472      case 2:
473         data = state->m_sports_pad_2_y & 0x0f;
474         break;
475      case 3:
476         data = (state->m_sports_pad_2_y >> 4) & 0x0f;
477         break;
478      }
479      state->m_input_port0 = (state->m_input_port0 & 0x3f) | ((data & 0x03) << 6);
480      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data >> 2) | ((input_port_read(machine, "CTRLIPT") & 0xc0) >> 4);
481      break;
482   }
483}
484
485
486WRITE8_HANDLER( sms_fm_detect_w )
487{
488   sms_state *state = space->machine().driver_data<sms_state>();
489
490   if (state->m_has_fm)
491      state->m_fm_detect = (data & 0x01);
492}
493
494
495READ8_HANDLER( sms_fm_detect_r )
496{
497   sms_state *state = space->machine().driver_data<sms_state>();
498
499   if (state->m_has_fm)
500   {
501      return state->m_fm_detect;
502   }
503   else
504   {
505      if (state->m_bios_port & IO_CHIP)
506      {
507         return 0xff;
508      }
509      else
510      {
511         sms_get_inputs(space);
512         return state->m_input_port0;
513      }
514   }
515}
516
517WRITE8_HANDLER( sms_io_control_w )
518{
519   sms_state *state = space->machine().driver_data<sms_state>();
520
521   if (data & 0x08)
522   {
523      /* check if TH pin level is high (1) and was low last time */
524      if (data & 0x80 && !(state->m_ctrl_reg & 0x80))
525      {
526         sms_vdp_hcount_latch(space->machine());
527      }
528      sms_input_write(space, 0, (data & 0x20) >> 5);
529   }
530
531   if (data & 0x02)
532   {
533      if (data & 0x20 && !(state->m_ctrl_reg & 0x20))
534      {
535         sms_vdp_hcount_latch(space->machine());
536      }
537      sms_input_write(space, 1, (data & 0x80) >> 7);
538   }
539
540   state->m_ctrl_reg = data;
541}
542
543
544READ8_HANDLER( sms_count_r )
545{
546   sms_state *state = space->machine().driver_data<sms_state>();
547
548   if (offset & 0x01)
549      return sms_vdp_hcount_latch_r(state->m_vdp, offset);
550   else
551      return sms_vdp_vcount_r(state->m_vdp, offset);
552}
553
554
555/*
556 Check if the pause button is pressed.
557 If the gamegear is in sms mode, check if the start button is pressed.
558 */
559void sms_pause_callback( running_machine &machine )
560{
561   sms_state *state = machine.driver_data<sms_state>();
562
563   if (state->m_is_gamegear && !(state->m_cartridge[state->m_current_cartridge].features & CF_GG_SMS_MODE))
564      return;
565
566   if (!(input_port_read(machine, state->m_is_gamegear ? "START" : "PAUSE") & 0x80))
567   {
568      if (!state->m_paused)
569      {
570         cputag_set_input_line(machine, "maincpu", INPUT_LINE_NMI, PULSE_LINE);
571      }
572      state->m_paused = 1;
573   }
574   else
575   {
576      state->m_paused = 0;
577   }
578
579   /* clear Light Phaser latch flags for next frame */
580   state->m_lphaser_1_latch = 0;
581   state->m_lphaser_2_latch = 0;
582}
583
584READ8_HANDLER( sms_input_port_0_r )
585{
586   sms_state *state = space->machine().driver_data<sms_state>();
587
588   if (state->m_bios_port & IO_CHIP)
589   {
590      return 0xff;
591   }
592   else
593   {
594      sms_get_inputs(space);
595      return state->m_input_port0;
596   }
597}
598
599
600READ8_HANDLER( sms_input_port_1_r )
601{
602   sms_state *state = space->machine().driver_data<sms_state>();
603
604   if (state->m_bios_port & IO_CHIP)
605      return 0xff;
606
607   sms_get_inputs(space);
608
609   /* Reset Button */
610   state->m_input_port1 = (state->m_input_port1 & 0xef) | (input_port_read_safe(space->machine(), "RESET", 0x01) & 0x01) << 4;
611
612   /* Do region detection if TH of ports A and B are set to output (0) */
613   if (!(state->m_ctrl_reg & 0x0a))
614   {
615      /* Move bits 7,5 of IO control port into bits 7, 6 */
616      state->m_input_port1 = (state->m_input_port1 & 0x3f) | (state->m_ctrl_reg & 0x80) | (state->m_ctrl_reg & 0x20) << 1;
617
618      /* Inverse region detect value for Japanese machines */
619      if (state->m_is_region_japan)
620         state->m_input_port1 ^= 0xc0;
621   }
622   else
623   {
624      if (state->m_ctrl_reg & 0x02 && state->m_lphaser_1_latch)
625      {
626         state->m_input_port1 &= ~0x40;
627         state->m_lphaser_1_latch = 0;
628      }
629
630      if (state->m_ctrl_reg & 0x08 && state->m_lphaser_2_latch)
631      {
632         state->m_input_port1 &= ~0x80;
633         state->m_lphaser_2_latch = 0;
634      }
635   }
636
637   return state->m_input_port1;
638}
639
640
641
642WRITE8_HANDLER( sms_ym2413_register_port_0_w )
643{
644   sms_state *state = space->machine().driver_data<sms_state>();
645
646   if (state->m_has_fm)
647      ym2413_w(state->m_ym, 0, (data & 0x3f));
648}
649
650
651WRITE8_HANDLER( sms_ym2413_data_port_0_w )
652{
653   sms_state *state = space->machine().driver_data<sms_state>();
654
655   if (state->m_has_fm)
656   {
657      logerror("data_port_0_w %x %x\n", offset, data);
658      ym2413_w(state->m_ym, 1, data);
659   }
660}
661
662
663READ8_HANDLER( gg_input_port_2_r )
664{
665   sms_state *state = space->machine().driver_data<sms_state>();
666
667   //logerror("joy 2 read, val: %02x, pc: %04x\n", ((state->m_is_region_japan ? 0x00 : 0x40) | (input_port_read(machine, "START") & 0x80)), activecpu_get_pc());
668   return ((state->m_is_region_japan ? 0x00 : 0x40) | (input_port_read(space->machine(), "START") & 0x80));
669}
670
671
672READ8_HANDLER( sms_sscope_r )
673{
674   sms_state *state = space->machine().driver_data<sms_state>();
675   return state->m_sscope_state;
676}
677
678
679WRITE8_HANDLER( sms_sscope_w )
680{
681   sms_state *state = space->machine().driver_data<sms_state>();
682   state->m_sscope_state = data;
683}
684
685
686READ8_HANDLER( sms_mapper_r )
687{
688   sms_state *state = space->machine().driver_data<sms_state>();
689   return state->m_mapper[offset];
690}
691
692/* Terebi Oekaki */
693/* The following code comes from sg1000.c. We should eventually merge these TV Draw implementations */
694static WRITE8_HANDLER( sms_tvdraw_axis_w )
695{
696   sms_state *state = space->machine().driver_data<sms_state>();
697   UINT8 tvboard_on = input_port_read_safe(space->machine(), "TVDRAW", 0x00);
698
699   if (data & 0x01)
700   {
701      state->m_tvdraw_data = tvboard_on ? input_port_read(space->machine(), "TVDRAW_X") : 0x80;
702
703      if (state->m_tvdraw_data < 4) state->m_tvdraw_data = 4;
704      if (state->m_tvdraw_data > 251) state->m_tvdraw_data = 251;
705   }
706   else
707   {
708      state->m_tvdraw_data = tvboard_on ? input_port_read(space->machine(), "TVDRAW_Y") + 0x20 : 0x80;
709   }
710}
711
712static READ8_HANDLER( sms_tvdraw_status_r )
713{
714   UINT8 tvboard_on = input_port_read_safe(space->machine(), "TVDRAW", 0x00);
715   return tvboard_on ? input_port_read(space->machine(), "TVDRAW_PEN") : 0x01;
716}
717
718static READ8_HANDLER( sms_tvdraw_data_r )
719{
720   sms_state *state = space->machine().driver_data<sms_state>();
721   return state->m_tvdraw_data;
722}
723
724
725WRITE8_HANDLER( sms_mapper_w )
726{
727   sms_state *state = space->machine().driver_data<sms_state>();
728   int page;
729   UINT8 *SOURCE_BIOS;
730   UINT8 *SOURCE_CART;
731   UINT8 *SOURCE;
732   UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
733
734   offset &= 3;
735
736   state->m_mapper[offset] = data;
737   state->m_mapper_ram[offset] = data;
738
739   if (state->m_cartridge[state->m_current_cartridge].ROM)
740   {
741      SOURCE_CART = state->m_cartridge[state->m_current_cartridge].ROM + (( rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
742   }
743   else
744   {
745      SOURCE_CART = state->m_banking_none[1];
746   }
747
748   if (state->m_BIOS)
749   {
750      SOURCE_BIOS = state->m_BIOS + ((state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0) * 0x4000;
751   }
752   else
753   {
754      SOURCE_BIOS = state->m_banking_none[1];
755   }
756
757   if (state->m_bios_port & IO_BIOS_ROM || (state->m_is_gamegear && state->m_BIOS == NULL))
758   {
759      if (!(state->m_bios_port & IO_CARTRIDGE) || (state->m_is_gamegear && state->m_BIOS == NULL))
760      {
761         page = (rom_page_count > 0) ? data % rom_page_count : 0;
762         if (!state->m_cartridge[state->m_current_cartridge].ROM)
763            return;
764         SOURCE = SOURCE_CART;
765      }
766      else
767      {
768         /* nothing to page in */
769         return;
770      }
771   }
772   else
773   {
774      page = (state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0;
775      if (!state->m_BIOS)
776         return;
777      SOURCE = SOURCE_BIOS;
778   }
779
780   switch (offset)
781   {
782   case 0: /* Control */
783      /* Is it ram or rom? */
784      if (data & 0x08) /* it's ram */
785      {
786         state->m_cartridge[state->m_current_cartridge].sram_save = 1;         /* SRAM should be saved on exit. */
787         if (data & 0x04)
788         {
789            LOG(("ram 1 paged.\n"));
790            SOURCE = state->m_cartridge[state->m_current_cartridge].cartSRAM + 0x4000;
791         }
792         else
793         {
794            LOG(("ram 0 paged.\n"));
795            SOURCE = state->m_cartridge[state->m_current_cartridge].cartSRAM;
796         }
797         memory_set_bankptr(space->machine(),  "bank5", SOURCE);
798         memory_set_bankptr(space->machine(),  "bank6", SOURCE + 0x2000);
799      }
800      else /* it's rom */
801      {
802         if (state->m_bios_port & IO_BIOS_ROM || ! state->m_has_bios)
803         {
804            page = (rom_page_count > 0) ? state->m_mapper[3] % rom_page_count : 0;
805            SOURCE = state->m_banking_cart[5];
806         }
807         else
808         {
809            page = (state->m_bios_page_count > 0) ? state->m_mapper[3] % state->m_bios_page_count : 0;
810            SOURCE = state->m_banking_bios[5];
811         }
812         LOG(("rom 2 paged in %x.\n", page));
813         memory_set_bankptr(space->machine(), "bank5", SOURCE);
814         memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
815      }
816      break;
817
818   case 1: /* Select 16k ROM bank for 0400-3FFF */
819      LOG(("rom 0 paged in %x.\n", page));
820      state->m_banking_bios[2] = SOURCE_BIOS + 0x0400;
821      state->m_banking_cart[2] = SOURCE_CART + 0x0400;
822      if (state->m_is_gamegear)
823         SOURCE = SOURCE_CART;
824
825      memory_set_bankptr(space->machine(), "bank2", SOURCE + 0x0400);
826      break;
827
828   case 2: /* Select 16k ROM bank for 4000-7FFF */
829      LOG(("rom 1 paged in %x.\n", page));
830      state->m_banking_bios[3] = SOURCE_BIOS;
831      state->m_banking_cart[3] = SOURCE_CART;
832      if (state->m_is_gamegear)
833         SOURCE = SOURCE_CART;
834
835      memory_set_bankptr(space->machine(), "bank3", SOURCE);
836      memory_set_bankptr(space->machine(), "bank4", SOURCE + 0x2000);
837      break;
838
839   case 3: /* Select 16k ROM bank for 8000-BFFF */
840      state->m_banking_bios[5] = SOURCE_BIOS;
841      if (state->m_is_gamegear)
842         SOURCE = SOURCE_CART;
843
844      if ( state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
845      {
846         if (SOURCE == SOURCE_CART)
847         {
848            SOURCE = state->m_banking_cart[5];
849         }
850      }
851      else
852      {
853         state->m_banking_cart[5] = SOURCE_CART;
854      }
855
856      if (!(state->m_mapper[0] & 0x08)) /* is RAM disabled? */
857      {
858         LOG(("rom 2 paged in %x.\n", page));
859         memory_set_bankptr(space->machine(), "bank5", SOURCE);
860         memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
861      }
862      break;
863   }
864}
865
866#ifdef MESS
867static WRITE8_HANDLER( sms_korean_zemina_banksw_w )
868{
869   sms_state *state = space->machine().driver_data<sms_state>();
870
871   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_ZEMINA_MAPPER)
872   {
873      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x2000;
874      int page = (rom_page_count > 0) ? data % rom_page_count : 0;
875
876      if (!state->m_cartridge[state->m_current_cartridge].ROM)
877         return;
878
879      switch (offset & 3)
880      {
881         case 0:
882            state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
883            memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
884            break;
885         case 1:
886            state->m_banking_cart[6] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
887            memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[6]);
888            break;
889         case 2:
890            state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
891            memory_set_bankptr(space->machine(), "bank3", state->m_banking_cart[3]);
892            break;
893         case 3:
894            state->m_banking_cart[4] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
895            memory_set_bankptr(space->machine(), "bank4", state->m_banking_cart[4]);
896            break;
897      }
898      LOG(("Zemina mapper write: offset %x data %x.\n", offset, page));
899   }
900}
901
902static WRITE8_HANDLER( sms_codemasters_page0_w )
903{
904   sms_state *state = space->machine().driver_data<sms_state>();
905
906   if (state->m_cartridge[state->m_current_cartridge].ROM && state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
907   {
908      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
909      state->m_banking_cart[1] = state->m_cartridge[state->m_current_cartridge].ROM + ((rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
910      state->m_banking_cart[2] = state->m_banking_cart[1] + 0x0400;
911      memory_set_bankptr(space->machine(), "bank1", state->m_banking_cart[1]);
912      memory_set_bankptr(space->machine(), "bank2", state->m_banking_cart[2]);
913   }
914}
915
916
917static WRITE8_HANDLER( sms_codemasters_page1_w )
918{
919   sms_state *state = space->machine().driver_data<sms_state>();
920
921   if (state->m_cartridge[state->m_current_cartridge].ROM && state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
922   {
923      /* Check if we need to switch in some RAM */
924      if (data & 0x80)
925      {
926         state->m_cartridge[state->m_current_cartridge].ram_page = data & 0x07;
927         memory_set_bankptr(space->machine(), "bank6", state->m_cartridge[state->m_current_cartridge].cartRAM + state->m_cartridge[state->m_current_cartridge].ram_page * 0x2000);
928      }
929      else
930      {
931         UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
932         state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + ((rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
933         memory_set_bankptr(space->machine(), "bank3", state->m_banking_cart[3]);
934         memory_set_bankptr(space->machine(), "bank4", state->m_banking_cart[3] + 0x2000);
935         memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
936      }
937   }
938}
939#endif
940
941static READ8_HANDLER( sms_kor_nobank_r )
942{
943//  printf("read %x\n", offset);
944   return space->read_byte(0xdffc + offset);
945}
946
947static WRITE8_HANDLER( sms_kor_nobank_w )
948{
949   sms_state *state = space->machine().driver_data<sms_state>();
950   UINT8 *SOURCE_BIOS;
951   UINT8 *SOURCE = NULL;
952
953   space->write_byte(0xdffc + offset, data);
954   state->m_mapper[offset] = data;
955
956   // FIXME: the code below (which only handles the BIOS bankswitch at start) should be cleaned up
957   // currently, it's just a stripped down version of sms_mapper_w
958   if (state->m_BIOS)
959      SOURCE_BIOS = state->m_BIOS + ((state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0) * 0x4000;
960   else
961      SOURCE_BIOS = state->m_banking_none[1];
962
963   if (state->m_bios_port & IO_BIOS_ROM || (state->m_is_gamegear && state->m_BIOS == NULL))
964      return;
965   else
966   {
967      if (!state->m_BIOS)
968         return;
969      SOURCE = SOURCE_BIOS;
970   }
971
972//  printf("write %x, %x\n", offset, data);
973
974   switch (offset)
975   {
976      case 0: /* Control */
977         if (!(data & 0x08)) /* it's not ram */
978         {
979            if (!(state->m_bios_port & IO_BIOS_ROM) && state->m_has_bios)
980            {
981               SOURCE = state->m_banking_bios[5];
982               memory_set_bankptr(space->machine(), "bank5", SOURCE);
983               memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
984            }
985         }
986         break;
987
988      case 1: /* Select 16k ROM bank for 0400-3FFF */
989         state->m_banking_bios[2] = SOURCE_BIOS + 0x0400;
990         memory_set_bankptr(space->machine(), "bank2", SOURCE + 0x0400);
991         break;
992
993      case 2: /* Select 16k ROM bank for 4000-7FFF */
994         state->m_banking_bios[3] = SOURCE_BIOS;
995         memory_set_bankptr(space->machine(), "bank3", SOURCE);
996         memory_set_bankptr(space->machine(), "bank4", SOURCE + 0x2000);
997         break;
998
999      case 3: /* Select 16k ROM bank for 8000-BFFF */
1000         state->m_banking_bios[5] = SOURCE_BIOS;
1001         if (!(state->m_mapper[0] & 0x08)) /* is RAM disabled? */
1002         {
1003            memory_set_bankptr(space->machine(), "bank5", SOURCE);
1004            memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
1005         }
1006         break;
1007   }
1008}
1009
1010WRITE8_HANDLER( sms_bios_w )
1011{
1012   sms_state *state = space->machine().driver_data<sms_state>();
1013   state->m_bios_port = data;
1014
1015   logerror("bios write %02x, pc: %04x\n", data, cpu_get_pc(&space->device()));
1016
1017   setup_rom(space);
1018}
1019
1020
1021WRITE8_HANDLER( sms_cartram2_w )
1022{
1023   sms_state *state = space->machine().driver_data<sms_state>();
1024
1025   if (state->m_mapper[0] & 0x08)
1026   {
1027      logerror("write %02X to cartram at offset #%04X\n", data, offset + 0x2000);
1028      if (state->m_mapper[0] & 0x04)
1029      {
1030         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x6000] = data;
1031      }
1032      else
1033      {
1034         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x2000] = data;
1035      }
1036   }
1037
1038   if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1039   {
1040      state->m_cartridge[state->m_current_cartridge].cartRAM[state->m_cartridge[state->m_current_cartridge].ram_page * 0x2000 + offset] = data;
1041   }
1042
1043   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_MAPPER && offset == 0) /* Dodgeball King mapper */
1044   {
1045      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1046      int page = (rom_page_count > 0) ? data % rom_page_count : 0;
1047
1048      if (!state->m_cartridge[state->m_current_cartridge].ROM)
1049         return;
1050
1051      state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x4000;
1052      memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
1053      memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
1054      LOG(("rom 2 paged in %x (Korean mapper).\n", page));
1055   }
1056}
1057
1058
1059WRITE8_HANDLER( sms_cartram_w )
1060{
1061   sms_state *state = space->machine().driver_data<sms_state>();
1062   int page;
1063
1064   if (state->m_mapper[0] & 0x08)
1065   {
1066      logerror("write %02X to cartram at offset #%04X\n", data, offset);
1067      if (state->m_mapper[0] & 0x04)
1068      {
1069         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x4000] = data;
1070      }
1071      else
1072      {
1073         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset] = data;
1074      }
1075   }
1076   else
1077   {
1078      if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER && offset == 0) /* Codemasters mapper */
1079      {
1080         UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1081         page = (rom_page_count > 0) ? data % rom_page_count : 0;
1082         if (!state->m_cartridge[state->m_current_cartridge].ROM)
1083            return;
1084         state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x4000;
1085         memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
1086         memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
1087         LOG(("rom 2 paged in %x (Codemasters mapper).\n", page));
1088      }
1089      else if (state->m_cartridge[state->m_current_cartridge].features & CF_ONCART_RAM)
1090      {
1091         state->m_cartridge[state->m_current_cartridge].cartRAM[offset & (state->m_cartridge[state->m_current_cartridge].ram_size - 1)] = data;
1092      }
1093      else
1094      {
1095         logerror("INVALID write %02X to cartram at offset #%04X\n", data, offset);
1096      }
1097   }
1098}
1099
1100
1101WRITE8_HANDLER( gg_sio_w )
1102{
1103   sms_state *state = space->machine().driver_data<sms_state>();
1104   logerror("*** write %02X to SIO register #%d\n", data, offset);
1105
1106   state->m_gg_sio[offset & 0x07] = data;
1107   switch (offset & 7)
1108   {
1109      case 0x00: /* Parallel Data */
1110         break;
1111
1112      case 0x01: /* Data Direction/ NMI Enable */
1113         break;
1114
1115      case 0x02: /* Serial Output */
1116         break;
1117
1118      case 0x03: /* Serial Input */
1119         break;
1120
1121      case 0x04: /* Serial Control / Status */
1122         break;
1123   }
1124}
1125
1126
1127READ8_HANDLER( gg_sio_r )
1128{
1129   sms_state *state = space->machine().driver_data<sms_state>();
1130   logerror("*** read SIO register #%d\n", offset);
1131
1132   switch (offset & 7)
1133   {
1134      case 0x00: /* Parallel Data */
1135         break;
1136
1137      case 0x01: /* Data Direction/ NMI Enable */
1138         break;
1139
1140      case 0x02: /* Serial Output */
1141         break;
1142
1143      case 0x03: /* Serial Input */
1144         break;
1145
1146      case 0x04: /* Serial Control / Status */
1147         break;
1148   }
1149
1150   return state->m_gg_sio[offset];
1151}
1152
1153static void sms_machine_stop( running_machine &machine )
1154{
1155   sms_state *state = machine.driver_data<sms_state>();
1156
1157   /* Does the cartridge have SRAM that should be saved? */
1158   if (state->m_cartridge[state->m_current_cartridge].sram_save) {
1159      device_image_interface *image = dynamic_cast<device_image_interface *>(machine.device("cart1"));
1160      image->battery_save(state->m_cartridge[state->m_current_cartridge].cartSRAM, sizeof(UINT8) * NVRAM_SIZE );
1161   }
1162}
1163
1164
1165static void setup_rom( address_space *space )
1166{
1167   sms_state *state = space->machine().driver_data<sms_state>();
1168   running_machine &machine = space->machine();
1169
1170   /* 1. set up bank pointers to point to nothing */
1171   memory_set_bankptr(machine, "bank1", state->m_banking_none[1]);
1172   memory_set_bankptr(machine, "bank2", state->m_banking_none[2]);
1173   memory_set_bankptr(machine, "bank3", state->m_banking_none[3]);
1174   memory_set_bankptr(machine, "bank4", state->m_banking_none[3] + 0x2000);
1175   memory_set_bankptr(machine, "bank5", state->m_banking_none[5]);
1176   memory_set_bankptr(machine, "bank6", state->m_banking_none[5] + 0x2000);
1177
1178   /* 2. check and set up expansion port */
1179   if (!(state->m_bios_port & IO_EXPANSION) && (state->m_bios_port & IO_CARTRIDGE) && (state->m_bios_port & IO_CARD))
1180   {
1181      /* TODO: Implement me */
1182      logerror("Switching to unsupported expansion port.\n");
1183   }
1184
1185   /* 3. check and set up card rom */
1186   if (!(state->m_bios_port & IO_CARD) && (state->m_bios_port & IO_CARTRIDGE) && (state->m_bios_port & IO_EXPANSION))
1187   {
1188      /* TODO: Implement me */
1189      logerror("Switching to unsupported card rom port.\n");
1190   }
1191
1192   /* 4. check and set up cartridge rom */
1193   /* if ((!(bios_port & IO_CARTRIDGE) && (bios_port & IO_EXPANSION) && (bios_port & IO_CARD)) || state->m_is_gamegear) { */
1194   /* Out Run Europa initially writes a value to port 3E where IO_CARTRIDGE, IO_EXPANSION and IO_CARD are reset */
1195   if ((!(state->m_bios_port & IO_CARTRIDGE)) || state->m_is_gamegear)
1196   {
1197      memory_set_bankptr(machine, "bank1", state->m_banking_cart[1]);
1198      memory_set_bankptr(machine, "bank2", state->m_banking_cart[2]);
1199      memory_set_bankptr(machine, "bank3", state->m_banking_cart[3]);
1200      memory_set_bankptr(machine, "bank4", state->m_banking_cart[3] + 0x2000);
1201      memory_set_bankptr(machine, "bank5", state->m_banking_cart[5]);
1202      memory_set_bankptr(machine, "bank6", state->m_banking_cart[5] + 0x2000);
1203      logerror("Switched in cartridge rom.\n");
1204   }
1205
1206   /* 5. check and set up bios rom */
1207   if (!(state->m_bios_port & IO_BIOS_ROM))
1208   {
1209      /* 0x0400 bioses */
1210      if (state->m_has_bios_0400)
1211      {
1212         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1213         logerror("Switched in 0x0400 bios.\n");
1214      }
1215      /* 0x2000 bioses */
1216      if (state->m_has_bios_2000)
1217      {
1218         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1219         memory_set_bankptr(machine, "bank2", state->m_banking_bios[2]);
1220         logerror("Switched in 0x2000 bios.\n");
1221      }
1222      if (state->m_has_bios_full)
1223      {
1224         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1225         memory_set_bankptr(machine, "bank2", state->m_banking_bios[2]);
1226         memory_set_bankptr(machine, "bank3", state->m_banking_bios[3]);
1227         memory_set_bankptr(machine, "bank4", state->m_banking_bios[3] + 0x2000);
1228         memory_set_bankptr(machine, "bank5", state->m_banking_bios[5]);
1229         memory_set_bankptr(machine, "bank6", state->m_banking_bios[5] + 0x2000);
1230         logerror("Switched in full bios.\n");
1231      }
1232   }
1233
1234   if (state->m_cartridge[state->m_current_cartridge].features & CF_ONCART_RAM)
1235   {
1236      memory_set_bankptr(machine, "bank5", state->m_cartridge[state->m_current_cartridge].cartRAM);
1237      memory_set_bankptr(machine, "bank6", state->m_cartridge[state->m_current_cartridge].cartRAM);
1238   }
1239}
1240
1241
1242static int sms_verify_cart( UINT8 *magic, int size )
1243{
1244   int retval;
1245
1246   retval = IMAGE_VERIFY_FAIL;
1247
1248   /* Verify the file is a valid image - check $7ff0 for "TMR SEGA" */
1249   if (size >= 0x8000)
1250   {
1251      if (!strncmp((char*)&magic[0x7ff0], "TMR SEGA", 8))
1252      {
1253#if 0
1254         /* Technically, it should be this, but remove for now until verified: */
1255         if (!strcmp(sysname, "gamegear"))
1256         {
1257            if ((unsigned char)magic[0x7ffd] < 0x50)
1258               retval = IMAGE_VERIFY_PASS;
1259         }
1260         if (!strcmp(sysname, "sms"))
1261         {
1262            if ((unsigned char)magic[0x7ffd] >= 0x50)
1263               retval = IMAGE_VERIFY_PASS;
1264         }
1265#endif
1266         retval = IMAGE_VERIFY_PASS;
1267      }
1268
1269#if 0
1270      /* Check at $81f0 also */
1271      if (!retval)
1272      {
1273         if (!strncmp(&magic[0x81f0], "TMR SEGA", 8))
1274         {
1275#if 0
1276            /* Technically, it should be this, but remove for now until verified: */
1277            if (!strcmp(sysname, "gamegear"))
1278            {
1279               if ((unsigned char)magic[0x81fd] < 0x50)
1280                  retval = IMAGE_VERIFY_PASS;
1281            }
1282            if (!strcmp(sysname, "sms"))
1283            {
1284               if ((unsigned char)magic[0x81fd] >= 0x50)
1285                  retval = IMAGE_VERIFY_PASS;
1286            }
1287#endif
1288            retval = IMAGE_VERIFY_PASS;
1289         }
1290      }
1291#endif
1292
1293   }
1294
1295   return retval;
1296}
1297
1298#ifdef UNUSED_FUNCTION
1299// For the moment we switch to a different detection routine which allows to detect
1300// in a single run Codemasters mapper, Korean mapper (including Jang Pung 3 which
1301// uses a diff signature then the one below here) and Zemina mapper (used by Wonsiin, etc.).
1302// I leave these here to document alt. detection routines and in the case these functions
1303// can be updated
1304
1305/* Check for Codemasters mapper
1306  0x7FE3 - 93 - sms Cosmis Spacehead
1307              - sms Dinobasher
1308              - sms The Excellent Dizzy Collection
1309              - sms Fantastic Dizzy
1310              - sms Micro Machines
1311              - gamegear Cosmic Spacehead
1312              - gamegear Micro Machines
1313         - 94 - gamegear Dropzone
1314              - gamegear Ernie Els Golf (also has 64KB additional RAM on the cartridge)
1315              - gamegear Pete Sampras Tennis
1316              - gamegear S.S. Lucifer
1317         - 95 - gamegear Micro Machines 2 - Turbo Tournament
1318
1319The Korean game Jang Pung II also seems to use a codemasters style mapper.
1320 */
1321static int detect_codemasters_mapper( UINT8 *rom )
1322{
1323   static const UINT8 jang_pung2[16] = { 0x00, 0xba, 0x38, 0x0d, 0x00, 0xb8, 0x38, 0x0c, 0x00, 0xb6, 0x38, 0x0b, 0x00, 0xb4, 0x38, 0x0a };
1324
1325   if (((rom[0x7fe0] & 0x0f ) <= 9) && (rom[0x7fe3] == 0x93 || rom[0x7fe3] == 0x94 || rom[0x7fe3] == 0x95) &&  rom[0x7fef] == 0x00)
1326      return 1;
1327
1328   if (!memcmp(&rom[0x7ff0], jang_pung2, 16))
1329      return 1;
1330
1331   return 0;
1332}
1333
1334
1335static int detect_korean_mapper( UINT8 *rom )
1336{
1337   static const UINT8 signatures[2][16] =
1338   {
1339      { 0x3e, 0x11, 0x32, 0x00, 0xa0, 0x78, 0xcd, 0x84, 0x85, 0x3e, 0x02, 0x32, 0x00, 0xa0, 0xc9, 0xff }, /* Dodgeball King */
1340      { 0x41, 0x48, 0x37, 0x37, 0x44, 0x37, 0x4e, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20 },   /* Sangokushi 3 */
1341   };
1342   int i;
1343
1344   for (i = 0; i < 2; i++)
1345   {
1346      if (!memcmp(&rom[0x7ff0], signatures[i], 16))
1347      {
1348         return 1;
1349      }
1350   }
1351   return 0;
1352}
1353#endif
1354
1355
1356static int detect_tvdraw( UINT8 *rom )
1357{
1358   static const UINT8 terebi_oekaki[7] = { 0x61, 0x6e, 0x6e, 0x61, 0x6b, 0x6d, 0x6e };   // "annakmn"
1359
1360   if (!memcmp(&rom[0x13b3], terebi_oekaki, 7))
1361      return 1;
1362
1363   return 0;
1364}
1365
1366
1367static int detect_lphaser_xoffset( running_machine &machine, UINT8 *rom )
1368{
1369   sms_state *state = machine.driver_data<sms_state>();
1370
1371   static const UINT8 signatures[6][16] =
1372   {
1373      /* Spacegun */
1374      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0xff, 0xff, 0x9d, 0x99, 0x10, 0x90, 0x00, 0x40 },
1375      /* Gangster Town */
1376      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x19, 0x87, 0x1b, 0xc9, 0x74, 0x50, 0x00, 0x4f },
1377      /* Shooting Gallery */
1378      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x20, 0x20, 0x8a, 0x3a, 0x72, 0x50, 0x00, 0x4f },
1379      /* Rescue Mission */
1380      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x20, 0x20, 0xfb, 0xd3, 0x06, 0x51, 0x00, 0x4f },
1381      /* Laser Ghost */
1382      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x00, 0x00, 0xb7, 0x55, 0x74, 0x70, 0x00, 0x40 },
1383      /* Assault City */
1384      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0xff, 0xff, 0x9f, 0x74, 0x34, 0x70, 0x00, 0x40 },
1385   };
1386
1387   if (!(state->m_bios_port & IO_CARTRIDGE) && state->m_cartridge[state->m_current_cartridge].size >= 0x8000)
1388   {
1389      if (!memcmp(&rom[0x7ff0], signatures[0], 16) || !memcmp(&rom[0x7ff0], signatures[1], 16))
1390         return 40;
1391
1392      if (!memcmp(&rom[0x7ff0], signatures[2], 16))
1393         return 49;
1394
1395      if (!memcmp(&rom[0x7ff0], signatures[3], 16))
1396         return 47;
1397
1398      if (!memcmp(&rom[0x7ff0], signatures[4], 16))
1399         return 44;
1400
1401      if (!memcmp(&rom[0x7ff0], signatures[5], 16))
1402         return 53;
1403
1404   }
1405   return 50;
1406}
1407
1408
1409DEVICE_START( sms_cart )
1410{
1411   sms_state *state = device->machine().driver_data<sms_state>();
1412   int i;
1413
1414   for (i = 0; i < MAX_CARTRIDGES; i++)
1415   {
1416      state->m_cartridge[i].ROM = NULL;
1417      state->m_cartridge[i].size = 0;
1418      state->m_cartridge[i].features = 0;
1419      state->m_cartridge[i].cartSRAM = NULL;
1420      state->m_cartridge[i].sram_save = 0;
1421      state->m_cartridge[i].cartRAM = NULL;
1422      state->m_cartridge[i].ram_size = 0;
1423      state->m_cartridge[i].ram_page = 0;
1424   }
1425   state->m_current_cartridge = 0;
1426
1427   state->m_bios_port = (IO_EXPANSION | IO_CARTRIDGE | IO_CARD);
1428   if (!state->m_is_gamegear && !state->m_has_bios)
1429   {
1430      state->m_bios_port &= ~(IO_CARTRIDGE);
1431      state->m_bios_port |= IO_BIOS_ROM;
1432   }
1433}
1434
1435
1436DEVICE_IMAGE_LOAD( sms_cart )
1437{
1438   running_machine &machine = image.device().machine();
1439   sms_state *state = machine.driver_data<sms_state>();
1440   int size, index = 0, offset = 0;
1441   const char *extrainfo = NULL;
1442
1443   if (strcmp(image.device().tag(), "cart1") == 0)
1444      index = 0;
1445   if (strcmp(image.device().tag(), "cart2") == 0)
1446      index = 1;
1447   if (strcmp(image.device().tag(), "cart3") == 0)
1448      index = 2;
1449   if (strcmp(image.device().tag(), "cart4") == 0)
1450      index = 3;
1451   if (strcmp(image.device().tag(), "cart5") == 0)
1452      index = 4;
1453   if (strcmp(image.device().tag(), "cart6") == 0)
1454      index = 5;
1455   if (strcmp(image.device().tag(), "cart7") == 0)
1456      index = 6;
1457   if (strcmp(image.device().tag(), "cart8") == 0)
1458      index = 7;
1459   if (strcmp(image.device().tag(), "cart9") == 0)
1460      index = 8;
1461   if (strcmp(image.device().tag(), "cart10") == 0)
1462      index = 9;
1463   if (strcmp(image.device().tag(), "cart11") == 0)
1464      index = 10;
1465   if (strcmp(image.device().tag(), "cart12") == 0)
1466      index = 11;
1467   if (strcmp(image.device().tag(), "cart13") == 0)
1468      index = 12;
1469   if (strcmp(image.device().tag(), "cart14") == 0)
1470      index = 13;
1471   if (strcmp(image.device().tag(), "cart15") == 0)
1472      index = 14;
1473   if (strcmp(image.device().tag(), "cart16") == 0)
1474      index = 15;
1475
1476   state->m_cartridge[index].features = 0;
1477
1478   if (image.software_entry() == NULL)
1479   {
1480      size = image.length();
1481      extrainfo = hashfile_extrainfo(image);
1482   }
1483   else
1484      size = image.get_software_region_length("rom");
1485
1486   /* Check for 512-byte header */
1487   if ((size / 512) & 1)
1488   {
1489      offset = 512;
1490      size -= 512;
1491   }
1492
1493   if (!size)
1494   {
1495      image.seterror(IMAGE_ERROR_UNSPECIFIED, "Invalid ROM image: ROM image is too small");
1496      return IMAGE_INIT_FAIL;
1497   }
1498
1499   /* Create a new memory region to hold the ROM. */
1500   /* Make sure the region holds only complete (0x4000) rom banks */
1501   state->m_cartridge[index].size = (size & 0x3fff) ? (((size >> 14) + 1) << 14) : size;
1502   state->m_cartridge[index].ROM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].size);
1503   state->m_cartridge[index].cartSRAM = auto_alloc_array(machine, UINT8, NVRAM_SIZE);
1504
1505   /* Load ROM banks */
1506   if (image.software_entry() == NULL)
1507   {
1508      image.fseek(offset, SEEK_SET);
1509
1510      if (image.fread( state->m_cartridge[index].ROM, size) != size)
1511         return IMAGE_INIT_FAIL;
1512   }
1513   else
1514   {
1515      memcpy(state->m_cartridge[index].ROM, image.get_software_region("rom") + offset, size);
1516
1517      // check for mapper feature (currently only KOREAN_NOBANK, but eventually we will add the other mappers as well)
1518      if (image.get_feature("pcb") != NULL)
1519      {
1520         const char *mapper = image.get_feature("pcb");
1521         if (!strcmp(mapper, "korean_nobank"))
1522            state->m_cartridge[index].features |= CF_KOREAN_NOBANK_MAPPER;
1523      }
1524   }
1525
1526   /* check the image */
1527   if (!state->m_has_bios)
1528   {
1529      if (sms_verify_cart(state->m_cartridge[index].ROM, size) == IMAGE_VERIFY_FAIL)
1530      {
1531         logerror("Warning loading image: sms_verify_cart failed\n");
1532      }
1533   }
1534
1535   /* Detect special features from the extrainfo field */
1536   if (extrainfo)
1537   {
1538      /* Check for codemasters mapper */
1539      if (strstr(extrainfo, "CODEMASTERS"))
1540         state->m_cartridge[index].features |= CF_CODEMASTERS_MAPPER;
1541
1542      /* Check for korean mapper */
1543      if (strstr(extrainfo, "KOREAN"))
1544         state->m_cartridge[index].features |= CF_KOREAN_MAPPER;
1545
1546      /* Check for special SMS Compatibility mode gamegear cartridges */
1547      if (state->m_is_gamegear && strstr(extrainfo, "GGSMS"))
1548         state->m_cartridge[index].features |= CF_GG_SMS_MODE;
1549
1550      /* Check for 93C46 eeprom */
1551      if (strstr(extrainfo, "93C46"))
1552         state->m_cartridge[index].features |= CF_93C46_EEPROM;
1553
1554      /* Check for 8KB on-cart RAM */
1555      if (strstr(extrainfo, "8KB_CART_RAM"))
1556      {
1557         state->m_cartridge[index].features |= CF_ONCART_RAM;
1558         state->m_cartridge[index].ram_size = 0x2000;
1559         state->m_cartridge[index].cartRAM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].ram_size);
1560      }
1561   }
1562   else
1563   {
1564      /* If no extrainfo information is available try to find special information out on our own */
1565      /* Check for special cartridge features (new routine, courtesy of Omar Cornut, from MEKA)  */
1566      if (size >= 0x8000)
1567      {
1568         int c0002 = 0, c8000 = 0, cA000 = 0, cFFFF = 0, i;
1569         for (i = 0; i < 0x8000; i++)
1570         {
1571            if (state->m_cartridge[index].ROM[i] == 0x32) // Z80 opcode for: LD (xxxx), A
1572            {
1573               UINT16 addr = (state->m_cartridge[index].ROM[i + 2] << 8) | state->m_cartridge[index].ROM[i + 1];
1574               if (addr == 0xFFFF)
1575               { i += 2; cFFFF++; continue; }
1576               if (addr == 0x0002 || addr == 0x0003 || addr == 0x0004)
1577               { i += 2; c0002++; continue; }
1578               if (addr == 0x8000)
1579               { i += 2; c8000++; continue; }
1580               if (addr == 0xA000)
1581               { i += 2; cA000++; continue; }
1582            }
1583         }
1584
1585         LOG(("Mapper test: c002 = %d, c8000 = %d, cA000 = %d, cFFFF = %d\n", c0002, c8000, cA000, cFFFF));
1586
1587         // 2 is a security measure, although tests on existing ROM showed it was not needed
1588         if (c0002 > cFFFF + 2 || (c0002 > 0 && cFFFF == 0))
1589            state->m_cartridge[index].features |= CF_KOREAN_ZEMINA_MAPPER;
1590         else if (c8000 > cFFFF + 2 || (c8000 > 0 && cFFFF == 0))
1591            state->m_cartridge[index].features |= CF_CODEMASTERS_MAPPER;
1592         else if (cA000 > cFFFF + 2 || (cA000 > 0 && cFFFF == 0))
1593            state->m_cartridge[index].features |= CF_KOREAN_MAPPER;
1594
1595      }
1596
1597      /* Check for special SMS Compatibility mode gamegear cartridges */
1598      if (state->m_is_gamegear && image.software_entry() == NULL)   // not sure about how to handle this with softlists
1599      {
1600         /* Just in case someone passes us an sms file */
1601         if (!mame_stricmp (image.filetype(), "sms"))
1602            state->m_cartridge[index].features |= CF_GG_SMS_MODE;
1603      }
1604   }
1605
1606   if (state->m_cartridge[index].features & CF_CODEMASTERS_MAPPER)
1607   {
1608      state->m_cartridge[index].ram_size = 0x10000;
1609      state->m_cartridge[index].cartRAM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].ram_size);
1610      state->m_cartridge[index].ram_page = 0;
1611   }
1612
1613   /* For Light Phaser games, we have to detect the x offset */
1614   state->m_lphaser_x_offs = detect_lphaser_xoffset(machine, state->m_cartridge[index].ROM);
1615
1616   /* Terebi Oekaki (TV Draw) is a SG1000 game with special input device which is compatible with SG1000 Mark III */
1617   if ((detect_tvdraw(state->m_cartridge[index].ROM)) && state->m_is_region_japan)
1618   {
1619      address_space *program = machine.device("maincpu")->memory().space(AS_PROGRAM);
1620      program->install_legacy_write_handler(0x6000, 0x6000, FUNC(sms_tvdraw_axis_w));
1621      program->install_legacy_read_handler(0x8000, 0x8000, FUNC(sms_tvdraw_status_r));
1622      program->install_legacy_read_handler(0xa000, 0xa000, FUNC(sms_tvdraw_data_r));
1623      program->nop_write(0xa000, 0xa000);
1624   }
1625
1626   if (state->m_cartridge[index].features & CF_KOREAN_NOBANK_MAPPER)
1627   {
1628      // FIXME: we should have by default FFFD-FFFF to be only a mirror for DFFD-DFFF (with no bankswitch logic)
1629      // and then the handlers should be installed here for all but the KOREAN_NOBANK carts
1630      // However, to avoid memory map breakage, we currently go the other way around
1631      address_space *program = machine.device("maincpu")->memory().space(AS_PROGRAM);
1632      program->install_legacy_readwrite_handler(0xfffc, 0xffff, FUNC(sms_kor_nobank_r), FUNC(sms_kor_nobank_w));
1633   }
1634
1635   LOG(("Cart Features: %x\n", state->m_cartridge[index].features));
1636
1637   /* Load battery backed RAM, if available */
1638   image.battery_load(state->m_cartridge[index].cartSRAM, sizeof(UINT8) * NVRAM_SIZE, 0x00);
1639
1640   return IMAGE_INIT_PASS;
1641}
1642
1643
1644static void setup_cart_banks( running_machine &machine )
1645{
1646   sms_state *state = machine.driver_data<sms_state>();
1647   if (state->m_cartridge[state->m_current_cartridge].ROM)
1648   {
1649      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1650      state->m_banking_cart[1] = state->m_cartridge[state->m_current_cartridge].ROM;
1651      state->m_banking_cart[2] = state->m_cartridge[state->m_current_cartridge].ROM + 0x0400;
1652      state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + ((1 < rom_page_count) ? 0x4000 : 0);
1653      state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + ((2 < rom_page_count) ? 0x8000 : 0);
1654      /* Codemasters mapper points to bank 0 for page 2 */
1655      if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1656      {
1657         state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM;
1658      }
1659   }
1660   else
1661   {
1662      state->m_banking_cart[1] = state->m_banking_none[1];
1663      state->m_banking_cart[2] = state->m_banking_none[2];
1664      state->m_banking_cart[3] = state->m_banking_none[3];
1665      state->m_banking_cart[5] = state->m_banking_none[5];
1666   }
1667}
1668
1669#ifdef MESS
1670static void setup_banks( running_machine &machine )
1671{
1672   sms_state *state = machine.driver_data<sms_state>();
1673   UINT8 *mem = machine.region("maincpu")->base();
1674   state->m_banking_bios[1] = state->m_banking_cart[1] = state->m_banking_none[1] = mem;
1675   state->m_banking_bios[2] = state->m_banking_cart[2] = state->m_banking_none[2] = mem;
1676   state->m_banking_bios[3] = state->m_banking_cart[3] = state->m_banking_none[3] = mem;
1677   state->m_banking_bios[4] = state->m_banking_cart[4] = state->m_banking_none[4] = mem;
1678   state->m_banking_bios[5] = state->m_banking_cart[5] = state->m_banking_none[5] = mem;
1679   state->m_banking_bios[6] = state->m_banking_cart[6] = state->m_banking_none[6] = mem;
1680
1681   state->m_BIOS = machine.region("user1")->base();
1682
1683   state->m_bios_page_count = (state->m_BIOS ? machine.region("user1")->bytes() / 0x4000 : 0);
1684
1685   setup_cart_banks(machine);
1686
1687   if (state->m_BIOS == NULL || state->m_BIOS[0] == 0x00)
1688   {
1689      state->m_BIOS = NULL;
1690      state->m_bios_port |= IO_BIOS_ROM;
1691   }
1692
1693   if (state->m_BIOS)
1694   {
1695      state->m_banking_bios[1] = state->m_BIOS;
1696      state->m_banking_bios[2] = state->m_BIOS + 0x0400;
1697      state->m_banking_bios[3] = state->m_BIOS + ((1 < state->m_bios_page_count) ? 0x4000 : 0);
1698      state->m_banking_bios[5] = state->m_BIOS + ((2 < state->m_bios_page_count) ? 0x8000 : 0);
1699   }
1700}
1701#endif
1702
1703MACHINE_START( sms )
1704{
1705   sms_state *state = machine.driver_data<sms_state>();
1706
1707   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(sms_machine_stop),&machine));
1708   state->m_rapid_fire_timer = machine.scheduler().timer_alloc(FUNC(rapid_fire_callback));
1709   state->m_rapid_fire_timer->adjust(attotime::from_hz(10), 0, attotime::from_hz(10));
1710
1711   state->m_lphaser_1_timer = machine.scheduler().timer_alloc(FUNC(lphaser_1_callback));
1712   state->m_lphaser_2_timer = machine.scheduler().timer_alloc(FUNC(lphaser_2_callback));
1713
1714   state->m_main_cpu = machine.device("maincpu");
1715   state->m_control_cpu = machine.device("control");
1716   state->m_vdp = machine.device("sms_vdp");
1717   state->m_ym = machine.device("ym2413");
1718   state->m_main_scr = machine.device("screen");
1719   state->m_left_lcd = machine.device("left_lcd");
1720   state->m_right_lcd = machine.device("right_lcd");
1721
1722   /* Check if lightgun has been chosen as input: if so, enable crosshair */
1723   machine.scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
1724}
1725
1726#ifdef MESS
1727MACHINE_RESET( sms )
1728{
1729   address_space *space = machine.device("maincpu")->memory().space(AS_PROGRAM);
1730   sms_state *state = machine.driver_data<sms_state>();
1731
1732   state->m_ctrl_reg = 0xff;
1733   if (state->m_has_fm)
1734      state->m_fm_detect = 0x01;
1735
1736   state->m_mapper_ram = (UINT8*)space->get_write_ptr(0xdffc);
1737
1738   state->m_bios_port = 0;
1739
1740   if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1741   {
1742      /* Install special memory handlers */
1743      space->install_legacy_write_handler(0x0000, 0x0000, FUNC(sms_codemasters_page0_w));
1744      space->install_legacy_write_handler(0x4000, 0x4000, FUNC(sms_codemasters_page1_w));
1745   }
1746
1747   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_ZEMINA_MAPPER)
1748      space->install_legacy_write_handler(0x0000, 0x0003, FUNC(sms_korean_zemina_banksw_w));
1749
1750   if (state->m_cartridge[state->m_current_cartridge].features & CF_GG_SMS_MODE)
1751      sms_vdp_set_ggsmsmode(state->m_vdp, 1);
1752
1753   /* Initialize SIO stuff for GG */
1754   state->m_gg_sio[0] = 0x7f;
1755   state->m_gg_sio[1] = 0xff;
1756   state->m_gg_sio[2] = 0x00;
1757   state->m_gg_sio[3] = 0xff;
1758   state->m_gg_sio[4] = 0x00;
1759
1760   state->m_store_control = 0;
1761
1762   setup_banks(machine);
1763
1764   setup_rom(space);
1765
1766   state->m_rapid_fire_state_1 = 0;
1767   state->m_rapid_fire_state_2 = 0;
1768
1769   state->m_last_paddle_read_time = 0;
1770   state->m_paddle_read_state = 0;
1771
1772   state->m_last_sports_pad_time_1 = 0;
1773   state->m_last_sports_pad_time_2 = 0;
1774   state->m_sports_pad_state_1 = 0;
1775   state->m_sports_pad_state_2 = 0;
1776   state->m_sports_pad_last_data_1 = 0;
1777   state->m_sports_pad_last_data_2 = 0;
1778   state->m_sports_pad_1_x = 0;
1779   state->m_sports_pad_1_y = 0;
1780   state->m_sports_pad_2_x = 0;
1781   state->m_sports_pad_2_y = 0;
1782
1783   state->m_lphaser_1_latch = 0;
1784   state->m_lphaser_2_latch = 0;
1785
1786   state->m_sscope_state = 0;
1787
1788   state->m_tvdraw_data = 0;
1789}
1790#endif
1791
1792READ8_HANDLER( sms_store_cart_select_r )
1793{
1794   return 0xff;
1795}
1796
1797
1798WRITE8_HANDLER( sms_store_cart_select_w )
1799{
1800   sms_state *state = space->machine().driver_data<sms_state>();
1801   UINT8 slot = data >> 4;
1802   UINT8 slottype = data & 0x08;
1803
1804   logerror("switching in part of %s slot #%d\n", slottype ? "card" : "cartridge", slot );
1805   /* cartridge? slot #0 */
1806   if (slottype == 0)
1807      state->m_current_cartridge = slot;
1808
1809   setup_cart_banks(space->machine());
1810   memory_set_bankptr(space->machine(), "bank10", state->m_banking_cart[3] + 0x2000);
1811   setup_rom(space);
1812}
1813
1814
1815READ8_HANDLER( sms_store_select1 )
1816{
1817   return 0xff;
1818}
1819
1820
1821READ8_HANDLER( sms_store_select2 )
1822{
1823   return 0xff;
1824}
1825
1826
1827READ8_HANDLER( sms_store_control_r )
1828{
1829   sms_state *state = space->machine().driver_data<sms_state>();
1830   return state->m_store_control;
1831}
1832
1833
1834WRITE8_HANDLER( sms_store_control_w )
1835{
1836   sms_state *state = space->machine().driver_data<sms_state>();
1837   logerror("0x%04X: sms_store_control write 0x%02X\n", cpu_get_pc(&space->device()), data);
1838   if (data & 0x02)
1839   {
1840      space->machine().device<cpu_device>("maincpu")->resume(SUSPEND_REASON_HALT);
1841   }
1842   else
1843   {
1844      /* Pull reset line of CPU #0 low */
1845      space->machine().device("maincpu")->reset();
1846      space->machine().device<cpu_device>("maincpu")->suspend(SUSPEND_REASON_HALT, 1);
1847   }
1848   state->m_store_control = data;
1849}
1850
1851void sms_store_int_callback( running_machine &machine, int state )
1852{
1853   sms_state *driver_state = machine.driver_data<sms_state>();
1854   device_set_input_line(driver_state->m_store_control & 0x01 ? driver_state->m_control_cpu : driver_state->m_main_cpu, 0, state);
1855}
1856
1857
1858static void sms_set_zero_flag( running_machine &machine )
1859{
1860   sms_state *state = machine.driver_data<sms_state>();
1861   state->m_is_gamegear = 0;
1862   state->m_is_region_japan = 0;
1863   state->m_has_bios_0400 = 0;
1864   state->m_has_bios_2000 = 0;
1865   state->m_has_bios_full = 0;
1866   state->m_has_bios = 0;
1867   state->m_has_fm = 0;
1868}
1869
1870DRIVER_INIT( sg1000m3 )
1871{
1872   sms_state *state = machine.driver_data<sms_state>();
1873   sms_set_zero_flag(machine);
1874   state->m_is_region_japan = 1;
1875   state->m_has_fm = 1;
1876}
1877
1878
1879DRIVER_INIT( sms1 )
1880{
1881   sms_state *state = machine.driver_data<sms_state>();
1882   sms_set_zero_flag(machine);
1883   state->m_has_bios_full = 1;
1884}
1885
1886
1887DRIVER_INIT( smsj )
1888{
1889   sms_state *state = machine.driver_data<sms_state>();
1890   sms_set_zero_flag(machine);
1891   state->m_is_region_japan = 1;
1892   state->m_has_bios_2000 = 1;
1893   state->m_has_fm = 1;
1894}
1895
1896
1897DRIVER_INIT( sms2kr )
1898{
1899   sms_state *state = machine.driver_data<sms_state>();
1900   sms_set_zero_flag(machine);
1901   state->m_is_region_japan = 1;
1902   state->m_has_bios_full = 1;
1903   state->m_has_fm = 1;
1904}
1905
1906
1907DRIVER_INIT( smssdisp )
1908{
1909   sms_set_zero_flag(machine);
1910}
1911
1912
1913DRIVER_INIT( gamegear )
1914{
1915   sms_state *state = machine.driver_data<sms_state>();
1916   sms_set_zero_flag(machine);
1917   state->m_is_gamegear = 1;
1918}
1919
1920
1921DRIVER_INIT( gamegeaj )
1922{
1923   sms_state *state = machine.driver_data<sms_state>();
1924   sms_set_zero_flag(machine);
1925   state->m_is_region_japan = 1;
1926   state->m_is_gamegear = 1;
1927   state->m_has_bios_0400 = 1;
1928}
1929
1930
1931static void sms_black_bitmap( const screen_device *screen, bitmap_t *bitmap )
1932{
1933   const int width = screen->width();
1934   const int height = screen->height();
1935   int x, y;
1936
1937   for (y = 0; y < height; y++)
1938      for (x = 0; x < width; x++)
1939         *BITMAP_ADDR32(bitmap, y, x) = MAKE_RGB(0,0,0);
1940}
1941
1942VIDEO_START( sms1 )
1943{
1944   sms_state *state = machine.driver_data<sms_state>();
1945   screen_device *screen = machine.first_screen();
1946   int width = screen->width();
1947   int height = screen->height();
1948
1949   state->m_prevleft_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
1950   state->m_prevright_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
1951   state->save_item(NAME(*state->m_prevleft_bitmap));
1952   state->save_item(NAME(*state->m_prevright_bitmap));
1953}
1954
1955SCREEN_UPDATE( sms1 )
1956{
1957   sms_state *state = screen->machine().driver_data<sms_state>();
1958   UINT8 sscope = input_port_read_safe(screen->machine(), "SEGASCOPE", 0x00);
1959   UINT8 sscope_binocular_hack = input_port_read_safe(screen->machine(), "SSCOPE_BINOCULAR", 0x00);
1960   UINT8 occluded_view = 0;
1961
1962   // without SegaScope, both LCDs for glasses go black
1963   if ((screen != state->m_main_scr) && !sscope)
1964      occluded_view = 1;
1965
1966   // with SegaScope, sscope_state 0 = left screen OFF, right screen ON
1967   if (!(state->m_sscope_state & 0x01) && (screen == state->m_left_lcd))
1968      occluded_view = 1;
1969
1970   // with SegaScope, sscope_state 1 = left screen ON, right screen OFF
1971   if ((state->m_sscope_state & 0x01) && (screen == state->m_right_lcd))
1972      occluded_view = 1;
1973
1974   if (!occluded_view)
1975   {
1976      sms_vdp_update(state->m_vdp, bitmap, cliprect);
1977
1978      // HACK: fake 3D->2D handling (if enabled, it repeats each frame twice on the selected lens)
1979      // save a copy of current bitmap for the binocular hack
1980      if (sscope && (screen == state->m_left_lcd) && (sscope_binocular_hack & 0x01))
1981         copybitmap(state->m_prevleft_bitmap, bitmap, 0, 0, 0, 0, cliprect);
1982      if (sscope && (screen == state->m_right_lcd) && (sscope_binocular_hack & 0x02))
1983         copybitmap(state->m_prevright_bitmap, bitmap, 0, 0, 0, 0, cliprect);
1984   }
1985   else
1986   {
1987      sms_black_bitmap(screen, bitmap);
1988
1989      // HACK: fake 3D->2D handling (if enabled, it repeats each frame twice on the selected lens)
1990      // use the copied bitmap for the binocular hack
1991      if (sscope && (screen == state->m_left_lcd) && (sscope_binocular_hack & 0x01))
1992         copybitmap(bitmap, state->m_prevleft_bitmap, 0, 0, 0, 0, cliprect);
1993      if (sscope && (screen == state->m_right_lcd) && (sscope_binocular_hack & 0x02))
1994         copybitmap(bitmap, state->m_prevright_bitmap, 0, 0, 0, 0, cliprect);
1995   }
1996
1997   return 0;
1998}
1999
2000SCREEN_UPDATE( sms )
2001{
2002   sms_state *state = screen->machine().driver_data<sms_state>();
2003   sms_vdp_update(state->m_vdp, bitmap, cliprect);
2004   return 0;
2005}
2006
2007VIDEO_START( gamegear )
2008{
2009   sms_state *state = machine.driver_data<sms_state>();
2010   screen_device *screen = machine.first_screen();
2011   int width = screen->width();
2012   int height = screen->height();
2013
2014   state->m_prev_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
2015   state->m_tmp_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
2016   state->save_item(NAME(*state->m_prev_bitmap));
2017}
2018
2019SCREEN_UPDATE( gamegear )
2020{
2021   sms_state *state = screen->machine().driver_data<sms_state>();
2022   int width = screen->width();
2023   int height = screen->height();
2024   int x, y;
2025
2026   sms_vdp_update(state->m_vdp, state->m_tmp_bitmap, cliprect);
2027
2028   // HACK: fake LCD persistence effect
2029   // (it would be better to generalize this in the core, to be used for all LCD systems)
2030   for (y = 0; y < height; y++)
2031   {
2032      UINT32 *line0 = BITMAP_ADDR32(state->m_tmp_bitmap, y, 0);
2033      UINT32 *line1 = BITMAP_ADDR32(state->m_prev_bitmap, y, 0);
2034      for (x = 0; x < width; x++)
2035      {
2036         UINT32 color0 = line0[x];
2037         UINT32 color1 = line1[x];
2038         UINT16 r0 = (color0 >> 16) & 0x000000ff;
2039         UINT16 g0 = (color0 >>  8) & 0x000000ff;
2040         UINT16 b0 = (color0 >>  0) & 0x000000ff;
2041         UINT16 r1 = (color1 >> 16) & 0x000000ff;
2042         UINT16 g1 = (color1 >>  8) & 0x000000ff;
2043         UINT16 b1 = (color1 >>  0) & 0x000000ff;
2044         UINT8 r = (UINT8)((r0 + r1) >> 1);
2045         UINT8 g = (UINT8)((g0 + g1) >> 1);
2046         UINT8 b = (UINT8)((b0 + b1) >> 1);
2047         *BITMAP_ADDR32(bitmap, y, x) = (r << 16) | (g << 8) | b;
2048      }
2049   }
2050   copybitmap(state->m_prev_bitmap, state->m_tmp_bitmap, 0, 0, 0, 0, cliprect);
2051
2052   return 0;
2053}
src/mame/machine/dccons.c
r0r11451
1/*
2
3    dc.c - Sega Dreamcast hardware
4
5    MESS (DC home console) hardware overrides (GD-ROM drive etc)
6
7    c230048 - 5 is written, want 6
8    c0d9d9e - where bad happens, from routine @ c0da260
9
10    c0d9d8e - R0 on return is the value to put in
11
12    cfffee0 - stack location when bad happens
13
14*/
15
16#include "emu.h"
17#include "cdrom.h"
18#include "debugger.h"
19#include "includes/dc.h"
20#include "cpu/sh4/sh4.h"
21#include "sound/aica.h"
22#include "includes/naomi.h"
23#include "machine/gdrom.h"
24#include "imagedev/chd_cd.h"
25
26#define ATAPI_CYCLES_PER_SECTOR (5000)   // TBD for Dreamcast
27
28#define ATAPI_STAT_BSY      0x80
29#define ATAPI_STAT_DRDY    0x40
30#define ATAPI_STAT_DMARDDF 0x20
31#define ATAPI_STAT_SERVDSC 0x10
32#define ATAPI_STAT_DRQ     0x08
33#define ATAPI_STAT_CORR    0x04
34#define ATAPI_STAT_CHECK   0x01
35
36#define ATAPI_INTREASON_COMMAND 0x01
37#define ATAPI_INTREASON_IO      0x02
38#define ATAPI_INTREASON_RELEASE 0x04
39
40#define ATAPI_REG_DATA      0
41#define ATAPI_REG_FEATURES   1
42#define ATAPI_REG_INTREASON   2
43#define ATAPI_REG_SAMTAG   3
44#define ATAPI_REG_COUNTLOW   4
45#define ATAPI_REG_COUNTHIGH   5
46#define ATAPI_REG_DRIVESEL   6
47#define ATAPI_REG_CMDSTATUS   7
48#define ATAPI_REG_ERROR      16   // read-only ERROR (write is FEATURES)
49
50#define ATAPI_REG_MAX 24
51
52#define ATAPI_XFER_PIO      0x00
53#define ATAPI_XFER_PIO_FLOW   0x08
54#define ATAPI_XFER_MULTI_DMA   0x20
55#define ATAPI_XFER_ULTRA_DMA   0x40
56
57#define ATAPI_DATA_SIZE ( 64 * 1024 )
58
59static UINT8 *atapi_regs;
60static emu_timer *atapi_timer;
61static SCSIInstance *gdrom_device;
62static UINT8 *atapi_data;
63static int atapi_data_ptr, atapi_data_len, atapi_xferlen, atapi_xferbase, atapi_cdata_wait, atapi_xfermod;
64static UINT32 gdrom_alt_status;
65static UINT8 xfer_mode = ATAPI_XFER_PIO;
66
67#define MAX_TRANSFER_SIZE ( 63488 )
68
69extern UINT32 dc_sysctrl_regs[0x200/4];
70
71extern UINT32 g1bus_regs[0x100/4];
72
73static void gdrom_raise_irq(running_machine &machine)
74{
75   dc_sysctrl_regs[SB_ISTEXT] |= IST_EXT_GDROM;
76   dc_update_interrupt_status(machine);
77}
78
79static TIMER_CALLBACK( atapi_xfer_end )
80{
81   UINT8 sector_buffer[ 4096 ];
82
83   atapi_timer->adjust(attotime::never);
84
85   printf("atapi_xfer_end atapi_xferlen = %d, atapi_xfermod=%d\n", atapi_xfermod, atapi_xferlen );
86
87   mame_printf_debug("ATAPI: xfer_end.  xferlen = %d, atapi_xfermod = %d\n", atapi_xferlen, atapi_xfermod);
88
89   while (atapi_xferlen > 0 )
90   {
91      struct sh4_ddt_dma ddtdata;
92
93      // get a sector from the SCSI device
94      SCSIReadData( gdrom_device, sector_buffer, 2048 );
95
96      atapi_xferlen -= 2048;
97
98      // perform the DMA
99      ddtdata.destination = atapi_xferbase;   // destination address
100      ddtdata.length = 2048/4;
101      ddtdata.size = 4;
102      ddtdata.buffer = sector_buffer;
103      ddtdata.direction=1;   // 0 source to buffer, 1 buffer to destination
104      ddtdata.channel= -1;   // not used
105      ddtdata.mode= -1;      // copy from/to buffer
106      printf("ATAPI: DMA one sector to %x, %x remaining\n", atapi_xferbase, atapi_xferlen);
107      sh4_dma_ddt(machine.device("maincpu"), &ddtdata);
108
109      atapi_xferbase += 2048;
110   }
111
112   if (atapi_xfermod > MAX_TRANSFER_SIZE)
113   {
114      atapi_xferlen = MAX_TRANSFER_SIZE;
115      atapi_xfermod = atapi_xfermod - MAX_TRANSFER_SIZE;
116   }
117   else
118   {
119      atapi_xferlen = atapi_xfermod;
120      atapi_xfermod = 0;
121   }
122
123   if (atapi_xferlen > 0)
124   {
125      printf("ATAPI: starting next piece of multi-part transfer\n");
126      atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
127      atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
128
129      atapi_timer->adjust(machine.device<cpu_device>("maincpu")->cycles_to_attotime((ATAPI_CYCLES_PER_SECTOR * (atapi_xferlen/2048))));
130   }
131   else
132   {
133      printf("ATAPI: Transfer completed, dropping DRQ\n");
134      atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRDY;
135      gdrom_alt_status = ATAPI_STAT_DRDY;
136      atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO | ATAPI_INTREASON_COMMAND;
137
138      g1bus_regs[SB_GDST]=0;
139      dc_sysctrl_regs[SB_ISTNRM] |= IST_DMA_GDROM;
140      dc_update_interrupt_status(machine);
141   }
142
143   gdrom_raise_irq(machine);
144
145   printf( "atapi_xfer_end: %d %d\n", atapi_xferlen, atapi_xfermod );
146}
147
148static READ32_HANDLER( atapi_r )
149{
150   running_machine &machine = space->machine();
151   int reg, data;
152
153   if (mem_mask == 0x0000ffff)   // word-wide command read
154   {
155//      mame_printf_debug("ATAPI: packet read = %04x\n", atapi_data[atapi_data_ptr]);
156
157      // assert IRQ and drop DRQ
158      if (atapi_data_ptr == 0 && atapi_data_len == 0)
159      {
160         // get the data from the device
161         if( atapi_xferlen > 0 )
162         {
163            SCSIReadData( gdrom_device, atapi_data, atapi_xferlen );
164            atapi_data_len = atapi_xferlen;
165         }
166
167         if (atapi_xfermod > MAX_TRANSFER_SIZE)
168         {
169            atapi_xferlen = MAX_TRANSFER_SIZE;
170            atapi_xfermod = atapi_xfermod - MAX_TRANSFER_SIZE;
171         }
172         else
173         {
174            atapi_xferlen = atapi_xfermod;
175            atapi_xfermod = 0;
176         }
177
178//          printf( "atapi_r: atapi_xferlen=%d\n", atapi_xferlen );
179         if( atapi_xferlen != 0 )
180         {
181            atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC;
182            gdrom_alt_status = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC;
183            atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
184         }
185         else
186         {
187            //mame_printf_debug("ATAPI: dropping DRQ\n");
188            atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
189            gdrom_alt_status = 0;
190            atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
191         }
192
193         atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
194         atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
195
196         gdrom_raise_irq(machine);
197      }
198
199      if( atapi_data_ptr < atapi_data_len )
200      {
201         data = atapi_data[atapi_data_ptr++];
202         data |= ( atapi_data[atapi_data_ptr++] << 8 );
203         if( atapi_data_ptr >= atapi_data_len )
204         {
205//              printf( "atapi_r: read all bytes\n" );
206            atapi_data_ptr = 0;
207            atapi_data_len = 0;
208
209            if( atapi_xferlen == 0 )
210            {
211               atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
212               gdrom_alt_status = 0;
213               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
214               gdrom_raise_irq(machine);
215            }
216         }
217      }
218      else
219      {
220         data = 0;
221      }
222   }
223   else
224   {
225      reg = offset;
226
227      // get read-only side of read-only/write-only registers from elsewhere
228      if (reg == ATAPI_REG_FEATURES)
229      {
230         reg = ATAPI_REG_ERROR;
231      }
232      data = atapi_regs[reg];
233
234      #if 0
235      switch( reg )
236      {
237      case ATAPI_REG_DATA:
238         printf( "atapi_r: data=%02x\n", data );
239         break;
240      case ATAPI_REG_ERROR:
241         printf( "atapi_r: error=%02x\n", data );
242         break;
243      case ATAPI_REG_INTREASON:
244         printf( "atapi_r: intreason=%02x\n", data );
245         break;
246      case ATAPI_REG_SAMTAG:
247         printf( "atapi_r: samtag=%02x\n", data );
248         break;
249      case ATAPI_REG_COUNTLOW:
250         printf( "atapi_r: countlow=%02x\n", data );
251         break;
252      case ATAPI_REG_COUNTHIGH:
253         printf( "atapi_r: counthigh=%02x\n", data );
254         break;
255      case ATAPI_REG_DRIVESEL:
256         printf( "atapi_r: drivesel=%02x\n", data );
257         break;
258      case ATAPI_REG_CMDSTATUS:
259         printf( "atapi_r: cmdstatus=%02x\n", data );
260         break;
261      }
262      #endif
263
264      mame_printf_debug("ATAPI: read reg %d = %x (PC=%x)\n", reg, data, cpu_get_pc(&space->device()));
265   }
266
267//  printf( "atapi_r( %08x, %08x ) %08x\n", offset, mem_mask, data );
268   return data;
269}
270
271static WRITE32_HANDLER( atapi_w )
272{
273   running_machine &machine = space->machine();
274   int reg;
275
276//  printf( "atapi_w( %08x, %08x, %08x )\n", offset, mem_mask, data );
277
278   if (mem_mask == 0x0000ffff)   // word-wide command write
279   {
280//      printf("atapi_w: data=%04x\n", data );
281
282//      printf("ATAPI: packet write %04x\n", data);
283      atapi_data[atapi_data_ptr++] = data & 0xff;
284      atapi_data[atapi_data_ptr++] = data >> 8;
285
286      if (atapi_cdata_wait)
287      {
288//                  printf("ATAPI: waiting, ptr %d wait %d\n", atapi_data_ptr, atapi_cdata_wait);
289         if (atapi_data_ptr == atapi_cdata_wait)
290         {
291            // send it to the device
292            SCSIWriteData( gdrom_device, atapi_data, atapi_cdata_wait );
293
294            // assert IRQ
295            gdrom_raise_irq(machine);
296
297            // not sure here, but clear DRQ at least?
298            atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
299         }
300      }
301
302      else if ( atapi_data_ptr == 12 )
303      {
304         int phase;
305
306//          printf("atapi_w: command %02x\n", atapi_data[0]&0xff );
307
308         // reset data pointer for reading SCSI results
309         atapi_data_ptr = 0;
310         atapi_data_len = 0;
311
312         // send it to the SCSI device
313         SCSISetCommand( gdrom_device, atapi_data, 12 );
314         SCSIExecCommand( gdrom_device, &atapi_xferlen );
315         SCSIGetPhase( gdrom_device, &phase );
316
317         if (atapi_xferlen != -1)
318         {
319            printf("ATAPI: SCSI command %02x returned %d bytes from the device\n", atapi_data[0]&0xff, atapi_xferlen);
320
321            // store the returned command length in the ATAPI regs, splitting into
322            // multiple transfers if necessary
323            atapi_xfermod = 0;
324            if (atapi_xferlen > MAX_TRANSFER_SIZE)
325            {
326               atapi_xfermod = atapi_xferlen - MAX_TRANSFER_SIZE;
327               atapi_xferlen = MAX_TRANSFER_SIZE;
328            }
329
330            atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
331            atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
332
333            gdrom_alt_status = 0;   // (I guess?)
334
335            if (atapi_xferlen == 0)
336            {
337               // if no data to return, set the registers properly
338               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRDY;
339               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO|ATAPI_INTREASON_COMMAND;
340            }
341            else
342            {
343               // indicate data ready: set DRQ and DMA ready, and IO in INTREASON
344               if (atapi_regs[ATAPI_REG_FEATURES] & 0x01)   // DMA feature
345               {
346                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_BSY | ATAPI_STAT_DRDY | ATAPI_STAT_SERVDSC;
347               }
348               else
349               {
350                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC | ATAPI_STAT_DRQ;
351               }
352               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
353            }
354
355            switch( phase )
356            {
357            case SCSI_PHASE_DATAOUT:
358               atapi_cdata_wait = atapi_xferlen;
359               break;
360            }
361
362            // perform special ATAPI processing of certain commands
363            switch (atapi_data[0]&0xff)
364            {
365               case 0x00: // BUS RESET / TEST UNIT READY
366               case 0xbb: // SET CDROM SPEED
367                  atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
368                  break;
369
370               case 0x45: // PLAY
371                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_BSY;
372                  atapi_timer->adjust( downcast<cpu_device *>(&space->device())->cycles_to_attotime(ATAPI_CYCLES_PER_SECTOR ) );
373                  break;
374            }
375
376            // assert IRQ
377            gdrom_raise_irq(machine);
378         }
379         else
380         {
381                     printf("ATAPI: SCSI device returned error!\n");
382
383            atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_CHECK;
384            atapi_regs[ATAPI_REG_ERROR] = 0x50;   // sense key = ILLEGAL REQUEST
385            atapi_regs[ATAPI_REG_COUNTLOW] = 0;
386            atapi_regs[ATAPI_REG_COUNTHIGH] = 0;
387         }
388      }
389   }
390   else
391   {
392      reg = offset;
393#if 0
394      switch( reg )
395      {
396      case ATAPI_REG_DATA:
397         printf( "atapi_w: data=%02x\n", data );
398             break;
399          case ATAPI_REG_FEATURES:
400         printf( "atapi_w: features=%02x\n", data );
401             break;
402          case ATAPI_REG_INTREASON:
403         printf( "atapi_w: intreason=%02x\n", data );
404             break;
405          case ATAPI_REG_SAMTAG:
406         printf( "atapi_w: samtag=%02x\n", data );
407             break;
408          case ATAPI_REG_COUNTLOW:
409         printf( "atapi_w: countlow=%02x\n", data );
410             break;
411          case ATAPI_REG_COUNTHIGH:
412         printf( "atapi_w: counthigh=%02x\n", data );
413             break;
414          case ATAPI_REG_DRIVESEL:
415         printf( "atapi_w: drivesel=%02x\n", data );
416             break;
417          case ATAPI_REG_CMDSTATUS:
418         printf( "atapi_w: cmdstatus=%02x\n", data );
419         break;
420      }
421#endif
422      atapi_regs[reg] = data;
423//      mame_printf_debug("ATAPI: reg %d = %x (offset %x mask %x PC=%x)\n", reg, data, offset, mem_mask, cpu_get_pc(&space->device()));
424
425      if (reg == ATAPI_REG_CMDSTATUS)
426      {
427         printf("ATAPI command %x issued! (PC=%x)\n", data, cpu_get_pc(&space->device()));
428
429         switch (data)
430         {
431            case 0xa0:   // PACKET
432               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ;
433               gdrom_alt_status = ATAPI_STAT_DRQ;
434               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_COMMAND;
435
436               atapi_data_ptr = 0;
437               atapi_data_len = 0;
438
439               /* we have no data */
440               atapi_xferlen = 0;
441               atapi_xfermod = 0;
442
443               atapi_cdata_wait = 0;
444               break;
445
446            case 0xa1:   // IDENTIFY PACKET DEVICE
447               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ;
448               gdrom_alt_status = ATAPI_STAT_DRQ;
449
450               atapi_data_ptr = 0;
451               atapi_data_len = 512;
452
453               /* we have no data */
454               atapi_xferlen = 0;
455               atapi_xfermod = 0;
456
457               memset( atapi_data, 0, atapi_data_len );
458
459               atapi_data[ 0 ^ 1 ] = 0x86;   // ATAPI device, cmd set 6 compliant, DRQ within 3 ms of PACKET command
460               atapi_data[ 1 ^ 1 ] = 0x00;
461
462               memset( &atapi_data[ 46 ], ' ', 8 );
463               atapi_data[ 46 ^ 1 ] = 'S';
464               atapi_data[ 47 ^ 1 ] = 'E';
465
466               memset( &atapi_data[ 54 ], ' ', 40 );
467               atapi_data[ 54 ^ 1 ] = 'C';
468               atapi_data[ 55 ^ 1 ] = 'D';
469               atapi_data[ 56 ^ 1 ] = '-';
470               atapi_data[ 57 ^ 1 ] = 'R';
471               atapi_data[ 58 ^ 1 ] = 'O';
472               atapi_data[ 59 ^ 1 ] = 'M';
473               atapi_data[ 60 ^ 1 ] = ' ';
474               atapi_data[ 61 ^ 1 ] = 'D';
475               atapi_data[ 62 ^ 1 ] = 'R';
476               atapi_data[ 63 ^ 1 ] = 'I';
477               atapi_data[ 64 ^ 1 ] = 'V';
478               atapi_data[ 65 ^ 1 ] = 'E';
479               atapi_data[ 66 ^ 1 ] = ' ';
480               atapi_data[ 67 ^ 1 ] = ' ';
481               atapi_data[ 68 ^ 1 ] = ' ';
482               atapi_data[ 69 ^ 1 ] = ' ';
483               atapi_data[ 70 ^ 1 ] = '6';
484               atapi_data[ 71 ^ 1 ] = '.';
485               atapi_data[ 72 ^ 1 ] = '4';
486               atapi_data[ 73 ^ 1 ] = '2';
487
488               atapi_data[ 98 ^ 1 ] = 0x04; // IORDY may be disabled
489               atapi_data[ 99 ^ 1 ] = 0x00;
490
491               atapi_regs[ATAPI_REG_COUNTLOW] = 0;
492               atapi_regs[ATAPI_REG_COUNTHIGH] = 2;
493
494               gdrom_raise_irq(space->machine());
495               break;
496
497            case 0xef:   // SET FEATURES
498               // set xfer mode?
499               if (atapi_regs[ATAPI_REG_FEATURES] == 0x03)
500               {
501                  printf("Set transfer mode to %x\n", atapi_regs[ATAPI_REG_COUNTLOW] & 0xf8);
502                  xfer_mode = atapi_regs[ATAPI_REG_COUNTLOW] & 0xf8;
503               }
504               else
505               {
506                  printf("ATAPI: Unknown set features %x\n", atapi_regs[ATAPI_REG_FEATURES]);
507               }
508
509               atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
510               gdrom_alt_status = 0;   // is this correct?
511
512               atapi_data_ptr = 0;
513               atapi_data_len = 0;
514
515               gdrom_raise_irq(space->machine());
516               break;
517
518            default:
519               mame_printf_debug("ATAPI: Unknown IDE command %x\n", data);
520               break;
521         }
522      }
523   }
524}
525
526static void dreamcast_atapi_exit(running_machine& machine)
527{
528   if (gdrom_device != NULL)
529   {
530      SCSIDeleteInstance( gdrom_device );
531   }
532}
533
534void dreamcast_atapi_init(running_machine &machine)
535{
536   atapi_regs = auto_alloc_array(machine, UINT8,  ATAPI_REG_MAX );
537   memset(atapi_regs, 0, sizeof(atapi_regs));
538
539   atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
540   atapi_regs[ATAPI_REG_ERROR] = 1;
541   atapi_regs[ATAPI_REG_COUNTLOW] = 0x14;
542   atapi_regs[ATAPI_REG_COUNTHIGH] = 0xeb;
543
544   atapi_data_ptr = 0;
545   atapi_data_len = 0;
546   atapi_cdata_wait = 0;
547
548   atapi_timer = machine.scheduler().timer_alloc(FUNC(atapi_xfer_end));
549   atapi_timer->adjust(attotime::never);
550
551   gdrom_device = NULL;
552
553   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(dreamcast_atapi_exit),&machine));
554
555   atapi_data = auto_alloc_array(machine, UINT8,  ATAPI_DATA_SIZE );
556
557   state_save_register_global_pointer(machine,  atapi_regs, ATAPI_REG_MAX );
558   state_save_register_global_pointer(machine,  atapi_data, ATAPI_DATA_SIZE / 2 );
559   state_save_register_global(machine,  atapi_data_ptr );
560   state_save_register_global(machine,  atapi_data_len );
561   state_save_register_global(machine,  atapi_xferlen );
562   state_save_register_global(machine,  atapi_xferbase );
563   state_save_register_global(machine,  atapi_cdata_wait );
564   state_save_register_global(machine,  atapi_xfermod );
565}
566
567void dreamcast_atapi_reset(running_machine &machine)
568{
569   atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
570   atapi_regs[ATAPI_REG_ERROR] = 1;
571   atapi_regs[ATAPI_REG_COUNTLOW] = 0x14;
572   atapi_regs[ATAPI_REG_COUNTHIGH] = 0xeb;
573
574   atapi_data_ptr = 0;
575   atapi_data_len = 0;
576   atapi_cdata_wait = 0;
577
578   atapi_xferlen = 0;
579   atapi_xfermod = 0;
580
581   if ( cd_get_cdrom_file(machine.device( "cdrom" )) != NULL )
582   {
583      SCSIAllocInstance( machine, &SCSIClassGDROM, &gdrom_device, "cdrom" );
584   }
585   else
586   {
587      gdrom_device = NULL;
588   }
589}
590
591/*
592
593 GDROM regsters:
594
595 5f7018: alternate status/device control
596 5f7080: data
597 5f7084: error/features
598 5f7088: interrupt reason/sector count
599 5f708c: sector number
600 5f7090: byte control low
601 5f7094: byte control high
602 5f7098: drive select
603 5f709c: status/command
604
605c002910 - ATAPI packet writes
606c002796 - aux status read after that
607c000776 - DMA triggered to c008000
608
609*/
610
611READ64_HANDLER( dc_mess_gdrom_r )
612{
613   UINT32 off;
614
615   if ((int)~mem_mask & 1)
616   {
617      off=(offset << 1) | 1;
618   }
619   else
620   {
621      off=offset << 1;
622   }
623
624//  printf("gdrom_r: @ %x (off %x), mask %llx (PC %x)\n", offset, off, mem_mask, cpu_get_pc(&space->device()));
625
626   if (offset == 3)
627   {
628      return gdrom_alt_status;
629   }
630   else if (off >= 0x20)
631   {
632      return atapi_r(space, off-0x20, 0xff);
633   }
634
635   return 0;
636}
637
638WRITE64_HANDLER( dc_mess_gdrom_w )
639{
640   UINT32 dat,off;
641
642   if ((int)~mem_mask & 1)
643   {
644      dat=(UINT32)(data >> 32);
645      off=(offset << 1) | 1;
646   }
647   else
648   {
649      dat=(UINT32)data;
650      off=offset << 1;
651   }
652
653//  printf("GDROM: [%08x=%x]write %llx to %x, mask %llx (PC %x)\n", 0x5f7000+off*4, dat, data, offset, mem_mask, cpu_get_pc(&space->device()));
654
655   if (off >= 0x20)
656   {
657      atapi_w(space, off-0x20, dat, (UINT32)mem_mask);
658   }
659}
660
661// register decode helpers
662
663// this accepts only 32-bit accesses
664INLINE int decode_reg32_64(running_machine &machine, UINT32 offset, UINT64 mem_mask, UINT64 *shift)
665{
666   int reg = offset * 2;
667
668   *shift = 0;
669
670   // non 32-bit accesses have not yet been seen here, we need to know when they are
671   if ((mem_mask != U64(0xffffffff00000000)) && (mem_mask != U64(0x00000000ffffffff)))
672   {
673      mame_printf_verbose("%s:Wrong mask!\n", machine.describe_context());
674//      debugger_break(machine);
675   }
676
677   if (mem_mask == U64(0xffffffff00000000))
678   {
679      reg++;
680      *shift = 32;
681   }
682
683   return reg;
684}
685
686READ64_HANDLER( dc_mess_g1_ctrl_r )
687{
688   int reg;
689   UINT64 shift;
690
691   reg = decode_reg32_64(space->machine(), offset, mem_mask, &shift);
692   mame_printf_verbose("G1CTRL:  Unmapped read %08x\n", 0x5f7400+reg*4);
693   return (UINT64)g1bus_regs[reg] << shift;
694}
695
696WRITE64_HANDLER( dc_mess_g1_ctrl_w )
697{
698   int reg;
699   UINT64 shift;
700   UINT32 old,dat;
701
702   reg = decode_reg32_64(space->machine(), offset, mem_mask, &shift);
703   dat = (UINT32)(data >> shift);
704   old = g1bus_regs[reg];
705
706   g1bus_regs[reg] = dat; // 5f7400+reg*4=dat
707   mame_printf_verbose("G1CTRL: [%08x=%x] write %" I64FMT "x to %x, mask %" I64FMT "x\n", 0x5f7400+reg*4, dat, data, offset, mem_mask);
708   switch (reg)
709   {
710   case SB_GDST:
711      if (dat & 1 && g1bus_regs[SB_GDEN] == 1) // 0 -> 1
712      {
713         if (g1bus_regs[SB_GDDIR] == 0)
714         {
715            printf("G1CTRL: unsupported transfer\n");
716            return;
717         }
718
719         atapi_xferbase = g1bus_regs[SB_GDSTAR];
720         atapi_timer->adjust(space->machine().device<cpu_device>("maincpu")->cycles_to_attotime((ATAPI_CYCLES_PER_SECTOR * (atapi_xferlen/2048))));
721      }
722      break;
723   }
724}
725
src/mame/includes/segasms.h
r0r11451
1/*****************************************************************************
2 *
3 * includes/sms.h
4 *
5 ****************************************************************************/
6
7#ifndef SMS_H_
8#define SMS_H_
9
10#define LOG_REG
11#define LOG_PAGING
12#define LOG_COLOR
13
14#define NVRAM_SIZE             (0x08000)
15#define CPU_ADDRESSABLE_SIZE   (0x10000)
16
17#define MAX_CARTRIDGES        16
18
19class sms_state : public driver_device
20{
21public:
22   sms_state(const machine_config &mconfig, device_type type, const char *tag)
23   : driver_device(mconfig, type, tag) { }
24
25   // device_ts
26   device_t *m_main_cpu;
27   device_t *m_control_cpu;
28   device_t *m_vdp;
29   device_t *m_ym;
30   device_t *m_main_scr;
31   device_t *m_left_lcd;
32   device_t *m_right_lcd;
33
34   UINT8 m_bios_page_count;
35   UINT8 m_fm_detect;
36   UINT8 m_ctrl_reg;
37   int m_paused;
38   UINT8 m_bios_port;
39   UINT8 *m_BIOS;
40   UINT8 *m_mapper_ram;
41   UINT8 m_mapper[4];
42   // we are going to use 1-6, same as bank numbers. Notice, though, that most mappers
43   // only work on 16K banks and, hence, banks 4-6 are not always directly set
44   // (they often use bank3 + 0x2000 and bank5 + 0x2000)
45   UINT8 *m_banking_bios[7];
46   UINT8 *m_banking_cart[7];
47   UINT8 *m_banking_none[7];
48   UINT8 m_gg_sio[5];
49   UINT8 m_store_control;
50   UINT8 m_input_port0;
51   UINT8 m_input_port1;
52
53   // for gamegear LCD persistence hack
54   bitmap_t *m_tmp_bitmap;
55   bitmap_t *m_prev_bitmap;
56
57   // for 3D glass binocular hack
58   bitmap_t *m_prevleft_bitmap;
59   bitmap_t *m_prevright_bitmap;
60
61   /* Model identifiers */
62   UINT8 m_is_gamegear;
63   UINT8 m_is_region_japan;
64   UINT8 m_has_bios_0400;
65   UINT8 m_has_bios_2000;
66   UINT8 m_has_bios_full;
67   UINT8 m_has_bios;
68   UINT8 m_has_fm;
69
70   /* Data needed for Rapid Fire Unit support */
71   emu_timer *m_rapid_fire_timer;
72   UINT8 m_rapid_fire_state_1;
73   UINT8 m_rapid_fire_state_2;
74
75   /* Data needed for Paddle Control controller */
76   UINT32 m_last_paddle_read_time;
77   UINT8 m_paddle_read_state;
78
79   /* Data needed for Sports Pad controller */
80   UINT32 m_last_sports_pad_time_1;
81   UINT32 m_last_sports_pad_time_2;
82   UINT8 m_sports_pad_state_1;
83   UINT8 m_sports_pad_state_2;
84   UINT8 m_sports_pad_last_data_1;
85   UINT8 m_sports_pad_last_data_2;
86   UINT8 m_sports_pad_1_x;
87   UINT8 m_sports_pad_1_y;
88   UINT8 m_sports_pad_2_x;
89   UINT8 m_sports_pad_2_y;
90
91   /* Data needed for Light Phaser */
92   emu_timer *m_lphaser_1_timer;
93   emu_timer *m_lphaser_2_timer;
94   UINT8 m_lphaser_1_latch;
95   UINT8 m_lphaser_2_latch;
96   int m_lphaser_x_offs;   /* Needed to 'calibrate' lphaser; set at cart loading */
97
98   /* Data needed for SegaScope (3D glasses) */
99   UINT8 m_sscope_state;
100
101   /* Data needed for Terebi Oekaki (TV Draw) */
102   UINT8 m_tvdraw_data;
103
104   /* Cartridge slot info */
105   UINT8 m_current_cartridge;
106   struct
107   {
108      UINT8 *ROM;        /* Pointer to ROM image data */
109      UINT32 size;       /* Size of the ROM image */
110      UINT8 features;    /* on-cartridge special hardware */
111      UINT8 *cartSRAM;   /* on-cartridge SRAM */
112      UINT8 sram_save;   /* should be the contents of the on-cartridge SRAM be saved */
113      UINT8 *cartRAM;    /* additional on-cartridge RAM (64KB for Ernie Els Golf) */
114      UINT32 ram_size;   /* size of the on-cartridge RAM */
115      UINT8 ram_page;    /* currently swapped in cartridge RAM */
116   } m_cartridge[MAX_CARTRIDGES];
117};
118
119
120/*----------- defined in machine/sms.c -----------*/
121
122/* Function prototypes */
123WRITE8_HANDLER( sms_cartram_w );
124WRITE8_HANDLER( sms_cartram2_w );
125WRITE8_HANDLER( sms_fm_detect_w );
126READ8_HANDLER( sms_fm_detect_r );
127READ8_HANDLER( sms_input_port_0_r );
128READ8_HANDLER( sms_input_port_1_r );
129WRITE8_HANDLER( sms_ym2413_register_port_0_w );
130WRITE8_HANDLER( sms_ym2413_data_port_0_w );
131WRITE8_HANDLER( sms_io_control_w );
132READ8_HANDLER( sms_count_r );
133WRITE8_HANDLER( sms_sscope_w );
134READ8_HANDLER( sms_sscope_r );
135WRITE8_HANDLER( sms_mapper_w );
136READ8_HANDLER( sms_mapper_r );
137WRITE8_HANDLER( sms_bios_w );
138WRITE8_HANDLER( gg_sio_w );
139READ8_HANDLER( gg_sio_r );
140READ8_HANDLER( gg_input_port_2_r );
141
142INPUT_CHANGED( lgun1_changed );
143INPUT_CHANGED( lgun2_changed );
144
145void sms_pause_callback( running_machine &machine );
146void sms_store_int_callback( running_machine &machine, int state );
147
148DEVICE_START( sms_cart );
149DEVICE_IMAGE_LOAD( sms_cart );
150
151MACHINE_START( sms );
152MACHINE_RESET( sms );
153
154READ8_HANDLER( sms_store_cart_select_r );
155WRITE8_HANDLER( sms_store_cart_select_w );
156READ8_HANDLER( sms_store_select1 );
157READ8_HANDLER( sms_store_select2 );
158READ8_HANDLER( sms_store_control_r );
159WRITE8_HANDLER( sms_store_control_w );
160
161#define IO_EXPANSION    (0x80)   /* Expansion slot enable (1= disabled, 0= enabled) */
162#define IO_CARTRIDGE    (0x40)   /* Cartridge slot enable (1= disabled, 0= enabled) */
163#define IO_CARD         (0x20)   /* Card slot disabled (1= disabled, 0= enabled) */
164#define IO_WORK_RAM     (0x10)   /* Work RAM disabled (1= disabled, 0= enabled) */
165#define IO_BIOS_ROM     (0x08)   /* BIOS ROM disabled (1= disabled, 0= enabled) */
166#define IO_CHIP         (0x04)   /* I/O chip disabled (1= disabled, 0= enabled) */
167
168
169DRIVER_INIT( sg1000m3 );
170DRIVER_INIT( sms1 );
171DRIVER_INIT( smsj );
172DRIVER_INIT( sms2kr );
173DRIVER_INIT( smssdisp );
174DRIVER_INIT( gamegear );
175DRIVER_INIT( gamegeaj );
176
177VIDEO_START( sms1 );
178VIDEO_START( gamegear );
179SCREEN_UPDATE( sms1 );
180SCREEN_UPDATE( sms );
181SCREEN_UPDATE( gamegear );
182
183#endif /* SMS_H_ */
src/mame/includes/seta.h
r11450r11451
112112SCREEN_UPDATE( seta_no_layers );
113113SCREEN_UPDATE( usclssic );
114114SCREEN_UPDATE( inttoote );
115SCREEN_UPDATE( setaroul );
115116
117SCREEN_EOF( setaroul );
116118
src/mame/includes/sg1000.h
r0r11451
1#ifndef __SG1000__
2#define __SG1000__
3
4#include "machine/ram.h"
5
6#define SCREEN_TAG      "screen"
7#define Z80_TAG         "z80"
8#define SN76489A_TAG   "sn76489a"
9#define UPD765_TAG      "upd765"
10#define CASSETTE_TAG   "cassette"
11#define UPD8251_TAG      "upd8251"
12#define UPD9255_TAG      "upd9255"
13#define UPD9255_0_TAG   "upd9255_0"
14#define UPD9255_1_TAG   "upd9255_1"
15#define CENTRONICS_TAG   "centronics"
16
17#define IS_CARTRIDGE_TV_DRAW(ptr) \
18   (!strncmp("annakmn", (const char *)&ptr[0x13b3], 7))
19
20#define IS_CARTRIDGE_THE_CASTLE(ptr) \
21   (!strncmp("ASCII 1986", (const char *)&ptr[0x1cc3], 10))
22
23#define IS_CARTRIDGE_BASIC_LEVEL_III(ptr) \
24   (!strncmp("SC-3000 BASIC Level 3 ver 1.0", (const char *)&ptr[0x6a20], 29))
25
26#define IS_CARTRIDGE_MUSIC_EDITOR(ptr) \
27   (!strncmp("PIANO", (const char *)&ptr[0x0841], 5))
28
29class sg1000_state : public driver_device
30{
31public:
32   sg1000_state(const machine_config &mconfig, device_type type, const char *tag)
33      : driver_device(mconfig, type, tag),
34        m_maincpu(*this, Z80_TAG),
35        m_ram(*this, RAM_TAG)
36   { }
37
38   required_device<cpu_device> m_maincpu;
39   required_device<device_t> m_ram;
40
41   virtual void machine_start();
42
43   void install_cartridge(UINT8 *ptr, int size);
44
45   DECLARE_WRITE8_MEMBER( tvdraw_axis_w );
46   DECLARE_READ8_MEMBER( tvdraw_status_r );
47   DECLARE_READ8_MEMBER( tvdraw_data_r );
48   DECLARE_READ8_MEMBER( joysel_r );
49
50   /* keyboard state */
51   UINT8 m_keylatch;
52
53   /* TV Draw state */
54   UINT8 m_tvdraw_data;
55};
56
57class sc3000_state : public sg1000_state
58{
59public:
60   sc3000_state(const machine_config &mconfig, device_type type, const char *tag)
61      : sg1000_state(mconfig, type, tag),
62        m_cassette(*this, CASSETTE_TAG)
63   { }
64
65   required_device<device_t> m_cassette;
66
67   virtual void machine_start();
68
69   void install_cartridge(UINT8 *ptr, int size);
70
71   DECLARE_READ8_MEMBER( ppi_pa_r );
72   DECLARE_READ8_MEMBER( ppi_pb_r );
73   DECLARE_WRITE8_MEMBER( ppi_pc_w );
74};
75
76class sf7000_state : public sc3000_state
77{
78public:
79   sf7000_state(const machine_config &mconfig, device_type type, const char *tag)
80      : sc3000_state(mconfig, type, tag),
81        m_fdc(*this, UPD765_TAG),
82        m_centronics(*this, CENTRONICS_TAG),
83        m_floppy0(*this, FLOPPY_0)
84   { }
85
86   required_device<device_t> m_fdc;
87   required_device<device_t> m_centronics;
88   required_device<device_t> m_floppy0;
89
90   virtual void machine_start();
91   virtual void machine_reset();
92
93   DECLARE_READ8_MEMBER( ppi_pa_r );
94   DECLARE_WRITE8_MEMBER( ppi_pc_w );
95   DECLARE_WRITE_LINE_MEMBER( fdc_intrq_w );
96
97   /* floppy state */
98   int m_fdc_irq;
99   int m_fdc_index;
100};
101
102#endif
src/mame/mame.mak
r11450r11451
1818LAYOUT = $(MAMEOBJ)/layout
1919MACHINE = $(MAMEOBJ)/machine
2020VIDEO = $(MAMEOBJ)/video
21FORMATS = $(MAMEOBJ)/formats
2122
2223OBJDIRS += \
2324   $(AUDIO) \
r11450r11451
2526   $(LAYOUT) \
2627   $(MACHINE) \
2728   $(VIDEO) \
29   $(FORMATS) \
2830
2931
3032
r11450r11451
335337   $(MAMEOBJ)/misc.a \
336338   $(MAMEOBJ)/pinball.a \
337339   $(MAMEOBJ)/shared.a \
340   $(MAMEOBJ)/formats.a \
338341
339342
340343
r11450r11451
352355   $(MACHINE)/ticket.o \
353356   $(VIDEO)/avgdvg.o \
354357
358#-------------------------------------------------
359# file formats, mostly used for MESS software
360#-------------------------------------------------
355361
362$(MAMEOBJ)/formats.a: \
363   $(FORMATS)/basicdsk.o   \
356364
357365#-------------------------------------------------
358366# manufacturer-specific groupings for drivers
r11450r11451
12191227   $(VIDEO)/segaic16.o \
12201228   $(VIDEO)/sega16sp.o \
12211229   $(VIDEO)/segaic24.o \
1230   $(VIDEO)/smsvdp.o \
1231   $(MACHINE)/segasms.o \
1232   $(DRIVERS)/segasms.o \
1233   $(DRIVERS)/sg1000.o \
1234   $(DRIVERS)/dc.o \
1235   $(MACHINE)/dccons.o \
1236   $(MACHINE)/gdrom.o \
12221237
12231238$(MAMEOBJ)/seibu.a: \
12241239   $(DRIVERS)/bloodbro.o $(VIDEO)/bloodbro.o \
r11450r11451
19761991
19771992$(DRIVERS)/segas32.o:   $(LAYOUT)/radr.lh
19781993
1994$(DRIVERS)/segasms.o:   $(LAYOUT)/sms1.lh
1995
19791996$(DRIVERS)/segaybd.o:   $(LAYOUT)/pdrift.lh
19801997
19811998$(DRIVERS)/snookr10.o:   $(LAYOUT)/snookr10.lh
src/mame/video/seta001.c
r11450r11451
5656   m_bgflag = 0x00;
5757
5858   m_bankcallback = NULL;
59
60   save_pointer(NAME(m_spriteylow), 0x300);
61   save_pointer(NAME(m_spritecodelow), 0x2000);
62   save_pointer(NAME(m_spritecodehigh), 0x2000);
63
64
5965}
6066
6167void seta001_device::device_reset()
r11450r11451
9197   dev->m_spritectrl[offset] = data;
9298}
9399
94// why is this needed? bug in the rendering?
95WRITE8_DEVICE_HANDLER( spritectrl_w8_champbwl )
96{
97   seta001_device *dev = (seta001_device *)device;
98
99   // hack??
100   //if (offset!=0) data ^=0xff;
101
102   dev->m_spritectrl[offset] = data;
103}
104
105100READ16_DEVICE_HANDLER( spriteylow_r16 )
106101{
107102   seta001_device *dev = (seta001_device *)device;
r11450r11451
294289               code,
295290               color,
296291               flipx,flipy,
297               ((sx + 0x10) & 0x1ff) - 0x10,((sy + 8) & 0x0ff) - 8,
292               ((sx) & 0x1ff),((sy) & 0x0ff),
298293               transpen);
294
295         drawgfx_transpen(bitmap,cliprect,machine.gfx[0],
296               code,
297               color,
298               flipx,flipy,
299               ((sx) & 0x1ff)-512,((sy) & 0x0ff),
300               transpen);
301
302         drawgfx_transpen(bitmap,cliprect,machine.gfx[0],
303               code,
304               color,
305               flipx,flipy,
306               ((sx) & 0x1ff),((sy) & 0x0ff)-256,
307               transpen);
308
309         drawgfx_transpen(bitmap,cliprect,machine.gfx[0],
310               code,
311               color,
312               flipx,flipy,
313               ((sx) & 0x1ff)-512,((sy) & 0x0ff)-256,
314               transpen);
315
299316      }
300317   }
301318}
r11450r11451
361378            code,
362379            color,
363380            flipx,flipy,
364            sx,
381            ((sx + xoffs)&0x1ff),
365382            max_y - ((sy + yoffs) & 0x0ff),m_transpen);
366383
367384      /* wrap around x */
r11450r11451
369386            code,
370387            color,
371388            flipx,flipy,
372            sx+512,
389            ((sx + xoffs)&0x1ff) - 512,
373390            max_y - ((sy + yoffs) & 0x0ff),m_transpen);
391
392
393      drawgfx_transpen(bitmap,cliprect,machine.gfx[0],
394            code,
395            color,
396            flipx,flipy,
397            ((sx + xoffs)&0x1ff),
398            max_y - ((sy + yoffs) & 0x0ff)-256,m_transpen);
399
400      /* wrap around x */
401      drawgfx_transpen(bitmap,cliprect,machine.gfx[0],
402            code,
403            color,
404            flipx,flipy,
405            ((sx + xoffs)&0x1ff) - 512,
406            max_y - ((sy + yoffs) & 0x0ff)-256,m_transpen);
407
374408   }
375409}
376410
src/mame/video/seta001.h
r11450r11451
6464WRITE16_DEVICE_HANDLER( spritectrl_w16 );
6565READ8_DEVICE_HANDLER( spritectrl_r8 );
6666WRITE8_DEVICE_HANDLER( spritectrl_w8 );
67WRITE8_DEVICE_HANDLER( spritectrl_w8_champbwl );
6867
6968READ16_DEVICE_HANDLER( spriteylow_r16 );
7069WRITE16_DEVICE_HANDLER( spriteylow_w16 );
src/mame/video/seta.c
r11450r11451
827827***************************************************************************/
828828   
829829
830
831
832
833830/* For games without tilemaps */
834831SCREEN_UPDATE( seta_no_layers )
835832{
r11450r11451
842839
843840
844841/* For games with 1 or 2 tilemaps */
845static SCREEN_UPDATE( seta_layers )
842void seta_layers_update(screen_device* screen, bitmap_t *bitmap, const rectangle *cliprect, int sprite_bank_size, int sprite_setac )
846843{
847844   seta_state *state = screen->machine().driver_data<seta_state>();
848845   int layers_ctrl = -1;
r11450r11451
959956
960957      if (order & 2)   // layer-sprite priority?
961958      {
962         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,0x1000, 1);
959         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,sprite_bank_size, sprite_setac);
963960
964961         if(order & 4)
965962         {
r11450r11451
979976         if (layers_ctrl & 1)   tilemap_draw(bitmap, cliprect, state->m_tilemap_0,  0, 0);
980977         if (layers_ctrl & 1)   tilemap_draw(bitmap, cliprect, state->m_tilemap_1,  0, 0);
981978
982         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,0x1000, 1);
979         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,sprite_bank_size, sprite_setac);
983980      }
984981   }
985982   else
r11450r11451
989986
990987      if (order & 2)   // layer-sprite priority?
991988      {
992         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,0x1000, 1);
989         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,sprite_bank_size, sprite_setac);
993990
994991         if((order & 4) && state->m_paletteram2 != NULL)
995992         {
r11450r11451
10431040            }
10441041         }
10451042
1046         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,0x1000, 1);
1043         if (layers_ctrl & 8)      screen->machine().device<seta001_device>("spritegen")->seta001_draw_sprites(screen->machine(),bitmap,cliprect,sprite_bank_size, sprite_setac);
10471044      }
10481045   }
1046
1047}
1048
1049static SCREEN_UPDATE( seta_layers )
1050{
1051   seta_layers_update(screen, bitmap, cliprect, 0x1000, 1 );
10491052   return 0;
10501053}
10511054
10521055
1056SCREEN_UPDATE( setaroul )
1057{
1058   bitmap_fill(bitmap, cliprect, 0x0);
1059
1060   screen->machine().device<seta001_device>("spritegen")->set_fg_yoffsets( -0x12, 0x0e );
1061   screen->machine().device<seta001_device>("spritegen")->set_bg_yoffsets( 0x1, -0x1 );
1062
1063   seta_layers_update(screen, bitmap, cliprect, 0x800, 1 );
1064
1065   return 0;
1066}
1067
1068SCREEN_EOF( setaroul )
1069{
1070   machine.device<seta001_device>("spritegen")->tnzs_eof();
1071}
1072
1073
1074
10531075SCREEN_UPDATE( seta )
10541076{
10551077   set_pens(screen->machine());
src/mame/video/smsvdp.c
r0r11451
1/*********************************************************************
2
3    smsvdp.c
4
5    Implementation of video hardware chip used by Sega Master System
6
7**********************************************************************/
8
9/*
10    For more information, please see:
11    - http://cgfm2.emuviews.com/txt/msvdp.txt
12    - http://www.smspower.org/forums/viewtopic.php?p=44198
13
14A scanline contains the following sections:
15  - horizontal sync     1  ED      => HSYNC high/increment line counter/generate interrupts/etc
16  - left blanking       2  ED-EE
17  - color burst        14  EE-EF
18  - left blanking       8  F5-F9
19  - left border        13  F9-FF
20  - active display    256  00-7F
21  - right border       15  80-87
22  - right blanking      8  87-8B
23  - horizontal sync    25  8B-97   => HSYNC low
24
25
26NTSC frame timing
27                       256x192         256x224        256x240 (doesn't work on real hardware)
28  - vertical blanking   3  D5-D7        3  E5-E7       3  EE-F0
29  - top blanking       13  D8-E4       13  E8-F4      13  F1-FD
30  - top border         27  E5-FF       11  F5-FF       3  FD-FF
31  - active display    192  00-BF      224  00-DF     240  00-EF
32  - bottom border      24  C0-D7        8  E0-E7       0  F0-F0
33  - bottom blanking     3  D8-DA        3  E8-EA       3  F0-F2
34
35
36PAL frame timing
37                       256x192         256x224        256x240
38  - vertical blanking   3  BA-BC        3  CA-CC       3  D2-D4
39  - top blanking       13  BD-C9       13  CD-D9      13  D5-E1
40  - top border         54  CA-FF       38  DA-FF      30  E2-FF
41  - active display    192  00-BF      224  00-DF     240  00-EF
42  - bottom border      48  C0-EF       32  E0-FF      24  F0-07
43  - bottom blanking     3  F0-F2        3  00-02       3  08-0A
44
45  TODO:
46    - implement differences between SMS1_VDP & SMS_VDP/GG_VDP
47
48*/
49
50#include "emu.h"
51#include "video/smsvdp.h"
52
53#define IS_SMS1_VDP           (smsvdp->features & MODEL_315_5124)
54#define IS_SMS2_VDP           (smsvdp->features & MODEL_315_5246)
55#define IS_GAMEGEAR_VDP       (smsvdp->features & MODEL_315_5378)
56
57#define STATUS_VINT           0x80   /* Pending vertical interrupt flag */
58#define STATUS_SPROVR         0x40   /* Sprite overflow flag */
59#define STATUS_SPRCOL         0x20   /* Object collision flag */
60#define STATUS_HINT           0x02   /* Pending horizontal interrupt flag */
61
62#define VINT_HPOS             23
63#define HINT_HPOS             23
64#define VCOUNT_CHANGE_HPOS    22
65#define VINT_FLAG_HPOS        7
66#define SPROVR_HPOS           6
67#define SPRCOL_BASEHPOS       42
68#define DISPLAY_CB_HPOS       5  /* fix X-Scroll latchtime (Flubba's VDPTest) */
69
70#define GG_CRAM_SIZE          0x40   /* 32 colors x 2 bytes per color = 64 bytes */
71#define SMS_CRAM_SIZE         0x20   /* 32 colors x 1 bytes per color = 32 bytes */
72#define MAX_CRAM_SIZE         0x40
73
74#define VRAM_SIZE             0x4000
75
76#define PRIORITY_BIT          0x1000
77#define BACKDROP_COLOR        ((smsvdp->vdp_mode == 4 ? 0x10 : 0x00) + (smsvdp->reg[0x07] & 0x0f))
78
79#define NUM_OF_REGISTER       0x10  /* 16 registers */
80
81#define INIT_VCOUNT           0
82#define VERTICAL_BLANKING     1
83#define TOP_BLANKING          2
84#define TOP_BORDER            3
85#define ACTIVE_DISPLAY_V      4
86#define BOTTOM_BORDER         5
87#define BOTTOM_BLANKING       6
88
89static const UINT8 sms_ntsc_192[7] = { 0xd5, 3, 13, 27, 192, 24, 3 };
90static const UINT8 sms_ntsc_224[7] = { 0xe5, 3, 13, 11, 224,  8, 3 };
91static const UINT8 sms_ntsc_240[7] = { 0xee, 3, 13,  3, 240,  0, 3 };
92static const UINT8 sms_pal_192[7]  = { 0xba, 3, 13, 54, 192, 48, 3 };
93static const UINT8 sms_pal_224[7]  = { 0xca, 3, 13, 38, 224, 32, 3 };
94static const UINT8 sms_pal_240[7]  = { 0xd2, 3, 13, 30, 240, 24, 3 };
95
96
97typedef struct _smsvdp_t smsvdp_t;
98struct _smsvdp_t
99{
100   UINT32           features;
101   UINT8            reg[NUM_OF_REGISTER];     /* All the registers */
102   UINT8            status;                   /* Status register */
103   UINT8            reg9copy;                 /* Internal copy of register 9 */
104   UINT8            addrmode;                 /* Type of VDP action */
105   UINT16           addr;                     /* Contents of internal VDP address register */
106   UINT8            cram_mask;                /* Mask to switch between SMS and GG CRAM sizes */
107   int              cram_dirty;               /* Have there been any changes to the CRAM area */
108   int              pending;
109   UINT8            buffer;
110   int              gg_sms_mode;              /* Shrunk SMS screen on GG lcd mode flag */
111   int              irq_state;                /* The status of the IRQ line of the VDP */
112   int              vdp_mode;                 /* Current mode of the VDP: 0,1,2,3,4 */
113   int              y_pixels;                 /* 192, 224, 240 */
114   UINT8            line_counter;
115   UINT8            hcounter;
116   memory_region            *VRAM;                    /* Pointer to VRAM */
117   memory_region            *CRAM;                    /* Pointer to CRAM */
118   const UINT8      *sms_frame_timing;
119   bitmap_t         *tmpbitmap;
120   UINT8            *collision_buffer;
121
122   /* line_buffer will be used to hold 5 lines of line data. Line #0 is the regular blitting area.
123       Lines #1-#4 will be used as a kind of cache to be used for vertical scaling in the gamegear
124       sms compatibility mode. */
125   int              *line_buffer;
126   int              current_palette[32];
127   smsvdp_int_cb    int_callback;
128   smsvdp_pause_cb  pause_callback;
129   emu_timer        *smsvdp_display_timer;
130};
131
132static TIMER_CALLBACK( smsvdp_display_callback );
133static void sms_refresh_line( running_machine &machine, smsvdp_t *smsvdp, bitmap_t *bitmap, int offsetx, int offsety, int line );
134static void sms_update_palette( smsvdp_t *smsvdp );
135
136
137/*****************************************************************************
138    INLINE FUNCTIONS
139*****************************************************************************/
140
141INLINE smsvdp_t *get_safe_token(device_t *device)
142{
143   assert(device != NULL);
144   assert(device->type() == SMSVDP);
145
146   return (smsvdp_t *)downcast<legacy_device_base *>(device)->token();
147}
148
149INLINE const smsvdp_interface *get_interface(device_t *device)
150{
151   assert(device != NULL);
152   assert((device->type() == SMSVDP));
153   return (const smsvdp_interface *) device->static_config();
154}
155
156/*************************************
157 *
158 *  Utilities
159 *
160 *************************************/
161
162static void set_display_settings( device_t *device )
163{
164   smsvdp_t *smsvdp = get_safe_token(device);
165
166   screen_device *screen = device->machine().first_screen();
167   int height = screen->height();
168   int M1, M2, M3, M4;
169   M1 = smsvdp->reg[0x01] & 0x10;
170   M2 = smsvdp->reg[0x00] & 0x02;
171   M3 = smsvdp->reg[0x01] & 0x08;
172   M4 = smsvdp->reg[0x00] & 0x04;
173   smsvdp->y_pixels = 192;
174   if (M4)
175   {
176      /* mode 4 */
177      smsvdp->vdp_mode = 4;
178      if (M2 && (IS_SMS2_VDP || IS_GAMEGEAR_VDP))
179      {
180         if (M1 && !M3)
181            smsvdp->y_pixels = 224;   /* 224-line display */
182         else if (!M1 && M3)
183            smsvdp->y_pixels = 240;   /* 240-line display */
184      }
185   }
186   else
187   {
188      /* original TMS9918 mode */
189      if (!M1 && !M2 && !M3)
190      {
191         smsvdp->vdp_mode = 0;
192      }
193      else
194//      if (M1 && !M2 && !M3)
195//      {
196//          smsvdp->vdp_mode = 1;
197//      }
198//      else
199      if (!M1 && M2 && !M3)
200      {
201         smsvdp->vdp_mode = 2;
202//      }
203//      else
204//      if (!M1 && !M2 && M3)
205//      {
206//          smsvdp->vdp_mode = 3;
207      }
208      else
209      {
210         logerror("Unknown video mode detected (M1 = %c, M2 = %c, M3 = %c, M4 = %c)\n", M1 ? '1' : '0', M2 ? '1' : '0', M3 ? '1' : '0', M4 ? '1' : '0');
211      }
212   }
213
214   switch (smsvdp->y_pixels)
215   {
216   case 192:
217      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_192 : sms_ntsc_192;
218      break;
219
220   case 224:
221      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_224 : sms_ntsc_224;
222      break;
223
224   case 240:
225      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_240 : sms_ntsc_240;
226      break;
227   }
228   smsvdp->cram_dirty = 1;
229}
230
231
232READ8_DEVICE_HANDLER( sms_vdp_vcount_r )
233{
234   smsvdp_t *smsvdp = get_safe_token(device);
235   int vpos = device->machine().primary_screen->vpos();
236
237   if (device->machine().primary_screen->hpos() < VCOUNT_CHANGE_HPOS)
238   {
239      vpos--;
240      if (vpos < 0)
241         vpos += device->machine().primary_screen->height();
242   }
243
244   return (smsvdp->sms_frame_timing[INIT_VCOUNT] + vpos) & 0xff;
245}
246
247
248READ8_DEVICE_HANDLER( sms_vdp_hcount_latch_r )
249{
250   smsvdp_t *smsvdp = get_safe_token(device);
251
252   return smsvdp->hcounter;
253}
254
255WRITE8_DEVICE_HANDLER( sms_vdp_hcount_latch_w )
256{
257   smsvdp_t *smsvdp = get_safe_token(device);
258
259   smsvdp->hcounter = data;
260}
261
262
263void sms_vdp_set_ggsmsmode( device_t *device, int mode )
264{
265   smsvdp_t *smsvdp = get_safe_token(device);
266
267   smsvdp->gg_sms_mode = mode;
268   smsvdp->cram_mask = (IS_GAMEGEAR_VDP && !smsvdp->gg_sms_mode) ? (GG_CRAM_SIZE - 1) : (SMS_CRAM_SIZE - 1);
269}
270
271
272static TIMER_CALLBACK( smsvdp_set_status )
273{
274   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
275
276   smsvdp->status |= (UINT8) param;
277}
278
279
280static TIMER_CALLBACK( smsvdp_check_hint )
281{
282   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
283
284   if (smsvdp->line_counter == 0x00)
285   {
286      smsvdp->line_counter = smsvdp->reg[0x0a];
287      smsvdp->status |= STATUS_HINT;
288   }
289   else
290   {
291      smsvdp->line_counter--;
292   }
293
294   if ((smsvdp->status & STATUS_HINT) && (smsvdp->reg[0x00] & 0x10))
295   {
296      smsvdp->irq_state = 1;
297
298      if (smsvdp->int_callback)
299         smsvdp->int_callback(machine, ASSERT_LINE);
300   }
301}
302
303
304static TIMER_CALLBACK( smsvdp_check_vint )
305{
306   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
307
308   if ((smsvdp->status & STATUS_VINT) && (smsvdp->reg[0x01] & 0x20))
309   {
310      smsvdp->irq_state = 1;
311
312      if (smsvdp->int_callback)
313         smsvdp->int_callback(machine, ASSERT_LINE);
314   }
315}
316
317
318static TIMER_CALLBACK( smsvdp_display_callback )
319{
320   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
321
322   rectangle rec;
323   int vpos = machine.primary_screen->vpos();
324   int vpos_limit = smsvdp->sms_frame_timing[VERTICAL_BLANKING] + smsvdp->sms_frame_timing[TOP_BLANKING]
325                  + smsvdp->sms_frame_timing[TOP_BORDER] + smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V]
326                  + smsvdp->sms_frame_timing[BOTTOM_BORDER] + smsvdp->sms_frame_timing[BOTTOM_BLANKING];
327
328   rec.min_y = rec.max_y = vpos;
329
330   /* Check if we're on the last line of a frame */
331   if (vpos == vpos_limit - 1)
332   {
333      smsvdp->line_counter = smsvdp->reg[0x0a];
334      if (smsvdp->pause_callback)
335         smsvdp->pause_callback(machine);
336
337      return;
338   }
339
340   vpos_limit -= smsvdp->sms_frame_timing[BOTTOM_BLANKING];
341
342   /* Check if we're below the bottom border */
343   if (vpos >= vpos_limit)
344   {
345      smsvdp->line_counter = smsvdp->reg[0x0a];
346      return;
347   }
348
349   vpos_limit -= smsvdp->sms_frame_timing[BOTTOM_BORDER];
350
351   /* Check if we're in the bottom border area */
352   if (vpos >= vpos_limit)
353   {
354      if (vpos == vpos_limit)
355      {
356         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, HINT_HPOS), FUNC(smsvdp_check_hint),0 ,smsvdp);
357      }
358      else
359      {
360         smsvdp->line_counter = smsvdp->reg[0x0a];
361      }
362
363      if (vpos == vpos_limit + 1)
364      {
365         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, VINT_FLAG_HPOS), FUNC(smsvdp_set_status), (int)STATUS_VINT, smsvdp);
366         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, VINT_HPOS), FUNC(smsvdp_check_vint), 0, smsvdp);
367      }
368
369      sms_update_palette(smsvdp);
370
371      /* Draw left border */
372      rec.min_x = LBORDER_START;
373      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
374      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
375
376      /* Draw right border */
377      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
378      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
379      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
380
381      /* Draw middle of the border */
382      /* We need to do this through the regular drawing function so it will */
383      /* be included in the gamegear scaling functions */
384      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit - smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V], vpos - (vpos_limit - smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V]));
385      return;
386   }
387
388   vpos_limit -= smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V];
389
390   /* Check if we're in the active display area */
391   if (vpos >= vpos_limit)
392   {
393      if (vpos == vpos_limit)
394      {
395         smsvdp->reg9copy = smsvdp->reg[0x09];
396      }
397
398      machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, HINT_HPOS), FUNC(smsvdp_check_hint),0, smsvdp);
399
400      sms_update_palette(smsvdp);
401
402      /* Draw left border */
403      rec.min_x = LBORDER_START;
404      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
405      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
406
407      /* Draw right border */
408      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
409      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
410      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
411
412      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit, vpos - vpos_limit);
413
414      return;
415   }
416
417   vpos_limit -= smsvdp->sms_frame_timing[TOP_BORDER];
418
419   /* Check if we're in the top border area */
420   if (vpos >= vpos_limit)
421   {
422      smsvdp->line_counter = smsvdp->reg[0x0a];
423      sms_update_palette(smsvdp);
424
425      /* Draw left border */
426      rec.min_x = LBORDER_START;
427      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
428      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
429
430      /* Draw right border */
431      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
432      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
433      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
434
435      /* Draw middle of the border */
436      /* We need to do this through the regular drawing function so it will */
437      /* be included in the gamegear scaling functions */
438      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit + smsvdp->sms_frame_timing[TOP_BORDER], vpos - (vpos_limit + smsvdp->sms_frame_timing[TOP_BORDER]));
439      return;
440   }
441
442   /* we're in the vertical or top blanking area */
443   smsvdp->line_counter = smsvdp->reg[0x0a];
444}
445
446
447READ8_DEVICE_HANDLER( sms_vdp_data_r )
448{
449   smsvdp_t *smsvdp = get_safe_token(device);
450   UINT8 temp;
451
452   /* SMS 2 & GG behaviour. Seems like the latched data is passed straight through */
453   /* to the address register when in the middle of doing a command.               */
454   /* Cosmic Spacehead needs this, among others                                    */
455   /* Clear pending write flag */
456   smsvdp->pending = 0;
457
458   /* Return read buffer contents */
459   temp = smsvdp->buffer;
460
461   /* Load read buffer */
462   smsvdp->buffer = smsvdp->VRAM->u8((smsvdp->addr & 0x3fff));
463
464   /* Bump internal address register */
465   smsvdp->addr += 1;
466   return temp;
467}
468
469
470READ8_DEVICE_HANDLER( sms_vdp_ctrl_r )
471{
472   smsvdp_t *smsvdp = get_safe_token(device);
473
474   UINT8 temp = smsvdp->status;
475
476   /* Clear pending write flag */
477   smsvdp->pending = 0;
478
479   smsvdp->status &= ~(STATUS_VINT | STATUS_SPROVR | STATUS_SPRCOL | STATUS_HINT);
480
481   if (smsvdp->irq_state == 1)
482   {
483      smsvdp->irq_state = 0;
484
485      if (smsvdp->int_callback)
486         smsvdp->int_callback(device->machine(), CLEAR_LINE);
487   }
488
489   /* low 5 bits return non-zero data (it fixes PGA Tour Golf course map introduction) */
490   return temp | 0x1f;
491}
492
493
494WRITE8_DEVICE_HANDLER( sms_vdp_data_w )
495{
496   smsvdp_t *smsvdp = get_safe_token(device);
497   int address;
498
499   /* SMS 2 & GG behaviour. Seems like the latched data is passed straight through */
500   /* to the address register when in the middle of doing a command.               */
501   /* Cosmic Spacehead needs this, among others                                    */
502   /* Clear pending write flag */
503   smsvdp->pending = 0;
504
505   switch(smsvdp->addrmode)
506   {
507      case 0x00:
508      case 0x01:
509      case 0x02:
510         address = (smsvdp->addr & 0x3fff);
511         smsvdp->VRAM->u8(address) = data;
512         break;
513
514      case 0x03:
515         address = smsvdp->addr & smsvdp->cram_mask;
516         if (data != smsvdp->CRAM->u8(address))
517         {
518            smsvdp->CRAM->u8(address) = data;
519            smsvdp->cram_dirty = 1;
520         }
521         break;
522   }
523
524   smsvdp->buffer = data;
525   smsvdp->addr += 1;
526}
527
528
529WRITE8_DEVICE_HANDLER( sms_vdp_ctrl_w )
530{
531   smsvdp_t *smsvdp = get_safe_token(device);
532
533   int reg_num;
534
535   if (smsvdp->pending == 0)
536   {
537      smsvdp->addr = (smsvdp->addr & 0xff00) | data;
538      smsvdp->pending = 1;
539   }
540   else
541   {
542      /* Clear pending write flag */
543      smsvdp->pending = 0;
544
545      smsvdp->addrmode = (data >> 6) & 0x03;
546      smsvdp->addr = (data << 8) | (smsvdp->addr & 0xff);
547      switch (smsvdp->addrmode)
548      {
549      case 0:      /* VRAM reading mode */
550         smsvdp->buffer = smsvdp->VRAM->u8(smsvdp->addr & 0x3fff);
551         smsvdp->addr += 1;
552         break;
553
554      case 1:      /* VRAM writing mode */
555         break;
556
557      case 2:      /* VDP register write */
558         reg_num = data & 0x0f;
559         smsvdp->reg[reg_num] = smsvdp->addr & 0xff;
560         if (reg_num == 0 && smsvdp->addr & 0x02)
561            logerror("overscan enabled.\n");
562
563         if (reg_num == 0 || reg_num == 1)
564            set_display_settings(device);
565
566         if (reg_num == 1)
567         {
568            device->machine().scheduler().timer_set(device->machine().primary_screen->time_until_pos(device->machine().primary_screen->vpos(), VINT_HPOS), FUNC(smsvdp_check_vint),0 ,smsvdp);
569         }
570         smsvdp->addrmode = 0;
571         break;
572
573      case 3:      /* CRAM writing mode */
574         break;
575      }
576   }
577}
578
579
580static void sms_refresh_line_mode4( smsvdp_t *smsvdp, int *line_buffer, int *priority_selected, int line )
581{
582   int tile_column;
583   int x_scroll, y_scroll, x_scroll_start_column;
584   int pixel_x, pixel_plot_x;
585   int bit_plane_0, bit_plane_1, bit_plane_2, bit_plane_3;
586   int scroll_mod;
587   UINT16 name_table_address;
588   UINT8 *name_table;
589
590   if (smsvdp->y_pixels != 192)
591   {
592      name_table_address = ((smsvdp->reg[0x02] & 0x0c) << 10) | 0x0700;
593      scroll_mod = 256;
594   }
595   else
596   {
597      name_table_address = (smsvdp->reg[0x02] << 10) & 0x3800;
598      scroll_mod = 224;
599   }
600
601   if (IS_SMS1_VDP)
602      name_table_address = name_table_address & (((smsvdp->reg[0x02] & 0x01) << 10) | 0x3bff);
603
604   /* if top 2 rows of screen not affected by horizontal scrolling, then x_scroll = 0 */
605   /* else x_scroll = reg[0x08]                                                       */
606   x_scroll = (((smsvdp->reg[0x00] & 0x40) && (line < 16)) ? 0 : 0x0100 - smsvdp->reg[0x08]);
607
608   x_scroll_start_column = (x_scroll >> 3);          /* x starting column tile */
609
610   /* Draw background layer */
611   for (tile_column = 0; tile_column < 33; tile_column++)
612   {
613      UINT16 tile_data;
614      int tile_selected, palette_selected, horiz_selected, vert_selected, priority_select;
615      int tile_line;
616
617      /* Rightmost 8 columns for SMS (or 2 columns for GG) not affected by */
618      /* vertical scrolling when bit 7 of reg[0x00] is set */
619      y_scroll = ((smsvdp->reg[0x00] & 0x80) && (tile_column > 23)) ? 0 : smsvdp->reg9copy;
620
621      name_table = smsvdp->VRAM->base() + name_table_address + ((((line + y_scroll) % scroll_mod) >> 3) << 6);
622
623      tile_line = ((tile_column + x_scroll_start_column) & 0x1f) * 2;
624      tile_data = name_table[tile_line] | (name_table[tile_line + 1] << 8);
625
626      tile_selected = (tile_data & 0x01ff);
627      priority_select = tile_data & PRIORITY_BIT;
628      palette_selected = (tile_data >> 11) & 0x01;
629      vert_selected = (tile_data >> 10) & 0x01;
630      horiz_selected = (tile_data >> 9) & 0x01;
631
632      tile_line = line - ((0x07 - (y_scroll & 0x07)) + 1);
633      if (vert_selected)
634         tile_line = 0x07 - tile_line;
635
636      bit_plane_0 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x00);
637      bit_plane_1 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x01);
638      bit_plane_2 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x02);
639      bit_plane_3 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x03);
640
641      for (pixel_x = 0; pixel_x < 8 ; pixel_x++)
642      {
643         UINT8 pen_bit_0, pen_bit_1, pen_bit_2, pen_bit_3;
644         UINT8 pen_selected;
645
646         pen_bit_0 = (bit_plane_0 >> (7 - pixel_x)) & 0x01;
647         pen_bit_1 = (bit_plane_1 >> (7 - pixel_x)) & 0x01;
648         pen_bit_2 = (bit_plane_2 >> (7 - pixel_x)) & 0x01;
649         pen_bit_3 = (bit_plane_3 >> (7 - pixel_x)) & 0x01;
650
651         pen_selected = (pen_bit_3 << 3 | pen_bit_2 << 2 | pen_bit_1 << 1 | pen_bit_0);
652         if (palette_selected)
653            pen_selected |= 0x10;
654
655
656         if (!horiz_selected)
657         {
658            pixel_plot_x = pixel_x;
659         }
660         else
661         {
662            pixel_plot_x = 7 - pixel_x;
663         }
664         pixel_plot_x = (0 - (x_scroll & 0x07) + (tile_column << 3) + pixel_plot_x);
665         if (pixel_plot_x >= 0 && pixel_plot_x < 256)
666         {
667//              logerror("%x %x\n", pixel_plot_x + pixel_offset_x, pixel_plot_y);
668            line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
669            priority_selected[pixel_plot_x] = priority_select | (pen_selected & 0x0f);
670         }
671      }
672   }
673}
674
675static void sms_refresh_mode4_sprites( running_machine &machine, smsvdp_t *smsvdp, int *line_buffer, int *priority_selected, int pixel_plot_y, int line )
676{
677   int sprite_index;
678   int pixel_x, pixel_plot_x;
679   int sprite_x, sprite_y, sprite_line, sprite_tile_selected, sprite_height, sprite_zoom;
680   int sprite_col_occurred, sprite_col_x;
681   int sprite_buffer[8], sprite_buffer_count, sprite_buffer_index;
682   int bit_plane_0, bit_plane_1, bit_plane_2, bit_plane_3;
683   UINT8 *sprite_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x05] << 7) & 0x3f00);
684
685   /* Draw sprite layer */
686   sprite_height = (smsvdp->reg[0x01] & 0x02 ? 16 : 8);
687   sprite_zoom = 1;
688
689   if (smsvdp->reg[0x01] & 0x01)      /* sprite doubling */
690      sprite_zoom = 2;
691
692   sprite_buffer_count = 0;
693   for (sprite_index = 0; (sprite_index < 64) && (sprite_table[sprite_index] != 0xd0 || smsvdp->y_pixels != 192) && (sprite_buffer_count < 9); sprite_index++)
694   {
695      sprite_y = sprite_table[sprite_index] + 1; /* sprite y position starts at line 1 */
696
697      if (sprite_y > 240)
698         sprite_y -= 256; /* wrap from top if y position is > 240 */
699
700      if ((line >= sprite_y) && (line < (sprite_y + sprite_height * sprite_zoom)))
701      {
702         if (sprite_buffer_count < 8)
703         {
704            sprite_buffer[sprite_buffer_count] = sprite_index;
705         }
706         else if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
707         {
708            /* Too many sprites per line */
709            machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPROVR_HPOS), FUNC(smsvdp_set_status), (int)STATUS_SPROVR, smsvdp);
710         }
711         sprite_buffer_count++;
712      }
713   }
714
715   /* Check if display is disabled */
716   if (!(smsvdp->reg[0x01] & 0x40))
717      return;
718
719   if (sprite_buffer_count > 8)
720      sprite_buffer_count = 8;
721
722   memset(smsvdp->collision_buffer, 0, SMS_X_PIXELS);
723   sprite_buffer_count--;
724
725   for (sprite_buffer_index = sprite_buffer_count; sprite_buffer_index >= 0; sprite_buffer_index--)
726   {
727      sprite_index = sprite_buffer[sprite_buffer_index];
728      sprite_y = sprite_table[sprite_index] + 1; /* sprite y position starts at line 1 */
729
730      if (sprite_y > 240)
731         sprite_y -= 256; /* wrap from top if y position is > 240 */
732
733      sprite_x = sprite_table[0x80 + (sprite_index << 1)];
734
735      if (smsvdp->reg[0x00] & 0x08)
736         sprite_x -= 0x08;    /* sprite shift */
737
738      sprite_tile_selected = sprite_table[0x81 + (sprite_index << 1)];
739
740      if (smsvdp->reg[0x06] & 0x04)
741         sprite_tile_selected += 256; /* pattern table select */
742
743      if (smsvdp->reg[0x01] & 0x02)
744         sprite_tile_selected &= 0x01fe; /* force even index */
745
746      sprite_line = (line - sprite_y) / sprite_zoom;
747
748      if (sprite_line > 0x07)
749         sprite_tile_selected += 1;
750
751      bit_plane_0 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x00);
752      bit_plane_1 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x01);
753      bit_plane_2 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x02);
754      bit_plane_3 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x03);
755
756      sprite_col_occurred = 0;
757      sprite_col_x = 0;
758
759      for (pixel_x = 0; pixel_x < 8 ; pixel_x++)
760      {
761         UINT8 pen_bit_0, pen_bit_1, pen_bit_2, pen_bit_3;
762         int pen_selected;
763
764         pen_bit_0 = (bit_plane_0 >> (7 - pixel_x)) & 0x01;
765         pen_bit_1 = (bit_plane_1 >> (7 - pixel_x)) & 0x01;
766         pen_bit_2 = (bit_plane_2 >> (7 - pixel_x)) & 0x01;
767         pen_bit_3 = (bit_plane_3 >> (7 - pixel_x)) & 0x01;
768
769         pen_selected = (pen_bit_3 << 3 | pen_bit_2 << 2 | pen_bit_1 << 1 | pen_bit_0) | 0x10;
770
771         if (pen_selected == 0x10)      /* Transparent palette so skip draw */
772         {
773            continue;
774         }
775
776         if (smsvdp->reg[0x01] & 0x01)
777         {
778            /* sprite doubling is enabled */
779            pixel_plot_x = sprite_x + (pixel_x << 1);
780
781            /* check to prevent going outside of active display area */
782            if (pixel_plot_x < 0 || pixel_plot_x > 255)
783            {
784               continue;
785            }
786
787            if (!(priority_selected[pixel_plot_x] & PRIORITY_BIT))
788            {
789               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
790               line_buffer[pixel_plot_x + 1] = smsvdp->current_palette[pen_selected];
791            }
792            else
793            {
794               if (priority_selected[pixel_plot_x] == PRIORITY_BIT)
795               {
796                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
797               }
798               if (priority_selected[pixel_plot_x + 1] == PRIORITY_BIT)
799               {
800                  line_buffer[pixel_plot_x + 1] = smsvdp->current_palette[pen_selected];
801               }
802            }
803            if (smsvdp->collision_buffer[pixel_plot_x] != 1)
804            {
805               smsvdp->collision_buffer[pixel_plot_x] = 1;
806            }
807            else
808            {
809               if (!sprite_col_occurred)
810               {
811                  sprite_col_occurred = 1;
812                  sprite_col_x = pixel_plot_x;
813               }
814            }
815            if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
816            {
817               smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
818            }
819            else
820            {
821               if (!sprite_col_occurred)
822               {
823                  sprite_col_occurred = 1;
824                  sprite_col_x = pixel_plot_x;
825               }
826            }
827         }
828         else
829         {
830            pixel_plot_x = sprite_x + pixel_x;
831
832            /* check to prevent going outside of active display area */
833            if (pixel_plot_x < 0 || pixel_plot_x > 255)
834            {
835               continue;
836            }
837
838            if (!(priority_selected[pixel_plot_x] & PRIORITY_BIT))
839            {
840               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
841            }
842            else
843            {
844               if (priority_selected[pixel_plot_x] == PRIORITY_BIT)
845               {
846                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
847               }
848            }
849            if (smsvdp->collision_buffer[pixel_plot_x] != 1)
850            {
851               smsvdp->collision_buffer[pixel_plot_x] = 1;
852            }
853            else
854            {
855               if (!sprite_col_occurred)
856               {
857                  sprite_col_occurred = 1;
858                  sprite_col_x = pixel_plot_x;
859               }
860            }
861         }
862      }
863      if (sprite_col_occurred)
864         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPRCOL_BASEHPOS + sprite_col_x), FUNC(smsvdp_set_status), (int)STATUS_SPRCOL, smsvdp);
865   }
866
867   /* Fill column 0 with overscan color from reg[0x07] */
868   if (smsvdp->reg[0x00] & 0x20)
869   {
870      line_buffer[0] = smsvdp->current_palette[BACKDROP_COLOR];
871      line_buffer[1] = smsvdp->current_palette[BACKDROP_COLOR];
872      line_buffer[2] = smsvdp->current_palette[BACKDROP_COLOR];
873      line_buffer[3] = smsvdp->current_palette[BACKDROP_COLOR];
874      line_buffer[4] = smsvdp->current_palette[BACKDROP_COLOR];
875      line_buffer[5] = smsvdp->current_palette[BACKDROP_COLOR];
876      line_buffer[6] = smsvdp->current_palette[BACKDROP_COLOR];
877      line_buffer[7] = smsvdp->current_palette[BACKDROP_COLOR];
878   }
879}
880
881
882static void sms_refresh_tms9918_sprites( running_machine &machine, smsvdp_t *smsvdp, int *line_buffer, int pixel_plot_y, int line )
883{
884   int pixel_plot_x;
885   int sprite_col_occurred, sprite_col_x;
886   int sprite_height, sprite_buffer_count, sprite_index, sprite_buffer[5], sprite_buffer_index;
887   UINT8 *sprite_table, *sprite_pattern_table;
888
889   /* Draw sprite layer */
890   sprite_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x05] & 0x7f) << 7);
891   sprite_pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x06] & 0x07) << 11);
892   sprite_height = 8;
893
894   if (smsvdp->reg[0x01] & 0x02)                         /* Check if SI is set */
895      sprite_height = sprite_height * 2;
896   if (smsvdp->reg[0x01] & 0x01)                         /* Check if MAG is set */
897      sprite_height = sprite_height * 2;
898
899   sprite_buffer_count = 0;
900   for (sprite_index = 0; (sprite_index < 32 * 4) && (sprite_table[sprite_index] != 0xd0) && (sprite_buffer_count < 5); sprite_index += 4)
901   {
902      int sprite_y = sprite_table[sprite_index] + 1;
903
904      if (sprite_y > 240)
905         sprite_y -= 256;
906
907      if ((line >= sprite_y) && (line < (sprite_y + sprite_height)))
908      {
909         if (sprite_buffer_count < 5)
910         {
911            sprite_buffer[sprite_buffer_count] = sprite_index;
912         }
913         else if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
914         {
915            /* Too many sprites per line */
916            machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPROVR_HPOS), FUNC(smsvdp_set_status), (int)STATUS_SPROVR, smsvdp);
917         }
918         sprite_buffer_count++;
919      }
920   }
921
922   /* Check if display is disabled */
923   if (!(smsvdp->reg[0x01] & 0x40))
924      return;
925
926   if (sprite_buffer_count > 4)
927      sprite_buffer_count = 4;
928
929   memset(smsvdp->collision_buffer, 0, SMS_X_PIXELS);
930   sprite_buffer_count--;
931
932   for (sprite_buffer_index = sprite_buffer_count; sprite_buffer_index >= 0; sprite_buffer_index--)
933   {
934      int pen_selected;
935      int sprite_line, pixel_x, sprite_x, sprite_tile_selected;
936      int sprite_y;
937      UINT8 pattern;
938
939      sprite_index = sprite_buffer[sprite_buffer_index];
940      sprite_y = sprite_table[sprite_index] + 1;
941
942      if (sprite_y > 240)
943         sprite_y -= 256;
944
945      sprite_x = sprite_table[sprite_index + 1];
946      pen_selected = sprite_table[sprite_index + 3] & 0x0f;
947
948      if (IS_GAMEGEAR_VDP)
949         pen_selected |= 0x10;
950
951      if (sprite_table[sprite_index + 3] & 0x80)
952         sprite_x -= 32;
953
954      sprite_tile_selected = sprite_table[sprite_index + 2];
955      sprite_line = line - sprite_y;
956
957      if (smsvdp->reg[0x01] & 0x01)
958         sprite_line >>= 1;
959
960      if (smsvdp->reg[0x01] & 0x02)
961      {
962         sprite_tile_selected &= 0xfc;
963
964         if (sprite_line > 0x07)
965         {
966            sprite_tile_selected += 1;
967            sprite_line -= 8;
968         }
969      }
970
971      pattern = sprite_pattern_table[sprite_tile_selected * 8 + sprite_line];
972
973      sprite_col_occurred = 0;
974      sprite_col_x = 0;
975
976      for (pixel_x = 0; pixel_x < 8; pixel_x++)
977      {
978         if (smsvdp->reg[0x01] & 0x01)
979         {
980            pixel_plot_x = sprite_x + pixel_x * 2;
981            if (pixel_plot_x < 0 || pixel_plot_x > 255)
982            {
983               continue;
984            }
985
986            if (pen_selected && (pattern & (1 << (7 - pixel_x))))
987            {
988               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
989
990               if (smsvdp->collision_buffer[pixel_plot_x] != 1)
991               {
992                  smsvdp->collision_buffer[pixel_plot_x] = 1;
993               }
994               else
995               {
996                  if (!sprite_col_occurred)
997                  {
998                     sprite_col_occurred = 1;
999                     sprite_col_x = pixel_plot_x;
1000                  }
1001               }
1002
1003               line_buffer[pixel_plot_x+1] = smsvdp->current_palette[pen_selected];
1004
1005               if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
1006               {
1007                  smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
1008               }
1009               else
1010               {
1011                  if (!sprite_col_occurred)
1012                  {
1013                     sprite_col_occurred = 1;
1014                     sprite_col_x = pixel_plot_x;
1015                  }
1016               }
1017            }
1018         }
1019         else
1020         {
1021            pixel_plot_x = sprite_x + pixel_x;
1022
1023            if (pixel_plot_x < 0 || pixel_plot_x > 255)
1024            {
1025               continue;
1026            }
1027
1028            if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1029            {
1030               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1031
1032               if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1033               {
1034                  smsvdp->collision_buffer[pixel_plot_x] = 1;
1035               }
1036               else
1037               {
1038                  if (!sprite_col_occurred)
1039                  {
1040                     sprite_col_occurred = 1;
1041                     sprite_col_x = pixel_plot_x;
1042                  }
1043               }
1044            }
1045         }
1046      }
1047
1048      if (smsvdp->reg[0x01] & 0x02)
1049      {
1050         sprite_tile_selected += 2;
1051         pattern = sprite_pattern_table[sprite_tile_selected * 8 + sprite_line];
1052         sprite_x += (smsvdp->reg[0x01] & 0x01 ? 16 : 8);
1053
1054         for (pixel_x = 0; pixel_x < 8; pixel_x++)
1055         {
1056            if (smsvdp->reg[0x01] & 0x01)
1057            {
1058               pixel_plot_x = sprite_x + pixel_x * 2;
1059
1060               if (pixel_plot_x < 0 || pixel_plot_x > 255)
1061               {
1062                  continue;
1063               }
1064
1065               if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1066               {
1067                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1068
1069                  if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1070                  {
1071                     smsvdp->collision_buffer[pixel_plot_x] = 1;
1072                  }
1073                  else
1074                  {
1075                     if (!sprite_col_occurred)
1076                     {
1077                        sprite_col_occurred = 1;
1078                        sprite_col_x = pixel_plot_x;
1079                     }
1080                  }
1081
1082                  line_buffer[pixel_plot_x+1] = smsvdp->current_palette[pen_selected];
1083
1084                  if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
1085                  {
1086                     smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
1087                  }
1088                  else
1089                  {
1090                     if (!sprite_col_occurred)
1091                     {
1092                        sprite_col_occurred = 1;
1093                        sprite_col_x = pixel_plot_x;
1094                     }
1095                  }
1096               }
1097            }
1098            else
1099            {
1100               pixel_plot_x = sprite_x + pixel_x;
1101
1102               if (pixel_plot_x < 0 || pixel_plot_x > 255)
1103               {
1104                  continue;
1105               }
1106
1107               if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1108               {
1109                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1110
1111                  if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1112                  {
1113                     smsvdp->collision_buffer[pixel_plot_x] = 1;
1114                  }
1115                  else
1116                  {
1117                     if (!sprite_col_occurred)
1118                     {
1119                        sprite_col_occurred = 1;
1120                        sprite_col_x = pixel_plot_x;
1121                     }
1122                  }
1123               }
1124            }
1125         }
1126      }
1127      if (sprite_col_occurred)
1128         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPRCOL_BASEHPOS + sprite_col_x), FUNC(smsvdp_set_status), (int)STATUS_SPRCOL, smsvdp);
1129   }
1130}
1131
1132
1133static void sms_refresh_line_mode2( smsvdp_t *smsvdp, int *line_buffer, int line )
1134{
1135   int tile_column;
1136   int pixel_x, pixel_plot_x;
1137   UINT8 *name_table, *color_table, *pattern_table;
1138   int pattern_mask, color_mask, pattern_offset;
1139
1140   /* Draw background layer */
1141   name_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x02] & 0x0f) << 10) + ((line >> 3) * 32);
1142   color_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x03] & 0x80) << 6);
1143   color_mask = ((smsvdp->reg[0x03] & 0x7f) << 3) | 0x07;
1144   pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x04] & 0x04) << 11);
1145   pattern_mask = ((smsvdp->reg[0x04] & 0x03) << 8) | 0xff;
1146   pattern_offset = (line & 0xc0) << 2;
1147
1148   for (tile_column = 0; tile_column < 32; tile_column++)
1149   {
1150      UINT8 pattern;
1151      UINT8 colors;
1152
1153      pattern = pattern_table[(((pattern_offset + name_table[tile_column]) & pattern_mask) * 8) + (line & 0x07)];
1154      colors = color_table[(((pattern_offset + name_table[tile_column]) & color_mask) * 8) + (line & 0x07)];
1155
1156      for (pixel_x = 0; pixel_x < 8; pixel_x++)
1157      {
1158         UINT8 pen_selected;
1159
1160         if (pattern & (1 << (7 - pixel_x)))
1161         {
1162            pen_selected = colors >> 4;
1163         }
1164         else
1165         {
1166            pen_selected = colors & 0x0f;
1167         }
1168
1169         if (!pen_selected)
1170            pen_selected = BACKDROP_COLOR;
1171
1172         pixel_plot_x = (tile_column << 3) + pixel_x;
1173
1174         if (IS_GAMEGEAR_VDP)
1175            pen_selected |= 0x10;
1176
1177         line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1178      }
1179   }
1180}
1181
1182
1183static void sms_refresh_line_mode0( smsvdp_t *smsvdp, int *line_buffer, int line)
1184{
1185   int tile_column;
1186   int pixel_x, pixel_plot_x;
1187   UINT8 *name_table, *color_table, *pattern_table;
1188
1189   /* Draw background layer */
1190   name_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x02] & 0x0f) << 10) + ((line >> 3) * 32);
1191   color_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x03] << 6) & (VRAM_SIZE - 1));
1192   pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x04] << 11) & (VRAM_SIZE - 1));
1193
1194   for (tile_column = 0; tile_column < 32; tile_column++)
1195   {
1196      UINT8 pattern;
1197      UINT8 colors;
1198
1199      pattern = pattern_table[(name_table[tile_column] * 8) + (line & 0x07)];
1200      colors = color_table[name_table[tile_column] >> 3];
1201
1202      for (pixel_x = 0; pixel_x < 8; pixel_x++)
1203      {
1204         int pen_selected;
1205
1206         if (pattern & (1 << (7 - pixel_x)))
1207            pen_selected = colors >> 4;
1208         else
1209            pen_selected = colors & 0x0f;
1210
1211         if (IS_GAMEGEAR_VDP)
1212            pen_selected |= 0x10;
1213
1214         pixel_plot_x = (tile_column << 3) + pixel_x;
1215         line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1216      }
1217   }
1218}
1219
1220
1221static void sms_refresh_line( running_machine &machine, smsvdp_t *smsvdp, bitmap_t *bitmap, int pixel_offset_x, int pixel_plot_y, int line )
1222{
1223   int x;
1224   int *blitline_buffer = smsvdp->line_buffer;
1225   int priority_selected[256];
1226
1227   switch( smsvdp->vdp_mode )
1228   {
1229   case 0:
1230      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1231         sms_refresh_line_mode0(smsvdp, blitline_buffer, line);
1232      sms_refresh_tms9918_sprites(machine, smsvdp, blitline_buffer, pixel_plot_y, line);
1233      break;
1234
1235   case 2:
1236      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1237         sms_refresh_line_mode2(smsvdp, blitline_buffer, line);
1238      sms_refresh_tms9918_sprites(machine, smsvdp, blitline_buffer, pixel_plot_y, line);
1239      break;
1240
1241   case 4:
1242   default:
1243      memset(priority_selected, 0, sizeof(priority_selected));
1244      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1245         sms_refresh_line_mode4(smsvdp, blitline_buffer, priority_selected, line);
1246      sms_refresh_mode4_sprites(machine, smsvdp, blitline_buffer, priority_selected, pixel_plot_y, line);
1247      break;
1248   }
1249
1250   /* Check if display is disabled or we're below/above active area */
1251   if (!(smsvdp->reg[0x01] & 0x40) || line < 0 || line >= smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1252   {
1253      for (x = 0; x < 256; x++)
1254      {
1255         blitline_buffer[x] = smsvdp->current_palette[BACKDROP_COLOR];
1256      }
1257   }
1258
1259   if (IS_GAMEGEAR_VDP && smsvdp->gg_sms_mode)
1260   {
1261      int *combineline_buffer = smsvdp->line_buffer + ((line & 0x03) + 1) * 256;
1262      int plot_x = 48;
1263
1264      /* Do horizontal scaling */
1265      for (x = 8; x < 248;)
1266      {
1267         int combined;
1268
1269         /* Take red and green from first pixel, and blue from second pixel */
1270         combined = (blitline_buffer[x] & 0x00ff) | (blitline_buffer[x + 1] & 0x0f00);
1271         combineline_buffer[plot_x] = combined;
1272
1273         /* Take red from second pixel, and green and blue from third pixel */
1274         combined = (blitline_buffer[x + 1] & 0x000f) | (blitline_buffer[x + 2] & 0x0ff0);
1275         combineline_buffer[plot_x + 1] = combined;
1276         x += 3;
1277         plot_x += 2;
1278      }
1279
1280      /* Do vertical scaling for a screen with 192 or 224 lines
1281           Lines 0-2 and 221-223 have no effect on the output on the GG screen.
1282           We will calculate the gamegear lines as follows:
1283           GG_0 = 1/6 * SMS_3 + 1/3 * SMS_4 + 1/3 * SMS_5 + 1/6 * SMS_6
1284           GG_1 = 1/6 * SMS_4 + 1/3 * SMS_5 + 1/3 * SMS_6 + 1/6 * SMS_7
1285           GG_2 = 1/6 * SMS_6 + 1/3 * SMS_7 + 1/3 * SMS_8 + 1/6 * SMS_9
1286           GG_3 = 1/6 * SMS_7 + 1/3 * SMS_8 + 1/3 * SMS_9 + 1/6 * SMS_10
1287           GG_4 = 1/6 * SMS_9 + 1/3 * SMS_10 + 1/3 * SMS_11 + 1/6 * SMS_12
1288           .....
1289           GG_142 = 1/6 * SMS_216 + 1/3 * SMS_217 + 1/3 * SMS_218 + 1/6 * SMS_219
1290           GG_143 = 1/6 * SMS_217 + 1/3 * SMS_218 + 1/3 * SMS_219 + 1/6 * SMS_220
1291        */
1292      {
1293         int gg_line;
1294         int my_line = pixel_plot_y + line - (TBORDER_START + NTSC_224_TBORDER_Y_PIXELS);
1295         int *line1, *line2, *line3, *line4;
1296
1297         /* First make sure there's enough data to draw anything */
1298         /* We need one more line of data if we're on line 8, 11, 14, 17, etc */
1299         if (my_line < 6 || my_line > 220 || ((my_line - 8) % 3 == 0))
1300         {
1301            return;
1302         }
1303
1304         gg_line = ((my_line - 6) / 3) * 2;
1305
1306         /* If we're on SMS line 7, 10, 13, etc we're on an odd GG line */
1307         if (my_line % 3)
1308         {
1309            gg_line++;
1310         }
1311
1312         /* Calculate the line we will be drawing on */
1313         pixel_plot_y = TBORDER_START + NTSC_192_TBORDER_Y_PIXELS + 24 + gg_line;
1314
1315         /* Setup our source lines */
1316         line1 = smsvdp->line_buffer + (((my_line - 3) & 0x03) + 1) * 256;
1317         line2 = smsvdp->line_buffer + (((my_line - 2) & 0x03) + 1) * 256;
1318         line3 = smsvdp->line_buffer + (((my_line - 1) & 0x03) + 1) * 256;
1319         line4 = smsvdp->line_buffer + (((my_line - 0) & 0x03) + 1) * 256;
1320
1321         for (x = 0 + 48; x < 160 + 48; x++)
1322         {
1323            rgb_t   c1 = machine.pens[line1[x]];
1324            rgb_t   c2 = machine.pens[line2[x]];
1325            rgb_t   c3 = machine.pens[line3[x]];
1326            rgb_t   c4 = machine.pens[line4[x]];
1327            *BITMAP_ADDR32(bitmap, pixel_plot_y, pixel_offset_x + x) =
1328               MAKE_RGB((RGB_RED(c1) / 6 + RGB_RED(c2) / 3 + RGB_RED(c3) / 3 + RGB_RED(c4) / 6 ),
1329                  (RGB_GREEN(c1) / 6 + RGB_GREEN(c2) / 3 + RGB_GREEN(c3) / 3 + RGB_GREEN(c4) / 6 ),
1330                  (RGB_BLUE(c1) / 6 + RGB_BLUE(c2) / 3 + RGB_BLUE(c3) / 3 + RGB_BLUE(c4) / 6 ) );
1331         }
1332         return;
1333      }
1334      blitline_buffer = combineline_buffer;
1335   }
1336
1337   for (x = 0; x < 256; x++)
1338   {
1339      *BITMAP_ADDR32(bitmap, pixel_plot_y + line, pixel_offset_x + x) = machine.pens[blitline_buffer[x]];
1340   }
1341}
1342
1343
1344// This is only used by Light Phaser. Should it be moved elsewhere?
1345int sms_vdp_check_brightness(device_t *device, int x, int y)
1346{
1347   /* brightness of the lightgray color in the frame drawn by Light Phaser games */
1348   const UINT8 sensor_min_brightness = 0x7f;
1349
1350   /* TODO: Check how Light Phaser behaves for border areas. For Gangster Town, should */
1351   /* a shot at right border (HC~=0x90) really appear at active scr, near to left border? */
1352   if (x < LBORDER_START + LBORDER_X_PIXELS || x >= LBORDER_START + LBORDER_X_PIXELS + 256)
1353      return 0;
1354
1355   smsvdp_t *smsvdp = get_safe_token(device);
1356   rgb_t color = *BITMAP_ADDR32(smsvdp->tmpbitmap, y, x);
1357
1358   /* reference: http://www.w3.org/TR/AERT#color-contrast */
1359   UINT8 brightness = (RGB_RED(color) * 0.299) + (RGB_GREEN(color) * 0.587) + (RGB_BLUE(color) * 0.114);
1360   //printf ("color brightness: %2X for x %d y %d\n", brightness, x, y);
1361
1362   return (brightness >= sensor_min_brightness) ? 1 : 0;
1363}
1364
1365
1366static void sms_update_palette( smsvdp_t *smsvdp )
1367{
1368   int i;
1369
1370   /* Exit if palette is has no changes */
1371   if (smsvdp->cram_dirty == 0)
1372   {
1373      return;
1374   }
1375   smsvdp->cram_dirty = 0;
1376
1377   if (smsvdp->vdp_mode != 4 && ! IS_GAMEGEAR_VDP)
1378   {
1379      for(i = 0; i < 16; i++)
1380      {
1381         smsvdp->current_palette[i] = 64 + i;
1382      }
1383      return;
1384   }
1385
1386   if (IS_GAMEGEAR_VDP)
1387   {
1388      if (smsvdp->gg_sms_mode)
1389      {
1390         for (i = 0; i < 32; i++)
1391         {
1392            smsvdp->current_palette[i] = ((smsvdp->CRAM->u8(i) & 0x30) << 6) | ((smsvdp->CRAM->u8(i) & 0x0c ) << 4) | ((smsvdp->CRAM->u8(i) & 0x03) << 2);
1393         }
1394      }
1395      else
1396      {
1397         for (i = 0; i < 32; i++)
1398         {
1399            smsvdp->current_palette[i] = ((smsvdp->CRAM->u8(i * 2 + 1) << 8) | smsvdp->CRAM->u8(i * 2)) & 0x0fff;
1400         }
1401      }
1402   }
1403   else
1404   {
1405      for (i = 0; i < 32; i++)
1406      {
1407         smsvdp->current_palette[i] = smsvdp->CRAM->u8(i) & 0x3f;
1408      }
1409   }
1410}
1411
1412
1413UINT32 sms_vdp_update( device_t *device, bitmap_t *bitmap, const rectangle *cliprect )
1414{
1415   smsvdp_t *smsvdp = get_safe_token(device);
1416   copybitmap(bitmap, smsvdp->tmpbitmap, 0, 0, 0, 0, cliprect);
1417   return 0;
1418}
1419
1420
1421/*****************************************************************************
1422    DEVICE INTERFACE
1423*****************************************************************************/
1424
1425static DEVICE_START( smsvdp )
1426{
1427   smsvdp_t *smsvdp = get_safe_token(device);
1428   const smsvdp_interface *intf = get_interface(device);
1429
1430   screen_device *screen = device->machine().first_screen();
1431   int width = screen->width();
1432   int height = screen->height();
1433
1434   smsvdp->features = intf->model;
1435   smsvdp->int_callback = intf->int_callback;
1436   smsvdp->pause_callback = intf->pause_callback;
1437
1438   /* Allocate video RAM */
1439   smsvdp->VRAM = device->machine().region_alloc("vdp_vram", VRAM_SIZE, 1, ENDIANNESS_LITTLE);
1440   smsvdp->CRAM = device->machine().region_alloc("vdp_cram", MAX_CRAM_SIZE, 1, ENDIANNESS_LITTLE);
1441   smsvdp->line_buffer = auto_alloc_array(device->machine(), int, 256 * 5);
1442
1443   smsvdp->collision_buffer = auto_alloc_array(device->machine(), UINT8, SMS_X_PIXELS);
1444   smsvdp->sms_frame_timing = auto_alloc_array(device->machine(), UINT8, 7);
1445
1446   /* Make temp bitmap for rendering */
1447   smsvdp->tmpbitmap = auto_bitmap_alloc(device->machine(), width, height, BITMAP_FORMAT_INDEXED32);
1448
1449   smsvdp->smsvdp_display_timer = device->machine().scheduler().timer_alloc(FUNC(smsvdp_display_callback), smsvdp);
1450   smsvdp->smsvdp_display_timer->adjust(screen->time_until_pos(0, DISPLAY_CB_HPOS), 0, screen->scan_period());
1451
1452   device->save_item(NAME(smsvdp->status));
1453   device->save_item(NAME(smsvdp->reg9copy));
1454   device->save_item(NAME(smsvdp->addrmode));
1455   device->save_item(NAME(smsvdp->addr));
1456   device->save_item(NAME(smsvdp->cram_mask));
1457   device->save_item(NAME(smsvdp->cram_dirty));
1458   device->save_item(NAME(smsvdp->pending));
1459   device->save_item(NAME(smsvdp->buffer));
1460   device->save_item(NAME(smsvdp->gg_sms_mode));
1461   device->save_item(NAME(smsvdp->irq_state));
1462   device->save_item(NAME(smsvdp->vdp_mode));
1463   device->save_item(NAME(smsvdp->y_pixels));
1464   device->save_item(NAME(smsvdp->line_counter));
1465   device->save_item(NAME(smsvdp->hcounter));
1466   device->save_item(NAME(smsvdp->reg));
1467   device->save_item(NAME(smsvdp->current_palette));
1468   device->save_pointer(NAME(smsvdp->line_buffer), 256 * 5);
1469   device->save_pointer(NAME(smsvdp->collision_buffer), SMS_X_PIXELS);
1470   device->save_item(NAME(*smsvdp->tmpbitmap));
1471}
1472
1473static DEVICE_RESET( smsvdp )
1474{
1475   smsvdp_t *smsvdp = get_safe_token(device);
1476   int i;
1477
1478   /* Most register are 0x00 at power-up */
1479   for (i = 0; i < NUM_OF_REGISTER; i++)
1480      smsvdp->reg[i] = 0x00;
1481
1482   smsvdp->reg[0x02] = 0x0e;
1483   smsvdp->reg[0x0a] = 0xff;
1484
1485   smsvdp->status = 0;
1486   smsvdp->reg9copy = 0;
1487   smsvdp->addrmode = 0;
1488   smsvdp->addr = 0;
1489   smsvdp->gg_sms_mode = 0;
1490   smsvdp->cram_mask = (IS_GAMEGEAR_VDP && !smsvdp->gg_sms_mode) ? (GG_CRAM_SIZE - 1) : (SMS_CRAM_SIZE - 1);
1491   smsvdp->cram_dirty = 1;
1492   smsvdp->pending = 0;
1493   smsvdp->buffer = 0;
1494   smsvdp->irq_state = 0;
1495   smsvdp->line_counter = 0;
1496   smsvdp->hcounter = 0;
1497
1498   for (i = 0; i < 0x20; i++)
1499      smsvdp->current_palette[i] = 0;
1500
1501   set_display_settings(device);
1502
1503   /* Clear RAM */
1504   memset(smsvdp->VRAM->base(), 0, VRAM_SIZE);
1505   memset(smsvdp->CRAM->base(), 0, MAX_CRAM_SIZE);
1506   memset(smsvdp->line_buffer, 0, 256 * 5 * sizeof(int));
1507}
1508
1509DEVICE_GET_INFO( smsvdp )
1510{
1511   switch (state)
1512   {
1513      /* --- the following bits of info are returned as 64-bit signed integers --- */
1514      case DEVINFO_INT_TOKEN_BYTES:         info->i = sizeof(smsvdp_t);               break;
1515
1516      /* --- the following bits of info are returned as pointers to data or functions --- */
1517      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(smsvdp);      break;
1518      case DEVINFO_FCT_STOP:               /* Nothing */                           break;
1519      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(smsvdp);      break;
1520
1521      /* --- the following bits of info are returned as NULL-terminated strings --- */
1522      case DEVINFO_STR_NAME:               strcpy(info->s, "Sega Master SYstem / Game Gear VDP");            break;
1523      case DEVINFO_STR_FAMILY:            strcpy(info->s, "Sega MS VDP");               break;
1524      case DEVINFO_STR_VERSION:            strcpy(info->s, "1.0");                     break;
1525      case DEVINFO_STR_SOURCE_FILE:         strcpy(info->s, __FILE__);                  break;
1526      case DEVINFO_STR_CREDITS:            strcpy(info->s, "Copyright MAME / MESS Team");         break;
1527   }
1528}
1529
1530DEFINE_LEGACY_DEVICE(SMSVDP, smsvdp);
src/mame/video/smsvdp.h
r0r11451
1/*************************************************************************
2
3    smsvdp.h
4
5    Implementation of Sega VDP chip used in Master System and Game Gear
6
7**************************************************************************/
8
9#ifndef __SMSVDP_H__
10#define __SMSVDP_H__
11
12#include "devcb.h"
13
14
15/***************************************************************************
16    CONSTANTS
17***************************************************************************/
18
19
20#define MODEL_315_5124         0x0001
21#define MODEL_315_5246         0x0002
22#define MODEL_315_5378         0x0004
23
24#define SMS_X_PIXELS         342      /* 342 pixels */
25#define NTSC_Y_PIXELS         262      /* 262 lines */
26#define PAL_Y_PIXELS         313      /* 313 lines */
27#define LBORDER_START         (1 + 2 + 14 + 8)
28#define LBORDER_X_PIXELS      (0x0d)      /* 13 pixels */
29#define RBORDER_X_PIXELS      (0x0f)      /* 15 pixels */
30#define TBORDER_START         (3 + 13)
31#define NTSC_192_TBORDER_Y_PIXELS   (0x1b)      /* 27 lines */
32#define NTSC_192_BBORDER_Y_PIXELS   (0x18)      /* 24 lines */
33#define NTSC_224_TBORDER_Y_PIXELS   (0x0b)      /* 11 lines */
34#define NTSC_224_BBORDER_Y_PIXELS   (0x08)      /* 8 lines */
35#define PAL_192_TBORDER_Y_PIXELS   (0x36)      /* 54 lines */
36#define PAL_192_BBORDER_Y_PIXELS   (0x30)      /* 48 lines */
37#define PAL_224_TBORDER_Y_PIXELS   (0x26)      /* 38 lines */
38#define PAL_224_BBORDER_Y_PIXELS   (0x20)      /* 32 lines */
39#define PAL_240_TBORDER_Y_PIXELS   (0x1e)      /* 30 lines */
40#define PAL_240_BBORDER_Y_PIXELS   (0x18)      /* 24 lines */
41
42
43/***************************************************************************
44    TYPE DEFINITIONS
45***************************************************************************/
46
47typedef void (*smsvdp_int_cb)( running_machine &machine, int state );
48typedef void (*smsvdp_pause_cb)( running_machine &machine );
49
50typedef struct _smsvdp_interface smsvdp_interface;
51struct _smsvdp_interface
52{
53   UINT32             model;                /* Select model/features for the emulation */
54   smsvdp_int_cb      int_callback;         /* Interrupt callback function */
55   smsvdp_pause_cb    pause_callback;       /* Pause callback function */
56};
57
58/***************************************************************************
59    DEVICE CONFIGURATION MACROS
60***************************************************************************/
61
62DECLARE_LEGACY_DEVICE(SMSVDP, smsvdp);
63
64#define MCFG_SMSVDP_ADD(_tag, _interface) \
65   MCFG_DEVICE_ADD(_tag, SMSVDP, 0) \
66   MCFG_DEVICE_CONFIG(_interface)
67
68
69/***************************************************************************
70    DEVICE I/O FUNCTIONS
71***************************************************************************/
72
73/* prototypes */
74
75UINT32 sms_vdp_update( device_t *device, bitmap_t *bitmap, const rectangle *cliprect );
76READ8_DEVICE_HANDLER( sms_vdp_vcount_r );
77READ8_DEVICE_HANDLER( sms_vdp_hcount_latch_r );
78WRITE8_DEVICE_HANDLER( sms_vdp_hcount_latch_w );
79READ8_DEVICE_HANDLER( sms_vdp_data_r );
80WRITE8_DEVICE_HANDLER( sms_vdp_data_w );
81READ8_DEVICE_HANDLER( sms_vdp_ctrl_r );
82WRITE8_DEVICE_HANDLER( sms_vdp_ctrl_w );
83void sms_vdp_set_ggsmsmode( device_t *device, int mode );
84int sms_vdp_check_brightness( device_t *device, int x, int y );
85
86#endif /* __SMSVDP_H__ */
src/mame/formats/basicdsk.c
r0r11451
1/*********************************************************************
2
3    formats/basicdsk.c
4
5    Floppy format code for basic disks
6
7*********************************************************************/
8
9#include <stdlib.h>
10#include <string.h>
11#include <assert.h>
12
13#include "basicdsk.h"
14
15static floperr_t basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen);
16static floperr_t basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam);
17static floperr_t basicdsk_read_indexed_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen);
18static floperr_t basicdsk_write_indexed_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam);
19static floperr_t basicdsk_get_sector_length(floppy_image *floppy, int head, int track, int sector, UINT32 *sector_length);
20static floperr_t basicdsk_get_indexed_sector_info(floppy_image *floppy, int head, int track, int sector_index, int *cylinder, int *side, int *sector, UINT32 *sector_length, unsigned long *flags);
21static int basicdsk_get_heads_per_disk(floppy_image *floppy);
22static int basicdsk_get_tracks_per_disk(floppy_image *floppy);
23static floperr_t basicdsk_format_track(floppy_image *floppy, int head, int track, option_resolution *params);
24
25
26
27#define BASICDSK_TAG   "basicdsktag"
28
29struct basicdsk_tag
30{
31   struct basicdsk_geometry geometry;
32};
33
34
35
36/********************************************************************/
37
38static const struct basicdsk_geometry *get_geometry(floppy_image *floppy)
39{
40   const struct basicdsk_tag *tag;
41   tag = (const basicdsk_tag *)floppy_tag(floppy);
42   return &tag->geometry;
43}
44
45
46
47floperr_t basicdsk_construct(floppy_image *floppy, const struct basicdsk_geometry *geometry)
48{
49   struct basicdsk_tag *tag;
50   struct FloppyCallbacks *format;
51
52   assert(geometry->heads);
53   assert(geometry->tracks);
54   assert(geometry->sectors);
55
56   tag = (struct basicdsk_tag *) floppy_create_tag(floppy, sizeof(struct basicdsk_tag));
57   if (!tag)
58      return FLOPPY_ERROR_OUTOFMEMORY;
59   tag->geometry = *geometry;
60
61   /* set up format callbacks */
62   format = floppy_callbacks(floppy);
63   format->read_sector = basicdsk_read_sector;
64   format->write_sector = basicdsk_write_sector;
65   format->read_indexed_sector = basicdsk_read_indexed_sector;
66   format->write_indexed_sector = basicdsk_write_indexed_sector;
67   format->get_sector_length = basicdsk_get_sector_length;
68   format->get_heads_per_disk = basicdsk_get_heads_per_disk;
69   format->get_tracks_per_disk = basicdsk_get_tracks_per_disk;
70   format->get_indexed_sector_info = basicdsk_get_indexed_sector_info;
71   format->format_track = basicdsk_format_track;
72
73   return FLOPPY_ERROR_SUCCESS;
74}
75
76
77
78static floperr_t get_offset(floppy_image *floppy, int head, int track, int sector, int sector_is_index, UINT64 *offset)
79{
80   const struct basicdsk_geometry *geom;
81   UINT64 offs;
82
83   geom = get_geometry(floppy);
84
85   /* translate the sector to a raw sector */
86   if (!sector_is_index)
87   {
88      sector -= geom->first_sector_id;
89   }
90
91   if (geom->translate_sector)
92      sector = geom->translate_sector(floppy, sector);
93
94   /* check to see if we are out of range */
95   if ((head < 0) || (head >= geom->heads) || (track < 0) || (track >= geom->tracks)
96         || (sector < 0) || (sector >= geom->sectors))
97      return FLOPPY_ERROR_SEEKERROR;
98
99   if (geom->translate_offset)
100      offs = geom->translate_offset(floppy, geom, track, head, sector);
101   else
102   {
103      offs = 0;
104      offs += track;
105      offs *= geom->heads;
106      offs += head;
107      offs *= geom->sectors;
108      offs += sector;
109   }
110   offs *= geom->sector_length;
111   offs += geom->offset;
112
113   if (offset)
114      *offset = offs;
115   return FLOPPY_ERROR_SUCCESS;
116}
117
118
119
120static int internal_basicdsk_translate_sector_interleave(floppy_image *floppy, int sector)
121{
122   const struct basicdsk_geometry *geom = get_geometry(floppy);
123   if (sector >= geom->sectors)
124      return sector;
125   return geom->sector_map[sector];
126}
127
128
129
130static floperr_t internal_basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, int sector_is_index, void *buffer, size_t buflen)
131{
132   UINT64 offset;
133   floperr_t err;
134
135   err = get_offset(floppy, head, track, sector, sector_is_index, &offset);
136   if (err)
137      return err;
138   floppy_image_read(floppy, buffer, offset, buflen);
139   return FLOPPY_ERROR_SUCCESS;
140}
141
142
143
144static floperr_t internal_basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, int sector_is_index, const void *buffer, size_t buflen, int ddam)
145{
146   UINT64 offset;
147   floperr_t err;
148
149   err = get_offset(floppy, head, track, sector, sector_is_index, &offset);
150   if (err)
151      return err;
152
153   floppy_image_write(floppy, buffer, offset, buflen);
154   return FLOPPY_ERROR_SUCCESS;
155}
156
157
158
159static floperr_t basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen)
160{
161   return internal_basicdsk_read_sector(floppy, head, track, sector, FALSE, buffer, buflen);
162}
163
164static floperr_t basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam)
165{
166   return internal_basicdsk_write_sector(floppy, head, track, sector, FALSE, buffer, buflen, ddam);
167}
168
169static floperr_t basicdsk_read_indexed_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen)
170{
171   return internal_basicdsk_read_sector(floppy, head, track, sector, TRUE, buffer, buflen);
172}
173
174static floperr_t basicdsk_write_indexed_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam)
175{
176   return internal_basicdsk_write_sector(floppy, head, track, sector, TRUE, buffer, buflen, ddam);
177}
178
179
180
181static floperr_t basicdsk_format_track(floppy_image *floppy, int head, int track, option_resolution *params)
182{
183   floperr_t err = FLOPPY_ERROR_SUCCESS;
184   UINT8 local_buffer[512];
185   void *alloc_buffer = NULL;
186   void *buffer;
187   UINT32 sector_length;
188   int sector;
189   const struct basicdsk_geometry *geometry;
190
191   geometry = get_geometry(floppy);
192
193   sector_length = geometry->sector_length;
194
195   if (sector_length > sizeof(local_buffer))
196   {
197      alloc_buffer = malloc(sector_length);
198      if (!alloc_buffer)
199      {
200         err = FLOPPY_ERROR_OUTOFMEMORY;
201         goto done;
202      }
203      buffer = alloc_buffer;
204   }
205   else
206   {
207      alloc_buffer = NULL;
208      buffer = local_buffer;
209   }
210
211   memset(buffer, floppy_get_filler(floppy), sector_length);
212
213   for (sector = 0; sector < geometry->sectors; sector++)
214   {
215      err = basicdsk_write_sector(floppy, head, track, sector + geometry->first_sector_id, buffer, sector_length, 0);
216      if (err)
217         goto done;
218   }
219
220done:
221   if (alloc_buffer)
222      free(alloc_buffer);
223   return err;
224}
225
226
227
228static int basicdsk_get_heads_per_disk(floppy_image *floppy)
229{
230   return get_geometry(floppy)->heads;
231}
232
233
234
235static int basicdsk_get_tracks_per_disk(floppy_image *floppy)
236{
237   return get_geometry(floppy)->tracks;
238}
239
240
241
242static floperr_t basicdsk_get_sector_length(floppy_image *floppy, int head, int track, int sector, UINT32 *sector_length)
243{
244   floperr_t err;
245
246   err = get_offset(floppy, head, track, sector, FALSE, NULL);
247   if (err)
248      return err;
249
250   if (sector_length)
251      *sector_length = get_geometry(floppy)->sector_length;
252   return FLOPPY_ERROR_SUCCESS;
253}
254
255
256
257static floperr_t basicdsk_get_indexed_sector_info(floppy_image *floppy, int head, int track, int sector_index, int *cylinder, int *side, int *sector, UINT32 *sector_length, unsigned long *flags)
258{
259   const struct basicdsk_geometry *geom = get_geometry(floppy);
260
261   if (geom->translate_sector)
262      sector_index = geom->translate_sector(floppy, sector_index);
263
264   sector_index += geom->first_sector_id;
265
266   if (cylinder)
267      *cylinder = track;
268   if (side)
269      *side = head;
270   if (sector)
271      *sector = sector_index;
272   if (flags) {
273      /* TODO: read DAM or DDAM and determine flags */
274      *flags = 0;
275      if (geom->get_ddam)
276         *flags = geom->get_ddam(floppy, geom, track, head, sector_index);
277   }
278   return basicdsk_get_sector_length(floppy, head, track, sector_index, sector_length);
279}
280
281
282
283/********************************************************************
284 * Generic Basicdsk Constructors
285 ********************************************************************/
286
287static void basicdsk_default_geometry(const struct FloppyFormat *format, struct basicdsk_geometry *geometry)
288{
289   optreserr_t err;
290   int sector_length;
291   memset(geometry, 0, sizeof(*geometry));
292
293   err = option_resolution_getdefault(format->param_guidelines, PARAM_HEADS,         &geometry->heads);
294   assert(!err);
295   err = option_resolution_getdefault(format->param_guidelines, PARAM_TRACKS,         &geometry->tracks);
296   assert(!err);
297   err = option_resolution_getdefault(format->param_guidelines, PARAM_SECTORS,         &geometry->sectors);
298   assert(!err);
299   err = option_resolution_getdefault(format->param_guidelines, PARAM_FIRST_SECTOR_ID,   &geometry->first_sector_id);
300   assert(!err);
301   err = option_resolution_getdefault(format->param_guidelines, PARAM_INTERLEAVE,      &geometry->interleave);
302   if (err!=0) {
303      geometry->interleave = 1;
304   }
305   err = option_resolution_getdefault(format->param_guidelines, PARAM_SECTOR_LENGTH,   &sector_length);
306   assert(!err);
307   geometry->sector_length = sector_length;
308
309   if (geometry->interleave > 1)
310   {
311      int sector = 0;
312
313      for (int i = 0; i < geometry->sectors; i++)
314      {
315         geometry->sector_map[i] = sector;
316
317         sector += geometry->interleave;
318
319         if (sector >= geometry->sectors)
320            sector -= geometry->sectors;
321      }
322
323      geometry->translate_sector = internal_basicdsk_translate_sector_interleave;
324   }
325}
326
327
328
329FLOPPY_CONSTRUCT(basicdsk_construct_default)
330{
331   struct basicdsk_geometry geometry;
332   basicdsk_default_geometry(format, &geometry);
333   return basicdsk_construct(floppy, &geometry);
334}
335
336
337
338FLOPPY_IDENTIFY(basicdsk_identify_default)
339{
340   UINT64 expected_size;
341   struct basicdsk_geometry geometry;
342
343   basicdsk_default_geometry(format, &geometry);
344
345   expected_size = geometry.sector_length;
346   expected_size *= geometry.heads;
347   expected_size *= geometry.tracks;
348   expected_size *= geometry.sectors;
349   *vote = (floppy_image_size(floppy) == expected_size) ? 100 : 0;
350   return FLOPPY_ERROR_SUCCESS;
351}
352
src/mame/formats/basicdsk.h
r0r11451
1/*********************************************************************
2
3    formats/basicdsk.h
4
5    Floppy format code for basic disks
6
7*********************************************************************/
8
9#ifndef BASICDSK_H
10#define BASICDSK_H
11
12#include "imagedev/flopimg.h"
13
14struct basicdsk_geometry
15{
16   int heads;
17   int tracks;
18   int sectors;
19   int first_sector_id;
20   int interleave;
21   int sector_map[256];
22   UINT32 sector_length;
23   UINT64 offset;
24
25   int (*translate_sector)(floppy_image *floppy, int sector);
26   UINT64 (*translate_offset)(floppy_image *floppy, const struct basicdsk_geometry *geom, int track, int head, int sector);
27   UINT64 (*get_ddam)(floppy_image *floppy, const struct basicdsk_geometry *geom, int track, int head, int sector);
28};
29
30floperr_t basicdsk_construct(floppy_image *floppy, const struct basicdsk_geometry *geometry);
31
32FLOPPY_IDENTIFY(basicdsk_identify_default);
33FLOPPY_CONSTRUCT(basicdsk_construct_default);
34
35#endif /* BASICDSK_H */
src/mame/layout/sms1.lay
r0r11451
1<?xml version="1.0"?>
2<mamelayout version="2">
3   <view name="Main Screen Standard (4:3)">
4      <screen index="0">
5         <bounds left="0" top="0" right="4" bottom="3" />
6      </screen>
7   </view>
8
9   <view name="SegaScope Left LCD Standard (4:3)">
10      <screen index="1">
11         <bounds left="0" top="0" right="4" bottom="3" />
12      </screen>
13   </view>
14
15   <view name="SegaScope Right LCD Standard (4:3)">
16      <screen index="2">
17         <bounds left="0" top="0" right="4" bottom="3" />
18      </screen>
19   </view>
20
21   <view name="Main Screen Pixel Aspect (~scr0nativexaspect~:~scr0nativeyaspect~)">
22      <screen index="0">
23         <bounds left="0" top="0" right="~scr0width~" bottom="~scr0height~" />
24      </screen>
25   </view>
26
27   <view name="SegaScope Left LCD Aspect (~scr1nativexaspect~:~scr1nativeyaspect~)">
28      <screen index="1">
29         <bounds left="0" top="0" right="~scr1width~" bottom="~scr1height~" />
30      </screen>
31   </view>
32
33   <view name="SegaScope Right LCD Pixel Aspect (~scr1nativexaspect~:~scr1nativeyaspect~)">
34      <screen index="2">
35         <bounds left="0" top="0" right="~scr1width~" bottom="~scr1height~" />
36      </screen>
37   </view>
38
39   <view name="Main Screen">
40      <screen index="0">
41         <bounds x="0" y="0" width="4" height="3" />
42      </screen>
43   </view>
44
45   <view name="SegaScope 3-D Glasses">
46      <screen index="1">
47         <bounds x="0" y="0" width="4" height="3" />
48      </screen>
49      <screen index="2">
50         <bounds x="4.03" y="0" width="4" height="3" />
51      </screen>
52   </view>
53
54   <view name="SegaScope 3-D Glasses (Gapless)">
55      <screen index="1">
56         <bounds x="0" y="0" width="4" height="3" />
57      </screen>
58      <screen index="2">
59         <bounds x="4" y="0" width="4" height="3" />
60      </screen>
61   </view>
62</mamelayout>
src/mame/drivers/mpu4.c
r11450r11451
66
77     04-2011: More accurate gamball code, fixed ROM banking (Project Amber), added BwB CHR simulator (Amber)
88              This is still a hard coded system, but significantly different to Barcrest's version.
9              Started adding support for the Crystal Gaming program card, and the link keys for setting parameters.
910     03-2011: Lamp timing fixes, support for all known expansion cards added.
10     01-2011: Adding the missing 'OKI' sound card, and documented it, but needs 6376 rewrite.
11     01-2011: Adding the missing 'OKI' sound card, and documented it, but it needs a 6376 rewrite.
1112     09-2007: Haze: Added Deal 'Em video support.
1213  03-08-2007: J Wallace: Removed audio filter for now, since sound is more accurate without them.
1314                         Connect 4 now has the right sound.
r11450r11451
5253The lamping and input handling side of the machine rely entirely on a column by column 'strobe' system, with lights and LEDs selected in turn.
5354In the inputs there are two orange connectors (sampled every 8ms) and two black ones (sampled every 16ms), giving 32 multiplexed inputs.
5455
55In addition there are two auxiliary ports taht can be accessed separately to these and are bidirectional
56In addition there are two auxiliary ports that can be accessed separately to these and are bidirectional
5657
5758--- Preliminary MPU4 Memorymap  ---
5859
r11450r11451
7071 0880      |R/W| D D D D D D D D | PIA6821 on soundboard (Oki MSM6376@16MHz)
7172           |   |                 | port A = ??
7273           |   |                 | port B (882)
73           |   |                 |        b7 = 0 if OKI busy
74           |   |                 |             1 if OKI ready
75           |   |                 |        b6 = ??
74           |   |                 |        b7 = NAR
75           |   |                 |        b6 = 0 if OKI busy, 1 if OKI ready
7676           |   |                 |        b5 = volume control clock
7777           |   |                 |        b4 = volume control direction (0= up, 1 = down)
7878           |   |                 |        b3 = ??
7979           |   |                 |        b2 = ??
80           |   |                 |        b1 = ??
81           |   |                 |        b0 = ??
80           |   |                 |        b1 = CH2
81           |   |                 |        b0 = ST
8282-----------+---+-----------------+--------------------------------------------------------------------------
8383 08C0      |   |                 | MC6840 on sound board
8484-----------+---+-----------------+--------------------------------------------------------------------------
r11450r11451
229229#include "sound/ay8910.h"
230230#include "sound/okim6376.h"
231231#include "sound/2413intf.h"
232#include "sound/upd7759.h"
232233#include "machine/steppers.h"
233234#include "machine/roc10937.h"
234235#include "machine/meters.h"
r11450r11451
261262
262263static const UINT8 bwb_chr_table_common[10]= {0x00,0x04,0x04,0x0c,0x0c,0x1c,0x14,0x2c,0x5c,0x2c};
263264
264#define STANDARD_REEL  0   /* As originally designed 3/4 reels*/
265#define FIVE_REEL_5TO8 1   /* Interfaces to meter port, allows some mechanical metering, but there is significant 'bounce' in the extra reel*/
266#define FIVE_REEL_8TO5 2   /* Mounted backwards for space reasons, but different board*/
267#define FIVE_REEL_3TO6 3   /* Connected to the centre of the meter connector, taking up meters 3 to 6 */
268#define SIX_REEL_1TO8  4   /* Two reels on the meter drives*/
269#define SIX_REEL_5TO8  5   /* Like FIVE_REEL_5TO8, but with an extra reel elsewhere*/
270#define SEVEN_REEL     6   /* Mainly club machines, significant reworking of reel hardware*/
271#define FLUTTERBOX     7   /* Will you start the fans, please!  A fan using a reel mux-like setup, but not actually a reel*/
265#define STANDARD_REEL  0   // As originally designed 3/4 reels
266#define FIVE_REEL_5TO8 1   // Interfaces to meter port, allows some mechanical metering, but there is significant 'bounce' in the extra reel
267#define FIVE_REEL_8TO5 2   // Mounted backwards for space reasons, but different board
268#define FIVE_REEL_3TO6 3   // Connected to the centre of the meter connector, taking up meters 3 to 6
269#define SIX_REEL_1TO8  4   // Two reels on the meter drives
270#define SIX_REEL_5TO8  5   // Like FIVE_REEL_5TO8, but with an extra reel elsewhere
271#define SEVEN_REEL     6   // Mainly club machines, significant reworking of reel hardware
272#define FLUTTERBOX     7   // Will you start the fans, please!  A fan using a reel mux-like setup, but not actually a reel
272273
273#define NO_EXTENDER         0   /* As originally designed */
274#define NO_EXTENDER         0 // As originally designed
274275#define SMALL_CARD         1
275276#define LARGE_CARD_A      2 //96 Lamps
276#define LARGE_CARD_B      3 // 96 Lamps, 16 LEDs - as used by BwB
277#define LARGE_CARD_B      3 //96 Lamps, 16 LEDs - as used by BwB
277278#define LARGE_CARD_C      4 //Identical to B, no built in LED support
278279
279280#define CARD_A         1
r11450r11451
295296   UINT8 response;
296297};
297298
298struct bwb_chr_table//dynamic populated table
299struct bwb_chr_table//dynamically populated table for BwB protection
299300{
300301   UINT8 response;
301302};
302303
303/* Video stuff */
304/* Video stuff - see mpu4drvr.c */
304305struct ef9369_t
305306{
306307   UINT32 addr;
r11450r11451
372373   int m_pageval;
373374   int m_pageset;
374375   int m_hopper;
376   int m_reels;
375377   const mpu4_chr_table* m_current_chr_table;
376378   const bwb_chr_table* m_bwb_chr_table1;
377379   //Video
r11450r11451
839841   LOG_IC3(("%s: IC3 PIA Write CA2 (alpha data), %02X\n", device->machine().describe_context(),state));
840842
841843   drvstate->m_alpha_data_line = state;
842   ROC10937_draw_16seg(0);
843844}
844845
845846
r11450r11451
847848{
848849   LOG_IC3(("%s: IC3 PIA Write CB (alpha reset), %02X\n",device->machine().describe_context(),state));
849850// DM Data pin A
850   if ( state ) ROC10937_reset(0);
851   ROC10937_draw_16seg(0);
851   if ( !state )
852   {
853      ROC10937_reset(0);
854   }
852855}
853856
854857
r11450r11451
13901393      awp_draw_reel(3);
13911394      awp_draw_reel(4);
13921395   }
1393   else
1396   else if (state->m_reels)
13941397   {
13951398      stepper_update(0, data & 0x0F );
13961399      stepper_update(1, (data>>4) & 0x0F );
r11450r11451
13981401      awp_draw_reel(1);
13991402   }
14001403
1401   if (state->m_reel_flag && (state->m_reel_mux == STANDARD_REEL))
1404   if (state->m_reel_flag && (state->m_reel_mux == STANDARD_REEL) && state->m_reels)
14021405   {
14031406      if ( stepper_optic_state(0) ) state->m_optic_pattern |=  0x01;
14041407      else                          state->m_optic_pattern &= ~0x01;
r11450r11451
14761479      awp_draw_reel(5);
14771480      awp_draw_reel(6);
14781481   }
1479   else
1482   else if (state->m_reels)
14801483   {
14811484      stepper_update(2, data & 0x0F );
14821485      stepper_update(3, (data>>4) & 0x0F );
r11450r11451
14841487      awp_draw_reel(3);
14851488   }
14861489
1487   if (state->m_reel_flag && (state->m_reel_mux == STANDARD_REEL))
1490   if (state->m_reel_flag && (state->m_reel_mux == STANDARD_REEL) && state->m_reels)
14881491   {
14891492      if ( stepper_optic_state(2) ) state->m_optic_pattern |=  0x04;
14901493      else                          state->m_optic_pattern &= ~0x04;
r11450r11451
16271630   LOG_IC8(("%s: IC8 PIA write CB2 (alpha clock) %02X\n", device->machine().describe_context(), state & 0xFF));
16281631
16291632   // DM Data pin B
1630   if ( !drvstate->m_alpha_clock && (state) )
1633   if (drvstate->m_alpha_clock != state)
16311634   {
1632      ROC10937_shift_data(0, drvstate->m_alpha_data_line&0x01?0:1);
1635      if (!drvstate->m_alpha_clock)//falling edge
1636      {
1637         ROC10937_shift_data(0, drvstate->m_alpha_data_line?0:1);
1638      }
16331639   }
16341640   drvstate->m_alpha_clock = state;
16351641   ROC10937_draw_16seg(0);
r11450r11451
17861792/* input ports for MPU4 board */
17871793static INPUT_PORTS_START( mpu4 )
17881794   PORT_START("ORANGE1")
1789   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("00")
1790   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("01")
1791   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("02")
1792   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("03")
1793   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("04")
1794   PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("05")
1795   PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("06")
1796   PORT_BIT( 0x80, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("07")
1795   PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("00")//  20p level
1796   PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("01")// 100p level
1797   PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("02")// Token 1 level
1798   PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("03")// Token 2 level
1799   PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("04")
1800   PORT_CONFNAME( 0xE0, 0x00, "Stake Key" )
1801   PORT_CONFSETTING(    0x00, "Not fitted / 5p"  )
1802   PORT_CONFSETTING(    0x20, "10p" )
1803   PORT_CONFSETTING(    0x40, "20p" )
1804   PORT_CONFSETTING(    0x60, "25p" )
1805   PORT_CONFSETTING(    0x80, "30p" )
1806   PORT_CONFSETTING(    0xA0, "40p" )
1807   PORT_CONFSETTING(    0xC0, "50p" )
1808   PORT_CONFSETTING(    0xE0, "1 GBP" )
17971809
17981810   PORT_START("ORANGE2")
1799   PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("08")
1800   PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("09")
1801   PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("10")
1802   PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("11")
1803   PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("12")
1804   PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("13")
1805   PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("14")
1806   PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("15")
1811   PORT_CONFNAME( 0x0F, 0x00, "Jackpot / Prize Key" )
1812   PORT_CONFSETTING(    0x00, "Not fitted"  )
1813   PORT_CONFSETTING(    0x01, "3 GBP"  )
1814   PORT_CONFSETTING(    0x02, "4 GBP"  )
1815   PORT_CONFSETTING(    0x08, "5 GBP"  )
1816   PORT_CONFSETTING(    0x03, "6 GBP"  )
1817   PORT_CONFSETTING(    0x04, "6 GBP Token"  )
1818   PORT_CONFSETTING(    0x05, "8 GBP"  )
1819   PORT_CONFSETTING(    0x06, "8 GBP Token"  )
1820   PORT_CONFSETTING(    0x07, "10 GBP"  )
1821   PORT_CONFSETTING(    0x09, "15 GBP"  )
1822   PORT_CONFSETTING(    0x0A, "25 GBP"  )
1823   PORT_CONFSETTING(    0x0B, "25 GBP (Licensed Betting Office Profile)"  )
1824   PORT_CONFSETTING(    0x0C, "35 GBP"  )
1825   PORT_CONFSETTING(    0x0D, "70 GBP"  )
1826   PORT_CONFSETTING(    0x0E, "Reserved"  )
1827   PORT_CONFSETTING(    0x0F, "Reserved"  )
18071828
1829   PORT_CONFNAME( 0xF0, 0x00, "Percentage Key" )
1830   PORT_CONFSETTING(    0x00, "Not fitted / 68% (Invalid for UK Games)"  )
1831   PORT_CONFSETTING(    0x10, "70" )
1832   PORT_CONFSETTING(    0x20, "72" )
1833   PORT_CONFSETTING(    0x30, "74" )
1834   PORT_CONFSETTING(    0x40, "76" )
1835   PORT_CONFSETTING(    0x50, "78" )
1836   PORT_CONFSETTING(    0x60, "80" )
1837   PORT_CONFSETTING(    0x70, "82" )
1838   PORT_CONFSETTING(    0x80, "84" )
1839   PORT_CONFSETTING(    0x90, "86" )
1840   PORT_CONFSETTING(    0xA0, "88" )
1841   PORT_CONFSETTING(    0xB0, "90" )
1842   PORT_CONFSETTING(    0xC0, "92" )
1843   PORT_CONFSETTING(    0xD0, "94" )
1844   PORT_CONFSETTING(    0xE0, "96" )
1845   PORT_CONFSETTING(    0xF0, "98" )
1846
18081847   PORT_START("BLACK1")
18091848   PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_NAME("Hi")
18101849   PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_BUTTON2) PORT_NAME("Lo")
r11450r11451
18131852   PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_OTHER)   PORT_NAME("20")
18141853   PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_SERVICE) PORT_NAME("Test Button") PORT_CODE(KEYCODE_W)
18151854   PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_SERVICE) PORT_NAME("Refill Key") PORT_CODE(KEYCODE_R) PORT_TOGGLE
1816   PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_INTERLOCK) PORT_NAME("Cashbox Door")  PORT_CODE(KEYCODE_Q) PORT_TOGGLE
1855   PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_INTERLOCK) PORT_NAME("Cashbox (Back) Door")  PORT_CODE(KEYCODE_Q) PORT_TOGGLE
18171856
18181857   PORT_START("BLACK2")
18191858   PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_OTHER) PORT_NAME("24")
r11450r11451
23672406           (1) = ( (BWBMagicAddress + 1))
23682407           (2) = ( (BWBMagicAddress + 2))
23692408           (3) = ( (BWBMagicAddress + 4))
2370
23712409           (4) = ( (BWBMagicAddress - 5))
23722410           (5) = ( (BWBMagicAddress - 4))
23732411           (6) = ( (BWBMagicAddress - 3))
r11450r11451
25362574{
25372575   mpu4_state *state = machine.driver_data<mpu4_state>();
25382576   state->m_reel_mux=SIX_REEL_1TO8;
2577   state->m_reels = 6;
25392578
25402579   stepper_config(machine, 0, &barcrest_opto1_interface);
25412580   stepper_config(machine, 1, &barcrest_opto1_interface);
r11450r11451
25522591{
25532592   mpu4_state *state = machine.driver_data<mpu4_state>();
25542593   state->m_reel_mux=STANDARD_REEL;
2594   state->m_reels = 4;
25552595   // setup 4 default 96 half step reels ///////////////////////////////////
25562596   mpu4_config_common_reels(machine,4);
25572597
r11450r11451
25622602{
25632603   mpu4_state *state = machine.driver_data<mpu4_state>();
25642604   state->m_reel_mux=STANDARD_REEL;
2605   state->m_reels = 4;
25652606   // setup 4 default 96 half step reels ///////////////////////////////////
25662607   mpu4_config_common_reels(machine,4);
25672608
r11450r11451
25722613{
25732614   mpu4_state *state = machine.driver_data<mpu4_state>();
25742615   state->m_reel_mux=FIVE_REEL_5TO8;
2616   state->m_reels = 5;
25752617   state->m_lamp_extender=SMALL_CARD;
25762618   // setup 4 default 96 half step reels with the mux board
25772619   mpu4_config_common_reels(machine,4);
r11450r11451
25842626   mpu4_state *state = machine.driver_data<mpu4_state>();
25852627   state->m_bwb_bank=1;
25862628   state->m_reel_mux=FIVE_REEL_5TO8;
2587
2629   state->m_reels = 5;
25882630   stepper_config(machine, 0, &bwb_opto1_interface);
25892631   stepper_config(machine, 1, &bwb_opto1_interface);
25902632   stepper_config(machine, 2, &bwb_opto1_interface);
r11450r11451
25982640{
25992641   mpu4_state *state = machine.driver_data<mpu4_state>();
26002642   state->m_reel_mux=STANDARD_REEL;
2601   // setup 5 default 96 half step reels with the mux board
2643   state->m_reels = 4;
26022644   mpu4_config_common_reels(machine,4);
2603
26042645}
26052646
26062647static DRIVER_INIT (mpu4utst)
26072648{
26082649   mpu4_state *state = machine.driver_data<mpu4_state>();
26092650   state->m_reel_mux=STANDARD_REEL;
2610   // setup 4 default 96 half step reels ///////////////////////////////////
2651   state->m_reels = 4;
26112652   mpu4_config_common_reels(machine,4);
26122653}
26132654
26142655static DRIVER_INIT (connect4)
26152656{
26162657   mpu4_state *state = machine.driver_data<mpu4_state>();
2658   state->m_reels = 0; //reel-free game
26172659   state->m_led_lamp=1;
26182660}
26192661
2662static DRIVER_INIT (m_frkstn)
2663{
2664   mpu4_state *state = machine.driver_data<mpu4_state>();
2665   state->m_reel_mux=STANDARD_REEL;
2666   state->m_reels = 4;
2667
2668   // setup 4 default 96 half step reels with the mux board
2669   mpu4_config_common_reels(machine,4);
2670
2671   //This is a Crystal ROM, needs UPD chip and Project Amber's ROM swizzle.
2672}
2673
26202674/* generate a 50 Hz signal (based on an RC time) */
26212675static TIMER_DEVICE_CALLBACK( gen_50hz )
26222676{
r11450r11451
27252779   AM_RANGE(0x1000, 0xffff) AM_ROMBANK("bank1")   // 64k  paged ROM (4 pages)
27262780ADDRESS_MAP_END
27272781
2728// memory map for barcrest mpu4 board /////////////////////////////////////
2782static ADDRESS_MAP_START( mpu4_crystal_map, AS_PROGRAM, 8 )
2783   AM_RANGE(0x0000, 0x07ff) AM_RAM AM_SHARE("nvram")
27292784
2785   AM_RANGE(0x0850, 0x0850) AM_WRITE(bankswitch_w)   // write bank (rom page select)
2786
2787   AM_RANGE(0x0858, 0x0858) AM_WRITE(bankswitch_w)   // write bank (rom page select)
2788   AM_RANGE(0x0878, 0x0878) AM_WRITE(bankset_w)   // write bank (rom page select)
2789
2790//  AM_RANGE(0x08e0, 0x08e7) AM_READWRITE(68681_duart_r,68681_duart_w) //Runs hoppers
2791
2792   AM_RANGE(0x0900, 0x0907) AM_DEVREADWRITE_MODERN("ptm_ic2", ptm6840_device, read, write)/* PTM6840 IC2 */
2793
2794   AM_RANGE(0x0a00, 0x0a03) AM_DEVREADWRITE_MODERN("pia_ic3", pia6821_device, read, write)      /* PIA6821 IC3 */
2795   AM_RANGE(0x0b00, 0x0b03) AM_DEVREADWRITE_MODERN("pia_ic4", pia6821_device, read, write)      /* PIA6821 IC4 */
2796   AM_RANGE(0x0c00, 0x0c03) AM_DEVREADWRITE_MODERN("pia_ic5", pia6821_device, read, write)      /* PIA6821 IC5 */
2797   AM_RANGE(0x0d00, 0x0d03) AM_DEVREADWRITE_MODERN("pia_ic6", pia6821_device, read, write)      /* PIA6821 IC6 */
2798   AM_RANGE(0x0e00, 0x0e03) AM_DEVREADWRITE_MODERN("pia_ic7", pia6821_device, read, write)      /* PIA6821 IC7 */
2799   AM_RANGE(0x0f00, 0x0f03) AM_DEVREADWRITE_MODERN("pia_ic8", pia6821_device, read, write)      /* PIA6821 IC8 */
2800
2801   AM_RANGE(0x1000, 0xffff) AM_ROMBANK("bank1")   // 64k  paged ROM (4 pages)
2802ADDRESS_MAP_END
2803
27302804static ADDRESS_MAP_START( dutch_memmap, AS_PROGRAM, 8 )
27312805
27322806   AM_RANGE(0x0000, 0x07ff) AM_RAM AM_SHARE("nvram")
r11450r11451
28242898   MCFG_MACHINE_START(mpu4dutch)               // main mpu4 board initialisation
28252899MACHINE_CONFIG_END
28262900
2827static MACHINE_CONFIG_DERIVED(bwboki, mod4oki )
2901static MACHINE_CONFIG_DERIVED( bwboki, mod4oki )
28282902   MCFG_CPU_MODIFY("maincpu")
28292903   MCFG_CPU_PROGRAM_MAP(mpu4_bwb_map)            // setup read and write memorymap
28302904MACHINE_CONFIG_END
28312905
2906static MACHINE_CONFIG_DERIVED(mpu4crys, mpu4mod2 )
2907   MCFG_CPU_MODIFY("maincpu")
2908   MCFG_CPU_PROGRAM_MAP(mpu4_crystal_map)            // setup read and write memorymap
2909
2910   MCFG_SOUND_ADD("upd", UPD7759, UPD7759_STANDARD_CLOCK)
2911   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
2912MACHINE_CONFIG_END
2913
2914
2915
28322916ROM_START( m_oldtmr )
28332917   ROM_REGION( 0x10000, "maincpu", 0 )
28342918   ROM_LOAD( "dot11.bin",  0x00000, 0x10000,  CRC(da095666) SHA1(bc7654dc9da1f830a43f925db8079f27e18bb61e))
r11450r11451
28882972   ROM_LOAD( "bbsnd.p2",  0x080000, 0x080000,  CRC(594a87f8) SHA1(edfef7d08fab41fb5814c92930f08a565371eae1) )
28892973ROM_END
28902974
2891//    year,  name,    parent,  machine,  input,   init,     monitor,company,        fullname,                     flags
2892GAME( 198?,  m_oldtmr,0,      mpu4dutch,mpu4,     m_oldtmr, ROT0,   "Barcrest",      "Old Timer",              GAME_NOT_WORKING|GAME_NO_SOUND|GAME_REQUIRES_ARTWORK )
2893GAME( 198?,  m_ccelbr,0,      mpu4mod2, mpu4,     m_ccelbr, ROT0,   "Barcrest",      "Club Celebration",           GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK )
2894GAMEL(198?,  m_gmball,0,      mod4yam,  gamball,  m_gmball, ROT0,   "Barcrest",     "Gamball",                 GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK|GAME_MECHANICAL,layout_gamball )//Mechanical ball launcher
2895GAMEL(198?,  m_grtecp,0,      mod4oki,  mpu4,     m_grtecp, ROT0,   "Barcrest",      "Andy's Great Escape",        GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK,layout_mpu4ext )//5 reel meter mux
2896GAME(199?,   m_blsbys,0,     bwboki,   mpu4,     m_blsbys, ROT0,   "Barcrest",      "Blues Boys (Version 6)",     GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK )
2975ROM_START( m_frkstn )
2976   ROM_REGION( 0x10000, "maincpu", ROMREGION_ERASE00  )
2977   ROM_LOAD( "fr1.536",  0x8000, 0x8000,  CRC(422b7209) SHA1(3c3f942d375a83d2470467651bca20f0feabdd3b))
28972978
2979   ROM_REGION( 0x40000, "upd", 0 )
2980   ROM_LOAD("fr1snd.bin",   0x00000, 0x40000, CRC(2d77bbde) SHA1(0397ede538e913dc2972e260589022564fcd8fe4))
2981ROM_END
2982
2983//    year,  name,    parent,  machine,  input,   init,     monitor,company,        fullname,                           flags
2984GAME( 198?,  m_oldtmr,0,      mpu4dutch,mpu4,     m_oldtmr, ROT0,   "Barcrest",       "Old Timer",                  GAME_NOT_WORKING|GAME_NO_SOUND|GAME_REQUIRES_ARTWORK )
2985GAME( 198?,  m_ccelbr,0,      mpu4mod2, mpu4,     m_ccelbr, ROT0,   "Barcrest",       "Club Celebration",            GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK )
2986GAMEL(198?,  m_gmball,0,      mod4yam,  gamball,  m_gmball, ROT0, "Barcrest",       "Gamball",                     GAME_REQUIRES_ARTWORK|GAME_MECHANICAL,layout_gamball )//Mechanical ball launcher
2987GAMEL(198?,  m_grtecp,0,      mod4oki,  mpu4,     m_grtecp, ROT0,   "Barcrest",       "Andy's Great Escape",            GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK,layout_mpu4ext )//5 reel meter mux
2988GAME(199?,   m_blsbys,0,     bwboki,   mpu4,     m_blsbys, ROT0,   "Barcrest",       "Blues Boys (Version 6)",         GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK )
2989GAME(199?,   m_frkstn,0,     mpu4crys, mpu4,     m_frkstn, ROT0,   "Crystal Gaming","Frank 'n' Stein (unencrypted)",   GAME_NOT_WORKING|GAME_REQUIRES_ARTWORK|GAME_NO_SOUND )//hardware not connected
2990
28982991//SWP
28992992GAMEL(1989?,connect4,        0, mpu4mod2,   connect4,   connect4,   ROT0, "Dolbeck Systems","Connect 4",GAME_IMPERFECT_GRAPHICS|GAME_REQUIRES_ARTWORK,layout_connect4 )
29002993
src/mame/drivers/dc.c
r0r11451
1/*
2
3    dc.c - Sega Dreamcast driver
4    by R. Belmont
5
6    SH-4 @ 200 MHz
7    ARM7DI @ 2.8223 MHz (no T or M extensions)
8    PowerVR 3D video
9    AICA audio
10    GD-ROM drive (modified ATAPI interface)
11
12            NTSC/N  NTSC/I   PAL/N   PAL/I   VGA
13        (x/240) (x/480) (x/240)  (x/480) (640x480)
14    VTOTAL   262     524      312     624    524
15    HTOTAL   857     857      863     863    857
16
17    PCLKs = 26917135 (NTSC 480 @ 59.94), 26944080 (VGA 480 @ 60.0), 13458568 (NTSC 240 @ 59.94),
18            25925600 (PAL 480 @ 50.00), 13462800 (PAL 240 @ 50.00)
19
20*/
21
22#include "emu.h"
23#include "cpu/arm7/arm7.h"
24#include "cpu/sh4/sh4.h"
25#include "cpu/arm7/arm7core.h"
26#include "sound/aica.h"
27#include "includes/dc.h"
28#include "imagedev/chd_cd.h"
29#include "machine/maple-dc.h"
30#define CPU_CLOCK (200000000)
31
32#ifdef MESS
33UINT16 actel_id;
34int jvsboard_type;
35#else
36extern UINT16 actel_id;
37extern int jvsboard_type;
38#endif
39
40// things from mess/machine/dc.c
41void dreamcast_atapi_init(running_machine &machine);
42void dreamcast_atapi_reset(running_machine &machine);
43extern READ64_HANDLER( dc_mess_gdrom_r );
44extern WRITE64_HANDLER( dc_mess_gdrom_w );
45extern READ64_HANDLER( dc_mess_g1_ctrl_r );
46extern WRITE64_HANDLER( dc_mess_g1_ctrl_w );
47
48static UINT32 *dc_sound_ram;
49static UINT64 *dc_ram;
50
51static READ64_HANDLER( dcus_idle_skip_r )
52{
53   if (cpu_get_pc(&space->device())==0xc0ba52a)
54      device_spin_until_time(&space->device(), attotime::from_usec(2500));
55   //  device_spinuntil_int(&space->device());
56
57   return dc_ram[0x2303b0/8];
58}
59
60static READ64_HANDLER( dcjp_idle_skip_r )
61{
62   if (cpu_get_pc(&space->device())==0xc0bac62)
63      device_spin_until_time(&space->device(), attotime::from_usec(2500));
64   //  device_spinuntil_int(&space->device());
65
66   return dc_ram[0x2302f8/8];
67}
68
69static DRIVER_INIT(dc)
70{
71   dreamcast_atapi_init(machine);
72}
73
74static DRIVER_INIT(dcus)
75{
76   machine.device("maincpu")->memory().space(AS_PROGRAM)->install_legacy_read_handler(0xc2303b0, 0xc2303b7, FUNC(dcus_idle_skip_r));
77
78   DRIVER_INIT_CALL(dc);
79}
80
81static DRIVER_INIT(dcjp)
82{
83   machine.device("maincpu")->memory().space(AS_PROGRAM)->install_legacy_read_handler(0xc2302f8, 0xc2302ff, FUNC(dcjp_idle_skip_r));
84
85   DRIVER_INIT_CALL(dc);
86}
87
88static UINT64 PDTRA, PCTRA;
89static READ64_HANDLER( dc_pdtra_r )
90{
91   UINT64 out = PCTRA<<32;
92
93   out |= PDTRA & ~3;
94
95   // if both bits are inputs
96   if (!(PCTRA & 0x5))
97   {
98      out |= 3;
99   }
100
101   // one's input one's output, always pull up both bits
102   if (((PCTRA & 5) == 1) || ((PCTRA & 5) == 4))
103   {
104      if (PDTRA & 3)
105      {
106         out |= 3;
107      }
108   }
109
110   return out;
111}
112
113static WRITE64_HANDLER( dc_pdtra_w )
114{
115   PCTRA = (data>>16) & 0xffff;
116   PDTRA = (data & 0xffff);
117}
118
119static READ64_HANDLER( dc_arm_r )
120{
121   return *((UINT64 *)dc_sound_ram+offset);
122}
123
124static WRITE64_HANDLER( dc_arm_w )
125{
126   COMBINE_DATA((UINT64 *)dc_sound_ram + offset);
127}
128
129 // SB_LMMODE0
130 static WRITE64_HANDLER( ta_texture_directpath0_w )
131 {
132   int mode = pvrctrl_regs[SB_LMMODE0]&1;
133   if (mode&1)
134   {
135      printf("ta_texture_directpath0_w 32-bit access!\n");
136      COMBINE_DATA(&dc_framebuffer_ram[offset]);
137   }
138   else
139   {
140      COMBINE_DATA(&dc_texture_ram[offset]);
141   }
142 }
143
144 // SB_LMMODE1
145 static WRITE64_HANDLER( ta_texture_directpath1_w )
146 {
147   int mode = pvrctrl_regs[SB_LMMODE1]&1;
148   if (mode&1)
149   {
150      printf("ta_texture_directpath0_w 32-bit access!\n");
151      COMBINE_DATA(&dc_framebuffer_ram[offset]);
152   }
153   else
154   {
155      COMBINE_DATA(&dc_texture_ram[offset]);
156   }
157 }
158
159static ADDRESS_MAP_START( dc_map, AS_PROGRAM, 64 )
160   AM_RANGE(0x00000000, 0x001fffff) AM_ROM   AM_WRITENOP            // BIOS
161   AM_RANGE(0x00200000, 0x0021ffff) AM_ROM AM_REGION("maincpu", 0x200000)   // flash
162   AM_RANGE(0x005f6800, 0x005f69ff) AM_READWRITE( dc_sysctrl_r, dc_sysctrl_w )
163   AM_RANGE(0x005f6c00, 0x005f6cff) AM_DEVREADWRITE32_MODERN( "maple_dc", maple_dc_device, sb_mdstar_r, sb_mdstar_w, U64(0xffffffff00000000) )
164   AM_RANGE(0x005f7000, 0x005f70ff) AM_READWRITE( dc_mess_gdrom_r, dc_mess_gdrom_w )
165   AM_RANGE(0x005f7400, 0x005f74ff) AM_READWRITE( dc_mess_g1_ctrl_r, dc_mess_g1_ctrl_w )
166   AM_RANGE(0x005f7800, 0x005f78ff) AM_READWRITE( dc_g2_ctrl_r, dc_g2_ctrl_w )
167   AM_RANGE(0x005f7c00, 0x005f7cff) AM_READWRITE( pvr_ctrl_r, pvr_ctrl_w )
168   AM_RANGE(0x005f8000, 0x005f9fff) AM_READWRITE( pvr_ta_r, pvr_ta_w )
169   AM_RANGE(0x00600000, 0x006007ff) AM_READWRITE( dc_modem_r, dc_modem_w )
170   AM_RANGE(0x00700000, 0x00707fff) AM_DEVREADWRITE("aica", dc_aica_reg_r, dc_aica_reg_w )
171   AM_RANGE(0x00710000, 0x0071000f) AM_READWRITE( dc_rtc_r, dc_rtc_w )
172   AM_RANGE(0x00800000, 0x009fffff) AM_READWRITE( dc_arm_r, dc_arm_w )
173
174   /* Area 1 */
175   AM_RANGE(0x04000000, 0x04ffffff) AM_RAM   AM_BASE( &dc_texture_ram )      // texture memory 64 bit access
176   AM_RANGE(0x05000000, 0x05ffffff) AM_RAM AM_BASE( &dc_framebuffer_ram ) // apparently this actually accesses the same memory as the 64-bit texture memory access, but in a different format, keep it apart for now
177
178   /* Area 3 */
179   AM_RANGE(0x0c000000, 0x0cffffff) AM_RAM AM_SHARE("share4") AM_BASE(&dc_ram)
180   AM_RANGE(0x0d000000, 0x0dffffff) AM_RAM AM_SHARE("share4")// extra ram on Naomi (mirror on DC)
181   AM_RANGE(0x0e000000, 0x0effffff) AM_RAM AM_SHARE("share4")// mirror
182   AM_RANGE(0x0f000000, 0x0fffffff) AM_RAM AM_SHARE("share4")// mirror
183
184   /* Area 4 */
185   AM_RANGE(0x10000000, 0x107fffff) AM_WRITE( ta_fifo_poly_w )
186   AM_RANGE(0x10800000, 0x10ffffff) AM_WRITE( ta_fifo_yuv_w )
187   AM_RANGE(0x11000000, 0x117fffff) AM_WRITE( ta_texture_directpath0_w ) AM_MIRROR(0x00800000)  // access to texture / fraembfufer memory (either 32-bit or 64-bit area depending on SB_LMMODE0 register - cannot be written directly, only through dma / store queue
188
189   AM_RANGE(0x12000000, 0x127fffff) AM_WRITE( ta_fifo_poly_w )
190   AM_RANGE(0x12800000, 0x12ffffff) AM_WRITE( ta_fifo_yuv_w )
191   AM_RANGE(0x13000000, 0x137fffff) AM_WRITE( ta_texture_directpath1_w ) AM_MIRROR(0x00800000) // access to texture / fraembfufer memory (either 32-bit or 64-bit area depending on SB_LMMODE1 register - cannot be written directly, only through dma / store queue
192
193   AM_RANGE(0x8c000000, 0x8cffffff) AM_RAM AM_SHARE("share4")   // another RAM mirror
194
195   AM_RANGE(0xa0000000, 0xa01fffff) AM_ROM AM_REGION("maincpu", 0)
196ADDRESS_MAP_END
197
198static ADDRESS_MAP_START( dc_port, AS_IO, 64 )
199   AM_RANGE(0x00000000, 0x00000007) AM_READWRITE( dc_pdtra_r, dc_pdtra_w )
200ADDRESS_MAP_END
201
202static ADDRESS_MAP_START( dc_audio_map, AS_PROGRAM, 32 )
203   AM_RANGE(0x00000000, 0x001fffff) AM_RAM AM_BASE(&dc_sound_ram)      /* shared with SH-4 */
204   AM_RANGE(0x00800000, 0x00807fff) AM_DEVREADWRITE("aica", dc_arm_aica_r, dc_arm_aica_w)
205ADDRESS_MAP_END
206
207static MACHINE_RESET( dc_console )
208{
209   device_t *aica = machine.device("aica");
210   MACHINE_RESET_CALL(dc);
211   aica_set_ram_base(aica, dc_sound_ram, 2*1024*1024);
212   dreamcast_atapi_reset(machine);
213}
214
215static void aica_irq(device_t *device, int irq)
216{
217   cputag_set_input_line(device->machine(), "soundcpu", ARM7_FIRQ_LINE, irq ? ASSERT_LINE : CLEAR_LINE);
218}
219
220static const aica_interface dc_aica_interface =
221{
222   0,
223   0,
224   aica_irq
225};
226
227static const struct sh4_config sh4cpu_config = {  1,  0,  1,  0,  0,  0,  1,  1,  0, CPU_CLOCK };
228
229static MACHINE_CONFIG_START( dc, driver_device )
230   /* basic machine hardware */
231   MCFG_CPU_ADD("maincpu", SH4, CPU_CLOCK)
232   MCFG_CPU_CONFIG(sh4cpu_config)
233   MCFG_CPU_PROGRAM_MAP(dc_map)
234   MCFG_CPU_IO_MAP(dc_port)
235
236   MCFG_CPU_ADD("soundcpu", ARM7, ((XTAL_33_8688MHz*2)/3)/8)   // AICA bus clock is 2/3rds * 33.8688.  ARM7 gets 1 bus cycle out of each 8.
237   MCFG_CPU_PROGRAM_MAP(dc_audio_map)
238
239   MCFG_MACHINE_START( dc )
240   MCFG_MACHINE_RESET( dc_console )
241
242   MCFG_MAPLE_DC_ADD( "maple_dc", "maincpu" )
243
244   /* video hardware */
245   MCFG_SCREEN_ADD("screen", RASTER)
246   MCFG_SCREEN_REFRESH_RATE(60)
247   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500) /* not accurate */)
248   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
249   MCFG_SCREEN_SIZE(640, 480)
250   MCFG_SCREEN_VISIBLE_AREA(0, 640-1, 0, 480-1)
251   MCFG_SCREEN_UPDATE(dc)
252
253   MCFG_PALETTE_LENGTH(0x1000)
254
255   MCFG_VIDEO_START(dc)
256
257   MCFG_SPEAKER_STANDARD_STEREO("lspeaker", "rspeaker")
258   MCFG_SOUND_ADD("aica", AICA, 0)
259   MCFG_SOUND_CONFIG(dc_aica_interface)
260   MCFG_SOUND_ROUTE(0, "lspeaker", 2.0)
261   MCFG_SOUND_ROUTE(0, "rspeaker", 2.0)
262
263   MCFG_CDROM_ADD( "cdrom" )
264MACHINE_CONFIG_END
265
266ROM_START(dc)
267   ROM_REGION(0x220000, "maincpu", 0)
268        ROM_LOAD( "dc101d_us.bin", 0x000000, 0x200000, CRC(89f2b1a1) SHA1(8951d1bb219ab2ff8583033d2119c899cc81f18c) )   // BIOS
269        ROM_LOAD( "dcus_ntsc.bin", 0x200000, 0x020000, CRC(c611b498) SHA1(94d44d7f9529ec1642ba3771ed3c5f756d5bc872) )   // Flash
270ROM_END
271
272ROM_START( dceu )
273   ROM_REGION(0x220000, "maincpu", 0)
274        ROM_LOAD( "dc101d_eu.bin", 0x000000, 0x200000, CRC(a2564fad) SHA1(edc5d3d70a93c935703d26119b37731fd317d2bf) )   // BIOS
275        ROM_LOAD( "dceu_pal.bin", 0x200000, 0x020000, CRC(b7e5aeeb) SHA1(11e02433e13b793ec7ffe0ae2356750bb8a575b4) )   // Flash
276ROM_END
277
278ROM_START( dcjp )
279   ROM_REGION(0x220000, "maincpu", 0)
280        ROM_LOAD( "dc1004jp.bin", 0x000000, 0x200000, CRC(5454841f) SHA1(1ea132c0fbbf07ef76789eadc07908045c089bd6) )   // BIOS
281        /* ROM_LOAD( "dcjp_ntsc.bad", 0x200000, 0x020000, BAD_DUMP CRC(307a7035) SHA1(1411423a9d071340ea52c56e19c1aafc4e1309ee) )      // Hacked Flash */
282        ROM_LOAD( "dcjp_ntsc.bin", 0x200000, 0x020000, CRC(5F92BF76) SHA1(BE78B834F512AB2CF3D67B96E377C9F3093FF82A) )  // Flash
283ROM_END
284
285ROM_START( dcdev )
286   ROM_REGION(0x220000, "maincpu", 0)
287        ROM_LOAD( "hkt-0120.bin", 0x000000, 0x200000, CRC(2186E0E5) SHA1(6BD18FB83F8FDB56F1941E079580E5DD672A6DAD) )      // BIOS
288        ROM_LOAD( "hkt-0120-flash.bin", 0x200000, 0x020000, CRC(7784C304) SHA1(31EF57F550D8CD13E40263CBC657253089E53034) )   // Flash
289ROM_END
290
291static INPUT_PORTS_START( dc )
292   PORT_START("P1L")
293   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(1)
294   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(1)
295   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(1)
296   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(1)
297   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 )
298   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
299   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1)
300   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1)
301   PORT_START("P1H")
302   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN1 )
303   PORT_SERVICE_NO_TOGGLE( 0x40, IP_ACTIVE_LOW )
304   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE1 )
305   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
306   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
307   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(1)
308   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(1)
309   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(1)
310
311   PORT_START("P2L")
312   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(2)
313   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(2)
314   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(2)
315   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(2)
316   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START2 )
317   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
318   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
319   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2)
320   PORT_START("P2H")
321   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN2 )
322   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
323   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE2 )
324   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
325   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
326   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(2)
327   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(2)
328   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(2)
329
330   PORT_START("P3L")
331   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(3)
332   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(3)
333   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(3)
334   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(3)
335   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START3 )
336   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(3)
337   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(3)
338   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(3)
339   PORT_START("P3H")
340   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN3 )
341   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
342   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE3 )
343   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
344   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
345   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(3)
346   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(3)
347   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(3)
348
349   PORT_START("P4L")
350   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_PLAYER(4)
351   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_PLAYER(4)
352   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_PLAYER(4)
353   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_PLAYER(4)
354   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START4 )
355   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(4)
356   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(4)
357   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(4)
358   PORT_START("P4H")
359   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_COIN4 )
360   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
361   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_SERVICE4 )
362   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN )
363   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
364   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON4 ) PORT_PLAYER(4)
365   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_PLAYER(4)
366   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_PLAYER(4)
367
368   PORT_START("MAMEDEBUG") \
369   PORT_DIPNAME( 0x01, 0x00, "Bilinear Filtering" )
370   PORT_DIPSETTING(    0x00, DEF_STR( Off ) )
371   PORT_DIPSETTING(    0x01, DEF_STR( On ) )
372INPUT_PORTS_END
373
374
375/*    YEAR  NAME    PARENT  COMPAT  MACHINE INPUT   INIT      COMPANY FULLNAME */
376CONS( 1999, dc,     dcjp,   0,      dc,     dc,     dcus,   "Sega", "Dreamcast (USA, NTSC)", GAME_NOT_WORKING )
377CONS( 1998, dcjp,   0,      0,      dc,     dc,     dcjp,   "Sega", "Dreamcast (Japan, NTSC)", GAME_NOT_WORKING )
378CONS( 1999, dceu,   dcjp,   0,      dc,     dc,     dcus,   "Sega", "Dreamcast (Europe, PAL)", GAME_NOT_WORKING )
379CONS( 1998, dcdev,  dcjp,   0,      dc,     dc,     dc,     "Sega", "HKT-0120 Sega Dreamcast Development Box", GAME_NOT_WORKING )
src/mame/drivers/seta.c
r11450r11451
13161316#include "sound/x1_010.h"
13171317#include "sound/2151intf.h"
13181318#include "video/seta001.h"
1319#include "machine/nvram.h"
13191320
13201321#if __uPD71054_TIMER
13211322
r11450r11451
22302231        Seta Roulette
22312232***************************************************************************/
22322233
2233static READ16_HANDLER( setaroul_c0_r )
2234{
2235   return 0x00;//space->machine().rand();
2236}
2234// the spritey low bits are mapped to 1 in every 4 bytes here as if it were a 32-bit bus..which is weird
2235// other ram is similar..
22372236
2238static READ16_HANDLER( setaroul_d4_0_r )
2237static WRITE16_HANDLER( setaroul_spriteylow_w )
22392238{
2240   return 0x00;//space->machine().rand();
2239   seta001_device *dev = space->machine().device<seta001_device>("spritegen");
2240   if ((offset&1)==0) spriteylow_w8(dev, offset>>1, (data & 0xff00) >> 8);
22412241}
22422242
2243static READ16_HANDLER( setaroul_d4_4_r )
2243static WRITE16_HANDLER( setaroul_spritectrl_w )
22442244{
2245   return 0x00;//space->machine().rand();
2245   seta001_device *dev = space->machine().device<seta001_device>("spritegen");
2246   if ((offset&1)==0) spritectrl_w8(dev, offset>>1, (data & 0xff00) >> 8);
22462247}
22472248
2248static READ16_HANDLER( setaroul_d4_6_r )
2249static WRITE16_HANDLER( setaroul_spritecode_w )
22492250{
2250   return 0xffff;//space->machine().rand();
2251   seta001_device *dev = space->machine().device<seta001_device>("spritegen");
2252   if ((offset&1)==1) spritecodelow_w8(dev, offset>>1, (data & 0xff00) >> 8);
2253   if ((offset&1)==0) spritecodehigh_w8(dev, offset>>1, (data & 0xff00) >> 8);
22512254}
22522255
2253static READ16_HANDLER( setaroul_d4_8_r )
2256static READ16_HANDLER( setaroul_spritecode_r )
22542257{
2255   return space->machine().rand()&0x000f;
2258   UINT16 ret;
2259   seta001_device *dev = space->machine().device<seta001_device>("spritegen");
2260   if ((offset&1)==1) ret = spritecodelow_r8(dev, offset>>1);
2261   if ((offset&1)==0) ret = spritecodehigh_r8(dev, offset>>1);
2262   return ret << 8;
22562263}
22572264
2258static READ16_HANDLER( setaroul_d4_a_r )
2259{
2260   return 0x00;//space->machine().rand();
2261}
22622265
2263static READ16_HANDLER( setaroul_d4_10_r )
2264{
2265   return 0x00;// space->machine().rand();
2266}
22672266
2268#if 0
2269// ?? looks like sprite ram access is 8-bit not 16?
2270static WRITE16_HANDLER( setaroul_spr_w )
2271{
22722267
2273   seta_state *state = space->machine().driver_data<seta_state>();
2274   UINT16 *spriteram16 = state->m_spriteram;
2275   int realoffs = offset;
22762268
2277   realoffs >>=1;
2278
2279   if (!(offset & 1))
2280   {
2281      data = data >> 8;
2282      mem_mask = mem_mask >> 8;
2283   }
2284
2285   COMBINE_DATA(&spriteram16[realoffs]);
2286
2287}
2288#endif
2289
22902269static ADDRESS_MAP_START( setaroul_map, AS_PROGRAM, 16 )
22912270   AM_RANGE(0x000000, 0x01ffff) AM_ROM                        // ROM
22922271
2293   AM_RANGE(0xc00000, 0xc03fff) AM_RAM AM_DEVREADWRITE("spritegen", spritecode_r16, spritecode_w16)      // Sprites Code + X + Attr (maybe not)
2272   AM_RANGE(0xc00000, 0xc03fff) AM_RAM AM_SHARE("nvram")
22942273
2295   AM_RANGE(0xc40000, 0xc40001) AM_RAM //AM_BASE_MEMBER(seta_state, m_vregs)
2274   AM_RANGE(0xc40000, 0xc40001) AM_RAM
22962275   AM_RANGE(0xc80000, 0xc80001) AM_NOP
22972276
22982277
2299   AM_RANGE(0xcc0000, 0xcc0019) AM_READ(setaroul_c0_r)
2278   AM_RANGE(0xcc0000, 0xcc0019) AM_READ_PORT("UNK0") // rtc?
23002279
23012280   AM_RANGE(0xd00000, 0xd00001) AM_NOP // watchdog?
2302   AM_RANGE(0xd40000, 0xd40001) AM_READ(setaroul_d4_0_r)
2303   AM_RANGE(0xd40004, 0xd40005) AM_READ(setaroul_d4_4_r)
2304   AM_RANGE(0xd40006, 0xd40007) AM_READ(setaroul_d4_6_r)
2305   AM_RANGE(0xd40008, 0xd40009) AM_READ(setaroul_d4_8_r)
2306   AM_RANGE(0xd4000a, 0xd4000b) AM_READ(setaroul_d4_a_r)
2307   AM_RANGE(0xd40010, 0xd40011) AM_READ(setaroul_d4_10_r) AM_WRITENOP // multiplex?
2281   AM_RANGE(0xd40000, 0xd40001) AM_READ_PORT("UNK1")
2282   AM_RANGE(0xd40004, 0xd40005) AM_READ_PORT("UNK2")
2283   AM_RANGE(0xd40006, 0xd40007) AM_READ_PORT("UNK3")
2284   AM_RANGE(0xd40008, 0xd40009) AM_READ_PORT("UNK4")
2285   AM_RANGE(0xd4000a, 0xd4000b) AM_READ_PORT("UNK5")
2286   AM_RANGE(0xd40010, 0xd40011) AM_READ_PORT("UNK6") AM_WRITENOP // multiplex?
23082287
23092288   AM_RANGE(0xdc0000, 0xdc3fff) AM_RAM
23102289
23112290   AM_RANGE(0xe00000, 0xe03fff) AM_RAM_WRITE(seta_vram_0_w) AM_BASE_MEMBER(seta_state, m_vram_0   )   // VRAM - draws wheel if you reset enough times..
23122291   AM_RANGE(0xe40000, 0xe40005) AM_RAM AM_BASE_MEMBER(seta_state, m_vctrl_0)      // VRAM Ctrl
2313   AM_RANGE(0xf00000, 0xf03fff) AM_RAM
2314   AM_RANGE(0xf40000, 0xf40bff) AM_RAM // AM_WRITE(setaroul_spr_w) AM_BASE_MEMBER(seta_state, m_spriteram)      // Sprites Y
2315   AM_RANGE(0xf40c00, 0xf40c11) AM_RAM // AM_DEVREADWRITE("spritegen", spritectrl_r16, spritectrl_w16) // probably wrong hookup
2292   AM_RANGE(0xf00000, 0xf03fff) AM_READWRITE(setaroul_spritecode_r, setaroul_spritecode_w)
2293   AM_RANGE(0xf40000, 0xf40bff) AM_WRITE(setaroul_spriteylow_w)
2294   AM_RANGE(0xf40c00, 0xf40c11) AM_WRITE(setaroul_spritectrl_w)
23162295ADDRESS_MAP_END
23172296
23182297/***************************************************************************
r11450r11451
37693748***************************************************************************/
37703749
37713750static INPUT_PORTS_START( setaroul )
3751   PORT_START("UNK0")
3752    PORT_DIPNAME( 0x0001, 0x0001, "0" )
3753    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3754    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3755     PORT_BIT( 0x000e, IP_ACTIVE_HIGH, IPT_UNKNOWN ) // rtc?
3756    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
3757    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
3758    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3759    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
3760    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
3761    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3762    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
3763    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
3764    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3765    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
3766    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
3767    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3768    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
3769    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
3770    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3771    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
3772    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
3773    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3774    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
3775    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
3776    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3777    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
3778    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
3779    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3780    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
3781    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
3782    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3783    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
3784    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
3785    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3786    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
3787    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
3788    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3789    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
3790    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
3791    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3792
3793   PORT_START("UNK1")
3794    PORT_DIPNAME( 0x0001, 0x0001, "1" )
3795    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3796    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3797   PORT_DIPNAME( 0x0002, 0x0002, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("SW1:2")
3798   PORT_DIPSETTING(      0x0002, DEF_STR( Off ) )
3799   PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3800    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
3801    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
3802    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3803    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
3804    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
3805    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3806    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
3807    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
3808    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3809    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
3810    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
3811    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3812    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
3813    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
3814    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3815    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
3816    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
3817    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3818    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
3819    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
3820    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3821    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
3822    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
3823    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3824    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
3825    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
3826    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3827    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
3828    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
3829    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3830    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
3831    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
3832    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3833    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
3834    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
3835    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3836    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
3837    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
3838    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3839    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
3840    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
3841    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3842
3843   PORT_START("UNK2")
3844    PORT_DIPNAME( 0x0001, 0x0001, "2" )
3845    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3846    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3847    PORT_DIPNAME( 0x0002, 0x0002, DEF_STR( Unknown ) )
3848    PORT_DIPSETTING(      0x0002, DEF_STR( Off ) )
3849    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3850    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
3851    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
3852    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3853    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
3854    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
3855    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3856    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
3857    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
3858    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3859    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
3860    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
3861    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3862    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
3863    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
3864    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3865    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
3866    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
3867    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3868    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
3869    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
3870    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3871    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
3872    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
3873    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3874    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
3875    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
3876    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3877    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
3878    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
3879    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3880    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
3881    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
3882    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3883    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
3884    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
3885    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3886    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
3887    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
3888    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3889    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
3890    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
3891    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3892   
3893   PORT_START("UNK3")
3894    PORT_DIPNAME( 0x0001, 0x0001, "3" )
3895    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3896    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3897    PORT_DIPNAME( 0x0002, 0x0002, DEF_STR( Unknown ) )
3898    PORT_DIPSETTING(      0x0002, DEF_STR( Off ) )
3899    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3900    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
3901    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
3902    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3903    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
3904    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
3905    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3906    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
3907    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
3908    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3909    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
3910    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
3911    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3912    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
3913    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
3914    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3915    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
3916    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
3917    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3918    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
3919    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
3920    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3921    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
3922    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
3923    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3924    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
3925    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
3926    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3927    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
3928    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
3929    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3930    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
3931    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
3932    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3933    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
3934    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
3935    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3936    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
3937    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
3938    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3939    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
3940    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
3941    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3942   
3943   PORT_START("UNK4")
3944    PORT_DIPNAME( 0x0001, 0x0001, "4" )
3945    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3946    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3947   PORT_SERVICE( 0x0002, IP_ACTIVE_LOW) // 'reset switch'
3948    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
3949    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
3950    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3951    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
3952    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
3953    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3954    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
3955    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
3956    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3957    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
3958    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
3959    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3960
3961   // hold COIN1 and press COIN2 to get credits..  both bits must change! (coin must pass 2 sensors?)  gives a coinjam / timeout after a while if this doesn't happen..
3962   PORT_BIT( 0x0040, IP_ACTIVE_HIGH, IPT_COIN2 ) //
3963   PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_COIN1 ) // ^^
3964
3965    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
3966    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
3967    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3968    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
3969    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
3970    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3971    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
3972    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
3973    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3974    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
3975    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
3976    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3977    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
3978    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
3979    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3980    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
3981    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
3982    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3983    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
3984    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
3985    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3986    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
3987    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
3988    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3989   
3990   PORT_START("UNK5")
3991    PORT_DIPNAME( 0x0001, 0x0001, "5" )
3992    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
3993    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3994    PORT_DIPNAME( 0x0002, 0x0002, DEF_STR( Unknown ) )
3995    PORT_DIPSETTING(      0x0002, DEF_STR( Off ) )
3996    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
3997    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
3998    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
3999    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4000    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
4001    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
4002    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4003    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
4004    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
4005    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4006    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
4007    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
4008    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4009    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
4010    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
4011    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4012    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
4013    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
4014    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4015    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
4016    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
4017    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4018    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
4019    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
4020    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4021    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
4022    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
4023    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4024    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
4025    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
4026    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4027    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
4028    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
4029    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4030    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
4031    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
4032    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4033    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
4034    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
4035    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4036    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
4037    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
4038    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4039
4040   PORT_START("UNK6")
4041    PORT_DIPNAME( 0x0001, 0x0001, "6" )
4042    PORT_DIPSETTING(      0x0001, DEF_STR( Off ) )
4043    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4044    PORT_DIPNAME( 0x0002, 0x0002, DEF_STR( Unknown ) )
4045    PORT_DIPSETTING(      0x0002, DEF_STR( Off ) )
4046    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4047    PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Unknown ) )
4048    PORT_DIPSETTING(      0x0004, DEF_STR( Off ) )
4049    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4050    PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Unknown ) )
4051    PORT_DIPSETTING(      0x0008, DEF_STR( Off ) )
4052    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4053    PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Unknown ) )
4054    PORT_DIPSETTING(      0x0010, DEF_STR( Off ) )
4055    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4056    PORT_DIPNAME( 0x0020, 0x0020, DEF_STR( Unknown ) )
4057    PORT_DIPSETTING(      0x0020, DEF_STR( Off ) )
4058    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4059    PORT_DIPNAME( 0x0040, 0x0040, DEF_STR( Unknown ) )
4060    PORT_DIPSETTING(      0x0040, DEF_STR( Off ) )
4061    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4062    PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Unknown ) )
4063    PORT_DIPSETTING(      0x0080, DEF_STR( Off ) )
4064    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4065    PORT_DIPNAME( 0x0100, 0x0100, DEF_STR( Unknown ) )
4066    PORT_DIPSETTING(      0x0100, DEF_STR( Off ) )
4067    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4068    PORT_DIPNAME( 0x0200, 0x0200, DEF_STR( Unknown ) )
4069    PORT_DIPSETTING(      0x0200, DEF_STR( Off ) )
4070    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4071    PORT_DIPNAME( 0x0400, 0x0400, DEF_STR( Unknown ) )
4072    PORT_DIPSETTING(      0x0400, DEF_STR( Off ) )
4073    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4074    PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Unknown ) )
4075    PORT_DIPSETTING(      0x0800, DEF_STR( Off ) )
4076    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4077    PORT_DIPNAME( 0x1000, 0x1000, DEF_STR( Unknown ) )
4078    PORT_DIPSETTING(      0x1000, DEF_STR( Off ) )
4079    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4080    PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) )
4081    PORT_DIPSETTING(      0x2000, DEF_STR( Off ) )
4082    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4083    PORT_DIPNAME( 0x4000, 0x4000, DEF_STR( Unknown ) )
4084    PORT_DIPSETTING(      0x4000, DEF_STR( Off ) )
4085    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
4086    PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Unknown ) )
4087    PORT_DIPSETTING(      0x8000, DEF_STR( Off ) )
4088    PORT_DIPSETTING(      0x0000, DEF_STR( On ) )
37724089INPUT_PORTS_END
37734090
37744091
r11450r11451
67497066***************************************************************************/
67507067
67517068static GFXDECODE_START( setaroul )
6752   GFXDECODE_ENTRY( "gfx1", 0, layout_planes_2roms,       512*0, 2 ) // [0] Sprites
7069   GFXDECODE_ENTRY( "gfx1", 0, layout_planes_2roms,       0x100, 16 ) // [0] Sprites
67537070   GFXDECODE_ENTRY( "gfx2", 0, layout_8bpp, 512*0, 2 ) // [1] Layer 1
67547071GFXDECODE_END
67557072
r11450r11451
75677884
75687885   MCFG_DEVICE_ADD("spritegen", SETA001_SPRITE, 0)
75697886
7887   MCFG_NVRAM_ADD_RANDOM_FILL("nvram")
7888
75707889   /* video hardware */
75717890   MCFG_SCREEN_ADD("screen", RASTER)
75727891   MCFG_SCREEN_REFRESH_RATE(60)
r11450r11451
75747893   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_INDEXED16)
75757894   MCFG_SCREEN_SIZE(64*8, 32*8)
75767895   MCFG_SCREEN_VISIBLE_AREA(0*8, 48*8-1, 1*8, 31*8-1)
7577   MCFG_SCREEN_UPDATE(seta)
7578   MCFG_SCREEN_EOF(seta_buffer_sprites)   /* qzkklogy uses sprite buffering */
7896   MCFG_SCREEN_UPDATE(setaroul)
7897   MCFG_SCREEN_EOF(setaroul)   /* qzkklogy uses sprite buffering */
75797898
75807899   MCFG_GFXDECODE(setaroul)
75817900   MCFG_PALETTE_LENGTH(512)
r11450r11451
1008710406   ROM_LOAD16_BYTE( "uf1003.u16", 0x000001, 0x010000, CRC(a6afd769) SHA1(82c54c8a2219f20d08faf9f7afcf821d83511660) )
1008810407
1008910408   ROM_REGION( 0x020000, "gfx1", 0 )   /* Sprites */
10090   ROM_LOAD16_BYTE( "uf0005.u3", 0x000000, 0x008000, CRC(383c2d57) SHA1(3bbf0464f80f657dfa275e885fbce064a0a08f4a) )
10091   ROM_LOAD16_BYTE( "uf0006.u4", 0x000001, 0x008000, CRC(90c9dae6) SHA1(a226aab82f5b8174644281fa3efab4f8a8f8d827) )
10092   ROM_LOAD16_BYTE( "uf0007.u5", 0x010000, 0x008000, CRC(e72c3dba) SHA1(aaebb484e76d8f3da0ecff26c3c1bad4f3f11ac0) )
10093   ROM_LOAD16_BYTE( "uf0008.u6", 0x010001, 0x008000, CRC(e198e602) SHA1(f53fa36d1ea51239e71fe1ea7432bb4b7b8b3466) )
10409   ROM_LOAD16_BYTE( "uf0005.u3", 0x010001, 0x008000, CRC(383c2d57) SHA1(3bbf0464f80f657dfa275e885fbce064a0a08f4a) )
10410   ROM_LOAD16_BYTE( "uf0006.u4", 0x010000, 0x008000, CRC(90c9dae6) SHA1(a226aab82f5b8174644281fa3efab4f8a8f8d827) )
10411   ROM_LOAD16_BYTE( "uf0007.u5", 0x000001, 0x008000, CRC(e72c3dba) SHA1(aaebb484e76d8f3da0ecff26c3c1bad4f3f11ac0) )
10412   ROM_LOAD16_BYTE( "uf0008.u6", 0x000000, 0x008000, CRC(e198e602) SHA1(f53fa36d1ea51239e71fe1ea7432bb4b7b8b3466) )
1009410413
1009510414   ROM_REGION( 0x400000, "gfx2", 0 )   /* Layer 1 - 8bpp? */
1009610415   ROM_LOAD( "uf0010.u15",  0x000000, 0x080000, CRC(0af13a56) SHA1(c294b7947d004c0e0b280ca44636e4059e05a57e) )
r11450r11451
1040410723GAME( 1989, metafox,  0,        metafox,  metafox,  metafox,  ROT270, "Seta",                   "Meta Fox" , 0) // Country/License: DSW
1040510724
1040610725/* 68000 */
10407GAME( 198?, setaroul, 0,        setaroul, setaroul, 0,        ROT270, "Seta / Visco",           "Seta / Visco Roulette?", GAME_NOT_WORKING ) // I can't see a title in the GFX roms.  If you reset it enough times you'll get a flickery roulette wheel
10726GAME( 198?, setaroul, 0,        setaroul, setaroul, 0,        ROT270, "Visco",           "Visco Roulette", GAME_NOT_WORKING ) // I can't see a title in the GFX roms.  Press F2 twice to boot..
1040810727GAME( 1989, drgnunit, 0,        drgnunit, drgnunit, 0,        ROT0,   "Seta",                   "Dragon Unit / Castle of Dragon", 0 )
1040910728GAME( 1989, wits,     0,        wits,     wits,     0,        ROT0,   "Athena (Visco license)", "Wit's (Japan)" , 0) // Country/License: DSW
1041010729GAME( 1990, thunderl, 0,        thunderl, thunderl, 0,        ROT270, "Seta",                   "Thunder & Lightning" , 0) // Country/License: DSW
src/mame/drivers/champbwl.c
r11450r11451
203203   AM_RANGE(0xb000, 0xbfff) AM_RAM AM_DEVREADWRITE("spritegen", spritecodehigh_r8, spritecodehigh_w8)
204204   AM_RANGE(0xc000, 0xdfff) AM_DEVREADWRITE("x1snd", seta_sound_r, seta_sound_w)
205205   AM_RANGE(0xe000, 0xe2ff) AM_RAM AM_DEVREADWRITE("spritegen", spriteylow_r8, spriteylow_w8)
206   AM_RANGE(0xe300, 0xe303) AM_MIRROR(0xfc) AM_DEVWRITE("spritegen", spritectrl_w8_champbwl) /* control registers (0x80 mirror used by Arkanoid 2) */
206   AM_RANGE(0xe300, 0xe303) AM_MIRROR(0xfc) AM_DEVWRITE("spritegen", spritectrl_w8) /* control registers (0x80 mirror used by Arkanoid 2) */
207207   AM_RANGE(0xe800, 0xe800) AM_DEVWRITE("spritegen", spritebgflag_w8)   /* enable / disable background transparency */
208208
209209   AM_RANGE(0xf000, 0xf000) AM_READ(trackball_r)
src/mame/drivers/segasms.c
r0r11451
1/******************************************************************************
2 Contributors:
3
4    Marat Fayzullin (MG source)
5    Charles Mac Donald
6    Mathis Rosenhauer
7    Brad Oliver
8    Michael Luong
9
10 To do:
11
12 - PSG control for Game Gear (needs custom SN76489 with stereo output for each channel)
13 - SIO interface for Game Gear (needs netplay, I guess)
14 - SMS lightgun support
15 - LCD persistence emulation for GG
16 - SMS 3D glass support
17
18 The Game Gear SIO and PSG hardware are not emulated but have some
19 placeholders in 'machine/sms.c'
20
21 Changes:
22    Apr 02 - Added raster palette effects for SMS & GG (ML)
23                 - Added sprite collision (ML)
24                 - Added zoomed sprites (ML)
25    May 02 - Fixed paging bug (ML)
26                 - Fixed sprite and tile priority bug (ML)
27                 - Fixed bug #66 (ML)
28                 - Fixed bug #78 (ML)
29                 - try to implement LCD persistence emulation for GG (ML)
30    Jun 10, 02 - Added bios emulation (ML)
31    Jun 12, 02 - Added PAL & NTSC systems (ML)
32    Jun 25, 02 - Added border emulation (ML)
33    Jun 27, 02 - Version bits for Game Gear (bits 6 of port 00) (ML)
34    Nov-Dec, 05 - Numerous cleanups, fixes, updates (WP)
35    Mar, 07 - More cleanups, fixes, mapper additions, etc (WP)
36
37SMS Store Unit memory map for the second CPU:
38
390000-3FFF - BIOS
404000-47FF - RAM
418000      - System Control Register (R/W)
42            Reading:
43            bit7      - ready (0 = ready, 1 = not ready)
44            bit6-bit5 - unknown
45            bit4-bit3 - timer selection bit switches
46            bit2-bit0 - unknown
47            Writing:
48            bit7-bit4 - unknown, maybe led of selected game to set?
49            bit3      - unknown, 1 seems to be written all the time
50            bit2      - unknown, 1 seems to be written all the time
51            bit1      - reset signal for sms cpu, 0 = reset low, 1 = reset high
52            bit0      - which cpu receives interrupt signals, 0 = sms cpu, 1 = controlling cpu
53C000      - Card/Cartridge selction register (W)
54            bit7-bit4 - slot to select
55            bit3      - slot type (0 = cartridge, 1 = card ?)
56            bit2-bit0 - unknown
57C400      - ???? (used once)
58D800      - Selection buttons #1, 1-8 (R)
59DC00      - Selection buttons #2, 9-16 (R)
60
61 ******************************************************************************/
62
63#include "emu.h"
64#include "cpu/z80/z80.h"
65#include "sound/sn76496.h"
66#include "sound/2413intf.h"
67#include "includes/segasms.h"
68#include "video/smsvdp.h"
69#include "imagedev/cartslot.h"
70
71#include "sms1.lh"
72
73#define MASTER_CLOCK_PAL   53203400   /* This might be a tiny bit too low */
74
75
76static ADDRESS_MAP_START( sms1_mem, AS_PROGRAM, 8 )
77   AM_RANGE(0x0000, 0x03ff) AM_ROMBANK("bank1")               /* First 0x0400 part always points to first page */
78   AM_RANGE(0x0400, 0x3fff) AM_ROMBANK("bank2")               /* switchable rom bank */
79   AM_RANGE(0x4000, 0x5fff) AM_ROMBANK("bank3")               /* switchable rom bank */
80   AM_RANGE(0x6000, 0x7fff) AM_ROMBANK("bank4")               /* switchable rom bank */
81   AM_RANGE(0x8000, 0x9fff) AM_READ_BANK("bank5") AM_WRITE(sms_cartram_w)   /* ROM bank / on-cart RAM */
82   AM_RANGE(0xa000, 0xbfff) AM_READ_BANK("bank6") AM_WRITE(sms_cartram2_w)   /* ROM bank / on-cart RAM */
83   AM_RANGE(0xc000, 0xdff7) AM_MIRROR(0x2000) AM_RAM         /* RAM (mirror at 0xE000) */
84   AM_RANGE(0xdff8, 0xdfff) AM_RAM                  /* RAM "underneath" frame registers */
85   AM_RANGE(0xfff8, 0xfffb) AM_READWRITE(sms_sscope_r, sms_sscope_w)   /* 3-D glasses */
86   AM_RANGE(0xfffc, 0xffff) AM_READWRITE(sms_mapper_r, sms_mapper_w)   /* Bankswitch control */
87ADDRESS_MAP_END
88
89static ADDRESS_MAP_START( sms_mem, AS_PROGRAM, 8 )
90   AM_RANGE(0x0000, 0x03ff) AM_ROMBANK("bank1")               /* First 0x0400 part always points to first page */
91   AM_RANGE(0x0400, 0x3fff) AM_ROMBANK("bank2")               /* switchable rom bank */
92   AM_RANGE(0x4000, 0x5fff) AM_ROMBANK("bank3")               /* switchable rom bank */
93   AM_RANGE(0x6000, 0x7fff) AM_ROMBANK("bank4")               /* switchable rom bank */
94   AM_RANGE(0x8000, 0x9fff) AM_READ_BANK("bank5") AM_WRITE(sms_cartram_w)   /* ROM bank / on-cart RAM */
95   AM_RANGE(0xa000, 0xbfff) AM_READ_BANK("bank6") AM_WRITE(sms_cartram2_w)   /* ROM bank / on-cart RAM */
96   AM_RANGE(0xc000, 0xdffb) AM_MIRROR(0x2000) AM_RAM         /* RAM (mirror at 0xE000) */
97   AM_RANGE(0xdffc, 0xdfff) AM_RAM                  /* RAM "underneath" frame registers */
98   AM_RANGE(0xfffc, 0xffff) AM_READWRITE(sms_mapper_r, sms_mapper_w)   /* Bankswitch control */
99ADDRESS_MAP_END
100
101static ADDRESS_MAP_START( sms_store_mem, AS_PROGRAM, 8 )
102   AM_RANGE(0x0000, 0x3fff) AM_ROM                  /* BIOS */
103   AM_RANGE(0x4000, 0x47ff) AM_RAM                  /* RAM */
104   AM_RANGE(0x6000, 0x7fff) AM_ROMBANK("bank10")               /* Cartridge/card peek area */
105   AM_RANGE(0x8000, 0x8000) AM_READWRITE(sms_store_control_r, sms_store_control_w)   /* Control */
106   AM_RANGE(0xc000, 0xc000) AM_READWRITE(sms_store_cart_select_r, sms_store_cart_select_w)    /* cartridge/card slot selector */
107   AM_RANGE(0xd800, 0xd800) AM_READ(sms_store_select1)         /* Game selector port #1 */
108   AM_RANGE(0xdc00, 0xdc00) AM_READ(sms_store_select2)         /* Game selector port #2 */
109ADDRESS_MAP_END
110
111static ADDRESS_MAP_START( sms_io, AS_IO, 8 )
112   ADDRESS_MAP_GLOBAL_MASK(0xff)
113   ADDRESS_MAP_UNMAP_HIGH
114   AM_RANGE(0x00, 0x00) AM_MIRROR(0x3e) AM_WRITE(sms_bios_w)
115   AM_RANGE(0x01, 0x01) AM_MIRROR(0x3e) AM_WRITE(sms_io_control_w)
116   AM_RANGE(0x40, 0x7f)                 AM_READ(sms_count_r)
117   AM_RANGE(0x40, 0x7f)                 AM_DEVWRITE("smsiii", sn76496_w)
118   AM_RANGE(0x80, 0x80) AM_MIRROR(0x3e) AM_DEVREADWRITE("sms_vdp", sms_vdp_data_r, sms_vdp_data_w)
119   AM_RANGE(0x81, 0x81) AM_MIRROR(0x3e) AM_DEVREADWRITE("sms_vdp", sms_vdp_ctrl_r, sms_vdp_ctrl_w)
120   AM_RANGE(0xc0, 0xc0) AM_MIRROR(0x1e) AM_READ(sms_input_port_0_r)
121   AM_RANGE(0xc1, 0xc1) AM_MIRROR(0x1e) AM_READ(sms_input_port_1_r)
122   AM_RANGE(0xe0, 0xe0) AM_MIRROR(0x0e) AM_READ(sms_input_port_0_r)
123   AM_RANGE(0xe1, 0xe1) AM_MIRROR(0x0e) AM_READ(sms_input_port_1_r)
124   AM_RANGE(0xf0, 0xf0)                 AM_READWRITE(sms_input_port_0_r, sms_ym2413_register_port_0_w)
125   AM_RANGE(0xf1, 0xf1)                 AM_READWRITE(sms_input_port_1_r, sms_ym2413_data_port_0_w)
126   AM_RANGE(0xf2, 0xf2)                 AM_READWRITE(sms_fm_detect_r, sms_fm_detect_w)
127   AM_RANGE(0xf3, 0xf3)                 AM_READ(sms_input_port_1_r)
128   AM_RANGE(0xf4, 0xf4) AM_MIRROR(0x02) AM_READ(sms_input_port_0_r)
129   AM_RANGE(0xf5, 0xf5) AM_MIRROR(0x02) AM_READ(sms_input_port_1_r)
130   AM_RANGE(0xf8, 0xf8) AM_MIRROR(0x06) AM_READ(sms_input_port_0_r)
131   AM_RANGE(0xf9, 0xf9) AM_MIRROR(0x06) AM_READ(sms_input_port_1_r)
132ADDRESS_MAP_END
133
134static ADDRESS_MAP_START( gg_io, AS_IO, 8 )
135   ADDRESS_MAP_GLOBAL_MASK(0xff)
136   ADDRESS_MAP_UNMAP_HIGH
137   AM_RANGE(0x00, 0x00)                 AM_READ(gg_input_port_2_r)
138   AM_RANGE(0x01, 0x05)                 AM_READWRITE(gg_sio_r, gg_sio_w)
139   AM_RANGE(0x06, 0x06)                 AM_DEVWRITE("gamegear", sn76496_stereo_w)
140   AM_RANGE(0x07, 0x07)                 AM_WRITE(sms_io_control_w)
141   AM_RANGE(0x08, 0x08) AM_MIRROR(0x06) AM_WRITE(sms_bios_w)
142   AM_RANGE(0x09, 0x09) AM_MIRROR(0x06) AM_WRITE(sms_io_control_w)
143   AM_RANGE(0x10, 0x10) AM_MIRROR(0x0e) AM_WRITE(sms_bios_w)
144   AM_RANGE(0x11, 0x11) AM_MIRROR(0x0e) AM_WRITE(sms_io_control_w)
145   AM_RANGE(0x20, 0x20) AM_MIRROR(0x1e) AM_WRITE(sms_bios_w)
146   AM_RANGE(0x21, 0x21) AM_MIRROR(0x1e) AM_WRITE(sms_io_control_w)
147   AM_RANGE(0x40, 0x7f)                 AM_READ(sms_count_r)
148   AM_RANGE(0x40, 0x7f)                 AM_DEVWRITE("gamegear", sn76496_w)
149   AM_RANGE(0x80, 0x80) AM_MIRROR(0x3e) AM_DEVREADWRITE("sms_vdp", sms_vdp_data_r, sms_vdp_data_w)
150   AM_RANGE(0x81, 0x81) AM_MIRROR(0x3e) AM_DEVREADWRITE("sms_vdp", sms_vdp_ctrl_r, sms_vdp_ctrl_w)
151   AM_RANGE(0xc0, 0xc0)                 AM_READ_PORT("PORT_DC")
152   AM_RANGE(0xc1, 0xc1)                 AM_READ_PORT("PORT_DD")
153   AM_RANGE(0xdc, 0xdc)                 AM_READ_PORT("PORT_DC")
154   AM_RANGE(0xdd, 0xdd)                 AM_READ_PORT("PORT_DD")
155ADDRESS_MAP_END
156
157
158static INPUT_PORTS_START( sms )
159   PORT_START("PORT_DC")
160   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_CATEGORY(10) PORT_PLAYER(1) PORT_8WAY
161   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_CATEGORY(10) PORT_PLAYER(1) PORT_8WAY
162   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_CATEGORY(10) PORT_PLAYER(1) PORT_8WAY
163   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_CATEGORY(10) PORT_PLAYER(1) PORT_8WAY
164   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(10) PORT_PLAYER(1)
165   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CATEGORY(10) PORT_PLAYER(1)
166   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_CATEGORY(20) PORT_PLAYER(2) PORT_8WAY
167   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_CATEGORY(20) PORT_PLAYER(2) PORT_8WAY
168
169   PORT_START("PORT_DD")
170   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_CATEGORY(20) PORT_PLAYER(2) PORT_8WAY
171   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_CATEGORY(20) PORT_PLAYER(2) PORT_8WAY
172   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(20) PORT_PLAYER(2)
173   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CATEGORY(20) PORT_PLAYER(2)
174   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED ) /* Software Reset bit */
175   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNUSED )
176   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNUSED ) /* Port A TH */
177   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED ) /* Port B TH */
178
179   PORT_START("PAUSE")
180   PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
181   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START ) PORT_NAME(DEF_STR(Pause))
182
183   PORT_START("LPHASER0")   /* Light phaser X - player 1 */
184   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_X ) PORT_CROSSHAIR( X, 1.0, 0.0, 0 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(15) PORT_CATEGORY(11) PORT_PLAYER(1) PORT_CHANGED(lgun1_changed, NULL)
185
186   PORT_START("LPHASER1")   /* Light phaser Y - player 1 */
187   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_Y ) PORT_CROSSHAIR( Y, 1.0, 0.0, 0 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(15) PORT_CATEGORY(11) PORT_PLAYER(1) PORT_CHANGED(lgun1_changed, NULL)
188
189   PORT_START("LPHASER2")   /* Light phaser X - player 2 */
190   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_X ) PORT_CROSSHAIR( X, 1.0, 0.0, 0 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(15) PORT_CATEGORY(21) PORT_PLAYER(2) PORT_CHANGED(lgun2_changed, NULL)
191
192   PORT_START("LPHASER3")   /* Light phaser Y - player 2 */
193   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_Y ) PORT_CROSSHAIR( Y, 1.0, 0.0, 0 ) PORT_SENSITIVITY(50) PORT_KEYDELTA(25) PORT_CATEGORY(21) PORT_PLAYER(2) PORT_CHANGED(lgun2_changed, NULL)
194
195   PORT_START("RFU")   /* Rapid Fire Unit */
196   PORT_CONFNAME( 0x03, 0x00, "Rapid Fire Unit - Player 1" )
197   PORT_CONFSETTING(   0x00, DEF_STR( Off ) )
198   PORT_CONFSETTING(   0x01, "Button A" )
199   PORT_CONFSETTING(   0x02, "Button B" )
200   PORT_CONFSETTING(   0x03, "Button A + B" )
201   PORT_CONFNAME( 0x0c, 0x00, "Rapid Fire Unit - Player 2" )
202   PORT_CONFSETTING(   0x00, DEF_STR( Off ) )
203   PORT_CONFSETTING(   0x04, "Button A" )
204   PORT_CONFSETTING(   0x08, "Button B" )
205   PORT_CONFSETTING(   0x0c, "Button A + B" )
206
207   PORT_START("PADDLE0")   /* Paddle player 1 */
208   PORT_BIT( 0xff, 0x80, IPT_PADDLE) PORT_SENSITIVITY(40) PORT_KEYDELTA(20) PORT_CENTERDELTA(0) PORT_MINMAX(0,255) PORT_CATEGORY(12) PORT_PLAYER(1)
209
210   PORT_START("PADDLE1")   /* Paddle player 2 */
211   PORT_BIT( 0xff, 0x80, IPT_PADDLE) PORT_SENSITIVITY(40) PORT_KEYDELTA(20) PORT_CENTERDELTA(0) PORT_MINMAX(0,255) PORT_CATEGORY(22) PORT_PLAYER(2)
212
213   PORT_START("CTRLIPT")   /* Light Phaser and Paddle Control buttons */
214   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(11) PORT_PLAYER(1)
215   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(12) PORT_PLAYER(1)
216   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(13) PORT_PLAYER(1)
217   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CATEGORY(13) PORT_PLAYER(1)
218   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(21) PORT_PLAYER(2)
219   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(22) PORT_PLAYER(2)
220   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_CATEGORY(23) PORT_PLAYER(2)
221   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_CATEGORY(23) PORT_PLAYER(2)
222
223   PORT_START("CTRLSEL")   /* Controller selection */
224   PORT_CATEGORY_CLASS( 0x0f, 0x00, "Player 1 Controller" )
225   PORT_CATEGORY_ITEM( 0x00, DEF_STR( Joystick ), 10 )
226   PORT_CATEGORY_ITEM( 0x01, "Light Phaser", 11 )
227   PORT_CATEGORY_ITEM( 0x02, "Sega Paddle Control", 12 )
228   PORT_CATEGORY_ITEM( 0x03, "Sega Sports Pad", 13 )
229   PORT_CATEGORY_CLASS( 0xf0, 0x00, "Player 2 Controller" )
230   PORT_CATEGORY_ITEM( 0x00, DEF_STR( Joystick ), 20 )
231   PORT_CATEGORY_ITEM( 0x10, "Light Phaser", 21 )
232   PORT_CATEGORY_ITEM( 0x20, "Sega Paddle Control", 22 )
233   PORT_CATEGORY_ITEM( 0x30, "Sega Sports Pad", 23 )
234
235   PORT_START("SPORT0")   /* Player 1 Sports Pad X axis */
236   PORT_BIT( 0xff, 0x00, IPT_TRACKBALL_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(40) PORT_RESET PORT_REVERSE PORT_CATEGORY(13) PORT_PLAYER(1)
237
238   PORT_START("SPORT1")   /* Player 1 Sports Pad Y axis */
239   PORT_BIT( 0xff, 0x00, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(40) PORT_RESET PORT_REVERSE PORT_CATEGORY(13) PORT_PLAYER(1)
240
241   PORT_START("SPORT2")   /* Player 2 Sports Pad X axis */
242   PORT_BIT( 0xff, 0x00, IPT_TRACKBALL_X ) PORT_SENSITIVITY(50) PORT_KEYDELTA(40) PORT_RESET PORT_REVERSE PORT_CATEGORY(23) PORT_PLAYER(2)
243
244   PORT_START("SPORT3")   /* Player 2 Sports Pad Y axis */
245   PORT_BIT( 0xff, 0x00, IPT_TRACKBALL_Y ) PORT_SENSITIVITY(50) PORT_KEYDELTA(40) PORT_RESET PORT_REVERSE PORT_CATEGORY(23) PORT_PLAYER(2)
246INPUT_PORTS_END
247
248static INPUT_PORTS_START( sms1 )
249   PORT_INCLUDE( sms )
250
251   PORT_START("RESET")
252   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_NAME("Reset Button")
253
254   PORT_START("SEGASCOPE")
255   PORT_CONFNAME( 0x01, 0x00, "SegaScope (3-D Glasses)" )
256   PORT_CONFSETTING( 0x00, DEF_STR( Off ) )
257   PORT_CONFSETTING( 0x01, DEF_STR( On ) )
258
259   PORT_START("SSCOPE_BINOCULAR")
260   PORT_CONFNAME( 0x03, 0x00, "SegaScope - Binocular Hack" ) PORT_CONDITION("SEGASCOPE", 0x01, PORTCOND_EQUALS, 0x01)
261   PORT_CONFSETTING( 0x00, DEF_STR( Off ) )
262   PORT_CONFSETTING( 0x01, "Left Lens" )
263   PORT_CONFSETTING( 0x02, "Right Lens" )
264   PORT_CONFSETTING( 0x03, "Both Lens" )
265   PORT_BIT( 0x03, 0x00, IPT_UNUSED ) PORT_CONDITION("SEGASCOPE", 0x01, PORTCOND_EQUALS, 0x00)
266INPUT_PORTS_END
267
268static INPUT_PORTS_START( smsj )
269   PORT_INCLUDE( sms1 )
270
271   PORT_START("TVDRAW")
272   PORT_CONFNAME( 0x01, 0x00, "Terebi Oekaki Graphics Tablet" )
273   PORT_CONFSETTING( 0x00, DEF_STR( Off ) )
274   PORT_CONFSETTING( 0x01, DEF_STR( On ) )
275
276   PORT_START("TVDRAW_X")
277   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_X ) PORT_NAME("Tablet - X Axis") PORT_CROSSHAIR(X, 1.0, 0.0, 0) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_PLAYER(1)
278      PORT_CONDITION("TVDRAW", 0x01, PORTCOND_EQUALS, 0x01)
279
280   PORT_START("TVDRAW_Y")
281   PORT_BIT( 0xff, 0x60, IPT_LIGHTGUN_Y ) PORT_NAME("Tablet - Y Axis") PORT_CROSSHAIR(Y, 1.0, 0.0, 0) PORT_MINMAX(0, 191) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_PLAYER(1)
282      PORT_CONDITION("TVDRAW", 0x01, PORTCOND_EQUALS, 0x01)
283
284   PORT_START("TVDRAW_PEN")
285   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Tablet - Pen") PORT_CONDITION("TVDRAW", 0x01, PORTCOND_EQUALS, 0x01)
286INPUT_PORTS_END
287
288static INPUT_PORTS_START( gg )
289   PORT_START("PORT_DC")
290   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(1) PORT_8WAY
291   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(1) PORT_8WAY
292   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(1) PORT_8WAY
293   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(1) PORT_8WAY
294   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1)
295   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1)
296   PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
297
298   PORT_START("PORT_DD")
299   PORT_BIT( 0xff, IP_ACTIVE_LOW, IPT_UNUSED )
300
301   PORT_START("START")
302   PORT_BIT( 0x7f, IP_ACTIVE_LOW, IPT_UNUSED )
303   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_START ) PORT_NAME("Start") /* Game Gear START */
304INPUT_PORTS_END
305
306static PALETTE_INIT( sms )
307{
308   int i;
309   for (i = 0; i < 64; i++)
310   {
311      int r = i & 0x03;
312      int g = (i & 0x0c) >> 2;
313      int b = (i & 0x30) >> 4;
314      palette_set_color_rgb(machine, i, r << 6, g << 6, b << 6);
315   }
316   /* TMS9918 palette */
317   palette_set_color_rgb(machine, 64+ 0,   0,   0,   0);
318   palette_set_color_rgb(machine, 64+ 1,   0,   0,   0);
319   palette_set_color_rgb(machine, 64+ 2,  33, 200,  66);
320   palette_set_color_rgb(machine, 64+ 3,  94, 220, 120);
321   palette_set_color_rgb(machine, 64+ 4,  84,  85, 237);
322   palette_set_color_rgb(machine, 64+ 5, 125, 118, 252);
323   palette_set_color_rgb(machine, 64+ 6, 212,  82,  77);
324   palette_set_color_rgb(machine, 64+ 7,  66, 235, 245);
325   palette_set_color_rgb(machine, 64+ 8, 252,  85,  84);
326   palette_set_color_rgb(machine, 64+ 9, 255, 121, 120);
327   palette_set_color_rgb(machine, 64+10, 212, 193,  84);
328   palette_set_color_rgb(machine, 64+11, 230, 206, 128);
329   palette_set_color_rgb(machine, 64+12,  33, 176,  59);
330   palette_set_color_rgb(machine, 64+13, 201,  91, 186);
331   palette_set_color_rgb(machine, 64+14, 204, 204, 204);
332   palette_set_color_rgb(machine, 64+15, 255, 255, 255);
333}
334
335static PALETTE_INIT( gamegear )
336{
337   int i;
338   for (i = 0; i < 4096; i++)
339   {
340      int r = i & 0x000f;
341      int g = (i & 0x00f0) >> 4;
342      int b = (i & 0x0f00) >> 8;
343      palette_set_color_rgb(machine, i, r << 4, g << 4, b << 4);
344   }
345}
346
347
348
349static void sms_int_callback( running_machine &machine, int state )
350{
351   cputag_set_input_line(machine, "maincpu", 0, state);
352}
353
354static const smsvdp_interface _315_5124_intf =
355{
356   MODEL_315_5124,
357   sms_int_callback,
358   sms_pause_callback
359};
360
361static const smsvdp_interface _315_5246_intf =
362{
363   MODEL_315_5246,
364   sms_int_callback,
365   sms_pause_callback
366};
367
368static const smsvdp_interface _315_5378_intf =
369{
370   MODEL_315_5378,
371   sms_int_callback,
372   sms_pause_callback
373};
374
375static const smsvdp_interface sms_store_intf =
376{
377   MODEL_315_5124,
378   sms_store_int_callback,
379   sms_pause_callback
380};
381
382static MACHINE_CONFIG_FRAGMENT( sms_cartslot )
383   MCFG_CARTSLOT_ADD("cart1")
384   MCFG_CARTSLOT_EXTENSION_LIST("sms,bin")
385   MCFG_CARTSLOT_NOT_MANDATORY
386   MCFG_CARTSLOT_INTERFACE("sms_cart")
387   MCFG_CARTSLOT_START(sms_cart)
388   MCFG_CARTSLOT_LOAD(sms_cart)
389
390   MCFG_SOFTWARE_LIST_ADD("cart_list","sms")
391MACHINE_CONFIG_END
392
393static MACHINE_CONFIG_FRAGMENT( gg_cartslot )
394   MCFG_CARTSLOT_ADD("cart1")
395   MCFG_CARTSLOT_EXTENSION_LIST("gg,bin")
396   MCFG_CARTSLOT_MANDATORY
397   MCFG_CARTSLOT_INTERFACE("gamegear_cart")
398   MCFG_CARTSLOT_START(sms_cart)
399   MCFG_CARTSLOT_LOAD(sms_cart)
400
401   MCFG_SOFTWARE_LIST_ADD("cart_list","gamegear")
402MACHINE_CONFIG_END
403
404static MACHINE_CONFIG_START( sms_ntsc_base, sms_state )
405   /* basic machine hardware */
406   MCFG_CPU_ADD("maincpu", Z80, XTAL_53_693175MHz/15)
407   MCFG_CPU_PROGRAM_MAP(sms_mem)
408   MCFG_CPU_IO_MAP(sms_io)
409
410   MCFG_QUANTUM_TIME(attotime::from_hz(60))
411
412   MCFG_MACHINE_START(sms)
413   MCFG_MACHINE_RESET(sms)
414
415   /* sound hardware */
416   MCFG_SPEAKER_STANDARD_MONO("mono")
417   MCFG_SOUND_ADD("smsiii", SMSIII, XTAL_53_693175MHz/15)
418   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
419
420   MCFG_FRAGMENT_ADD( sms_cartslot )
421MACHINE_CONFIG_END
422
423static MACHINE_CONFIG_DERIVED( sms2_ntsc, sms_ntsc_base )
424   /* video hardware */
425   MCFG_SCREEN_ADD("screen", RASTER)
426   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
427   MCFG_SCREEN_RAW_PARAMS(XTAL_53_693175MHz/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, NTSC_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS + 224)
428   MCFG_SCREEN_UPDATE(sms)
429
430   MCFG_PALETTE_LENGTH(64+16)
431   MCFG_PALETTE_INIT(sms)
432
433   MCFG_SMSVDP_ADD("sms_vdp", _315_5246_intf)
434MACHINE_CONFIG_END
435
436static MACHINE_CONFIG_DERIVED( sms1_ntsc, sms_ntsc_base )
437
438   MCFG_CPU_MODIFY("maincpu")
439   MCFG_CPU_PROGRAM_MAP(sms1_mem)   // This adds the SegaScope handlers for 3-D glasses
440   MCFG_CPU_IO_MAP(sms_io)
441
442   /* video hardware */
443   MCFG_SCREEN_ADD("screen", RASTER)
444   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
445   MCFG_SCREEN_RAW_PARAMS(XTAL_53_693175MHz/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, NTSC_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS + 224)
446   MCFG_SCREEN_UPDATE(sms1)
447
448   MCFG_SCREEN_ADD("left_lcd", LCD)   // This is needed for SegaScope Left LCD
449   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
450   MCFG_SCREEN_RAW_PARAMS(XTAL_53_693175MHz/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, NTSC_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS + 224)
451   MCFG_SCREEN_UPDATE(sms1)
452
453   MCFG_SCREEN_ADD("right_lcd", LCD)   // This is needed for SegaScope Right LCD
454   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
455   MCFG_SCREEN_RAW_PARAMS(XTAL_53_693175MHz/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, NTSC_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS, TBORDER_START + NTSC_224_TBORDER_Y_PIXELS + 224)
456   MCFG_SCREEN_UPDATE(sms1)
457
458   MCFG_DEFAULT_LAYOUT(layout_sms1)
459
460   MCFG_PALETTE_LENGTH(64+16)
461   MCFG_PALETTE_INIT(sms)
462
463   MCFG_VIDEO_START(sms1)
464
465   MCFG_SMSVDP_ADD("sms_vdp", _315_5124_intf)
466MACHINE_CONFIG_END
467
468#define MCFG_SMSSDISP_CARTSLOT_ADD(_tag) \
469   MCFG_CARTSLOT_ADD(_tag) \
470   MCFG_CARTSLOT_EXTENSION_LIST("sms,bin") \
471   MCFG_CARTSLOT_NOT_MANDATORY \
472   MCFG_CARTSLOT_INTERFACE("sms_cart") \
473   MCFG_CARTSLOT_START(sms_cart) \
474   MCFG_CARTSLOT_LOAD(sms_cart)
475
476static MACHINE_CONFIG_DERIVED( sms_sdisp, sms2_ntsc )
477
478   MCFG_DEVICE_REMOVE("sms_vdp")
479   MCFG_SMSVDP_ADD("sms_vdp", sms_store_intf)
480
481   MCFG_CPU_ADD("control", Z80, XTAL_53_693175MHz/15)
482   MCFG_CPU_PROGRAM_MAP(sms_store_mem)
483   /* Both CPUs seem to communicate with the VDP etc? */
484   MCFG_CPU_IO_MAP(sms_io)
485
486   MCFG_CARTSLOT_MODIFY("cart1")
487   MCFG_CARTSLOT_EXTENSION_LIST("sms,bin")
488   MCFG_CARTSLOT_MANDATORY
489   MCFG_CARTSLOT_INTERFACE("sms_cart")
490   MCFG_CARTSLOT_START(sms_cart)
491   MCFG_CARTSLOT_LOAD(sms_cart)
492
493   MCFG_SMSSDISP_CARTSLOT_ADD("cart2")
494   MCFG_SMSSDISP_CARTSLOT_ADD("cart3")
495   MCFG_SMSSDISP_CARTSLOT_ADD("cart4")
496   MCFG_SMSSDISP_CARTSLOT_ADD("cart5")
497   MCFG_SMSSDISP_CARTSLOT_ADD("cart6")
498   MCFG_SMSSDISP_CARTSLOT_ADD("cart7")
499   MCFG_SMSSDISP_CARTSLOT_ADD("cart8")
500   MCFG_SMSSDISP_CARTSLOT_ADD("cart9")
501   MCFG_SMSSDISP_CARTSLOT_ADD("cart10")
502   MCFG_SMSSDISP_CARTSLOT_ADD("cart11")
503   MCFG_SMSSDISP_CARTSLOT_ADD("cart12")
504   MCFG_SMSSDISP_CARTSLOT_ADD("cart13")
505   MCFG_SMSSDISP_CARTSLOT_ADD("cart14")
506   MCFG_SMSSDISP_CARTSLOT_ADD("cart15")
507   MCFG_SMSSDISP_CARTSLOT_ADD("cart16")
508MACHINE_CONFIG_END
509
510static MACHINE_CONFIG_START( sms_pal_base, sms_state )
511   /* basic machine hardware */
512   MCFG_CPU_ADD("maincpu", Z80, MASTER_CLOCK_PAL/15)
513   MCFG_CPU_PROGRAM_MAP(sms_mem)
514   MCFG_CPU_IO_MAP(sms_io)
515
516   MCFG_QUANTUM_TIME(attotime::from_hz(60))
517
518   MCFG_MACHINE_START(sms)
519   MCFG_MACHINE_RESET(sms)
520
521   /* sound hardware */
522   MCFG_SPEAKER_STANDARD_MONO("mono")
523   MCFG_SOUND_ADD("smsiii", SMSIII, MASTER_CLOCK_PAL/15)
524   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
525
526   MCFG_FRAGMENT_ADD( sms_cartslot )
527MACHINE_CONFIG_END
528
529static MACHINE_CONFIG_DERIVED( sms2_pal, sms_pal_base )
530
531   /* video hardware */
532   MCFG_SCREEN_ADD("screen", RASTER)
533   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
534   MCFG_SCREEN_RAW_PARAMS(MASTER_CLOCK_PAL/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, PAL_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS + 240)
535   MCFG_SCREEN_UPDATE(sms)
536
537   MCFG_PALETTE_LENGTH(64+16)
538   MCFG_PALETTE_INIT(sms)
539
540   MCFG_SMSVDP_ADD("sms_vdp", _315_5246_intf)
541MACHINE_CONFIG_END
542
543static MACHINE_CONFIG_DERIVED( sms1_pal, sms_pal_base )
544
545   MCFG_CPU_MODIFY("maincpu")
546   MCFG_CPU_PROGRAM_MAP(sms1_mem)   // This adds the SegaScope handlers for 3-D glasses
547   MCFG_CPU_IO_MAP(sms_io)
548
549   /* video hardware */
550   MCFG_SCREEN_ADD("screen", RASTER)
551   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
552   MCFG_SCREEN_RAW_PARAMS(MASTER_CLOCK_PAL/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, PAL_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS + 240)
553   MCFG_SCREEN_UPDATE(sms1)
554
555   MCFG_SCREEN_ADD("left_lcd", LCD)   // This is needed for SegaScope Left LCD
556   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
557   MCFG_SCREEN_RAW_PARAMS(MASTER_CLOCK_PAL/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, PAL_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS + 240)
558   MCFG_SCREEN_UPDATE(sms1)
559
560   MCFG_SCREEN_ADD("right_lcd", LCD)   // This is needed for SegaScope Right LCD
561   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
562   MCFG_SCREEN_RAW_PARAMS(MASTER_CLOCK_PAL/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS - 2, LBORDER_START + LBORDER_X_PIXELS + 256 + 10, PAL_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS, TBORDER_START + PAL_240_TBORDER_Y_PIXELS + 240)
563   MCFG_SCREEN_UPDATE(sms1)
564
565   MCFG_PALETTE_LENGTH(64+16)
566   MCFG_PALETTE_INIT(sms)
567
568   MCFG_DEFAULT_LAYOUT(layout_sms1)
569
570   MCFG_SMSVDP_ADD("sms_vdp", _315_5124_intf)
571MACHINE_CONFIG_END
572
573static MACHINE_CONFIG_DERIVED( sms_fm, sms1_ntsc )
574
575   MCFG_SOUND_ADD("ym2413", YM2413, XTAL_53_693175MHz/15)
576   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
577MACHINE_CONFIG_END
578
579static MACHINE_CONFIG_DERIVED( sg1000m3, sms_fm )
580
581   MCFG_CARTSLOT_MODIFY("cart1")
582   MCFG_CARTSLOT_EXTENSION_LIST("sms,bin,sg")
583   MCFG_CARTSLOT_MANDATORY
584   MCFG_CARTSLOT_START(sms_cart)
585   MCFG_CARTSLOT_LOAD(sms_cart)
586MACHINE_CONFIG_END
587
588static MACHINE_CONFIG_DERIVED( sms2_fm, sms2_ntsc )
589
590   MCFG_SOUND_ADD("ym2413", YM2413, XTAL_53_693175MHz/15)
591   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
592MACHINE_CONFIG_END
593
594static MACHINE_CONFIG_START( gamegear, sms_state )
595   /* basic machine hardware */
596   MCFG_CPU_ADD("maincpu", Z80, XTAL_53_693175MHz/15)
597   MCFG_CPU_PROGRAM_MAP(sms_mem)
598   MCFG_CPU_IO_MAP(gg_io)
599
600   MCFG_QUANTUM_TIME(attotime::from_hz(60))
601
602   MCFG_MACHINE_START(sms)
603   MCFG_MACHINE_RESET(sms)
604
605   /* video hardware */
606   MCFG_SCREEN_ADD("screen", LCD)
607   MCFG_SCREEN_FORMAT(BITMAP_FORMAT_RGB32)
608   MCFG_SCREEN_RAW_PARAMS(XTAL_53_693175MHz/10, SMS_X_PIXELS, LBORDER_START + LBORDER_X_PIXELS + 6*8, LBORDER_START + LBORDER_X_PIXELS + 26*8, NTSC_Y_PIXELS, TBORDER_START + NTSC_192_TBORDER_Y_PIXELS + 3*8, TBORDER_START + NTSC_192_TBORDER_Y_PIXELS + 21*8 )
609   MCFG_SCREEN_UPDATE(gamegear)
610
611   MCFG_PALETTE_LENGTH(4096)
612   MCFG_PALETTE_INIT(gamegear)
613
614   MCFG_VIDEO_START(gamegear)
615
616   MCFG_SMSVDP_ADD("sms_vdp", _315_5378_intf)
617
618   /* sound hardware */
619   MCFG_SPEAKER_STANDARD_STEREO("lspeaker","rspeaker")
620   MCFG_SOUND_ADD("gamegear", GAMEGEAR, XTAL_53_693175MHz/15)
621   MCFG_SOUND_ROUTE(0, "lspeaker", 1.00)
622   MCFG_SOUND_ROUTE(1, "rspeaker", 1.00)
623
624   /* cartridge */
625   MCFG_FRAGMENT_ADD( gg_cartslot )
626MACHINE_CONFIG_END
627
628
629ROM_START(sms1)
630   ROM_REGION(0x4000, "maincpu", 0)
631   ROM_FILL(0x0000, 0x4000, 0xff)
632
633   ROM_REGION(0x20000, "user1", 0)
634   ROM_SYSTEM_BIOS( 0, "bios13", "US/European BIOS v1.3 (1986)" )
635   ROMX_LOAD("bios13fx.rom", 0x0000, 0x2000, CRC(0072ED54) SHA1(c315672807d8ddb8d91443729405c766dd95cae7), ROM_BIOS(1))
636   ROM_SYSTEM_BIOS( 1, "hangonsh", "US/European BIOS v2.4 with Hang On and Safari Hunt (1988)" )
637   ROMX_LOAD("hshbios.rom", 0x0000, 0x20000, CRC(91E93385) SHA1(9e179392cd416af14024d8f31c981d9ee9a64517), ROM_BIOS(2))
638   ROM_SYSTEM_BIOS( 2, "hangon", "US/European BIOS v3.4 with Hang On (1988)" )
639   ROMX_LOAD("hangbios.rom", 0x0000, 0x20000, CRC(8EDF7AC6) SHA1(51fd6d7990f62cd9d18c9ecfc62ed7936169107e), ROM_BIOS(3))
640   ROM_SYSTEM_BIOS( 3, "missiled", "US/European BIOS v4.4 with Missile Defense 3D (1988)" )
641   ROMX_LOAD("missiled.rom", 0x0000, 0x20000, CRC(E79BB689) SHA1(aa92ae576ca670b00855e278378d89e9f85e0351), ROM_BIOS(4))
642   ROM_SYSTEM_BIOS( 4, "proto", "US Master System Prototype BIOS" )
643   ROMX_LOAD("m404prot.rom", 0x0000, 0x2000, CRC(1a15dfcc) SHA1(4a06c8e66261611dce0305217c42138b71331701), ROM_BIOS(5))
644ROM_END
645
646ROM_START(sms)
647   ROM_REGION(0x4000, "maincpu", 0)
648   ROM_FILL(0x0000, 0x4000, 0xff)
649
650   ROM_REGION(0x20000, "user1", 0)
651   ROM_SYSTEM_BIOS( 0, "alexkidd", "US/European BIOS with Alex Kidd in Miracle World (1990)" )
652   ROMX_LOAD("akbios.rom", 0x0000, 0x20000, CRC(CF4A09EA) SHA1(3af7b66248d34eb26da40c92bf2fa4c73a46a051), ROM_BIOS(1))
653ROM_END
654
655ROM_START(smssdisp)
656   ROM_REGION(0x4000, "maincpu", 0)
657   ROM_FILL(0x0000, 0x4000, 0x00)
658
659   ROM_REGION(0x4000, "user1", 0)
660   ROM_FILL(0x0000, 0x4000, 0xff)
661
662   ROM_REGION(0x4000, "control", 0)
663   ROM_LOAD("smssdisp.rom", 0x0000, 0x4000, CRC(ee2c29ba) SHA1(fc465122134d95363112eb51b9ab71db3576cefd))
664ROM_END
665
666ROM_START(sms1pal)
667   ROM_REGION(0x4000, "maincpu", 0)
668   ROM_FILL(0x0000, 0x4000, 0xff)
669
670   ROM_REGION(0x20000, "user1", 0)
671   ROM_SYSTEM_BIOS( 0, "bios13", "US/European BIOS v1.3 (1986)" )
672   ROMX_LOAD("bios13fx.rom", 0x0000, 0x2000, CRC(0072ED54) SHA1(c315672807d8ddb8d91443729405c766dd95cae7), ROM_BIOS(1))
673   ROM_SYSTEM_BIOS( 1, "hangonsh", "US/European BIOS v2.4 with Hang On and Safari Hunt (1988)" )
674   ROMX_LOAD("hshbios.rom", 0x0000, 0x20000, CRC(91E93385) SHA1(9e179392cd416af14024d8f31c981d9ee9a64517), ROM_BIOS(2))
675   ROM_SYSTEM_BIOS( 2, "hangon", "Sega Master System - US/European BIOS v3.4 with Hang On (1988)" )
676   ROMX_LOAD("hangbios.rom", 0x0000, 0x20000, CRC(8EDF7AC6) SHA1(51fd6d7990f62cd9d18c9ecfc62ed7936169107e), ROM_BIOS(3))
677   ROM_SYSTEM_BIOS( 3, "missiled", "US/European BIOS v4.4 with Missile Defense 3D (1988)" )
678   ROMX_LOAD("missiled.rom", 0x0000, 0x20000, CRC(E79BB689) SHA1(aa92ae576ca670b00855e278378d89e9f85e0351), ROM_BIOS(4))
679ROM_END
680
681ROM_START(smspal)
682   ROM_REGION(0x4000, "maincpu", 0)
683   ROM_FILL(0x0000, 0x4000, 0xff)
684
685   ROM_REGION(0x40000, "user1", 0)
686   ROM_SYSTEM_BIOS( 0, "alexkidd", "US/European BIOS with Alex Kidd in Miracle World (1990)" )
687   ROMX_LOAD("akbios.rom", 0x0000, 0x20000, CRC(CF4A09EA) SHA1(3af7b66248d34eb26da40c92bf2fa4c73a46a051), ROM_BIOS(1))
688   ROM_SYSTEM_BIOS( 1, "sonic", "European/Brazilian BIOS with Sonic the Hedgehog (1991)" )
689   ROMX_LOAD("sonbios.rom", 0x0000, 0x40000, CRC(81C3476B) SHA1(6aca0e3dffe461ba1cb11a86cd4caf5b97e1b8df), ROM_BIOS(2))
690ROM_END
691
692ROM_START(sg1000m3)
693   ROM_REGION(0x4000, "maincpu", 0)
694   ROM_FILL(0x0000, 0x4000, 0x00)
695ROM_END
696
697ROM_START(smsj)
698   ROM_REGION(0x4000, "maincpu", 0)
699   ROM_FILL(0x0000, 0x4000, 0xff)
700
701   ROM_REGION(0x4000, "user1", 0)
702   ROM_SYSTEM_BIOS( 0, "jbios21", "Japanese BIOS v2.1 (1987)" )
703   ROMX_LOAD("jbios21.rom", 0x0000, 0x2000, CRC(48D44A13) SHA1(a8c1b39a2e41137835eda6a5de6d46dd9fadbaf2), ROM_BIOS(1))
704ROM_END
705
706ROM_START(sms2kr)
707   ROM_REGION(0x4000, "maincpu", 0)
708   ROM_FILL(0x0000, 0x4000, 0xff)
709
710   ROM_REGION(0x20000, "user1", 0)
711   ROM_SYSTEM_BIOS( 0, "akbioskr", "Samsung Gam*Boy II with Alex Kidd in Miracle World (1990)" )
712   ROMX_LOAD("akbioskr.rom", 0x000, 0x20000, CRC(9c5bad91) SHA1(2feafd8f1c40fdf1bd5668f8c5c02e5560945b17), ROM_BIOS(1))
713ROM_END
714
715ROM_START(gamegear)
716   ROM_REGION(0x4000, "maincpu", 0)
717   ROM_FILL(0x0000, 0x4000, 0x00)
718
719   ROM_REGION(0x0400, "user1", 0)
720   ROM_SYSTEM_BIOS( 0, "none", "No BIOS" ) /* gamegear */
721   ROM_SYSTEM_BIOS( 1, "majesco", "Majesco BIOS" ) /* gamg */
722   ROMX_LOAD("majbios.rom", 0x0000, 0x0400, CRC(0EBEA9D4) SHA1(914aa165e3d879f060be77870d345b60cfeb4ede), ROM_BIOS(2))
723ROM_END
724
725#define rom_gamegeaj rom_gamegear
726
727/***************************************************************************
728
729  Game driver(s)
730
731  US
732   - Sega Master System I (sms1)
733     - prototype bios - 1986
734     - without built-in game v1.3 - 1986
735     - built-in Hang On/Safari Hunt v2.4 - 1988
736     - built-in Hang On v3.4 - 1988
737     - built-in Missile Defense 3-D v4.4 - 1988
738     - built-in Hang On/Astro Warrior ????
739   - Sega Master System II (sms/sms2)
740     - built-in Alex Kidd in Miracle World - 1990
741
742  JP
743   - Sega SG-1000 Mark III (smsm3)
744     - no bios
745   - Sega Master System (I) (smsj)
746     - without built-in game v2.1 - 1987
747
748  KR
749   - Sega Master System II (sms2kr)
750     - built-in Alex Kidd in Miracle World (Korean)
751
752  EU
753   - Sega Master System I (sms1pal)
754     - without built-in game v1.3 - 1986
755     - built-in Hang On/Safari Hunt v2.4 - 1988
756     - built-in Hang On v3.4 - 1988
757     - built-in Missile Defense 3-D v4.4 - 1988
758     - built-in Hang On/Astro Warrior ????
759   - Sega Master System II (sms2pal)
760     - built-in Alex Kidd in Miracle World - 1990
761     - built-in Sonic the Hedgehog - 1991
762
763  BR
764   - Sega Master System I - 1987
765   - Sega Master System II???
766   - Sega Master System III - Tec Toy, 1987
767   - Sega Master System Compact - Tec Toy, 1992
768   - Sega Master System Girl - Tec Toy, 1992
769
770***************************************************************************/
771
772/*    YEAR  NAME        PARENT      COMPAT  MACHINE      INPUT   INIT      COMPANY     FULLNAME                            FLAGS */
773CONS( 1984, sg1000m3,   sms,        0,      sg1000m3,    smsj,   sg1000m3, "Sega",     "SG-1000 Mark III",                 0 )
774CONS( 1986, sms1,       sms,        0,      sms1_ntsc,   sms1,   sms1,     "Sega",     "Master System I",                  0 )
775CONS( 1986, sms1pal,    sms,        0,      sms1_pal,    sms1,   sms1,     "Sega",     "Master System I (PAL)" ,           0 )
776CONS( 1986, smssdisp,   sms,        0,      sms_sdisp,   sms,    smssdisp, "Sega",     "Master System Store Display Unit", GAME_NOT_WORKING )
777CONS( 1987, smsj,       sms,        0,      sms_fm,      smsj,   smsj,     "Sega",     "Master System (Japan)",            0 )
778CONS( 1990, sms,        0,          0,      sms2_ntsc,   sms,    sms1,     "Sega",     "Master System II",                 0 )
779CONS( 1990, smspal,     sms,        0,      sms2_pal,    sms,    sms1,     "Sega",     "Master System II (PAL)",           0 )
780CONS( 1990, sms2kr,     sms,        0,      sms2_fm,     sms,    sms2kr,   "Samsung",  "Gam*Boy II (Korea)",               0 )
781
782CONS( 1990, gamegear,   0,          sms,    gamegear,    gg,     gamegear, "Sega",     "Game Gear (Europe/America)",       0 )
783CONS( 1990, gamegeaj,   gamegear,   0,      gamegear,    gg,     gamegeaj, "Sega",     "Game Gear (Japan)",                0 )
src/mame/drivers/mpu4drvr.c
r11450r11451
28072807static DRIVER_INIT (adders)
28082808{
28092809   mpu4_state *state = machine.driver_data<mpu4_state>();
2810   state->m_reels = 0;//currently no hybrid games
28102811   state->m_current_chr_table = adders_data;
28112812}
28122813
28132814static DRIVER_INIT (crmaze)
28142815{
28152816   mpu4_state *state = machine.driver_data<mpu4_state>();
2817   state->m_reels = 0;//currently no hybrid games
28162818   state->m_current_chr_table = crmaze_data;
28172819}
28182820
28192821static DRIVER_INIT (crmazea)
28202822{
28212823   mpu4_state *state = machine.driver_data<mpu4_state>();
2824   state->m_reels = 0;//currently no hybrid games
28222825   state->m_current_chr_table = crmazea_data;
28232826}
28242827
28252828static DRIVER_INIT (crmaze2)
28262829{
28272830   mpu4_state *state = machine.driver_data<mpu4_state>();
2831   state->m_reels = 0;//currently no hybrid games
28282832   state->m_current_chr_table = crmaze2_data;
28292833}
28302834
2835static DRIVER_INIT (crmaze2a)
2836{
2837   mpu4_state *state = machine.driver_data<mpu4_state>();
2838   state->m_reels = 0;//currently no hybrid games
2839}
2840
28312841static DRIVER_INIT (crmaze3)
28322842{
28332843   mpu4_state *state = machine.driver_data<mpu4_state>();
2844   state->m_reels = 0;//currently no hybrid games
28342845   state->m_reel_mux = FLUTTERBOX;
28352846   state->m_current_chr_table = crmaze3_data;
28362847}
r11450r11451
28382849static DRIVER_INIT (crmaze3a)
28392850{
28402851   mpu4_state *state = machine.driver_data<mpu4_state>();
2852   state->m_reels = 0;//currently no hybrid games
28412853   state->m_reel_mux = FLUTTERBOX;
28422854   state->m_current_chr_table = crmaze3a_data;
28432855}
r11450r11451
28532865
28542866   /* There is also an OKIM6376 present on the program card */
28552867   space->install_legacy_readwrite_handler(*device, 0xffa040, 0xffa0ff, FUNC(oki_r), FUNC(oki_w) );
2868   state->m_reels = 0;//currently no hybrid games
28562869
28572870   state->m_current_chr_table = mating_data;
28582871}
r11450r11451
28602873static DRIVER_INIT (skiltrek)
28612874{
28622875   mpu4_state *state = machine.driver_data<mpu4_state>();
2876   state->m_reels = 0;//currently no hybrid games
28632877   state->m_current_chr_table = skiltrek_data;
28642878}
28652879
28662880static DRIVER_INIT (timemchn)
28672881{
28682882   mpu4_state *state = machine.driver_data<mpu4_state>();
2883   state->m_reels = 0;//currently no hybrid games
28692884   state->m_current_chr_table = timemchn_data;
28702885}
28712886
28722887static DRIVER_INIT (strikeit)
28732888{
28742889   mpu4_state *state = machine.driver_data<mpu4_state>();
2890   state->m_reels = 0;//currently no hybrid games
28752891   state->m_current_chr_table = strikeit_data;
28762892}
28772893
28782894static DRIVER_INIT (turnover)
28792895{
28802896   mpu4_state *state = machine.driver_data<mpu4_state>();
2897   state->m_reels = 0;//currently no hybrid games
28812898   state->m_current_chr_table = turnover_data;
28822899}
28832900
28842901static DRIVER_INIT (eyesdown)
28852902{
28862903   mpu4_state *state = machine.driver_data<mpu4_state>();
2904   state->m_reels = 0;//currently no hybrid games
28872905   state->m_current_chr_table = eyesdown_data;
28882906}
28892907
28902908static DRIVER_INIT (quidgrid)
28912909{
28922910   mpu4_state *state = machine.driver_data<mpu4_state>();
2911   state->m_reels = 0;//currently no hybrid games
28932912   state->m_current_chr_table = quidgrid_data;
28942913}
28952914
28962915static DRIVER_INIT (prizeinv)
28972916{
28982917   mpu4_state *state = machine.driver_data<mpu4_state>();
2918   state->m_reels = 0;//currently no hybrid games
28992919   state->m_current_chr_table = prizeinv_data;
29002920}
29012921
r11450r11451
34673487
34683488GAME( 1993,  crmaze2,   bctvidbs, crmaze,   crmaze,   crmaze2,  ROT0, "Barcrest",      "The New Crystal Maze Featuring Ocean Zone (v2.2)",               GAME_NOT_WORKING )//SWP 1.0
34693489GAME( 1993,  crmaze2d,  crmaze2,  crmaze,   crmaze,   crmaze2,  ROT0, "Barcrest",      "The New Crystal Maze Featuring Ocean Zone (v2.2, Datapak)",            GAME_NOT_WORKING )//SWP 1.0D
3470GAME( 1993,  crmaze2a,  crmaze2,  crmaze,   crmaze,   0,        ROT0, "Barcrest",      "The New Crystal Maze Featuring Ocean Zone (v0.1, AMLD)",         GAME_NOT_WORKING )//SWP 1.0 /* unprotected? bootleg? */
3490GAME( 1993,  crmaze2a,  crmaze2,  crmaze,   crmaze,   crmaze2a, ROT0, "Barcrest",      "The New Crystal Maze Featuring Ocean Zone (v0.1, AMLD)",         GAME_NOT_WORKING )//SWP 1.0 /* unprotected? bootleg? */
34713491
34723492GAME( 1994,  crmaze3,   bctvidbs, crmaze,   crmaze,   crmaze3,  ROT0, "Barcrest",      "The Crystal Maze Team Challenge (v0.9)",                     GAME_NOT_WORKING )//SWP 0.7
34733493GAME( 1994,  crmaze3d,  crmaze3,  crmaze,   crmaze,   crmaze3,  ROT0, "Barcrest",      "The Crystal Maze Team Challenge (v0.9, Datapak)",               GAME_NOT_WORKING )//SWP 0.7D
src/mame/drivers/sg1000.c
r0r11451
1/*
2
3Sega SG-1000
4
5PCB Layout
6----------
7
8171-5078 (C) SEGA 1983
9171-5046 REV. A (C) SEGA 1983
10
11|---------------------------|                              |----------------------------|
12|   SW1     CN2             |   |------|---------------|   |    SW2     CN4             |
13|                           |---|         CN3          |---|                            |
14|  CN1                                                                              CN5 |
15|                                                                                       |
16|   10.738635MHz            |------------------------------|                7805        |
17|   |---|                   |------------------------------|                            |
18|   |   |                                 CN6                                           |
19|   | 9 |                                                                               |
20|   | 9 |                                                                       LS32    |
21|   | 1 |       |---------|                                                             |
22|   | 8 |       | TMM2009 |                                                     LS139   |
23|   | A |       |---------|             |------------------|                            |
24|   |   |                               |       Z80        |                            |
25|   |---|                               |------------------|                            |
26|                                                                                       |
27|                                                                                       |
28|       MB8118  MB8118  MB8118  MB8118              SN76489A            SW3             |
29|           MB8118  MB8118  MB8118  MB8118                          LS257   LS257       |
30|---------------------------------------------------------------------------------------|
31
32Notes:
33    All IC's shown.
34
35    Z80     - NEC D780C-1 / Zilog Z8400A (REV.A) Z80A CPU @ 3.579545
36    TMS9918A- Texas Instruments TMS9918ANL Video Display Processor @ 10.738635MHz
37    MB8118  - Fujitsu MB8118-12 16K x 1 Dynamic RAM
38    TMM2009 - Toshiba TMM2009P-A / TMM2009P-B (REV.A)
39    SN76489A- Texas Instruments SN76489AN Digital Complex Sound Generator @ 3.579545
40    CN1     - player 1 joystick connector
41    CN2     - RF video connector
42    CN3     - keyboard connector
43    CN4     - power connector (+9VDC)
44    CN5     - player 2 joystick connector
45    CN6     - cartridge connector
46    SW1     - TV channel select switch
47    SW2     - power switch
48    SW3     - hold switch
49
50*/
51
52/*
53
54    TODO:
55
56    - SC-3000 return instruction referenced by R when reading ports 60-7f,e0-ff
57    - connect PSG /READY signal to Z80 WAIT
58    - accurate video timing
59    - SP-400 serial printer
60    - SH-400 racing controller
61    - SF-7000 serial comms
62
63*/
64
65#define ADDRESS_MAP_MODERN
66
67#include "emu.h"
68#include "cpu/z80/z80.h"
69#include "imagedev/flopdrv.h"
70#include "imagedev/cartslot.h"
71#include "imagedev/cassette.h"
72#include "machine/ram.h"
73#include "imagedev/printer.h"
74#include "formats/basicdsk.h"
75#include "machine/ctronics.h"
76#include "machine/i8255.h"
77#include "machine/msm8251.h"
78#include "machine/upd765.h"
79#include "sound/sn76496.h"
80#include "video/tms9928a.h"
81#include "crsshair.h"
82#include "includes/sg1000.h"
83
84/***************************************************************************
85    READ/WRITE HANDLERS
86***************************************************************************/
87
88/*
89
90    Terebi Oekaki (TV Draw)
91
92    Address Access  Bits
93                    7       6   5   4   3   2   1   0
94    $6000   W       -       -   -   -   -   -   -   AXIS
95    $8000   R       BUSY    -   -   -   -   -   -   PRESS
96    $A000   R/W     DATA
97
98    AXIS: write 0 to select X axis, 1 to select Y axis.
99    BUSY: reads 1 when graphic board is busy sampling position, else 0.
100    PRESS: reads 0 when pen is touching graphic board, else 1.
101    DATA: when pen is touching graphic board, return 8-bit sample position for currently selected axis (X is in the 0-255 range, Y in the 0-191 range). Else, return 0.
102
103*/
104
105/*-------------------------------------------------
106    tvdraw_axis_w - TV Draw axis select
107-------------------------------------------------*/
108
109WRITE8_MEMBER( sg1000_state::tvdraw_axis_w )
110{
111   if (data & 0x01)
112   {
113      m_tvdraw_data = input_port_read(machine(), "TVDRAW_X");
114
115      if (m_tvdraw_data < 4) m_tvdraw_data = 4;
116      if (m_tvdraw_data > 251) m_tvdraw_data = 251;
117   }
118   else
119   {
120      m_tvdraw_data = input_port_read(machine(), "TVDRAW_Y") + 32;
121   }
122}
123
124/*-------------------------------------------------
125    tvdraw_status_r - TV Draw status read
126-------------------------------------------------*/
127
128READ8_MEMBER( sg1000_state::tvdraw_status_r )
129{
130   return input_port_read(machine(), "TVDRAW_PEN");
131}
132
133/*-------------------------------------------------
134    tvdraw_data_r - TV Draw data read
135-------------------------------------------------*/
136
137READ8_MEMBER( sg1000_state::tvdraw_data_r )
138{
139   return m_tvdraw_data;
140}
141
142/*-------------------------------------------------
143    joysel_r -
144-------------------------------------------------*/
145
146READ8_MEMBER( sg1000_state::joysel_r )
147{
148   return 0x80;
149}
150
151/***************************************************************************
152    MEMORY MAPS
153***************************************************************************/
154
155/*-------------------------------------------------
156    ADDRESS_MAP( sg1000_map )
157-------------------------------------------------*/
158
159static ADDRESS_MAP_START( sg1000_map, AS_PROGRAM, 8, sg1000_state )
160   AM_RANGE(0x0000, 0x7fff) AM_ROM
161   AM_RANGE(0x8000, 0xbfff) AM_RAMBANK("bank1")
162   AM_RANGE(0xc000, 0xffff) AM_RAMBANK("bank2")
163ADDRESS_MAP_END
164
165/*-------------------------------------------------
166    ADDRESS_MAP( sg1000_io_map )
167-------------------------------------------------*/
168
169static ADDRESS_MAP_START( sg1000_io_map, AS_IO, 8, sg1000_state )
170   ADDRESS_MAP_GLOBAL_MASK(0xff)
171   AM_RANGE(0x40, 0x40) AM_MIRROR(0x3f) AM_DEVWRITE_LEGACY(SN76489A_TAG, sn76496_w)
172   AM_RANGE(0x80, 0x80) AM_MIRROR(0x3e) AM_READWRITE_LEGACY(TMS9928A_vram_r, TMS9928A_vram_w)
173   AM_RANGE(0x81, 0x81) AM_MIRROR(0x3e) AM_READWRITE_LEGACY(TMS9928A_register_r, TMS9928A_register_w)
174   AM_RANGE(0xdc, 0xdc) AM_READ_PORT("PA7")
175   AM_RANGE(0xdd, 0xdd) AM_READ_PORT("PB7")
176   AM_RANGE(0xde, 0xde) AM_READ(joysel_r) AM_WRITENOP
177   AM_RANGE(0xdf, 0xdf) AM_NOP
178ADDRESS_MAP_END
179
180/*-------------------------------------------------
181    ADDRESS_MAP( omv_map )
182-------------------------------------------------*/
183
184static ADDRESS_MAP_START( omv_map, AS_PROGRAM, 8, sg1000_state )
185   AM_RANGE(0x0000, 0x7fff) AM_ROM
186   AM_RANGE(0x8000, 0xbfff) AM_RAMBANK("bank1")
187   AM_RANGE(0xc000, 0xc7ff) AM_MIRROR(0x3800) AM_RAM
188ADDRESS_MAP_END
189
190/*-------------------------------------------------
191    ADDRESS_MAP( omv_io_map )
192-------------------------------------------------*/
193
194static ADDRESS_MAP_START( omv_io_map, AS_IO, 8, sg1000_state )
195   ADDRESS_MAP_GLOBAL_MASK(0xff)
196   AM_RANGE(0x40, 0x40) AM_MIRROR(0x3f) AM_DEVWRITE_LEGACY(SN76489A_TAG, sn76496_w)
197   AM_RANGE(0x80, 0x80) AM_MIRROR(0x3e) AM_READWRITE_LEGACY(TMS9928A_vram_r, TMS9928A_vram_w)
198   AM_RANGE(0x81, 0x81) AM_MIRROR(0x3e) AM_READWRITE_LEGACY(TMS9928A_register_r, TMS9928A_register_w)
199   AM_RANGE(0xc0, 0xc0) AM_MIRROR(0x38) AM_READ_PORT("C0")
200   AM_RANGE(0xc1, 0xc1) AM_MIRROR(0x38) AM_READ_PORT("C1")
201   AM_RANGE(0xc2, 0xc2) AM_MIRROR(0x38) AM_READ_PORT("C2")
202   AM_RANGE(0xc3, 0xc3) AM_MIRROR(0x38) AM_READ_PORT("C3")
203   AM_RANGE(0xc4, 0xc4) AM_MIRROR(0x3a) AM_READ_PORT("C4")
204   AM_RANGE(0xc5, 0xc5) AM_MIRROR(0x3a) AM_READ_PORT("C5")
205ADDRESS_MAP_END
206
207/*-------------------------------------------------
208    ADDRESS_MAP( sc3000_map )
209-------------------------------------------------*/
210
211static ADDRESS_MAP_START( sc3000_map, AS_PROGRAM, 8, sg1000_state )
212   AM_RANGE(0x0000, 0x7fff) AM_ROM
213   AM_RANGE(0x8000, 0xbfff) AM_RAMBANK("bank1")
214   AM_RANGE(0xc000, 0xffff) AM_RAMBANK("bank2")
215ADDRESS_MAP_END
216
217/*-------------------------------------------------
218    ADDRESS_MAP( sc3000_io_map )
219-------------------------------------------------*/
220
221static ADDRESS_MAP_START( sc3000_io_map, AS_IO, 8, sg1000_state )
222   ADDRESS_MAP_GLOBAL_MASK(0xff)
223   AM_RANGE(0x7f, 0x7f) AM_DEVWRITE_LEGACY(SN76489A_TAG, sn76496_w)
224   AM_RANGE(0xbe, 0xbe) AM_READWRITE_LEGACY(TMS9928A_vram_r, TMS9928A_vram_w)
225   AM_RANGE(0xbf, 0xbf) AM_READWRITE_LEGACY(TMS9928A_register_r, TMS9928A_register_w)
226   AM_RANGE(0xdc, 0xdf) AM_DEVREADWRITE(UPD9255_TAG, i8255_device, read, write)
227ADDRESS_MAP_END
228
229/* This is how the I/O ports are really mapped, but MAME does not support overlapping ranges
230static ADDRESS_MAP_START( sc3000_io_map, AS_IO, 8, sg1000_state )
231    ADDRESS_MAP_GLOBAL_MASK(0xff)
232    AM_RANGE(0x00, 0x00) AM_MIRROR(0xdf) AM_DEVREADWRITE(UPD9255_TAG, i8255_device, read, write)
233    AM_RANGE(0x00, 0x00) AM_MIRROR(0x7f) AM_DEVWRITE_LEGACY(SN76489A_TAG, sn76496_w)
234    AM_RANGE(0x00, 0x00) AM_MIRROR(0xae) AM_READWRITE_LEGACY(TMS9928A_vram_r, TMS9928A_vram_w)
235    AM_RANGE(0x01, 0x01) AM_MIRROR(0xae) AM_READWRITE_LEGACY(TMS9928A_register_r, TMS9928A_register_w)
236    AM_RANGE(0x60, 0x60) AM_MIRROR(0x9f) AM_READ(sc3000_r_r)
237ADDRESS_MAP_END
238*/
239
240/*-------------------------------------------------
241    ADDRESS_MAP( sf7000_map )
242-------------------------------------------------*/
243
244static ADDRESS_MAP_START( sf7000_map, AS_PROGRAM, 8, sf7000_state )
245   AM_RANGE(0x0000, 0x3fff) AM_READ_BANK("bank1") AM_WRITE_BANK("bank2")
246   AM_RANGE(0x4000, 0xffff) AM_RAM
247ADDRESS_MAP_END
248
249/*-------------------------------------------------
250    ADDRESS_MAP( sf7000_io_map )
251-------------------------------------------------*/
252
253static ADDRESS_MAP_START( sf7000_io_map, AS_IO, 8, sf7000_state )
254   ADDRESS_MAP_GLOBAL_MASK(0xff)
255   AM_RANGE(0x7f, 0x7f) AM_DEVWRITE_LEGACY(SN76489A_TAG, sn76496_w)
256   AM_RANGE(0xbe, 0xbe) AM_READWRITE_LEGACY(TMS9928A_vram_r, TMS9928A_vram_w)
257   AM_RANGE(0xbf, 0xbf) AM_READWRITE_LEGACY(TMS9928A_register_r, TMS9928A_register_w)
258   AM_RANGE(0xdc, 0xdf) AM_DEVREADWRITE(UPD9255_0_TAG, i8255_device, read, write)
259   AM_RANGE(0xe0, 0xe0) AM_DEVREAD_LEGACY(UPD765_TAG, upd765_status_r)
260   AM_RANGE(0xe1, 0xe1) AM_DEVREADWRITE_LEGACY(UPD765_TAG, upd765_data_r, upd765_data_w)
261   AM_RANGE(0xe4, 0xe7) AM_DEVREADWRITE(UPD9255_1_TAG, i8255_device, read, write)
262   AM_RANGE(0xe8, 0xe8) AM_DEVREADWRITE_LEGACY(UPD8251_TAG, msm8251_data_r, msm8251_data_w)
263   AM_RANGE(0xe9, 0xe9) AM_DEVREADWRITE_LEGACY(UPD8251_TAG, msm8251_status_r, msm8251_control_w)
264ADDRESS_MAP_END
265
266/***************************************************************************
267    INPUT PORTS
268***************************************************************************/
269
270/*-------------------------------------------------
271    INPUT_CHANGED( trigger_nmi )
272-------------------------------------------------*/
273
274static INPUT_CHANGED( trigger_nmi )
275{
276   cputag_set_input_line(field->port->machine(), Z80_TAG, INPUT_LINE_NMI, (input_port_read(field->port->machine(), "NMI") ? CLEAR_LINE : ASSERT_LINE));
277}
278
279/*-------------------------------------------------
280    INPUT_PORTS( tvdraw )
281-------------------------------------------------*/
282
283static INPUT_PORTS_START( tvdraw )
284   PORT_START("TVDRAW_X")
285   PORT_BIT( 0xff, 0x80, IPT_LIGHTGUN_X ) PORT_CROSSHAIR(X, 1.0, 0.0, 0) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_PLAYER(1)
286
287   PORT_START("TVDRAW_Y")
288   PORT_BIT( 0xff, 0x60, IPT_LIGHTGUN_Y ) PORT_CROSSHAIR(Y, 1.0, 0.0, 0) PORT_MINMAX(0, 191) PORT_SENSITIVITY(50) PORT_KEYDELTA(10) PORT_PLAYER(1)
289
290   PORT_START("TVDRAW_PEN")
291   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_NAME("Pen")
292INPUT_PORTS_END
293
294/*-------------------------------------------------
295    INPUT_PORTS( sg1000 )
296-------------------------------------------------*/
297
298static INPUT_PORTS_START( sg1000 )
299   PORT_START("PA7")
300   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
301   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
302   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
303   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
304   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
305   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
306   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
307   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
308
309   PORT_START("PB7")
310   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
311   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
312   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
313   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
314   PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
315
316   PORT_START("NMI")
317   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_START ) PORT_NAME("PAUSE") PORT_CODE(KEYCODE_P) PORT_CHANGED(trigger_nmi, 0)
318
319   PORT_INCLUDE( tvdraw )
320INPUT_PORTS_END
321
322/*-------------------------------------------------
323    INPUT_PORTS( omv )
324-------------------------------------------------*/
325
326static INPUT_PORTS_START( omv )
327   PORT_START("C0")
328    PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1')
329    PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2')
330    PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3')
331    PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4')
332    PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5')
333    PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6')
334   PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
335
336   PORT_START("C1")
337    PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7')
338   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8')
339   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_NAME("9 #") PORT_CODE(KEYCODE_9) PORT_CHAR('9')
340   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_NAME("0 *") PORT_CODE(KEYCODE_0) PORT_CHAR('0')
341   PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
342
343   PORT_START("C2")
344   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
345    PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
346    PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
347    PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
348    PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
349    PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
350   PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
351
352   PORT_START("C3")
353   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
354    PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYPAD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
355   PORT_BIT( 0xfc, IP_ACTIVE_LOW, IPT_UNUSED )
356
357   PORT_START("C4")
358   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
359   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
360   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
361   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
362   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_NAME("S-1")
363   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_NAME("S-2")
364   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
365   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
366
367   PORT_START("C5")
368   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
369   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
370   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
371   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
372   PORT_BIT( 0xf0, IP_ACTIVE_LOW, IPT_UNUSED )
373
374   PORT_INCLUDE( tvdraw )
375INPUT_PORTS_END
376
377/*-------------------------------------------------
378    INPUT_PORTS( sk1100 )
379-------------------------------------------------*/
380
381static INPUT_PORTS_START( sk1100 )
382   PORT_START("PA0")
383   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
384   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') PORT_CHAR('q')
385   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_CHAR('A') PORT_CHAR('a')
386   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z') PORT_CHAR('z')
387   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("ENG DIER'S") PORT_CODE(KEYCODE_RALT) PORT_CHAR(UCHAR_MAMEKEY(RALT))
388   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
389   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_K) PORT_CHAR('K') PORT_CHAR('k')
390   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_I) PORT_CHAR('I') PORT_CHAR('i')
391
392   PORT_START("PA1")
393   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
394   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_W) PORT_CHAR('W') PORT_CHAR('w')
395   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_CHAR('S') PORT_CHAR('s')
396   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_X) PORT_CHAR('X') PORT_CHAR('x')
397   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("SPC") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
398   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
399   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_L) PORT_CHAR('L') PORT_CHAR('l')
400   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_O) PORT_CHAR('O') PORT_CHAR('o')
401
402   PORT_START("PA2")
403   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
404   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CHAR('E') PORT_CHAR('e')
405   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_D) PORT_CHAR('D') PORT_CHAR('d')
406   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_C) PORT_CHAR('C') PORT_CHAR('c')
407   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("HOME CLR") PORT_CODE(KEYCODE_HOME) PORT_CHAR(UCHAR_MAMEKEY(HOME))
408   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
409   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+')
410   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_P) PORT_CHAR('P') PORT_CHAR('p')
411
412   PORT_START("PA3")
413   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
414   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CHAR('R') PORT_CHAR('r')
415   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_F) PORT_CHAR('F') PORT_CHAR('f')
416   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_V) PORT_CHAR('V') PORT_CHAR('v')
417   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("INS DEL") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
418   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("\xcf\x80") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR(0x03c0)
419   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*')
420   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('@') PORT_CHAR('`')
421
422   PORT_START("PA4")
423   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
424   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_T) PORT_CHAR('T') PORT_CHAR('t')
425   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_G) PORT_CHAR('G') PORT_CHAR('g')
426   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_B) PORT_CHAR('B') PORT_CHAR('b')
427   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
428   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_DOWN) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
429   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR(']') PORT_CHAR('}')
430   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR('[') PORT_CHAR('{')
431
432   PORT_START("PA5")
433   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
434   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y') PORT_CHAR('y')
435   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_H) PORT_CHAR('H') PORT_CHAR('h')
436   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_N) PORT_CHAR('N') PORT_CHAR('n')
437   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
438   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_LEFT) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
439   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("CR") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
440   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
441
442   PORT_START("PA6")
443   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'')
444   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_U) PORT_CHAR('U') PORT_CHAR('u')
445   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_J) PORT_CHAR('J') PORT_CHAR('j')
446   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_M) PORT_CHAR('M') PORT_CHAR('m')
447   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_UNUSED )
448   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_RIGHT) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
449   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME(UTF8_UP) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
450   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNUSED )
451
452   PORT_START("PA7")
453   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_UP )
454   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN )
455   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT )
456   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT )
457   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 )
458   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON2 )
459   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_PLAYER(2)
460   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_PLAYER(2)
461
462   PORT_START("PB0")
463   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(')
464   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
465
466   PORT_START("PB1")
467   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')')
468   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
469
470   PORT_START("PB2")
471   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CHAR('0')
472   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
473
474   PORT_START("PB3")
475   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('=')
476   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
477
478   PORT_START("PB4")
479   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_CODE(KEYCODE_BACKSLASH2) PORT_CHAR('^')
480   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
481
482   PORT_START("PB5")
483   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("\xc2\xa5") PORT_CODE(KEYCODE_TILDE) PORT_CHAR(0x00a5)
484   PORT_BIT( 0x06, IP_ACTIVE_LOW, IPT_UNUSED )
485   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("FUNC") PORT_CODE(KEYCODE_TAB)
486
487   PORT_START("PB6")
488   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("BREAK") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
489   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("GRAPH") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(LALT))
490   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("CTRL") PORT_CODE(KEYCODE_LCONTROL) PORT_CHAR(UCHAR_MAMEKEY(LCONTROL))
491   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("SHIFT") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
492
493   PORT_START("PB7")
494   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_PLAYER(2)
495   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_PLAYER(2)
496   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2)
497   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2)
498
499   PORT_START("NMI")
500   PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_KEYBOARD ) PORT_NAME("RESET") PORT_CODE(KEYCODE_F10) PORT_CHANGED(trigger_nmi, 0)
501INPUT_PORTS_END
502
503/*-------------------------------------------------
504    INPUT_PORTS( sc3000 )
505-------------------------------------------------*/
506
507static INPUT_PORTS_START( sc3000 )
508   PORT_INCLUDE( sk1100 )
509   PORT_INCLUDE( tvdraw )
510INPUT_PORTS_END
511
512/*-------------------------------------------------
513    INPUT_PORTS( sf7000 )
514-------------------------------------------------*/
515
516static INPUT_PORTS_START( sf7000 )
517   PORT_INCLUDE( sk1100 )
518
519   PORT_START("BAUD")
520   PORT_CONFNAME( 0x05, 0x05, "Baud rate")
521   PORT_CONFSETTING( 0x00, "9600 baud" )
522   PORT_CONFSETTING( 0x01, "4800 baud" )
523   PORT_CONFSETTING( 0x02, "2400 baud" )
524   PORT_CONFSETTING( 0x03, "1200 baud" )
525   PORT_CONFSETTING( 0x04, "600 baud" )
526   PORT_CONFSETTING( 0x05, "300 baud" )
527INPUT_PORTS_END
528
529/***************************************************************************
530    DEVICE CONFIGURATION
531***************************************************************************/
532
533/*-------------------------------------------------
534    TMS9928a_interface tms9928a_interface
535-------------------------------------------------*/
536
537static INTERRUPT_GEN( sg1000_int )
538{
539    TMS9928A_interrupt(device->machine());
540}
541
542static void sg1000_vdp_interrupt(running_machine &machine, int state)
543{
544   cputag_set_input_line(machine, Z80_TAG, INPUT_LINE_IRQ0, state);
545}
546
547static const TMS9928a_interface tms9928a_interface =
548{
549   TMS99x8A,
550   0x4000,
551   0, 0,
552   sg1000_vdp_interrupt
553};
554
555/*-------------------------------------------------
556    I8255_INTERFACE( sc3000_ppi_intf )
557-------------------------------------------------*/
558
559READ8_MEMBER( sc3000_state::ppi_pa_r )
560{
561   /*
562        Signal  Description
563
564        PA0     Keyboard input
565        PA1     Keyboard input
566        PA2     Keyboard input
567        PA3     Keyboard input
568        PA4     Keyboard input
569        PA5     Keyboard input
570        PA6     Keyboard input
571        PA7     Keyboard input
572    */
573
574   static const char *const keynames[] = { "PA0", "PA1", "PA2", "PA3", "PA4", "PA5", "PA6", "PA7" };
575
576   return input_port_read(machine(), keynames[m_keylatch]);
577}
578
579READ8_MEMBER( sc3000_state::ppi_pb_r )
580{
581   /*
582        Signal  Description
583
584        PB0     Keyboard input
585        PB1     Keyboard input
586        PB2     Keyboard input
587        PB3     Keyboard input
588        PB4     /CONT input from cartridge terminal B-11
589        PB5     FAULT input from printer
590        PB6     BUSY input from printer
591        PB7     Cassette tape input
592    */
593
594   static const char *const keynames[] = { "PB0", "PB1", "PB2", "PB3", "PB4", "PB5", "PB6", "PB7" };
595
596   /* keyboard */
597   UINT8 data = input_port_read(machine(), keynames[m_keylatch]);
598
599   /* cartridge contact */
600   data |= 0x10;
601
602   /* printer */
603   data |= 0x60;
604
605   /* tape input */
606   if (cassette_input(m_cassette) > +0.0) data |= 0x80;
607
608   return data;
609}
610
611WRITE8_MEMBER( sc3000_state::ppi_pc_w )
612{
613   /*
614        Signal  Description
615
616        PC0     Keyboard raster output
617        PC1     Keyboard raster output
618        PC2     Keyboard raster output
619        PC3     not connected
620        PC4     Cassette tape output
621        PC5     DATA to printer
622        PC6     /RESET to printer
623        PC7     /FEED to printer
624    */
625
626   /* keyboard */
627   m_keylatch = data & 0x07;
628
629   /* cassette */
630   cassette_output(m_cassette, BIT(data, 4) ? +1.0 : -1.0);
631
632   /* TODO printer */
633}
634
635static I8255_INTERFACE( sc3000_ppi_intf )
636{
637   DEVCB_DRIVER_MEMBER(sc3000_state, ppi_pa_r),   // Port A read
638   DEVCB_NULL,                              // Port A write
639   DEVCB_DRIVER_MEMBER(sc3000_state, ppi_pb_r),   // Port B read
640   DEVCB_NULL,                              // Port B write
641   DEVCB_NULL,                              // Port C read
642   DEVCB_DRIVER_MEMBER(sc3000_state, ppi_pc_w),   // Port C write
643};
644
645/*-------------------------------------------------
646    cassette_config sc3000_cassette_config
647-------------------------------------------------*/
648
649static const cassette_config sc3000_cassette_config =
650{
651   cassette_default_formats,
652   NULL,
653   (cassette_state)(CASSETTE_STOPPED | CASSETTE_MOTOR_ENABLED | CASSETTE_SPEAKER_ENABLED),
654   NULL
655};
656
657/*-------------------------------------------------
658    I8255_INTERFACE( sf7000_ppi_intf )
659-------------------------------------------------*/
660
661READ8_MEMBER( sf7000_state::ppi_pa_r )
662{
663   /*
664        Signal  Description
665
666        PA0     INT from FDC
667        PA1     BUSY from Centronics printer
668        PA2     INDEX from FDD
669        PA3
670        PA4
671        PA5
672        PA6
673        PA7
674    */
675
676   UINT8 data = 0;
677
678   data |= m_fdc_irq;
679   data |= centronics_busy_r(m_centronics) << 1;
680   data |= m_fdc_index << 2;
681
682   return data;
683}
684
685WRITE8_MEMBER( sf7000_state::ppi_pc_w )
686{
687   /*
688        Signal  Description
689
690        PC0     /INUSE signal to FDD
691        PC1     /MOTOR ON signal to FDD
692        PC2     TC signal to FDC
693        PC3     RESET signal to FDC
694        PC4     not connected
695        PC5     not connected
696        PC6     /ROM SEL (switch between IPL ROM and RAM)
697        PC7     /STROBE to Centronics printer
698    */
699
700   /* floppy motor */
701   floppy_mon_w(m_floppy0, BIT(data, 1));
702   floppy_drive_set_ready_state(m_floppy0, 1, 1);
703
704   /* FDC terminal count */
705   upd765_tc_w(m_fdc, BIT(data, 2));
706
707   /* FDC reset */
708   if (BIT(data, 3))
709   {
710      upd765_reset(m_fdc, 0);
711   }
712
713   /* ROM selection */
714   memory_set_bank(machine(), "bank1", BIT(data, 6));
715
716   /* printer strobe */
717   centronics_strobe_w(m_centronics, BIT(data, 7));
718}
719
720static I8255_INTERFACE( sf7000_ppi_intf )
721{
722   DEVCB_DRIVER_MEMBER(sf7000_state, ppi_pa_r),            // Port A read
723   DEVCB_NULL,                                       // Port A write
724   DEVCB_NULL,                                       // Port B read
725   DEVCB_DEVICE_HANDLER(CENTRONICS_TAG, centronics_data_w),   // Port B write
726   DEVCB_NULL,                                       // Port C read
727   DEVCB_DRIVER_MEMBER(sf7000_state, ppi_pc_w)               // Port C write
728};
729
730/*-------------------------------------------------
731    upd765_interface sf7000_upd765_interface
732-------------------------------------------------*/
733
734WRITE_LINE_MEMBER( sf7000_state::fdc_intrq_w )
735{
736   m_fdc_irq = state;
737}
738
739static const struct upd765_interface sf7000_upd765_interface =
740{
741   DEVCB_DRIVER_LINE_MEMBER(sf7000_state, fdc_intrq_w),
742   DEVCB_NULL,
743   NULL,
744   UPD765_RDY_PIN_CONNECTED,
745   { FLOPPY_0, NULL, NULL, NULL }
746};
747
748/*-------------------------------------------------
749    FLOPPY_OPTIONS( sf7000 )
750-------------------------------------------------*/
751
752static FLOPPY_OPTIONS_START( sf7000 )
753   FLOPPY_OPTION(sf7000, "sf7", "SF7 disk image", basicdsk_identify_default, basicdsk_construct_default, NULL,
754      HEADS([1])
755      TRACKS([40])
756      SECTORS([16])
757      SECTOR_LENGTH([256])
758      FIRST_SECTOR_ID([1]))
759FLOPPY_OPTIONS_END
760
761/*-------------------------------------------------
762    floppy_config sf7000_floppy_config
763-------------------------------------------------*/
764
765static const floppy_config sf7000_floppy_config =
766{
767   DEVCB_NULL,
768   DEVCB_NULL,
769   DEVCB_NULL,
770   DEVCB_NULL,
771   DEVCB_NULL,
772   FLOPPY_STANDARD_5_25_DSHD,
773   FLOPPY_OPTIONS_NAME(sf7000),
774   NULL
775};
776
777/***************************************************************************
778    CARTRIDGE LOADING
779***************************************************************************/
780
781/*-------------------------------------------------
782    sg1000_install_cartridge -
783-------------------------------------------------*/
784
785void sg1000_state::install_cartridge(UINT8 *ptr, int size)
786{
787   address_space *program = m_maincpu->memory().space(AS_PROGRAM);
788
789   switch (size)
790   {
791   case 40 * 1024:
792      program->install_read_bank(0x8000, 0x9fff, "bank1");
793      program->unmap_write(0x8000, 0x9fff);
794      memory_configure_bank(machine(), "bank1", 0, 1, machine().region(Z80_TAG)->base() + 0x8000, 0);
795      memory_set_bank(machine(), "bank1", 0);
796      break;
797
798   case 48 * 1024:
799      program->install_read_bank(0x8000, 0xbfff, "bank1");
800      program->unmap_write(0x8000, 0xbfff);
801      memory_configure_bank(machine(), "bank1", 0, 1, machine().region(Z80_TAG)->base() + 0x8000, 0);
802      memory_set_bank(machine(), "bank1", 0);
803      break;
804
805   default:
806      if (IS_CARTRIDGE_TV_DRAW(ptr))
807      {
808         program->install_write_handler(0x6000, 0x6000, 0, 0, write8_delegate(FUNC(sg1000_state::tvdraw_axis_w), this), 0);
809         program->install_read_handler(0x8000, 0x8000, 0, 0, read8_delegate(FUNC(sg1000_state::tvdraw_status_r), this), 0);
810         program->install_read_handler(0xa000, 0xa000, 0, 0, read8_delegate(FUNC(sg1000_state::tvdraw_data_r), this), 0);
811         program->nop_write(0xa000, 0xa000);
812      }
813      else if (IS_CARTRIDGE_THE_CASTLE(ptr))
814      {
815         program->install_readwrite_bank(0x8000, 0x9fff, "bank1");
816      }
817      break;
818   }
819}
820
821/*-------------------------------------------------
822    DEVICE_IMAGE_LOAD( sg1000_cart )
823-------------------------------------------------*/
824
825static DEVICE_IMAGE_LOAD( sg1000_cart )
826{
827   running_machine &machine = image.device().machine();
828   sg1000_state *state = machine.driver_data<sg1000_state>();
829   address_space *program = machine.device(Z80_TAG)->memory().space(AS_PROGRAM);
830   UINT8 *ptr = machine.region(Z80_TAG)->base();
831   UINT32 size;
832
833   if (image.software_entry() == NULL)
834   {
835      size = image.length();
836      if (image.fread( ptr, size) != size)
837         return IMAGE_INIT_FAIL;
838   }
839   else
840   {
841      size = image.get_software_region_length("rom");
842      memcpy(ptr, image.get_software_region("rom"), size);
843   }
844
845   /* cartridge ROM banking */
846   state->install_cartridge(ptr, size);
847
848   /* work RAM banking */
849   program->install_readwrite_bank(0xc000, 0xc3ff, 0, 0x3c00, "bank2");
850
851   return IMAGE_INIT_PASS;
852}
853
854/*-------------------------------------------------
855    DEVICE_IMAGE_LOAD( omv_cart )
856-------------------------------------------------*/
857
858static DEVICE_IMAGE_LOAD( omv_cart )
859{
860   running_machine &machine = image.device().machine();
861   sg1000_state *state = machine.driver_data<sg1000_state>();
862   UINT32 size;
863   UINT8 *ptr = machine.region(Z80_TAG)->base();
864
865   if (image.software_entry() == NULL)
866   {
867      size = image.length();
868      if (image.fread( ptr, size) != size)
869         return IMAGE_INIT_FAIL;
870   }
871   else
872   {
873      size = image.get_software_region_length("rom");
874      memcpy(ptr, image.get_software_region("rom"), size);
875   }
876
877   /* cartridge ROM banking */
878   state->install_cartridge(ptr, size);
879
880   return IMAGE_INIT_PASS;
881}
882
883/*-------------------------------------------------
884    sc3000_install_cartridge -
885-------------------------------------------------*/
886
887void sc3000_state::install_cartridge(UINT8 *ptr, int size)
888{
889   address_space *program = m_maincpu->memory().space(AS_PROGRAM);
890
891   /* include SG-1000 mapping */
892   sg1000_state::install_cartridge(ptr, size);
893
894   if (IS_CARTRIDGE_BASIC_LEVEL_III(ptr))
895   {
896      program->install_readwrite_bank(0x8000, 0xbfff, "bank1");
897      program->install_readwrite_bank(0xc000, 0xffff, "bank2");
898   }
899   else if (IS_CARTRIDGE_MUSIC_EDITOR(ptr))
900   {
901      program->install_readwrite_bank(0x8000, 0x9fff, "bank1");
902      program->install_readwrite_bank(0xc000, 0xc7ff, 0, 0x3800, "bank2");
903   }
904   else
905   {
906      /* regular cartridges */
907      program->install_readwrite_bank(0xc000, 0xc7ff, 0, 0x3800, "bank2");
908   }
909}
910
911/*-------------------------------------------------
912    DEVICE_IMAGE_LOAD( sc3000_cart )
913-------------------------------------------------*/
914
915static DEVICE_IMAGE_LOAD( sc3000_cart )
916{
917   running_machine &machine = image.device().machine();
918   sc3000_state *state = machine.driver_data<sc3000_state>();
919   UINT8 *ptr = machine.region(Z80_TAG)->base();
920   UINT32 size;
921
922   if (image.software_entry() == NULL)
923   {
924      size = image.length();
925      if (image.fread( ptr, size) != size)
926         return IMAGE_INIT_FAIL;
927   }
928   else
929   {
930      size = image.get_software_region_length("rom");
931      memcpy(ptr, image.get_software_region("rom"), size);
932   }
933
934   /* cartridge ROM and work RAM banking */
935   state->install_cartridge(ptr, size);
936
937   return IMAGE_INIT_PASS;
938}
939
940/***************************************************************************
941    MACHINE INITIALIZATION
942***************************************************************************/
943
944/*-------------------------------------------------
945    TIMER_CALLBACK( lightgun_tick )
946-------------------------------------------------*/
947
948static TIMER_CALLBACK( lightgun_tick )
949{
950   UINT8 *rom = machine.region(Z80_TAG)->base();
951
952   if (IS_CARTRIDGE_TV_DRAW(rom))
953   {
954      /* enable crosshair for TV Draw */
955      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_ALL);
956   }
957   else
958   {
959      /* disable crosshair for other cartridges */
960      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_NONE);
961   }
962}
963
964/*-------------------------------------------------
965    MACHINE_START( sg1000 )
966-------------------------------------------------*/
967
968void sg1000_state::machine_start()
969{
970   /* configure VDP */
971   TMS9928A_configure(&tms9928a_interface);
972
973   /* toggle light gun crosshair */
974   machine().scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
975
976   /* register for state saving */
977   state_save_register_global(machine(), m_tvdraw_data);
978}
979
980/*-------------------------------------------------
981    MACHINE_START( sc3000 )
982-------------------------------------------------*/
983
984void sc3000_state::machine_start()
985{
986   /* configure VDP */
987   TMS9928A_configure(&tms9928a_interface);
988
989   /* toggle light gun crosshair */
990   machine().scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
991
992   /* register for state saving */
993   state_save_register_global(machine(), m_tvdraw_data);
994   state_save_register_global(machine(), m_keylatch);
995}
996
997/*-------------------------------------------------
998    sf7000_fdc_index_callback -
999-------------------------------------------------*/
1000
1001static void sf7000_fdc_index_callback(device_t *controller, device_t *img, int state)
1002{
1003   sf7000_state *driver_state = img->machine().driver_data<sf7000_state>();
1004
1005   driver_state->m_fdc_index = state;
1006}
1007
1008/*-------------------------------------------------
1009    MACHINE_START( sf7000 )
1010-------------------------------------------------*/
1011
1012void sf7000_state::machine_start()
1013{
1014   /* configure VDP */
1015   TMS9928A_configure(&tms9928a_interface);
1016
1017   /* configure FDC */
1018   floppy_drive_set_index_pulse_callback(m_floppy0, sf7000_fdc_index_callback);
1019
1020   /* configure memory banking */
1021   memory_configure_bank(machine(), "bank1", 0, 1, machine().region(Z80_TAG)->base(), 0);
1022   memory_configure_bank(machine(), "bank1", 1, 1, ram_get_ptr(m_ram), 0);
1023   memory_configure_bank(machine(), "bank2", 0, 1, ram_get_ptr(m_ram), 0);
1024
1025   /* register for state saving */
1026   state_save_register_global(machine(), m_keylatch);
1027   state_save_register_global(machine(), m_fdc_irq);
1028   state_save_register_global(machine(), m_fdc_index);
1029}
1030
1031/*-------------------------------------------------
1032    MACHINE_RESET( sf7000 )
1033-------------------------------------------------*/
1034
1035void sf7000_state::machine_reset()
1036{
1037   memory_set_bank(machine(), "bank1", 0);
1038   memory_set_bank(machine(), "bank2", 0);
1039}
1040
1041/***************************************************************************
1042    MACHINE DRIVERS
1043***************************************************************************/
1044
1045/*-------------------------------------------------
1046    MACHINE_CONFIG_START( sg1000, sg1000_state )
1047-------------------------------------------------*/
1048
1049static MACHINE_CONFIG_START( sg1000, sg1000_state )
1050   /* basic machine hardware */
1051   MCFG_CPU_ADD(Z80_TAG, Z80, XTAL_10_738635MHz/3)
1052   MCFG_CPU_PROGRAM_MAP(sg1000_map)
1053   MCFG_CPU_IO_MAP(sg1000_io_map)
1054   MCFG_CPU_VBLANK_INT(SCREEN_TAG, sg1000_int)
1055
1056    /* video hardware */
1057   MCFG_FRAGMENT_ADD(tms9928a)
1058   MCFG_SCREEN_MODIFY(SCREEN_TAG)
1059   MCFG_SCREEN_REFRESH_RATE((float)XTAL_10_738635MHz/2/342/262)
1060   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */
1061
1062   /* sound hardware */
1063   MCFG_SPEAKER_STANDARD_MONO("mono")
1064   MCFG_SOUND_ADD(SN76489A_TAG, SN76489A, XTAL_10_738635MHz/3)
1065   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
1066
1067   /* cartridge */
1068   MCFG_CARTSLOT_ADD("cart")
1069   MCFG_CARTSLOT_EXTENSION_LIST("sg,bin")
1070   MCFG_CARTSLOT_MANDATORY
1071   MCFG_CARTSLOT_INTERFACE("sg1000_cart")
1072   MCFG_CARTSLOT_LOAD(sg1000_cart)
1073
1074   /* software lists */
1075   MCFG_SOFTWARE_LIST_ADD("cart_list","sg1000")
1076
1077   /* internal ram */
1078   MCFG_RAM_ADD(RAM_TAG)
1079   MCFG_RAM_DEFAULT_SIZE("1K")
1080MACHINE_CONFIG_END
1081
1082/*-------------------------------------------------
1083    MACHINE_CONFIG_DERIVED( omv, sg1000 )
1084-------------------------------------------------*/
1085
1086static MACHINE_CONFIG_DERIVED( omv, sg1000 )
1087   MCFG_CPU_MODIFY(Z80_TAG)
1088   MCFG_CPU_PROGRAM_MAP(omv_map)
1089   MCFG_CPU_IO_MAP(omv_io_map)
1090
1091   MCFG_CARTSLOT_MODIFY("cart")
1092   MCFG_CARTSLOT_EXTENSION_LIST("sg,bin")
1093   MCFG_CARTSLOT_NOT_MANDATORY
1094   MCFG_CARTSLOT_LOAD(omv_cart)
1095
1096   MCFG_RAM_MODIFY(RAM_TAG)
1097   MCFG_RAM_DEFAULT_SIZE("2K")
1098MACHINE_CONFIG_END
1099
1100/*-------------------------------------------------
1101    MACHINE_CONFIG_START( sc3000, sc3000_state )
1102-------------------------------------------------*/
1103
1104static MACHINE_CONFIG_START( sc3000, sc3000_state )
1105   /* basic machine hardware */
1106   MCFG_CPU_ADD(Z80_TAG, Z80, XTAL_10_738635MHz/3) // LH0080A
1107   MCFG_CPU_PROGRAM_MAP(sc3000_map)
1108   MCFG_CPU_IO_MAP(sc3000_io_map)
1109   MCFG_CPU_VBLANK_INT(SCREEN_TAG, sg1000_int)
1110
1111    /* video hardware */
1112   MCFG_FRAGMENT_ADD(tms9928a)
1113   MCFG_SCREEN_MODIFY(SCREEN_TAG)
1114   MCFG_SCREEN_REFRESH_RATE((float)XTAL_10_738635MHz/2/342/262)
1115   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */
1116
1117   /* sound hardware */
1118   MCFG_SPEAKER_STANDARD_MONO("mono")
1119   MCFG_SOUND_ADD(SN76489A_TAG, SN76489A, XTAL_10_738635MHz/3)
1120   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
1121
1122   /* devices */
1123   MCFG_I8255_ADD(UPD9255_TAG, sc3000_ppi_intf)
1124//  MCFG_PRINTER_ADD("sp400") /* serial printer */
1125   MCFG_CASSETTE_ADD(CASSETTE_TAG, sc3000_cassette_config)
1126
1127   /* cartridge */
1128   MCFG_CARTSLOT_ADD("cart")
1129   MCFG_CARTSLOT_EXTENSION_LIST("sg,sc,bin")
1130   MCFG_CARTSLOT_INTERFACE("sg1000_cart")
1131   MCFG_CARTSLOT_LOAD(sc3000_cart)
1132
1133   /* software lists */
1134   MCFG_SOFTWARE_LIST_ADD("cart_list","sg1000")
1135
1136   /* internal ram */
1137   MCFG_RAM_ADD(RAM_TAG)
1138   MCFG_RAM_DEFAULT_SIZE("2K")
1139MACHINE_CONFIG_END
1140
1141/*-------------------------------------------------
1142    MACHINE_CONFIG_START( sf7000, sf7000_state )
1143-------------------------------------------------*/
1144
1145static MACHINE_CONFIG_START( sf7000, sf7000_state )
1146   /* basic machine hardware */
1147   MCFG_CPU_ADD(Z80_TAG, Z80, XTAL_10_738635MHz/3)
1148   MCFG_CPU_PROGRAM_MAP(sf7000_map)
1149   MCFG_CPU_IO_MAP(sf7000_io_map)
1150   MCFG_CPU_VBLANK_INT(SCREEN_TAG, sg1000_int)
1151
1152    /* video hardware */
1153   MCFG_FRAGMENT_ADD(tms9928a)
1154   MCFG_SCREEN_MODIFY(SCREEN_TAG)
1155   MCFG_SCREEN_REFRESH_RATE((float)XTAL_10_738635MHz/2/342/262)
1156   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */
1157
1158   /* sound hardware */
1159   MCFG_SPEAKER_STANDARD_MONO("mono")
1160   MCFG_SOUND_ADD(SN76489A_TAG, SN76489A, XTAL_10_738635MHz/3)
1161   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.00)
1162
1163   /* devices */
1164   MCFG_I8255_ADD(UPD9255_0_TAG, sc3000_ppi_intf)
1165   MCFG_I8255_ADD(UPD9255_1_TAG, sf7000_ppi_intf)
1166   MCFG_MSM8251_ADD(UPD8251_TAG, default_msm8251_interface)
1167   MCFG_UPD765A_ADD(UPD765_TAG, sf7000_upd765_interface)
1168   MCFG_FLOPPY_DRIVE_ADD(FLOPPY_0, sf7000_floppy_config)
1169//  MCFG_PRINTER_ADD("sp400") /* serial printer */
1170   MCFG_CENTRONICS_ADD(CENTRONICS_TAG, standard_centronics)
1171   MCFG_CASSETTE_ADD(CASSETTE_TAG, sc3000_cassette_config)
1172
1173   /* internal ram */
1174   MCFG_RAM_ADD(RAM_TAG)
1175   MCFG_RAM_DEFAULT_SIZE("64K")
1176MACHINE_CONFIG_END
1177
1178/***************************************************************************
1179    ROMS
1180***************************************************************************/
1181
1182ROM_START( sg1000 )
1183   ROM_REGION( 0x10000, Z80_TAG, ROMREGION_ERASE00 )
1184ROM_END
1185
1186#define rom_sg1000m2 rom_sg1000
1187
1188ROM_START( sc3000 )
1189   ROM_REGION( 0x10000, Z80_TAG, ROMREGION_ERASE00 )
1190   ROM_LOAD( "sc3000.rom", 0x0000, 0x8000, CRC(a46e3c73) SHA1(b1a8585a9afff962e8fd0e79b3305199da4e4562))
1191ROM_END
1192
1193#define rom_sc3000h rom_sg1000
1194
1195ROM_START( omv1000 )
1196   ROM_REGION( 0x10000, Z80_TAG, ROMREGION_ERASE00 )
1197   ROM_LOAD( "omvbios.bin", 0x0000, 0x4000, BAD_DUMP CRC(c5a67b95) SHA1(6d7c64dd60dee4a33061d3d3a7c2ed190d895cdb) )   // The BIOS comes from a Multivision FG-2000. It is still unknown if the FG-1000 BIOS differs
1198ROM_END
1199
1200ROM_START( omv2000 )
1201   ROM_REGION( 0x10000, Z80_TAG, ROMREGION_ERASE00 )
1202   ROM_LOAD( "omvbios.bin", 0x0000, 0x4000, CRC(c5a67b95) SHA1(6d7c64dd60dee4a33061d3d3a7c2ed190d895cdb) )
1203ROM_END
1204
1205ROM_START( sf7000 )
1206   ROM_REGION( 0x10000, Z80_TAG, 0 )
1207   ROM_LOAD( "ipl.rom", 0x0000, 0x2000, CRC(d76810b8) SHA1(77339a6db2593aadc638bed77b8e9bed5d9d87e3) )
1208ROM_END
1209
1210/***************************************************************************
1211    SYSTEM DRIVERS
1212***************************************************************************/
1213
1214/*    YEAR  NAME        PARENT      COMPAT      MACHINE     INPUT       INIT    COMPANY             FULLNAME                                    FLAGS */
1215CONS( 1983,   sg1000,     0,          0,          sg1000,     sg1000,     0,      "Sega",             "SG-1000",                                  GAME_SUPPORTS_SAVE )
1216CONS( 1984,   sg1000m2,   sg1000,     0,          sc3000,     sc3000,     0,      "Sega",             "SG-1000 II",                               GAME_SUPPORTS_SAVE )
1217COMP( 1983,   sc3000,     0,          sg1000,     sc3000,     sc3000,     0,      "Sega",             "SC-3000",                                  GAME_SUPPORTS_SAVE )
1218COMP( 1983,   sc3000h,    sc3000,     0,          sc3000,     sc3000,     0,      "Sega",             "SC-3000H",                                 GAME_SUPPORTS_SAVE )
1219COMP( 1983,   sf7000,     sc3000,     0,          sf7000,     sf7000,     0,      "Sega",             "SC-3000/Super Control Station SF-7000",    GAME_SUPPORTS_SAVE )
1220CONS( 1984,   omv1000,    sg1000,     0,          omv,        omv,        0,      "Tsukuda Original", "Othello Multivision FG-1000",              GAME_SUPPORTS_SAVE )
1221CONS( 1984,   omv2000,    sg1000,     0,          omv,        omv,        0,      "Tsukuda Original", "Othello Multivision FG-2000",              GAME_SUPPORTS_SAVE )
src/emu/hashfile.c
r0r11451
1/*********************************************************************
2
3    hashfile.c
4
5    Code for parsing hash info (*.hsi) files
6
7*********************************************************************/
8
9#include "hashfile.h"
10#include "pool.h"
11#include "expat.h"
12#include "emuopts.h"
13#include "hash.h"
14
15
16/***************************************************************************
17    TYPE DEFINITIONS
18***************************************************************************/
19
20typedef struct _hash_info hash_info;
21struct _hash_info
22{
23   hash_collection *hashes;
24   const char *extrainfo;
25};
26
27typedef struct _hash_file hash_file;
28
29typedef void (*hashfile_error_func)(const char *message);
30
31
32
33/***************************************************************************
34    FUNCTION PROTOTYPES
35***************************************************************************/
36
37/* opens a hash file; if is_preload is non-zero, the entire file is preloaded */
38hash_file *hashfile_open(emu_options &options, const char *sysname, int is_preload, hashfile_error_func error_proc);
39
40/* closes a hash file and associated resources */
41void hashfile_close(hash_file *hashfile);
42
43/* looks up information in a hash file */
44const hash_info *hashfile_lookup(hash_file *hashfile, const hash_collection *hashes);
45
46/***************************************************************************
47    TYPE DEFINITIONS
48***************************************************************************/
49
50struct _hash_file
51{
52   emu_file *file;
53   object_pool *pool;
54   astring functions[IO_COUNT];
55
56   hash_info **preloaded_hashes;
57   int preloaded_hash_count;
58
59   void (*error_proc)(const char *message);
60};
61
62
63
64enum hash_parse_position
65{
66   HASH_POS_ROOT,
67   HASH_POS_MAIN,
68   HASH_POS_HASH
69};
70
71
72
73struct hash_parse_state
74{
75   XML_Parser parser;
76   hash_file *hashfile;
77   int done;
78
79   int (*selector_proc)(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes);
80   void (*use_proc)(hash_file *hashfile, void *param, hash_info *hi);
81   void (*error_proc)(const char *message);
82   void *param;
83
84   enum hash_parse_position pos;
85   char **text_dest;
86   hash_info *hi;
87};
88
89
90
91/***************************************************************************
92    PROTOTYPES
93***************************************************************************/
94
95static void *expat_malloc(size_t size);
96static void *expat_realloc(void *ptr, size_t size);
97static void expat_free(void *ptr);
98
99
100
101/***************************************************************************
102    CORE IMPLEMENTATION
103***************************************************************************/
104
105/*-------------------------------------------------
106    parse_error
107-------------------------------------------------*/
108
109static void ATTR_PRINTF(2,3) parse_error(struct hash_parse_state *state, const char *fmt, ...)
110{
111   char buf[256];
112   va_list va;
113
114   if (state->error_proc)
115   {
116      va_start(va, fmt);
117      vsnprintf(buf, ARRAY_LENGTH(buf), fmt, va);
118      va_end(va);
119      (*state->error_proc)(buf);
120   }
121}
122
123
124
125/*-------------------------------------------------
126    unknown_tag
127-------------------------------------------------*/
128
129static void unknown_tag(struct hash_parse_state *state, const char *tagname)
130{
131   parse_error(state, "[%lu:%lu]: Unknown tag: %s\n",
132      XML_GetCurrentLineNumber(state->parser),
133      XML_GetCurrentColumnNumber(state->parser),
134      tagname);
135}
136
137
138
139/*-------------------------------------------------
140    unknown_attribute
141-------------------------------------------------*/
142
143static void unknown_attribute(struct hash_parse_state *state, const char *attrname)
144{
145   parse_error(state, "[%lu:%lu]: Unknown attribute: %s\n",
146      XML_GetCurrentLineNumber(state->parser),
147      XML_GetCurrentColumnNumber(state->parser),
148      attrname);
149}
150
151
152
153/*-------------------------------------------------
154    unknown_attribute_value
155-------------------------------------------------*/
156
157static void unknown_attribute_value(struct hash_parse_state *state,
158   const char *attrname, const char *attrvalue)
159{
160   parse_error(state, "[%lu:%lu]: Unknown attribute value: %s\n",
161      XML_GetCurrentLineNumber(state->parser),
162      XML_GetCurrentColumnNumber(state->parser),
163      attrvalue);
164}
165
166
167
168/*-------------------------------------------------
169    start_handler
170-------------------------------------------------*/
171
172static void start_handler(void *data, const char *tagname, const char **attributes)
173{
174   struct hash_parse_state *state = (struct hash_parse_state *) data;
175   const char *name;
176   hash_info *hi;
177   char **text_dest;
178   hash_collection hashes;
179   astring all_functions;
180   char functions;
181   iodevice_t device;
182   int i;
183
184   switch(state->pos)
185   {
186      case HASH_POS_ROOT:
187         if (!strcmp(tagname, "hashfile"))
188         {
189         }
190         else
191         {
192            unknown_tag(state, tagname);
193         }
194         break;
195
196      case HASH_POS_MAIN:
197         if (!strcmp(tagname, "hash"))
198         {
199            // we are now examining a hash tag
200            name = NULL;
201            device = IO_COUNT;
202
203            while(attributes[0])
204            {
205               functions = 0;
206               if (!strcmp(attributes[0], "name"))
207               {
208                  /* name attribute */
209                  name = attributes[1];
210               }
211               else if (!strcmp(attributes[0], "crc32"))
212               {
213                  /* crc32 attribute */
214                  functions = hash_collection::HASH_CRC;
215               }
216               else if (!strcmp(attributes[0], "md5"))
217               {
218                  /* md5 attribute */
219                  functions = hash_collection::HASH_MD5;
220               }
221               else if (!strcmp(attributes[0], "sha1"))
222               {
223                  /* sha1 attribute */
224                  functions = hash_collection::HASH_SHA1;
225               }
226               else if (!strcmp(attributes[0], "type"))
227               {
228                  /* type attribute */
229                  i = 0;//device_typeid(attributes[1]);
230                  if (i < 0)
231                     unknown_attribute_value(state, attributes[0], attributes[1]);
232                  else
233                     device = (iodevice_t) i;
234               }
235               else
236               {
237                  /* unknown attribute */
238                  unknown_attribute(state, attributes[0]);
239               }
240
241               if (functions)
242               {
243                  hashes.add_from_string(functions, attributes[1], strlen(attributes[1]));
244                  all_functions.cat(functions);
245               }
246
247               attributes += 2;
248            }
249
250            /* do we use this hash? */
251            if (!state->selector_proc || state->selector_proc(state->hashfile, state->param, name, &hashes))
252            {
253               hi = (hash_info*)pool_malloc_lib(state->hashfile->pool, sizeof(hash_info));
254               if (!hi)
255                  return;
256               memset(hi, 0, sizeof(*hi));
257
258               hi->hashes = &hashes;
259               state->hi = hi;
260            }
261         }
262         else
263         {
264            unknown_tag(state, tagname);
265         }
266         break;
267
268      case HASH_POS_HASH:
269         text_dest = NULL;
270
271         if (!strcmp(tagname, "year")) {
272         }
273         else if (!strcmp(tagname, "manufacturer")){
274         }
275         else if (!strcmp(tagname, "status")){
276         }
277         else if (!strcmp(tagname, "pcb")){
278         }
279         else if (!strcmp(tagname, "extrainfo")) {
280            text_dest = (char **) &state->hi->extrainfo;
281         }
282         else
283            unknown_tag(state, tagname);
284
285         if (text_dest && state->hi)
286            state->text_dest = text_dest;
287         break;
288   }
289   state->pos = (hash_parse_position) (state->pos + 1);
290}
291
292
293
294/*-------------------------------------------------
295    end_handler
296-------------------------------------------------*/
297
298static void end_handler(void *data, const char *name)
299{
300   struct hash_parse_state *state = (struct hash_parse_state *) data;
301   state->text_dest = NULL;
302
303   state->pos = (hash_parse_position) (state->pos - 1);
304   switch(state->pos)
305   {
306      case HASH_POS_ROOT:
307      case HASH_POS_HASH:
308         break;
309
310      case HASH_POS_MAIN:
311         if (state->hi)
312         {
313            if (state->use_proc)
314               (*state->use_proc)(state->hashfile, state->param, state->hi);
315            state->hi = NULL;
316         }
317         break;
318   }
319}
320
321
322
323/*-------------------------------------------------
324    data_handler
325-------------------------------------------------*/
326
327static void data_handler(void *data, const XML_Char *s, int len)
328{
329   struct hash_parse_state *state = (struct hash_parse_state *) data;
330   int text_len;
331   char *text;
332
333   if (state->text_dest)
334   {
335      text = *state->text_dest;
336
337      text_len = text ? strlen(text) : 0;
338      text = (char*)pool_realloc_lib(state->hashfile->pool, text, text_len + len + 1);
339      if (!text)
340         return;
341
342      memcpy(&text[text_len], s, len);
343      text[text_len + len] = '\0';
344      *state->text_dest = text;
345   }
346}
347
348
349
350/*-------------------------------------------------
351    hashfile_parse
352-------------------------------------------------*/
353
354static void hashfile_parse(hash_file *hashfile,
355   int (*selector_proc)(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes),
356   void (*use_proc)(hash_file *hashfile, void *param, hash_info *hi),
357   void (*error_proc)(const char *message),
358   void *param)
359{
360   struct hash_parse_state state;
361   char buf[1024];
362   UINT32 len;
363   XML_Memory_Handling_Suite memcallbacks;
364
365   hashfile->file->seek(0, SEEK_SET);
366
367   memset(&state, 0, sizeof(state));
368   state.hashfile = hashfile;
369   state.selector_proc = selector_proc;
370   state.use_proc = use_proc;
371   state.error_proc = error_proc;
372   state.param = param;
373
374   /* create the XML parser */
375   memcallbacks.malloc_fcn = expat_malloc;
376   memcallbacks.realloc_fcn = expat_realloc;
377   memcallbacks.free_fcn = expat_free;
378   state.parser = XML_ParserCreate_MM(NULL, &memcallbacks, NULL);
379   if (!state.parser)
380      goto done;
381
382   XML_SetUserData(state.parser, &state);
383   XML_SetElementHandler(state.parser, start_handler, end_handler);
384   XML_SetCharacterDataHandler(state.parser, data_handler);
385
386   while(!state.done)
387   {
388      len = hashfile->file->read(buf, sizeof(buf));
389      state.done = hashfile->file->eof();
390      if (XML_Parse(state.parser, buf, len, state.done) == XML_STATUS_ERROR)
391      {
392         parse_error(&state, "[%lu:%lu]: %s\n",
393            XML_GetCurrentLineNumber(state.parser),
394            XML_GetCurrentColumnNumber(state.parser),
395            XML_ErrorString(XML_GetErrorCode(state.parser)));
396         goto done;
397      }
398   }
399
400done:
401   if (state.parser)
402      XML_ParserFree(state.parser);
403}
404
405
406
407/*-------------------------------------------------
408    preload_use_proc
409-------------------------------------------------*/
410
411static void preload_use_proc(hash_file *hashfile, void *param, hash_info *hi)
412{
413   hash_info **new_preloaded_hashes;
414
415   new_preloaded_hashes = (hash_info **)pool_realloc_lib(hashfile->pool, hashfile->preloaded_hashes,
416      (hashfile->preloaded_hash_count + 1) * sizeof(*new_preloaded_hashes));
417   if (!new_preloaded_hashes)
418      return;
419
420   hashfile->preloaded_hashes = new_preloaded_hashes;
421   hashfile->preloaded_hashes[hashfile->preloaded_hash_count++] = hi;
422}
423
424
425
426/*-------------------------------------------------
427    hashfile_open
428-------------------------------------------------*/
429
430hash_file *hashfile_open(emu_options &options, const char *sysname, int is_preload,
431   void (*error_proc)(const char *message))
432{
433   hash_file *hashfile = NULL;
434   object_pool *pool = NULL;
435   file_error filerr;
436
437   /* create a pool for this hash file */
438   pool = pool_alloc_lib(error_proc);
439   if (!pool)
440      goto error;
441
442   /* allocate space for this hash file */
443   hashfile = (hash_file *) pool_malloc_lib(pool, sizeof(*hashfile));
444   if (!hashfile)
445      goto error;
446
447   /* set up the hashfile structure */
448   memset(hashfile, 0, sizeof(*hashfile));
449   hashfile->pool = pool;
450   hashfile->error_proc = error_proc;
451
452   /* open a file */
453   hashfile->file = global_alloc(emu_file(options.hash_path(), OPEN_FLAG_READ));
454   filerr = hashfile->file->open(sysname, ".hsi");
455   if (filerr != FILERR_NONE)
456   {
457      global_free(hashfile->file);
458      hashfile->file = NULL;
459      goto error;
460   }
461
462   if (is_preload)
463      hashfile_parse(hashfile, NULL, preload_use_proc, hashfile->error_proc, NULL);
464
465   return hashfile;
466
467error:
468   if (hashfile != NULL)
469      hashfile_close(hashfile);
470   return NULL;
471}
472
473
474
475/*-------------------------------------------------
476    hashfile_close
477-------------------------------------------------*/
478
479void hashfile_close(hash_file *hashfile)
480{
481   global_free(hashfile->file);
482   pool_free_lib(hashfile->pool);
483}
484
485
486
487/*-------------------------------------------------
488    singular_selector_proc
489-------------------------------------------------*/
490
491struct hashlookup_params
492{
493   const hash_collection *hashes;
494   hash_info *hi;
495};
496
497static int singular_selector_proc(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes)
498{
499   astring tempstr;
500   struct hashlookup_params *hlparams = (struct hashlookup_params *) param;
501   return (*hashes == *hlparams->hashes);
502}
503
504
505
506/*-------------------------------------------------
507    singular_use_proc
508-------------------------------------------------*/
509
510static void singular_use_proc(hash_file *hashfile, void *param, hash_info *hi)
511{
512   struct hashlookup_params *hlparams = (struct hashlookup_params *) param;
513   hlparams->hi = hi;
514}
515
516
517
518/*-------------------------------------------------
519    hashfile_lookup
520-------------------------------------------------*/
521
522const hash_info *hashfile_lookup(hash_file *hashfile, const hash_collection *hashes)
523{
524   struct hashlookup_params param;
525   int i;
526
527   param.hashes = hashes;
528   param.hi = NULL;
529
530   for (i = 0; i < hashfile->preloaded_hash_count; i++)
531   {
532      if (singular_selector_proc(hashfile, &param, NULL, hashfile->preloaded_hashes[i]->hashes))
533         return hashfile->preloaded_hashes[i];
534   }
535
536   hashfile_parse(hashfile, singular_selector_proc, singular_use_proc,
537      hashfile->error_proc, (void *) &param);
538   return param.hi;
539}
540
541const char *extra_info = NULL;
542
543const char *read_hash_config(device_image_interface &image, const char *sysname)
544{
545   hash_file *hashfile = NULL;
546   const hash_info *info = NULL;
547
548   /* open the hash file */
549   hashfile = hashfile_open(image.device().machine().options(), sysname, FALSE, NULL);
550   if (!hashfile)
551      return NULL;
552
553   /* look up this entry in the hash file */
554   info = hashfile_lookup(hashfile, &image.hash());
555
556   if (!info || !info->extrainfo)
557   {
558      hashfile_close(hashfile);
559      return NULL;
560   }
561
562   extra_info = auto_strdup(image.device().machine(),info->extrainfo);
563   if (!extra_info)
564   {
565      hashfile_close(hashfile);
566      return NULL;
567   }
568
569   /* copy the relevant entries */
570   hashfile_close(hashfile);
571
572   return extra_info;
573}
574
575const char *hashfile_extrainfo(device_image_interface &image)
576{
577   const char *rc;
578
579   /* now read the hash file */
580   image.crc();
581   extra_info = NULL;
582   int drv = driver_list::find(image.device().machine().system());
583   do
584   {
585      rc = read_hash_config(image,driver_list::driver(drv).name);
586      drv = driver_list::compatible_with(drv);
587   }
588   while(rc!=NULL && drv != -1);
589   return rc;
590}
591
592/***************************************************************************
593    EXPAT INTERFACES
594***************************************************************************/
595
596/*-------------------------------------------------
597    expat_malloc/expat_realloc/expat_free -
598    wrappers for memory allocation functions so
599    that they pass through out memory tracking
600    systems
601-------------------------------------------------*/
602
603static void *expat_malloc(size_t size)
604{
605   return global_alloc_array_clear(UINT8,size);
606}
607
608static void *expat_realloc(void *ptr, size_t size)
609{
610   if (ptr) global_free(ptr);
611   return global_alloc_array_clear(UINT8,size);
612}
613
614static void expat_free(void *ptr)
615{
616   global_free(ptr);
617}
src/emu/hashfile.h
r0r11451
1/*********************************************************************
2
3    hashfile.h
4
5    Code for parsing hash info (*.hsi) files
6
7*********************************************************************/
8
9#ifndef __HASHFILE_H__
10#define __HASHFILE_H__
11
12#include "emu.h"
13
14
15const char *hashfile_extrainfo(device_image_interface &image);
16
17#endif /* __HASHFILE_H__ */
src/emu/emu.mak
r11450r11451
4444#-------------------------------------------------
4545
4646EMUOBJS = \
47   $(EMUOBJ)/hashfile.o \
4748   $(EMUOBJ)/addrmap.o \
4849   $(EMUOBJ)/attotime.o \
4950   $(EMUOBJ)/audit.o \
r11450r11451
163164   $(EMUMACHINE)/cdp1871.o      \
164165   $(EMUMACHINE)/com8116.o      \
165166   $(EMUMACHINE)/cr589.o      \
167   $(EMUMACHINE)/ctronics.o   \
166168   $(EMUMACHINE)/ds1302.o      \
167169   $(EMUMACHINE)/ds2401.o      \
168170   $(EMUMACHINE)/ds2404.o      \
r11450r11451
204206   $(EMUMACHINE)/msm5832.o   \
205207   $(EMUMACHINE)/msm58321.o   \
206208   $(EMUMACHINE)/msm6242.o      \
209   $(EMUMACHINE)/msm8251.o      \
207210   $(EMUMACHINE)/nmc9306.o      \
208211   $(EMUMACHINE)/nvram.o      \
209212   $(EMUMACHINE)/pc16552d.o   \
r11450r11451
225228   $(EMUMACHINE)/scsidev.o      \
226229   $(EMUMACHINE)/scsihd.o      \
227230   $(EMUMACHINE)/secflash.o   \
231   $(EMUMACHINE)/serial.o   \
228232   $(EMUMACHINE)/smc91c9x.o   \
229233   $(EMUMACHINE)/timekpr.o      \
230234   $(EMUMACHINE)/tmp68301.o   \
r11450r11451
232236   $(EMUMACHINE)/upd1990a.o   \
233237   $(EMUMACHINE)/upd4701.o      \
234238   $(EMUMACHINE)/upd7201.o      \
239   $(EMUMACHINE)/upd765.o      \
235240   $(EMUMACHINE)/wd33c93.o      \
236241   $(EMUMACHINE)/x2212.o      \
237242   $(EMUMACHINE)/x76f041.o      \
src/emu/machine/upd765.c
r0r11451
1/***************************************************************************
2
3    machine/upd765.c
4
5    Functions to emulate a UPD765/Intel 8272 compatible floppy disk controller
6
7    Code by Kevin Thacker.
8
9    TODO:
10
11    - overrun condition
12    - Scan Commands
13    - crc error in id field and crc error in data field errors
14    - disc not present, and no sectors on track for data, deleted data, write, write deleted,
15        read a track etc
16        - end of cylinder condition - almost working, needs fixing  with
17                PCW and PC drivers
18    - resolve "ready" state stuff (ready state when reset for PC, ready state change while processing command AND
19    while idle)
20
21    Changes:
22    091006 (Mariusz Wojcieszek, changes needed by QX-10):
23    - allowed "Sense Interrupt Status" command when Seek is active
24    - DIO bit in status register (0x40) is cleared when "Read Data" command is executed,
25      it is later set during result phase.
26
27***************************************************************************/
28
29#include "emu.h"
30#include "machine/upd765.h"
31
32
33typedef enum
34{
35   UPD765_COMMAND_PHASE_FIRST_BYTE,
36   UPD765_COMMAND_PHASE_BYTES,
37   UPD765_RESULT_PHASE,
38   UPD765_EXECUTION_PHASE_READ,
39   UPD765_EXECUTION_PHASE_WRITE
40} UPD765_PHASE;
41
42/* supported versions */
43typedef enum
44{
45   TYPE_UPD765A = 0,
46   TYPE_UPD765B = 1,
47   TYPE_SMC37C78 = 2,
48   TYPE_UPD72065 = 3
49} UPD765_VERSION;
50
51
52/* uncomment the following line for verbose information */
53#define LOG_VERBOSE      0
54#define LOG_COMMAND      0
55#define LOG_EXTRA      0
56#define LOG_INTERRUPT   0
57
58/* uncomment this to not allow end of cylinder "error" */
59#define NO_END_OF_CYLINDER
60
61
62
63/* state of upd765 Interrupt (INT) output */
64#define UPD765_INT   0x02
65/* data rate for floppy discs (MFM data) */
66#define UPD765_DATA_RATE   32
67/* state of upd765 terminal count input*/
68#define UPD765_TC   0x04
69
70#define UPD765_DMA_MODE 0x08
71
72#define UPD765_SEEK_OPERATION_IS_RECALIBRATE 0x01
73
74#define UPD765_SEEK_ACTIVE 0x010
75/* state of upd765 DMA DRQ output */
76#define UPD765_DMA_DRQ 0x020
77/* state of upd765 FDD READY input */
78#define UPD765_FDD_READY 0x040
79
80#define UPD765_MF   0x40
81
82#define UPD765_RESET 0x080
83
84typedef struct _upd765_t upd765_t;
85struct _upd765_t
86{
87   devcb_resolved_write_line   out_int_func;
88   devcb_resolved_write_line   out_drq_func;
89
90   unsigned long   sector_counter;
91   /* version of fdc to emulate */
92   UPD765_VERSION version;
93
94   /* main status register */
95   unsigned char    FDC_main;
96   /* data register */
97   unsigned char   upd765_data_reg;
98
99   unsigned char c,h,r,n;
100
101   int sector_id;
102
103   int data_type;
104
105   char format_data[4];
106
107   UPD765_PHASE    upd765_phase;
108   unsigned int    upd765_command_bytes[16];
109   unsigned int    upd765_result_bytes[16];
110   unsigned int    upd765_transfer_bytes_remaining;
111   unsigned int    upd765_transfer_bytes_count;
112   unsigned int    upd765_status[4];
113   /* present cylinder number per drive */
114   unsigned int    pcn[4];
115
116   /* drive being accessed. drive outputs from fdc */
117   unsigned int    drive;
118   /* side being accessed: side output from fdc */
119   unsigned int   side;
120
121
122   /* step rate time in us */
123   unsigned long   srt_in_ms;
124
125   unsigned int   ncn;
126
127//  unsigned int    upd765_id_index;
128   char *execution_phase_data;
129   unsigned int   upd765_flags;
130
131//  unsigned char specify[2];
132//  unsigned char perpendicular_mode[1];
133
134   int command;
135
136   emu_timer *seek_timer;
137   emu_timer *timer;
138   int timer_type;
139
140   emu_timer *command_timer;
141
142   char *data_buffer;
143   const upd765_interface *intf;
144};
145
146//static void upd765_setup_data_request(unsigned char Data);
147static void upd765_setup_command(device_t *device);
148static TIMER_CALLBACK(upd765_continue_command);
149static int upd765_sector_count_complete(device_t *device);
150static void upd765_increment_sector(device_t *device);
151static void upd765_update_state(device_t *device);
152static void upd765_set_dma_drq(device_t *device,int state);
153static void upd765_set_int(device_t *device,int state);
154
155static const INT8 upd765_cmd_size[32] =
156{
157   1,1,9,3,2,9,9,2,1,9,2,1,9,6,1,3,
158   1,9,1,1,1,1,9,1,1,9,1,1,1,9,1,1
159};
160
161INLINE upd765_t *get_safe_token(device_t *device)
162{
163   assert(device != NULL);
164   assert(device->type() == UPD765A || device->type() == UPD765B ||
165      device->type() == SMC37C78 || device->type() == UPD72065);
166
167   return (upd765_t *)downcast<legacy_device_base *>(device)->token();
168}
169
170static device_t *current_image(device_t *device)
171{
172   device_t *image = NULL;
173   upd765_t *fdc = get_safe_token(device);
174
175   if (!fdc->intf->get_image)
176   {
177      if (fdc->intf->floppy_drive_tags[fdc->drive] != NULL)
178      {
179         if (device->owner() != NULL)
180            image = device->owner()->subdevice(fdc->intf->floppy_drive_tags[fdc->drive]);
181         else
182            image = device->machine().device(fdc->intf->floppy_drive_tags[fdc->drive]);
183      }
184   }
185   else
186   {
187      image = fdc->intf->get_image(device, fdc->drive);
188   }
189   return image;
190}
191
192static void upd765_setup_drive_and_side(device_t *device)
193{
194   upd765_t *fdc = get_safe_token(device);
195   /* drive index upd765 sees */
196   fdc->drive = fdc->upd765_command_bytes[1] & 0x03;
197   /* side index upd765 sees */
198   fdc->side = (fdc->upd765_command_bytes[1]>>2) & 0x01;
199}
200
201
202/* setup status register 0 based on data in status register 1 and 2 */
203static void upd765_setup_st0(device_t *device)
204{
205   upd765_t *fdc = get_safe_token(device);
206   /* clear completition status bits, drive bits and side bits */
207   fdc->upd765_status[0] &= ~((1<<7) | (1<<6) | (1<<2) | (1<<1) | (1<<0));
208   /* fill in drive */
209   fdc->upd765_status[0] |= fdc->drive | (fdc->side<<2);
210
211   /* fill in completion status bits based on bits in st0, st1, st2 */
212   /* no error bits set */
213   if ((fdc->upd765_status[1] | fdc->upd765_status[2])==0)
214   {
215      return;
216   }
217
218   fdc->upd765_status[0] |= 0x040;
219}
220
221
222static int upd765_n_to_bytes(int n)
223{
224   /* 0-> 128 bytes, 1->256 bytes, 2->512 bytes etc */
225   /* data_size = ((1<<(N+7)) */
226   return 1<<(n+7);
227}
228
229static void upd765_set_data_request(device_t *device)
230{
231   upd765_t *fdc = get_safe_token(device);
232   fdc->FDC_main |= 0x080;
233}
234
235static void upd765_clear_data_request(device_t *device)
236{
237   upd765_t *fdc = get_safe_token(device);
238   fdc->FDC_main &= ~0x080;
239}
240
241static int upd765_get_rdy(device_t *device)
242{
243   upd765_t *fdc = get_safe_token(device);
244
245   if (fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED)
246   {
247      device_t *img = current_image(device);
248      return floppy_drive_get_flag_state(img, FLOPPY_DRIVE_READY);
249   }
250   else
251      return 1;
252}
253
254static void upd765_seek_complete(device_t *device)
255{
256   /* tested on Amstrad CPC */
257
258   /* if a seek is done without drive connected: */
259   /*  abnormal termination of command,
260        seek complete,
261        not ready
262    */
263
264   /* if a seek is done with drive connected, but disc missing: */
265   /* abnormal termination of command,
266        seek complete,
267        not ready */
268
269   /* if a seek is done with drive connected and disc in drive */
270   /* seek complete */
271
272
273   /* On the PC however, it appears that recalibrates and seeks can be performed without
274    a disc in the drive. */
275
276   /* Therefore, the above output is dependant on the state of the drive */
277
278   /* In the Amstrad CPC, the drive select is provided by the UPD765. A single port is also
279    assigned for setting the drive motor state. The motor state controls the motor of the selected
280    drive */
281
282   /* On the PC the drive can be selected with the DIGITAL OUTPUT REGISTER, and the motor of each
283    of the 4 possible drives is also settable using the same register */
284
285   /* Assumption for PC: (NOT TESTED - NEEDS VERIFICATION) */
286
287   /* If a seek is done without drive connected: */
288   /* abnormal termination of command,
289        seek complete,
290        fault
291        */
292
293   /* if a seek is done with drive connected, but disc missing: */
294   /* seek complete */
295
296   /* if a seek is done with drive connected and disc in drive: */
297   /* seek complete */
298
299   /* On Amstrad CPC:
300        If drive not connected, or drive connected but disc not in drive, not ready!
301        If drive connected and drive motor on, ready!
302       On PC:
303        Drive is always ready!
304
305        In 37c78 docs, the ready bits of the upd765 are marked as unused.
306        This indicates it is always ready!!!!!
307    */
308
309   device_t *img = current_image(device);
310   upd765_t *fdc = get_safe_token(device);
311
312   fdc->pcn[fdc->drive] = fdc->ncn;
313
314   fdc->upd765_status[0] = 0x20;
315
316   /* drive ready? */
317   if (img != NULL && upd765_get_rdy(device))
318   {
319      /* recalibrate? */
320      if (fdc->upd765_flags & UPD765_SEEK_OPERATION_IS_RECALIBRATE)
321      {
322         /* not at track 0? */
323         if (fdc->pcn[fdc->drive] != 0)
324            /* no, track 0 failed after 77 steps */
325            fdc->upd765_status[0] |= 0x40 | 0x10;
326      }
327   }
328   else
329   {
330      /* abnormal termination, not ready */
331      fdc->upd765_status[0] |= 0x40 | 0x08;
332   }
333
334   /* set drive and side. note: commented out side to avoid problems with the tf20 */
335   fdc->upd765_status[0] |= fdc->drive; //| (fdc->side<<2);
336
337   upd765_set_int(device,0);
338   upd765_set_int(device,1);
339
340   fdc->upd765_flags &= ~UPD765_SEEK_ACTIVE;
341
342   upd765_idle(device);
343}
344
345static TIMER_CALLBACK(upd765_seek_timer_callback)
346{
347   device_t *device = (device_t *)ptr;
348   upd765_t *fdc = get_safe_token(device);
349   /* seek complete */
350   upd765_seek_complete(device);
351
352   fdc->seek_timer->reset();
353}
354
355static void upd765_timer_func(device_t *device, int timer_type)
356{
357   upd765_t *fdc = get_safe_token(device);
358   /* type 0 = data transfer mode in execution phase */
359   if (fdc->timer_type == 0)
360   {
361      /* set data request */
362      upd765_set_data_request(device);
363
364      fdc->timer_type = 4;
365
366      if (!(fdc->upd765_flags & UPD765_DMA_MODE))
367      {
368         if (fdc->upd765_command_bytes[0] & UPD765_MF)
369         {
370            /* MFM */
371            fdc->timer->reset(attotime::from_usec(13));
372         }
373         else
374         {
375            /* FM */
376            fdc->timer->reset(attotime::from_usec(27));
377         }
378      }
379      else
380      {
381         upd765_timer_func(device, fdc->timer_type);
382      }
383   }
384   else if (fdc->timer_type==2)
385   {
386      /* result phase begin */
387
388      /* generate a int for specific commands */
389      switch (fdc->command) {
390      case 2:      /* read a track */
391      case 5:      /* write data */
392      case 6:      /* read data */
393      case 9:      /* write deleted data */
394      case 10:   /* read id */
395      case 12:   /* read deleted data */
396      case 13:   /* format at track */
397      case 17:   /* scan equal */
398      case 19:   /* scan low or equal */
399      case 29:   /* scan high or equal */
400         upd765_set_int(device,1);
401         break;
402
403      default:
404         break;
405      }
406
407      upd765_set_data_request(device);
408
409      fdc->timer->reset();
410   }
411   else if (fdc->timer_type == 4)
412   {
413      /* if in dma mode, a int is not generated per byte. If not in  DMA mode
414        a int is generated per byte */
415      if (fdc->upd765_flags & UPD765_DMA_MODE)
416      {
417         upd765_set_dma_drq(device,1);
418      }
419      else
420      {
421         if (fdc->FDC_main & (1<<7))
422         {
423            /* set int to indicate data is ready */
424            upd765_set_int(device,1);
425         }
426      }
427
428      fdc->timer->reset();
429   }
430}
431
432static TIMER_CALLBACK(upd765_timer_callback)
433{
434   device_t *device = (device_t *)ptr;
435   upd765_timer_func(device,param);
436}
437
438/* after (32-27) the DRQ is set, then 27 us later, the int is set.
439I don't know if this is correct, but it is required for the PCW driver.
440In this driver, the first NMI calls the handler function, furthur NMI's are
441effectively disabled by reading the data before the NMI int can be set.
442*/
443
444static void upd765_setup_timed_generic(device_t *device, int timer_type, attotime duration)
445{
446   upd765_t *fdc = get_safe_token(device);
447
448   fdc->timer_type = timer_type;
449
450   if (!(fdc->upd765_flags & UPD765_DMA_MODE))
451   {
452      fdc->timer->adjust(duration);
453   }
454   else
455   {
456      upd765_timer_func(device,fdc->timer_type);
457      fdc->timer->reset();
458   }
459}
460
461/* setup data request */
462static void upd765_setup_timed_data_request(device_t *device, int bytes)
463{
464   /* setup timer to trigger in UPD765_DATA_RATE us */
465   upd765_setup_timed_generic(device, 0, attotime::from_usec(32-27)   /*UPD765_DATA_RATE)*bytes*/);
466}
467
468/* setup result data request */
469static void upd765_setup_timed_result_data_request(device_t *device)
470{
471   upd765_setup_timed_generic(device, 2, attotime::from_usec(UPD765_DATA_RATE*2));
472}
473
474
475/* sets up a timer to issue a seek complete in signed_tracks time */
476static void upd765_setup_timed_int(device_t *device,int signed_tracks)
477{
478   upd765_t *fdc = get_safe_token(device);
479   /* setup timer to signal after seek time is complete */
480   fdc->seek_timer->adjust(attotime::from_double(fdc->srt_in_ms*abs(signed_tracks)*0.001));
481}
482
483static void upd765_seek_setup(device_t *device, int is_recalibrate)
484{
485   device_t *img;
486   int signed_tracks;
487   upd765_t *fdc = get_safe_token(device);
488
489   fdc->upd765_flags |= UPD765_SEEK_ACTIVE;
490
491   if (is_recalibrate)
492   {
493      /* head cannot be specified with recalibrate */
494      fdc->upd765_command_bytes[1] &=~0x04;
495   }
496
497   upd765_setup_drive_and_side(device);
498
499   img = current_image(device);
500
501   fdc->FDC_main |= (1<<fdc->drive);
502   fdc->FDC_main |= 0x20;  // execution phase
503   fdc->FDC_main &= ~0x10;  // not busy, can send another seek/recalibrate
504                            // for a different drive, or sense int status
505
506   /* recalibrate command? */
507   if (is_recalibrate)
508   {
509      fdc->upd765_flags |= UPD765_SEEK_OPERATION_IS_RECALIBRATE;
510
511      fdc->ncn = 0;
512
513      /* if drive is already at track 0, or drive is not ready */
514      if (img == NULL || floppy_tk00_r(img) == CLEAR_LINE || (!upd765_get_rdy(device)))
515      {
516         /* seek completed */
517//          upd765_seek_complete(device);
518         // delay for the time of 1 step, the PCW does not like immediate recalibrates
519         upd765_setup_timed_int(device,1);
520      }
521      else
522      {
523         /* is drive present? */
524         if (1) //image_slotexists(img)) //fix me
525         {
526            /* yes - calculate real number of tracks to seek */
527
528            int current_track;
529
530            /* get current track */
531            current_track = floppy_drive_get_current_track(img);
532
533            /* get number of tracks to seek */
534            signed_tracks = -current_track;
535         }
536         else
537         {
538            /* no, seek 77 tracks and then stop */
539            /* true for UPD765A, but not for other variants */
540            signed_tracks = -77;
541         }
542
543         if (signed_tracks!=0)
544         {
545            /* perform seek - if drive isn't present it will not do anything */
546            floppy_drive_seek(img, signed_tracks);
547
548            upd765_setup_timed_int(device,signed_tracks);
549         }
550         else
551         {
552            upd765_seek_complete(device);
553         }
554      }
555   }
556   else
557   {
558
559      fdc->upd765_flags &= ~UPD765_SEEK_OPERATION_IS_RECALIBRATE;
560
561      fdc->ncn = fdc->upd765_command_bytes[2];
562
563      /* get signed tracks */
564      signed_tracks = fdc->ncn - fdc->pcn[fdc->drive];
565
566      /* if no tracks to seek, or drive is not ready, seek is complete */
567      if (img == NULL || (signed_tracks==0) || (!upd765_get_rdy(device)))
568      {
569         upd765_seek_complete(device);
570      }
571      else
572      {
573         /* perform seek - if drive isn't present it will not do anything */
574         floppy_drive_seek(img, signed_tracks);
575
576         /* seek complete - issue an interrupt */
577         upd765_setup_timed_int(device,signed_tracks);
578      }
579   }
580//    upd765_idle(device);
581}
582
583
584
585static void upd765_setup_execution_phase_read(device_t *device, char *ptr, int size)
586{
587   upd765_t *fdc = get_safe_token(device);
588
589   fdc->FDC_main &= ~0x040;                     /* FDC->CPU */
590
591   fdc->upd765_transfer_bytes_count = 0;
592   fdc->upd765_transfer_bytes_remaining = size;
593   fdc->execution_phase_data = ptr;
594   fdc->upd765_phase = UPD765_EXECUTION_PHASE_READ;
595
596   upd765_setup_timed_data_request(device, 1);
597}
598
599static void upd765_setup_execution_phase_write(device_t *device, char *ptr, int size)
600{
601   upd765_t *fdc = get_safe_token(device);
602
603   fdc->FDC_main &= ~0x040;                     /* FDC->CPU */
604
605   fdc->upd765_transfer_bytes_count = 0;
606   fdc->upd765_transfer_bytes_remaining = size;
607   fdc->execution_phase_data = ptr;
608   fdc->upd765_phase = UPD765_EXECUTION_PHASE_WRITE;
609
610   /* setup a data request with first byte */
611   upd765_setup_timed_data_request(device,1);
612}
613
614
615static void upd765_setup_result_phase(device_t *device, int byte_count)
616{
617   upd765_t *fdc = get_safe_token(device);
618
619   fdc->FDC_main |= 0x040;                     /* FDC->CPU */
620   fdc->FDC_main &= ~0x020;                    /* not execution phase */
621
622   fdc->upd765_transfer_bytes_count = 0;
623   fdc->upd765_transfer_bytes_remaining = byte_count;
624   fdc->upd765_phase = UPD765_RESULT_PHASE;
625
626   upd765_setup_timed_result_data_request(device);
627}
628
629void upd765_idle(device_t *device)
630{
631   upd765_t *fdc = get_safe_token(device);
632
633   fdc->FDC_main &= ~0x040;                     /* CPU->FDC */
634   fdc->FDC_main &= ~0x020;                    /* not execution phase */
635   fdc->FDC_main &= ~0x010;                     /* not busy */
636   fdc->upd765_phase = UPD765_COMMAND_PHASE_FIRST_BYTE;
637
638   upd765_set_data_request(device);
639}
640
641
642
643/* change flags */
644static void upd765_change_flags(device_t *device,unsigned int flags, unsigned int mask)
645{
646   unsigned int new_flags;
647   unsigned int changed_flags;
648   upd765_t *fdc = get_safe_token(device);
649
650   assert((flags & ~mask) == 0);
651
652   /* compute the new flags and which ones have changed */
653   new_flags = fdc->upd765_flags & ~mask;
654   new_flags |= flags;
655   changed_flags = fdc->upd765_flags ^ new_flags;
656   fdc->upd765_flags = new_flags;
657
658   /* if interrupt changed, call the handler */
659   if (changed_flags & UPD765_INT)
660      fdc->out_int_func((fdc->upd765_flags & UPD765_INT) ? 1 : 0);
661
662   /* if DRQ changed, call the handler */
663   if (changed_flags & UPD765_DMA_DRQ)
664      fdc->out_drq_func((fdc->upd765_flags & UPD765_DMA_DRQ) ? 1 : 0);
665}
666
667
668
669/* set int output */
670static void upd765_set_int(device_t *device, int state)
671{
672   if (LOG_INTERRUPT)
673      logerror("upd765_set_int(): state=%d\n", state);
674   upd765_change_flags(device, state ? UPD765_INT : 0, UPD765_INT);
675}
676
677
678
679/* set dma request output */
680static void upd765_set_dma_drq(device_t *device, int state)
681{
682   upd765_change_flags(device, state ? UPD765_DMA_DRQ : 0, UPD765_DMA_DRQ);
683}
684
685
686
687/* Drive ready */
688
689/*
690
691A drive will report ready if:
692- drive is selected
693- disc is in the drive
694- disk is rotating at a constant speed (normally 300rpm)
695
696On more modern PCs, a ready signal is not provided by the drive.
697This signal is not used in the PC design and was eliminated to save costs
698If you look at the datasheets for the modern UPD765 variants, you will see the Ready
699signal is not mentioned.
700
701On the original UPD765A, ready signal is required, and some commands will fail if the drive
702is not ready.
703
704
705
706
707*/
708
709
710
711
712/* done when ready state of drive changes */
713/* this ignores if command is active, in which case command should terminate immediatly
714with error */
715static void upd765_set_ready_change_callback(device_t *controller, device_t *img, int state)
716{
717   upd765_t *fdc = get_safe_token(controller);
718   int drive = floppy_get_drive(img);
719
720   if (LOG_EXTRA)
721      logerror("upd765: ready state change\n");
722
723   /* drive that changed state */
724   fdc->upd765_status[0] = 0x0c0 | drive;
725
726   /* not ready */
727   if (state==0 && fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED )
728      fdc->upd765_status[0] |= 8;
729
730   /* trigger an int */
731   upd765_set_int(controller, 1);
732}
733
734
735/* terminal count input */
736WRITE_LINE_DEVICE_HANDLER( upd765_tc_w )
737{
738   int old_state;
739   upd765_t *fdc = get_safe_token(device);
740
741   old_state = fdc->upd765_flags;
742
743   /* clear drq */
744   upd765_set_dma_drq(device, 0);
745
746   fdc->upd765_flags &= ~UPD765_TC;
747   if (state)
748   {
749      fdc->upd765_flags |= UPD765_TC;
750   }
751
752   /* changed state? */
753   if (((fdc->upd765_flags^old_state) & UPD765_TC)!=0)
754   {
755      /* now set? */
756      if ((fdc->upd765_flags & UPD765_TC)!=0)
757      {
758         /* yes */
759         if (fdc->timer)
760         {
761            if (fdc->timer_type==0)
762            {
763               fdc->timer->reset();
764
765
766            }
767         }
768
769#ifdef NO_END_OF_CYLINDER
770         fdc->command_timer->adjust(attotime::zero);
771#else
772         upd765_update_state(device);
773#endif
774      }
775   }
776}
777
778READ8_DEVICE_HANDLER( upd765_status_r )
779{
780   upd765_t *fdc = get_safe_token(device);
781   if (LOG_EXTRA)
782      logerror("%s: upd765_status_r: %02x\n", device->machine().describe_context(), fdc->FDC_main);
783   return fdc->FDC_main;
784}
785
786
787/* control mark handling code */
788
789/* if SK==1, and we are executing a read data command, and a deleted data mark is found,
790skip it.
791if SK==1, and we are executing a read deleted data command, and a data mark is found,
792skip it. */
793
794static int upd765_read_skip_sector(device_t *device)
795{
796   upd765_t *fdc = get_safe_token(device);
797   /* skip set? */
798   if ((fdc->upd765_command_bytes[0] & (1<<5))!=0)
799   {
800      /* read data? */
801      if (fdc->command == 0x06)
802      {
803         /* did we just find a sector with deleted data mark? */
804         if (fdc->data_type == UPD765_DAM_DELETED_DATA)
805         {
806            /* skip it */
807            return TRUE;
808         }
809      }
810      /* deleted data? */
811      else
812      if (fdc->command == 0x0c)
813      {
814         /* did we just find a sector with data mark ? */
815         if (fdc->data_type == UPD765_DAM_DATA)
816         {
817            /* skip it */
818            return TRUE;
819         }
820      }
821   }
822
823   /* do not skip */
824   return FALSE;
825}
826
827/* this is much closer to how the upd765 actually gets sectors */
828/* used by read data, read deleted data, write data, write deleted data */
829/* What the upd765 does:
830
831  - get next sector id from disc
832  - if sector id matches id specified in command, it will
833    search for next data block and read data from it.
834
835  - if the index is seen twice while it is searching for a sector, then the sector cannot be found
836*/
837
838static void upd765_get_next_id(device_t *device, chrn_id *id)
839{
840   upd765_t *fdc = get_safe_token(device);
841   device_t *img = current_image(device);
842
843   /* get next id from disc */
844   floppy_drive_get_next_id(img, fdc->side,id);
845
846   fdc->sector_id = id->data_id;
847
848   /* set correct data type */
849   fdc->data_type = UPD765_DAM_DATA;
850   if (id->flags & ID_FLAG_DELETED_DATA)
851   {
852      fdc->data_type = UPD765_DAM_DELETED_DATA;
853   }
854}
855
856static int upd765_get_matching_sector(device_t *device)
857{
858   upd765_t *fdc = get_safe_token(device);
859   device_t *img = current_image(device);
860   chrn_id id;
861
862   /* number of times we have seen index hole */
863   int index_count = 0;
864
865   /* get sector id's */
866   do
867    {
868      upd765_get_next_id(device, &id);
869
870      /* tested on Amstrad CPC - All bytes must match, otherwise
871        a NO DATA error is reported */
872      if (id.R == fdc->upd765_command_bytes[4])
873      {
874         if (id.C == fdc->upd765_command_bytes[2])
875         {
876            if (id.H == fdc->upd765_command_bytes[3])
877            {
878               if (id.N == fdc->upd765_command_bytes[5])
879               {
880                  /* end of cylinder is set if:
881                        1. sector data is read completely (i.e. no other errors occur like
882                        no data.
883                        2. sector being read is same specified by EOT
884                        3. terminal count is not received */
885                  if (fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6])
886                  {
887                     /* set end of cylinder */
888                     fdc->upd765_status[1] |= UPD765_ST1_END_OF_CYLINDER;
889                  }
890
891                  return TRUE;
892               }
893            }
894         }
895         else
896         {
897            /* the specified sector ID was found, however, the C value specified
898                in the read/write command did not match the C value read from the disc */
899
900            /* no data - checked on Amstrad CPC */
901            fdc->upd765_status[1] |= UPD765_ST1_NO_DATA;
902            /* bad C value */
903            fdc->upd765_status[2] |= UPD765_ST2_WRONG_CYLINDER;
904
905            if (id.C == 0x0ff)
906            {
907               /* the C value is 0x0ff which indicates a bad track in the IBM soft-sectored
908                    format */
909               fdc->upd765_status[2] |= UPD765_ST2_BAD_CYLINDER;
910            }
911
912            return FALSE;
913         }
914      }
915
916       /* index set? */
917      if (floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))
918      {
919         index_count++;
920      }
921
922   }
923   while (index_count!=2);
924
925   if (fdc->upd765_command_bytes[4] != fdc->upd765_command_bytes[6])
926   {
927      /* no data - specified sector ID was not found */
928      fdc->upd765_status[1] |= UPD765_ST1_NO_DATA;
929   }
930
931   return 0;
932}
933
934static void upd765_read_complete(device_t *device)
935{
936   upd765_t *fdc = get_safe_token(device);
937/* causes problems!!! - need to fix */
938#ifdef NO_END_OF_CYLINDER
939   /* set end of cylinder */
940   fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
941#else
942   /* completed read command */
943
944   /* end of cylinder is set when:
945        - a whole sector has been read
946        - terminal count input is not set
947        - AND the the sector specified by EOT was read
948        */
949
950   /* if end of cylinder is set, and we did receive a terminal count, then clear it */
951   if ((fdc->upd765_flags & UPD765_TC)!=0)
952   {
953      /* set end of cylinder */
954      fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
955   }
956#endif
957
958   upd765_setup_st0(device);
959
960   fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
961   fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
962   fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
963   fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
964   fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
965   fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
966   fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
967
968   upd765_setup_result_phase(device,7);
969}
970
971static void upd765_read_data(device_t *device)
972{
973   upd765_t *fdc = get_safe_token(device);
974   device_t *img = current_image(device);
975
976   if (!upd765_get_rdy(device))
977   {
978      fdc->upd765_status[0] = 0x0c0 | (1<<4) | fdc->drive | (fdc->side<<2);
979      fdc->upd765_status[1] = 0x00;
980      fdc->upd765_status[2] = 0x00;
981
982      fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
983      fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
984      fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
985      fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
986      fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
987      fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
988      fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
989      upd765_setup_result_phase(device,7);
990      return;
991   }
992
993   if (LOG_VERBOSE)
994      logerror("sector c: %02x h: %02x r: %02x n: %02x\n",fdc->upd765_command_bytes[2], fdc->upd765_command_bytes[3],fdc->upd765_command_bytes[4], fdc->upd765_command_bytes[5]);
995
996   /* find a sector to read data from */
997   {
998      int found_sector_to_read;
999
1000      found_sector_to_read = 0;
1001      /* check for finished reading sectors */
1002      do
1003      {
1004         /* get matching sector */
1005         if (upd765_get_matching_sector(device))
1006         {
1007
1008            /* skip it? */
1009            if (upd765_read_skip_sector(device))
1010            {
1011               /* yes */
1012
1013               /* check that we haven't finished reading all sectors */
1014               if (upd765_sector_count_complete(device))
1015               {
1016                  /* read complete */
1017                  upd765_read_complete(device);
1018                  return;
1019               }
1020
1021               /* read not finished */
1022
1023               /* increment sector count */
1024               upd765_increment_sector(device);
1025            }
1026            else
1027            {
1028               /* found a sector to read */
1029               found_sector_to_read = 1;
1030            }
1031         }
1032         else
1033         {
1034            /* error in finding sector */
1035            upd765_read_complete(device);
1036            return;
1037         }
1038      }
1039      while (found_sector_to_read==0);
1040   }
1041
1042   {
1043      int data_size;
1044
1045      data_size = upd765_n_to_bytes(fdc->upd765_command_bytes[5]);
1046
1047      floppy_drive_read_sector_data(img, fdc->side, fdc->sector_id,fdc->data_buffer,data_size);
1048
1049        upd765_setup_execution_phase_read(device,fdc->data_buffer, data_size);
1050   }
1051}
1052
1053
1054static void upd765_format_track(device_t *device)
1055{
1056   upd765_t *fdc = get_safe_token(device);
1057   device_t *img = current_image(device);
1058
1059   /* write protected? */
1060   if (floppy_wpt_r(img) == CLEAR_LINE)
1061   {
1062      fdc->upd765_status[1] |= UPD765_ST1_NOT_WRITEABLE;
1063
1064      upd765_setup_st0(device);
1065      /* TODO: Check result is correct */
1066         fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1067            fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1068            fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1069         fdc->upd765_result_bytes[3] = fdc->format_data[0];
1070         fdc->upd765_result_bytes[4] = fdc->format_data[1];
1071         fdc->upd765_result_bytes[5] = fdc->format_data[2];
1072         fdc->upd765_result_bytes[6] = fdc->format_data[3];
1073         upd765_setup_result_phase(device,7);
1074
1075      return;
1076   }
1077
1078    upd765_setup_execution_phase_write(device, &fdc->format_data[0], 4);
1079}
1080
1081static void upd765_read_a_track(device_t *device)
1082{
1083   upd765_t *fdc = get_safe_token(device);
1084   int data_size;
1085
1086   /* SKIP not allowed with this command! */
1087
1088   /* get next id */
1089   chrn_id id;
1090
1091   upd765_get_next_id(device, &id);
1092
1093   /* TO BE CONFIRMED! */
1094   /* check id from disc */
1095   if (id.C==fdc->upd765_command_bytes[2])
1096   {
1097      if (id.H==fdc->upd765_command_bytes[3])
1098      {
1099         if (id.R==fdc->upd765_command_bytes[4])
1100         {
1101            if (id.N==fdc->upd765_command_bytes[5])
1102            {
1103               /* if ID found, then no data is not set */
1104               /* otherwise no data will remain set */
1105               fdc->upd765_status[1] &=~UPD765_ST1_NO_DATA;
1106            }
1107         }
1108      }
1109   }
1110
1111
1112   data_size = upd765_n_to_bytes(id.N);
1113
1114   floppy_drive_read_sector_data(current_image(device), fdc->side, fdc->sector_id,fdc->data_buffer,data_size);
1115
1116   upd765_setup_execution_phase_read(device,fdc->data_buffer, data_size);
1117}
1118
1119static int upd765_just_read_last_sector_on_track(device_t *device)
1120{
1121   if (floppy_drive_get_flag_state(current_image(device), FLOPPY_DRIVE_INDEX))
1122      return 1;
1123   return 0;
1124}
1125
1126static void upd765_write_complete(device_t *device)
1127{
1128   upd765_t *fdc = get_safe_token(device);
1129
1130/* causes problems!!! - need to fix */
1131#ifdef NO_END_OF_CYLINDER
1132        /* set end of cylinder */
1133        fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
1134#else
1135   /* completed read command */
1136
1137   /* end of cylinder is set when:
1138     - a whole sector has been read
1139     - terminal count input is not set
1140     - AND the the sector specified by EOT was read
1141     */
1142
1143   /* if end of cylinder is set, and we did receive a terminal count, then clear it */
1144   if ((fdc->upd765_flags & UPD765_TC)!=0)
1145   {
1146      /* set end of cylinder */
1147      fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
1148   }
1149#endif
1150
1151   upd765_setup_st0(device);
1152
1153    fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1154    fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1155    fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1156    fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1157    fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1158    fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1159    fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1160
1161    upd765_setup_result_phase(device,7);
1162}
1163
1164
1165static void upd765_write_data(device_t *device)
1166{
1167   upd765_t *fdc = get_safe_token(device);
1168   if (!upd765_get_rdy(device))
1169   {
1170      fdc->upd765_status[0] = 0x0c0 | (1<<4) | fdc->drive | (fdc->side<<2);
1171        fdc->upd765_status[1] = 0x00;
1172        fdc->upd765_status[2] = 0x00;
1173
1174        fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1175        fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1176        fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1177        fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1178        fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1179        fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1180        fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1181      upd765_setup_result_phase(device,7);
1182      return;
1183   }
1184
1185   /* write protected? */
1186   if (floppy_wpt_r(current_image(device)) == CLEAR_LINE)
1187   {
1188      fdc->upd765_status[1] |= UPD765_ST1_NOT_WRITEABLE;
1189
1190      upd765_write_complete(device);
1191      return;
1192   }
1193
1194   if (upd765_get_matching_sector(device))
1195   {
1196      int data_size;
1197
1198      data_size = upd765_n_to_bytes(fdc->upd765_command_bytes[5]);
1199
1200        upd765_setup_execution_phase_write(device,fdc->data_buffer, data_size);
1201   }
1202    else
1203    {
1204        upd765_setup_result_phase(device,7);
1205    }
1206}
1207
1208
1209/* return true if we have read all sectors, false if not */
1210static int upd765_sector_count_complete(device_t *device)
1211{
1212   upd765_t *fdc = get_safe_token(device);
1213/* this is not correct?? */
1214#if 1
1215   /* if terminal count has been set - yes */
1216   if (fdc->upd765_flags & UPD765_TC)
1217   {
1218      /* completed */
1219      return 1;
1220   }
1221
1222
1223
1224   /* multi-track? */
1225   if (fdc->upd765_command_bytes[0] & 0x080)
1226   {
1227      /* it appears that in multi-track mode,
1228        the EOT parameter of the command is ignored!? -
1229        or is it ignored the first time and not the next, so that
1230        if it is started on side 0, it will end at EOT on side 1,
1231        but if started on side 1 it will end at end of track????
1232
1233        PC driver requires this to end at last sector on side 1, and
1234        ignore EOT parameter.
1235
1236        To be checked!!!!
1237        */
1238
1239      /* if just read last sector and on side 1 - finish */
1240      if (upd765_just_read_last_sector_on_track(device))
1241      {
1242         if (floppy_get_heads_per_disk(flopimg_get_image(current_image(device)))==1) {
1243            return 1;
1244         } else {
1245            if (fdc->side==1)
1246               return 1;
1247         }
1248      }
1249
1250      /* if not on second side then we haven't finished yet */
1251      if (fdc->side!=1)
1252      {
1253         /* haven't finished yet */
1254         return 0;
1255      }
1256   }
1257   else
1258   {
1259      /* sector id == EOT? */
1260      if ((fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6]))
1261      {
1262
1263         /* completed */
1264         return 1;
1265      }
1266   }
1267#else
1268
1269   /* if terminal count has been set - yes */
1270   if (fdc->upd765_flags & UPD765_TC)
1271   {
1272      /* completed */
1273      return 1;
1274   }
1275
1276   /* Multi-Track operation:
1277
1278    Verified on Amstrad CPC.
1279
1280        disc format used:
1281            9 sectors per track
1282            2 sides
1283            Sector IDs: &01, &02, &03, &04, &05, &06, &07, &08, &09
1284
1285        Command specified:
1286            SIDE = 0,
1287            C = 0,H = 0,R = 1, N = 2, EOT = 1
1288        Sectors read:
1289            Sector 1 side 0
1290            Sector 1 side 1
1291
1292        Command specified:
1293            SIDE = 0,
1294            C = 0,H = 0,R = 1, N = 2, EOT = 3
1295        Sectors read:
1296            Sector 1 side 0
1297            Sector 2 side 0
1298            Sector 3 side 0
1299            Sector 1 side 1
1300            Sector 2 side 1
1301            Sector 3 side 1
1302
1303
1304        Command specified:
1305            SIDE = 0,
1306            C = 0, H = 0, R = 7, N = 2, EOT = 3
1307        Sectors read:
1308            Sector 7 side 0
1309            Sector 8 side 0
1310            Sector 9 side 0
1311            Sector 10 not found. Error "No Data"
1312
1313        Command specified:
1314            SIDE = 1,
1315            C = 0, H = 1, R = 1, N = 2, EOT = 1
1316        Sectors read:
1317            Sector 1 side 1
1318
1319        Command specified:
1320            SIDE = 1,
1321            C = 0, H = 1, R = 1, N = 2, EOT = 2
1322        Sectors read:
1323            Sector 1 side 1
1324            Sector 1 side 2
1325
1326  */
1327
1328   /* sector id == EOT? */
1329   if ((fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6]))
1330   {
1331      /* multi-track? */
1332      if (fdc->upd765_command_bytes[0] & 0x080)
1333      {
1334         /* if we have reached EOT (fdc->upd765_command_bytes[6])
1335            on side 1, then read is complete */
1336         if (fdc->side==1)
1337            return 1;
1338
1339         return 0;
1340
1341      }
1342
1343      /* completed */
1344      return 1;
1345   }
1346#endif
1347   /* not complete */
1348   return 0;
1349}
1350
1351static void   upd765_increment_sector(device_t *device)
1352{
1353   upd765_t *fdc = get_safe_token(device);
1354   /* multi-track? */
1355   if (fdc->upd765_command_bytes[0] & 0x080)
1356   {
1357      /* reached EOT? */
1358      /* if (fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6])*/
1359      if (upd765_just_read_last_sector_on_track(device))
1360      {
1361         /* yes */
1362
1363         /* reached EOT */
1364         /* change side to 1 */
1365         fdc->side = 1;
1366         /* reset sector id to 1 */
1367         fdc->upd765_command_bytes[4] = 1;
1368         /* set head to 1 for get next sector test */
1369         fdc->upd765_command_bytes[3] = 1;
1370      }
1371      else
1372      {
1373         /* increment */
1374         fdc->upd765_command_bytes[4]++;
1375      }
1376
1377   }
1378   else
1379   {
1380      fdc->upd765_command_bytes[4]++;
1381   }
1382}
1383
1384/* control mark handling code */
1385
1386/* if SK==0, and we are executing a read data command, and a deleted data sector is found,
1387the data is not skipped. The data is read, but the control mark is set and the read is stopped */
1388/* if SK==0, and we are executing a read deleted data command, and a data sector is found,
1389the data is not skipped. The data is read, but the control mark is set and the read is stopped */
1390static int upd765_read_data_stop(device_t *device)
1391{
1392   upd765_t *fdc = get_safe_token(device);
1393   /* skip not set? */
1394   if ((fdc->upd765_command_bytes[0] & (1<<5))==0)
1395   {
1396      /* read data? */
1397      if (fdc->command == 0x06)
1398      {
1399         /* did we just read a sector with deleted data? */
1400         if (fdc->data_type == UPD765_DAM_DELETED_DATA)
1401         {
1402            /* set control mark */
1403            fdc->upd765_status[2] |= UPD765_ST2_CONTROL_MARK;
1404
1405            /* quit */
1406            return TRUE;
1407         }
1408      }
1409      /* deleted data? */
1410      else
1411      if (fdc->command == 0x0c)
1412      {
1413         /* did we just read a sector with data? */
1414         if (fdc->data_type == UPD765_DAM_DATA)
1415         {
1416            /* set control mark */
1417            fdc->upd765_status[2] |= UPD765_ST2_CONTROL_MARK;
1418
1419            /* quit */
1420            return TRUE;
1421         }
1422      }
1423   }
1424
1425   /* continue */
1426   return FALSE;
1427}
1428
1429static TIMER_CALLBACK(upd765_continue_command)
1430{
1431   device_t *device = (device_t *)ptr;
1432   upd765_t *fdc = get_safe_token(device);
1433   if ((fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1434      (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1435   {
1436      switch (fdc->command)
1437        {
1438         /* read a track */
1439         case 0x02:
1440         {
1441            fdc->sector_counter++;
1442
1443            /* sector counter == EOT */
1444            if (fdc->sector_counter==fdc->upd765_command_bytes[6])
1445            {
1446               /* TODO: Add correct info here */
1447
1448               fdc->upd765_status[1] |= UPD765_ST1_END_OF_CYLINDER;
1449
1450               upd765_setup_st0(device);
1451
1452               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1453               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1454               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1455               fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1456               fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1457               fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1458               fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1459
1460               upd765_setup_result_phase(device,7);
1461            }
1462            else
1463            {
1464               upd765_read_a_track(device);
1465            }
1466         }
1467         break;
1468
1469         /* format track */
1470         case 0x0d:
1471         {
1472            floppy_drive_format_sector(current_image(device), fdc->side, fdc->sector_counter,
1473               fdc->format_data[0], fdc->format_data[1],
1474               fdc->format_data[2], fdc->format_data[3],
1475               fdc->upd765_command_bytes[5]);
1476
1477            fdc->sector_counter++;
1478
1479            /* sector_counter = SC */
1480            if (fdc->sector_counter == fdc->upd765_command_bytes[3])
1481            {
1482               /* TODO: Check result is correct */
1483               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1484               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1485               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1486               fdc->upd765_result_bytes[3] = fdc->format_data[0];
1487               fdc->upd765_result_bytes[4] = fdc->format_data[1];
1488               fdc->upd765_result_bytes[5] = fdc->format_data[2];
1489               fdc->upd765_result_bytes[6] = fdc->format_data[3];
1490               upd765_setup_result_phase(device,7);
1491            }
1492            else
1493            {
1494               upd765_format_track(device);
1495            }
1496         }
1497         break;
1498
1499         /* write data, write deleted data */
1500         case 0x09:
1501         case 0x05:
1502         {
1503            /* sector id == EOT */
1504            UINT8 ddam;
1505
1506            ddam = 0;
1507            if (fdc->command == 0x09)
1508            {
1509               ddam = 1;
1510            }
1511
1512            /* write data to disc */
1513            floppy_drive_write_sector_data(current_image(device), fdc->side, fdc->sector_id,fdc->data_buffer,upd765_n_to_bytes(fdc->upd765_command_bytes[5]),ddam);
1514
1515            if (upd765_sector_count_complete(device))
1516            {
1517               upd765_increment_sector(device);
1518               upd765_write_complete(device);
1519            }
1520            else
1521            {
1522               upd765_increment_sector(device);
1523               upd765_write_data(device);
1524            }
1525         }
1526         break;
1527
1528         /* read data, read deleted data */
1529         case 0x0c:
1530         case 0x06:
1531         {
1532
1533            /* read all sectors? */
1534
1535            /* sector id == EOT */
1536            if (upd765_sector_count_complete(device) || upd765_read_data_stop(device))
1537            {
1538               upd765_read_complete(device);
1539            }
1540            else
1541            {
1542               upd765_increment_sector(device);
1543               upd765_read_data(device);
1544            }
1545         }
1546         break;
1547
1548         default:
1549            break;
1550      }
1551   }
1552}
1553
1554
1555static int upd765_get_command_byte_count(device_t *device)
1556{
1557   upd765_t *fdc = get_safe_token(device);
1558   fdc->command = fdc->upd765_command_bytes[0] & 0x01f;
1559
1560   if (fdc->version==TYPE_UPD765A)
1561   {
1562       return upd765_cmd_size[fdc->command];
1563    }
1564   else
1565   {
1566      if (fdc->version==TYPE_UPD72065)
1567      {
1568         switch(fdc->upd765_command_bytes[0])
1569         {
1570            case 0x34: // Reset Standby
1571            case 0x35: // Set Standby
1572            case 0x36: // Software Reset
1573               return 1;
1574            default:
1575               return upd765_cmd_size[fdc->command];
1576         }
1577      }
1578      if (fdc->version==TYPE_SMC37C78)
1579      {
1580         switch (fdc->command)
1581         {
1582            /* version */
1583            case 0x010:
1584               return 1;
1585
1586            /* verify */
1587            case 0x016:
1588               return 9;
1589
1590            /* configure */
1591            case 0x013:
1592               return 4;
1593
1594            /* dumpreg */
1595            case 0x0e:
1596               return 1;
1597
1598            /* perpendicular mode */
1599            case 0x012:
1600               return 1;
1601
1602            /* lock */
1603            case 0x014:
1604               return 1;
1605
1606            /* seek/relative seek are together! */
1607
1608            default:
1609               return upd765_cmd_size[fdc->command];
1610         }
1611      }
1612   }
1613
1614   return upd765_cmd_size[fdc->command];
1615}
1616
1617
1618
1619
1620
1621void upd765_update_state(device_t *device)
1622{
1623   upd765_t *fdc = get_safe_token(device);
1624   switch (fdc->upd765_phase) {
1625   case UPD765_RESULT_PHASE:
1626      /* set data reg */
1627      fdc->upd765_data_reg = fdc->upd765_result_bytes[fdc->upd765_transfer_bytes_count];
1628
1629      if (fdc->upd765_transfer_bytes_count == 0)
1630      {
1631         /* clear int for specific commands */
1632         switch (fdc->command) {
1633         case 2:   /* read a track */
1634         case 5:   /* write data */
1635         case 6:   /* read data */
1636         case 9:   /* write deleted data */
1637         case 10:   /* read id */
1638         case 12:   /* read deleted data */
1639         case 13:   /* format at track */
1640         case 17:   /* scan equal */
1641         case 19:   /* scan low or equal */
1642         case 29:   /* scan high or equal */
1643            upd765_set_int(device, 0);
1644            break;
1645
1646         default:
1647            break;
1648         }
1649      }
1650
1651      if (LOG_VERBOSE)
1652         logerror("UPD765: RESULT: %02x\n", fdc->upd765_data_reg);
1653
1654      fdc->upd765_transfer_bytes_count++;
1655      fdc->upd765_transfer_bytes_remaining--;
1656
1657      if (fdc->upd765_transfer_bytes_remaining==0)
1658      {
1659         upd765_idle(device);
1660      }
1661      else
1662      {
1663         upd765_set_data_request(device);
1664      }
1665      break;
1666
1667   case UPD765_EXECUTION_PHASE_READ:
1668      /* setup data register */
1669      fdc->upd765_data_reg = fdc->execution_phase_data[fdc->upd765_transfer_bytes_count];
1670      fdc->upd765_transfer_bytes_count++;
1671      fdc->upd765_transfer_bytes_remaining--;
1672
1673      if (LOG_EXTRA)
1674         logerror("EXECUTION PHASE READ: %02x\n", fdc->upd765_data_reg);
1675
1676      if ((fdc->upd765_transfer_bytes_remaining==0) || (fdc->upd765_flags & UPD765_TC))
1677      {
1678         fdc->command_timer->adjust(attotime::zero);
1679      }
1680      else
1681      {
1682         /* trigger int */
1683         upd765_setup_timed_data_request(device,1);
1684      }
1685      break;
1686
1687   case UPD765_COMMAND_PHASE_FIRST_BYTE:
1688      fdc->FDC_main |= 0x10;                      /* set BUSY */
1689
1690      if (LOG_VERBOSE)
1691         logerror("%s: upd765(): command=0x%02x\n", device->machine().describe_context(), fdc->upd765_data_reg);
1692
1693      /* seek in progress? */
1694      if (fdc->upd765_flags & UPD765_SEEK_ACTIVE)
1695      {
1696         /* any command results in a invalid - I think that seek, recalibrate and
1697            sense interrupt status may work*/
1698         if (fdc->upd765_data_reg != 8)   /* Sense Interrupt Status */
1699            fdc->upd765_data_reg = 0;
1700      }
1701
1702      fdc->upd765_command_bytes[0] = fdc->upd765_data_reg;
1703
1704      fdc->upd765_transfer_bytes_remaining = upd765_get_command_byte_count(device);
1705
1706      fdc->upd765_transfer_bytes_count = 1;
1707      fdc->upd765_transfer_bytes_remaining--;
1708
1709      if (fdc->upd765_transfer_bytes_remaining==0)
1710      {
1711         upd765_setup_command(device);
1712      }
1713      else
1714      {
1715         /* request more data */
1716         upd765_set_data_request(device);
1717         fdc->upd765_phase = UPD765_COMMAND_PHASE_BYTES;
1718      }
1719        break;
1720
1721    case UPD765_COMMAND_PHASE_BYTES:
1722      if (LOG_VERBOSE)
1723         logerror("%s: upd765(): command=0x%02x\n", device->machine().describe_context(), fdc->upd765_data_reg);
1724
1725      fdc->upd765_command_bytes[fdc->upd765_transfer_bytes_count] = fdc->upd765_data_reg;
1726      fdc->upd765_transfer_bytes_count++;
1727      fdc->upd765_transfer_bytes_remaining--;
1728
1729      if (fdc->upd765_transfer_bytes_remaining==0)
1730      {
1731         upd765_setup_command(device);
1732      }
1733      else
1734      {
1735         /* request more data */
1736         upd765_set_data_request(device);
1737      }
1738      break;
1739
1740    case UPD765_EXECUTION_PHASE_WRITE:
1741      fdc->execution_phase_data[fdc->upd765_transfer_bytes_count]=fdc->upd765_data_reg;
1742      fdc->upd765_transfer_bytes_count++;
1743      fdc->upd765_transfer_bytes_remaining--;
1744
1745      if ((fdc->upd765_transfer_bytes_remaining == 0) || (fdc->upd765_flags & UPD765_TC))
1746      {
1747         fdc->command_timer->adjust(attotime::zero);
1748      }
1749      else
1750      {
1751         upd765_setup_timed_data_request(device,1);
1752      }
1753      break;
1754   }
1755}
1756
1757
1758READ8_DEVICE_HANDLER(upd765_data_r)
1759{
1760   upd765_t *fdc = get_safe_token(device);
1761
1762//  if ((fdc->FDC_main & 0x0c0) == 0x0c0)
1763   if ((fdc->FDC_main & 0x080) == 0x080)
1764   {
1765      if (
1766         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1767         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1768      {
1769
1770         /* reading the data byte clears the interrupt */
1771         upd765_set_int(device,CLEAR_LINE);
1772      }
1773
1774      /* reset data request */
1775      upd765_clear_data_request(device);
1776
1777      /* update state */
1778      upd765_update_state(device);
1779   }
1780
1781   if (LOG_EXTRA)
1782      logerror("DATA R: %02x\n", fdc->upd765_data_reg);
1783
1784   return fdc->upd765_data_reg;
1785}
1786
1787WRITE8_DEVICE_HANDLER(upd765_data_w)
1788{
1789   upd765_t *fdc = get_safe_token(device);
1790
1791   if (LOG_EXTRA)
1792      logerror("DATA W: %02x\n", data);
1793
1794   /* write data to data reg */
1795   fdc->upd765_data_reg = data;
1796
1797   if ((fdc->FDC_main & 0x0c0)==0x080)
1798   {
1799      if (
1800         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1801         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1802      {
1803
1804         /* reading the data byte clears the interrupt */
1805         upd765_set_int(device, CLEAR_LINE);
1806      }
1807
1808      /* reset data request */
1809      upd765_clear_data_request(device);
1810
1811      /* update state */
1812      upd765_update_state(device);
1813   }
1814}
1815
1816static void upd765_setup_invalid(device_t *device)
1817{
1818   upd765_t *fdc = get_safe_token(device);
1819
1820   fdc->command = 0;
1821   fdc->upd765_result_bytes[0] = 0x080;
1822   upd765_setup_result_phase(device,1);
1823}
1824
1825static void upd765_setup_command(device_t *device)
1826{
1827   upd765_t *fdc = get_safe_token(device);
1828
1829   static const char *const commands[] =
1830   {
1831      NULL,                  /* [00] */
1832      NULL,                  /* [01] */
1833      "Read Track",            /* [02] */
1834      "Specify",               /* [03] */
1835      "Sense Drive Status",      /* [04] */
1836      "Write Data",            /* [05] */
1837      "Read Data",            /* [06] */
1838      "Recalibrate",            /* [07] */
1839      "Sense Interrupt Status",   /* [08] */
1840      "Write Deleted Data",      /* [09] */
1841      "Read ID",               /* [0A] */
1842      NULL,                  /* [0B] */
1843      "Read Deleted Data",      /* [0C] */
1844      "Format Track",            /* [0D] */
1845      "Dump Registers",         /* [0E] */
1846      "Seek",                  /* [0F] */
1847      "Version",               /* [10] */
1848      NULL,                  /* [11] */
1849      "Perpendicular Mode",      /* [12] */
1850      "Configure",            /* [13] */
1851      "Lock"                  /* [14] */
1852   };
1853
1854   device_t *img;
1855   const char *cmd = NULL;
1856   chrn_id id;
1857
1858   /* if not in dma mode set execution phase bit */
1859   if (!(fdc->upd765_flags & UPD765_DMA_MODE))
1860   {
1861        fdc->FDC_main |= 0x020;              /* execution phase */
1862   }
1863
1864   if (LOG_COMMAND)
1865   {
1866      if ((fdc->upd765_command_bytes[0] & 0x1f) < ARRAY_LENGTH(commands))
1867         cmd = commands[fdc->upd765_command_bytes[0] & 0x1f];
1868      logerror("upd765_setup_command(): Setting up command 0x%02X (%s)\n",
1869         fdc->upd765_command_bytes[0] & 0x1f, cmd ? cmd : "???");
1870   }
1871
1872   switch (fdc->upd765_command_bytes[0] & 0x1f)
1873   {
1874      case 0x03:      /* specify */
1875         /* setup step rate */
1876         fdc->srt_in_ms = 16-((fdc->upd765_command_bytes[1]>>4) & 0x0f);
1877
1878         fdc->upd765_flags &= ~UPD765_DMA_MODE;
1879
1880         if ((fdc->upd765_command_bytes[2] & 0x01)==0)
1881         {
1882            fdc->upd765_flags |= UPD765_DMA_MODE;
1883         }
1884
1885         upd765_idle(device);
1886         break;
1887
1888      case 0x04:  /* sense drive status */
1889         upd765_setup_drive_and_side(device);
1890         img = current_image(device);
1891
1892         fdc->upd765_status[3] = fdc->drive | (fdc->side<<2);
1893
1894         if (img)
1895         {
1896            fdc->upd765_status[3] |= !floppy_tk00_r(img) << 4;
1897            fdc->upd765_status[3] |= !floppy_wpt_r(img) << 6;
1898
1899            if (upd765_get_rdy(device))
1900            {
1901               fdc->upd765_status[3] |= 0x20;
1902            }
1903         }
1904
1905         fdc->upd765_status[3] |= 0x08;
1906
1907         /* two side and fault not set but should be? */
1908         fdc->upd765_result_bytes[0] = fdc->upd765_status[3];
1909         upd765_setup_result_phase(device,1);
1910         break;
1911
1912      case 0x07:          /* recalibrate */
1913         upd765_seek_setup(device, 1);
1914         break;
1915
1916      case 0x0f:          /* seek */
1917         upd765_seek_setup(device, 0);
1918         break;
1919
1920      case 0x0a:      /* read id */
1921         upd765_setup_drive_and_side(device);
1922         img = current_image(device);
1923
1924         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
1925         fdc->upd765_status[1] = 0;
1926         fdc->upd765_status[2] = 0;
1927
1928         /* drive ready? */
1929         if (upd765_get_rdy(device))
1930         {
1931            /* is disk inserted? */
1932            device_image_interface *image = dynamic_cast<device_image_interface *>( img);
1933            if (image->exists())
1934            {
1935               int index_count = 0;
1936
1937               /* floppy drive is ready and disc is inserted */
1938
1939               /* this is the id that appears when a disc is not formatted */
1940               /* to be checked on Amstrad */
1941               id.C = 0;
1942               id.H = 0;
1943               id.R = 0x01;
1944               id.N = 0x02;
1945
1946               /* repeat for two index counts before quitting */
1947               do
1948               {
1949                  /* get next id from disc */
1950                  if (floppy_drive_get_next_id(img, fdc->side, &id))
1951                  {
1952                     /* got an id - quit */
1953                     break;
1954                  }
1955
1956                  if (floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))
1957                  {
1958                     /* update index count */
1959                     index_count++;
1960                  }
1961               }
1962               while (index_count!=2);
1963
1964               /* at this point, we have seen a id or two index pulses have occured! */
1965               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1966               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1967               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1968               fdc->upd765_result_bytes[3] = id.C; /* C */
1969               fdc->upd765_result_bytes[4] = id.H; /* H */
1970               fdc->upd765_result_bytes[5] = id.R; /* R */
1971               fdc->upd765_result_bytes[6] = id.N; /* N */
1972
1973               upd765_setup_result_phase(device,7);
1974            }
1975            else
1976            {
1977               /* floppy drive is ready, but no disc is inserted */
1978               /* this occurs on the PC */
1979               /* in this case, the command never quits! */
1980               /* there are no index pulses to stop the command! */
1981            }
1982         }
1983         else
1984         {
1985            /* what are id values when drive not ready? */
1986
1987            /* not ready, abnormal termination */
1988            fdc->upd765_status[0] |= (1<<3) | (1<<6);
1989            fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1990            fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1991            fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1992            fdc->upd765_result_bytes[3] = 0; /* C */
1993            fdc->upd765_result_bytes[4] = 0; /* H */
1994            fdc->upd765_result_bytes[5] = 0; /* R */
1995            fdc->upd765_result_bytes[6] = 0; /* N */
1996         }
1997         break;
1998
1999
2000      case 0x08: /* sense interrupt status */
2001         /* interrupt pending? */
2002         if (fdc->upd765_flags & UPD765_INT)
2003         {
2004            /* yes. Clear int */
2005            upd765_set_int(device, CLEAR_LINE);
2006
2007            /* clear drive seek bits */
2008            fdc->FDC_main &= ~(1 | 2 | 4 | 8);
2009
2010            /* return status */
2011            fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2012            /* return pcn */
2013            fdc->upd765_result_bytes[1] = fdc->pcn[fdc->drive];
2014
2015            /* return result */
2016            upd765_setup_result_phase(device,2);
2017         }
2018         else
2019         {
2020            if(fdc->version == TYPE_UPD72065 && (fdc->FDC_main & 0x0f) == 0x00)
2021            {  // based on XM6
2022               upd765_setup_invalid(device);
2023            }
2024            else
2025            {
2026               /* no int */
2027               fdc->upd765_result_bytes[0] = 0x80;
2028               /* return pcn */
2029               fdc->upd765_result_bytes[1] = fdc->pcn[fdc->drive];
2030
2031               /* return result */
2032               upd765_setup_result_phase(device,2);
2033            }
2034         }
2035         break;
2036
2037      case 0x06:  /* read data */
2038         upd765_setup_drive_and_side(device);
2039
2040         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2041         fdc->upd765_status[1] = 0;
2042         fdc->upd765_status[2] = 0;
2043
2044         upd765_read_data(device);
2045         break;
2046
2047      case 0x0c:
2048         /* read deleted data */
2049         upd765_setup_drive_and_side(device);
2050
2051         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2052         fdc->upd765_status[1] = 0;
2053         fdc->upd765_status[2] = 0;
2054
2055         /* .. for now */
2056         upd765_read_data(device);
2057         break;
2058
2059      case 0x09:
2060         /* write deleted data */
2061         upd765_setup_drive_and_side(device);
2062
2063         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2064         fdc->upd765_status[1] = 0;
2065         fdc->upd765_status[2] = 0;
2066
2067         /* ... for now */
2068         upd765_write_data(device);
2069         break;
2070
2071      case 0x02:
2072         /* read a track */
2073         upd765_setup_drive_and_side(device);
2074         img = current_image(device);
2075         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2076         fdc->upd765_status[1] = 0;
2077         fdc->upd765_status[2] = 0;
2078
2079         fdc->upd765_status[0] |= UPD765_ST1_NO_DATA;
2080
2081         /* wait for index */
2082         do
2083         {
2084            /* get next id from disc */
2085            floppy_drive_get_next_id(img, fdc->side,&id);
2086         }
2087         while ((floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))==0);
2088
2089         fdc->sector_counter = 0;
2090
2091         upd765_read_a_track(device);
2092         break;
2093
2094      case 0x05:  /* write data */
2095         upd765_setup_drive_and_side(device);
2096
2097         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2098         fdc->upd765_status[1] = 0;
2099         fdc->upd765_status[2] = 0;
2100
2101         upd765_write_data(device);
2102         break;
2103
2104      case 0x0d:   /* format a track */
2105         upd765_setup_drive_and_side(device);
2106
2107         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2108         fdc->upd765_status[1] = 0;
2109         fdc->upd765_status[2] = 0;
2110
2111         fdc->sector_counter = 0;
2112
2113         upd765_format_track(device);
2114         break;
2115
2116      default:   /* invalid */
2117         switch (fdc->version)
2118         {
2119            case TYPE_UPD765A:
2120               upd765_setup_invalid(device);
2121               break;
2122
2123            case TYPE_UPD765B:
2124               /* from upd765b data sheet */
2125               if ((fdc->upd765_command_bytes[0] & 0x01f)==0x010)
2126               {
2127                  /* version */
2128                  fdc->upd765_status[0] = 0x090;
2129                  fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2130                  upd765_setup_result_phase(device,1);
2131               }
2132               break;
2133
2134            case TYPE_UPD72065:
2135               switch(fdc->upd765_command_bytes[0] & 0x3f)
2136               {
2137                  case 0x36:  // Software Reset
2138                     upd765_reset(device,0);
2139                     upd765_idle(device);
2140                     if(LOG_COMMAND)
2141                        logerror("upd72065: command - Software Reset\n");
2142                     break;
2143                  default:
2144                     upd765_setup_invalid(device);
2145                     break;
2146               }
2147               break;
2148
2149            case TYPE_SMC37C78:
2150               /* TO BE COMPLETED!!! !*/
2151               switch (fdc->upd765_command_bytes[0] & 0x1f)
2152               {
2153                  case 0x10:      /* version */
2154                     fdc->upd765_status[0] = 0x90;
2155                     fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2156                     upd765_setup_result_phase(device,1);
2157                     break;
2158
2159                  case 0x13:      /* configure */
2160                     upd765_idle(device);
2161                     break;
2162
2163                  case 0x0e:      /* dump reg */
2164                     fdc->upd765_result_bytes[0] = fdc->pcn[0];
2165                     fdc->upd765_result_bytes[1] = fdc->pcn[1];
2166                     fdc->upd765_result_bytes[2] = fdc->pcn[2];
2167                     fdc->upd765_result_bytes[3] = fdc->pcn[3];
2168
2169                     upd765_setup_result_phase(device,10);
2170                     break;
2171
2172                  case 0x12:      /* perpendicular mode */
2173                     upd765_idle(device);
2174                     break;
2175
2176                  case 0x14:      /* lock */
2177                     upd765_setup_result_phase(device,1);
2178                     break;
2179               }
2180               break;
2181         }
2182   }
2183}
2184
2185
2186/* dma acknowledge write */
2187WRITE8_DEVICE_HANDLER(upd765_dack_w)
2188{
2189   /* clear request */
2190   upd765_set_dma_drq(device, CLEAR_LINE);
2191
2192   /* write data */
2193   upd765_data_w(device, offset, data);
2194}
2195
2196READ8_DEVICE_HANDLER(upd765_dack_r)
2197{
2198   /* clear data request */
2199   upd765_set_dma_drq(device,CLEAR_LINE);
2200
2201   /* read data */
2202   return upd765_data_r(device, offset);
2203}
2204
2205static TIMER_CALLBACK( interrupt_callback )
2206{
2207   device_t* device = (device_t*)ptr;
2208   upd765_set_int(device, 1);
2209}
2210
2211void upd765_reset(device_t *device, int offset)
2212{
2213   upd765_t *fdc = get_safe_token(device);
2214
2215   /* upd765 in idle state - ready to accept commands */
2216   upd765_idle(device);
2217
2218   /* set int low */
2219   upd765_set_int(device, 0);
2220   /* set dma drq output */
2221   upd765_set_dma_drq(device,0);
2222
2223   /* tandy 100hx assumes that after NEC is reset, it is in DMA mode */
2224   fdc->upd765_flags |= UPD765_DMA_MODE;
2225
2226   /* if ready input is set during reset generate an int */
2227   if (fdc->upd765_flags & UPD765_FDD_READY)
2228   {
2229      int i;
2230      int a_drive_is_ready;
2231
2232      fdc->upd765_status[0] = 0x080 | 0x040;
2233
2234      /* for the purpose of pc-xt. If any of the drives have a disk inserted,
2235        do not set not-ready - need to check with pc_fdc->c whether all drives
2236        are checked or only the drive selected with the drive select bits?? */
2237
2238      a_drive_is_ready = 0;
2239      for (i = 0; i < 4; i++)
2240      {
2241         if (fdc->intf->floppy_drive_tags[i]!=NULL)
2242         {
2243            device_t *img;
2244
2245            if (device->owner() != NULL)
2246               img = device->owner()->subdevice(fdc->intf->floppy_drive_tags[i]);
2247            else
2248               img = device->machine().device(fdc->intf->floppy_drive_tags[i]);
2249
2250            device_image_interface *image = dynamic_cast<device_image_interface *>( img);
2251            if (image->exists())
2252            {
2253               a_drive_is_ready = 1;
2254               break;
2255            }
2256         }
2257
2258      }
2259
2260      if (!a_drive_is_ready && fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED )
2261      {
2262         fdc->upd765_status[0] |= 0x08;
2263      }
2264
2265      device->machine().scheduler().timer_set(attotime::from_usec(5), FUNC(interrupt_callback),0,device);
2266   }
2267}
2268
2269WRITE_LINE_DEVICE_HANDLER( upd765_reset_w )
2270{
2271   upd765_t *fdc = get_safe_token(device);
2272
2273   int flags;
2274
2275   /* get previous reset state */
2276   flags = fdc->upd765_flags;
2277
2278   /* set new reset state */
2279   /* clear reset */
2280   fdc->upd765_flags &= ~UPD765_RESET;
2281
2282   /* reset */
2283   if (state)
2284   {
2285      fdc->upd765_flags |= UPD765_RESET;
2286
2287      upd765_set_int(device, 0);
2288   }
2289
2290   /* reset changed state? */
2291   if (((flags^fdc->upd765_flags) & UPD765_RESET)!=0)
2292   {
2293      /* yes */
2294
2295      /* no longer reset */
2296      if ((fdc->upd765_flags & UPD765_RESET)==0)
2297      {
2298         /* reset nec */
2299         upd765_reset(device, 0);
2300      }
2301   }
2302}
2303
2304
2305WRITE_LINE_DEVICE_HANDLER( upd765_ready_w )
2306{
2307   upd765_t *fdc = get_safe_token(device);
2308
2309   /* clear ready state */
2310   fdc->upd765_flags &= ~UPD765_FDD_READY;
2311
2312   if (state)
2313   {
2314      fdc->upd765_flags |= UPD765_FDD_READY;
2315   }
2316}
2317
2318
2319/* Device Interface */
2320
2321static void common_start(device_t *device, int device_type)
2322{
2323   upd765_t *fdc = get_safe_token(device);
2324   // validate arguments
2325
2326   assert(device != NULL);
2327   assert(device->tag() != NULL);
2328   assert(device->static_config() != NULL);
2329
2330   fdc->intf = (const upd765_interface*)device->static_config();
2331
2332   fdc->version = (UPD765_VERSION)device_type;
2333   fdc->timer = device->machine().scheduler().timer_alloc(FUNC(upd765_timer_callback), (void*)device);
2334   fdc->seek_timer = device->machine().scheduler().timer_alloc(FUNC(upd765_seek_timer_callback), (void*)device);
2335   fdc->command_timer = device->machine().scheduler().timer_alloc(FUNC(upd765_continue_command), (void*)device);
2336
2337   fdc->upd765_flags &= UPD765_FDD_READY;
2338   fdc->data_buffer = auto_alloc_array(device->machine(), char, 32*1024);
2339
2340   fdc->out_int_func.resolve(fdc->intf->out_int_func, *device);
2341   fdc->out_drq_func.resolve(fdc->intf->out_drq_func, *device);
2342
2343   // register for state saving
2344   //state_save_register_item(device->machine(), "upd765", device->tag(), 0, upd765->number);
2345}
2346
2347static DEVICE_START( upd765a )
2348{
2349   common_start(device, TYPE_UPD765A);
2350}
2351
2352static DEVICE_START( upd765b )
2353{
2354   common_start(device, TYPE_UPD765B);
2355}
2356
2357static DEVICE_START( smc37c78 )
2358{
2359   common_start(device, TYPE_SMC37C78);
2360}
2361
2362static DEVICE_START( upd72065 )
2363{
2364   common_start(device, TYPE_UPD72065);
2365}
2366
2367static DEVICE_RESET( upd765 )
2368{
2369   int i;
2370   upd765_t *fdc = get_safe_token(device);
2371   for (i = 0; i < 4; i++) {
2372      if (fdc->intf->floppy_drive_tags[i]!=NULL)
2373      {
2374         device_t *img;
2375
2376         if (device->owner() != NULL)
2377            img = device->owner()->subdevice(fdc->intf->floppy_drive_tags[i]);
2378         else
2379            img = device->machine().device(fdc->intf->floppy_drive_tags[i]);
2380
2381         floppy_drive_set_controller(img, device);
2382         floppy_drive_set_ready_state_change_callback(img, upd765_set_ready_change_callback);
2383      }
2384   }
2385
2386   upd765_reset(device,0);
2387}
2388
2389DEVICE_GET_INFO( upd765a )
2390{
2391   switch (state)
2392   {
2393      /* --- the following bits of info are returned as 64-bit signed integers --- */
2394      case DEVINFO_INT_TOKEN_BYTES:               info->i = sizeof(upd765_t);               break;
2395      case DEVINFO_INT_INLINE_CONFIG_BYTES:         info->i = 0;                        break;
2396
2397      /* --- the following bits of info are returned as pointers to data or functions --- */
2398      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd765a);   break;
2399      case DEVINFO_FCT_STOP:                     /* Nothing */                        break;
2400      case DEVINFO_FCT_RESET:                     info->reset = DEVICE_RESET_NAME(upd765);   break;
2401
2402      /* --- the following bits of info are returned as NULL-terminated strings --- */
2403      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD765A");                  break;
2404      case DEVINFO_STR_FAMILY:                  strcpy(info->s, "UPD765A");                  break;
2405      case DEVINFO_STR_VERSION:                  strcpy(info->s, "1.0");                     break;
2406      case DEVINFO_STR_SOURCE_FILE:               strcpy(info->s, __FILE__);                     break;
2407      case DEVINFO_STR_CREDITS:                  strcpy(info->s, "Copyright MESS Team");         break;
2408   }
2409}
2410
2411
2412DEVICE_GET_INFO( upd765b )
2413{
2414   switch (state)
2415   {
2416      /* --- the following bits of info are returned as NULL-terminated strings --- */
2417      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD765B");            break;
2418
2419      /* --- the following bits of info are returned as pointers to data or functions --- */
2420      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd765b);   break;
2421
2422      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2423   }
2424}
2425
2426DEVICE_GET_INFO( smc37c78 )
2427{
2428   switch (state)
2429   {
2430      /* --- the following bits of info are returned as NULL-terminated strings --- */
2431      case DEVINFO_STR_NAME:                     strcpy(info->s, "SMC37C78");            break;
2432
2433      /* --- the following bits of info are returned as pointers to data or functions --- */
2434      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(smc37c78);   break;
2435
2436      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2437   }
2438}
2439
2440DEVICE_GET_INFO( upd72065 )
2441{
2442   switch (state)
2443   {
2444      /* --- the following bits of info are returned as NULL-terminated strings --- */
2445      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD72065");            break;
2446
2447      /* --- the following bits of info are returned as pointers to data or functions --- */
2448      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd72065);   break;
2449
2450      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2451   }
2452}
2453
2454DEFINE_LEGACY_DEVICE(UPD765A, upd765a);
2455DEFINE_LEGACY_DEVICE(UPD765B, upd765b);
2456DEFINE_LEGACY_DEVICE(SMC37C78, smc37c78);
2457DEFINE_LEGACY_DEVICE(UPD72065, upd72065);
src/emu/machine/upd765.h
r0r11451
1/***************************************************************************
2
3    machine/upd765.h
4
5    Functions to emulate a NEC upd765/Intel 8272 compatible
6    floppy disk controller
7
8***************************************************************************/
9
10#ifndef __UPD765_H__
11#define __UPD765_H__
12
13#include "devcb.h"
14#include "imagedev/flopdrv.h"
15
16
17/***************************************************************************
18    MACROS
19***************************************************************************/
20
21DECLARE_LEGACY_DEVICE(UPD765A, upd765a);
22DECLARE_LEGACY_DEVICE(UPD765B, upd765b);
23DECLARE_LEGACY_DEVICE(SMC37C78, smc37c78);
24DECLARE_LEGACY_DEVICE(UPD72065, upd72065);
25
26/***************************************************************************
27    TYPE DEFINITIONS
28***************************************************************************/
29
30/* RDY pin connected state */
31typedef enum
32{
33   UPD765_RDY_PIN_NOT_CONNECTED = 0,
34   UPD765_RDY_PIN_CONNECTED = 1
35} UPD765_RDY_PIN;
36
37#define UPD765_DAM_DELETED_DATA 0x0f8
38#define UPD765_DAM_DATA 0x0fb
39
40typedef device_t *(*upd765_get_image_func)(device_t *device, int floppy_index);
41#define UPD765_GET_IMAGE(name)   device_t *name(device_t *device, int floppy_index )
42
43
44typedef struct upd765_interface
45{
46   /* interrupt issued */
47   devcb_write_line out_int_func;
48
49   /* dma data request */
50   devcb_write_line out_drq_func;
51
52   /* image lookup */
53   upd765_get_image_func get_image;
54
55   UPD765_RDY_PIN rdy_pin;
56
57   const char *floppy_drive_tags[4];
58} upd765_interface;
59
60
61/***************************************************************************
62    FUNCTION PROTOTYPES
63***************************************************************************/
64
65/* read of data register */
66READ8_DEVICE_HANDLER(upd765_data_r);
67/* write to data register */
68WRITE8_DEVICE_HANDLER(upd765_data_w);
69/* read of main status register */
70READ8_DEVICE_HANDLER(upd765_status_r);
71
72/* dma acknowledge with write */
73WRITE8_DEVICE_HANDLER(upd765_dack_w);
74/* dma acknowledge with read */
75READ8_DEVICE_HANDLER(upd765_dack_r);
76
77/* reset upd765 */
78void upd765_reset(device_t *device, int);
79
80/* reset pin of upd765 */
81WRITE_LINE_DEVICE_HANDLER(upd765_reset_w);
82
83/* set upd765 terminal count input state */
84WRITE_LINE_DEVICE_HANDLER(upd765_tc_w);
85
86/* set upd765 ready input*/
87WRITE_LINE_DEVICE_HANDLER(upd765_ready_w);
88
89void upd765_idle(device_t *device);
90
91/*********************/
92/* STATUS REGISTER 1 */
93
94/* this is set if a TC signal was not received after the sector data was read */
95#define UPD765_ST1_END_OF_CYLINDER (1<<7)
96/* this is set if the sector ID being searched for is not found */
97#define UPD765_ST1_NO_DATA (1<<2)
98/* set if disc is write protected and a write/format operation was performed */
99#define UPD765_ST1_NOT_WRITEABLE (1<<1)
100
101/*********************/
102/* STATUS REGISTER 2 */
103
104/* C parameter specified did not match C value read from disc */
105#define UPD765_ST2_WRONG_CYLINDER (1<<4)
106/* C parameter specified did not match C value read from disc, and C read from disc was 0x0ff */
107#define UPD765_ST2_BAD_CYLINDER (1<<1)
108/* this is set if the FDC encounters a Deleted Data Mark when executing a read data
109command, or FDC encounters a Data Mark when executing a read deleted data command */
110#define UPD765_ST2_CONTROL_MARK (1<<6)
111
112/***************************************************************************
113    DEVICE CONFIGURATION MACROS
114***************************************************************************/
115
116#define MCFG_UPD765A_ADD(_tag, _intrf) \
117   MCFG_DEVICE_ADD(_tag, UPD765A, 0) \
118   MCFG_DEVICE_CONFIG(_intrf)
119
120#define MCFG_UPD765A_MODIFY(_tag, _intrf) \
121  MCFG_DEVICE_MODIFY(_tag)         \
122  MCFG_DEVICE_CONFIG(_intrf)
123
124#define MCFG_UPD765A_REMOVE(_tag)      \
125  MCFG_DEVICE_REMOVE(_tag)
126
127#define MCFG_UPD765B_ADD(_tag, _intrf) \
128   MCFG_DEVICE_ADD(_tag, UPD765B, 0) \
129   MCFG_DEVICE_CONFIG(_intrf)
130
131#define MCFG_UPD765B_MODIFY(_tag, _intrf) \
132  MCFG_DEVICE_MODIFY(_tag)         \
133  MCFG_DEVICE_CONFIG(_intrf)
134
135#define MCFG_UPD765B_REMOVE(_tag)      \
136  MCFG_DEVICE_REMOVE(_tag)
137
138#define MCFG_SMC37C78_ADD(_tag, _intrf) \
139   MCFG_DEVICE_ADD(_tag, SMC37C78, 0) \
140   MCFG_DEVICE_CONFIG(_intrf)
141
142#define MCFG_SMC37C78_MODIFY(_tag, _intrf) \
143  MCFG_DEVICE_MODIFY(_tag)         \
144  MCFG_DEVICE_CONFIG(_intrf)
145
146#define MCFG_SMC37C78_REMOVE(_tag)      \
147  MCFG_DEVICE_REMOVE(_tag)
148
149#define MCFG_UPD72065_ADD(_tag, _intrf) \
150   MCFG_DEVICE_ADD(_tag, UPD72065, 0) \
151   MCFG_DEVICE_CONFIG(_intrf)
152
153#define MCFG_UPD72065_MODIFY(_tag, _intrf) \
154  MCFG_DEVICE_MODIFY(_tag)         \
155  MCFG_DEVICE_CONFIG(_intrf)
156
157#define MCFG_UPD72065_REMOVE(_tag)      \
158  MCFG_DEVICE_REMOVE(_tag)
159
160
161#endif /* __UPD765_H__ */
src/emu/machine/6840ptm.c
r11450r11451
644644
645645void ptm6840_device::set_gate(int idx, int state)
646646{
647   if ( (m_mode[idx] == 0) || (m_mode[idx] == 2) || (m_mode[0] == 4) || (m_mode[idx] == 6) )
647   if ((m_mode[idx] & 1) == 0)
648648   {
649649      if (state == 0 && m_gate[idx])
650650      {
src/emu/machine/ctronics.c
r0r11451
1/***************************************************************************
2
3    Centronics printer interface
4
5***************************************************************************/
6
7#include "emu.h"
8#include "ctronics.h"
9#include "imagedev/printer.h"
10
11
12/***************************************************************************
13    FUNCTION PROTOTYPES
14***************************************************************************/
15
16static WRITE_LINE_DEVICE_HANDLER( centronics_printer_online );
17static TIMER_CALLBACK( ack_callback );
18static TIMER_CALLBACK( busy_callback );
19
20
21/***************************************************************************
22    TYPE DEFINITIONS
23***************************************************************************/
24
25typedef struct _centronics_state centronics_state;
26struct _centronics_state
27{
28   device_t *printer;
29
30   devcb_resolved_write_line out_ack_func;
31   devcb_resolved_write_line out_busy_func;
32   devcb_resolved_write_line out_not_busy_func;
33
34   int strobe;
35   int busy;
36   int ack;
37   int auto_fd;
38   int pe;
39   int fault;
40
41   UINT8 data;
42};
43
44
45/*****************************************************************************
46    INLINE FUNCTIONS
47*****************************************************************************/
48
49INLINE centronics_state *get_safe_token(device_t *device)
50{
51   assert(device != NULL);
52   assert(device->type() == CENTRONICS);
53
54   return (centronics_state *)downcast<legacy_device_base *>(device)->token();
55}
56
57
58/*****************************************************************************
59    GLOBAL VARIABLES
60*****************************************************************************/
61
62const centronics_interface standard_centronics =
63{
64   FALSE,
65   DEVCB_NULL,
66   DEVCB_NULL,
67   DEVCB_NULL
68};
69
70
71/*****************************************************************************
72    PRINTER INTERFACE
73*****************************************************************************/
74
75static MACHINE_CONFIG_FRAGMENT( centronics )
76   MCFG_PRINTER_ADD("printer")
77   MCFG_PRINTER_ONLINE(centronics_printer_online)
78MACHINE_CONFIG_END
79
80
81/*****************************************************************************
82    DEVICE INTERFACE
83*****************************************************************************/
84
85static DEVICE_START( centronics )
86{
87   centronics_state *centronics = get_safe_token(device);
88   const centronics_interface *intf = (const centronics_interface *)device->static_config();
89
90   /* validate some basic stuff */
91   assert(device->static_config() != NULL);
92
93   /* set some initial values */
94   centronics->pe = FALSE;
95   centronics->fault = FALSE;
96   centronics->busy = TRUE;
97   centronics->strobe = TRUE;
98
99   /* get printer device */
100   centronics->printer = device->subdevice("printer");
101
102   /* resolve callbacks */
103   centronics->out_ack_func.resolve(intf->out_ack_func, *device);
104   centronics->out_busy_func.resolve(intf->out_busy_func, *device);
105   centronics->out_not_busy_func.resolve(intf->out_not_busy_func, *device);
106
107   /* register for state saving */
108   device->save_item(NAME(centronics->auto_fd));
109   device->save_item(NAME(centronics->strobe));
110   device->save_item(NAME(centronics->busy));
111   device->save_item(NAME(centronics->ack));
112   device->save_item(NAME(centronics->data));
113}
114
115static DEVICE_RESET( centronics )
116{
117}
118
119DEVICE_GET_INFO( centronics )
120{
121   switch (state)
122   {
123      /* --- the following bits of info are returned as 64-bit signed integers --- */
124      case DEVINFO_INT_TOKEN_BYTES:         info->i = sizeof(centronics_state);      break;
125      case DEVINFO_INT_INLINE_CONFIG_BYTES:   info->i = 0;                     break;
126
127      /* --- the following bits of info are returned as pointers --- */
128      case DEVINFO_PTR_MACHINE_CONFIG:      info->machine_config = MACHINE_CONFIG_NAME(centronics);   break;
129
130      /* --- the following bits of info are returned as pointers to data or functions --- */
131      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(centronics);      break;
132      case DEVINFO_FCT_STOP:               /* Nothing */                              break;
133      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(centronics);      break;
134
135      /* --- the following bits of info are returned as NULL-terminated strings --- */
136      case DEVINFO_STR_NAME:               strcpy(info->s, "Centronics");         break;
137      case DEVINFO_STR_FAMILY:            strcpy(info->s, "Centronics");         break;
138      case DEVINFO_STR_VERSION:            strcpy(info->s, "1.0");               break;
139      case DEVINFO_STR_SOURCE_FILE:         strcpy(info->s, __FILE__);            break;
140      case DEVINFO_STR_CREDITS:            strcpy(info->s, "Copyright MESS Team");   break;
141   }
142}
143
144
145/***************************************************************************
146    IMPLEMENTATION
147***************************************************************************/
148
149/*-------------------------------------------------
150    centronics_printer_online - callback that
151    sets us busy when the printer goes offline
152-------------------------------------------------*/
153
154void centronics_printer_online(device_t *device, int state)
155{
156   centronics_state *centronics = get_safe_token(device->owner());
157
158   /* when going online, set PE and FAULT high and BUSY low */
159   centronics->pe = state;
160   centronics->fault = state;
161   centronics->busy = !state;
162}
163
164
165static TIMER_CALLBACK( ack_callback )
166{
167   centronics_state *centronics = (centronics_state *)ptr;
168
169   /* signal change */
170   centronics->out_ack_func(param);
171   centronics->ack = param;
172
173   if (param == FALSE)
174   {
175      /* data is now ready, output it */
176      printer_output(centronics->printer, centronics->data);
177
178      /* ready to receive more data, return BUSY to low */
179      machine.scheduler().timer_set(attotime::from_usec(7), FUNC(busy_callback), FALSE, ptr);
180   }
181}
182
183
184static TIMER_CALLBACK( busy_callback )
185{
186   centronics_state *centronics = (centronics_state *)ptr;
187
188   /* signal change */
189   centronics->out_busy_func(param);
190   centronics->out_not_busy_func(!param);
191   centronics->busy = param;
192
193   if (param == TRUE)
194   {
195      /* timer to turn ACK low to receive data */
196      machine.scheduler().timer_set(attotime::from_usec(10), FUNC(ack_callback), FALSE, ptr);
197   }
198   else
199   {
200      /* timer to return ACK to high state */
201      machine.scheduler().timer_set(attotime::from_usec(5), FUNC(ack_callback), TRUE, ptr);
202   }
203}
204
205
206/*-------------------------------------------------
207    centronics_data_w - write print data
208-------------------------------------------------*/
209
210WRITE8_DEVICE_HANDLER( centronics_data_w )
211{
212   centronics_state *centronics = get_safe_token(device);
213   centronics->data = data;
214}
215
216
217/*-------------------------------------------------
218    centronics_data_r - return current data
219-------------------------------------------------*/
220
221READ8_DEVICE_HANDLER( centronics_data_r )
222{
223   centronics_state *centronics = get_safe_token(device);
224   return centronics->data;
225}
226
227
228/*-------------------------------------------------
229    set_line - helper to set individual bits
230-------------------------------------------------*/
231
232static void set_line(device_t *device, int line, int state)
233{
234   centronics_state *centronics = get_safe_token(device);
235
236   if (state)
237      centronics->data |= 1 << line;
238   else
239      centronics->data &= ~(1 << line);
240}
241
242
243/*-------------------------------------------------
244    centronics_dx_w - write line dx print data
245-------------------------------------------------*/
246
247WRITE_LINE_DEVICE_HANDLER( centronics_d0_w ) { set_line(device, 0, state); }
248WRITE_LINE_DEVICE_HANDLER( centronics_d1_w ) { set_line(device, 1, state); }
249WRITE_LINE_DEVICE_HANDLER( centronics_d2_w ) { set_line(device, 2, state); }
250WRITE_LINE_DEVICE_HANDLER( centronics_d3_w ) { set_line(device, 3, state); }
251WRITE_LINE_DEVICE_HANDLER( centronics_d4_w ) { set_line(device, 4, state); }
252WRITE_LINE_DEVICE_HANDLER( centronics_d5_w ) { set_line(device, 5, state); }
253WRITE_LINE_DEVICE_HANDLER( centronics_d6_w ) { set_line(device, 6, state); }
254WRITE_LINE_DEVICE_HANDLER( centronics_d7_w ) { set_line(device, 7, state); }
255
256
257/*-------------------------------------------------
258    centronics_strobe_w - signal that data is
259    ready
260-------------------------------------------------*/
261
262WRITE_LINE_DEVICE_HANDLER( centronics_strobe_w )
263{
264   centronics_state *centronics = get_safe_token(device);
265
266   /* look for a high -> low transition */
267   if (centronics->strobe == TRUE && state == FALSE && centronics->busy == FALSE)
268   {
269      /* STROBE has gone low, data is ready */
270      device->machine().scheduler().timer_set(attotime::zero, FUNC(busy_callback), TRUE, centronics);
271   }
272
273   centronics->strobe = state;
274}
275
276
277/*-------------------------------------------------
278    centronics_prime_w - initialize and reset
279    printer (centronics mode)
280-------------------------------------------------*/
281
282WRITE_LINE_DEVICE_HANDLER( centronics_prime_w )
283{
284   assert(((const centronics_interface *)device->static_config())->is_ibmpc == FALSE);
285
286   /* reset printer if line is low */
287   if (state == FALSE)
288      DEVICE_RESET_CALL( centronics );
289}
290
291
292/*-------------------------------------------------
293    centronics_init_w - initialize and reset
294    printer (ibm mode)
295-------------------------------------------------*/
296
297WRITE_LINE_DEVICE_HANDLER( centronics_init_w )
298{
299   assert(((const centronics_interface *)device->static_config())->is_ibmpc == TRUE);
300
301   /* reset printer if line is low */
302   if (state == FALSE)
303      DEVICE_RESET_CALL( centronics );
304}
305
306
307/*-------------------------------------------------
308    centronics_autofeed_w - auto line feed
309-------------------------------------------------*/
310
311WRITE_LINE_DEVICE_HANDLER( centronics_autofeed_w )
312{
313   centronics_state *centronics = get_safe_token(device);
314   assert(((const centronics_interface *)device->static_config())->is_ibmpc == TRUE);
315
316   centronics->auto_fd = state;
317}
318
319
320/*-------------------------------------------------
321    centronics_ack_r - return the state of the
322    ack line
323-------------------------------------------------*/
324
325READ_LINE_DEVICE_HANDLER( centronics_ack_r )
326{
327   centronics_state *centronics = get_safe_token(device);
328   return centronics->ack;
329}
330
331
332/*-------------------------------------------------
333    centronics_busy_r - return the state of the
334    busy line
335-------------------------------------------------*/
336
337READ_LINE_DEVICE_HANDLER( centronics_busy_r )
338{
339   centronics_state *centronics = get_safe_token(device);
340   return centronics->busy;
341}
342
343
344/*-------------------------------------------------
345    centronics_pe_r - return the state of the
346    pe line
347-------------------------------------------------*/
348
349READ_LINE_DEVICE_HANDLER( centronics_pe_r )
350{
351   centronics_state *centronics = get_safe_token(device);
352   return centronics->pe;
353}
354
355
356/*-------------------------------------------------
357    centronics_not_busy_r - return the state of the
358    not busy line
359-------------------------------------------------*/
360
361READ_LINE_DEVICE_HANDLER( centronics_not_busy_r )
362{
363   centronics_state *centronics = get_safe_token(device);
364   return !centronics->busy;
365}
366
367
368/*-------------------------------------------------
369    centronics_vcc_r - return the state of the
370    vcc line
371-------------------------------------------------*/
372
373READ_LINE_DEVICE_HANDLER( centronics_vcc_r )
374{
375   /* always return high */
376   return TRUE;
377}
378
379
380/*-------------------------------------------------
381    centronics_fault_r - return the state of the
382    fault line
383-------------------------------------------------*/
384
385READ_LINE_DEVICE_HANDLER( centronics_fault_r )
386{
387   centronics_state *centronics = get_safe_token(device);
388   return centronics->fault;
389}
390
391DEFINE_LEGACY_DEVICE(CENTRONICS, centronics);
src/emu/machine/ctronics.h
r0r11451
1/***************************************************************************
2
3    Centronics printer interface
4
5***************************************************************************/
6
7#ifndef __CTRONICS_H__
8#define __CTRONICS_H__
9
10#include "devcb.h"
11
12
13/***************************************************************************
14    TYPE DEFINITIONS
15***************************************************************************/
16
17typedef struct _centronics_interface centronics_interface;
18struct _centronics_interface
19{
20   int is_ibmpc;
21
22   devcb_write_line out_ack_func;
23   devcb_write_line out_busy_func;
24   devcb_write_line out_not_busy_func;
25};
26
27
28/***************************************************************************
29    FUNCTION PROTOTYPES
30***************************************************************************/
31WRITE8_DEVICE_HANDLER( centronics_data_w );
32READ8_DEVICE_HANDLER( centronics_data_r );
33
34/* access to the individual bits */
35WRITE_LINE_DEVICE_HANDLER( centronics_d0_w );
36WRITE_LINE_DEVICE_HANDLER( centronics_d1_w );
37WRITE_LINE_DEVICE_HANDLER( centronics_d2_w );
38WRITE_LINE_DEVICE_HANDLER( centronics_d3_w );
39WRITE_LINE_DEVICE_HANDLER( centronics_d4_w );
40WRITE_LINE_DEVICE_HANDLER( centronics_d5_w );
41WRITE_LINE_DEVICE_HANDLER( centronics_d6_w );
42WRITE_LINE_DEVICE_HANDLER( centronics_d7_w );
43
44WRITE_LINE_DEVICE_HANDLER( centronics_strobe_w );
45WRITE_LINE_DEVICE_HANDLER( centronics_prime_w );
46WRITE_LINE_DEVICE_HANDLER( centronics_init_w );
47WRITE_LINE_DEVICE_HANDLER( centronics_autofeed_w );
48
49READ_LINE_DEVICE_HANDLER( centronics_ack_r );
50READ_LINE_DEVICE_HANDLER( centronics_busy_r );
51READ_LINE_DEVICE_HANDLER( centronics_pe_r );
52READ_LINE_DEVICE_HANDLER( centronics_not_busy_r );
53READ_LINE_DEVICE_HANDLER( centronics_vcc_r );
54READ_LINE_DEVICE_HANDLER( centronics_fault_r );
55
56
57/***************************************************************************
58    DEVICE CONFIGURATION MACROS
59***************************************************************************/
60
61DECLARE_LEGACY_DEVICE(CENTRONICS, centronics);
62
63#define MCFG_CENTRONICS_ADD(_tag, _intf) \
64   MCFG_DEVICE_ADD(_tag, CENTRONICS, 0) \
65   MCFG_DEVICE_CONFIG(_intf)
66
67
68/***************************************************************************
69    DEFAULT INTERFACES
70***************************************************************************/
71
72extern const centronics_interface standard_centronics;
73
74
75#endif /* __CTRONICS_H__ */
src/emu/machine/serial.c
r0r11451
1/* internal serial transmission */
2
3/* select a file on host filesystem to transfer using serial method,
4setup serial interface software in driver and let the transfer begin */
5
6/* this is used in the Amstrad NC Notepad emulation */
7
8
9
10/*
11
12    the output starts at 1 level. It changes to 0 when the start bit has been transmitted.
13    This therefore signals that data is following.
14    When all data bits have been received, stop bits are transmitted with a value of 1.
15
16    msm8251 expects this in asynchronous mode:
17    packet format:
18
19    bit count           function        value
20    1                   start bit       0
21    note 1              data bits       x
22    note 2              parity bit      x
23    note 3              stop bits       1
24
25    Note:
26    1. Data size can be defined (usual value is 8)
27    2. Parity bit (if parity is set to odd or even). Value of bit
28        is defined by data parity.
29    3. There should be at least 1 stop bit.
30*/
31
32#include "emu.h"
33#include "serial.h"
34
35
36#define VERBOSE 0
37#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
38
39/* a read/write bit stream. used to transmit data and to receive data */
40typedef struct _data_stream data_stream;
41struct _data_stream
42{
43   /* pointer to buffer */
44   unsigned char *pData;
45   /* length of buffer */
46   unsigned long DataLength;
47
48   /* bit offset within current byte */
49   unsigned long BitCount;
50   /* byte offset within data */
51   unsigned long ByteCount;
52};
53
54typedef struct _serial_t serial_t;
55struct _serial_t
56{
57   /* transmit data bit-stream */
58   data_stream transmit;
59   /* receive data bit-stream */
60   data_stream receive;
61
62   /* register to receive data */
63   serial_receive_register   receive_reg;
64   /* register to transmit data */
65   serial_transmit_register transmit_reg;
66
67   /* connection to transmit/receive data over */
68   serial_connection connection;
69
70   /* data form to transmit/receive */
71   data_form form;
72
73   int transmit_state;
74
75   /* baud rate */
76   unsigned long BaudRate;
77
78   /* baud rate timer */
79   emu_timer   *timer;
80};
81
82INLINE serial_t *get_safe_token(device_t *device)
83{
84   assert(device != NULL);
85   //assert(device->type() == SERIAL);
86
87   return (serial_t *)downcast<legacy_device_base *>(device)->token();
88}
89
90
91/* the serial streams */
92static TIMER_CALLBACK(serial_device_baud_rate_callback);
93
94
95/*********************************************************/
96
97static unsigned char serial_parity_table[256];
98
99void serial_helper_setup(void)
100{
101   int i;
102
103   /* if sum of all bits in the byte is even, then the data
104    has even parity, otherwise it has odd parity */
105   for (i=0; i<256; i++)
106   {
107      int data;
108      int sum;
109      int b;
110
111      sum = 0;
112      data = i;
113
114      for (b=0; b<8; b++)
115      {
116         sum+=data & 0x01;
117
118         data = data>>1;
119      }
120
121      serial_parity_table[i] = sum & 0x01;
122   }
123}
124
125static unsigned char serial_helper_get_parity(unsigned char data)
126{
127   return serial_parity_table[data & 0x0ff];
128}
129
130static void serial_device_in_callback(running_machine &machine, int id, unsigned long status)
131{
132/*  serial_t *ser = get_safe_token(device);
133
134    ser->connection.input_state = status;*/
135}
136
137/***** SERIAL DEVICE ******/
138void serial_device_setup(device_t *device, int baud_rate, int num_data_bits, int stop_bit_count, int parity_code)
139{
140   serial_t *ser = get_safe_token(device);
141
142   ser->BaudRate = baud_rate;
143   ser->form.word_length = num_data_bits;
144   ser->form.stop_bit_count = stop_bit_count;
145   ser->form.parity = parity_code;
146   ser->timer = device->machine().scheduler().timer_alloc(FUNC(serial_device_baud_rate_callback), (void *)device);
147
148   serial_connection_init(device->machine(),&ser->connection);
149   serial_connection_set_in_callback(device->machine(),&ser->connection, serial_device_in_callback);
150
151   /* signal to other end it is clear to send! */
152   /* data is initially high state */
153   /* set /rts */
154   ser->connection.State |= SERIAL_STATE_RTS;
155   /* signal to other end data is ready to be accepted */
156   /* set /dtr */
157   ser->connection.State |= SERIAL_STATE_DTR;
158   set_out_data_bit(ser->connection.State, 1);
159   serial_connection_out(device->machine(),&ser->connection);
160   transmit_register_reset(&ser->transmit_reg);
161   receive_register_reset(&ser->receive_reg);
162   receive_register_setup(&ser->receive_reg, &ser->form);
163}
164
165
166unsigned long serial_device_get_state(device_t *device)
167{
168   serial_t *ser = get_safe_token(device);
169
170   return ser->connection.State;
171}
172
173void serial_device_set_transmit_state(device_t *device, int state)
174{
175   int previous_state;
176   serial_t *ser = get_safe_token(device);
177
178   previous_state = ser->transmit_state;
179
180   ser->transmit_state = state;
181
182   if ((state^previous_state)!=0)
183   {
184      if (state)
185      {
186         /* start timer */
187         ser->timer->adjust(attotime::zero, 0, attotime::from_hz(ser->BaudRate));
188      }
189      else
190      {
191         /* remove timer */
192         ser->timer->reset();
193      }
194   }
195
196}
197
198/* get a bit from input stream */
199static int data_stream_get_data_bit_from_data_byte(data_stream *stream)
200{
201   int data_bit;
202   int data_byte;
203
204   if (stream->ByteCount<stream->DataLength)
205   {
206      /* get data from buffer */
207      data_byte= stream->pData[stream->ByteCount];
208   }
209   else
210   {
211      /* over end of buffer, so return 0 */
212      data_byte= 0;
213   }
214
215   /* get bit from data */
216   data_bit = (data_byte>>(7-stream->BitCount)) & 0x01;
217
218   /* update bit count */
219   stream->BitCount++;
220   /* ripple overflow onto byte count */
221   stream->ByteCount+=stream->BitCount>>3;
222   /* lock bit count into range */
223   stream->BitCount &=0x07;
224
225   /* do not let it read over end of data */
226   if (stream->ByteCount>=stream->DataLength)
227   {
228      stream->ByteCount = stream->DataLength-1;
229   }
230
231   return data_bit;
232}
233
234
235void receive_register_setup(serial_receive_register *receive, data_form *data_form)
236{
237   receive->bit_count = data_form->word_length + data_form->stop_bit_count;
238
239   if (data_form->parity != SERIAL_PARITY_NONE)
240   {
241      receive->bit_count++;
242   }
243}
244
245
246/* this is generic code to be used in serial chip implementations */
247/* the majority of serial chips work in the same way and this code will work */
248/* for them */
249
250/* receive a bit */
251void receive_register_update_bit(serial_receive_register *receive, int bit)
252{
253   int previous_bit;
254
255   LOG(("receive register receive bit: %1x\n",bit));
256   previous_bit = receive->register_data & 1;
257
258   /* shift previous bit 7 out */
259   receive->register_data = receive->register_data<<1;
260   /* shift new bit in */
261   receive->register_data = (receive->register_data & 0xfffe) | bit;
262   /* update bit count received */
263   receive->bit_count_received++;
264
265   /* asyncrhonouse mode */
266   if (receive->flags & RECEIVE_REGISTER_WAITING_FOR_START_BIT)
267   {
268      /* the previous bit is stored in uart.receive char bit 0 */
269      /* has the bit state changed? */
270      if (((previous_bit ^ bit) & 0x01)!=0)
271      {
272         /* yes */
273         if (bit==0)
274         {
275            //logerror("receive register saw start bit\n");
276
277            /* seen start bit! */
278            /* not waiting for start bit now! */
279            receive->flags &=~RECEIVE_REGISTER_WAITING_FOR_START_BIT;
280            receive->flags |=RECEIVE_REGISTER_SYNCHRONISED;
281            /* reset bit count received */
282            receive->bit_count_received = 0;
283         }
284      }
285   }
286   else
287   if (receive->flags & RECEIVE_REGISTER_SYNCHRONISED)
288   {
289      /* received all bits? */
290      if (receive->bit_count_received==receive->bit_count)
291      {
292         receive->bit_count_received = 0;
293         receive->flags &=~RECEIVE_REGISTER_SYNCHRONISED;
294         receive->flags |= RECEIVE_REGISTER_WAITING_FOR_START_BIT;
295         //logerror("receive register full\n");
296         receive->flags |= RECEIVE_REGISTER_FULL;
297      }
298   }
299}
300
301void receive_register_reset(serial_receive_register *receive_reg)
302{
303   receive_reg->bit_count_received = 0;
304   receive_reg->flags &=~RECEIVE_REGISTER_FULL;
305   receive_reg->flags &=~RECEIVE_REGISTER_SYNCHRONISED;
306   receive_reg->flags |= RECEIVE_REGISTER_WAITING_FOR_START_BIT;
307}
308
309void receive_register_extract(serial_receive_register *receive_reg, data_form *data_form)
310{
311   unsigned long data_shift;
312   UINT8 data;
313
314   receive_register_reset(receive_reg);
315
316   data_shift = 0;
317
318   /* if parity is even or odd, there should be a parity bit in the stream! */
319   if (data_form->parity!=SERIAL_PARITY_NONE)
320   {
321      data_shift++;
322   }
323
324   data_shift+=data_form->stop_bit_count;
325
326   /* strip off stop bits and parity */
327   data = receive_reg->register_data>>data_shift;
328
329   /* mask off other bits so data byte has 0's in unused bits */
330   data = data & (0x0ff
331      >>
332      (8-(data_form->word_length)));
333
334   receive_reg->byte_received  = data;
335
336   /* parity enable? */
337   switch (data_form->parity)
338   {
339      case SERIAL_PARITY_NONE:
340         break;
341
342      /* check parity */
343      case SERIAL_PARITY_ODD:
344      case SERIAL_PARITY_EVEN:
345      {
346         //unsigned char computed_parity;
347         //unsigned char parity_received;
348
349         /* get state of parity bit received */
350         //parity_received = (receive_reg->register_data>>data_form->stop_bit_count) & 0x01;
351
352         /* compute parity for received bits */
353         //computed_parity = serial_helper_get_parity(data);
354
355         if (data_form->parity == SERIAL_PARITY_ODD)
356         {
357            /* odd parity */
358
359
360         }
361         else
362         {
363            /* even parity */
364
365
366         }
367
368      }
369      break;
370   }
371}
372
373/***** TRANSMIT REGISTER *****/
374
375void transmit_register_reset(serial_transmit_register *transmit_reg)
376{
377   transmit_reg->flags |=TRANSMIT_REGISTER_EMPTY;
378}
379
380/* used to construct data in stream format */
381static void transmit_register_add_bit(serial_transmit_register *transmit_reg, int bit)
382{
383   /* combine bit */
384   transmit_reg->register_data = transmit_reg->register_data<<1;
385   transmit_reg->register_data &=~1;
386   transmit_reg->register_data|=(bit & 0x01);
387   transmit_reg->bit_count++;
388}
389
390
391/* generate data in stream format ready for transfer */
392void transmit_register_setup(serial_transmit_register *transmit_reg, data_form *data_form,unsigned char data_byte)
393{
394   int i;
395   unsigned char transmit_data;
396
397
398   transmit_reg->bit_count_transmitted = 0;
399   transmit_reg->bit_count = 0;
400   transmit_reg->flags &=~TRANSMIT_REGISTER_EMPTY;
401
402   /* start bit */
403   transmit_register_add_bit(transmit_reg,0);
404
405   /* data bits */
406   transmit_data = data_byte;
407   for (i=0; i<data_form->word_length; i++)
408   {
409      int databit;
410
411      /* get bit from data */
412      databit = (transmit_data>>(data_form->word_length-1)) & 0x01;
413      /* add bit to formatted byte */
414      transmit_register_add_bit(transmit_reg, databit);
415      transmit_data = transmit_data<<1;
416   }
417
418   /* parity */
419   if (data_form->parity!=SERIAL_PARITY_NONE)
420   {
421      /* odd or even parity */
422      unsigned char parity;
423
424      /* get parity */
425      /* if parity = 0, data has even parity - i.e. there is an even number of one bits in the data */
426      /* if parity = 1, data has odd parity - i.e. there is an odd number of one bits in the data */
427      parity = serial_helper_get_parity(data_byte);
428
429      transmit_register_add_bit(transmit_reg, parity);
430   }
431
432   /* stop bit(s) */
433   for (i=0; i<data_form->stop_bit_count; i++)
434   {
435      transmit_register_add_bit(transmit_reg,1);
436   }
437}
438
439
440/* get a bit from the transmit register */
441static int transmit_register_get_data_bit(serial_transmit_register *transmit_reg)
442{
443   int bit;
444
445   bit = (transmit_reg->register_data>>
446      (transmit_reg->bit_count - 1 -
447      transmit_reg->bit_count_transmitted)) & 0x01;
448
449   transmit_reg->bit_count_transmitted++;
450
451   /* have all bits of this stream formatted byte been sent? */
452   if (transmit_reg->bit_count_transmitted==transmit_reg->bit_count)
453   {
454      /* yes - generate a new byte to send */
455      transmit_reg->flags |= TRANSMIT_REGISTER_EMPTY;
456   }
457
458   return bit;
459}
460
461
462void transmit_register_send_bit(running_machine &machine, serial_transmit_register *transmit_reg, serial_connection *connection)
463{
464   int data;
465
466   data = transmit_register_get_data_bit(transmit_reg);
467
468   /* set tx data bit */
469   set_out_data_bit(connection->State, data);
470
471   /* state out through connection */
472   serial_connection_out(machine, connection);
473}
474
475static void serial_protocol_none_sent_char(device_t *device)
476{
477   int i;
478   int bit;
479   unsigned char data_byte;
480   serial_t *ser = get_safe_token(device);
481
482   /* generate byte to transmit */
483   data_byte = 0;
484   for (i=0; i<ser->form.word_length; i++)
485   {
486      data_byte = data_byte<<1;
487      bit = data_stream_get_data_bit_from_data_byte(&ser->transmit);
488      data_byte = data_byte|bit;
489   }
490   /* setup register */
491   transmit_register_setup(&ser->transmit_reg,&ser->form, data_byte);
492
493   logerror("serial device transmitted char: %02x\n",data_byte);
494}
495
496static TIMER_CALLBACK(serial_device_baud_rate_callback)
497{
498   serial_t *ser = get_safe_token((device_t*)ptr);
499
500   /* receive data into receive register */
501   receive_register_update_bit(&ser->receive_reg, get_in_data_bit(ser->connection.input_state));
502
503   if (ser->receive_reg.flags & RECEIVE_REGISTER_FULL)
504   {
505      //logerror("SERIAL DEVICE\n");
506      receive_register_extract(&ser->receive_reg, &ser->form);
507
508      logerror("serial device receive char: %02x\n",ser->receive_reg.byte_received);
509   }
510
511   /* is transmit empty? */
512   if (ser->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)
513   {
514      /* char has been sent, execute callback */
515      serial_protocol_none_sent_char((device_t*)ptr);
516   }
517
518   /* other side says it is clear to send? */
519   if (ser->connection.input_state & SERIAL_STATE_CTS)
520   {
521      /* send bit */
522      transmit_register_send_bit(machine, &ser->transmit_reg, &ser->connection);
523   }
524}
525
526/* connect the specified connection to this serial device */
527void serial_device_connect(device_t *device, serial_connection *connection)
528{
529   serial_t *ser = get_safe_token(device);
530   serial_connection_link(device->machine(), connection, &ser->connection);
531}
532
533
534/* load image */
535static int serial_device_load_internal(device_image_interface &image, unsigned char **ptr, int *pDataSize)
536{
537   int datasize;
538   unsigned char *data;
539
540   /* get file size */
541   datasize = image.length();
542
543   if (datasize!=0)
544   {
545      /* malloc memory for this data */
546      data = (unsigned char *)malloc(datasize);
547
548      if (data!=NULL)
549      {
550         /* read whole file */
551         image.fread(data, datasize);
552
553         *ptr = data;
554         *pDataSize = datasize;
555
556         logerror("File loaded!\r\n");
557
558         /* ok! */
559         return 1;
560      }
561   }
562   return 0;
563}
564
565/* reset position in stream */
566static void data_stream_reset(data_stream *stream)
567{
568   /* reset byte offset */
569   stream->ByteCount= 0;
570   /* reset bit count */
571   stream->BitCount = 0;
572}
573
574/* free stream */
575static void data_stream_free(data_stream *stream)
576{
577   if (stream->pData!=NULL)
578   {
579      free(stream->pData);
580      stream->pData = NULL;
581   }
582   stream->DataLength = 0;
583}
584
585/* initialise stream */
586static void data_stream_init(data_stream *stream, unsigned char *pData, unsigned long DataLength)
587{
588   stream->pData = pData;
589   stream->DataLength = DataLength;
590   data_stream_reset(stream);
591}
592
593DEVICE_START(serial)
594{
595   //serial_t *ser = get_safe_token(device);
596}
597
598DEVICE_RESET(serial)
599{
600//  serial_t *ser = get_safe_token(device);
601}
602
603DEVICE_IMAGE_LOAD(serial)
604{
605   int data_length;
606   unsigned char *data;
607   device_t *device = &image.device();
608
609   serial_t *ser = get_safe_token(device);
610
611   /* load file and setup transmit data */
612   if (serial_device_load_internal(image, &data, &data_length))
613   {
614      data_stream_init(&ser->transmit, data, data_length);
615      return IMAGE_INIT_PASS;
616   }
617
618   return IMAGE_INIT_FAIL;
619}
620
621
622DEVICE_IMAGE_UNLOAD(serial)
623{
624   device_t *device = &image.device();
625   serial_t *ser = get_safe_token(device);
626
627   /* stop transmit */
628   serial_device_set_transmit_state(device, 0);
629   /* free streams */
630   data_stream_free(&ser->transmit);
631   data_stream_free(&ser->receive);
632}
633
634
635DEVICE_GET_INFO( serial )
636{
637   switch ( state )
638   {
639      case DEVINFO_INT_TOKEN_BYTES:            info->i = sizeof(serial_t);                        break;
640      case DEVINFO_INT_INLINE_CONFIG_BYTES:      info->i = 0;                                 break;
641      case DEVINFO_INT_IMAGE_TYPE:               info->i = IO_SERIAL;                                   break;
642      case DEVINFO_INT_IMAGE_READABLE:            info->i = 1;                                           break;
643      case DEVINFO_INT_IMAGE_WRITEABLE:         info->i = 1;                                           break;
644      case DEVINFO_INT_IMAGE_CREATABLE:          info->i = 1;                                           break;
645
646      case DEVINFO_FCT_START:                      info->start = DEVICE_START_NAME( serial );             break;
647      case DEVINFO_FCT_RESET:                  info->reset = DEVICE_RESET_NAME( serial );            break;
648      case DEVINFO_FCT_IMAGE_LOAD:              info->f = (genf *) DEVICE_IMAGE_LOAD_NAME( serial );   break;
649      case DEVINFO_FCT_IMAGE_UNLOAD:              info->f = (genf *) DEVICE_IMAGE_UNLOAD_NAME(serial );   break;
650      case DEVINFO_STR_NAME:                      strcpy( info->s, "Serial port");                       break;
651      case DEVINFO_STR_FAMILY:                    strcpy(info->s, "Serial port");                           break;
652      case DEVINFO_STR_IMAGE_FILE_EXTENSIONS:       strcpy(info->s, "");                                    break;
653      case DEVINFO_STR_VERSION:               strcpy(info->s, "1.0");                           break;
654      case DEVINFO_STR_SOURCE_FILE:            strcpy(info->s, __FILE__);                        break;
655      case DEVINFO_STR_CREDITS:               strcpy(info->s, "Copyright the MESS Team");          break;
656   }
657}
658
659/*******************************************************************************/
660/*******************************************************************************/
661/********* SERIAL CONNECTION ***********/
662
663
664/* this converts state at this end to a state the other end can accept */
665/* e.g. CTS at this end becomes RTS at other end.
666        RTS at this end becomes CTS at other end.
667        TX at this end becomes RX at other end.
668        RX at this end becomes TX at other end.
669        etc
670
671        The same thing is done inside the serial null-terminal lead */
672
673static unsigned long serial_connection_spin_bits(unsigned long input_status)
674{
675
676   return
677      /* cts -> rts */
678      (((input_status & 0x01)<<1) |
679      /* rts -> cts */
680      ((input_status>>1) & 0x01) |
681      /* dsr -> dtr */
682      (((input_status>>2) & 0x01)<<3) |
683      /* dtr -> dsr */
684      (((input_status>>3) & 0x01)<<2) |
685      /* rx -> tx */
686      (((input_status>>4) & 0x01)<<5) |
687      /* tx -> rx */
688      (((input_status>>5) & 0x01)<<4));
689}
690
691
692/* setup callbacks for connection */
693void serial_connection_init(running_machine &machine, serial_connection *connection)
694{
695   connection->out_callback = NULL;
696   connection->in_callback = NULL;
697}
698
699/* set callback which will be executed when in status has changed */
700void serial_connection_set_in_callback(running_machine &machine, serial_connection *connection, void (*in_cb)(running_machine &machine, int id, unsigned long status))
701{
702   connection->in_callback = in_cb;
703}
704
705/* output new state through connection */
706void serial_connection_out(running_machine &machine, serial_connection *connection)
707{
708   if (connection->out_callback!=NULL)
709   {
710      unsigned long state_at_other_end;
711
712      state_at_other_end = serial_connection_spin_bits(connection->State);
713
714      connection->out_callback(machine, connection->id, state_at_other_end);
715   }
716}
717
718/* join two serial connections together */
719void serial_connection_link(running_machine &machine, serial_connection *connection_a, serial_connection *connection_b)
720{
721   /* both connections should have their in connection setup! */
722   /* the in connection is the callback they use to update their state based
723    on the output from the other side */
724   connection_a->out_callback = connection_b->in_callback;
725   connection_b->out_callback = connection_a->in_callback;
726
727   /* let b know the state of a */
728   serial_connection_out(machine,connection_a);
729   /* let a know the state of b */
730   serial_connection_out(machine,connection_b);
731}
732
733DEFINE_LEGACY_IMAGE_DEVICE(SERIAL, serial);
src/emu/machine/serial.h
r0r11451
1/*****************************************************************************
2 *
3 * machine/serial.h
4 *
5 * internal serial transmission
6 *
7 * This code is used to transmit a file stored on the host filesystem
8 * (e.g. PC harddrive) to an emulated system.
9 *
10 * The file is converted into a serial bit-stream which can be received
11 * by the emulated serial chip in the emulated system.
12 *
13 * The file can be transmitted using different protocols.
14 *
15 * A and B are two computers linked with a serial connection
16 * A and B can transmit and receive data, through the same connection
17 *
18 * These flags apply to A and B, and give the state of the input & output
19 * signals at each side.
20 *
21 ****************************************************************************/
22
23#ifndef SERIAL_H_
24#define SERIAL_H_
25
26
27/*
28    CTS = Clear to Send. (INPUT)
29    Other end of connection is ready to accept data
30
31
32    NOTE:
33
34      This output is active low on serial chips (e.g. 0 is CTS is set),
35      but here it is active high!
36*/
37#define SERIAL_STATE_CTS   0x0001
38
39/*
40    RTS = Request to Send. (OUTPUT)
41    This end is ready to send data, and requests if the other
42    end is ready to accept it
43
44    NOTE:
45
46      This output is active low on serial chips (e.g. 0 is RTS is set),
47      but here it is active high!
48*/
49#define SERIAL_STATE_RTS   0x0002
50
51/*
52    DSR = Data Set ready. (INPUT)
53    Other end of connection has data
54
55
56    NOTE:
57
58      This output is active low on serial chips (e.g. 0 is DSR is set),
59      but here it is active high!
60*/
61#define SERIAL_STATE_DSR   0x0004
62
63/*
64    DTR = Data terminal Ready. (OUTPUT)
65    TX contains new data.
66
67    NOTE:
68
69      This output is active low on serial chips (e.g. 0 is DTR is set),
70      but here it is active high!
71*/
72#define SERIAL_STATE_DTR   0x0008
73/* RX = Recieve data. (INPUT) */
74#define SERIAL_STATE_RX_DATA   0x00010
75/* TX = Transmit data. (OUTPUT) */
76#define SERIAL_STATE_TX_DATA   0x00020
77
78/* parity selections */
79/* if all the bits are added in a byte, if the result is:
80    even -> parity is even
81    odd -> parity is odd
82*/
83enum
84{
85   SERIAL_PARITY_NONE,      /* no parity. a parity bit will not be in the transmitted/received data */
86   SERIAL_PARITY_ODD,      /* odd parity */
87   SERIAL_PARITY_EVEN      /* even parity */
88};
89
90/* this macro is used to extract the received data from the status */
91#define get_in_data_bit(x) ((x & SERIAL_STATE_RX_DATA)>>4)
92
93/* this macro is used to set the transmitted data in the status */
94#define set_out_data_bit(x, data) \
95   x&=~SERIAL_STATE_TX_DATA; \
96   x|=(data<<5)
97
98
99/*******************************************************************************/
100/**** SERIAL CONNECTION ***/
101
102
103/* this structure represents a serial connection */
104typedef struct _serial_connection serial_connection;
105struct _serial_connection
106{
107   int id;
108   /* state of this side */
109   unsigned long State;
110
111   /* state of other side - store here */
112   unsigned long input_state;
113
114   /* this callback is executed when this side has refreshed it's state,
115    to let the other end know */
116   void   (*out_callback)(running_machine &machine, int id, unsigned long state);
117   /* this callback is executed when the other side has refreshed it's state,
118    to let the other end know */
119   void   (*in_callback)(running_machine &machine, int id, unsigned long state);
120};
121
122/*----------- defined in machine/serial.c -----------*/
123
124/* setup out and in callbacks */
125void serial_connection_init(running_machine &machine, serial_connection *connection);
126
127/* set callback which will be executed when in status has changed */
128void serial_connection_set_in_callback(running_machine &machine, serial_connection *connection, void (*in_cb)(running_machine &machine, int id, unsigned long status));
129
130/* output status, if callback is setup it will be executed with the new status */
131void serial_connection_out(running_machine &machine, serial_connection *connection);
132
133/* join two serial connections */
134void serial_connection_link(running_machine &machine, serial_connection *connection_a, serial_connection *connection_b);
135
136
137/*******************************************************************************/
138
139/* form of data being transmitted and received */
140typedef struct _data_form data_form;
141struct _data_form
142{
143   /* length of word in bits */
144   unsigned long word_length;
145   /* parity state */
146   unsigned long parity;
147   /* number of stop bits */
148   unsigned long stop_bit_count;
149};
150
151/*******************************************************************************/
152
153/*******************************************************************************/
154/**** RECEIVE AND TRANSMIT GENERIC CODE ****/
155
156/* this can be used by most of the serial chip implementations,
157because they all work in roughly the same way.
158There is generic code to send and receive data in the specified form */
159
160/* receive is waiting for start bit. The transition from high-low indicates
161start of start bit. This is used to synchronise with the data being transfered */
162#define RECEIVE_REGISTER_WAITING_FOR_START_BIT 0x01
163/* receive is synchronised with data, data bits will be clocked in */
164#define RECEIVE_REGISTER_SYNCHRONISED 0x02
165/* set if receive register has been filled */
166#define RECEIVE_REGISTER_FULL 0x04
167
168
169/* the receive register holds data in receive form! */
170/* this must be extracted to get the data byte received */
171typedef struct _serial_receive_register serial_receive_register;
172struct _serial_receive_register
173{
174   /* data */
175   unsigned long register_data;
176   /* flags */
177   unsigned long flags;
178   /* bit count received */
179   unsigned long bit_count_received;
180   /* length of data to receive - includes data bits, parity bit and stop bit */
181   unsigned long bit_count;
182
183   /* the byte of data received */
184   unsigned char byte_received;
185};
186
187void   receive_register_setup(serial_receive_register *receive, data_form *data_form);
188void   receive_register_update_bit(serial_receive_register *receive, int bit_state);
189void   receive_register_extract(serial_receive_register *receive_reg, data_form *data_form);
190void   receive_register_reset(serial_receive_register *receive_reg);
191
192/* the transmit register is the final stage
193in the serial transmit procedure */
194/* normally, data is written to the transmit reg,
195then it is assembled into transmit form and transmitted */
196/* the transmit register holds data in transmit form */
197
198/* register is empty and ready to be filled with data */
199#define TRANSMIT_REGISTER_EMPTY 0x0001
200
201typedef struct _serial_transmit_register serial_transmit_register;
202struct _serial_transmit_register
203{
204   /* data */
205   unsigned long register_data;
206   /* flags */
207   unsigned long flags;
208   /* number of bits transmitted */
209   unsigned long bit_count_transmitted;
210   /* length of data to send */
211   unsigned long bit_count;
212};
213
214/* setup transmit reg ready for transmit */
215void transmit_register_setup(serial_transmit_register *transmit_reg, data_form *data_form,unsigned char data_byte);
216void   transmit_register_send_bit(running_machine &machine, serial_transmit_register *transmit_reg, serial_connection *connection);
217void   transmit_register_reset(serial_transmit_register *transmit_reg);
218
219/*******************************************************************************/
220/**** SERIAL HELPER ****/
221
222void serial_helper_setup(void);
223
224/*******************************************************************************/
225/**** SERIAL DEVICE ****/
226
227unsigned long serial_device_get_state(device_t *device);
228
229/* connect this device to the emulated serial chip */
230/* id is the serial device to connect to */
231/* connection is the serial connection to connect to the serial device */
232void serial_device_connect(device_t *image, serial_connection *connection);
233
234DECLARE_LEGACY_IMAGE_DEVICE(SERIAL, serial);
235
236#define MCFG_SERIAL_ADD(_tag) \
237   MCFG_DEVICE_ADD(_tag, SERIAL, 0)
238
239DEVICE_START(serial);
240DEVICE_IMAGE_LOAD(serial);
241
242void serial_device_setup(device_t *image, int baud_rate, int num_data_bits, int stop_bit_count, int parity_code);
243
244/* set the transmit state of the serial device */
245void serial_device_set_transmit_state(device_t *image, int state);
246
247#endif /* SERIAL_H_ */
src/emu/machine/msm8251.c
r0r11451
1/*********************************************************************
2
3    msm8251.c
4
5    MSM/Intel 8251 Universal Synchronous/Asynchronous Receiver Transmitter code
6
7*********************************************************************/
8
9#include "emu.h"
10#include "msm8251.h"
11
12
13/***************************************************************************
14    MACROS
15***************************************************************************/
16
17#define VERBOSE 0
18
19#define LOG(x)   do { if (VERBOSE) logerror x; } while (0)
20
21
22/***************************************************************************
23    TYPE DEFINITIONS
24***************************************************************************/
25
26typedef struct _msm8251_t msm8251_t;
27struct _msm8251_t
28{
29   devcb_resolved_read_line   in_rxd_func;
30   devcb_resolved_write_line   out_txd_func;
31   devcb_resolved_read_line   in_dsr_func;
32   devcb_resolved_write_line   out_dtr_func;
33   devcb_resolved_write_line   out_rts_func;
34   devcb_resolved_write_line   out_rxrdy_func;
35   devcb_resolved_write_line   out_txrdy_func;
36   devcb_resolved_write_line   out_txempty_func;
37   devcb_resolved_write_line   out_syndet_func;
38
39   /* flags controlling how msm8251_control_w operates */
40   UINT8 flags;
41   /* offset into sync_bytes used during sync byte transfer */
42   UINT8 sync_byte_offset;
43   /* number of sync bytes written so far */
44   UINT8 sync_byte_count;
45   /* the sync bytes written */
46   UINT8 sync_bytes[2];
47   /* status of msm8251 */
48   UINT8 status;
49   UINT8 command;
50   /* mode byte - bit definitions depend on mode - e.g. synchronous, asynchronous */
51   UINT8 mode_byte;
52
53   /* data being received */
54   UINT8 data;
55
56   /* receive reg */
57   serial_receive_register receive_reg;
58   /* transmit reg */
59   serial_transmit_register transmit_reg;
60
61   data_form form;
62
63   /* the serial connection that data is transfered over */
64   /* this is usually connected to the serial device */
65   serial_connection connection;
66};
67
68
69
70/***************************************************************************
71    PROTOTYPES
72***************************************************************************/
73
74static void msm8251_in_callback(running_machine &machine, int id, unsigned long state);
75static void msm8251_update_tx_empty(device_t *device);
76static void msm8251_update_tx_ready(device_t *device);
77
78
79
80/***************************************************************************
81    INLINE FUNCTIONS
82***************************************************************************/
83
84INLINE msm8251_t *get_token(device_t *device)
85{
86   assert(device != NULL);
87   assert(device->type() == MSM8251);
88
89   return (msm8251_t *) downcast<legacy_device_base *>(device)->token();
90}
91
92
93INLINE const msm8251_interface *get_interface(device_t *device)
94{
95   assert(device != NULL);
96   assert(device->type() == MSM8251);
97
98   return (const msm8251_interface *) device->static_config();
99}
100
101
102/***************************************************************************
103    GLOBAL VARIABLES
104***************************************************************************/
105
106const msm8251_interface default_msm8251_interface = { DEVCB_NULL, };
107
108
109/***************************************************************************
110    IMPLEMENTATION
111***************************************************************************/
112
113/*-------------------------------------------------
114    msm8251_in_callback
115-------------------------------------------------*/
116
117static void msm8251_in_callback(running_machine &machine, int id, unsigned long state)
118{
119   device_t *device;
120   msm8251_t *uart;
121   int changed;
122
123   /* NPW 29-Nov-2008 - These two lines are a hack and indicate why our "serial" infrastructure needs to be updated */
124   device = machine.device("uart");
125   uart = get_token(device);
126
127   changed = uart->connection.input_state^state;
128
129   uart->connection.input_state = state;
130
131   /* did cts change state? */
132   if (changed & SERIAL_STATE_CTS)
133   {
134      /* yes */
135      /* update tx ready */
136      /* msm8251_update_tx_ready(device); */
137   }
138}
139
140
141
142/*-------------------------------------------------
143    DEVICE_START( msm8251 )
144-------------------------------------------------*/
145
146static DEVICE_START( msm8251 )
147{
148   msm8251_t *uart = get_token(device);
149   const msm8251_interface *intf = get_interface(device);
150
151   serial_helper_setup();
152
153   // resolve callbacks
154   uart->out_rxrdy_func.resolve(intf->out_rxrdy_func, *device);
155   uart->out_txrdy_func.resolve(intf->out_txrdy_func, *device);
156   uart->out_txempty_func.resolve(intf->out_txempty_func, *device);
157
158   /* setup this side of the serial connection */
159   serial_connection_init(device->machine(),&uart->connection);
160   serial_connection_set_in_callback(device->machine(),&uart->connection, msm8251_in_callback);
161   uart->connection.input_state = 0;
162}
163
164
165
166/*-------------------------------------------------
167    msm8251_update_rx_ready
168-------------------------------------------------*/
169
170static void msm8251_update_rx_ready(device_t *device)
171{
172   msm8251_t *uart = get_token(device);
173   int state;
174
175   state = uart->status & MSM8251_STATUS_RX_READY;
176
177   /* masked? */
178   if ((uart->command & (1<<2))==0)
179   {
180      state = 0;
181   }
182
183   uart->out_rxrdy_func(state != 0);
184}
185
186
187
188/*-------------------------------------------------
189    msm8251_receive_clock
190-------------------------------------------------*/
191
192void msm8251_receive_clock(device_t *device)
193{
194   msm8251_t *uart = get_token(device);
195
196   /* receive enable? */
197   if (uart->command & (1<<2))
198   {
199      //logerror("MSM8251\n");
200      /* get bit received from other side and update receive register */
201      receive_register_update_bit(&uart->receive_reg, get_in_data_bit(uart->connection.input_state));
202
203      if (uart->receive_reg.flags & RECEIVE_REGISTER_FULL)
204      {
205         receive_register_extract(&uart->receive_reg, &uart->form);
206         msm8251_receive_character(device, uart->receive_reg.byte_received);
207      }
208   }
209}
210
211
212
213/*-------------------------------------------------
214    msm8251_transmit_clock
215-------------------------------------------------*/
216
217void msm8251_transmit_clock(device_t *device)
218{
219   msm8251_t *uart = get_token(device);
220
221   /* transmit enable? */
222   if (uart->command & (1<<0))
223   {
224
225      /* transmit register full? */
226      if ((uart->status & MSM8251_STATUS_TX_READY)==0)
227      {
228         /* if transmit reg is empty */
229         if ((uart->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)!=0)
230         {
231            /* set it up */
232            transmit_register_setup(&uart->transmit_reg, &uart->form, uart->data);
233            /* msm8251 transmit reg now empty */
234            uart->status |=MSM8251_STATUS_TX_EMPTY;
235            /* ready for next transmit */
236            uart->status |=MSM8251_STATUS_TX_READY;
237
238            msm8251_update_tx_empty(device);
239            msm8251_update_tx_ready(device);
240         }
241      }
242
243      /* if transmit is not empty... transmit data */
244      if ((uart->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)==0)
245      {
246   //      logerror("MSM8251\n");
247         transmit_register_send_bit(device->machine(),&uart->transmit_reg, &uart->connection);
248      }
249   }
250
251#if 0
252   /* hunt mode? */
253   /* after each bit has been shifted in, it is compared against the current sync byte */
254   if (uart->command & (1<<7))
255   {
256      /* data matches sync byte? */
257      if (uart->data == uart->sync_bytes[uart->sync_byte_offset])
258      {
259         /* sync byte matches */
260         /* update for next sync byte? */
261         uart->sync_byte_offset++;
262
263         /* do all sync bytes match? */
264         if (uart->sync_byte_offset == uart->sync_byte_count)
265         {
266            /* ent hunt mode */
267            uart->command &=~(1<<7);
268         }
269      }
270      else
271      {
272         /* if there is no match, reset */
273         uart->sync_byte_offset = 0;
274      }
275   }
276#endif
277}
278
279
280
281/*-------------------------------------------------
282    msm8251_update_tx_ready
283-------------------------------------------------*/
284
285static void msm8251_update_tx_ready(device_t *device)
286{
287   msm8251_t *uart = get_token(device);
288
289   /* clear tx ready state */
290   int tx_ready;
291
292   /* tx ready output is set if:
293        DB Buffer Empty &
294        CTS is set &
295        Transmit enable is 1
296    */
297
298   tx_ready = 0;
299
300   /* transmit enable? */
301   if ((uart->command & (1<<0))!=0)
302   {
303      /* other side has rts set (comes in as CTS at this side) */
304      if (uart->connection.input_state & SERIAL_STATE_CTS)
305      {
306         if (uart->status & MSM8251_STATUS_TX_EMPTY)
307         {
308            /* enable transfer */
309            tx_ready = 1;
310         }
311      }
312   }
313
314   uart->out_txrdy_func(tx_ready);
315}
316
317
318
319/*-------------------------------------------------
320    msm8251_update_tx_empty
321-------------------------------------------------*/
322
323static void msm8251_update_tx_empty(device_t *device)
324{
325   msm8251_t *uart = get_token(device);
326
327   if (uart->status & MSM8251_STATUS_TX_EMPTY)
328   {
329      /* tx is in marking state (high) when tx empty! */
330      set_out_data_bit(uart->connection.State, 1);
331      serial_connection_out(device->machine(),&uart->connection);
332   }
333
334   uart->out_txempty_func((uart->status & MSM8251_STATUS_TX_EMPTY) != 0);
335}
336
337
338
339/*-------------------------------------------------
340    DEVICE_RESET( msm8251 )
341-------------------------------------------------*/
342
343static DEVICE_RESET( msm8251 )
344{
345   msm8251_t *uart = get_token(device);
346
347   LOG(("MSM8251: Reset\n"));
348
349   /* what is the default setup when the 8251 has been reset??? */
350
351   /* msm8251 datasheet explains the state of tx pin at reset */
352   /* tx is set to 1 */
353   set_out_data_bit(uart->connection.State,1);
354
355   /* assumption, rts is set to 1 */
356   uart->connection.State &= ~SERIAL_STATE_RTS;
357   serial_connection_out(device->machine(), &uart->connection);
358
359   transmit_register_reset(&uart->transmit_reg);
360   receive_register_reset(&uart->receive_reg);
361   /* expecting mode byte */
362   uart->flags |= MSM8251_EXPECTING_MODE;
363   /* not expecting a sync byte */
364   uart->flags &= ~MSM8251_EXPECTING_SYNC_BYTE;
365
366   /* no character to read by cpu */
367   /* transmitter is ready and is empty */
368   uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
369   uart->mode_byte = 0;
370   uart->command = 0;
371
372   /* update tx empty pin output */
373   msm8251_update_tx_empty(device);
374   /* update rx ready pin output */
375   msm8251_update_rx_ready(device);
376   /* update tx ready pin output */
377   msm8251_update_tx_ready(device);
378}
379
380
381
382/*-------------------------------------------------
383    WRITE8_DEVICE_HANDLER(msm8251_control_w)
384-------------------------------------------------*/
385
386WRITE8_DEVICE_HANDLER(msm8251_control_w)
387{
388   msm8251_t *uart = get_token(device);
389
390   if (uart->flags & MSM8251_EXPECTING_MODE)
391   {
392      if (uart->flags & MSM8251_EXPECTING_SYNC_BYTE)
393      {
394         LOG(("MSM8251: Sync byte\n"));
395
396         LOG(("Sync byte: %02x\n", data));
397         /* store sync byte written */
398         uart->sync_bytes[uart->sync_byte_offset] = data;
399         uart->sync_byte_offset++;
400
401         if (uart->sync_byte_offset == uart->sync_byte_count)
402         {
403            /* finished transfering sync bytes, now expecting command */
404            uart->flags &= ~(MSM8251_EXPECTING_MODE | MSM8251_EXPECTING_SYNC_BYTE);
405            uart->sync_byte_offset = 0;
406         //  uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
407         }
408      }
409      else
410      {
411         LOG(("MSM8251: Mode byte\n"));
412
413         uart->mode_byte = data;
414
415         /* Synchronous or Asynchronous? */
416         if ((data & 0x03)!=0)
417         {
418            /*  Asynchronous
419
420                    bit 7,6: stop bit length
421                        0 = inhibit
422                        1 = 1 bit
423                        2 = 1.5 bits
424                        3 = 2 bits
425                    bit 5: parity type
426                        0 = parity odd
427                        1 = parity even
428                    bit 4: parity test enable
429                        0 = disable
430                        1 = enable
431                    bit 3,2: character length
432                        0 = 5 bits
433                        1 = 6 bits
434                        2 = 7 bits
435                        3 = 8 bits
436                    bit 1,0: baud rate factor
437                        0 = defines command byte for synchronous or asynchronous
438                        1 = x1
439                        2 = x16
440                        3 = x64
441                */
442
443            LOG(("MSM8251: Asynchronous operation\n"));
444
445            LOG(("Character length: %d\n", (((data>>2) & 0x03)+5)));
446
447            if (data & (1<<4))
448            {
449               LOG(("enable parity checking\n"));
450            }
451            else
452            {
453               LOG(("parity check disabled\n"));
454            }
455
456            if (data & (1<<5))
457            {
458               LOG(("even parity\n"));
459            }
460            else
461            {
462               LOG(("odd parity\n"));
463            }
464
465            {
466               UINT8 stop_bit_length;
467
468               stop_bit_length = (data>>6) & 0x03;
469
470               switch (stop_bit_length)
471               {
472                  case 0:
473                  {
474                     /* inhibit */
475                     LOG(("stop bit: inhibit\n"));
476                  }
477                  break;
478
479                  case 1:
480                  {
481                     /* 1 */
482                     LOG(("stop bit: 1 bit\n"));
483                  }
484                  break;
485
486                  case 2:
487                  {
488                     /* 1.5 */
489                     LOG(("stop bit: 1.5 bits\n"));
490                  }
491                  break;
492
493                  case 3:
494                  {
495                     /* 2 */
496                     LOG(("stop bit: 2 bits\n"));
497                  }
498                  break;
499               }
500            }
501
502            uart->form.word_length = ((data>>2) & 0x03)+5;
503            uart->form.parity = SERIAL_PARITY_NONE;
504            switch ((data>>6) & 0x03)
505            {
506               case 0:
507               case 1:
508                  uart->form.stop_bit_count =  1;
509                  break;
510               case 2:
511               case 3:
512                  uart->form.stop_bit_count =  2;
513                  break;
514            }
515            receive_register_setup(&uart->receive_reg, &uart->form);
516
517
518#if 0
519            /* data bits */
520            uart->receive_char_length = (((data>>2) & 0x03)+5);
521
522            if (data & (1<<4))
523            {
524               /* parity */
525               uart->receive_char_length++;
526            }
527
528            /* stop bits */
529            uart->receive_char_length++;
530
531            uart->receive_flags &=~MSM8251_TRANSFER_RECEIVE_SYNCHRONISED;
532            uart->receive_flags |= MSM8251_TRANSFER_RECEIVE_WAITING_FOR_START_BIT;
533#endif
534            /* not expecting mode byte now */
535            uart->flags &= ~MSM8251_EXPECTING_MODE;
536//              uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
537         }
538         else
539         {
540            /*  bit 7: Number of sync characters
541                        0 = 1 character
542                        1 = 2 character
543                    bit 6: Synchronous mode
544                        0 = Internal synchronisation
545                        1 = External synchronisation
546                    bit 5: parity type
547                        0 = parity odd
548                        1 = parity even
549                    bit 4: parity test enable
550                        0 = disable
551                        1 = enable
552                    bit 3,2: character length
553                        0 = 5 bits
554                        1 = 6 bits
555                        2 = 7 bits
556                        3 = 8 bits
557                    bit 1,0 = 0
558                */
559            LOG(("MSM8251: Synchronous operation\n"));
560
561            /* setup for sync byte(s) */
562            uart->flags |= MSM8251_EXPECTING_SYNC_BYTE;
563            uart->sync_byte_offset = 0;
564            if (data & 0x07)
565            {
566               uart->sync_byte_count = 1;
567            }
568            else
569            {
570               uart->sync_byte_count = 2;
571            }
572
573         }
574      }
575   }
576   else
577   {
578      /* command */
579      LOG(("MSM8251: Command byte\n"));
580
581      uart->command = data;
582
583      LOG(("Command byte: %02x\n", data));
584
585      if (data & (1<<7))
586      {
587         LOG(("hunt mode\n"));
588      }
589
590      if (data & (1<<5))
591      {
592         LOG(("/rts set to 0\n"));
593      }
594      else
595      {
596         LOG(("/rts set to 1\n"));
597      }
598
599      if (data & (1<<2))
600      {
601         LOG(("receive enable\n"));
602      }
603      else
604      {
605         LOG(("receive disable\n"));
606      }
607
608      if (data & (1<<1))
609      {
610         LOG(("/dtr set to 0\n"));
611      }
612      else
613      {
614         LOG(("/dtr set to 1\n"));
615      }
616
617      if (data & (1<<0))
618      {
619         LOG(("transmit enable\n"));
620      }
621      else
622      {
623         LOG(("transmit disable\n"));
624      }
625
626
627      /*  bit 7:
628                0 = normal operation
629                1 = hunt mode
630            bit 6:
631                0 = normal operation
632                1 = internal reset
633            bit 5:
634                0 = /RTS set to 1
635                1 = /RTS set to 0
636            bit 4:
637                0 = normal operation
638                1 = reset error flag
639            bit 3:
640                0 = normal operation
641                1 = send break character
642            bit 2:
643                0 = receive disable
644                1 = receive enable
645            bit 1:
646                0 = /DTR set to 1
647                1 = /DTR set to 0
648            bit 0:
649                0 = transmit disable
650                1 = transmit enable
651        */
652
653      uart->connection.State &=~SERIAL_STATE_RTS;
654      if (data & (1<<5))
655      {
656         /* rts set to 0 */
657         uart->connection.State |= SERIAL_STATE_RTS;
658      }
659
660      uart->connection.State &=~SERIAL_STATE_DTR;
661      if (data & (1<<1))
662      {
663         uart->connection.State |= SERIAL_STATE_DTR;
664      }
665
666      if ((data & (1<<0))==0)
667      {
668         /* held in high state when transmit disable */
669         set_out_data_bit(uart->connection.State,1);
670      }
671
672
673      /* refresh outputs */
674      serial_connection_out(device->machine(), &uart->connection);
675
676      if (data & (1<<4))
677      {
678         uart->status &= ~(MSM8251_STATUS_PARITY_ERROR | MSM8251_STATUS_OVERRUN_ERROR | MSM8251_STATUS_FRAMING_ERROR);
679      }
680
681      if (data & (1<<6))
682      {
683         device->reset();
684      }
685
686      msm8251_update_rx_ready(device);
687      msm8251_update_tx_ready(device);
688
689   }
690}
691
692
693
694/*-------------------------------------------------
695    READ8_DEVICE_HANDLER(msm8251_status_r)
696-------------------------------------------------*/
697
698READ8_DEVICE_HANDLER(msm8251_status_r)
699{
700   msm8251_t *uart = get_token(device);
701
702   LOG(("status: %02x\n", uart->status));
703   return uart->status;
704}
705
706
707
708/*-------------------------------------------------
709    WRITE8_DEVICE_HANDLER(msm8251_data_w)
710-------------------------------------------------*/
711
712WRITE8_DEVICE_HANDLER(msm8251_data_w)
713{
714   msm8251_t *uart = get_token(device);
715
716   uart->data = data;
717
718   logerror("write data: %02x\n",data);
719
720   /* writing clears */
721   uart->status &=~MSM8251_STATUS_TX_READY;
722
723   /* if transmitter is active, then tx empty will be signalled */
724
725   msm8251_update_tx_ready(device);
726}
727
728
729
730/*-------------------------------------------------
731    msm8251_receive_character - called when last
732    bit of data has been received
733-------------------------------------------------*/
734
735void msm8251_receive_character(device_t *device, UINT8 ch)
736{
737   msm8251_t *uart = get_token(device);
738
739   logerror("msm8251 receive char: %02x\n",ch);
740
741   uart->data = ch;
742
743   /* char has not been read and another has arrived! */
744   if (uart->status & MSM8251_STATUS_RX_READY)
745   {
746      uart->status |= MSM8251_STATUS_OVERRUN_ERROR;
747   }
748   uart->status |= MSM8251_STATUS_RX_READY;
749
750   msm8251_update_rx_ready(device);
751}
752
753
754
755/*-------------------------------------------------
756    READ8_DEVICE_HANDLER(msm8251_data_r) - read data
757-------------------------------------------------*/
758
759READ8_DEVICE_HANDLER(msm8251_data_r)
760{
761   msm8251_t *uart = get_token(device);
762
763   logerror("read data: %02x, STATUS=%02x\n",uart->data,uart->status);
764   /* reading clears */
765   uart->status &= ~MSM8251_STATUS_RX_READY;
766
767   msm8251_update_rx_ready(device);
768   return uart->data;
769}
770
771
772
773/*-------------------------------------------------
774    msm8251_connect_to_serial_device - initialise
775    transfer using serial device - set the callback
776    which will be called when serial device has
777    updated it's state
778-------------------------------------------------*/
779
780void msm8251_connect_to_serial_device(device_t *device, device_t *image)
781{
782   msm8251_t *uart = get_token(device);
783   serial_device_connect(image, &uart->connection);
784}
785
786
787
788/*-------------------------------------------------
789    msm8251_connect
790-------------------------------------------------*/
791
792void msm8251_connect(device_t *device, serial_connection *other_connection)
793{
794   msm8251_t *uart = get_token(device);
795   serial_connection_link(device->machine(), &uart->connection, other_connection);
796}
797
798
799/*-------------------------------------------------
800    DEVICE_GET_INFO( msm8251 )
801-------------------------------------------------*/
802
803DEVICE_GET_INFO( msm8251 )
804{
805   switch (state)
806   {
807      /* --- the following bits of info are returned as 64-bit signed integers --- */
808      case DEVINFO_INT_TOKEN_BYTES:               info->i = sizeof(msm8251_t);            break;
809      case DEVINFO_INT_INLINE_CONFIG_BYTES:         info->i = 0;                        break;
810
811      /* --- the following bits of info are returned as pointers to data or functions --- */
812      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(msm8251);   break;
813      case DEVINFO_FCT_STOP:                     /* Nothing */                        break;
814      case DEVINFO_FCT_RESET:                     info->reset = DEVICE_RESET_NAME(msm8251);   break;
815
816      /* --- the following bits of info are returned as NULL-terminated strings --- */
817      case DEVINFO_STR_NAME:                     strcpy(info->s, "Intel 8251 UART");            break;
818      case DEVINFO_STR_FAMILY:                  strcpy(info->s, "Intel 8251 UART");            break;
819      case DEVINFO_STR_VERSION:                  strcpy(info->s, "1.0");                     break;
820      case DEVINFO_STR_SOURCE_FILE:               strcpy(info->s, __FILE__);                     break;
821      case DEVINFO_STR_CREDITS:                  /* Nothing */                        break;
822   }
823}
824
825DEFINE_LEGACY_DEVICE(MSM8251, msm8251);
src/emu/machine/msm8251.h
r0r11451
1/*********************************************************************
2
3    msm8251.h
4
5    MSM/Intel 8251 Universal Synchronous/Asynchronous Receiver Transmitter code
6
7*********************************************************************/
8
9#ifndef __MSM8251_H__
10#define __MSM8251_H__
11
12#include "machine/serial.h"
13
14
15/***************************************************************************
16    CONSTANTS
17***************************************************************************/
18
19DECLARE_LEGACY_DEVICE(MSM8251, msm8251);
20
21#define MSM8251_EXPECTING_MODE 0x01
22#define MSM8251_EXPECTING_SYNC_BYTE 0x02
23
24#define MSM8251_STATUS_FRAMING_ERROR 0x020
25#define MSM8251_STATUS_OVERRUN_ERROR 0x010
26#define MSM8251_STATUS_PARITY_ERROR 0x08
27#define MSM8251_STATUS_TX_EMPTY      0x04
28#define MSM8251_STATUS_RX_READY   0x02
29#define MSM8251_STATUS_TX_READY   0x01
30
31#define MCFG_MSM8251_ADD(_tag, _intrf) \
32   MCFG_DEVICE_ADD(_tag, MSM8251, 0) \
33   MCFG_DEVICE_CONFIG(_intrf)
34
35#define MCFG_MSM8251_REMOVE(_tag) \
36   MCFG_DEVICE_REMOVE(_tag)
37
38
39/***************************************************************************
40    TYPE DEFINITIONS
41***************************************************************************/
42
43typedef struct _msm8251_interface msm8251_interface;
44struct _msm8251_interface
45{
46   devcb_read_line      in_rxd_func;
47   devcb_write_line   out_txd_func;
48   devcb_read_line      in_dsr_func;
49   devcb_write_line   out_dtr_func;
50   devcb_write_line   out_rts_func;
51   devcb_write_line   out_rxrdy_func;
52   devcb_write_line   out_txrdy_func;
53   devcb_write_line   out_txempty_func;
54   devcb_write_line   out_syndet_func;
55};
56
57
58/***************************************************************************
59    PROTOTYPES
60***************************************************************************/
61
62extern const msm8251_interface default_msm8251_interface;
63
64/* read data register */
65READ8_DEVICE_HANDLER(msm8251_data_r);
66
67/* read status register */
68READ8_DEVICE_HANDLER(msm8251_status_r);
69
70/* write data register */
71WRITE8_DEVICE_HANDLER(msm8251_data_w);
72
73/* write control word */
74WRITE8_DEVICE_HANDLER(msm8251_control_w);
75
76/* The 8251 has seperate transmit and receive clocks */
77/* use these two functions to update the msm8251 for each clock */
78/* on NC100 system, the clocks are the same */
79void msm8251_transmit_clock(device_t *device);
80void msm8251_receive_clock(device_t *device);
81
82/* connecting to serial output */
83void msm8251_connect_to_serial_device(device_t *device, device_t *image);
84void msm8251_connect(device_t *device, serial_connection *other_connection);
85
86void msm8251_receive_character(device_t *device, UINT8 ch);
87
88#endif /* __MSM8251_H__ */
src/mess/hashfile.c
r11450r11451
1/*********************************************************************
2
3    hashfile.c
4
5    Code for parsing hash info (*.hsi) files
6
7*********************************************************************/
8
9#include "hashfile.h"
10#include "pool.h"
11#include "expat.h"
12#include "emuopts.h"
13#include "hash.h"
14
15
16/***************************************************************************
17    TYPE DEFINITIONS
18***************************************************************************/
19
20typedef struct _hash_info hash_info;
21struct _hash_info
22{
23   hash_collection *hashes;
24   const char *extrainfo;
25};
26
27typedef struct _hash_file hash_file;
28
29typedef void (*hashfile_error_func)(const char *message);
30
31
32
33/***************************************************************************
34    FUNCTION PROTOTYPES
35***************************************************************************/
36
37/* opens a hash file; if is_preload is non-zero, the entire file is preloaded */
38hash_file *hashfile_open(emu_options &options, const char *sysname, int is_preload, hashfile_error_func error_proc);
39
40/* closes a hash file and associated resources */
41void hashfile_close(hash_file *hashfile);
42
43/* looks up information in a hash file */
44const hash_info *hashfile_lookup(hash_file *hashfile, const hash_collection *hashes);
45
46/***************************************************************************
47    TYPE DEFINITIONS
48***************************************************************************/
49
50struct _hash_file
51{
52   emu_file *file;
53   object_pool *pool;
54   astring functions[IO_COUNT];
55
56   hash_info **preloaded_hashes;
57   int preloaded_hash_count;
58
59   void (*error_proc)(const char *message);
60};
61
62
63
64enum hash_parse_position
65{
66   HASH_POS_ROOT,
67   HASH_POS_MAIN,
68   HASH_POS_HASH
69};
70
71
72
73struct hash_parse_state
74{
75   XML_Parser parser;
76   hash_file *hashfile;
77   int done;
78
79   int (*selector_proc)(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes);
80   void (*use_proc)(hash_file *hashfile, void *param, hash_info *hi);
81   void (*error_proc)(const char *message);
82   void *param;
83
84   enum hash_parse_position pos;
85   char **text_dest;
86   hash_info *hi;
87};
88
89
90
91/***************************************************************************
92    PROTOTYPES
93***************************************************************************/
94
95static void *expat_malloc(size_t size);
96static void *expat_realloc(void *ptr, size_t size);
97static void expat_free(void *ptr);
98
99
100
101/***************************************************************************
102    CORE IMPLEMENTATION
103***************************************************************************/
104
105/*-------------------------------------------------
106    parse_error
107-------------------------------------------------*/
108
109static void ATTR_PRINTF(2,3) parse_error(struct hash_parse_state *state, const char *fmt, ...)
110{
111   char buf[256];
112   va_list va;
113
114   if (state->error_proc)
115   {
116      va_start(va, fmt);
117      vsnprintf(buf, ARRAY_LENGTH(buf), fmt, va);
118      va_end(va);
119      (*state->error_proc)(buf);
120   }
121}
122
123
124
125/*-------------------------------------------------
126    unknown_tag
127-------------------------------------------------*/
128
129static void unknown_tag(struct hash_parse_state *state, const char *tagname)
130{
131   parse_error(state, "[%lu:%lu]: Unknown tag: %s\n",
132      XML_GetCurrentLineNumber(state->parser),
133      XML_GetCurrentColumnNumber(state->parser),
134      tagname);
135}
136
137
138
139/*-------------------------------------------------
140    unknown_attribute
141-------------------------------------------------*/
142
143static void unknown_attribute(struct hash_parse_state *state, const char *attrname)
144{
145   parse_error(state, "[%lu:%lu]: Unknown attribute: %s\n",
146      XML_GetCurrentLineNumber(state->parser),
147      XML_GetCurrentColumnNumber(state->parser),
148      attrname);
149}
150
151
152
153/*-------------------------------------------------
154    unknown_attribute_value
155-------------------------------------------------*/
156
157static void unknown_attribute_value(struct hash_parse_state *state,
158   const char *attrname, const char *attrvalue)
159{
160   parse_error(state, "[%lu:%lu]: Unknown attribute value: %s\n",
161      XML_GetCurrentLineNumber(state->parser),
162      XML_GetCurrentColumnNumber(state->parser),
163      attrvalue);
164}
165
166
167
168/*-------------------------------------------------
169    start_handler
170-------------------------------------------------*/
171
172static void start_handler(void *data, const char *tagname, const char **attributes)
173{
174   struct hash_parse_state *state = (struct hash_parse_state *) data;
175   const char *name;
176   hash_info *hi;
177   char **text_dest;
178   hash_collection hashes;
179   astring all_functions;
180   char functions;
181   iodevice_t device;
182   int i;
183
184   switch(state->pos)
185   {
186      case HASH_POS_ROOT:
187         if (!strcmp(tagname, "hashfile"))
188         {
189         }
190         else
191         {
192            unknown_tag(state, tagname);
193         }
194         break;
195
196      case HASH_POS_MAIN:
197         if (!strcmp(tagname, "hash"))
198         {
199            // we are now examining a hash tag
200            name = NULL;
201            device = IO_COUNT;
202
203            while(attributes[0])
204            {
205               functions = 0;
206               if (!strcmp(attributes[0], "name"))
207               {
208                  /* name attribute */
209                  name = attributes[1];
210               }
211               else if (!strcmp(attributes[0], "crc32"))
212               {
213                  /* crc32 attribute */
214                  functions = hash_collection::HASH_CRC;
215               }
216               else if (!strcmp(attributes[0], "md5"))
217               {
218                  /* md5 attribute */
219                  functions = hash_collection::HASH_MD5;
220               }
221               else if (!strcmp(attributes[0], "sha1"))
222               {
223                  /* sha1 attribute */
224                  functions = hash_collection::HASH_SHA1;
225               }
226               else if (!strcmp(attributes[0], "type"))
227               {
228                  /* type attribute */
229                  i = 0;//device_typeid(attributes[1]);
230                  if (i < 0)
231                     unknown_attribute_value(state, attributes[0], attributes[1]);
232                  else
233                     device = (iodevice_t) i;
234               }
235               else
236               {
237                  /* unknown attribute */
238                  unknown_attribute(state, attributes[0]);
239               }
240
241               if (functions)
242               {
243                  hashes.add_from_string(functions, attributes[1], strlen(attributes[1]));
244                  all_functions.cat(functions);
245               }
246
247               attributes += 2;
248            }
249
250            /* do we use this hash? */
251            if (!state->selector_proc || state->selector_proc(state->hashfile, state->param, name, &hashes))
252            {
253               hi = (hash_info*)pool_malloc_lib(state->hashfile->pool, sizeof(hash_info));
254               if (!hi)
255                  return;
256               memset(hi, 0, sizeof(*hi));
257
258               hi->hashes = &hashes;
259               state->hi = hi;
260            }
261         }
262         else
263         {
264            unknown_tag(state, tagname);
265         }
266         break;
267
268      case HASH_POS_HASH:
269         text_dest = NULL;
270
271         if (!strcmp(tagname, "year")) {
272         }
273         else if (!strcmp(tagname, "manufacturer")){
274         }
275         else if (!strcmp(tagname, "status")){
276         }
277         else if (!strcmp(tagname, "pcb")){
278         }
279         else if (!strcmp(tagname, "extrainfo")) {
280            text_dest = (char **) &state->hi->extrainfo;
281         }
282         else
283            unknown_tag(state, tagname);
284
285         if (text_dest && state->hi)
286            state->text_dest = text_dest;
287         break;
288   }
289   state->pos = (hash_parse_position) (state->pos + 1);
290}
291
292
293
294/*-------------------------------------------------
295    end_handler
296-------------------------------------------------*/
297
298static void end_handler(void *data, const char *name)
299{
300   struct hash_parse_state *state = (struct hash_parse_state *) data;
301   state->text_dest = NULL;
302
303   state->pos = (hash_parse_position) (state->pos - 1);
304   switch(state->pos)
305   {
306      case HASH_POS_ROOT:
307      case HASH_POS_HASH:
308         break;
309
310      case HASH_POS_MAIN:
311         if (state->hi)
312         {
313            if (state->use_proc)
314               (*state->use_proc)(state->hashfile, state->param, state->hi);
315            state->hi = NULL;
316         }
317         break;
318   }
319}
320
321
322
323/*-------------------------------------------------
324    data_handler
325-------------------------------------------------*/
326
327static void data_handler(void *data, const XML_Char *s, int len)
328{
329   struct hash_parse_state *state = (struct hash_parse_state *) data;
330   int text_len;
331   char *text;
332
333   if (state->text_dest)
334   {
335      text = *state->text_dest;
336
337      text_len = text ? strlen(text) : 0;
338      text = (char*)pool_realloc_lib(state->hashfile->pool, text, text_len + len + 1);
339      if (!text)
340         return;
341
342      memcpy(&text[text_len], s, len);
343      text[text_len + len] = '\0';
344      *state->text_dest = text;
345   }
346}
347
348
349
350/*-------------------------------------------------
351    hashfile_parse
352-------------------------------------------------*/
353
354static void hashfile_parse(hash_file *hashfile,
355   int (*selector_proc)(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes),
356   void (*use_proc)(hash_file *hashfile, void *param, hash_info *hi),
357   void (*error_proc)(const char *message),
358   void *param)
359{
360   struct hash_parse_state state;
361   char buf[1024];
362   UINT32 len;
363   XML_Memory_Handling_Suite memcallbacks;
364
365   hashfile->file->seek(0, SEEK_SET);
366
367   memset(&state, 0, sizeof(state));
368   state.hashfile = hashfile;
369   state.selector_proc = selector_proc;
370   state.use_proc = use_proc;
371   state.error_proc = error_proc;
372   state.param = param;
373
374   /* create the XML parser */
375   memcallbacks.malloc_fcn = expat_malloc;
376   memcallbacks.realloc_fcn = expat_realloc;
377   memcallbacks.free_fcn = expat_free;
378   state.parser = XML_ParserCreate_MM(NULL, &memcallbacks, NULL);
379   if (!state.parser)
380      goto done;
381
382   XML_SetUserData(state.parser, &state);
383   XML_SetElementHandler(state.parser, start_handler, end_handler);
384   XML_SetCharacterDataHandler(state.parser, data_handler);
385
386   while(!state.done)
387   {
388      len = hashfile->file->read(buf, sizeof(buf));
389      state.done = hashfile->file->eof();
390      if (XML_Parse(state.parser, buf, len, state.done) == XML_STATUS_ERROR)
391      {
392         parse_error(&state, "[%lu:%lu]: %s\n",
393            XML_GetCurrentLineNumber(state.parser),
394            XML_GetCurrentColumnNumber(state.parser),
395            XML_ErrorString(XML_GetErrorCode(state.parser)));
396         goto done;
397      }
398   }
399
400done:
401   if (state.parser)
402      XML_ParserFree(state.parser);
403}
404
405
406
407/*-------------------------------------------------
408    preload_use_proc
409-------------------------------------------------*/
410
411static void preload_use_proc(hash_file *hashfile, void *param, hash_info *hi)
412{
413   hash_info **new_preloaded_hashes;
414
415   new_preloaded_hashes = (hash_info **)pool_realloc_lib(hashfile->pool, hashfile->preloaded_hashes,
416      (hashfile->preloaded_hash_count + 1) * sizeof(*new_preloaded_hashes));
417   if (!new_preloaded_hashes)
418      return;
419
420   hashfile->preloaded_hashes = new_preloaded_hashes;
421   hashfile->preloaded_hashes[hashfile->preloaded_hash_count++] = hi;
422}
423
424
425
426/*-------------------------------------------------
427    hashfile_open
428-------------------------------------------------*/
429
430hash_file *hashfile_open(emu_options &options, const char *sysname, int is_preload,
431   void (*error_proc)(const char *message))
432{
433   hash_file *hashfile = NULL;
434   object_pool *pool = NULL;
435   file_error filerr;
436
437   /* create a pool for this hash file */
438   pool = pool_alloc_lib(error_proc);
439   if (!pool)
440      goto error;
441
442   /* allocate space for this hash file */
443   hashfile = (hash_file *) pool_malloc_lib(pool, sizeof(*hashfile));
444   if (!hashfile)
445      goto error;
446
447   /* set up the hashfile structure */
448   memset(hashfile, 0, sizeof(*hashfile));
449   hashfile->pool = pool;
450   hashfile->error_proc = error_proc;
451
452   /* open a file */
453   hashfile->file = global_alloc(emu_file(options.hash_path(), OPEN_FLAG_READ));
454   filerr = hashfile->file->open(sysname, ".hsi");
455   if (filerr != FILERR_NONE)
456   {
457      global_free(hashfile->file);
458      hashfile->file = NULL;
459      goto error;
460   }
461
462   if (is_preload)
463      hashfile_parse(hashfile, NULL, preload_use_proc, hashfile->error_proc, NULL);
464
465   return hashfile;
466
467error:
468   if (hashfile != NULL)
469      hashfile_close(hashfile);
470   return NULL;
471}
472
473
474
475/*-------------------------------------------------
476    hashfile_close
477-------------------------------------------------*/
478
479void hashfile_close(hash_file *hashfile)
480{
481   global_free(hashfile->file);
482   pool_free_lib(hashfile->pool);
483}
484
485
486
487/*-------------------------------------------------
488    singular_selector_proc
489-------------------------------------------------*/
490
491struct hashlookup_params
492{
493   const hash_collection *hashes;
494   hash_info *hi;
495};
496
497static int singular_selector_proc(hash_file *hashfile, void *param, const char *name, const hash_collection *hashes)
498{
499   astring tempstr;
500   struct hashlookup_params *hlparams = (struct hashlookup_params *) param;
501   return (*hashes == *hlparams->hashes);
502}
503
504
505
506/*-------------------------------------------------
507    singular_use_proc
508-------------------------------------------------*/
509
510static void singular_use_proc(hash_file *hashfile, void *param, hash_info *hi)
511{
512   struct hashlookup_params *hlparams = (struct hashlookup_params *) param;
513   hlparams->hi = hi;
514}
515
516
517
518/*-------------------------------------------------
519    hashfile_lookup
520-------------------------------------------------*/
521
522const hash_info *hashfile_lookup(hash_file *hashfile, const hash_collection *hashes)
523{
524   struct hashlookup_params param;
525   int i;
526
527   param.hashes = hashes;
528   param.hi = NULL;
529
530   for (i = 0; i < hashfile->preloaded_hash_count; i++)
531   {
532      if (singular_selector_proc(hashfile, &param, NULL, hashfile->preloaded_hashes[i]->hashes))
533         return hashfile->preloaded_hashes[i];
534   }
535
536   hashfile_parse(hashfile, singular_selector_proc, singular_use_proc,
537      hashfile->error_proc, (void *) &param);
538   return param.hi;
539}
540
541const char *extra_info = NULL;
542
543const char *read_hash_config(device_image_interface &image, const char *sysname)
544{
545   hash_file *hashfile = NULL;
546   const hash_info *info = NULL;
547
548   /* open the hash file */
549   hashfile = hashfile_open(image.device().machine().options(), sysname, FALSE, NULL);
550   if (!hashfile)
551      return NULL;
552
553   /* look up this entry in the hash file */
554   info = hashfile_lookup(hashfile, &image.hash());
555
556   if (!info || !info->extrainfo)
557   {
558      hashfile_close(hashfile);
559      return NULL;
560   }
561
562   extra_info = auto_strdup(image.device().machine(),info->extrainfo);
563   if (!extra_info)
564   {
565      hashfile_close(hashfile);
566      return NULL;
567   }
568
569   /* copy the relevant entries */
570   hashfile_close(hashfile);
571
572   return extra_info;
573}
574
575const char *hashfile_extrainfo(device_image_interface &image)
576{
577   const char *rc;
578
579   /* now read the hash file */
580   image.crc();
581   extra_info = NULL;
582   int drv = driver_list::find(image.device().machine().system());
583   do
584   {
585      rc = read_hash_config(image,driver_list::driver(drv).name);
586      drv = driver_list::compatible_with(drv);
587   }
588   while(rc!=NULL && drv != -1);
589   return rc;
590}
591
592/***************************************************************************
593    EXPAT INTERFACES
594***************************************************************************/
595
596/*-------------------------------------------------
597    expat_malloc/expat_realloc/expat_free -
598    wrappers for memory allocation functions so
599    that they pass through out memory tracking
600    systems
601-------------------------------------------------*/
602
603static void *expat_malloc(size_t size)
604{
605   return global_alloc_array_clear(UINT8,size);
606}
607
608static void *expat_realloc(void *ptr, size_t size)
609{
610   if (ptr) global_free(ptr);
611   return global_alloc_array_clear(UINT8,size);
612}
613
614static void expat_free(void *ptr)
615{
616   global_free(ptr);
617}
src/mess/hashfile.h
r11450r11451
1/*********************************************************************
2
3    hashfile.h
4
5    Code for parsing hash info (*.hsi) files
6
7*********************************************************************/
8
9#ifndef __HASHFILE_H__
10#define __HASHFILE_H__
11
12#include "emu.h"
13
14
15const char *hashfile_extrainfo(device_image_interface &image);
16
17#endif /* __HASHFILE_H__ */
src/mess/messcore.mak
r11450r11451
3838MAME_AUDIO = $(MAMEOBJ)/audio
3939MAME_MACHINE = $(MAMEOBJ)/machine
4040MAME_DRIVERS = $(MAMEOBJ)/drivers
41MAME_FORMATS = $(MAMEOBJ)/formats
4142MAME_VIDEO = $(MAMEOBJ)/video
4243MAME_LAYOUT = $(MAMEOBJ)/layout
4344
r11450r11451
5657   $(EMU_VIDEO) \
5758   $(MAME_AUDIO) \
5859   $(MAME_DRIVERS) \
60   $(MAME_FORMATS) \
5961   $(MAME_LAYOUT) \
6062   $(MAME_MACHINE) \
6163   $(MAME_VIDEO) \
r11450r11451
7678#-------------------------------------------------
7779
7880LIBOCORE_NOMAIN = $(OBJ)/libocore_nomain.a
79
80EMUOBJS += \
81   $(MESSOBJ)/hashfile.o   \
82
83$(LIBEMU): $(EMUOBJS)
src/mess/machine/gdrom.c
r11450r11451
1/***************************************************************************
2
3 gdrom.c - Implementation of the Sega GD-ROM device
4
5***************************************************************************/
6
7#include "emu.h"
8#include "machine/scsidev.h"
9#include "cdrom.h"
10#include "sound/cdda.h"
11#include "imagedev/chd_cd.h"
12#include "gdrom.h"
13
14typedef struct
15{
16   UINT32 lba;
17   UINT32 blocks;
18   UINT32 last_lba;
19   UINT32 bytes_per_sector;
20   UINT32 num_subblocks;
21   UINT32 cur_subblock;
22   UINT32 play_err_flag;
23   UINT32 read_type;   // for command 0x30 only
24   UINT32 data_select;   // for command 0x30 only
25   cdrom_file *cdrom;
26   bool is_file;
27} SCSIGd;
28
29static const UINT8 GDROM_Cmd11_Reply[32] =
30{
31   0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x19, 0x00, 0x00, 0x08, 0x53, 0x45, 0x20, 0x20, 0x20, 0x20,
32   0x20, 0x20, 0x52, 0x65, 0x76, 0x20, 0x36, 0x2E, 0x34, 0x32, 0x39, 0x39, 0x30, 0x33, 0x31, 0x36
33};
34
35static void phys_frame_to_msf(int phys_frame, int *m, int *s, int *f)
36{
37   *m = phys_frame / (60*75);
38   phys_frame -= (*m * 60 * 75);
39   *s = phys_frame / 75;
40   *f = phys_frame % 75;
41}
42
43
44// scsicd_exec_command
45//
46// Execute a SCSI command.
47
48static int scsicd_exec_command( SCSIInstance *scsiInstance, UINT8 *statusCode )
49{
50   UINT8 *command;
51   int commandLength;
52   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
53
54   cdrom_file *cdrom = our_this->cdrom;
55   device_t *cdda;
56   int trk;
57
58   SCSIGetCommand( scsiInstance, &command, &commandLength );
59
60   switch ( command[0] )
61   {
62
63
64      case 0x03: // REQUEST SENSE
65         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
66         return SCSILengthFromUINT8( &command[ 4 ] );
67
68      case 0x11: // REQ_MODE
69         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
70         printf("REQ_MODE %02x %02x %02x %02x %02x %02x\n",
71            command[0], command[1],
72            command[2], command[3],
73            command[4], command[5]);
74//          if (SCSILengthFromUINT8( &command[ 4 ] ) < 32) return -1;
75         return 32; //SCSILengthFromUINT8( &command[ 4 ] );
76
77      case 0x12: // INQUIRY
78         logerror("GDROM: REQUEST SENSE\n");
79         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
80         return SCSILengthFromUINT8( &command[ 4 ] );
81
82      case 0x15: // MODE SELECT(6)
83         logerror("GDROM: MODE SELECT(6) length %x control %x\n", command[4], command[5]);
84         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAOUT );
85         return SCSILengthFromUINT8( &command[ 4 ] );
86
87      case 0x1a: // MODE SENSE(6)
88         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
89         return SCSILengthFromUINT8( &command[ 4 ] );
90
91      case 0x1b: // START STOP UNIT
92         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
93         if (cdda != NULL)
94         {
95            cdda_stop_audio(cdda);
96         }
97         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
98         return 0;
99
100      case 0x1e: // PREVENT ALLOW MEDIUM REMOVAL
101         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
102         return 0;
103
104      case 0x25: // READ CAPACITY
105         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
106         return 8;
107
108      case 0x28: // READ(10)
109
110         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
111         our_this->blocks = SCSILengthFromUINT16( &command[7] );
112
113         logerror("GDROM: READ(10) at LBA %x for %d blocks (%d bytes)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector);
114
115         if (our_this->num_subblocks > 1)
116         {
117            our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
118            our_this->lba /= our_this->num_subblocks;
119         }
120         else
121         {
122            our_this->cur_subblock = 0;
123         }
124
125         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
126         if (cdda != NULL)
127         {
128            cdda_stop_audio(cdda);
129         }
130
131         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
132         return our_this->blocks * our_this->bytes_per_sector;
133
134      case 0x30: // CD_READ
135         if (command[1] & 1)
136         {
137            fatalerror("GDROM: MSF mode used for CD_READ, unsupported");
138            return 0;
139         }
140         else
141         {
142            our_this->lba = (command[2]<<16 | command[3]<<8 | command[4]) - 150;
143            our_this->blocks = command[8]<<16 | command[9]<<8 | command[10];
144
145            our_this->read_type = (command[1] >> 1) & 7;
146            our_this->data_select = (command[1]>>4) & 0xf;
147
148            if (our_this->read_type != 2)   // mode 1
149            {
150               fatalerror("GDROM: Unhandled read_type %d", our_this->read_type);
151            }
152
153            if (our_this->data_select != 2)   // just sector data
154            {
155               fatalerror("GDROM: Unhandled data_select %d", our_this->data_select);
156            }
157
158            printf("GDROM: CD_READ at LBA %x for %d blocks (%d bytes, read type %d, data select %d)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector, our_this->read_type, our_this->data_select);
159
160            if (our_this->num_subblocks > 1)
161            {
162               our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
163               our_this->lba /= our_this->num_subblocks;
164            }
165            else
166            {
167               our_this->cur_subblock = 0;
168            }
169
170            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
171            if (cdda != NULL)
172            {
173               cdda_stop_audio(cdda);
174            }
175
176            SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
177            return our_this->blocks * our_this->bytes_per_sector;
178         }
179
180      case 0x42: // READ SUB-CHANNEL
181//                      logerror("GDROM: READ SUB-CHANNEL type %d\n", command[3]);
182         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
183         return SCSILengthFromUINT16( &command[ 7 ] );
184
185      case 0x43: // READ TOC
186      {
187         int start_trk = command[6];
188         int end_trk = cdrom_get_last_track(cdrom);
189         int length;
190         int allocation_length = SCSILengthFromUINT16( &command[ 7 ] );
191
192         if( start_trk == 0 )
193         {
194            start_trk = 1;
195         }
196         if( start_trk == 0xaa )
197         {
198            end_trk = start_trk;
199         }
200
201         length = 4 + ( 8 * ( ( end_trk - start_trk ) + 1 ) );
202         if( length > allocation_length )
203         {
204            length = allocation_length;
205         }
206         else if( length < 4 )
207         {
208            length = 4;
209         }
210
211         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
212         if (cdda != NULL)
213         {
214            cdda_stop_audio(cdda);
215         }
216
217         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
218         return length;
219      }
220      case 0x45: // PLAY AUDIO(10)
221         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
222         our_this->blocks = SCSILengthFromUINT16( &command[7] );
223
224         // special cases: lba of 0 means MSF of 00:02:00
225         if (our_this->lba == 0)
226         {
227            our_this->lba = 150;
228         }
229         else if (our_this->lba == 0xffffffff)
230         {
231            logerror("GDROM: play audio from current not implemented!\n");
232         }
233
234         logerror("GDROM: PLAY AUDIO(10) at LBA %x for %x blocks\n", our_this->lba, our_this->blocks);
235
236         trk = cdrom_get_track(cdrom, our_this->lba);
237
238         if (cdrom_get_track_type(cdrom, trk) == CD_TRACK_AUDIO)
239         {
240            our_this->play_err_flag = 0;
241            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
242            if (cdda != NULL)
243               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
244         }
245         else
246         {
247            logerror("GDROM: track is NOT audio!\n");
248            our_this->play_err_flag = 1;
249         }
250
251         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
252         return 0;
253
254      case 0x48: // PLAY AUDIO TRACK/INDEX
255         // be careful: tracks here are zero-based, but the SCSI command
256         // uses the real CD track number which is 1-based!
257         our_this->lba = cdrom_get_track_start(cdrom, command[4]-1);
258         our_this->blocks = cdrom_get_track_start(cdrom, command[7]-1) - our_this->lba;
259         if (command[4] > command[7])
260         {
261            our_this->blocks = 0;
262         }
263
264         if (command[4] == command[7])
265         {
266            our_this->blocks = cdrom_get_track_start(cdrom, command[4]) - our_this->lba;
267         }
268
269         if (our_this->blocks && cdrom)
270         {
271            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
272            if (cdda != NULL)
273               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
274         }
275
276         logerror("GDROM: PLAY AUDIO T/I: strk %d idx %d etrk %d idx %d frames %d\n", command[4], command[5], command[7], command[8], our_this->blocks);
277         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
278         return 0;
279
280      case 0x4b: // PAUSE/RESUME
281         if (cdrom)
282         {
283            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
284            if (cdda != NULL)
285               cdda_pause_audio(cdda, (command[8] & 0x01) ^ 0x01);
286         }
287
288         logerror("GDROM: PAUSE/RESUME: %s\n", command[8]&1 ? "RESUME" : "PAUSE");
289         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
290         return 0;
291
292      case 0x55: // MODE SELECT(10)
293         logerror("GDROM: MODE SELECT length %x control %x\n", command[7]<<8 | command[8], command[1]);
294         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAOUT );
295         return SCSILengthFromUINT16( &command[ 7 ] );
296
297      case 0x5a: // MODE SENSE(10)
298         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
299         return SCSILengthFromUINT16( &command[ 7 ] );
300
301      case 0xa5: // PLAY AUDIO(12)
302         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
303         our_this->blocks = command[6]<<24 | command[7]<<16 | command[8]<<8 | command[9];
304
305         // special cases: lba of 0 means MSF of 00:02:00
306         if (our_this->lba == 0)
307         {
308            our_this->lba = 150;
309         }
310         else if (our_this->lba == 0xffffffff)
311         {
312            logerror("GDROM: play audio from current not implemented!\n");
313         }
314
315         logerror("GDROM: PLAY AUDIO(12) at LBA %x for %x blocks\n", our_this->lba, our_this->blocks);
316
317         trk = cdrom_get_track(cdrom, our_this->lba);
318
319         if (cdrom_get_track_type(cdrom, trk) == CD_TRACK_AUDIO)
320         {
321            our_this->play_err_flag = 0;
322            cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
323            if (cdda != NULL)
324               cdda_start_audio(cdda, our_this->lba, our_this->blocks);
325         }
326         else
327         {
328            logerror("GDROM: track is NOT audio!\n");
329            our_this->play_err_flag = 1;
330         }
331         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
332         return 0;
333
334      case 0xa8: // READ(12)
335         our_this->lba = command[2]<<24 | command[3]<<16 | command[4]<<8 | command[5];
336         our_this->blocks = command[7]<<16 | command[8]<<8 | command[9];
337
338         logerror("GDROM: READ(12) at LBA %x for %x blocks (%x bytes)\n", our_this->lba, our_this->blocks, our_this->blocks * our_this->bytes_per_sector);
339
340         if (our_this->num_subblocks > 1)
341         {
342            our_this->cur_subblock = our_this->lba % our_this->num_subblocks;
343            our_this->lba /= our_this->num_subblocks;
344         }
345         else
346         {
347            our_this->cur_subblock = 0;
348         }
349
350         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
351         if (cdda != NULL)
352         {
353            cdda_stop_audio(cdda);
354         }
355
356         SCSISetPhase( scsiInstance, SCSI_PHASE_DATAIN );
357         return our_this->blocks * our_this->bytes_per_sector;
358
359      case 0xbb: // SET CD SPEED
360         logerror("GDROM: SET CD SPEED to %d kbytes/sec.\n", command[2]<<8 | command[3]);
361         SCSISetPhase( scsiInstance, SCSI_PHASE_STATUS );
362         return 0;
363
364      default:
365         return SCSIBase( &SCSIClassGDROM, SCSIOP_EXEC_COMMAND, scsiInstance, 0, NULL );
366   }
367}
368
369// scsicd_read_data
370//
371// Read data from the device resulting from the execution of a command
372
373static void scsicd_read_data( SCSIInstance *scsiInstance, UINT8 *data, int dataLength )
374{
375   UINT8 *command;
376   int commandLength;
377   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
378
379   int i;
380   UINT32 last_phys_frame;
381   cdrom_file *cdrom = our_this->cdrom;
382   UINT32 temp;
383   UINT8 tmp_buffer[2048];
384   device_t *cdda;
385
386   SCSIGetCommand( scsiInstance, &command, &commandLength );
387
388   switch ( command[0] )
389   {
390      case 0x03: // REQUEST SENSE
391         logerror("GDROM: Reading REQUEST SENSE data\n");
392
393         memset( data, 0, dataLength );
394
395         data[0] = 0x71;   // deferred error
396
397         cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
398         if (cdda != NULL && cdda_audio_active(cdda))
399         {
400            data[12] = 0x00;
401            data[13] = 0x11;   // AUDIO PLAY OPERATION IN PROGRESS
402         }
403         else if (our_this->play_err_flag)
404         {
405            our_this->play_err_flag = 0;
406            data[12] = 0x64;   // ILLEGAL MODE FOR THIS TRACK
407            data[13] = 0x00;
408         }
409         // (else 00/00 means no error to report)
410         break;
411
412      case 0x11: // REQ_MODE
413         printf("REQ_MODE: dataLength %d\n", dataLength);
414         memcpy(data, &GDROM_Cmd11_Reply[0], (dataLength >= 32) ? 32 : dataLength);
415         break;
416
417      case 0x12: // INQUIRY
418         memset( data, 0, dataLength );
419         data[0] = 0x05; // device is present, device is CD/DVD (MMC-3)
420         data[1] = 0x80; // media is removable
421         data[2] = 0x05; // device complies with SPC-3 standard
422         data[3] = 0x02; // response data format = SPC-3 standard
423         // some Konami games freak out if this isn't "Sony", so we'll lie
424         // this is the actual drive on my Nagano '98 board
425         strcpy((char *)&data[8], "Sony");
426         strcpy((char *)&data[16], "CDU-76S");
427         strcpy((char *)&data[32], "1.0");
428         break;
429
430      case 0x25: // READ CAPACITY
431         logerror("GDROM: READ CAPACITY\n");
432
433         temp = cdrom_get_track_start(cdrom, 0xaa);
434         temp--;   // return the last used block on the disc
435
436         data[0] = (temp>>24) & 0xff;
437         data[1] = (temp>>16) & 0xff;
438         data[2] = (temp>>8) & 0xff;
439         data[3] = (temp & 0xff);
440         data[4] = 0;
441         data[5] = 0;
442         data[6] = (our_this->bytes_per_sector>>8)&0xff;
443         data[7] = (our_this->bytes_per_sector & 0xff);
444         break;
445
446      case 0x28: // READ(10)
447      case 0xa8: // READ(12)
448         logerror("GDROM: read %x dataLength, \n", dataLength);
449         if ((our_this->cdrom) && (our_this->blocks))
450         {
451            while (dataLength > 0)
452            {
453               if (!cdrom_read_data(our_this->cdrom, our_this->lba, tmp_buffer, CD_TRACK_MODE1))
454               {
455                  logerror("GDROM: CD read error!\n");
456               }
457
458               logerror("True LBA: %d, buffer half: %d\n", our_this->lba, our_this->cur_subblock * our_this->bytes_per_sector);
459
460               memcpy(data, &tmp_buffer[our_this->cur_subblock * our_this->bytes_per_sector], our_this->bytes_per_sector);
461
462               our_this->cur_subblock++;
463               if (our_this->cur_subblock >= our_this->num_subblocks)
464               {
465                  our_this->cur_subblock = 0;
466
467                  our_this->lba++;
468                  our_this->blocks--;
469               }
470
471               our_this->last_lba = our_this->lba;
472               dataLength -= our_this->bytes_per_sector;
473               data += our_this->bytes_per_sector;
474            }
475         }
476         break;
477
478      case 0x30: // CD_READ
479         logerror("GDROM: read %x dataLength, \n", dataLength);
480         if ((our_this->cdrom) && (our_this->blocks))
481         {
482            while (dataLength > 0)
483            {
484               if (!cdrom_read_data(our_this->cdrom, our_this->lba, tmp_buffer, CD_TRACK_MODE1))
485               {
486                  logerror("GDROM: CD read error!\n");
487               }
488
489               logerror("True LBA: %d, buffer half: %d\n", our_this->lba, our_this->cur_subblock * our_this->bytes_per_sector);
490
491               memcpy(data, &tmp_buffer[our_this->cur_subblock * our_this->bytes_per_sector], our_this->bytes_per_sector);
492
493               our_this->cur_subblock++;
494               if (our_this->cur_subblock >= our_this->num_subblocks)
495               {
496                  our_this->cur_subblock = 0;
497
498                  our_this->lba++;
499                  our_this->blocks--;
500               }
501
502               our_this->last_lba = our_this->lba;
503               dataLength -= our_this->bytes_per_sector;
504               data += our_this->bytes_per_sector;
505            }
506         }
507
508      case 0x42: // READ SUB-CHANNEL
509         switch (command[3])
510         {
511            case 1:   // return current position
512            {
513               int audio_active;
514               int msf;
515
516               if (!cdrom)
517               {
518                  return;
519               }
520
521               logerror("GDROM: READ SUB-CHANNEL Time = %x, SUBQ = %x\n", command[1], command[2]);
522
523               msf = command[1] & 0x2;
524
525               cdda = cdda_from_cdrom(scsiInstance->machine(), cdrom);
526               audio_active = cdda != NULL && cdda_audio_active(cdda);
527               if (audio_active)
528               {
529                  if (cdda_audio_paused(cdda))
530                  {
531                     data[1] = 0x12;      // audio is paused
532                  }
533                  else
534                  {
535                     data[1] = 0x11;      // audio in progress
536                  }
537               }
538               else
539               {
540                  if (cdda != NULL && cdda_audio_ended(cdda))
541                  {
542                     data[1] = 0x13;   // ended successfully
543                  }
544                  else
545                  {
546//                          data[1] = 0x14;    // stopped due to error
547                     data[1] = 0x15;   // No current audio status to return
548                  }
549               }
550
551               // if audio is playing, get the latest LBA from the CDROM layer
552               if (audio_active)
553               {
554                  our_this->last_lba = cdda_get_audio_lba(cdda);
555               }
556               else
557               {
558                  our_this->last_lba = 0;
559               }
560
561               data[2] = 0;
562               data[3] = 12;      // data length
563               data[4] = 0x01;   // sub-channel format code
564               data[5] = 0x10 | (audio_active ? 0 : 4);
565               data[6] = cdrom_get_track(cdrom, our_this->last_lba) + 1;   // track
566               data[7] = 0;   // index
567
568               last_phys_frame = our_this->last_lba;
569
570               if (msf)
571               {
572                  int m,s,f;
573                  phys_frame_to_msf(last_phys_frame, &m, &s, &f);
574                  data[8] = 0;
575                  data[9] = m;
576                  data[10] = s;
577                  data[11] = f;
578               }
579               else
580               {
581                  data[8] = last_phys_frame>>24;
582                  data[9] = (last_phys_frame>>16)&0xff;
583                  data[10] = (last_phys_frame>>8)&0xff;
584                  data[11] = last_phys_frame&0xff;
585               }
586
587               last_phys_frame -= cdrom_get_track_start(cdrom, data[6] - 1);
588
589               if (msf)
590               {
591                  int m,s,f;
592                  phys_frame_to_msf(last_phys_frame, &m, &s, &f);
593                  data[12] = 0;
594                  data[13] = m;
595                  data[14] = s;
596                  data[15] = f;
597               }
598               else
599               {
600                  data[12] = last_phys_frame>>24;
601                  data[13] = (last_phys_frame>>16)&0xff;
602                  data[14] = (last_phys_frame>>8)&0xff;
603                  data[15] = last_phys_frame&0xff;
604               }
605               break;
606            }
607            default:
608               logerror("GDROM: Unknown subchannel type %d requested\n", command[3]);
609         }
610         break;
611
612      case 0x43: // READ TOC
613         /*
614                Track numbers are problematic here: 0 = lead-in, 0xaa = lead-out.
615                That makes sense in terms of how real-world CDs are referred to, but
616                our internal routines for tracks use "0" as track 1.  That probably
617                should be fixed...
618            */
619         logerror("GDROM: READ TOC, format = %d time=%d\n", command[2]&0xf,(command[1]>>1)&1);
620         switch (command[2] & 0x0f)
621         {
622            case 0:      // normal
623               {
624                  int start_trk;
625                  int end_trk;
626                  int len;
627                  int in_len;
628                  int dptr;
629                  UINT32 tstart;
630
631                  start_trk = command[6];
632                  if( start_trk == 0 )
633                  {
634                     start_trk = 1;
635                  }
636
637                  end_trk = cdrom_get_last_track(cdrom);
638                  len = (end_trk * 8) + 2;
639
640                  // the returned TOC DATA LENGTH must be the full amount,
641                  // regardless of how much we're able to pass back due to in_len
642                  dptr = 0;
643                  data[dptr++] = (len>>8) & 0xff;
644                  data[dptr++] = (len & 0xff);
645                  data[dptr++] = 1;
646                  data[dptr++] = end_trk;
647
648                  if( start_trk == 0xaa )
649                  {
650                     end_trk = 0xaa;
651                  }
652
653                  in_len = command[7]<<8 | command[8];
654
655                  for (i = start_trk; i <= end_trk; i++)
656                  {
657                     int cdrom_track = i;
658                     if( cdrom_track != 0xaa )
659                     {
660                        cdrom_track--;
661                     }
662
663                     if( dptr >= in_len )
664                     {
665                        break;
666                     }
667
668                     data[dptr++] = 0;
669                     data[dptr++] = cdrom_get_adr_control(cdrom, cdrom_track);
670                     data[dptr++] = i;
671                     data[dptr++] = 0;
672
673                     tstart = cdrom_get_track_start(cdrom, cdrom_track);
674                     if ((command[1]&2)>>1)
675                        tstart = lba_to_msf(tstart);
676                     data[dptr++] = (tstart>>24) & 0xff;
677                     data[dptr++] = (tstart>>16) & 0xff;
678                     data[dptr++] = (tstart>>8) & 0xff;
679                     data[dptr++] = (tstart & 0xff);
680                  }
681               }
682               break;
683            default:
684               logerror("GDROM: Unhandled READ TOC format %d\n", command[2]&0xf);
685               break;
686         }
687         break;
688
689      case 0x1a: // MODE SENSE(6)
690      case 0x5a: // MODE SENSE(10)
691         logerror("GDROM: MODE SENSE page code = %x, PC = %x\n", command[2] & 0x3f, (command[2]&0xc0)>>6);
692
693         switch (command[2] & 0x3f)
694         {
695            case 0xe:   // CD Audio control page
696               data[0] = 0x8e;   // page E, parameter is savable
697               data[1] = 0x0e;   // page length
698               data[2] = 0x04;   // IMMED = 1, SOTC = 0
699               data[3] = data[4] = data[5] = data[6] = data[7] = 0; // reserved
700
701               // connect each audio channel to 1 output port
702               data[8] = 1;
703               data[10] = 2;
704               data[12] = 4;
705               data[14] = 8;
706
707               // indicate max volume
708               data[9] = data[11] = data[13] = data[15] = 0xff;
709               break;
710
711            default:
712               logerror("GDROM: MODE SENSE unknown page %x\n", command[2] & 0x3f);
713               break;
714         }
715         break;
716
717      default:
718         SCSIBase( &SCSIClassGDROM, SCSIOP_READ_DATA, scsiInstance, dataLength, data );
719         break;
720   }
721}
722
723// scsicd_write_data
724//
725// Write data to the CD-ROM device as part of the execution of a command
726
727static void scsicd_write_data( SCSIInstance *scsiInstance, UINT8 *data, int dataLength )
728{
729   UINT8 *command;
730   int commandLength;
731   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
732   SCSIGetCommand( scsiInstance, &command, &commandLength );
733
734   switch (command[ 0 ])
735   {
736      case 0x15: // MODE SELECT(6)
737      case 0x55: // MODE SELECT(10)
738         logerror("GDROM: MODE SELECT page %x\n", data[0] & 0x3f);
739
740         switch (data[0] & 0x3f)
741         {
742            case 0x0:   // vendor-specific
743               // check for SGI extension to force 512-byte blocks
744               if ((data[3] == 8) && (data[10] == 2))
745               {
746                  logerror("GDROM: Experimental SGI 512-byte block extension enabled\n");
747
748                  our_this->bytes_per_sector = 512;
749                  our_this->num_subblocks = 4;
750               }
751               else
752               {
753                  logerror("GDROM: Unknown vendor-specific page!\n");
754               }
755               break;
756
757            case 0xe:   // audio page
758               logerror("Ch 0 route: %x vol: %x\n", data[8], data[9]);
759               logerror("Ch 1 route: %x vol: %x\n", data[10], data[11]);
760               logerror("Ch 2 route: %x vol: %x\n", data[12], data[13]);
761               logerror("Ch 3 route: %x vol: %x\n", data[14], data[15]);
762               break;
763         }
764         break;
765
766      default:
767         SCSIBase( &SCSIClassGDROM, SCSIOP_WRITE_DATA, scsiInstance, dataLength, data );
768         break;
769   }
770}
771
772static void scsicd_alloc_instance( SCSIInstance *scsiInstance, const char *diskregion )
773{
774   running_machine &machine = scsiInstance->machine();
775   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
776
777   our_this->lba = 0;
778   our_this->blocks = 0;
779   our_this->last_lba = 0;
780   our_this->bytes_per_sector = 2048;
781   our_this->num_subblocks = 1;
782   our_this->cur_subblock = 0;
783   our_this->play_err_flag = 0;
784
785   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->lba );
786   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->blocks );
787   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->last_lba );
788   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->bytes_per_sector );
789   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->num_subblocks );
790   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->cur_subblock );
791   state_save_register_item( machine, "scsicd", diskregion, 0, our_this->play_err_flag );
792
793   if (machine.device( diskregion )) {
794      our_this->is_file = TRUE;
795      our_this->cdrom = cd_get_cdrom_file( machine.device( diskregion ) );
796   } else {
797      our_this->is_file = FALSE;
798      our_this->cdrom = cdrom_open(get_disk_handle( machine, diskregion ));
799   }
800
801   if (!our_this->cdrom)
802   {
803      logerror("GDROM: no CD found!\n");
804   }
805}
806
807static void scsicd_delete_instance( SCSIInstance *scsiInstance )
808{
809   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
810   if (!our_this->is_file) {
811      if( our_this->cdrom )
812      {
813         cdrom_close( our_this->cdrom );
814      }
815   }
816}
817
818static void scsicd_get_device( SCSIInstance *scsiInstance, cdrom_file **cdrom )
819{
820   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
821   *cdrom = our_this->cdrom;
822}
823
824static void scsicd_set_device( SCSIInstance *scsiInstance, cdrom_file *cdrom )
825{
826   SCSIGd *our_this = (SCSIGd *)SCSIThis( &SCSIClassGDROM, scsiInstance );
827   our_this->cdrom = cdrom;
828}
829
830static int scsigd_dispatch(int operation, void *file, INT64 intparm, void *ptrparm)
831{
832   SCSIAllocInstanceParams *params;
833
834   switch (operation)
835   {
836      case SCSIOP_EXEC_COMMAND:
837         return scsicd_exec_command( (SCSIInstance *)file, (UINT8 *)ptrparm );
838
839      case SCSIOP_READ_DATA:
840         scsicd_read_data( (SCSIInstance *)file, (UINT8 *)ptrparm, intparm );
841         return 0;
842
843      case SCSIOP_WRITE_DATA:
844         scsicd_write_data( (SCSIInstance *)file, (UINT8 *)ptrparm, intparm );
845         return 0;
846
847      case SCSIOP_ALLOC_INSTANCE:
848         params = (SCSIAllocInstanceParams *)ptrparm;
849         SCSIBase( &SCSIClassGDROM, operation, (SCSIInstance *)file, intparm, (UINT8 *)ptrparm );
850         scsicd_alloc_instance( params->instance, params->diskregion );
851         return 0;
852
853      case SCSIOP_DELETE_INSTANCE:
854         scsicd_delete_instance( (SCSIInstance *)file );
855         break;
856
857      case SCSIOP_GET_DEVICE:
858         scsicd_get_device( (SCSIInstance *)file, (cdrom_file **)ptrparm );
859         return 0;
860
861      case SCSIOP_SET_DEVICE:
862         scsicd_set_device( (SCSIInstance *)file, (cdrom_file *)ptrparm );
863         return 0;
864   }
865
866   return SCSIBase( &SCSIClassGDROM, operation, (SCSIInstance *)file, intparm, (UINT8 *)ptrparm );
867}
868
869const SCSIClass SCSIClassGDROM =
870{
871   &SCSIClassDevice,
872   scsigd_dispatch,
873   sizeof( SCSIGd )
874};
src/mess/machine/gdrom.h
r11450r11451
1/***************************************************************************
2
3 gdrom.h
4
5***************************************************************************/
6
7#ifndef _GDROM_H_
8#define _GDROM_H_
9
10#include "machine/scsi.h"
11
12// Sega GD-ROM handler
13extern const SCSIClass SCSIClassGDROM;
14#define SCSI_DEVICE_GDROM &SCSIClassGDROM
15
16#endif
17
src/mess/machine/upd765.c
r11450r11451
1/***************************************************************************
2
3    machine/upd765.c
4
5    Functions to emulate a UPD765/Intel 8272 compatible floppy disk controller
6
7    Code by Kevin Thacker.
8
9    TODO:
10
11    - overrun condition
12    - Scan Commands
13    - crc error in id field and crc error in data field errors
14    - disc not present, and no sectors on track for data, deleted data, write, write deleted,
15        read a track etc
16        - end of cylinder condition - almost working, needs fixing  with
17                PCW and PC drivers
18    - resolve "ready" state stuff (ready state when reset for PC, ready state change while processing command AND
19    while idle)
20
21    Changes:
22    091006 (Mariusz Wojcieszek, changes needed by QX-10):
23    - allowed "Sense Interrupt Status" command when Seek is active
24    - DIO bit in status register (0x40) is cleared when "Read Data" command is executed,
25      it is later set during result phase.
26
27***************************************************************************/
28
29#include "emu.h"
30#include "machine/upd765.h"
31
32
33typedef enum
34{
35   UPD765_COMMAND_PHASE_FIRST_BYTE,
36   UPD765_COMMAND_PHASE_BYTES,
37   UPD765_RESULT_PHASE,
38   UPD765_EXECUTION_PHASE_READ,
39   UPD765_EXECUTION_PHASE_WRITE
40} UPD765_PHASE;
41
42/* supported versions */
43typedef enum
44{
45   TYPE_UPD765A = 0,
46   TYPE_UPD765B = 1,
47   TYPE_SMC37C78 = 2,
48   TYPE_UPD72065 = 3
49} UPD765_VERSION;
50
51
52/* uncomment the following line for verbose information */
53#define LOG_VERBOSE      0
54#define LOG_COMMAND      0
55#define LOG_EXTRA      0
56#define LOG_INTERRUPT   0
57
58/* uncomment this to not allow end of cylinder "error" */
59#define NO_END_OF_CYLINDER
60
61
62
63/* state of upd765 Interrupt (INT) output */
64#define UPD765_INT   0x02
65/* data rate for floppy discs (MFM data) */
66#define UPD765_DATA_RATE   32
67/* state of upd765 terminal count input*/
68#define UPD765_TC   0x04
69
70#define UPD765_DMA_MODE 0x08
71
72#define UPD765_SEEK_OPERATION_IS_RECALIBRATE 0x01
73
74#define UPD765_SEEK_ACTIVE 0x010
75/* state of upd765 DMA DRQ output */
76#define UPD765_DMA_DRQ 0x020
77/* state of upd765 FDD READY input */
78#define UPD765_FDD_READY 0x040
79
80#define UPD765_MF   0x40
81
82#define UPD765_RESET 0x080
83
84typedef struct _upd765_t upd765_t;
85struct _upd765_t
86{
87   devcb_resolved_write_line   out_int_func;
88   devcb_resolved_write_line   out_drq_func;
89
90   unsigned long   sector_counter;
91   /* version of fdc to emulate */
92   UPD765_VERSION version;
93
94   /* main status register */
95   unsigned char    FDC_main;
96   /* data register */
97   unsigned char   upd765_data_reg;
98
99   unsigned char c,h,r,n;
100
101   int sector_id;
102
103   int data_type;
104
105   char format_data[4];
106
107   UPD765_PHASE    upd765_phase;
108   unsigned int    upd765_command_bytes[16];
109   unsigned int    upd765_result_bytes[16];
110   unsigned int    upd765_transfer_bytes_remaining;
111   unsigned int    upd765_transfer_bytes_count;
112   unsigned int    upd765_status[4];
113   /* present cylinder number per drive */
114   unsigned int    pcn[4];
115
116   /* drive being accessed. drive outputs from fdc */
117   unsigned int    drive;
118   /* side being accessed: side output from fdc */
119   unsigned int   side;
120
121
122   /* step rate time in us */
123   unsigned long   srt_in_ms;
124
125   unsigned int   ncn;
126
127//  unsigned int    upd765_id_index;
128   char *execution_phase_data;
129   unsigned int   upd765_flags;
130
131//  unsigned char specify[2];
132//  unsigned char perpendicular_mode[1];
133
134   int command;
135
136   emu_timer *seek_timer;
137   emu_timer *timer;
138   int timer_type;
139
140   emu_timer *command_timer;
141
142   char *data_buffer;
143   const upd765_interface *intf;
144};
145
146//static void upd765_setup_data_request(unsigned char Data);
147static void upd765_setup_command(device_t *device);
148static TIMER_CALLBACK(upd765_continue_command);
149static int upd765_sector_count_complete(device_t *device);
150static void upd765_increment_sector(device_t *device);
151static void upd765_update_state(device_t *device);
152static void upd765_set_dma_drq(device_t *device,int state);
153static void upd765_set_int(device_t *device,int state);
154
155static const INT8 upd765_cmd_size[32] =
156{
157   1,1,9,3,2,9,9,2,1,9,2,1,9,6,1,3,
158   1,9,1,1,1,1,9,1,1,9,1,1,1,9,1,1
159};
160
161INLINE upd765_t *get_safe_token(device_t *device)
162{
163   assert(device != NULL);
164   assert(device->type() == UPD765A || device->type() == UPD765B ||
165      device->type() == SMC37C78 || device->type() == UPD72065);
166
167   return (upd765_t *)downcast<legacy_device_base *>(device)->token();
168}
169
170static device_t *current_image(device_t *device)
171{
172   device_t *image = NULL;
173   upd765_t *fdc = get_safe_token(device);
174
175   if (!fdc->intf->get_image)
176   {
177      if (fdc->intf->floppy_drive_tags[fdc->drive] != NULL)
178      {
179         if (device->owner() != NULL)
180            image = device->owner()->subdevice(fdc->intf->floppy_drive_tags[fdc->drive]);
181         else
182            image = device->machine().device(fdc->intf->floppy_drive_tags[fdc->drive]);
183      }
184   }
185   else
186   {
187      image = fdc->intf->get_image(device, fdc->drive);
188   }
189   return image;
190}
191
192static void upd765_setup_drive_and_side(device_t *device)
193{
194   upd765_t *fdc = get_safe_token(device);
195   /* drive index upd765 sees */
196   fdc->drive = fdc->upd765_command_bytes[1] & 0x03;
197   /* side index upd765 sees */
198   fdc->side = (fdc->upd765_command_bytes[1]>>2) & 0x01;
199}
200
201
202/* setup status register 0 based on data in status register 1 and 2 */
203static void upd765_setup_st0(device_t *device)
204{
205   upd765_t *fdc = get_safe_token(device);
206   /* clear completition status bits, drive bits and side bits */
207   fdc->upd765_status[0] &= ~((1<<7) | (1<<6) | (1<<2) | (1<<1) | (1<<0));
208   /* fill in drive */
209   fdc->upd765_status[0] |= fdc->drive | (fdc->side<<2);
210
211   /* fill in completion status bits based on bits in st0, st1, st2 */
212   /* no error bits set */
213   if ((fdc->upd765_status[1] | fdc->upd765_status[2])==0)
214   {
215      return;
216   }
217
218   fdc->upd765_status[0] |= 0x040;
219}
220
221
222static int upd765_n_to_bytes(int n)
223{
224   /* 0-> 128 bytes, 1->256 bytes, 2->512 bytes etc */
225   /* data_size = ((1<<(N+7)) */
226   return 1<<(n+7);
227}
228
229static void upd765_set_data_request(device_t *device)
230{
231   upd765_t *fdc = get_safe_token(device);
232   fdc->FDC_main |= 0x080;
233}
234
235static void upd765_clear_data_request(device_t *device)
236{
237   upd765_t *fdc = get_safe_token(device);
238   fdc->FDC_main &= ~0x080;
239}
240
241static int upd765_get_rdy(device_t *device)
242{
243   upd765_t *fdc = get_safe_token(device);
244
245   if (fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED)
246   {
247      device_t *img = current_image(device);
248      return floppy_drive_get_flag_state(img, FLOPPY_DRIVE_READY);
249   }
250   else
251      return 1;
252}
253
254static void upd765_seek_complete(device_t *device)
255{
256   /* tested on Amstrad CPC */
257
258   /* if a seek is done without drive connected: */
259   /*  abnormal termination of command,
260        seek complete,
261        not ready
262    */
263
264   /* if a seek is done with drive connected, but disc missing: */
265   /* abnormal termination of command,
266        seek complete,
267        not ready */
268
269   /* if a seek is done with drive connected and disc in drive */
270   /* seek complete */
271
272
273   /* On the PC however, it appears that recalibrates and seeks can be performed without
274    a disc in the drive. */
275
276   /* Therefore, the above output is dependant on the state of the drive */
277
278   /* In the Amstrad CPC, the drive select is provided by the UPD765. A single port is also
279    assigned for setting the drive motor state. The motor state controls the motor of the selected
280    drive */
281
282   /* On the PC the drive can be selected with the DIGITAL OUTPUT REGISTER, and the motor of each
283    of the 4 possible drives is also settable using the same register */
284
285   /* Assumption for PC: (NOT TESTED - NEEDS VERIFICATION) */
286
287   /* If a seek is done without drive connected: */
288   /* abnormal termination of command,
289        seek complete,
290        fault
291        */
292
293   /* if a seek is done with drive connected, but disc missing: */
294   /* seek complete */
295
296   /* if a seek is done with drive connected and disc in drive: */
297   /* seek complete */
298
299   /* On Amstrad CPC:
300        If drive not connected, or drive connected but disc not in drive, not ready!
301        If drive connected and drive motor on, ready!
302       On PC:
303        Drive is always ready!
304
305        In 37c78 docs, the ready bits of the upd765 are marked as unused.
306        This indicates it is always ready!!!!!
307    */
308
309   device_t *img = current_image(device);
310   upd765_t *fdc = get_safe_token(device);
311
312   fdc->pcn[fdc->drive] = fdc->ncn;
313
314   fdc->upd765_status[0] = 0x20;
315
316   /* drive ready? */
317   if (img != NULL && upd765_get_rdy(device))
318   {
319      /* recalibrate? */
320      if (fdc->upd765_flags & UPD765_SEEK_OPERATION_IS_RECALIBRATE)
321      {
322         /* not at track 0? */
323         if (fdc->pcn[fdc->drive] != 0)
324            /* no, track 0 failed after 77 steps */
325            fdc->upd765_status[0] |= 0x40 | 0x10;
326      }
327   }
328   else
329   {
330      /* abnormal termination, not ready */
331      fdc->upd765_status[0] |= 0x40 | 0x08;
332   }
333
334   /* set drive and side. note: commented out side to avoid problems with the tf20 */
335   fdc->upd765_status[0] |= fdc->drive; //| (fdc->side<<2);
336
337   upd765_set_int(device,0);
338   upd765_set_int(device,1);
339
340   fdc->upd765_flags &= ~UPD765_SEEK_ACTIVE;
341
342   upd765_idle(device);
343}
344
345static TIMER_CALLBACK(upd765_seek_timer_callback)
346{
347   device_t *device = (device_t *)ptr;
348   upd765_t *fdc = get_safe_token(device);
349   /* seek complete */
350   upd765_seek_complete(device);
351
352   fdc->seek_timer->reset();
353}
354
355static void upd765_timer_func(device_t *device, int timer_type)
356{
357   upd765_t *fdc = get_safe_token(device);
358   /* type 0 = data transfer mode in execution phase */
359   if (fdc->timer_type == 0)
360   {
361      /* set data request */
362      upd765_set_data_request(device);
363
364      fdc->timer_type = 4;
365
366      if (!(fdc->upd765_flags & UPD765_DMA_MODE))
367      {
368         if (fdc->upd765_command_bytes[0] & UPD765_MF)
369         {
370            /* MFM */
371            fdc->timer->reset(attotime::from_usec(13));
372         }
373         else
374         {
375            /* FM */
376            fdc->timer->reset(attotime::from_usec(27));
377         }
378      }
379      else
380      {
381         upd765_timer_func(device, fdc->timer_type);
382      }
383   }
384   else if (fdc->timer_type==2)
385   {
386      /* result phase begin */
387
388      /* generate a int for specific commands */
389      switch (fdc->command) {
390      case 2:      /* read a track */
391      case 5:      /* write data */
392      case 6:      /* read data */
393      case 9:      /* write deleted data */
394      case 10:   /* read id */
395      case 12:   /* read deleted data */
396      case 13:   /* format at track */
397      case 17:   /* scan equal */
398      case 19:   /* scan low or equal */
399      case 29:   /* scan high or equal */
400         upd765_set_int(device,1);
401         break;
402
403      default:
404         break;
405      }
406
407      upd765_set_data_request(device);
408
409      fdc->timer->reset();
410   }
411   else if (fdc->timer_type == 4)
412   {
413      /* if in dma mode, a int is not generated per byte. If not in  DMA mode
414        a int is generated per byte */
415      if (fdc->upd765_flags & UPD765_DMA_MODE)
416      {
417         upd765_set_dma_drq(device,1);
418      }
419      else
420      {
421         if (fdc->FDC_main & (1<<7))
422         {
423            /* set int to indicate data is ready */
424            upd765_set_int(device,1);
425         }
426      }
427
428      fdc->timer->reset();
429   }
430}
431
432static TIMER_CALLBACK(upd765_timer_callback)
433{
434   device_t *device = (device_t *)ptr;
435   upd765_timer_func(device,param);
436}
437
438/* after (32-27) the DRQ is set, then 27 us later, the int is set.
439I don't know if this is correct, but it is required for the PCW driver.
440In this driver, the first NMI calls the handler function, furthur NMI's are
441effectively disabled by reading the data before the NMI int can be set.
442*/
443
444static void upd765_setup_timed_generic(device_t *device, int timer_type, attotime duration)
445{
446   upd765_t *fdc = get_safe_token(device);
447
448   fdc->timer_type = timer_type;
449
450   if (!(fdc->upd765_flags & UPD765_DMA_MODE))
451   {
452      fdc->timer->adjust(duration);
453   }
454   else
455   {
456      upd765_timer_func(device,fdc->timer_type);
457      fdc->timer->reset();
458   }
459}
460
461/* setup data request */
462static void upd765_setup_timed_data_request(device_t *device, int bytes)
463{
464   /* setup timer to trigger in UPD765_DATA_RATE us */
465   upd765_setup_timed_generic(device, 0, attotime::from_usec(32-27)   /*UPD765_DATA_RATE)*bytes*/);
466}
467
468/* setup result data request */
469static void upd765_setup_timed_result_data_request(device_t *device)
470{
471   upd765_setup_timed_generic(device, 2, attotime::from_usec(UPD765_DATA_RATE*2));
472}
473
474
475/* sets up a timer to issue a seek complete in signed_tracks time */
476static void upd765_setup_timed_int(device_t *device,int signed_tracks)
477{
478   upd765_t *fdc = get_safe_token(device);
479   /* setup timer to signal after seek time is complete */
480   fdc->seek_timer->adjust(attotime::from_double(fdc->srt_in_ms*abs(signed_tracks)*0.001));
481}
482
483static void upd765_seek_setup(device_t *device, int is_recalibrate)
484{
485   device_t *img;
486   int signed_tracks;
487   upd765_t *fdc = get_safe_token(device);
488
489   fdc->upd765_flags |= UPD765_SEEK_ACTIVE;
490
491   if (is_recalibrate)
492   {
493      /* head cannot be specified with recalibrate */
494      fdc->upd765_command_bytes[1] &=~0x04;
495   }
496
497   upd765_setup_drive_and_side(device);
498
499   img = current_image(device);
500
501   fdc->FDC_main |= (1<<fdc->drive);
502   fdc->FDC_main |= 0x20;  // execution phase
503   fdc->FDC_main &= ~0x10;  // not busy, can send another seek/recalibrate
504                            // for a different drive, or sense int status
505
506   /* recalibrate command? */
507   if (is_recalibrate)
508   {
509      fdc->upd765_flags |= UPD765_SEEK_OPERATION_IS_RECALIBRATE;
510
511      fdc->ncn = 0;
512
513      /* if drive is already at track 0, or drive is not ready */
514      if (img == NULL || floppy_tk00_r(img) == CLEAR_LINE || (!upd765_get_rdy(device)))
515      {
516         /* seek completed */
517//          upd765_seek_complete(device);
518         // delay for the time of 1 step, the PCW does not like immediate recalibrates
519         upd765_setup_timed_int(device,1);
520      }
521      else
522      {
523         /* is drive present? */
524         if (1) //image_slotexists(img)) //fix me
525         {
526            /* yes - calculate real number of tracks to seek */
527
528            int current_track;
529
530            /* get current track */
531            current_track = floppy_drive_get_current_track(img);
532
533            /* get number of tracks to seek */
534            signed_tracks = -current_track;
535         }
536         else
537         {
538            /* no, seek 77 tracks and then stop */
539            /* true for UPD765A, but not for other variants */
540            signed_tracks = -77;
541         }
542
543         if (signed_tracks!=0)
544         {
545            /* perform seek - if drive isn't present it will not do anything */
546            floppy_drive_seek(img, signed_tracks);
547
548            upd765_setup_timed_int(device,signed_tracks);
549         }
550         else
551         {
552            upd765_seek_complete(device);
553         }
554      }
555   }
556   else
557   {
558
559      fdc->upd765_flags &= ~UPD765_SEEK_OPERATION_IS_RECALIBRATE;
560
561      fdc->ncn = fdc->upd765_command_bytes[2];
562
563      /* get signed tracks */
564      signed_tracks = fdc->ncn - fdc->pcn[fdc->drive];
565
566      /* if no tracks to seek, or drive is not ready, seek is complete */
567      if (img == NULL || (signed_tracks==0) || (!upd765_get_rdy(device)))
568      {
569         upd765_seek_complete(device);
570      }
571      else
572      {
573         /* perform seek - if drive isn't present it will not do anything */
574         floppy_drive_seek(img, signed_tracks);
575
576         /* seek complete - issue an interrupt */
577         upd765_setup_timed_int(device,signed_tracks);
578      }
579   }
580//    upd765_idle(device);
581}
582
583
584
585static void upd765_setup_execution_phase_read(device_t *device, char *ptr, int size)
586{
587   upd765_t *fdc = get_safe_token(device);
588
589   fdc->FDC_main &= ~0x040;                     /* FDC->CPU */
590
591   fdc->upd765_transfer_bytes_count = 0;
592   fdc->upd765_transfer_bytes_remaining = size;
593   fdc->execution_phase_data = ptr;
594   fdc->upd765_phase = UPD765_EXECUTION_PHASE_READ;
595
596   upd765_setup_timed_data_request(device, 1);
597}
598
599static void upd765_setup_execution_phase_write(device_t *device, char *ptr, int size)
600{
601   upd765_t *fdc = get_safe_token(device);
602
603   fdc->FDC_main &= ~0x040;                     /* FDC->CPU */
604
605   fdc->upd765_transfer_bytes_count = 0;
606   fdc->upd765_transfer_bytes_remaining = size;
607   fdc->execution_phase_data = ptr;
608   fdc->upd765_phase = UPD765_EXECUTION_PHASE_WRITE;
609
610   /* setup a data request with first byte */
611   upd765_setup_timed_data_request(device,1);
612}
613
614
615static void upd765_setup_result_phase(device_t *device, int byte_count)
616{
617   upd765_t *fdc = get_safe_token(device);
618
619   fdc->FDC_main |= 0x040;                     /* FDC->CPU */
620   fdc->FDC_main &= ~0x020;                    /* not execution phase */
621
622   fdc->upd765_transfer_bytes_count = 0;
623   fdc->upd765_transfer_bytes_remaining = byte_count;
624   fdc->upd765_phase = UPD765_RESULT_PHASE;
625
626   upd765_setup_timed_result_data_request(device);
627}
628
629void upd765_idle(device_t *device)
630{
631   upd765_t *fdc = get_safe_token(device);
632
633   fdc->FDC_main &= ~0x040;                     /* CPU->FDC */
634   fdc->FDC_main &= ~0x020;                    /* not execution phase */
635   fdc->FDC_main &= ~0x010;                     /* not busy */
636   fdc->upd765_phase = UPD765_COMMAND_PHASE_FIRST_BYTE;
637
638   upd765_set_data_request(device);
639}
640
641
642
643/* change flags */
644static void upd765_change_flags(device_t *device,unsigned int flags, unsigned int mask)
645{
646   unsigned int new_flags;
647   unsigned int changed_flags;
648   upd765_t *fdc = get_safe_token(device);
649
650   assert((flags & ~mask) == 0);
651
652   /* compute the new flags and which ones have changed */
653   new_flags = fdc->upd765_flags & ~mask;
654   new_flags |= flags;
655   changed_flags = fdc->upd765_flags ^ new_flags;
656   fdc->upd765_flags = new_flags;
657
658   /* if interrupt changed, call the handler */
659   if (changed_flags & UPD765_INT)
660      fdc->out_int_func((fdc->upd765_flags & UPD765_INT) ? 1 : 0);
661
662   /* if DRQ changed, call the handler */
663   if (changed_flags & UPD765_DMA_DRQ)
664      fdc->out_drq_func((fdc->upd765_flags & UPD765_DMA_DRQ) ? 1 : 0);
665}
666
667
668
669/* set int output */
670static void upd765_set_int(device_t *device, int state)
671{
672   if (LOG_INTERRUPT)
673      logerror("upd765_set_int(): state=%d\n", state);
674   upd765_change_flags(device, state ? UPD765_INT : 0, UPD765_INT);
675}
676
677
678
679/* set dma request output */
680static void upd765_set_dma_drq(device_t *device, int state)
681{
682   upd765_change_flags(device, state ? UPD765_DMA_DRQ : 0, UPD765_DMA_DRQ);
683}
684
685
686
687/* Drive ready */
688
689/*
690
691A drive will report ready if:
692- drive is selected
693- disc is in the drive
694- disk is rotating at a constant speed (normally 300rpm)
695
696On more modern PCs, a ready signal is not provided by the drive.
697This signal is not used in the PC design and was eliminated to save costs
698If you look at the datasheets for the modern UPD765 variants, you will see the Ready
699signal is not mentioned.
700
701On the original UPD765A, ready signal is required, and some commands will fail if the drive
702is not ready.
703
704
705
706
707*/
708
709
710
711
712/* done when ready state of drive changes */
713/* this ignores if command is active, in which case command should terminate immediatly
714with error */
715static void upd765_set_ready_change_callback(device_t *controller, device_t *img, int state)
716{
717   upd765_t *fdc = get_safe_token(controller);
718   int drive = floppy_get_drive(img);
719
720   if (LOG_EXTRA)
721      logerror("upd765: ready state change\n");
722
723   /* drive that changed state */
724   fdc->upd765_status[0] = 0x0c0 | drive;
725
726   /* not ready */
727   if (state==0 && fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED )
728      fdc->upd765_status[0] |= 8;
729
730   /* trigger an int */
731   upd765_set_int(controller, 1);
732}
733
734
735/* terminal count input */
736WRITE_LINE_DEVICE_HANDLER( upd765_tc_w )
737{
738   int old_state;
739   upd765_t *fdc = get_safe_token(device);
740
741   old_state = fdc->upd765_flags;
742
743   /* clear drq */
744   upd765_set_dma_drq(device, 0);
745
746   fdc->upd765_flags &= ~UPD765_TC;
747   if (state)
748   {
749      fdc->upd765_flags |= UPD765_TC;
750   }
751
752   /* changed state? */
753   if (((fdc->upd765_flags^old_state) & UPD765_TC)!=0)
754   {
755      /* now set? */
756      if ((fdc->upd765_flags & UPD765_TC)!=0)
757      {
758         /* yes */
759         if (fdc->timer)
760         {
761            if (fdc->timer_type==0)
762            {
763               fdc->timer->reset();
764
765
766            }
767         }
768
769#ifdef NO_END_OF_CYLINDER
770         fdc->command_timer->adjust(attotime::zero);
771#else
772         upd765_update_state(device);
773#endif
774      }
775   }
776}
777
778READ8_DEVICE_HANDLER( upd765_status_r )
779{
780   upd765_t *fdc = get_safe_token(device);
781   if (LOG_EXTRA)
782      logerror("%s: upd765_status_r: %02x\n", device->machine().describe_context(), fdc->FDC_main);
783   return fdc->FDC_main;
784}
785
786
787/* control mark handling code */
788
789/* if SK==1, and we are executing a read data command, and a deleted data mark is found,
790skip it.
791if SK==1, and we are executing a read deleted data command, and a data mark is found,
792skip it. */
793
794static int upd765_read_skip_sector(device_t *device)
795{
796   upd765_t *fdc = get_safe_token(device);
797   /* skip set? */
798   if ((fdc->upd765_command_bytes[0] & (1<<5))!=0)
799   {
800      /* read data? */
801      if (fdc->command == 0x06)
802      {
803         /* did we just find a sector with deleted data mark? */
804         if (fdc->data_type == UPD765_DAM_DELETED_DATA)
805         {
806            /* skip it */
807            return TRUE;
808         }
809      }
810      /* deleted data? */
811      else
812      if (fdc->command == 0x0c)
813      {
814         /* did we just find a sector with data mark ? */
815         if (fdc->data_type == UPD765_DAM_DATA)
816         {
817            /* skip it */
818            return TRUE;
819         }
820      }
821   }
822
823   /* do not skip */
824   return FALSE;
825}
826
827/* this is much closer to how the upd765 actually gets sectors */
828/* used by read data, read deleted data, write data, write deleted data */
829/* What the upd765 does:
830
831  - get next sector id from disc
832  - if sector id matches id specified in command, it will
833    search for next data block and read data from it.
834
835  - if the index is seen twice while it is searching for a sector, then the sector cannot be found
836*/
837
838static void upd765_get_next_id(device_t *device, chrn_id *id)
839{
840   upd765_t *fdc = get_safe_token(device);
841   device_t *img = current_image(device);
842
843   /* get next id from disc */
844   floppy_drive_get_next_id(img, fdc->side,id);
845
846   fdc->sector_id = id->data_id;
847
848   /* set correct data type */
849   fdc->data_type = UPD765_DAM_DATA;
850   if (id->flags & ID_FLAG_DELETED_DATA)
851   {
852      fdc->data_type = UPD765_DAM_DELETED_DATA;
853   }
854}
855
856static int upd765_get_matching_sector(device_t *device)
857{
858   upd765_t *fdc = get_safe_token(device);
859   device_t *img = current_image(device);
860   chrn_id id;
861
862   /* number of times we have seen index hole */
863   int index_count = 0;
864
865   /* get sector id's */
866   do
867    {
868      upd765_get_next_id(device, &id);
869
870      /* tested on Amstrad CPC - All bytes must match, otherwise
871        a NO DATA error is reported */
872      if (id.R == fdc->upd765_command_bytes[4])
873      {
874         if (id.C == fdc->upd765_command_bytes[2])
875         {
876            if (id.H == fdc->upd765_command_bytes[3])
877            {
878               if (id.N == fdc->upd765_command_bytes[5])
879               {
880                  /* end of cylinder is set if:
881                        1. sector data is read completely (i.e. no other errors occur like
882                        no data.
883                        2. sector being read is same specified by EOT
884                        3. terminal count is not received */
885                  if (fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6])
886                  {
887                     /* set end of cylinder */
888                     fdc->upd765_status[1] |= UPD765_ST1_END_OF_CYLINDER;
889                  }
890
891                  return TRUE;
892               }
893            }
894         }
895         else
896         {
897            /* the specified sector ID was found, however, the C value specified
898                in the read/write command did not match the C value read from the disc */
899
900            /* no data - checked on Amstrad CPC */
901            fdc->upd765_status[1] |= UPD765_ST1_NO_DATA;
902            /* bad C value */
903            fdc->upd765_status[2] |= UPD765_ST2_WRONG_CYLINDER;
904
905            if (id.C == 0x0ff)
906            {
907               /* the C value is 0x0ff which indicates a bad track in the IBM soft-sectored
908                    format */
909               fdc->upd765_status[2] |= UPD765_ST2_BAD_CYLINDER;
910            }
911
912            return FALSE;
913         }
914      }
915
916       /* index set? */
917      if (floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))
918      {
919         index_count++;
920      }
921
922   }
923   while (index_count!=2);
924
925   if (fdc->upd765_command_bytes[4] != fdc->upd765_command_bytes[6])
926   {
927      /* no data - specified sector ID was not found */
928      fdc->upd765_status[1] |= UPD765_ST1_NO_DATA;
929   }
930
931   return 0;
932}
933
934static void upd765_read_complete(device_t *device)
935{
936   upd765_t *fdc = get_safe_token(device);
937/* causes problems!!! - need to fix */
938#ifdef NO_END_OF_CYLINDER
939   /* set end of cylinder */
940   fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
941#else
942   /* completed read command */
943
944   /* end of cylinder is set when:
945        - a whole sector has been read
946        - terminal count input is not set
947        - AND the the sector specified by EOT was read
948        */
949
950   /* if end of cylinder is set, and we did receive a terminal count, then clear it */
951   if ((fdc->upd765_flags & UPD765_TC)!=0)
952   {
953      /* set end of cylinder */
954      fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
955   }
956#endif
957
958   upd765_setup_st0(device);
959
960   fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
961   fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
962   fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
963   fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
964   fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
965   fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
966   fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
967
968   upd765_setup_result_phase(device,7);
969}
970
971static void upd765_read_data(device_t *device)
972{
973   upd765_t *fdc = get_safe_token(device);
974   device_t *img = current_image(device);
975
976   if (!upd765_get_rdy(device))
977   {
978      fdc->upd765_status[0] = 0x0c0 | (1<<4) | fdc->drive | (fdc->side<<2);
979      fdc->upd765_status[1] = 0x00;
980      fdc->upd765_status[2] = 0x00;
981
982      fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
983      fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
984      fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
985      fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
986      fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
987      fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
988      fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
989      upd765_setup_result_phase(device,7);
990      return;
991   }
992
993   if (LOG_VERBOSE)
994      logerror("sector c: %02x h: %02x r: %02x n: %02x\n",fdc->upd765_command_bytes[2], fdc->upd765_command_bytes[3],fdc->upd765_command_bytes[4], fdc->upd765_command_bytes[5]);
995
996   /* find a sector to read data from */
997   {
998      int found_sector_to_read;
999
1000      found_sector_to_read = 0;
1001      /* check for finished reading sectors */
1002      do
1003      {
1004         /* get matching sector */
1005         if (upd765_get_matching_sector(device))
1006         {
1007
1008            /* skip it? */
1009            if (upd765_read_skip_sector(device))
1010            {
1011               /* yes */
1012
1013               /* check that we haven't finished reading all sectors */
1014               if (upd765_sector_count_complete(device))
1015               {
1016                  /* read complete */
1017                  upd765_read_complete(device);
1018                  return;
1019               }
1020
1021               /* read not finished */
1022
1023               /* increment sector count */
1024               upd765_increment_sector(device);
1025            }
1026            else
1027            {
1028               /* found a sector to read */
1029               found_sector_to_read = 1;
1030            }
1031         }
1032         else
1033         {
1034            /* error in finding sector */
1035            upd765_read_complete(device);
1036            return;
1037         }
1038      }
1039      while (found_sector_to_read==0);
1040   }
1041
1042   {
1043      int data_size;
1044
1045      data_size = upd765_n_to_bytes(fdc->upd765_command_bytes[5]);
1046
1047      floppy_drive_read_sector_data(img, fdc->side, fdc->sector_id,fdc->data_buffer,data_size);
1048
1049        upd765_setup_execution_phase_read(device,fdc->data_buffer, data_size);
1050   }
1051}
1052
1053
1054static void upd765_format_track(device_t *device)
1055{
1056   upd765_t *fdc = get_safe_token(device);
1057   device_t *img = current_image(device);
1058
1059   /* write protected? */
1060   if (floppy_wpt_r(img) == CLEAR_LINE)
1061   {
1062      fdc->upd765_status[1] |= UPD765_ST1_NOT_WRITEABLE;
1063
1064      upd765_setup_st0(device);
1065      /* TODO: Check result is correct */
1066         fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1067            fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1068            fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1069         fdc->upd765_result_bytes[3] = fdc->format_data[0];
1070         fdc->upd765_result_bytes[4] = fdc->format_data[1];
1071         fdc->upd765_result_bytes[5] = fdc->format_data[2];
1072         fdc->upd765_result_bytes[6] = fdc->format_data[3];
1073         upd765_setup_result_phase(device,7);
1074
1075      return;
1076   }
1077
1078    upd765_setup_execution_phase_write(device, &fdc->format_data[0], 4);
1079}
1080
1081static void upd765_read_a_track(device_t *device)
1082{
1083   upd765_t *fdc = get_safe_token(device);
1084   int data_size;
1085
1086   /* SKIP not allowed with this command! */
1087
1088   /* get next id */
1089   chrn_id id;
1090
1091   upd765_get_next_id(device, &id);
1092
1093   /* TO BE CONFIRMED! */
1094   /* check id from disc */
1095   if (id.C==fdc->upd765_command_bytes[2])
1096   {
1097      if (id.H==fdc->upd765_command_bytes[3])
1098      {
1099         if (id.R==fdc->upd765_command_bytes[4])
1100         {
1101            if (id.N==fdc->upd765_command_bytes[5])
1102            {
1103               /* if ID found, then no data is not set */
1104               /* otherwise no data will remain set */
1105               fdc->upd765_status[1] &=~UPD765_ST1_NO_DATA;
1106            }
1107         }
1108      }
1109   }
1110
1111
1112   data_size = upd765_n_to_bytes(id.N);
1113
1114   floppy_drive_read_sector_data(current_image(device), fdc->side, fdc->sector_id,fdc->data_buffer,data_size);
1115
1116   upd765_setup_execution_phase_read(device,fdc->data_buffer, data_size);
1117}
1118
1119static int upd765_just_read_last_sector_on_track(device_t *device)
1120{
1121   if (floppy_drive_get_flag_state(current_image(device), FLOPPY_DRIVE_INDEX))
1122      return 1;
1123   return 0;
1124}
1125
1126static void upd765_write_complete(device_t *device)
1127{
1128   upd765_t *fdc = get_safe_token(device);
1129
1130/* causes problems!!! - need to fix */
1131#ifdef NO_END_OF_CYLINDER
1132        /* set end of cylinder */
1133        fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
1134#else
1135   /* completed read command */
1136
1137   /* end of cylinder is set when:
1138     - a whole sector has been read
1139     - terminal count input is not set
1140     - AND the the sector specified by EOT was read
1141     */
1142
1143   /* if end of cylinder is set, and we did receive a terminal count, then clear it */
1144   if ((fdc->upd765_flags & UPD765_TC)!=0)
1145   {
1146      /* set end of cylinder */
1147      fdc->upd765_status[1] &= ~UPD765_ST1_END_OF_CYLINDER;
1148   }
1149#endif
1150
1151   upd765_setup_st0(device);
1152
1153    fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1154    fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1155    fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1156    fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1157    fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1158    fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1159    fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1160
1161    upd765_setup_result_phase(device,7);
1162}
1163
1164
1165static void upd765_write_data(device_t *device)
1166{
1167   upd765_t *fdc = get_safe_token(device);
1168   if (!upd765_get_rdy(device))
1169   {
1170      fdc->upd765_status[0] = 0x0c0 | (1<<4) | fdc->drive | (fdc->side<<2);
1171        fdc->upd765_status[1] = 0x00;
1172        fdc->upd765_status[2] = 0x00;
1173
1174        fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1175        fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1176        fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1177        fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1178        fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1179        fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1180        fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1181      upd765_setup_result_phase(device,7);
1182      return;
1183   }
1184
1185   /* write protected? */
1186   if (floppy_wpt_r(current_image(device)) == CLEAR_LINE)
1187   {
1188      fdc->upd765_status[1] |= UPD765_ST1_NOT_WRITEABLE;
1189
1190      upd765_write_complete(device);
1191      return;
1192   }
1193
1194   if (upd765_get_matching_sector(device))
1195   {
1196      int data_size;
1197
1198      data_size = upd765_n_to_bytes(fdc->upd765_command_bytes[5]);
1199
1200        upd765_setup_execution_phase_write(device,fdc->data_buffer, data_size);
1201   }
1202    else
1203    {
1204        upd765_setup_result_phase(device,7);
1205    }
1206}
1207
1208
1209/* return true if we have read all sectors, false if not */
1210static int upd765_sector_count_complete(device_t *device)
1211{
1212   upd765_t *fdc = get_safe_token(device);
1213/* this is not correct?? */
1214#if 1
1215   /* if terminal count has been set - yes */
1216   if (fdc->upd765_flags & UPD765_TC)
1217   {
1218      /* completed */
1219      return 1;
1220   }
1221
1222
1223
1224   /* multi-track? */
1225   if (fdc->upd765_command_bytes[0] & 0x080)
1226   {
1227      /* it appears that in multi-track mode,
1228        the EOT parameter of the command is ignored!? -
1229        or is it ignored the first time and not the next, so that
1230        if it is started on side 0, it will end at EOT on side 1,
1231        but if started on side 1 it will end at end of track????
1232
1233        PC driver requires this to end at last sector on side 1, and
1234        ignore EOT parameter.
1235
1236        To be checked!!!!
1237        */
1238
1239      /* if just read last sector and on side 1 - finish */
1240      if (upd765_just_read_last_sector_on_track(device))
1241      {
1242         if (floppy_get_heads_per_disk(flopimg_get_image(current_image(device)))==1) {
1243            return 1;
1244         } else {
1245            if (fdc->side==1)
1246               return 1;
1247         }
1248      }
1249
1250      /* if not on second side then we haven't finished yet */
1251      if (fdc->side!=1)
1252      {
1253         /* haven't finished yet */
1254         return 0;
1255      }
1256   }
1257   else
1258   {
1259      /* sector id == EOT? */
1260      if ((fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6]))
1261      {
1262
1263         /* completed */
1264         return 1;
1265      }
1266   }
1267#else
1268
1269   /* if terminal count has been set - yes */
1270   if (fdc->upd765_flags & UPD765_TC)
1271   {
1272      /* completed */
1273      return 1;
1274   }
1275
1276   /* Multi-Track operation:
1277
1278    Verified on Amstrad CPC.
1279
1280        disc format used:
1281            9 sectors per track
1282            2 sides
1283            Sector IDs: &01, &02, &03, &04, &05, &06, &07, &08, &09
1284
1285        Command specified:
1286            SIDE = 0,
1287            C = 0,H = 0,R = 1, N = 2, EOT = 1
1288        Sectors read:
1289            Sector 1 side 0
1290            Sector 1 side 1
1291
1292        Command specified:
1293            SIDE = 0,
1294            C = 0,H = 0,R = 1, N = 2, EOT = 3
1295        Sectors read:
1296            Sector 1 side 0
1297            Sector 2 side 0
1298            Sector 3 side 0
1299            Sector 1 side 1
1300            Sector 2 side 1
1301            Sector 3 side 1
1302
1303
1304        Command specified:
1305            SIDE = 0,
1306            C = 0, H = 0, R = 7, N = 2, EOT = 3
1307        Sectors read:
1308            Sector 7 side 0
1309            Sector 8 side 0
1310            Sector 9 side 0
1311            Sector 10 not found. Error "No Data"
1312
1313        Command specified:
1314            SIDE = 1,
1315            C = 0, H = 1, R = 1, N = 2, EOT = 1
1316        Sectors read:
1317            Sector 1 side 1
1318
1319        Command specified:
1320            SIDE = 1,
1321            C = 0, H = 1, R = 1, N = 2, EOT = 2
1322        Sectors read:
1323            Sector 1 side 1
1324            Sector 1 side 2
1325
1326  */
1327
1328   /* sector id == EOT? */
1329   if ((fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6]))
1330   {
1331      /* multi-track? */
1332      if (fdc->upd765_command_bytes[0] & 0x080)
1333      {
1334         /* if we have reached EOT (fdc->upd765_command_bytes[6])
1335            on side 1, then read is complete */
1336         if (fdc->side==1)
1337            return 1;
1338
1339         return 0;
1340
1341      }
1342
1343      /* completed */
1344      return 1;
1345   }
1346#endif
1347   /* not complete */
1348   return 0;
1349}
1350
1351static void   upd765_increment_sector(device_t *device)
1352{
1353   upd765_t *fdc = get_safe_token(device);
1354   /* multi-track? */
1355   if (fdc->upd765_command_bytes[0] & 0x080)
1356   {
1357      /* reached EOT? */
1358      /* if (fdc->upd765_command_bytes[4]==fdc->upd765_command_bytes[6])*/
1359      if (upd765_just_read_last_sector_on_track(device))
1360      {
1361         /* yes */
1362
1363         /* reached EOT */
1364         /* change side to 1 */
1365         fdc->side = 1;
1366         /* reset sector id to 1 */
1367         fdc->upd765_command_bytes[4] = 1;
1368         /* set head to 1 for get next sector test */
1369         fdc->upd765_command_bytes[3] = 1;
1370      }
1371      else
1372      {
1373         /* increment */
1374         fdc->upd765_command_bytes[4]++;
1375      }
1376
1377   }
1378   else
1379   {
1380      fdc->upd765_command_bytes[4]++;
1381   }
1382}
1383
1384/* control mark handling code */
1385
1386/* if SK==0, and we are executing a read data command, and a deleted data sector is found,
1387the data is not skipped. The data is read, but the control mark is set and the read is stopped */
1388/* if SK==0, and we are executing a read deleted data command, and a data sector is found,
1389the data is not skipped. The data is read, but the control mark is set and the read is stopped */
1390static int upd765_read_data_stop(device_t *device)
1391{
1392   upd765_t *fdc = get_safe_token(device);
1393   /* skip not set? */
1394   if ((fdc->upd765_command_bytes[0] & (1<<5))==0)
1395   {
1396      /* read data? */
1397      if (fdc->command == 0x06)
1398      {
1399         /* did we just read a sector with deleted data? */
1400         if (fdc->data_type == UPD765_DAM_DELETED_DATA)
1401         {
1402            /* set control mark */
1403            fdc->upd765_status[2] |= UPD765_ST2_CONTROL_MARK;
1404
1405            /* quit */
1406            return TRUE;
1407         }
1408      }
1409      /* deleted data? */
1410      else
1411      if (fdc->command == 0x0c)
1412      {
1413         /* did we just read a sector with data? */
1414         if (fdc->data_type == UPD765_DAM_DATA)
1415         {
1416            /* set control mark */
1417            fdc->upd765_status[2] |= UPD765_ST2_CONTROL_MARK;
1418
1419            /* quit */
1420            return TRUE;
1421         }
1422      }
1423   }
1424
1425   /* continue */
1426   return FALSE;
1427}
1428
1429static TIMER_CALLBACK(upd765_continue_command)
1430{
1431   device_t *device = (device_t *)ptr;
1432   upd765_t *fdc = get_safe_token(device);
1433   if ((fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1434      (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1435   {
1436      switch (fdc->command)
1437        {
1438         /* read a track */
1439         case 0x02:
1440         {
1441            fdc->sector_counter++;
1442
1443            /* sector counter == EOT */
1444            if (fdc->sector_counter==fdc->upd765_command_bytes[6])
1445            {
1446               /* TODO: Add correct info here */
1447
1448               fdc->upd765_status[1] |= UPD765_ST1_END_OF_CYLINDER;
1449
1450               upd765_setup_st0(device);
1451
1452               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1453               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1454               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1455               fdc->upd765_result_bytes[3] = fdc->upd765_command_bytes[2]; /* C */
1456               fdc->upd765_result_bytes[4] = fdc->upd765_command_bytes[3]; /* H */
1457               fdc->upd765_result_bytes[5] = fdc->upd765_command_bytes[4]; /* R */
1458               fdc->upd765_result_bytes[6] = fdc->upd765_command_bytes[5]; /* N */
1459
1460               upd765_setup_result_phase(device,7);
1461            }
1462            else
1463            {
1464               upd765_read_a_track(device);
1465            }
1466         }
1467         break;
1468
1469         /* format track */
1470         case 0x0d:
1471         {
1472            floppy_drive_format_sector(current_image(device), fdc->side, fdc->sector_counter,
1473               fdc->format_data[0], fdc->format_data[1],
1474               fdc->format_data[2], fdc->format_data[3],
1475               fdc->upd765_command_bytes[5]);
1476
1477            fdc->sector_counter++;
1478
1479            /* sector_counter = SC */
1480            if (fdc->sector_counter == fdc->upd765_command_bytes[3])
1481            {
1482               /* TODO: Check result is correct */
1483               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1484               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1485               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1486               fdc->upd765_result_bytes[3] = fdc->format_data[0];
1487               fdc->upd765_result_bytes[4] = fdc->format_data[1];
1488               fdc->upd765_result_bytes[5] = fdc->format_data[2];
1489               fdc->upd765_result_bytes[6] = fdc->format_data[3];
1490               upd765_setup_result_phase(device,7);
1491            }
1492            else
1493            {
1494               upd765_format_track(device);
1495            }
1496         }
1497         break;
1498
1499         /* write data, write deleted data */
1500         case 0x09:
1501         case 0x05:
1502         {
1503            /* sector id == EOT */
1504            UINT8 ddam;
1505
1506            ddam = 0;
1507            if (fdc->command == 0x09)
1508            {
1509               ddam = 1;
1510            }
1511
1512            /* write data to disc */
1513            floppy_drive_write_sector_data(current_image(device), fdc->side, fdc->sector_id,fdc->data_buffer,upd765_n_to_bytes(fdc->upd765_command_bytes[5]),ddam);
1514
1515            if (upd765_sector_count_complete(device))
1516            {
1517               upd765_increment_sector(device);
1518               upd765_write_complete(device);
1519            }
1520            else
1521            {
1522               upd765_increment_sector(device);
1523               upd765_write_data(device);
1524            }
1525         }
1526         break;
1527
1528         /* read data, read deleted data */
1529         case 0x0c:
1530         case 0x06:
1531         {
1532
1533            /* read all sectors? */
1534
1535            /* sector id == EOT */
1536            if (upd765_sector_count_complete(device) || upd765_read_data_stop(device))
1537            {
1538               upd765_read_complete(device);
1539            }
1540            else
1541            {
1542               upd765_increment_sector(device);
1543               upd765_read_data(device);
1544            }
1545         }
1546         break;
1547
1548         default:
1549            break;
1550      }
1551   }
1552}
1553
1554
1555static int upd765_get_command_byte_count(device_t *device)
1556{
1557   upd765_t *fdc = get_safe_token(device);
1558   fdc->command = fdc->upd765_command_bytes[0] & 0x01f;
1559
1560   if (fdc->version==TYPE_UPD765A)
1561   {
1562       return upd765_cmd_size[fdc->command];
1563    }
1564   else
1565   {
1566      if (fdc->version==TYPE_UPD72065)
1567      {
1568         switch(fdc->upd765_command_bytes[0])
1569         {
1570            case 0x34: // Reset Standby
1571            case 0x35: // Set Standby
1572            case 0x36: // Software Reset
1573               return 1;
1574            default:
1575               return upd765_cmd_size[fdc->command];
1576         }
1577      }
1578      if (fdc->version==TYPE_SMC37C78)
1579      {
1580         switch (fdc->command)
1581         {
1582            /* version */
1583            case 0x010:
1584               return 1;
1585
1586            /* verify */
1587            case 0x016:
1588               return 9;
1589
1590            /* configure */
1591            case 0x013:
1592               return 4;
1593
1594            /* dumpreg */
1595            case 0x0e:
1596               return 1;
1597
1598            /* perpendicular mode */
1599            case 0x012:
1600               return 1;
1601
1602            /* lock */
1603            case 0x014:
1604               return 1;
1605
1606            /* seek/relative seek are together! */
1607
1608            default:
1609               return upd765_cmd_size[fdc->command];
1610         }
1611      }
1612   }
1613
1614   return upd765_cmd_size[fdc->command];
1615}
1616
1617
1618
1619
1620
1621void upd765_update_state(device_t *device)
1622{
1623   upd765_t *fdc = get_safe_token(device);
1624   switch (fdc->upd765_phase) {
1625   case UPD765_RESULT_PHASE:
1626      /* set data reg */
1627      fdc->upd765_data_reg = fdc->upd765_result_bytes[fdc->upd765_transfer_bytes_count];
1628
1629      if (fdc->upd765_transfer_bytes_count == 0)
1630      {
1631         /* clear int for specific commands */
1632         switch (fdc->command) {
1633         case 2:   /* read a track */
1634         case 5:   /* write data */
1635         case 6:   /* read data */
1636         case 9:   /* write deleted data */
1637         case 10:   /* read id */
1638         case 12:   /* read deleted data */
1639         case 13:   /* format at track */
1640         case 17:   /* scan equal */
1641         case 19:   /* scan low or equal */
1642         case 29:   /* scan high or equal */
1643            upd765_set_int(device, 0);
1644            break;
1645
1646         default:
1647            break;
1648         }
1649      }
1650
1651      if (LOG_VERBOSE)
1652         logerror("UPD765: RESULT: %02x\n", fdc->upd765_data_reg);
1653
1654      fdc->upd765_transfer_bytes_count++;
1655      fdc->upd765_transfer_bytes_remaining--;
1656
1657      if (fdc->upd765_transfer_bytes_remaining==0)
1658      {
1659         upd765_idle(device);
1660      }
1661      else
1662      {
1663         upd765_set_data_request(device);
1664      }
1665      break;
1666
1667   case UPD765_EXECUTION_PHASE_READ:
1668      /* setup data register */
1669      fdc->upd765_data_reg = fdc->execution_phase_data[fdc->upd765_transfer_bytes_count];
1670      fdc->upd765_transfer_bytes_count++;
1671      fdc->upd765_transfer_bytes_remaining--;
1672
1673      if (LOG_EXTRA)
1674         logerror("EXECUTION PHASE READ: %02x\n", fdc->upd765_data_reg);
1675
1676      if ((fdc->upd765_transfer_bytes_remaining==0) || (fdc->upd765_flags & UPD765_TC))
1677      {
1678         fdc->command_timer->adjust(attotime::zero);
1679      }
1680      else
1681      {
1682         /* trigger int */
1683         upd765_setup_timed_data_request(device,1);
1684      }
1685      break;
1686
1687   case UPD765_COMMAND_PHASE_FIRST_BYTE:
1688      fdc->FDC_main |= 0x10;                      /* set BUSY */
1689
1690      if (LOG_VERBOSE)
1691         logerror("%s: upd765(): command=0x%02x\n", device->machine().describe_context(), fdc->upd765_data_reg);
1692
1693      /* seek in progress? */
1694      if (fdc->upd765_flags & UPD765_SEEK_ACTIVE)
1695      {
1696         /* any command results in a invalid - I think that seek, recalibrate and
1697            sense interrupt status may work*/
1698         if (fdc->upd765_data_reg != 8)   /* Sense Interrupt Status */
1699            fdc->upd765_data_reg = 0;
1700      }
1701
1702      fdc->upd765_command_bytes[0] = fdc->upd765_data_reg;
1703
1704      fdc->upd765_transfer_bytes_remaining = upd765_get_command_byte_count(device);
1705
1706      fdc->upd765_transfer_bytes_count = 1;
1707      fdc->upd765_transfer_bytes_remaining--;
1708
1709      if (fdc->upd765_transfer_bytes_remaining==0)
1710      {
1711         upd765_setup_command(device);
1712      }
1713      else
1714      {
1715         /* request more data */
1716         upd765_set_data_request(device);
1717         fdc->upd765_phase = UPD765_COMMAND_PHASE_BYTES;
1718      }
1719        break;
1720
1721    case UPD765_COMMAND_PHASE_BYTES:
1722      if (LOG_VERBOSE)
1723         logerror("%s: upd765(): command=0x%02x\n", device->machine().describe_context(), fdc->upd765_data_reg);
1724
1725      fdc->upd765_command_bytes[fdc->upd765_transfer_bytes_count] = fdc->upd765_data_reg;
1726      fdc->upd765_transfer_bytes_count++;
1727      fdc->upd765_transfer_bytes_remaining--;
1728
1729      if (fdc->upd765_transfer_bytes_remaining==0)
1730      {
1731         upd765_setup_command(device);
1732      }
1733      else
1734      {
1735         /* request more data */
1736         upd765_set_data_request(device);
1737      }
1738      break;
1739
1740    case UPD765_EXECUTION_PHASE_WRITE:
1741      fdc->execution_phase_data[fdc->upd765_transfer_bytes_count]=fdc->upd765_data_reg;
1742      fdc->upd765_transfer_bytes_count++;
1743      fdc->upd765_transfer_bytes_remaining--;
1744
1745      if ((fdc->upd765_transfer_bytes_remaining == 0) || (fdc->upd765_flags & UPD765_TC))
1746      {
1747         fdc->command_timer->adjust(attotime::zero);
1748      }
1749      else
1750      {
1751         upd765_setup_timed_data_request(device,1);
1752      }
1753      break;
1754   }
1755}
1756
1757
1758READ8_DEVICE_HANDLER(upd765_data_r)
1759{
1760   upd765_t *fdc = get_safe_token(device);
1761
1762//  if ((fdc->FDC_main & 0x0c0) == 0x0c0)
1763   if ((fdc->FDC_main & 0x080) == 0x080)
1764   {
1765      if (
1766         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1767         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1768      {
1769
1770         /* reading the data byte clears the interrupt */
1771         upd765_set_int(device,CLEAR_LINE);
1772      }
1773
1774      /* reset data request */
1775      upd765_clear_data_request(device);
1776
1777      /* update state */
1778      upd765_update_state(device);
1779   }
1780
1781   if (LOG_EXTRA)
1782      logerror("DATA R: %02x\n", fdc->upd765_data_reg);
1783
1784   return fdc->upd765_data_reg;
1785}
1786
1787WRITE8_DEVICE_HANDLER(upd765_data_w)
1788{
1789   upd765_t *fdc = get_safe_token(device);
1790
1791   if (LOG_EXTRA)
1792      logerror("DATA W: %02x\n", data);
1793
1794   /* write data to data reg */
1795   fdc->upd765_data_reg = data;
1796
1797   if ((fdc->FDC_main & 0x0c0)==0x080)
1798   {
1799      if (
1800         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_READ) ||
1801         (fdc->upd765_phase == UPD765_EXECUTION_PHASE_WRITE))
1802      {
1803
1804         /* reading the data byte clears the interrupt */
1805         upd765_set_int(device, CLEAR_LINE);
1806      }
1807
1808      /* reset data request */
1809      upd765_clear_data_request(device);
1810
1811      /* update state */
1812      upd765_update_state(device);
1813   }
1814}
1815
1816static void upd765_setup_invalid(device_t *device)
1817{
1818   upd765_t *fdc = get_safe_token(device);
1819
1820   fdc->command = 0;
1821   fdc->upd765_result_bytes[0] = 0x080;
1822   upd765_setup_result_phase(device,1);
1823}
1824
1825static void upd765_setup_command(device_t *device)
1826{
1827   upd765_t *fdc = get_safe_token(device);
1828
1829   static const char *const commands[] =
1830   {
1831      NULL,                  /* [00] */
1832      NULL,                  /* [01] */
1833      "Read Track",            /* [02] */
1834      "Specify",               /* [03] */
1835      "Sense Drive Status",      /* [04] */
1836      "Write Data",            /* [05] */
1837      "Read Data",            /* [06] */
1838      "Recalibrate",            /* [07] */
1839      "Sense Interrupt Status",   /* [08] */
1840      "Write Deleted Data",      /* [09] */
1841      "Read ID",               /* [0A] */
1842      NULL,                  /* [0B] */
1843      "Read Deleted Data",      /* [0C] */
1844      "Format Track",            /* [0D] */
1845      "Dump Registers",         /* [0E] */
1846      "Seek",                  /* [0F] */
1847      "Version",               /* [10] */
1848      NULL,                  /* [11] */
1849      "Perpendicular Mode",      /* [12] */
1850      "Configure",            /* [13] */
1851      "Lock"                  /* [14] */
1852   };
1853
1854   device_t *img;
1855   const char *cmd = NULL;
1856   chrn_id id;
1857
1858   /* if not in dma mode set execution phase bit */
1859   if (!(fdc->upd765_flags & UPD765_DMA_MODE))
1860   {
1861        fdc->FDC_main |= 0x020;              /* execution phase */
1862   }
1863
1864   if (LOG_COMMAND)
1865   {
1866      if ((fdc->upd765_command_bytes[0] & 0x1f) < ARRAY_LENGTH(commands))
1867         cmd = commands[fdc->upd765_command_bytes[0] & 0x1f];
1868      logerror("upd765_setup_command(): Setting up command 0x%02X (%s)\n",
1869         fdc->upd765_command_bytes[0] & 0x1f, cmd ? cmd : "???");
1870   }
1871
1872   switch (fdc->upd765_command_bytes[0] & 0x1f)
1873   {
1874      case 0x03:      /* specify */
1875         /* setup step rate */
1876         fdc->srt_in_ms = 16-((fdc->upd765_command_bytes[1]>>4) & 0x0f);
1877
1878         fdc->upd765_flags &= ~UPD765_DMA_MODE;
1879
1880         if ((fdc->upd765_command_bytes[2] & 0x01)==0)
1881         {
1882            fdc->upd765_flags |= UPD765_DMA_MODE;
1883         }
1884
1885         upd765_idle(device);
1886         break;
1887
1888      case 0x04:  /* sense drive status */
1889         upd765_setup_drive_and_side(device);
1890         img = current_image(device);
1891
1892         fdc->upd765_status[3] = fdc->drive | (fdc->side<<2);
1893
1894         if (img)
1895         {
1896            fdc->upd765_status[3] |= !floppy_tk00_r(img) << 4;
1897            fdc->upd765_status[3] |= !floppy_wpt_r(img) << 6;
1898
1899            if (upd765_get_rdy(device))
1900            {
1901               fdc->upd765_status[3] |= 0x20;
1902            }
1903         }
1904
1905         fdc->upd765_status[3] |= 0x08;
1906
1907         /* two side and fault not set but should be? */
1908         fdc->upd765_result_bytes[0] = fdc->upd765_status[3];
1909         upd765_setup_result_phase(device,1);
1910         break;
1911
1912      case 0x07:          /* recalibrate */
1913         upd765_seek_setup(device, 1);
1914         break;
1915
1916      case 0x0f:          /* seek */
1917         upd765_seek_setup(device, 0);
1918         break;
1919
1920      case 0x0a:      /* read id */
1921         upd765_setup_drive_and_side(device);
1922         img = current_image(device);
1923
1924         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
1925         fdc->upd765_status[1] = 0;
1926         fdc->upd765_status[2] = 0;
1927
1928         /* drive ready? */
1929         if (upd765_get_rdy(device))
1930         {
1931            /* is disk inserted? */
1932            device_image_interface *image = dynamic_cast<device_image_interface *>( img);
1933            if (image->exists())
1934            {
1935               int index_count = 0;
1936
1937               /* floppy drive is ready and disc is inserted */
1938
1939               /* this is the id that appears when a disc is not formatted */
1940               /* to be checked on Amstrad */
1941               id.C = 0;
1942               id.H = 0;
1943               id.R = 0x01;
1944               id.N = 0x02;
1945
1946               /* repeat for two index counts before quitting */
1947               do
1948               {
1949                  /* get next id from disc */
1950                  if (floppy_drive_get_next_id(img, fdc->side, &id))
1951                  {
1952                     /* got an id - quit */
1953                     break;
1954                  }
1955
1956                  if (floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))
1957                  {
1958                     /* update index count */
1959                     index_count++;
1960                  }
1961               }
1962               while (index_count!=2);
1963
1964               /* at this point, we have seen a id or two index pulses have occured! */
1965               fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1966               fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1967               fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1968               fdc->upd765_result_bytes[3] = id.C; /* C */
1969               fdc->upd765_result_bytes[4] = id.H; /* H */
1970               fdc->upd765_result_bytes[5] = id.R; /* R */
1971               fdc->upd765_result_bytes[6] = id.N; /* N */
1972
1973               upd765_setup_result_phase(device,7);
1974            }
1975            else
1976            {
1977               /* floppy drive is ready, but no disc is inserted */
1978               /* this occurs on the PC */
1979               /* in this case, the command never quits! */
1980               /* there are no index pulses to stop the command! */
1981            }
1982         }
1983         else
1984         {
1985            /* what are id values when drive not ready? */
1986
1987            /* not ready, abnormal termination */
1988            fdc->upd765_status[0] |= (1<<3) | (1<<6);
1989            fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
1990            fdc->upd765_result_bytes[1] = fdc->upd765_status[1];
1991            fdc->upd765_result_bytes[2] = fdc->upd765_status[2];
1992            fdc->upd765_result_bytes[3] = 0; /* C */
1993            fdc->upd765_result_bytes[4] = 0; /* H */
1994            fdc->upd765_result_bytes[5] = 0; /* R */
1995            fdc->upd765_result_bytes[6] = 0; /* N */
1996         }
1997         break;
1998
1999
2000      case 0x08: /* sense interrupt status */
2001         /* interrupt pending? */
2002         if (fdc->upd765_flags & UPD765_INT)
2003         {
2004            /* yes. Clear int */
2005            upd765_set_int(device, CLEAR_LINE);
2006
2007            /* clear drive seek bits */
2008            fdc->FDC_main &= ~(1 | 2 | 4 | 8);
2009
2010            /* return status */
2011            fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2012            /* return pcn */
2013            fdc->upd765_result_bytes[1] = fdc->pcn[fdc->drive];
2014
2015            /* return result */
2016            upd765_setup_result_phase(device,2);
2017         }
2018         else
2019         {
2020            if(fdc->version == TYPE_UPD72065 && (fdc->FDC_main & 0x0f) == 0x00)
2021            {  // based on XM6
2022               upd765_setup_invalid(device);
2023            }
2024            else
2025            {
2026               /* no int */
2027               fdc->upd765_result_bytes[0] = 0x80;
2028               /* return pcn */
2029               fdc->upd765_result_bytes[1] = fdc->pcn[fdc->drive];
2030
2031               /* return result */
2032               upd765_setup_result_phase(device,2);
2033            }
2034         }
2035         break;
2036
2037      case 0x06:  /* read data */
2038         upd765_setup_drive_and_side(device);
2039
2040         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2041         fdc->upd765_status[1] = 0;
2042         fdc->upd765_status[2] = 0;
2043
2044         upd765_read_data(device);
2045         break;
2046
2047      case 0x0c:
2048         /* read deleted data */
2049         upd765_setup_drive_and_side(device);
2050
2051         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2052         fdc->upd765_status[1] = 0;
2053         fdc->upd765_status[2] = 0;
2054
2055         /* .. for now */
2056         upd765_read_data(device);
2057         break;
2058
2059      case 0x09:
2060         /* write deleted data */
2061         upd765_setup_drive_and_side(device);
2062
2063         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2064         fdc->upd765_status[1] = 0;
2065         fdc->upd765_status[2] = 0;
2066
2067         /* ... for now */
2068         upd765_write_data(device);
2069         break;
2070
2071      case 0x02:
2072         /* read a track */
2073         upd765_setup_drive_and_side(device);
2074         img = current_image(device);
2075         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2076         fdc->upd765_status[1] = 0;
2077         fdc->upd765_status[2] = 0;
2078
2079         fdc->upd765_status[0] |= UPD765_ST1_NO_DATA;
2080
2081         /* wait for index */
2082         do
2083         {
2084            /* get next id from disc */
2085            floppy_drive_get_next_id(img, fdc->side,&id);
2086         }
2087         while ((floppy_drive_get_flag_state(img, FLOPPY_DRIVE_INDEX))==0);
2088
2089         fdc->sector_counter = 0;
2090
2091         upd765_read_a_track(device);
2092         break;
2093
2094      case 0x05:  /* write data */
2095         upd765_setup_drive_and_side(device);
2096
2097         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2098         fdc->upd765_status[1] = 0;
2099         fdc->upd765_status[2] = 0;
2100
2101         upd765_write_data(device);
2102         break;
2103
2104      case 0x0d:   /* format a track */
2105         upd765_setup_drive_and_side(device);
2106
2107         fdc->upd765_status[0] = fdc->drive | (fdc->side<<2);
2108         fdc->upd765_status[1] = 0;
2109         fdc->upd765_status[2] = 0;
2110
2111         fdc->sector_counter = 0;
2112
2113         upd765_format_track(device);
2114         break;
2115
2116      default:   /* invalid */
2117         switch (fdc->version)
2118         {
2119            case TYPE_UPD765A:
2120               upd765_setup_invalid(device);
2121               break;
2122
2123            case TYPE_UPD765B:
2124               /* from upd765b data sheet */
2125               if ((fdc->upd765_command_bytes[0] & 0x01f)==0x010)
2126               {
2127                  /* version */
2128                  fdc->upd765_status[0] = 0x090;
2129                  fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2130                  upd765_setup_result_phase(device,1);
2131               }
2132               break;
2133
2134            case TYPE_UPD72065:
2135               switch(fdc->upd765_command_bytes[0] & 0x3f)
2136               {
2137                  case 0x36:  // Software Reset
2138                     upd765_reset(device,0);
2139                     upd765_idle(device);
2140                     if(LOG_COMMAND)
2141                        logerror("upd72065: command - Software Reset\n");
2142                     break;
2143                  default:
2144                     upd765_setup_invalid(device);
2145                     break;
2146               }
2147               break;
2148
2149            case TYPE_SMC37C78:
2150               /* TO BE COMPLETED!!! !*/
2151               switch (fdc->upd765_command_bytes[0] & 0x1f)
2152               {
2153                  case 0x10:      /* version */
2154                     fdc->upd765_status[0] = 0x90;
2155                     fdc->upd765_result_bytes[0] = fdc->upd765_status[0];
2156                     upd765_setup_result_phase(device,1);
2157                     break;
2158
2159                  case 0x13:      /* configure */
2160                     upd765_idle(device);
2161                     break;
2162
2163                  case 0x0e:      /* dump reg */
2164                     fdc->upd765_result_bytes[0] = fdc->pcn[0];
2165                     fdc->upd765_result_bytes[1] = fdc->pcn[1];
2166                     fdc->upd765_result_bytes[2] = fdc->pcn[2];
2167                     fdc->upd765_result_bytes[3] = fdc->pcn[3];
2168
2169                     upd765_setup_result_phase(device,10);
2170                     break;
2171
2172                  case 0x12:      /* perpendicular mode */
2173                     upd765_idle(device);
2174                     break;
2175
2176                  case 0x14:      /* lock */
2177                     upd765_setup_result_phase(device,1);
2178                     break;
2179               }
2180               break;
2181         }
2182   }
2183}
2184
2185
2186/* dma acknowledge write */
2187WRITE8_DEVICE_HANDLER(upd765_dack_w)
2188{
2189   /* clear request */
2190   upd765_set_dma_drq(device, CLEAR_LINE);
2191
2192   /* write data */
2193   upd765_data_w(device, offset, data);
2194}
2195
2196READ8_DEVICE_HANDLER(upd765_dack_r)
2197{
2198   /* clear data request */
2199   upd765_set_dma_drq(device,CLEAR_LINE);
2200
2201   /* read data */
2202   return upd765_data_r(device, offset);
2203}
2204
2205static TIMER_CALLBACK( interrupt_callback )
2206{
2207   device_t* device = (device_t*)ptr;
2208   upd765_set_int(device, 1);
2209}
2210
2211void upd765_reset(device_t *device, int offset)
2212{
2213   upd765_t *fdc = get_safe_token(device);
2214
2215   /* upd765 in idle state - ready to accept commands */
2216   upd765_idle(device);
2217
2218   /* set int low */
2219   upd765_set_int(device, 0);
2220   /* set dma drq output */
2221   upd765_set_dma_drq(device,0);
2222
2223   /* tandy 100hx assumes that after NEC is reset, it is in DMA mode */
2224   fdc->upd765_flags |= UPD765_DMA_MODE;
2225
2226   /* if ready input is set during reset generate an int */
2227   if (fdc->upd765_flags & UPD765_FDD_READY)
2228   {
2229      int i;
2230      int a_drive_is_ready;
2231
2232      fdc->upd765_status[0] = 0x080 | 0x040;
2233
2234      /* for the purpose of pc-xt. If any of the drives have a disk inserted,
2235        do not set not-ready - need to check with pc_fdc->c whether all drives
2236        are checked or only the drive selected with the drive select bits?? */
2237
2238      a_drive_is_ready = 0;
2239      for (i = 0; i < 4; i++)
2240      {
2241         if (fdc->intf->floppy_drive_tags[i]!=NULL)
2242         {
2243            device_t *img;
2244
2245            if (device->owner() != NULL)
2246               img = device->owner()->subdevice(fdc->intf->floppy_drive_tags[i]);
2247            else
2248               img = device->machine().device(fdc->intf->floppy_drive_tags[i]);
2249
2250            device_image_interface *image = dynamic_cast<device_image_interface *>( img);
2251            if (image->exists())
2252            {
2253               a_drive_is_ready = 1;
2254               break;
2255            }
2256         }
2257
2258      }
2259
2260      if (!a_drive_is_ready && fdc->intf->rdy_pin == UPD765_RDY_PIN_CONNECTED )
2261      {
2262         fdc->upd765_status[0] |= 0x08;
2263      }
2264
2265      device->machine().scheduler().timer_set(attotime::from_usec(5), FUNC(interrupt_callback),0,device);
2266   }
2267}
2268
2269WRITE_LINE_DEVICE_HANDLER( upd765_reset_w )
2270{
2271   upd765_t *fdc = get_safe_token(device);
2272
2273   int flags;
2274
2275   /* get previous reset state */
2276   flags = fdc->upd765_flags;
2277
2278   /* set new reset state */
2279   /* clear reset */
2280   fdc->upd765_flags &= ~UPD765_RESET;
2281
2282   /* reset */
2283   if (state)
2284   {
2285      fdc->upd765_flags |= UPD765_RESET;
2286
2287      upd765_set_int(device, 0);
2288   }
2289
2290   /* reset changed state? */
2291   if (((flags^fdc->upd765_flags) & UPD765_RESET)!=0)
2292   {
2293      /* yes */
2294
2295      /* no longer reset */
2296      if ((fdc->upd765_flags & UPD765_RESET)==0)
2297      {
2298         /* reset nec */
2299         upd765_reset(device, 0);
2300      }
2301   }
2302}
2303
2304
2305WRITE_LINE_DEVICE_HANDLER( upd765_ready_w )
2306{
2307   upd765_t *fdc = get_safe_token(device);
2308
2309   /* clear ready state */
2310   fdc->upd765_flags &= ~UPD765_FDD_READY;
2311
2312   if (state)
2313   {
2314      fdc->upd765_flags |= UPD765_FDD_READY;
2315   }
2316}
2317
2318
2319/* Device Interface */
2320
2321static void common_start(device_t *device, int device_type)
2322{
2323   upd765_t *fdc = get_safe_token(device);
2324   // validate arguments
2325
2326   assert(device != NULL);
2327   assert(device->tag() != NULL);
2328   assert(device->static_config() != NULL);
2329
2330   fdc->intf = (const upd765_interface*)device->static_config();
2331
2332   fdc->version = (UPD765_VERSION)device_type;
2333   fdc->timer = device->machine().scheduler().timer_alloc(FUNC(upd765_timer_callback), (void*)device);
2334   fdc->seek_timer = device->machine().scheduler().timer_alloc(FUNC(upd765_seek_timer_callback), (void*)device);
2335   fdc->command_timer = device->machine().scheduler().timer_alloc(FUNC(upd765_continue_command), (void*)device);
2336
2337   fdc->upd765_flags &= UPD765_FDD_READY;
2338   fdc->data_buffer = auto_alloc_array(device->machine(), char, 32*1024);
2339
2340   fdc->out_int_func.resolve(fdc->intf->out_int_func, *device);
2341   fdc->out_drq_func.resolve(fdc->intf->out_drq_func, *device);
2342
2343   // register for state saving
2344   //state_save_register_item(device->machine(), "upd765", device->tag(), 0, upd765->number);
2345}
2346
2347static DEVICE_START( upd765a )
2348{
2349   common_start(device, TYPE_UPD765A);
2350}
2351
2352static DEVICE_START( upd765b )
2353{
2354   common_start(device, TYPE_UPD765B);
2355}
2356
2357static DEVICE_START( smc37c78 )
2358{
2359   common_start(device, TYPE_SMC37C78);
2360}
2361
2362static DEVICE_START( upd72065 )
2363{
2364   common_start(device, TYPE_UPD72065);
2365}
2366
2367static DEVICE_RESET( upd765 )
2368{
2369   int i;
2370   upd765_t *fdc = get_safe_token(device);
2371   for (i = 0; i < 4; i++) {
2372      if (fdc->intf->floppy_drive_tags[i]!=NULL)
2373      {
2374         device_t *img;
2375
2376         if (device->owner() != NULL)
2377            img = device->owner()->subdevice(fdc->intf->floppy_drive_tags[i]);
2378         else
2379            img = device->machine().device(fdc->intf->floppy_drive_tags[i]);
2380
2381         floppy_drive_set_controller(img, device);
2382         floppy_drive_set_ready_state_change_callback(img, upd765_set_ready_change_callback);
2383      }
2384   }
2385
2386   upd765_reset(device,0);
2387}
2388
2389DEVICE_GET_INFO( upd765a )
2390{
2391   switch (state)
2392   {
2393      /* --- the following bits of info are returned as 64-bit signed integers --- */
2394      case DEVINFO_INT_TOKEN_BYTES:               info->i = sizeof(upd765_t);               break;
2395      case DEVINFO_INT_INLINE_CONFIG_BYTES:         info->i = 0;                        break;
2396
2397      /* --- the following bits of info are returned as pointers to data or functions --- */
2398      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd765a);   break;
2399      case DEVINFO_FCT_STOP:                     /* Nothing */                        break;
2400      case DEVINFO_FCT_RESET:                     info->reset = DEVICE_RESET_NAME(upd765);   break;
2401
2402      /* --- the following bits of info are returned as NULL-terminated strings --- */
2403      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD765A");                  break;
2404      case DEVINFO_STR_FAMILY:                  strcpy(info->s, "UPD765A");                  break;
2405      case DEVINFO_STR_VERSION:                  strcpy(info->s, "1.0");                     break;
2406      case DEVINFO_STR_SOURCE_FILE:               strcpy(info->s, __FILE__);                     break;
2407      case DEVINFO_STR_CREDITS:                  strcpy(info->s, "Copyright MESS Team");         break;
2408   }
2409}
2410
2411
2412DEVICE_GET_INFO( upd765b )
2413{
2414   switch (state)
2415   {
2416      /* --- the following bits of info are returned as NULL-terminated strings --- */
2417      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD765B");            break;
2418
2419      /* --- the following bits of info are returned as pointers to data or functions --- */
2420      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd765b);   break;
2421
2422      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2423   }
2424}
2425
2426DEVICE_GET_INFO( smc37c78 )
2427{
2428   switch (state)
2429   {
2430      /* --- the following bits of info are returned as NULL-terminated strings --- */
2431      case DEVINFO_STR_NAME:                     strcpy(info->s, "SMC37C78");            break;
2432
2433      /* --- the following bits of info are returned as pointers to data or functions --- */
2434      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(smc37c78);   break;
2435
2436      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2437   }
2438}
2439
2440DEVICE_GET_INFO( upd72065 )
2441{
2442   switch (state)
2443   {
2444      /* --- the following bits of info are returned as NULL-terminated strings --- */
2445      case DEVINFO_STR_NAME:                     strcpy(info->s, "UPD72065");            break;
2446
2447      /* --- the following bits of info are returned as pointers to data or functions --- */
2448      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(upd72065);   break;
2449
2450      default:                              DEVICE_GET_INFO_CALL(upd765a);            break;
2451   }
2452}
2453
2454DEFINE_LEGACY_DEVICE(UPD765A, upd765a);
2455DEFINE_LEGACY_DEVICE(UPD765B, upd765b);
2456DEFINE_LEGACY_DEVICE(SMC37C78, smc37c78);
2457DEFINE_LEGACY_DEVICE(UPD72065, upd72065);
src/mess/machine/upd765.h
r11450r11451
1/***************************************************************************
2
3    machine/upd765.h
4
5    Functions to emulate a NEC upd765/Intel 8272 compatible
6    floppy disk controller
7
8***************************************************************************/
9
10#ifndef __UPD765_H__
11#define __UPD765_H__
12
13#include "devcb.h"
14#include "imagedev/flopdrv.h"
15
16
17/***************************************************************************
18    MACROS
19***************************************************************************/
20
21DECLARE_LEGACY_DEVICE(UPD765A, upd765a);
22DECLARE_LEGACY_DEVICE(UPD765B, upd765b);
23DECLARE_LEGACY_DEVICE(SMC37C78, smc37c78);
24DECLARE_LEGACY_DEVICE(UPD72065, upd72065);
25
26/***************************************************************************
27    TYPE DEFINITIONS
28***************************************************************************/
29
30/* RDY pin connected state */
31typedef enum
32{
33   UPD765_RDY_PIN_NOT_CONNECTED = 0,
34   UPD765_RDY_PIN_CONNECTED = 1
35} UPD765_RDY_PIN;
36
37#define UPD765_DAM_DELETED_DATA 0x0f8
38#define UPD765_DAM_DATA 0x0fb
39
40typedef device_t *(*upd765_get_image_func)(device_t *device, int floppy_index);
41#define UPD765_GET_IMAGE(name)   device_t *name(device_t *device, int floppy_index )
42
43
44typedef struct upd765_interface
45{
46   /* interrupt issued */
47   devcb_write_line out_int_func;
48
49   /* dma data request */
50   devcb_write_line out_drq_func;
51
52   /* image lookup */
53   upd765_get_image_func get_image;
54
55   UPD765_RDY_PIN rdy_pin;
56
57   const char *floppy_drive_tags[4];
58} upd765_interface;
59
60
61/***************************************************************************
62    FUNCTION PROTOTYPES
63***************************************************************************/
64
65/* read of data register */
66READ8_DEVICE_HANDLER(upd765_data_r);
67/* write to data register */
68WRITE8_DEVICE_HANDLER(upd765_data_w);
69/* read of main status register */
70READ8_DEVICE_HANDLER(upd765_status_r);
71
72/* dma acknowledge with write */
73WRITE8_DEVICE_HANDLER(upd765_dack_w);
74/* dma acknowledge with read */
75READ8_DEVICE_HANDLER(upd765_dack_r);
76
77/* reset upd765 */
78void upd765_reset(device_t *device, int);
79
80/* reset pin of upd765 */
81WRITE_LINE_DEVICE_HANDLER(upd765_reset_w);
82
83/* set upd765 terminal count input state */
84WRITE_LINE_DEVICE_HANDLER(upd765_tc_w);
85
86/* set upd765 ready input*/
87WRITE_LINE_DEVICE_HANDLER(upd765_ready_w);
88
89void upd765_idle(device_t *device);
90
91/*********************/
92/* STATUS REGISTER 1 */
93
94/* this is set if a TC signal was not received after the sector data was read */
95#define UPD765_ST1_END_OF_CYLINDER (1<<7)
96/* this is set if the sector ID being searched for is not found */
97#define UPD765_ST1_NO_DATA (1<<2)
98/* set if disc is write protected and a write/format operation was performed */
99#define UPD765_ST1_NOT_WRITEABLE (1<<1)
100
101/*********************/
102/* STATUS REGISTER 2 */
103
104/* C parameter specified did not match C value read from disc */
105#define UPD765_ST2_WRONG_CYLINDER (1<<4)
106/* C parameter specified did not match C value read from disc, and C read from disc was 0x0ff */
107#define UPD765_ST2_BAD_CYLINDER (1<<1)
108/* this is set if the FDC encounters a Deleted Data Mark when executing a read data
109command, or FDC encounters a Data Mark when executing a read deleted data command */
110#define UPD765_ST2_CONTROL_MARK (1<<6)
111
112/***************************************************************************
113    DEVICE CONFIGURATION MACROS
114***************************************************************************/
115
116#define MCFG_UPD765A_ADD(_tag, _intrf) \
117   MCFG_DEVICE_ADD(_tag, UPD765A, 0) \
118   MCFG_DEVICE_CONFIG(_intrf)
119
120#define MCFG_UPD765A_MODIFY(_tag, _intrf) \
121  MCFG_DEVICE_MODIFY(_tag)         \
122  MCFG_DEVICE_CONFIG(_intrf)
123
124#define MCFG_UPD765A_REMOVE(_tag)      \
125  MCFG_DEVICE_REMOVE(_tag)
126
127#define MCFG_UPD765B_ADD(_tag, _intrf) \
128   MCFG_DEVICE_ADD(_tag, UPD765B, 0) \
129   MCFG_DEVICE_CONFIG(_intrf)
130
131#define MCFG_UPD765B_MODIFY(_tag, _intrf) \
132  MCFG_DEVICE_MODIFY(_tag)         \
133  MCFG_DEVICE_CONFIG(_intrf)
134
135#define MCFG_UPD765B_REMOVE(_tag)      \
136  MCFG_DEVICE_REMOVE(_tag)
137
138#define MCFG_SMC37C78_ADD(_tag, _intrf) \
139   MCFG_DEVICE_ADD(_tag, SMC37C78, 0) \
140   MCFG_DEVICE_CONFIG(_intrf)
141
142#define MCFG_SMC37C78_MODIFY(_tag, _intrf) \
143  MCFG_DEVICE_MODIFY(_tag)         \
144  MCFG_DEVICE_CONFIG(_intrf)
145
146#define MCFG_SMC37C78_REMOVE(_tag)      \
147  MCFG_DEVICE_REMOVE(_tag)
148
149#define MCFG_UPD72065_ADD(_tag, _intrf) \
150   MCFG_DEVICE_ADD(_tag, UPD72065, 0) \
151   MCFG_DEVICE_CONFIG(_intrf)
152
153#define MCFG_UPD72065_MODIFY(_tag, _intrf) \
154  MCFG_DEVICE_MODIFY(_tag)         \
155  MCFG_DEVICE_CONFIG(_intrf)
156
157#define MCFG_UPD72065_REMOVE(_tag)      \
158  MCFG_DEVICE_REMOVE(_tag)
159
160
161#endif /* __UPD765_H__ */
src/mess/machine/serial.c
r11450r11451
1/* internal serial transmission */
2
3/* select a file on host filesystem to transfer using serial method,
4setup serial interface software in driver and let the transfer begin */
5
6/* this is used in the Amstrad NC Notepad emulation */
7
8
9
10/*
11
12    the output starts at 1 level. It changes to 0 when the start bit has been transmitted.
13    This therefore signals that data is following.
14    When all data bits have been received, stop bits are transmitted with a value of 1.
15
16    msm8251 expects this in asynchronous mode:
17    packet format:
18
19    bit count           function        value
20    1                   start bit       0
21    note 1              data bits       x
22    note 2              parity bit      x
23    note 3              stop bits       1
24
25    Note:
26    1. Data size can be defined (usual value is 8)
27    2. Parity bit (if parity is set to odd or even). Value of bit
28        is defined by data parity.
29    3. There should be at least 1 stop bit.
30*/
31
32#include "emu.h"
33#include "serial.h"
34
35
36#define VERBOSE 0
37#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
38
39/* a read/write bit stream. used to transmit data and to receive data */
40typedef struct _data_stream data_stream;
41struct _data_stream
42{
43   /* pointer to buffer */
44   unsigned char *pData;
45   /* length of buffer */
46   unsigned long DataLength;
47
48   /* bit offset within current byte */
49   unsigned long BitCount;
50   /* byte offset within data */
51   unsigned long ByteCount;
52};
53
54typedef struct _serial_t serial_t;
55struct _serial_t
56{
57   /* transmit data bit-stream */
58   data_stream transmit;
59   /* receive data bit-stream */
60   data_stream receive;
61
62   /* register to receive data */
63   serial_receive_register   receive_reg;
64   /* register to transmit data */
65   serial_transmit_register transmit_reg;
66
67   /* connection to transmit/receive data over */
68   serial_connection connection;
69
70   /* data form to transmit/receive */
71   data_form form;
72
73   int transmit_state;
74
75   /* baud rate */
76   unsigned long BaudRate;
77
78   /* baud rate timer */
79   emu_timer   *timer;
80};
81
82INLINE serial_t *get_safe_token(device_t *device)
83{
84   assert(device != NULL);
85   //assert(device->type() == SERIAL);
86
87   return (serial_t *)downcast<legacy_device_base *>(device)->token();
88}
89
90
91/* the serial streams */
92static TIMER_CALLBACK(serial_device_baud_rate_callback);
93
94
95/*********************************************************/
96
97static unsigned char serial_parity_table[256];
98
99void serial_helper_setup(void)
100{
101   int i;
102
103   /* if sum of all bits in the byte is even, then the data
104    has even parity, otherwise it has odd parity */
105   for (i=0; i<256; i++)
106   {
107      int data;
108      int sum;
109      int b;
110
111      sum = 0;
112      data = i;
113
114      for (b=0; b<8; b++)
115      {
116         sum+=data & 0x01;
117
118         data = data>>1;
119      }
120
121      serial_parity_table[i] = sum & 0x01;
122   }
123}
124
125static unsigned char serial_helper_get_parity(unsigned char data)
126{
127   return serial_parity_table[data & 0x0ff];
128}
129
130static void serial_device_in_callback(running_machine &machine, int id, unsigned long status)
131{
132/*  serial_t *ser = get_safe_token(device);
133
134    ser->connection.input_state = status;*/
135}
136
137/***** SERIAL DEVICE ******/
138void serial_device_setup(device_t *device, int baud_rate, int num_data_bits, int stop_bit_count, int parity_code)
139{
140   serial_t *ser = get_safe_token(device);
141
142   ser->BaudRate = baud_rate;
143   ser->form.word_length = num_data_bits;
144   ser->form.stop_bit_count = stop_bit_count;
145   ser->form.parity = parity_code;
146   ser->timer = device->machine().scheduler().timer_alloc(FUNC(serial_device_baud_rate_callback), (void *)device);
147
148   serial_connection_init(device->machine(),&ser->connection);
149   serial_connection_set_in_callback(device->machine(),&ser->connection, serial_device_in_callback);
150
151   /* signal to other end it is clear to send! */
152   /* data is initially high state */
153   /* set /rts */
154   ser->connection.State |= SERIAL_STATE_RTS;
155   /* signal to other end data is ready to be accepted */
156   /* set /dtr */
157   ser->connection.State |= SERIAL_STATE_DTR;
158   set_out_data_bit(ser->connection.State, 1);
159   serial_connection_out(device->machine(),&ser->connection);
160   transmit_register_reset(&ser->transmit_reg);
161   receive_register_reset(&ser->receive_reg);
162   receive_register_setup(&ser->receive_reg, &ser->form);
163}
164
165
166unsigned long serial_device_get_state(device_t *device)
167{
168   serial_t *ser = get_safe_token(device);
169
170   return ser->connection.State;
171}
172
173void serial_device_set_transmit_state(device_t *device, int state)
174{
175   int previous_state;
176   serial_t *ser = get_safe_token(device);
177
178   previous_state = ser->transmit_state;
179
180   ser->transmit_state = state;
181
182   if ((state^previous_state)!=0)
183   {
184      if (state)
185      {
186         /* start timer */
187         ser->timer->adjust(attotime::zero, 0, attotime::from_hz(ser->BaudRate));
188      }
189      else
190      {
191         /* remove timer */
192         ser->timer->reset();
193      }
194   }
195
196}
197
198/* get a bit from input stream */
199static int data_stream_get_data_bit_from_data_byte(data_stream *stream)
200{
201   int data_bit;
202   int data_byte;
203
204   if (stream->ByteCount<stream->DataLength)
205   {
206      /* get data from buffer */
207      data_byte= stream->pData[stream->ByteCount];
208   }
209   else
210   {
211      /* over end of buffer, so return 0 */
212      data_byte= 0;
213   }
214
215   /* get bit from data */
216   data_bit = (data_byte>>(7-stream->BitCount)) & 0x01;
217
218   /* update bit count */
219   stream->BitCount++;
220   /* ripple overflow onto byte count */
221   stream->ByteCount+=stream->BitCount>>3;
222   /* lock bit count into range */
223   stream->BitCount &=0x07;
224
225   /* do not let it read over end of data */
226   if (stream->ByteCount>=stream->DataLength)
227   {
228      stream->ByteCount = stream->DataLength-1;
229   }
230
231   return data_bit;
232}
233
234
235void receive_register_setup(serial_receive_register *receive, data_form *data_form)
236{
237   receive->bit_count = data_form->word_length + data_form->stop_bit_count;
238
239   if (data_form->parity != SERIAL_PARITY_NONE)
240   {
241      receive->bit_count++;
242   }
243}
244
245
246/* this is generic code to be used in serial chip implementations */
247/* the majority of serial chips work in the same way and this code will work */
248/* for them */
249
250/* receive a bit */
251void receive_register_update_bit(serial_receive_register *receive, int bit)
252{
253   int previous_bit;
254
255   LOG(("receive register receive bit: %1x\n",bit));
256   previous_bit = receive->register_data & 1;
257
258   /* shift previous bit 7 out */
259   receive->register_data = receive->register_data<<1;
260   /* shift new bit in */
261   receive->register_data = (receive->register_data & 0xfffe) | bit;
262   /* update bit count received */
263   receive->bit_count_received++;
264
265   /* asyncrhonouse mode */
266   if (receive->flags & RECEIVE_REGISTER_WAITING_FOR_START_BIT)
267   {
268      /* the previous bit is stored in uart.receive char bit 0 */
269      /* has the bit state changed? */
270      if (((previous_bit ^ bit) & 0x01)!=0)
271      {
272         /* yes */
273         if (bit==0)
274         {
275            //logerror("receive register saw start bit\n");
276
277            /* seen start bit! */
278            /* not waiting for start bit now! */
279            receive->flags &=~RECEIVE_REGISTER_WAITING_FOR_START_BIT;
280            receive->flags |=RECEIVE_REGISTER_SYNCHRONISED;
281            /* reset bit count received */
282            receive->bit_count_received = 0;
283         }
284      }
285   }
286   else
287   if (receive->flags & RECEIVE_REGISTER_SYNCHRONISED)
288   {
289      /* received all bits? */
290      if (receive->bit_count_received==receive->bit_count)
291      {
292         receive->bit_count_received = 0;
293         receive->flags &=~RECEIVE_REGISTER_SYNCHRONISED;
294         receive->flags |= RECEIVE_REGISTER_WAITING_FOR_START_BIT;
295         //logerror("receive register full\n");
296         receive->flags |= RECEIVE_REGISTER_FULL;
297      }
298   }
299}
300
301void receive_register_reset(serial_receive_register *receive_reg)
302{
303   receive_reg->bit_count_received = 0;
304   receive_reg->flags &=~RECEIVE_REGISTER_FULL;
305   receive_reg->flags &=~RECEIVE_REGISTER_SYNCHRONISED;
306   receive_reg->flags |= RECEIVE_REGISTER_WAITING_FOR_START_BIT;
307}
308
309void receive_register_extract(serial_receive_register *receive_reg, data_form *data_form)
310{
311   unsigned long data_shift;
312   UINT8 data;
313
314   receive_register_reset(receive_reg);
315
316   data_shift = 0;
317
318   /* if parity is even or odd, there should be a parity bit in the stream! */
319   if (data_form->parity!=SERIAL_PARITY_NONE)
320   {
321      data_shift++;
322   }
323
324   data_shift+=data_form->stop_bit_count;
325
326   /* strip off stop bits and parity */
327   data = receive_reg->register_data>>data_shift;
328
329   /* mask off other bits so data byte has 0's in unused bits */
330   data = data & (0x0ff
331      >>
332      (8-(data_form->word_length)));
333
334   receive_reg->byte_received  = data;
335
336   /* parity enable? */
337   switch (data_form->parity)
338   {
339      case SERIAL_PARITY_NONE:
340         break;
341
342      /* check parity */
343      case SERIAL_PARITY_ODD:
344      case SERIAL_PARITY_EVEN:
345      {
346         //unsigned char computed_parity;
347         //unsigned char parity_received;
348
349         /* get state of parity bit received */
350         //parity_received = (receive_reg->register_data>>data_form->stop_bit_count) & 0x01;
351
352         /* compute parity for received bits */
353         //computed_parity = serial_helper_get_parity(data);
354
355         if (data_form->parity == SERIAL_PARITY_ODD)
356         {
357            /* odd parity */
358
359
360         }
361         else
362         {
363            /* even parity */
364
365
366         }
367
368      }
369      break;
370   }
371}
372
373/***** TRANSMIT REGISTER *****/
374
375void transmit_register_reset(serial_transmit_register *transmit_reg)
376{
377   transmit_reg->flags |=TRANSMIT_REGISTER_EMPTY;
378}
379
380/* used to construct data in stream format */
381static void transmit_register_add_bit(serial_transmit_register *transmit_reg, int bit)
382{
383   /* combine bit */
384   transmit_reg->register_data = transmit_reg->register_data<<1;
385   transmit_reg->register_data &=~1;
386   transmit_reg->register_data|=(bit & 0x01);
387   transmit_reg->bit_count++;
388}
389
390
391/* generate data in stream format ready for transfer */
392void transmit_register_setup(serial_transmit_register *transmit_reg, data_form *data_form,unsigned char data_byte)
393{
394   int i;
395   unsigned char transmit_data;
396
397
398   transmit_reg->bit_count_transmitted = 0;
399   transmit_reg->bit_count = 0;
400   transmit_reg->flags &=~TRANSMIT_REGISTER_EMPTY;
401
402   /* start bit */
403   transmit_register_add_bit(transmit_reg,0);
404
405   /* data bits */
406   transmit_data = data_byte;
407   for (i=0; i<data_form->word_length; i++)
408   {
409      int databit;
410
411      /* get bit from data */
412      databit = (transmit_data>>(data_form->word_length-1)) & 0x01;
413      /* add bit to formatted byte */
414      transmit_register_add_bit(transmit_reg, databit);
415      transmit_data = transmit_data<<1;
416   }
417
418   /* parity */
419   if (data_form->parity!=SERIAL_PARITY_NONE)
420   {
421      /* odd or even parity */
422      unsigned char parity;
423
424      /* get parity */
425      /* if parity = 0, data has even parity - i.e. there is an even number of one bits in the data */
426      /* if parity = 1, data has odd parity - i.e. there is an odd number of one bits in the data */
427      parity = serial_helper_get_parity(data_byte);
428
429      transmit_register_add_bit(transmit_reg, parity);
430   }
431
432   /* stop bit(s) */
433   for (i=0; i<data_form->stop_bit_count; i++)
434   {
435      transmit_register_add_bit(transmit_reg,1);
436   }
437}
438
439
440/* get a bit from the transmit register */
441static int transmit_register_get_data_bit(serial_transmit_register *transmit_reg)
442{
443   int bit;
444
445   bit = (transmit_reg->register_data>>
446      (transmit_reg->bit_count - 1 -
447      transmit_reg->bit_count_transmitted)) & 0x01;
448
449   transmit_reg->bit_count_transmitted++;
450
451   /* have all bits of this stream formatted byte been sent? */
452   if (transmit_reg->bit_count_transmitted==transmit_reg->bit_count)
453   {
454      /* yes - generate a new byte to send */
455      transmit_reg->flags |= TRANSMIT_REGISTER_EMPTY;
456   }
457
458   return bit;
459}
460
461
462void transmit_register_send_bit(running_machine &machine, serial_transmit_register *transmit_reg, serial_connection *connection)
463{
464   int data;
465
466   data = transmit_register_get_data_bit(transmit_reg);
467
468   /* set tx data bit */
469   set_out_data_bit(connection->State, data);
470
471   /* state out through connection */
472   serial_connection_out(machine, connection);
473}
474
475static void serial_protocol_none_sent_char(device_t *device)
476{
477   int i;
478   int bit;
479   unsigned char data_byte;
480   serial_t *ser = get_safe_token(device);
481
482   /* generate byte to transmit */
483   data_byte = 0;
484   for (i=0; i<ser->form.word_length; i++)
485   {
486      data_byte = data_byte<<1;
487      bit = data_stream_get_data_bit_from_data_byte(&ser->transmit);
488      data_byte = data_byte|bit;
489   }
490   /* setup register */
491   transmit_register_setup(&ser->transmit_reg,&ser->form, data_byte);
492
493   logerror("serial device transmitted char: %02x\n",data_byte);
494}
495
496static TIMER_CALLBACK(serial_device_baud_rate_callback)
497{
498   serial_t *ser = get_safe_token((device_t*)ptr);
499
500   /* receive data into receive register */
501   receive_register_update_bit(&ser->receive_reg, get_in_data_bit(ser->connection.input_state));
502
503   if (ser->receive_reg.flags & RECEIVE_REGISTER_FULL)
504   {
505      //logerror("SERIAL DEVICE\n");
506      receive_register_extract(&ser->receive_reg, &ser->form);
507
508      logerror("serial device receive char: %02x\n",ser->receive_reg.byte_received);
509   }
510
511   /* is transmit empty? */
512   if (ser->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)
513   {
514      /* char has been sent, execute callback */
515      serial_protocol_none_sent_char((device_t*)ptr);
516   }
517
518   /* other side says it is clear to send? */
519   if (ser->connection.input_state & SERIAL_STATE_CTS)
520   {
521      /* send bit */
522      transmit_register_send_bit(machine, &ser->transmit_reg, &ser->connection);
523   }
524}
525
526/* connect the specified connection to this serial device */
527void serial_device_connect(device_t *device, serial_connection *connection)
528{
529   serial_t *ser = get_safe_token(device);
530   serial_connection_link(device->machine(), connection, &ser->connection);
531}
532
533
534/* load image */
535static int serial_device_load_internal(device_image_interface &image, unsigned char **ptr, int *pDataSize)
536{
537   int datasize;
538   unsigned char *data;
539
540   /* get file size */
541   datasize = image.length();
542
543   if (datasize!=0)
544   {
545      /* malloc memory for this data */
546      data = (unsigned char *)malloc(datasize);
547
548      if (data!=NULL)
549      {
550         /* read whole file */
551         image.fread(data, datasize);
552
553         *ptr = data;
554         *pDataSize = datasize;
555
556         logerror("File loaded!\r\n");
557
558         /* ok! */
559         return 1;
560      }
561   }
562   return 0;
563}
564
565/* reset position in stream */
566static void data_stream_reset(data_stream *stream)
567{
568   /* reset byte offset */
569   stream->ByteCount= 0;
570   /* reset bit count */
571   stream->BitCount = 0;
572}
573
574/* free stream */
575static void data_stream_free(data_stream *stream)
576{
577   if (stream->pData!=NULL)
578   {
579      free(stream->pData);
580      stream->pData = NULL;
581   }
582   stream->DataLength = 0;
583}
584
585/* initialise stream */
586static void data_stream_init(data_stream *stream, unsigned char *pData, unsigned long DataLength)
587{
588   stream->pData = pData;
589   stream->DataLength = DataLength;
590   data_stream_reset(stream);
591}
592
593DEVICE_START(serial)
594{
595   //serial_t *ser = get_safe_token(device);
596}
597
598DEVICE_RESET(serial)
599{
600//  serial_t *ser = get_safe_token(device);
601}
602
603DEVICE_IMAGE_LOAD(serial)
604{
605   int data_length;
606   unsigned char *data;
607   device_t *device = &image.device();
608
609   serial_t *ser = get_safe_token(device);
610
611   /* load file and setup transmit data */
612   if (serial_device_load_internal(image, &data, &data_length))
613   {
614      data_stream_init(&ser->transmit, data, data_length);
615      return IMAGE_INIT_PASS;
616   }
617
618   return IMAGE_INIT_FAIL;
619}
620
621
622DEVICE_IMAGE_UNLOAD(serial)
623{
624   device_t *device = &image.device();
625   serial_t *ser = get_safe_token(device);
626
627   /* stop transmit */
628   serial_device_set_transmit_state(device, 0);
629   /* free streams */
630   data_stream_free(&ser->transmit);
631   data_stream_free(&ser->receive);
632}
633
634
635DEVICE_GET_INFO( serial )
636{
637   switch ( state )
638   {
639      case DEVINFO_INT_TOKEN_BYTES:            info->i = sizeof(serial_t);                        break;
640      case DEVINFO_INT_INLINE_CONFIG_BYTES:      info->i = 0;                                 break;
641      case DEVINFO_INT_IMAGE_TYPE:               info->i = IO_SERIAL;                                   break;
642      case DEVINFO_INT_IMAGE_READABLE:            info->i = 1;                                           break;
643      case DEVINFO_INT_IMAGE_WRITEABLE:         info->i = 1;                                           break;
644      case DEVINFO_INT_IMAGE_CREATABLE:          info->i = 1;                                           break;
645
646      case DEVINFO_FCT_START:                      info->start = DEVICE_START_NAME( serial );             break;
647      case DEVINFO_FCT_RESET:                  info->reset = DEVICE_RESET_NAME( serial );            break;
648      case DEVINFO_FCT_IMAGE_LOAD:              info->f = (genf *) DEVICE_IMAGE_LOAD_NAME( serial );   break;
649      case DEVINFO_FCT_IMAGE_UNLOAD:              info->f = (genf *) DEVICE_IMAGE_UNLOAD_NAME(serial );   break;
650      case DEVINFO_STR_NAME:                      strcpy( info->s, "Serial port");                       break;
651      case DEVINFO_STR_FAMILY:                    strcpy(info->s, "Serial port");                           break;
652      case DEVINFO_STR_IMAGE_FILE_EXTENSIONS:       strcpy(info->s, "");                                    break;
653      case DEVINFO_STR_VERSION:               strcpy(info->s, "1.0");                           break;
654      case DEVINFO_STR_SOURCE_FILE:            strcpy(info->s, __FILE__);                        break;
655      case DEVINFO_STR_CREDITS:               strcpy(info->s, "Copyright the MESS Team");          break;
656   }
657}
658
659/*******************************************************************************/
660/*******************************************************************************/
661/********* SERIAL CONNECTION ***********/
662
663
664/* this converts state at this end to a state the other end can accept */
665/* e.g. CTS at this end becomes RTS at other end.
666        RTS at this end becomes CTS at other end.
667        TX at this end becomes RX at other end.
668        RX at this end becomes TX at other end.
669        etc
670
671        The same thing is done inside the serial null-terminal lead */
672
673static unsigned long serial_connection_spin_bits(unsigned long input_status)
674{
675
676   return
677      /* cts -> rts */
678      (((input_status & 0x01)<<1) |
679      /* rts -> cts */
680      ((input_status>>1) & 0x01) |
681      /* dsr -> dtr */
682      (((input_status>>2) & 0x01)<<3) |
683      /* dtr -> dsr */
684      (((input_status>>3) & 0x01)<<2) |
685      /* rx -> tx */
686      (((input_status>>4) & 0x01)<<5) |
687      /* tx -> rx */
688      (((input_status>>5) & 0x01)<<4));
689}
690
691
692/* setup callbacks for connection */
693void serial_connection_init(running_machine &machine, serial_connection *connection)
694{
695   connection->out_callback = NULL;
696   connection->in_callback = NULL;
697}
698
699/* set callback which will be executed when in status has changed */
700void serial_connection_set_in_callback(running_machine &machine, serial_connection *connection, void (*in_cb)(running_machine &machine, int id, unsigned long status))
701{
702   connection->in_callback = in_cb;
703}
704
705/* output new state through connection */
706void serial_connection_out(running_machine &machine, serial_connection *connection)
707{
708   if (connection->out_callback!=NULL)
709   {
710      unsigned long state_at_other_end;
711
712      state_at_other_end = serial_connection_spin_bits(connection->State);
713
714      connection->out_callback(machine, connection->id, state_at_other_end);
715   }
716}
717
718/* join two serial connections together */
719void serial_connection_link(running_machine &machine, serial_connection *connection_a, serial_connection *connection_b)
720{
721   /* both connections should have their in connection setup! */
722   /* the in connection is the callback they use to update their state based
723    on the output from the other side */
724   connection_a->out_callback = connection_b->in_callback;
725   connection_b->out_callback = connection_a->in_callback;
726
727   /* let b know the state of a */
728   serial_connection_out(machine,connection_a);
729   /* let a know the state of b */
730   serial_connection_out(machine,connection_b);
731}
732
733DEFINE_LEGACY_IMAGE_DEVICE(SERIAL, serial);
src/mess/machine/serial.h
r11450r11451
1/*****************************************************************************
2 *
3 * machine/serial.h
4 *
5 * internal serial transmission
6 *
7 * This code is used to transmit a file stored on the host filesystem
8 * (e.g. PC harddrive) to an emulated system.
9 *
10 * The file is converted into a serial bit-stream which can be received
11 * by the emulated serial chip in the emulated system.
12 *
13 * The file can be transmitted using different protocols.
14 *
15 * A and B are two computers linked with a serial connection
16 * A and B can transmit and receive data, through the same connection
17 *
18 * These flags apply to A and B, and give the state of the input & output
19 * signals at each side.
20 *
21 ****************************************************************************/
22
23#ifndef SERIAL_H_
24#define SERIAL_H_
25
26
27/*
28    CTS = Clear to Send. (INPUT)
29    Other end of connection is ready to accept data
30
31
32    NOTE:
33
34      This output is active low on serial chips (e.g. 0 is CTS is set),
35      but here it is active high!
36*/
37#define SERIAL_STATE_CTS   0x0001
38
39/*
40    RTS = Request to Send. (OUTPUT)
41    This end is ready to send data, and requests if the other
42    end is ready to accept it
43
44    NOTE:
45
46      This output is active low on serial chips (e.g. 0 is RTS is set),
47      but here it is active high!
48*/
49#define SERIAL_STATE_RTS   0x0002
50
51/*
52    DSR = Data Set ready. (INPUT)
53    Other end of connection has data
54
55
56    NOTE:
57
58      This output is active low on serial chips (e.g. 0 is DSR is set),
59      but here it is active high!
60*/
61#define SERIAL_STATE_DSR   0x0004
62
63/*
64    DTR = Data terminal Ready. (OUTPUT)
65    TX contains new data.
66
67    NOTE:
68
69      This output is active low on serial chips (e.g. 0 is DTR is set),
70      but here it is active high!
71*/
72#define SERIAL_STATE_DTR   0x0008
73/* RX = Recieve data. (INPUT) */
74#define SERIAL_STATE_RX_DATA   0x00010
75/* TX = Transmit data. (OUTPUT) */
76#define SERIAL_STATE_TX_DATA   0x00020
77
78/* parity selections */
79/* if all the bits are added in a byte, if the result is:
80    even -> parity is even
81    odd -> parity is odd
82*/
83enum
84{
85   SERIAL_PARITY_NONE,      /* no parity. a parity bit will not be in the transmitted/received data */
86   SERIAL_PARITY_ODD,      /* odd parity */
87   SERIAL_PARITY_EVEN      /* even parity */
88};
89
90/* this macro is used to extract the received data from the status */
91#define get_in_data_bit(x) ((x & SERIAL_STATE_RX_DATA)>>4)
92
93/* this macro is used to set the transmitted data in the status */
94#define set_out_data_bit(x, data) \
95   x&=~SERIAL_STATE_TX_DATA; \
96   x|=(data<<5)
97
98
99/*******************************************************************************/
100/**** SERIAL CONNECTION ***/
101
102
103/* this structure represents a serial connection */
104typedef struct _serial_connection serial_connection;
105struct _serial_connection
106{
107   int id;
108   /* state of this side */
109   unsigned long State;
110
111   /* state of other side - store here */
112   unsigned long input_state;
113
114   /* this callback is executed when this side has refreshed it's state,
115    to let the other end know */
116   void   (*out_callback)(running_machine &machine, int id, unsigned long state);
117   /* this callback is executed when the other side has refreshed it's state,
118    to let the other end know */
119   void   (*in_callback)(running_machine &machine, int id, unsigned long state);
120};
121
122/*----------- defined in machine/serial.c -----------*/
123
124/* setup out and in callbacks */
125void serial_connection_init(running_machine &machine, serial_connection *connection);
126
127/* set callback which will be executed when in status has changed */
128void serial_connection_set_in_callback(running_machine &machine, serial_connection *connection, void (*in_cb)(running_machine &machine, int id, unsigned long status));
129
130/* output status, if callback is setup it will be executed with the new status */
131void serial_connection_out(running_machine &machine, serial_connection *connection);
132
133/* join two serial connections */
134void serial_connection_link(running_machine &machine, serial_connection *connection_a, serial_connection *connection_b);
135
136
137/*******************************************************************************/
138
139/* form of data being transmitted and received */
140typedef struct _data_form data_form;
141struct _data_form
142{
143   /* length of word in bits */
144   unsigned long word_length;
145   /* parity state */
146   unsigned long parity;
147   /* number of stop bits */
148   unsigned long stop_bit_count;
149};
150
151/*******************************************************************************/
152
153/*******************************************************************************/
154/**** RECEIVE AND TRANSMIT GENERIC CODE ****/
155
156/* this can be used by most of the serial chip implementations,
157because they all work in roughly the same way.
158There is generic code to send and receive data in the specified form */
159
160/* receive is waiting for start bit. The transition from high-low indicates
161start of start bit. This is used to synchronise with the data being transfered */
162#define RECEIVE_REGISTER_WAITING_FOR_START_BIT 0x01
163/* receive is synchronised with data, data bits will be clocked in */
164#define RECEIVE_REGISTER_SYNCHRONISED 0x02
165/* set if receive register has been filled */
166#define RECEIVE_REGISTER_FULL 0x04
167
168
169/* the receive register holds data in receive form! */
170/* this must be extracted to get the data byte received */
171typedef struct _serial_receive_register serial_receive_register;
172struct _serial_receive_register
173{
174   /* data */
175   unsigned long register_data;
176   /* flags */
177   unsigned long flags;
178   /* bit count received */
179   unsigned long bit_count_received;
180   /* length of data to receive - includes data bits, parity bit and stop bit */
181   unsigned long bit_count;
182
183   /* the byte of data received */
184   unsigned char byte_received;
185};
186
187void   receive_register_setup(serial_receive_register *receive, data_form *data_form);
188void   receive_register_update_bit(serial_receive_register *receive, int bit_state);
189void   receive_register_extract(serial_receive_register *receive_reg, data_form *data_form);
190void   receive_register_reset(serial_receive_register *receive_reg);
191
192/* the transmit register is the final stage
193in the serial transmit procedure */
194/* normally, data is written to the transmit reg,
195then it is assembled into transmit form and transmitted */
196/* the transmit register holds data in transmit form */
197
198/* register is empty and ready to be filled with data */
199#define TRANSMIT_REGISTER_EMPTY 0x0001
200
201typedef struct _serial_transmit_register serial_transmit_register;
202struct _serial_transmit_register
203{
204   /* data */
205   unsigned long register_data;
206   /* flags */
207   unsigned long flags;
208   /* number of bits transmitted */
209   unsigned long bit_count_transmitted;
210   /* length of data to send */
211   unsigned long bit_count;
212};
213
214/* setup transmit reg ready for transmit */
215void transmit_register_setup(serial_transmit_register *transmit_reg, data_form *data_form,unsigned char data_byte);
216void   transmit_register_send_bit(running_machine &machine, serial_transmit_register *transmit_reg, serial_connection *connection);
217void   transmit_register_reset(serial_transmit_register *transmit_reg);
218
219/*******************************************************************************/
220/**** SERIAL HELPER ****/
221
222void serial_helper_setup(void);
223
224/*******************************************************************************/
225/**** SERIAL DEVICE ****/
226
227unsigned long serial_device_get_state(device_t *device);
228
229/* connect this device to the emulated serial chip */
230/* id is the serial device to connect to */
231/* connection is the serial connection to connect to the serial device */
232void serial_device_connect(device_t *image, serial_connection *connection);
233
234DECLARE_LEGACY_IMAGE_DEVICE(SERIAL, serial);
235
236#define MCFG_SERIAL_ADD(_tag) \
237   MCFG_DEVICE_ADD(_tag, SERIAL, 0)
238
239DEVICE_START(serial);
240DEVICE_IMAGE_LOAD(serial);
241
242void serial_device_setup(device_t *image, int baud_rate, int num_data_bits, int stop_bit_count, int parity_code);
243
244/* set the transmit state of the serial device */
245void serial_device_set_transmit_state(device_t *image, int state);
246
247#endif /* SERIAL_H_ */
src/mess/machine/sms.c
r11450r11451
1#include "emu.h"
2#include "crsshair.h"
3#include "image.h"
4#include "includes/sms.h"
5#include "video/smsvdp.h"
6#include "sound/2413intf.h"
7#include "imagedev/cartslot.h"
8#include "hashfile.h"
9
10#define VERBOSE 0
11#define LOG(x) do { if (VERBOSE) logerror x; } while (0)
12
13#define CF_CODEMASTERS_MAPPER    0x01
14#define CF_KOREAN_MAPPER         0x02
15#define CF_KOREAN_ZEMINA_MAPPER  0x04
16#define CF_KOREAN_NOBANK_MAPPER  0x08
17#define CF_93C46_EEPROM          0x10
18#define CF_ONCART_RAM            0x20
19#define CF_GG_SMS_MODE           0x40
20
21#define LGUN_RADIUS           6
22#define LGUN_X_INTERVAL       4
23
24
25static void setup_rom(address_space *space);
26
27
28static TIMER_CALLBACK( rapid_fire_callback )
29{
30   sms_state *state = machine.driver_data<sms_state>();
31   state->m_rapid_fire_state_1 ^= 0xff;
32   state->m_rapid_fire_state_2 ^= 0xff;
33}
34
35
36static WRITE8_HANDLER( sms_input_write )
37{
38   sms_state *state = space->machine().driver_data<sms_state>();
39
40   switch (offset)
41   {
42   case 0:
43      switch (input_port_read_safe(space->machine(), "CTRLSEL", 0x00) & 0x0f)
44      {
45      case 0x03:   /* Sports Pad */
46         if (data != state->m_sports_pad_last_data_1)
47         {
48            UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
49
50            state->m_sports_pad_last_data_1 = data;
51            if (cpu_cycles - state->m_last_sports_pad_time_1 > 512)
52            {
53               state->m_sports_pad_state_1 = 3;
54               state->m_sports_pad_1_x = input_port_read(space->machine(), "SPORT0");
55               state->m_sports_pad_1_y = input_port_read(space->machine(), "SPORT1");
56            }
57            state->m_last_sports_pad_time_1 = cpu_cycles;
58            state->m_sports_pad_state_1 = (state->m_sports_pad_state_1 + 1) & 3;
59         }
60         break;
61      }
62      break;
63
64   case 1:
65      switch (input_port_read_safe(space->machine(), "CTRLSEL", 0x00) >> 4)
66      {
67      case 0x03:   /* Sports Pad */
68         if (data != state->m_sports_pad_last_data_2)
69         {
70            UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
71
72            state->m_sports_pad_last_data_2 = data;
73            if (cpu_cycles - state->m_last_sports_pad_time_2 > 2048)
74            {
75               state->m_sports_pad_state_2 = 3;
76               state->m_sports_pad_2_x = input_port_read(space->machine(), "SPORT2");
77               state->m_sports_pad_2_y = input_port_read(space->machine(), "SPORT3");
78            }
79            state->m_last_sports_pad_time_2 = cpu_cycles;
80            state->m_sports_pad_state_2 = (state->m_sports_pad_state_2 + 1) & 3;
81         }
82         break;
83      }
84      break;
85   }
86}
87
88/* FIXME: this function is a hack for Light Phaser emulation. Theoretically
89   sms_vdp_hcount_latch() should be used instead, but it returns incorrect
90   position for unknown reason (timing?) */
91static void sms_vdp_hcount_lphaser( running_machine &machine, int hpos )
92{
93   sms_state *state = machine.driver_data<sms_state>();
94   int hpos_tmp = hpos + state->m_lphaser_x_offs;
95   UINT8 tmp = ((hpos_tmp - 46) >> 1) & 0xff;
96
97   //printf ("sms_vdp_hcount_lphaser: hpos %3d hpos_tmp %3d => hcount %2X\n", hpos, hpos_tmp, tmp);
98   sms_vdp_hcount_latch_w(state->m_vdp, 0, tmp);
99}
100
101
102/*
103    Light Phaser (light gun) emulation notes:
104    - The sensor is activated based on color brightness of some individual
105      pixels being drawn by the beam, at circular area where the gun is aiming.
106    - Currently, brightness is calculated based only on single pixels.
107    - In general, after the trigger is pressed, games draw the next frame using
108      a light color pattern, to make sure sensor will be activated. If emulation
109      skips that frame, sensor may stay deactivated. Frameskip set to 0 (no skip) is
110      recommended to avoid problems.
111    - When sensor switches from off to on, a value is latched for HCount register
112      and a flag is set. The emulation uses the flag to avoid sequential latches and
113      to signal that TH line is activated when the status of the input port is read.
114      When the status is read, the flag is cleared, or else it is cleared later when
115      the Pause status is read (end of a frame). This is necessary because the
116      "Color & Switch Test" ROM only reads the TH bit after the VINT line.
117    - The gun test of "Color & Switch Test" is an example that requires checks
118      of sensor status independent of other events, like trigger press or TH bit
119      reads. Another example is the title screen of "Hang-On & Safari Hunt", where
120      the game only reads HCount register in a loop, expecting a latch by the gun.
121    - The whole procedure is managed by a timer callback, that always reschedule
122      itself to run in some intervals when the beam is at the circular area.
123*/
124static int lgun_bright_aim_area( running_machine &machine, emu_timer *timer, int lgun_x, int lgun_y )
125{
126   sms_state *state = machine.driver_data<sms_state>();
127   const int r_x_r = LGUN_RADIUS * LGUN_RADIUS;
128   screen_device *screen = machine.first_screen();
129   const rectangle &visarea = screen->visible_area();
130   int beam_x = screen->hpos();
131   int beam_y = screen->vpos();
132   int dx, dy;
133   int result = 0;
134   int pos_changed = 0;
135   double dx_circ;
136
137    while (1)
138   {
139      dy = abs(beam_y - lgun_y);
140
141      if (dy > LGUN_RADIUS || beam_y < visarea.min_y || beam_y > visarea.max_y)
142      {
143         beam_y = lgun_y - LGUN_RADIUS;
144         if (beam_y < visarea.min_y)
145            beam_y = visarea.min_y;
146         dy = abs(beam_y - lgun_y);
147         pos_changed = 1;
148      }
149      /* step 1: r^2 = dx^2 + dy^2 */
150      /* step 2: dx^2 = r^2 - dy^2 */
151      /* step 3: dx = sqrt(r^2 - dy^2) */
152      dx_circ = ceil((float) sqrt((float) (r_x_r - (dy * dy))));
153      dx = abs(beam_x - lgun_x);
154
155      if (dx > dx_circ || beam_x < visarea.min_x || beam_x > visarea.max_x)
156      {
157         if (beam_x > lgun_x)
158         {
159            beam_x = 0;
160            beam_y++;
161            continue;
162         }
163         beam_x = lgun_x - dx_circ;
164         if (beam_x < visarea.min_x)
165            beam_x = visarea.min_x;
166         pos_changed = 1;
167      }
168
169      if (!pos_changed)
170      {
171         result = sms_vdp_check_brightness(state->m_vdp, beam_x, beam_y);
172         /* next check at same line */
173         beam_x += LGUN_X_INTERVAL;
174         pos_changed = 1;
175      }
176      else
177         break;
178   }
179   timer->adjust(machine.first_screen()->time_until_pos(beam_y, beam_x));
180
181   return result;
182}
183
184static UINT8 sms_vdp_hcount( running_machine &machine )
185{
186   UINT8 tmp;
187   screen_device *screen = machine.first_screen();
188   int hpos = screen->hpos();
189
190   /* alternative method: pass HCounter test, but some others fail */
191   //int hpos_tmp = hpos;
192   //if ((hpos + 2) % 6 == 0) hpos_tmp--;
193   //tmp = ((hpos_tmp - 46) >> 1) & 0xff;
194
195   UINT64 calc_cycles;
196   attotime time_end;
197   int vpos = screen->vpos();
198   int max_hpos = screen->width() - 1;
199
200   if (hpos == max_hpos)
201      time_end = attotime::zero;
202   else
203      time_end = screen->time_until_pos(vpos, max_hpos);
204   calc_cycles = machine.device<cpu_device>("maincpu")->attotime_to_clocks(time_end);
205
206   /* equation got from SMSPower forum, posted by Flubba. */
207   tmp = ((590 - (calc_cycles * 3)) / 4) & 0xff;
208
209   //printf ("sms_vdp_hcount: hpos %3d => hcount %2X\n", hpos, tmp);
210   return tmp;
211}
212
213
214static void sms_vdp_hcount_latch( running_machine &machine )
215{
216   sms_state *state = machine.driver_data<sms_state>();
217   UINT8 value = sms_vdp_hcount(machine);
218
219   sms_vdp_hcount_latch_w(state->m_vdp, 0, value);
220}
221
222
223static UINT16 screen_hpos_nonscaled( screen_device *screen, int scaled_hpos )
224{
225   const rectangle &visarea = screen->visible_area();
226   int offset_x = (scaled_hpos * (visarea.max_x - visarea.min_x)) / 255;
227   return visarea.min_x + offset_x;
228}
229
230
231static UINT16 screen_vpos_nonscaled( screen_device *screen, int scaled_vpos )
232{
233   const rectangle &visarea = screen->visible_area();
234   int offset_y = (scaled_vpos * (visarea.max_y - visarea.min_y)) / 255;
235   return visarea.min_y + offset_y;
236}
237
238
239static void lphaser1_sensor_check( running_machine &machine )
240{
241   sms_state *state = machine.driver_data<sms_state>();
242   const int x = screen_hpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER0"));
243   const int y = screen_vpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER1"));
244
245   if (lgun_bright_aim_area(machine, state->m_lphaser_1_timer, x, y))
246   {
247      if (state->m_lphaser_1_latch == 0)
248      {
249         state->m_lphaser_1_latch = 1;
250         sms_vdp_hcount_lphaser(machine, x);
251      }
252   }
253}
254
255static void lphaser2_sensor_check( running_machine &machine )
256{
257   sms_state *state = machine.driver_data<sms_state>();
258   const int x = screen_hpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER2"));
259   const int y = screen_vpos_nonscaled(machine.first_screen(), input_port_read(machine, "LPHASER3"));
260
261   if (lgun_bright_aim_area(machine, state->m_lphaser_2_timer, x, y))
262   {
263      if (state->m_lphaser_2_latch == 0)
264      {
265         state->m_lphaser_2_latch = 1;
266         sms_vdp_hcount_lphaser(machine, x);
267      }
268   }
269}
270
271
272// at each input port read we check if lightguns are enabled in one of the ports:
273// if so, we turn on crosshair and the lightgun timer
274static TIMER_CALLBACK( lightgun_tick )
275{
276   sms_state *state = machine.driver_data<sms_state>();
277
278   if ((input_port_read_safe(machine, "CTRLSEL", 0x00) & 0x0f) == 0x01)
279   {
280      /* enable crosshair */
281      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_ALL);
282      if (!state->m_lphaser_1_timer->enabled())
283         lphaser1_sensor_check(machine);
284   }
285   else
286   {
287      /* disable crosshair */
288      crosshair_set_screen(machine, 0, CROSSHAIR_SCREEN_NONE);
289      state->m_lphaser_1_timer->enable(0);
290   }
291
292   if ((input_port_read_safe(machine, "CTRLSEL", 0x00) & 0xf0) == 0x10)
293   {
294      /* enable crosshair */
295      crosshair_set_screen(machine, 1, CROSSHAIR_SCREEN_ALL);
296      if (!state->m_lphaser_2_timer->enabled())
297         lphaser2_sensor_check(machine);
298   }
299   else
300   {
301      /* disable crosshair */
302      crosshair_set_screen(machine, 1, CROSSHAIR_SCREEN_NONE);
303      state->m_lphaser_2_timer->enable(0);
304   }
305}
306
307
308static TIMER_CALLBACK( lphaser_1_callback )
309{
310   lphaser1_sensor_check(machine);
311}
312
313
314static TIMER_CALLBACK( lphaser_2_callback )
315{
316   lphaser2_sensor_check(machine);
317}
318
319
320INPUT_CHANGED( lgun1_changed )
321{
322   sms_state *state = field->port->machine().driver_data<sms_state>();
323   if (!state->m_lphaser_1_timer ||
324      (input_port_read_safe(field->port->machine(), "CTRLSEL", 0x00) & 0x0f) != 0x01)
325      return;
326
327   if (newval != oldval)
328      lphaser1_sensor_check(field->port->machine());
329}
330
331INPUT_CHANGED( lgun2_changed )
332{
333   sms_state *state = field->port->machine().driver_data<sms_state>();
334   if (!state->m_lphaser_2_timer ||
335      (input_port_read_safe(field->port->machine(), "CTRLSEL", 0x00) & 0xf0) != 0x10)
336      return;
337
338   if (newval != oldval)
339      lphaser2_sensor_check(field->port->machine());
340}
341
342
343static void sms_get_inputs( address_space *space )
344{
345   sms_state *state = space->machine().driver_data<sms_state>();
346   UINT8 data = 0x00;
347   UINT32 cpu_cycles = downcast<cpu_device *>(&space->device())->total_cycles();
348   running_machine &machine = space->machine();
349
350   state->m_input_port0 = 0xff;
351   state->m_input_port1 = 0xff;
352
353   if (cpu_cycles - state->m_last_paddle_read_time > 256)
354   {
355      state->m_paddle_read_state ^= 0xff;
356      state->m_last_paddle_read_time = cpu_cycles;
357   }
358
359   /* Check if lightgun has been chosen as input: if so, enable crosshair */
360   machine.scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
361
362   /* Player 1 */
363   switch (input_port_read_safe(machine, "CTRLSEL", 0x00) & 0x0f)
364   {
365   case 0x00:  /* Joystick */
366      data = input_port_read(machine, "PORT_DC");
367      /* Check Rapid Fire setting for Button A */
368      if (!(data & 0x10) && (input_port_read(machine, "RFU") & 0x01))
369         data |= state->m_rapid_fire_state_1 & 0x10;
370
371      /* Check Rapid Fire setting for Button B */
372      if (!(data & 0x20) && (input_port_read(machine, "RFU") & 0x02))
373         data |= state->m_rapid_fire_state_1 & 0x20;
374
375      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x3f);
376      break;
377
378   case 0x01:  /* Light Phaser */
379      data = (input_port_read(machine, "CTRLIPT") & 0x01) << 4;
380      if (!(data & 0x10))
381      {
382         if (input_port_read(machine, "RFU") & 0x01)
383            data |= state->m_rapid_fire_state_1 & 0x10;
384      }
385      /* just consider the button (trigger) bit */
386      data |= ~0x10;
387      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x3f);
388      break;
389
390   case 0x02:  /* Paddle Control */
391      /* Get button A state */
392      data = input_port_read(machine, "PADDLE0");
393
394      if (state->m_paddle_read_state)
395         data = data >> 4;
396
397      state->m_input_port0 = (state->m_input_port0 & 0xc0) | (data & 0x0f) | (state->m_paddle_read_state & 0x20)
398                      | ((input_port_read(machine, "CTRLIPT") & 0x02) << 3);
399      break;
400
401   case 0x03:   /* Sega Sports Pad */
402      switch (state->m_sports_pad_state_1)
403      {
404      case 0:
405         data = (state->m_sports_pad_1_x >> 4) & 0x0f;
406         break;
407      case 1:
408         data = state->m_sports_pad_1_x & 0x0f;
409         break;
410      case 2:
411         data = (state->m_sports_pad_1_y >> 4) & 0x0f;
412         break;
413      case 3:
414         data = state->m_sports_pad_1_y & 0x0f;
415         break;
416      }
417      state->m_input_port0 = (state->m_input_port0 & 0xc0) | data | ((input_port_read(machine, "CTRLIPT") & 0x0c) << 2);
418      break;
419   }
420
421   /* Player 2 */
422   switch (input_port_read_safe(machine, "CTRLSEL", 0x00)  & 0xf0)
423   {
424   case 0x00:   /* Joystick */
425      data = input_port_read(machine, "PORT_DC");
426      state->m_input_port0 = (state->m_input_port0 & 0x3f) | (data & 0xc0);
427
428      data = input_port_read(machine, "PORT_DD");
429      /* Check Rapid Fire setting for Button A */
430      if (!(data & 0x04) && (input_port_read(machine, "RFU") & 0x04))
431         data |= state->m_rapid_fire_state_2 & 0x04;
432
433      /* Check Rapid Fire setting for Button B */
434      if (!(data & 0x08) && (input_port_read(machine, "RFU") & 0x08))
435         data |= state->m_rapid_fire_state_2 & 0x08;
436
437      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data & 0x0f);
438      break;
439
440   case 0x10:   /* Light Phaser */
441      data = (input_port_read(machine, "CTRLIPT") & 0x10) >> 2;
442      if (!(data & 0x04))
443      {
444         if (input_port_read(machine, "RFU") & 0x04)
445            data |= state->m_rapid_fire_state_2 & 0x04;
446      }
447      /* just consider the button (trigger) bit */
448      data |= ~0x04;
449      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data & 0x0f);
450      break;
451
452   case 0x20:   /* Paddle Control */
453      /* Get button A state */
454      data = input_port_read(machine, "PADDLE1");
455      if (state->m_paddle_read_state)
456         data = data >> 4;
457
458      state->m_input_port0 = (state->m_input_port0 & 0x3f) | ((data & 0x03) << 6);
459      state->m_input_port1 = (state->m_input_port1 & 0xf0) | ((data & 0x0c) >> 2) | (state->m_paddle_read_state & 0x08)
460                      | ((input_port_read(machine, "CTRLIPT") & 0x20) >> 3);
461      break;
462
463   case 0x30:   /* Sega Sports Pad */
464      switch (state->m_sports_pad_state_2)
465      {
466      case 0:
467         data = state->m_sports_pad_2_x & 0x0f;
468         break;
469      case 1:
470         data = (state->m_sports_pad_2_x >> 4) & 0x0f;
471         break;
472      case 2:
473         data = state->m_sports_pad_2_y & 0x0f;
474         break;
475      case 3:
476         data = (state->m_sports_pad_2_y >> 4) & 0x0f;
477         break;
478      }
479      state->m_input_port0 = (state->m_input_port0 & 0x3f) | ((data & 0x03) << 6);
480      state->m_input_port1 = (state->m_input_port1 & 0xf0) | (data >> 2) | ((input_port_read(machine, "CTRLIPT") & 0xc0) >> 4);
481      break;
482   }
483}
484
485
486WRITE8_HANDLER( sms_fm_detect_w )
487{
488   sms_state *state = space->machine().driver_data<sms_state>();
489
490   if (state->m_has_fm)
491      state->m_fm_detect = (data & 0x01);
492}
493
494
495READ8_HANDLER( sms_fm_detect_r )
496{
497   sms_state *state = space->machine().driver_data<sms_state>();
498
499   if (state->m_has_fm)
500   {
501      return state->m_fm_detect;
502   }
503   else
504   {
505      if (state->m_bios_port & IO_CHIP)
506      {
507         return 0xff;
508      }
509      else
510      {
511         sms_get_inputs(space);
512         return state->m_input_port0;
513      }
514   }
515}
516
517WRITE8_HANDLER( sms_io_control_w )
518{
519   sms_state *state = space->machine().driver_data<sms_state>();
520
521   if (data & 0x08)
522   {
523      /* check if TH pin level is high (1) and was low last time */
524      if (data & 0x80 && !(state->m_ctrl_reg & 0x80))
525      {
526         sms_vdp_hcount_latch(space->machine());
527      }
528      sms_input_write(space, 0, (data & 0x20) >> 5);
529   }
530
531   if (data & 0x02)
532   {
533      if (data & 0x20 && !(state->m_ctrl_reg & 0x20))
534      {
535         sms_vdp_hcount_latch(space->machine());
536      }
537      sms_input_write(space, 1, (data & 0x80) >> 7);
538   }
539
540   state->m_ctrl_reg = data;
541}
542
543
544READ8_HANDLER( sms_count_r )
545{
546   sms_state *state = space->machine().driver_data<sms_state>();
547
548   if (offset & 0x01)
549      return sms_vdp_hcount_latch_r(state->m_vdp, offset);
550   else
551      return sms_vdp_vcount_r(state->m_vdp, offset);
552}
553
554
555/*
556 Check if the pause button is pressed.
557 If the gamegear is in sms mode, check if the start button is pressed.
558 */
559void sms_pause_callback( running_machine &machine )
560{
561   sms_state *state = machine.driver_data<sms_state>();
562
563   if (state->m_is_gamegear && !(state->m_cartridge[state->m_current_cartridge].features & CF_GG_SMS_MODE))
564      return;
565
566   if (!(input_port_read(machine, state->m_is_gamegear ? "START" : "PAUSE") & 0x80))
567   {
568      if (!state->m_paused)
569      {
570         cputag_set_input_line(machine, "maincpu", INPUT_LINE_NMI, PULSE_LINE);
571      }
572      state->m_paused = 1;
573   }
574   else
575   {
576      state->m_paused = 0;
577   }
578
579   /* clear Light Phaser latch flags for next frame */
580   state->m_lphaser_1_latch = 0;
581   state->m_lphaser_2_latch = 0;
582}
583
584READ8_HANDLER( sms_input_port_0_r )
585{
586   sms_state *state = space->machine().driver_data<sms_state>();
587
588   if (state->m_bios_port & IO_CHIP)
589   {
590      return 0xff;
591   }
592   else
593   {
594      sms_get_inputs(space);
595      return state->m_input_port0;
596   }
597}
598
599
600READ8_HANDLER( sms_input_port_1_r )
601{
602   sms_state *state = space->machine().driver_data<sms_state>();
603
604   if (state->m_bios_port & IO_CHIP)
605      return 0xff;
606
607   sms_get_inputs(space);
608
609   /* Reset Button */
610   state->m_input_port1 = (state->m_input_port1 & 0xef) | (input_port_read_safe(space->machine(), "RESET", 0x01) & 0x01) << 4;
611
612   /* Do region detection if TH of ports A and B are set to output (0) */
613   if (!(state->m_ctrl_reg & 0x0a))
614   {
615      /* Move bits 7,5 of IO control port into bits 7, 6 */
616      state->m_input_port1 = (state->m_input_port1 & 0x3f) | (state->m_ctrl_reg & 0x80) | (state->m_ctrl_reg & 0x20) << 1;
617
618      /* Inverse region detect value for Japanese machines */
619      if (state->m_is_region_japan)
620         state->m_input_port1 ^= 0xc0;
621   }
622   else
623   {
624      if (state->m_ctrl_reg & 0x02 && state->m_lphaser_1_latch)
625      {
626         state->m_input_port1 &= ~0x40;
627         state->m_lphaser_1_latch = 0;
628      }
629
630      if (state->m_ctrl_reg & 0x08 && state->m_lphaser_2_latch)
631      {
632         state->m_input_port1 &= ~0x80;
633         state->m_lphaser_2_latch = 0;
634      }
635   }
636
637   return state->m_input_port1;
638}
639
640
641
642WRITE8_HANDLER( sms_ym2413_register_port_0_w )
643{
644   sms_state *state = space->machine().driver_data<sms_state>();
645
646   if (state->m_has_fm)
647      ym2413_w(state->m_ym, 0, (data & 0x3f));
648}
649
650
651WRITE8_HANDLER( sms_ym2413_data_port_0_w )
652{
653   sms_state *state = space->machine().driver_data<sms_state>();
654
655   if (state->m_has_fm)
656   {
657      logerror("data_port_0_w %x %x\n", offset, data);
658      ym2413_w(state->m_ym, 1, data);
659   }
660}
661
662
663READ8_HANDLER( gg_input_port_2_r )
664{
665   sms_state *state = space->machine().driver_data<sms_state>();
666
667   //logerror("joy 2 read, val: %02x, pc: %04x\n", ((state->m_is_region_japan ? 0x00 : 0x40) | (input_port_read(machine, "START") & 0x80)), activecpu_get_pc());
668   return ((state->m_is_region_japan ? 0x00 : 0x40) | (input_port_read(space->machine(), "START") & 0x80));
669}
670
671
672READ8_HANDLER( sms_sscope_r )
673{
674   sms_state *state = space->machine().driver_data<sms_state>();
675   return state->m_sscope_state;
676}
677
678
679WRITE8_HANDLER( sms_sscope_w )
680{
681   sms_state *state = space->machine().driver_data<sms_state>();
682   state->m_sscope_state = data;
683}
684
685
686READ8_HANDLER( sms_mapper_r )
687{
688   sms_state *state = space->machine().driver_data<sms_state>();
689   return state->m_mapper[offset];
690}
691
692/* Terebi Oekaki */
693/* The following code comes from sg1000.c. We should eventually merge these TV Draw implementations */
694static WRITE8_HANDLER( sms_tvdraw_axis_w )
695{
696   sms_state *state = space->machine().driver_data<sms_state>();
697   UINT8 tvboard_on = input_port_read_safe(space->machine(), "TVDRAW", 0x00);
698
699   if (data & 0x01)
700   {
701      state->m_tvdraw_data = tvboard_on ? input_port_read(space->machine(), "TVDRAW_X") : 0x80;
702
703      if (state->m_tvdraw_data < 4) state->m_tvdraw_data = 4;
704      if (state->m_tvdraw_data > 251) state->m_tvdraw_data = 251;
705   }
706   else
707   {
708      state->m_tvdraw_data = tvboard_on ? input_port_read(space->machine(), "TVDRAW_Y") + 0x20 : 0x80;
709   }
710}
711
712static READ8_HANDLER( sms_tvdraw_status_r )
713{
714   UINT8 tvboard_on = input_port_read_safe(space->machine(), "TVDRAW", 0x00);
715   return tvboard_on ? input_port_read(space->machine(), "TVDRAW_PEN") : 0x01;
716}
717
718static READ8_HANDLER( sms_tvdraw_data_r )
719{
720   sms_state *state = space->machine().driver_data<sms_state>();
721   return state->m_tvdraw_data;
722}
723
724
725WRITE8_HANDLER( sms_mapper_w )
726{
727   sms_state *state = space->machine().driver_data<sms_state>();
728   int page;
729   UINT8 *SOURCE_BIOS;
730   UINT8 *SOURCE_CART;
731   UINT8 *SOURCE;
732   UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
733
734   offset &= 3;
735
736   state->m_mapper[offset] = data;
737   state->m_mapper_ram[offset] = data;
738
739   if (state->m_cartridge[state->m_current_cartridge].ROM)
740   {
741      SOURCE_CART = state->m_cartridge[state->m_current_cartridge].ROM + (( rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
742   }
743   else
744   {
745      SOURCE_CART = state->m_banking_none[1];
746   }
747
748   if (state->m_BIOS)
749   {
750      SOURCE_BIOS = state->m_BIOS + ((state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0) * 0x4000;
751   }
752   else
753   {
754      SOURCE_BIOS = state->m_banking_none[1];
755   }
756
757   if (state->m_bios_port & IO_BIOS_ROM || (state->m_is_gamegear && state->m_BIOS == NULL))
758   {
759      if (!(state->m_bios_port & IO_CARTRIDGE) || (state->m_is_gamegear && state->m_BIOS == NULL))
760      {
761         page = (rom_page_count > 0) ? data % rom_page_count : 0;
762         if (!state->m_cartridge[state->m_current_cartridge].ROM)
763            return;
764         SOURCE = SOURCE_CART;
765      }
766      else
767      {
768         /* nothing to page in */
769         return;
770      }
771   }
772   else
773   {
774      page = (state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0;
775      if (!state->m_BIOS)
776         return;
777      SOURCE = SOURCE_BIOS;
778   }
779
780   switch (offset)
781   {
782   case 0: /* Control */
783      /* Is it ram or rom? */
784      if (data & 0x08) /* it's ram */
785      {
786         state->m_cartridge[state->m_current_cartridge].sram_save = 1;         /* SRAM should be saved on exit. */
787         if (data & 0x04)
788         {
789            LOG(("ram 1 paged.\n"));
790            SOURCE = state->m_cartridge[state->m_current_cartridge].cartSRAM + 0x4000;
791         }
792         else
793         {
794            LOG(("ram 0 paged.\n"));
795            SOURCE = state->m_cartridge[state->m_current_cartridge].cartSRAM;
796         }
797         memory_set_bankptr(space->machine(),  "bank5", SOURCE);
798         memory_set_bankptr(space->machine(),  "bank6", SOURCE + 0x2000);
799      }
800      else /* it's rom */
801      {
802         if (state->m_bios_port & IO_BIOS_ROM || ! state->m_has_bios)
803         {
804            page = (rom_page_count > 0) ? state->m_mapper[3] % rom_page_count : 0;
805            SOURCE = state->m_banking_cart[5];
806         }
807         else
808         {
809            page = (state->m_bios_page_count > 0) ? state->m_mapper[3] % state->m_bios_page_count : 0;
810            SOURCE = state->m_banking_bios[5];
811         }
812         LOG(("rom 2 paged in %x.\n", page));
813         memory_set_bankptr(space->machine(), "bank5", SOURCE);
814         memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
815      }
816      break;
817
818   case 1: /* Select 16k ROM bank for 0400-3FFF */
819      LOG(("rom 0 paged in %x.\n", page));
820      state->m_banking_bios[2] = SOURCE_BIOS + 0x0400;
821      state->m_banking_cart[2] = SOURCE_CART + 0x0400;
822      if (state->m_is_gamegear)
823         SOURCE = SOURCE_CART;
824
825      memory_set_bankptr(space->machine(), "bank2", SOURCE + 0x0400);
826      break;
827
828   case 2: /* Select 16k ROM bank for 4000-7FFF */
829      LOG(("rom 1 paged in %x.\n", page));
830      state->m_banking_bios[3] = SOURCE_BIOS;
831      state->m_banking_cart[3] = SOURCE_CART;
832      if (state->m_is_gamegear)
833         SOURCE = SOURCE_CART;
834
835      memory_set_bankptr(space->machine(), "bank3", SOURCE);
836      memory_set_bankptr(space->machine(), "bank4", SOURCE + 0x2000);
837      break;
838
839   case 3: /* Select 16k ROM bank for 8000-BFFF */
840      state->m_banking_bios[5] = SOURCE_BIOS;
841      if (state->m_is_gamegear)
842         SOURCE = SOURCE_CART;
843
844      if ( state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
845      {
846         if (SOURCE == SOURCE_CART)
847         {
848            SOURCE = state->m_banking_cart[5];
849         }
850      }
851      else
852      {
853         state->m_banking_cart[5] = SOURCE_CART;
854      }
855
856      if (!(state->m_mapper[0] & 0x08)) /* is RAM disabled? */
857      {
858         LOG(("rom 2 paged in %x.\n", page));
859         memory_set_bankptr(space->machine(), "bank5", SOURCE);
860         memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
861      }
862      break;
863   }
864}
865
866#ifdef MESS
867static WRITE8_HANDLER( sms_korean_zemina_banksw_w )
868{
869   sms_state *state = space->machine().driver_data<sms_state>();
870
871   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_ZEMINA_MAPPER)
872   {
873      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x2000;
874      int page = (rom_page_count > 0) ? data % rom_page_count : 0;
875
876      if (!state->m_cartridge[state->m_current_cartridge].ROM)
877         return;
878
879      switch (offset & 3)
880      {
881         case 0:
882            state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
883            memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
884            break;
885         case 1:
886            state->m_banking_cart[6] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
887            memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[6]);
888            break;
889         case 2:
890            state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
891            memory_set_bankptr(space->machine(), "bank3", state->m_banking_cart[3]);
892            break;
893         case 3:
894            state->m_banking_cart[4] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x2000;
895            memory_set_bankptr(space->machine(), "bank4", state->m_banking_cart[4]);
896            break;
897      }
898      LOG(("Zemina mapper write: offset %x data %x.\n", offset, page));
899   }
900}
901
902static WRITE8_HANDLER( sms_codemasters_page0_w )
903{
904   sms_state *state = space->machine().driver_data<sms_state>();
905
906   if (state->m_cartridge[state->m_current_cartridge].ROM && state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
907   {
908      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
909      state->m_banking_cart[1] = state->m_cartridge[state->m_current_cartridge].ROM + ((rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
910      state->m_banking_cart[2] = state->m_banking_cart[1] + 0x0400;
911      memory_set_bankptr(space->machine(), "bank1", state->m_banking_cart[1]);
912      memory_set_bankptr(space->machine(), "bank2", state->m_banking_cart[2]);
913   }
914}
915
916
917static WRITE8_HANDLER( sms_codemasters_page1_w )
918{
919   sms_state *state = space->machine().driver_data<sms_state>();
920
921   if (state->m_cartridge[state->m_current_cartridge].ROM && state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
922   {
923      /* Check if we need to switch in some RAM */
924      if (data & 0x80)
925      {
926         state->m_cartridge[state->m_current_cartridge].ram_page = data & 0x07;
927         memory_set_bankptr(space->machine(), "bank6", state->m_cartridge[state->m_current_cartridge].cartRAM + state->m_cartridge[state->m_current_cartridge].ram_page * 0x2000);
928      }
929      else
930      {
931         UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
932         state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + ((rom_page_count > 0) ? data % rom_page_count : 0) * 0x4000;
933         memory_set_bankptr(space->machine(), "bank3", state->m_banking_cart[3]);
934         memory_set_bankptr(space->machine(), "bank4", state->m_banking_cart[3] + 0x2000);
935         memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
936      }
937   }
938}
939#endif
940
941static READ8_HANDLER( sms_kor_nobank_r )
942{
943//  printf("read %x\n", offset);
944   return space->read_byte(0xdffc + offset);
945}
946
947static WRITE8_HANDLER( sms_kor_nobank_w )
948{
949   sms_state *state = space->machine().driver_data<sms_state>();
950   UINT8 *SOURCE_BIOS;
951   UINT8 *SOURCE = NULL;
952
953   space->write_byte(0xdffc + offset, data);
954   state->m_mapper[offset] = data;
955
956   // FIXME: the code below (which only handles the BIOS bankswitch at start) should be cleaned up
957   // currently, it's just a stripped down version of sms_mapper_w
958   if (state->m_BIOS)
959      SOURCE_BIOS = state->m_BIOS + ((state->m_bios_page_count > 0) ? data % state->m_bios_page_count : 0) * 0x4000;
960   else
961      SOURCE_BIOS = state->m_banking_none[1];
962
963   if (state->m_bios_port & IO_BIOS_ROM || (state->m_is_gamegear && state->m_BIOS == NULL))
964      return;
965   else
966   {
967      if (!state->m_BIOS)
968         return;
969      SOURCE = SOURCE_BIOS;
970   }
971
972//  printf("write %x, %x\n", offset, data);
973
974   switch (offset)
975   {
976      case 0: /* Control */
977         if (!(data & 0x08)) /* it's not ram */
978         {
979            if (!(state->m_bios_port & IO_BIOS_ROM) && state->m_has_bios)
980            {
981               SOURCE = state->m_banking_bios[5];
982               memory_set_bankptr(space->machine(), "bank5", SOURCE);
983               memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
984            }
985         }
986         break;
987
988      case 1: /* Select 16k ROM bank for 0400-3FFF */
989         state->m_banking_bios[2] = SOURCE_BIOS + 0x0400;
990         memory_set_bankptr(space->machine(), "bank2", SOURCE + 0x0400);
991         break;
992
993      case 2: /* Select 16k ROM bank for 4000-7FFF */
994         state->m_banking_bios[3] = SOURCE_BIOS;
995         memory_set_bankptr(space->machine(), "bank3", SOURCE);
996         memory_set_bankptr(space->machine(), "bank4", SOURCE + 0x2000);
997         break;
998
999      case 3: /* Select 16k ROM bank for 8000-BFFF */
1000         state->m_banking_bios[5] = SOURCE_BIOS;
1001         if (!(state->m_mapper[0] & 0x08)) /* is RAM disabled? */
1002         {
1003            memory_set_bankptr(space->machine(), "bank5", SOURCE);
1004            memory_set_bankptr(space->machine(), "bank6", SOURCE + 0x2000);
1005         }
1006         break;
1007   }
1008}
1009
1010WRITE8_HANDLER( sms_bios_w )
1011{
1012   sms_state *state = space->machine().driver_data<sms_state>();
1013   state->m_bios_port = data;
1014
1015   logerror("bios write %02x, pc: %04x\n", data, cpu_get_pc(&space->device()));
1016
1017   setup_rom(space);
1018}
1019
1020
1021WRITE8_HANDLER( sms_cartram2_w )
1022{
1023   sms_state *state = space->machine().driver_data<sms_state>();
1024
1025   if (state->m_mapper[0] & 0x08)
1026   {
1027      logerror("write %02X to cartram at offset #%04X\n", data, offset + 0x2000);
1028      if (state->m_mapper[0] & 0x04)
1029      {
1030         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x6000] = data;
1031      }
1032      else
1033      {
1034         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x2000] = data;
1035      }
1036   }
1037
1038   if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1039   {
1040      state->m_cartridge[state->m_current_cartridge].cartRAM[state->m_cartridge[state->m_current_cartridge].ram_page * 0x2000 + offset] = data;
1041   }
1042
1043   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_MAPPER && offset == 0) /* Dodgeball King mapper */
1044   {
1045      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1046      int page = (rom_page_count > 0) ? data % rom_page_count : 0;
1047
1048      if (!state->m_cartridge[state->m_current_cartridge].ROM)
1049         return;
1050
1051      state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x4000;
1052      memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
1053      memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
1054      LOG(("rom 2 paged in %x (Korean mapper).\n", page));
1055   }
1056}
1057
1058
1059WRITE8_HANDLER( sms_cartram_w )
1060{
1061   sms_state *state = space->machine().driver_data<sms_state>();
1062   int page;
1063
1064   if (state->m_mapper[0] & 0x08)
1065   {
1066      logerror("write %02X to cartram at offset #%04X\n", data, offset);
1067      if (state->m_mapper[0] & 0x04)
1068      {
1069         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset + 0x4000] = data;
1070      }
1071      else
1072      {
1073         state->m_cartridge[state->m_current_cartridge].cartSRAM[offset] = data;
1074      }
1075   }
1076   else
1077   {
1078      if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER && offset == 0) /* Codemasters mapper */
1079      {
1080         UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1081         page = (rom_page_count > 0) ? data % rom_page_count : 0;
1082         if (!state->m_cartridge[state->m_current_cartridge].ROM)
1083            return;
1084         state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + page * 0x4000;
1085         memory_set_bankptr(space->machine(), "bank5", state->m_banking_cart[5]);
1086         memory_set_bankptr(space->machine(), "bank6", state->m_banking_cart[5] + 0x2000);
1087         LOG(("rom 2 paged in %x (Codemasters mapper).\n", page));
1088      }
1089      else if (state->m_cartridge[state->m_current_cartridge].features & CF_ONCART_RAM)
1090      {
1091         state->m_cartridge[state->m_current_cartridge].cartRAM[offset & (state->m_cartridge[state->m_current_cartridge].ram_size - 1)] = data;
1092      }
1093      else
1094      {
1095         logerror("INVALID write %02X to cartram at offset #%04X\n", data, offset);
1096      }
1097   }
1098}
1099
1100
1101WRITE8_HANDLER( gg_sio_w )
1102{
1103   sms_state *state = space->machine().driver_data<sms_state>();
1104   logerror("*** write %02X to SIO register #%d\n", data, offset);
1105
1106   state->m_gg_sio[offset & 0x07] = data;
1107   switch (offset & 7)
1108   {
1109      case 0x00: /* Parallel Data */
1110         break;
1111
1112      case 0x01: /* Data Direction/ NMI Enable */
1113         break;
1114
1115      case 0x02: /* Serial Output */
1116         break;
1117
1118      case 0x03: /* Serial Input */
1119         break;
1120
1121      case 0x04: /* Serial Control / Status */
1122         break;
1123   }
1124}
1125
1126
1127READ8_HANDLER( gg_sio_r )
1128{
1129   sms_state *state = space->machine().driver_data<sms_state>();
1130   logerror("*** read SIO register #%d\n", offset);
1131
1132   switch (offset & 7)
1133   {
1134      case 0x00: /* Parallel Data */
1135         break;
1136
1137      case 0x01: /* Data Direction/ NMI Enable */
1138         break;
1139
1140      case 0x02: /* Serial Output */
1141         break;
1142
1143      case 0x03: /* Serial Input */
1144         break;
1145
1146      case 0x04: /* Serial Control / Status */
1147         break;
1148   }
1149
1150   return state->m_gg_sio[offset];
1151}
1152
1153static void sms_machine_stop( running_machine &machine )
1154{
1155   sms_state *state = machine.driver_data<sms_state>();
1156
1157   /* Does the cartridge have SRAM that should be saved? */
1158   if (state->m_cartridge[state->m_current_cartridge].sram_save) {
1159      device_image_interface *image = dynamic_cast<device_image_interface *>(machine.device("cart1"));
1160      image->battery_save(state->m_cartridge[state->m_current_cartridge].cartSRAM, sizeof(UINT8) * NVRAM_SIZE );
1161   }
1162}
1163
1164
1165static void setup_rom( address_space *space )
1166{
1167   sms_state *state = space->machine().driver_data<sms_state>();
1168   running_machine &machine = space->machine();
1169
1170   /* 1. set up bank pointers to point to nothing */
1171   memory_set_bankptr(machine, "bank1", state->m_banking_none[1]);
1172   memory_set_bankptr(machine, "bank2", state->m_banking_none[2]);
1173   memory_set_bankptr(machine, "bank3", state->m_banking_none[3]);
1174   memory_set_bankptr(machine, "bank4", state->m_banking_none[3] + 0x2000);
1175   memory_set_bankptr(machine, "bank5", state->m_banking_none[5]);
1176   memory_set_bankptr(machine, "bank6", state->m_banking_none[5] + 0x2000);
1177
1178   /* 2. check and set up expansion port */
1179   if (!(state->m_bios_port & IO_EXPANSION) && (state->m_bios_port & IO_CARTRIDGE) && (state->m_bios_port & IO_CARD))
1180   {
1181      /* TODO: Implement me */
1182      logerror("Switching to unsupported expansion port.\n");
1183   }
1184
1185   /* 3. check and set up card rom */
1186   if (!(state->m_bios_port & IO_CARD) && (state->m_bios_port & IO_CARTRIDGE) && (state->m_bios_port & IO_EXPANSION))
1187   {
1188      /* TODO: Implement me */
1189      logerror("Switching to unsupported card rom port.\n");
1190   }
1191
1192   /* 4. check and set up cartridge rom */
1193   /* if ((!(bios_port & IO_CARTRIDGE) && (bios_port & IO_EXPANSION) && (bios_port & IO_CARD)) || state->m_is_gamegear) { */
1194   /* Out Run Europa initially writes a value to port 3E where IO_CARTRIDGE, IO_EXPANSION and IO_CARD are reset */
1195   if ((!(state->m_bios_port & IO_CARTRIDGE)) || state->m_is_gamegear)
1196   {
1197      memory_set_bankptr(machine, "bank1", state->m_banking_cart[1]);
1198      memory_set_bankptr(machine, "bank2", state->m_banking_cart[2]);
1199      memory_set_bankptr(machine, "bank3", state->m_banking_cart[3]);
1200      memory_set_bankptr(machine, "bank4", state->m_banking_cart[3] + 0x2000);
1201      memory_set_bankptr(machine, "bank5", state->m_banking_cart[5]);
1202      memory_set_bankptr(machine, "bank6", state->m_banking_cart[5] + 0x2000);
1203      logerror("Switched in cartridge rom.\n");
1204   }
1205
1206   /* 5. check and set up bios rom */
1207   if (!(state->m_bios_port & IO_BIOS_ROM))
1208   {
1209      /* 0x0400 bioses */
1210      if (state->m_has_bios_0400)
1211      {
1212         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1213         logerror("Switched in 0x0400 bios.\n");
1214      }
1215      /* 0x2000 bioses */
1216      if (state->m_has_bios_2000)
1217      {
1218         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1219         memory_set_bankptr(machine, "bank2", state->m_banking_bios[2]);
1220         logerror("Switched in 0x2000 bios.\n");
1221      }
1222      if (state->m_has_bios_full)
1223      {
1224         memory_set_bankptr(machine, "bank1", state->m_banking_bios[1]);
1225         memory_set_bankptr(machine, "bank2", state->m_banking_bios[2]);
1226         memory_set_bankptr(machine, "bank3", state->m_banking_bios[3]);
1227         memory_set_bankptr(machine, "bank4", state->m_banking_bios[3] + 0x2000);
1228         memory_set_bankptr(machine, "bank5", state->m_banking_bios[5]);
1229         memory_set_bankptr(machine, "bank6", state->m_banking_bios[5] + 0x2000);
1230         logerror("Switched in full bios.\n");
1231      }
1232   }
1233
1234   if (state->m_cartridge[state->m_current_cartridge].features & CF_ONCART_RAM)
1235   {
1236      memory_set_bankptr(machine, "bank5", state->m_cartridge[state->m_current_cartridge].cartRAM);
1237      memory_set_bankptr(machine, "bank6", state->m_cartridge[state->m_current_cartridge].cartRAM);
1238   }
1239}
1240
1241
1242static int sms_verify_cart( UINT8 *magic, int size )
1243{
1244   int retval;
1245
1246   retval = IMAGE_VERIFY_FAIL;
1247
1248   /* Verify the file is a valid image - check $7ff0 for "TMR SEGA" */
1249   if (size >= 0x8000)
1250   {
1251      if (!strncmp((char*)&magic[0x7ff0], "TMR SEGA", 8))
1252      {
1253#if 0
1254         /* Technically, it should be this, but remove for now until verified: */
1255         if (!strcmp(sysname, "gamegear"))
1256         {
1257            if ((unsigned char)magic[0x7ffd] < 0x50)
1258               retval = IMAGE_VERIFY_PASS;
1259         }
1260         if (!strcmp(sysname, "sms"))
1261         {
1262            if ((unsigned char)magic[0x7ffd] >= 0x50)
1263               retval = IMAGE_VERIFY_PASS;
1264         }
1265#endif
1266         retval = IMAGE_VERIFY_PASS;
1267      }
1268
1269#if 0
1270      /* Check at $81f0 also */
1271      if (!retval)
1272      {
1273         if (!strncmp(&magic[0x81f0], "TMR SEGA", 8))
1274         {
1275#if 0
1276            /* Technically, it should be this, but remove for now until verified: */
1277            if (!strcmp(sysname, "gamegear"))
1278            {
1279               if ((unsigned char)magic[0x81fd] < 0x50)
1280                  retval = IMAGE_VERIFY_PASS;
1281            }
1282            if (!strcmp(sysname, "sms"))
1283            {
1284               if ((unsigned char)magic[0x81fd] >= 0x50)
1285                  retval = IMAGE_VERIFY_PASS;
1286            }
1287#endif
1288            retval = IMAGE_VERIFY_PASS;
1289         }
1290      }
1291#endif
1292
1293   }
1294
1295   return retval;
1296}
1297
1298#ifdef UNUSED_FUNCTION
1299// For the moment we switch to a different detection routine which allows to detect
1300// in a single run Codemasters mapper, Korean mapper (including Jang Pung 3 which
1301// uses a diff signature then the one below here) and Zemina mapper (used by Wonsiin, etc.).
1302// I leave these here to document alt. detection routines and in the case these functions
1303// can be updated
1304
1305/* Check for Codemasters mapper
1306  0x7FE3 - 93 - sms Cosmis Spacehead
1307              - sms Dinobasher
1308              - sms The Excellent Dizzy Collection
1309              - sms Fantastic Dizzy
1310              - sms Micro Machines
1311              - gamegear Cosmic Spacehead
1312              - gamegear Micro Machines
1313         - 94 - gamegear Dropzone
1314              - gamegear Ernie Els Golf (also has 64KB additional RAM on the cartridge)
1315              - gamegear Pete Sampras Tennis
1316              - gamegear S.S. Lucifer
1317         - 95 - gamegear Micro Machines 2 - Turbo Tournament
1318
1319The Korean game Jang Pung II also seems to use a codemasters style mapper.
1320 */
1321static int detect_codemasters_mapper( UINT8 *rom )
1322{
1323   static const UINT8 jang_pung2[16] = { 0x00, 0xba, 0x38, 0x0d, 0x00, 0xb8, 0x38, 0x0c, 0x00, 0xb6, 0x38, 0x0b, 0x00, 0xb4, 0x38, 0x0a };
1324
1325   if (((rom[0x7fe0] & 0x0f ) <= 9) && (rom[0x7fe3] == 0x93 || rom[0x7fe3] == 0x94 || rom[0x7fe3] == 0x95) &&  rom[0x7fef] == 0x00)
1326      return 1;
1327
1328   if (!memcmp(&rom[0x7ff0], jang_pung2, 16))
1329      return 1;
1330
1331   return 0;
1332}
1333
1334
1335static int detect_korean_mapper( UINT8 *rom )
1336{
1337   static const UINT8 signatures[2][16] =
1338   {
1339      { 0x3e, 0x11, 0x32, 0x00, 0xa0, 0x78, 0xcd, 0x84, 0x85, 0x3e, 0x02, 0x32, 0x00, 0xa0, 0xc9, 0xff }, /* Dodgeball King */
1340      { 0x41, 0x48, 0x37, 0x37, 0x44, 0x37, 0x4e, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x20 },   /* Sangokushi 3 */
1341   };
1342   int i;
1343
1344   for (i = 0; i < 2; i++)
1345   {
1346      if (!memcmp(&rom[0x7ff0], signatures[i], 16))
1347      {
1348         return 1;
1349      }
1350   }
1351   return 0;
1352}
1353#endif
1354
1355
1356static int detect_tvdraw( UINT8 *rom )
1357{
1358   static const UINT8 terebi_oekaki[7] = { 0x61, 0x6e, 0x6e, 0x61, 0x6b, 0x6d, 0x6e };   // "annakmn"
1359
1360   if (!memcmp(&rom[0x13b3], terebi_oekaki, 7))
1361      return 1;
1362
1363   return 0;
1364}
1365
1366
1367static int detect_lphaser_xoffset( running_machine &machine, UINT8 *rom )
1368{
1369   sms_state *state = machine.driver_data<sms_state>();
1370
1371   static const UINT8 signatures[6][16] =
1372   {
1373      /* Spacegun */
1374      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0xff, 0xff, 0x9d, 0x99, 0x10, 0x90, 0x00, 0x40 },
1375      /* Gangster Town */
1376      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x19, 0x87, 0x1b, 0xc9, 0x74, 0x50, 0x00, 0x4f },
1377      /* Shooting Gallery */
1378      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x20, 0x20, 0x8a, 0x3a, 0x72, 0x50, 0x00, 0x4f },
1379      /* Rescue Mission */
1380      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x20, 0x20, 0xfb, 0xd3, 0x06, 0x51, 0x00, 0x4f },
1381      /* Laser Ghost */
1382      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0x00, 0x00, 0xb7, 0x55, 0x74, 0x70, 0x00, 0x40 },
1383      /* Assault City */
1384      { 0x54, 0x4d, 0x52, 0x20, 0x53, 0x45, 0x47, 0x41, 0xff, 0xff, 0x9f, 0x74, 0x34, 0x70, 0x00, 0x40 },
1385   };
1386
1387   if (!(state->m_bios_port & IO_CARTRIDGE) && state->m_cartridge[state->m_current_cartridge].size >= 0x8000)
1388   {
1389      if (!memcmp(&rom[0x7ff0], signatures[0], 16) || !memcmp(&rom[0x7ff0], signatures[1], 16))
1390         return 40;
1391
1392      if (!memcmp(&rom[0x7ff0], signatures[2], 16))
1393         return 49;
1394
1395      if (!memcmp(&rom[0x7ff0], signatures[3], 16))
1396         return 47;
1397
1398      if (!memcmp(&rom[0x7ff0], signatures[4], 16))
1399         return 44;
1400
1401      if (!memcmp(&rom[0x7ff0], signatures[5], 16))
1402         return 53;
1403
1404   }
1405   return 50;
1406}
1407
1408
1409DEVICE_START( sms_cart )
1410{
1411   sms_state *state = device->machine().driver_data<sms_state>();
1412   int i;
1413
1414   for (i = 0; i < MAX_CARTRIDGES; i++)
1415   {
1416      state->m_cartridge[i].ROM = NULL;
1417      state->m_cartridge[i].size = 0;
1418      state->m_cartridge[i].features = 0;
1419      state->m_cartridge[i].cartSRAM = NULL;
1420      state->m_cartridge[i].sram_save = 0;
1421      state->m_cartridge[i].cartRAM = NULL;
1422      state->m_cartridge[i].ram_size = 0;
1423      state->m_cartridge[i].ram_page = 0;
1424   }
1425   state->m_current_cartridge = 0;
1426
1427   state->m_bios_port = (IO_EXPANSION | IO_CARTRIDGE | IO_CARD);
1428   if (!state->m_is_gamegear && !state->m_has_bios)
1429   {
1430      state->m_bios_port &= ~(IO_CARTRIDGE);
1431      state->m_bios_port |= IO_BIOS_ROM;
1432   }
1433}
1434
1435
1436DEVICE_IMAGE_LOAD( sms_cart )
1437{
1438   running_machine &machine = image.device().machine();
1439   sms_state *state = machine.driver_data<sms_state>();
1440   int size, index = 0, offset = 0;
1441   const char *extrainfo = NULL;
1442
1443   if (strcmp(image.device().tag(), "cart1") == 0)
1444      index = 0;
1445   if (strcmp(image.device().tag(), "cart2") == 0)
1446      index = 1;
1447   if (strcmp(image.device().tag(), "cart3") == 0)
1448      index = 2;
1449   if (strcmp(image.device().tag(), "cart4") == 0)
1450      index = 3;
1451   if (strcmp(image.device().tag(), "cart5") == 0)
1452      index = 4;
1453   if (strcmp(image.device().tag(), "cart6") == 0)
1454      index = 5;
1455   if (strcmp(image.device().tag(), "cart7") == 0)
1456      index = 6;
1457   if (strcmp(image.device().tag(), "cart8") == 0)
1458      index = 7;
1459   if (strcmp(image.device().tag(), "cart9") == 0)
1460      index = 8;
1461   if (strcmp(image.device().tag(), "cart10") == 0)
1462      index = 9;
1463   if (strcmp(image.device().tag(), "cart11") == 0)
1464      index = 10;
1465   if (strcmp(image.device().tag(), "cart12") == 0)
1466      index = 11;
1467   if (strcmp(image.device().tag(), "cart13") == 0)
1468      index = 12;
1469   if (strcmp(image.device().tag(), "cart14") == 0)
1470      index = 13;
1471   if (strcmp(image.device().tag(), "cart15") == 0)
1472      index = 14;
1473   if (strcmp(image.device().tag(), "cart16") == 0)
1474      index = 15;
1475
1476   state->m_cartridge[index].features = 0;
1477
1478   if (image.software_entry() == NULL)
1479   {
1480      size = image.length();
1481      extrainfo = hashfile_extrainfo(image);
1482   }
1483   else
1484      size = image.get_software_region_length("rom");
1485
1486   /* Check for 512-byte header */
1487   if ((size / 512) & 1)
1488   {
1489      offset = 512;
1490      size -= 512;
1491   }
1492
1493   if (!size)
1494   {
1495      image.seterror(IMAGE_ERROR_UNSPECIFIED, "Invalid ROM image: ROM image is too small");
1496      return IMAGE_INIT_FAIL;
1497   }
1498
1499   /* Create a new memory region to hold the ROM. */
1500   /* Make sure the region holds only complete (0x4000) rom banks */
1501   state->m_cartridge[index].size = (size & 0x3fff) ? (((size >> 14) + 1) << 14) : size;
1502   state->m_cartridge[index].ROM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].size);
1503   state->m_cartridge[index].cartSRAM = auto_alloc_array(machine, UINT8, NVRAM_SIZE);
1504
1505   /* Load ROM banks */
1506   if (image.software_entry() == NULL)
1507   {
1508      image.fseek(offset, SEEK_SET);
1509
1510      if (image.fread( state->m_cartridge[index].ROM, size) != size)
1511         return IMAGE_INIT_FAIL;
1512   }
1513   else
1514   {
1515      memcpy(state->m_cartridge[index].ROM, image.get_software_region("rom") + offset, size);
1516
1517      // check for mapper feature (currently only KOREAN_NOBANK, but eventually we will add the other mappers as well)
1518      if (image.get_feature("pcb") != NULL)
1519      {
1520         const char *mapper = image.get_feature("pcb");
1521         if (!strcmp(mapper, "korean_nobank"))
1522            state->m_cartridge[index].features |= CF_KOREAN_NOBANK_MAPPER;
1523      }
1524   }
1525
1526   /* check the image */
1527   if (!state->m_has_bios)
1528   {
1529      if (sms_verify_cart(state->m_cartridge[index].ROM, size) == IMAGE_VERIFY_FAIL)
1530      {
1531         logerror("Warning loading image: sms_verify_cart failed\n");
1532      }
1533   }
1534
1535   /* Detect special features from the extrainfo field */
1536   if (extrainfo)
1537   {
1538      /* Check for codemasters mapper */
1539      if (strstr(extrainfo, "CODEMASTERS"))
1540         state->m_cartridge[index].features |= CF_CODEMASTERS_MAPPER;
1541
1542      /* Check for korean mapper */
1543      if (strstr(extrainfo, "KOREAN"))
1544         state->m_cartridge[index].features |= CF_KOREAN_MAPPER;
1545
1546      /* Check for special SMS Compatibility mode gamegear cartridges */
1547      if (state->m_is_gamegear && strstr(extrainfo, "GGSMS"))
1548         state->m_cartridge[index].features |= CF_GG_SMS_MODE;
1549
1550      /* Check for 93C46 eeprom */
1551      if (strstr(extrainfo, "93C46"))
1552         state->m_cartridge[index].features |= CF_93C46_EEPROM;
1553
1554      /* Check for 8KB on-cart RAM */
1555      if (strstr(extrainfo, "8KB_CART_RAM"))
1556      {
1557         state->m_cartridge[index].features |= CF_ONCART_RAM;
1558         state->m_cartridge[index].ram_size = 0x2000;
1559         state->m_cartridge[index].cartRAM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].ram_size);
1560      }
1561   }
1562   else
1563   {
1564      /* If no extrainfo information is available try to find special information out on our own */
1565      /* Check for special cartridge features (new routine, courtesy of Omar Cornut, from MEKA)  */
1566      if (size >= 0x8000)
1567      {
1568         int c0002 = 0, c8000 = 0, cA000 = 0, cFFFF = 0, i;
1569         for (i = 0; i < 0x8000; i++)
1570         {
1571            if (state->m_cartridge[index].ROM[i] == 0x32) // Z80 opcode for: LD (xxxx), A
1572            {
1573               UINT16 addr = (state->m_cartridge[index].ROM[i + 2] << 8) | state->m_cartridge[index].ROM[i + 1];
1574               if (addr == 0xFFFF)
1575               { i += 2; cFFFF++; continue; }
1576               if (addr == 0x0002 || addr == 0x0003 || addr == 0x0004)
1577               { i += 2; c0002++; continue; }
1578               if (addr == 0x8000)
1579               { i += 2; c8000++; continue; }
1580               if (addr == 0xA000)
1581               { i += 2; cA000++; continue; }
1582            }
1583         }
1584
1585         LOG(("Mapper test: c002 = %d, c8000 = %d, cA000 = %d, cFFFF = %d\n", c0002, c8000, cA000, cFFFF));
1586
1587         // 2 is a security measure, although tests on existing ROM showed it was not needed
1588         if (c0002 > cFFFF + 2 || (c0002 > 0 && cFFFF == 0))
1589            state->m_cartridge[index].features |= CF_KOREAN_ZEMINA_MAPPER;
1590         else if (c8000 > cFFFF + 2 || (c8000 > 0 && cFFFF == 0))
1591            state->m_cartridge[index].features |= CF_CODEMASTERS_MAPPER;
1592         else if (cA000 > cFFFF + 2 || (cA000 > 0 && cFFFF == 0))
1593            state->m_cartridge[index].features |= CF_KOREAN_MAPPER;
1594
1595      }
1596
1597      /* Check for special SMS Compatibility mode gamegear cartridges */
1598      if (state->m_is_gamegear && image.software_entry() == NULL)   // not sure about how to handle this with softlists
1599      {
1600         /* Just in case someone passes us an sms file */
1601         if (!mame_stricmp (image.filetype(), "sms"))
1602            state->m_cartridge[index].features |= CF_GG_SMS_MODE;
1603      }
1604   }
1605
1606   if (state->m_cartridge[index].features & CF_CODEMASTERS_MAPPER)
1607   {
1608      state->m_cartridge[index].ram_size = 0x10000;
1609      state->m_cartridge[index].cartRAM = auto_alloc_array(machine, UINT8, state->m_cartridge[index].ram_size);
1610      state->m_cartridge[index].ram_page = 0;
1611   }
1612
1613   /* For Light Phaser games, we have to detect the x offset */
1614   state->m_lphaser_x_offs = detect_lphaser_xoffset(machine, state->m_cartridge[index].ROM);
1615
1616   /* Terebi Oekaki (TV Draw) is a SG1000 game with special input device which is compatible with SG1000 Mark III */
1617   if ((detect_tvdraw(state->m_cartridge[index].ROM)) && state->m_is_region_japan)
1618   {
1619      address_space *program = machine.device("maincpu")->memory().space(AS_PROGRAM);
1620      program->install_legacy_write_handler(0x6000, 0x6000, FUNC(sms_tvdraw_axis_w));
1621      program->install_legacy_read_handler(0x8000, 0x8000, FUNC(sms_tvdraw_status_r));
1622      program->install_legacy_read_handler(0xa000, 0xa000, FUNC(sms_tvdraw_data_r));
1623      program->nop_write(0xa000, 0xa000);
1624   }
1625
1626   if (state->m_cartridge[index].features & CF_KOREAN_NOBANK_MAPPER)
1627   {
1628      // FIXME: we should have by default FFFD-FFFF to be only a mirror for DFFD-DFFF (with no bankswitch logic)
1629      // and then the handlers should be installed here for all but the KOREAN_NOBANK carts
1630      // However, to avoid memory map breakage, we currently go the other way around
1631      address_space *program = machine.device("maincpu")->memory().space(AS_PROGRAM);
1632      program->install_legacy_readwrite_handler(0xfffc, 0xffff, FUNC(sms_kor_nobank_r), FUNC(sms_kor_nobank_w));
1633   }
1634
1635   LOG(("Cart Features: %x\n", state->m_cartridge[index].features));
1636
1637   /* Load battery backed RAM, if available */
1638   image.battery_load(state->m_cartridge[index].cartSRAM, sizeof(UINT8) * NVRAM_SIZE, 0x00);
1639
1640   return IMAGE_INIT_PASS;
1641}
1642
1643
1644static void setup_cart_banks( running_machine &machine )
1645{
1646   sms_state *state = machine.driver_data<sms_state>();
1647   if (state->m_cartridge[state->m_current_cartridge].ROM)
1648   {
1649      UINT8 rom_page_count = state->m_cartridge[state->m_current_cartridge].size / 0x4000;
1650      state->m_banking_cart[1] = state->m_cartridge[state->m_current_cartridge].ROM;
1651      state->m_banking_cart[2] = state->m_cartridge[state->m_current_cartridge].ROM + 0x0400;
1652      state->m_banking_cart[3] = state->m_cartridge[state->m_current_cartridge].ROM + ((1 < rom_page_count) ? 0x4000 : 0);
1653      state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM + ((2 < rom_page_count) ? 0x8000 : 0);
1654      /* Codemasters mapper points to bank 0 for page 2 */
1655      if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1656      {
1657         state->m_banking_cart[5] = state->m_cartridge[state->m_current_cartridge].ROM;
1658      }
1659   }
1660   else
1661   {
1662      state->m_banking_cart[1] = state->m_banking_none[1];
1663      state->m_banking_cart[2] = state->m_banking_none[2];
1664      state->m_banking_cart[3] = state->m_banking_none[3];
1665      state->m_banking_cart[5] = state->m_banking_none[5];
1666   }
1667}
1668
1669#ifdef MESS
1670static void setup_banks( running_machine &machine )
1671{
1672   sms_state *state = machine.driver_data<sms_state>();
1673   UINT8 *mem = machine.region("maincpu")->base();
1674   state->m_banking_bios[1] = state->m_banking_cart[1] = state->m_banking_none[1] = mem;
1675   state->m_banking_bios[2] = state->m_banking_cart[2] = state->m_banking_none[2] = mem;
1676   state->m_banking_bios[3] = state->m_banking_cart[3] = state->m_banking_none[3] = mem;
1677   state->m_banking_bios[4] = state->m_banking_cart[4] = state->m_banking_none[4] = mem;
1678   state->m_banking_bios[5] = state->m_banking_cart[5] = state->m_banking_none[5] = mem;
1679   state->m_banking_bios[6] = state->m_banking_cart[6] = state->m_banking_none[6] = mem;
1680
1681   state->m_BIOS = machine.region("user1")->base();
1682
1683   state->m_bios_page_count = (state->m_BIOS ? machine.region("user1")->bytes() / 0x4000 : 0);
1684
1685   setup_cart_banks(machine);
1686
1687   if (state->m_BIOS == NULL || state->m_BIOS[0] == 0x00)
1688   {
1689      state->m_BIOS = NULL;
1690      state->m_bios_port |= IO_BIOS_ROM;
1691   }
1692
1693   if (state->m_BIOS)
1694   {
1695      state->m_banking_bios[1] = state->m_BIOS;
1696      state->m_banking_bios[2] = state->m_BIOS + 0x0400;
1697      state->m_banking_bios[3] = state->m_BIOS + ((1 < state->m_bios_page_count) ? 0x4000 : 0);
1698      state->m_banking_bios[5] = state->m_BIOS + ((2 < state->m_bios_page_count) ? 0x8000 : 0);
1699   }
1700}
1701#endif
1702
1703MACHINE_START( sms )
1704{
1705   sms_state *state = machine.driver_data<sms_state>();
1706
1707   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(sms_machine_stop),&machine));
1708   state->m_rapid_fire_timer = machine.scheduler().timer_alloc(FUNC(rapid_fire_callback));
1709   state->m_rapid_fire_timer->adjust(attotime::from_hz(10), 0, attotime::from_hz(10));
1710
1711   state->m_lphaser_1_timer = machine.scheduler().timer_alloc(FUNC(lphaser_1_callback));
1712   state->m_lphaser_2_timer = machine.scheduler().timer_alloc(FUNC(lphaser_2_callback));
1713
1714   state->m_main_cpu = machine.device("maincpu");
1715   state->m_control_cpu = machine.device("control");
1716   state->m_vdp = machine.device("sms_vdp");
1717   state->m_ym = machine.device("ym2413");
1718   state->m_main_scr = machine.device("screen");
1719   state->m_left_lcd = machine.device("left_lcd");
1720   state->m_right_lcd = machine.device("right_lcd");
1721
1722   /* Check if lightgun has been chosen as input: if so, enable crosshair */
1723   machine.scheduler().timer_set(attotime::zero, FUNC(lightgun_tick));
1724}
1725
1726#ifdef MESS
1727MACHINE_RESET( sms )
1728{
1729   address_space *space = machine.device("maincpu")->memory().space(AS_PROGRAM);
1730   sms_state *state = machine.driver_data<sms_state>();
1731
1732   state->m_ctrl_reg = 0xff;
1733   if (state->m_has_fm)
1734      state->m_fm_detect = 0x01;
1735
1736   state->m_mapper_ram = (UINT8*)space->get_write_ptr(0xdffc);
1737
1738   state->m_bios_port = 0;
1739
1740   if (state->m_cartridge[state->m_current_cartridge].features & CF_CODEMASTERS_MAPPER)
1741   {
1742      /* Install special memory handlers */
1743      space->install_legacy_write_handler(0x0000, 0x0000, FUNC(sms_codemasters_page0_w));
1744      space->install_legacy_write_handler(0x4000, 0x4000, FUNC(sms_codemasters_page1_w));
1745   }
1746
1747   if (state->m_cartridge[state->m_current_cartridge].features & CF_KOREAN_ZEMINA_MAPPER)
1748      space->install_legacy_write_handler(0x0000, 0x0003, FUNC(sms_korean_zemina_banksw_w));
1749
1750   if (state->m_cartridge[state->m_current_cartridge].features & CF_GG_SMS_MODE)
1751      sms_vdp_set_ggsmsmode(state->m_vdp, 1);
1752
1753   /* Initialize SIO stuff for GG */
1754   state->m_gg_sio[0] = 0x7f;
1755   state->m_gg_sio[1] = 0xff;
1756   state->m_gg_sio[2] = 0x00;
1757   state->m_gg_sio[3] = 0xff;
1758   state->m_gg_sio[4] = 0x00;
1759
1760   state->m_store_control = 0;
1761
1762   setup_banks(machine);
1763
1764   setup_rom(space);
1765
1766   state->m_rapid_fire_state_1 = 0;
1767   state->m_rapid_fire_state_2 = 0;
1768
1769   state->m_last_paddle_read_time = 0;
1770   state->m_paddle_read_state = 0;
1771
1772   state->m_last_sports_pad_time_1 = 0;
1773   state->m_last_sports_pad_time_2 = 0;
1774   state->m_sports_pad_state_1 = 0;
1775   state->m_sports_pad_state_2 = 0;
1776   state->m_sports_pad_last_data_1 = 0;
1777   state->m_sports_pad_last_data_2 = 0;
1778   state->m_sports_pad_1_x = 0;
1779   state->m_sports_pad_1_y = 0;
1780   state->m_sports_pad_2_x = 0;
1781   state->m_sports_pad_2_y = 0;
1782
1783   state->m_lphaser_1_latch = 0;
1784   state->m_lphaser_2_latch = 0;
1785
1786   state->m_sscope_state = 0;
1787
1788   state->m_tvdraw_data = 0;
1789}
1790#endif
1791
1792READ8_HANDLER( sms_store_cart_select_r )
1793{
1794   return 0xff;
1795}
1796
1797
1798WRITE8_HANDLER( sms_store_cart_select_w )
1799{
1800   sms_state *state = space->machine().driver_data<sms_state>();
1801   UINT8 slot = data >> 4;
1802   UINT8 slottype = data & 0x08;
1803
1804   logerror("switching in part of %s slot #%d\n", slottype ? "card" : "cartridge", slot );
1805   /* cartridge? slot #0 */
1806   if (slottype == 0)
1807      state->m_current_cartridge = slot;
1808
1809   setup_cart_banks(space->machine());
1810   memory_set_bankptr(space->machine(), "bank10", state->m_banking_cart[3] + 0x2000);
1811   setup_rom(space);
1812}
1813
1814
1815READ8_HANDLER( sms_store_select1 )
1816{
1817   return 0xff;
1818}
1819
1820
1821READ8_HANDLER( sms_store_select2 )
1822{
1823   return 0xff;
1824}
1825
1826
1827READ8_HANDLER( sms_store_control_r )
1828{
1829   sms_state *state = space->machine().driver_data<sms_state>();
1830   return state->m_store_control;
1831}
1832
1833
1834WRITE8_HANDLER( sms_store_control_w )
1835{
1836   sms_state *state = space->machine().driver_data<sms_state>();
1837   logerror("0x%04X: sms_store_control write 0x%02X\n", cpu_get_pc(&space->device()), data);
1838   if (data & 0x02)
1839   {
1840      space->machine().device<cpu_device>("maincpu")->resume(SUSPEND_REASON_HALT);
1841   }
1842   else
1843   {
1844      /* Pull reset line of CPU #0 low */
1845      space->machine().device("maincpu")->reset();
1846      space->machine().device<cpu_device>("maincpu")->suspend(SUSPEND_REASON_HALT, 1);
1847   }
1848   state->m_store_control = data;
1849}
1850
1851void sms_store_int_callback( running_machine &machine, int state )
1852{
1853   sms_state *driver_state = machine.driver_data<sms_state>();
1854   device_set_input_line(driver_state->m_store_control & 0x01 ? driver_state->m_control_cpu : driver_state->m_main_cpu, 0, state);
1855}
1856
1857
1858static void sms_set_zero_flag( running_machine &machine )
1859{
1860   sms_state *state = machine.driver_data<sms_state>();
1861   state->m_is_gamegear = 0;
1862   state->m_is_region_japan = 0;
1863   state->m_has_bios_0400 = 0;
1864   state->m_has_bios_2000 = 0;
1865   state->m_has_bios_full = 0;
1866   state->m_has_bios = 0;
1867   state->m_has_fm = 0;
1868}
1869
1870DRIVER_INIT( sg1000m3 )
1871{
1872   sms_state *state = machine.driver_data<sms_state>();
1873   sms_set_zero_flag(machine);
1874   state->m_is_region_japan = 1;
1875   state->m_has_fm = 1;
1876}
1877
1878
1879DRIVER_INIT( sms1 )
1880{
1881   sms_state *state = machine.driver_data<sms_state>();
1882   sms_set_zero_flag(machine);
1883   state->m_has_bios_full = 1;
1884}
1885
1886
1887DRIVER_INIT( smsj )
1888{
1889   sms_state *state = machine.driver_data<sms_state>();
1890   sms_set_zero_flag(machine);
1891   state->m_is_region_japan = 1;
1892   state->m_has_bios_2000 = 1;
1893   state->m_has_fm = 1;
1894}
1895
1896
1897DRIVER_INIT( sms2kr )
1898{
1899   sms_state *state = machine.driver_data<sms_state>();
1900   sms_set_zero_flag(machine);
1901   state->m_is_region_japan = 1;
1902   state->m_has_bios_full = 1;
1903   state->m_has_fm = 1;
1904}
1905
1906
1907DRIVER_INIT( smssdisp )
1908{
1909   sms_set_zero_flag(machine);
1910}
1911
1912
1913DRIVER_INIT( gamegear )
1914{
1915   sms_state *state = machine.driver_data<sms_state>();
1916   sms_set_zero_flag(machine);
1917   state->m_is_gamegear = 1;
1918}
1919
1920
1921DRIVER_INIT( gamegeaj )
1922{
1923   sms_state *state = machine.driver_data<sms_state>();
1924   sms_set_zero_flag(machine);
1925   state->m_is_region_japan = 1;
1926   state->m_is_gamegear = 1;
1927   state->m_has_bios_0400 = 1;
1928}
1929
1930
1931static void sms_black_bitmap( const screen_device *screen, bitmap_t *bitmap )
1932{
1933   const int width = screen->width();
1934   const int height = screen->height();
1935   int x, y;
1936
1937   for (y = 0; y < height; y++)
1938      for (x = 0; x < width; x++)
1939         *BITMAP_ADDR32(bitmap, y, x) = MAKE_RGB(0,0,0);
1940}
1941
1942VIDEO_START( sms1 )
1943{
1944   sms_state *state = machine.driver_data<sms_state>();
1945   screen_device *screen = machine.first_screen();
1946   int width = screen->width();
1947   int height = screen->height();
1948
1949   state->m_prevleft_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
1950   state->m_prevright_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
1951   state->save_item(NAME(*state->m_prevleft_bitmap));
1952   state->save_item(NAME(*state->m_prevright_bitmap));
1953}
1954
1955SCREEN_UPDATE( sms1 )
1956{
1957   sms_state *state = screen->machine().driver_data<sms_state>();
1958   UINT8 sscope = input_port_read_safe(screen->machine(), "SEGASCOPE", 0x00);
1959   UINT8 sscope_binocular_hack = input_port_read_safe(screen->machine(), "SSCOPE_BINOCULAR", 0x00);
1960   UINT8 occluded_view = 0;
1961
1962   // without SegaScope, both LCDs for glasses go black
1963   if ((screen != state->m_main_scr) && !sscope)
1964      occluded_view = 1;
1965
1966   // with SegaScope, sscope_state 0 = left screen OFF, right screen ON
1967   if (!(state->m_sscope_state & 0x01) && (screen == state->m_left_lcd))
1968      occluded_view = 1;
1969
1970   // with SegaScope, sscope_state 1 = left screen ON, right screen OFF
1971   if ((state->m_sscope_state & 0x01) && (screen == state->m_right_lcd))
1972      occluded_view = 1;
1973
1974   if (!occluded_view)
1975   {
1976      sms_vdp_update(state->m_vdp, bitmap, cliprect);
1977
1978      // HACK: fake 3D->2D handling (if enabled, it repeats each frame twice on the selected lens)
1979      // save a copy of current bitmap for the binocular hack
1980      if (sscope && (screen == state->m_left_lcd) && (sscope_binocular_hack & 0x01))
1981         copybitmap(state->m_prevleft_bitmap, bitmap, 0, 0, 0, 0, cliprect);
1982      if (sscope && (screen == state->m_right_lcd) && (sscope_binocular_hack & 0x02))
1983         copybitmap(state->m_prevright_bitmap, bitmap, 0, 0, 0, 0, cliprect);
1984   }
1985   else
1986   {
1987      sms_black_bitmap(screen, bitmap);
1988
1989      // HACK: fake 3D->2D handling (if enabled, it repeats each frame twice on the selected lens)
1990      // use the copied bitmap for the binocular hack
1991      if (sscope && (screen == state->m_left_lcd) && (sscope_binocular_hack & 0x01))
1992         copybitmap(bitmap, state->m_prevleft_bitmap, 0, 0, 0, 0, cliprect);
1993      if (sscope && (screen == state->m_right_lcd) && (sscope_binocular_hack & 0x02))
1994         copybitmap(bitmap, state->m_prevright_bitmap, 0, 0, 0, 0, cliprect);
1995   }
1996
1997   return 0;
1998}
1999
2000SCREEN_UPDATE( sms )
2001{
2002   sms_state *state = screen->machine().driver_data<sms_state>();
2003   sms_vdp_update(state->m_vdp, bitmap, cliprect);
2004   return 0;
2005}
2006
2007VIDEO_START( gamegear )
2008{
2009   sms_state *state = machine.driver_data<sms_state>();
2010   screen_device *screen = machine.first_screen();
2011   int width = screen->width();
2012   int height = screen->height();
2013
2014   state->m_prev_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
2015   state->m_tmp_bitmap = auto_bitmap_alloc(machine, width, height, BITMAP_FORMAT_INDEXED32);
2016   state->save_item(NAME(*state->m_prev_bitmap));
2017}
2018
2019SCREEN_UPDATE( gamegear )
2020{
2021   sms_state *state = screen->machine().driver_data<sms_state>();
2022   int width = screen->width();
2023   int height = screen->height();
2024   int x, y;
2025
2026   sms_vdp_update(state->m_vdp, state->m_tmp_bitmap, cliprect);
2027
2028   // HACK: fake LCD persistence effect
2029   // (it would be better to generalize this in the core, to be used for all LCD systems)
2030   for (y = 0; y < height; y++)
2031   {
2032      UINT32 *line0 = BITMAP_ADDR32(state->m_tmp_bitmap, y, 0);
2033      UINT32 *line1 = BITMAP_ADDR32(state->m_prev_bitmap, y, 0);
2034      for (x = 0; x < width; x++)
2035      {
2036         UINT32 color0 = line0[x];
2037         UINT32 color1 = line1[x];
2038         UINT16 r0 = (color0 >> 16) & 0x000000ff;
2039         UINT16 g0 = (color0 >>  8) & 0x000000ff;
2040         UINT16 b0 = (color0 >>  0) & 0x000000ff;
2041         UINT16 r1 = (color1 >> 16) & 0x000000ff;
2042         UINT16 g1 = (color1 >>  8) & 0x000000ff;
2043         UINT16 b1 = (color1 >>  0) & 0x000000ff;
2044         UINT8 r = (UINT8)((r0 + r1) >> 1);
2045         UINT8 g = (UINT8)((g0 + g1) >> 1);
2046         UINT8 b = (UINT8)((b0 + b1) >> 1);
2047         *BITMAP_ADDR32(bitmap, y, x) = (r << 16) | (g << 8) | b;
2048      }
2049   }
2050   copybitmap(state->m_prev_bitmap, state->m_tmp_bitmap, 0, 0, 0, 0, cliprect);
2051
2052   return 0;
2053}
src/mess/machine/ctronics.c
r11450r11451
1/***************************************************************************
2
3    Centronics printer interface
4
5***************************************************************************/
6
7#include "emu.h"
8#include "ctronics.h"
9#include "imagedev/printer.h"
10
11
12/***************************************************************************
13    FUNCTION PROTOTYPES
14***************************************************************************/
15
16static WRITE_LINE_DEVICE_HANDLER( centronics_printer_online );
17static TIMER_CALLBACK( ack_callback );
18static TIMER_CALLBACK( busy_callback );
19
20
21/***************************************************************************
22    TYPE DEFINITIONS
23***************************************************************************/
24
25typedef struct _centronics_state centronics_state;
26struct _centronics_state
27{
28   device_t *printer;
29
30   devcb_resolved_write_line out_ack_func;
31   devcb_resolved_write_line out_busy_func;
32   devcb_resolved_write_line out_not_busy_func;
33
34   int strobe;
35   int busy;
36   int ack;
37   int auto_fd;
38   int pe;
39   int fault;
40
41   UINT8 data;
42};
43
44
45/*****************************************************************************
46    INLINE FUNCTIONS
47*****************************************************************************/
48
49INLINE centronics_state *get_safe_token(device_t *device)
50{
51   assert(device != NULL);
52   assert(device->type() == CENTRONICS);
53
54   return (centronics_state *)downcast<legacy_device_base *>(device)->token();
55}
56
57
58/*****************************************************************************
59    GLOBAL VARIABLES
60*****************************************************************************/
61
62const centronics_interface standard_centronics =
63{
64   FALSE,
65   DEVCB_NULL,
66   DEVCB_NULL,
67   DEVCB_NULL
68};
69
70
71/*****************************************************************************
72    PRINTER INTERFACE
73*****************************************************************************/
74
75static MACHINE_CONFIG_FRAGMENT( centronics )
76   MCFG_PRINTER_ADD("printer")
77   MCFG_PRINTER_ONLINE(centronics_printer_online)
78MACHINE_CONFIG_END
79
80
81/*****************************************************************************
82    DEVICE INTERFACE
83*****************************************************************************/
84
85static DEVICE_START( centronics )
86{
87   centronics_state *centronics = get_safe_token(device);
88   const centronics_interface *intf = (const centronics_interface *)device->static_config();
89
90   /* validate some basic stuff */
91   assert(device->static_config() != NULL);
92
93   /* set some initial values */
94   centronics->pe = FALSE;
95   centronics->fault = FALSE;
96   centronics->busy = TRUE;
97   centronics->strobe = TRUE;
98
99   /* get printer device */
100   centronics->printer = device->subdevice("printer");
101
102   /* resolve callbacks */
103   centronics->out_ack_func.resolve(intf->out_ack_func, *device);
104   centronics->out_busy_func.resolve(intf->out_busy_func, *device);
105   centronics->out_not_busy_func.resolve(intf->out_not_busy_func, *device);
106
107   /* register for state saving */
108   device->save_item(NAME(centronics->auto_fd));
109   device->save_item(NAME(centronics->strobe));
110   device->save_item(NAME(centronics->busy));
111   device->save_item(NAME(centronics->ack));
112   device->save_item(NAME(centronics->data));
113}
114
115static DEVICE_RESET( centronics )
116{
117}
118
119DEVICE_GET_INFO( centronics )
120{
121   switch (state)
122   {
123      /* --- the following bits of info are returned as 64-bit signed integers --- */
124      case DEVINFO_INT_TOKEN_BYTES:         info->i = sizeof(centronics_state);      break;
125      case DEVINFO_INT_INLINE_CONFIG_BYTES:   info->i = 0;                     break;
126
127      /* --- the following bits of info are returned as pointers --- */
128      case DEVINFO_PTR_MACHINE_CONFIG:      info->machine_config = MACHINE_CONFIG_NAME(centronics);   break;
129
130      /* --- the following bits of info are returned as pointers to data or functions --- */
131      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(centronics);      break;
132      case DEVINFO_FCT_STOP:               /* Nothing */                              break;
133      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(centronics);      break;
134
135      /* --- the following bits of info are returned as NULL-terminated strings --- */
136      case DEVINFO_STR_NAME:               strcpy(info->s, "Centronics");         break;
137      case DEVINFO_STR_FAMILY:            strcpy(info->s, "Centronics");         break;
138      case DEVINFO_STR_VERSION:            strcpy(info->s, "1.0");               break;
139      case DEVINFO_STR_SOURCE_FILE:         strcpy(info->s, __FILE__);            break;
140      case DEVINFO_STR_CREDITS:            strcpy(info->s, "Copyright MESS Team");   break;
141   }
142}
143
144
145/***************************************************************************
146    IMPLEMENTATION
147***************************************************************************/
148
149/*-------------------------------------------------
150    centronics_printer_online - callback that
151    sets us busy when the printer goes offline
152-------------------------------------------------*/
153
154void centronics_printer_online(device_t *device, int state)
155{
156   centronics_state *centronics = get_safe_token(device->owner());
157
158   /* when going online, set PE and FAULT high and BUSY low */
159   centronics->pe = state;
160   centronics->fault = state;
161   centronics->busy = !state;
162}
163
164
165static TIMER_CALLBACK( ack_callback )
166{
167   centronics_state *centronics = (centronics_state *)ptr;
168
169   /* signal change */
170   centronics->out_ack_func(param);
171   centronics->ack = param;
172
173   if (param == FALSE)
174   {
175      /* data is now ready, output it */
176      printer_output(centronics->printer, centronics->data);
177
178      /* ready to receive more data, return BUSY to low */
179      machine.scheduler().timer_set(attotime::from_usec(7), FUNC(busy_callback), FALSE, ptr);
180   }
181}
182
183
184static TIMER_CALLBACK( busy_callback )
185{
186   centronics_state *centronics = (centronics_state *)ptr;
187
188   /* signal change */
189   centronics->out_busy_func(param);
190   centronics->out_not_busy_func(!param);
191   centronics->busy = param;
192
193   if (param == TRUE)
194   {
195      /* timer to turn ACK low to receive data */
196      machine.scheduler().timer_set(attotime::from_usec(10), FUNC(ack_callback), FALSE, ptr);
197   }
198   else
199   {
200      /* timer to return ACK to high state */
201      machine.scheduler().timer_set(attotime::from_usec(5), FUNC(ack_callback), TRUE, ptr);
202   }
203}
204
205
206/*-------------------------------------------------
207    centronics_data_w - write print data
208-------------------------------------------------*/
209
210WRITE8_DEVICE_HANDLER( centronics_data_w )
211{
212   centronics_state *centronics = get_safe_token(device);
213   centronics->data = data;
214}
215
216
217/*-------------------------------------------------
218    centronics_data_r - return current data
219-------------------------------------------------*/
220
221READ8_DEVICE_HANDLER( centronics_data_r )
222{
223   centronics_state *centronics = get_safe_token(device);
224   return centronics->data;
225}
226
227
228/*-------------------------------------------------
229    set_line - helper to set individual bits
230-------------------------------------------------*/
231
232static void set_line(device_t *device, int line, int state)
233{
234   centronics_state *centronics = get_safe_token(device);
235
236   if (state)
237      centronics->data |= 1 << line;
238   else
239      centronics->data &= ~(1 << line);
240}
241
242
243/*-------------------------------------------------
244    centronics_dx_w - write line dx print data
245-------------------------------------------------*/
246
247WRITE_LINE_DEVICE_HANDLER( centronics_d0_w ) { set_line(device, 0, state); }
248WRITE_LINE_DEVICE_HANDLER( centronics_d1_w ) { set_line(device, 1, state); }
249WRITE_LINE_DEVICE_HANDLER( centronics_d2_w ) { set_line(device, 2, state); }
250WRITE_LINE_DEVICE_HANDLER( centronics_d3_w ) { set_line(device, 3, state); }
251WRITE_LINE_DEVICE_HANDLER( centronics_d4_w ) { set_line(device, 4, state); }
252WRITE_LINE_DEVICE_HANDLER( centronics_d5_w ) { set_line(device, 5, state); }
253WRITE_LINE_DEVICE_HANDLER( centronics_d6_w ) { set_line(device, 6, state); }
254WRITE_LINE_DEVICE_HANDLER( centronics_d7_w ) { set_line(device, 7, state); }
255
256
257/*-------------------------------------------------
258    centronics_strobe_w - signal that data is
259    ready
260-------------------------------------------------*/
261
262WRITE_LINE_DEVICE_HANDLER( centronics_strobe_w )
263{
264   centronics_state *centronics = get_safe_token(device);
265
266   /* look for a high -> low transition */
267   if (centronics->strobe == TRUE && state == FALSE && centronics->busy == FALSE)
268   {
269      /* STROBE has gone low, data is ready */
270      device->machine().scheduler().timer_set(attotime::zero, FUNC(busy_callback), TRUE, centronics);
271   }
272
273   centronics->strobe = state;
274}
275
276
277/*-------------------------------------------------
278    centronics_prime_w - initialize and reset
279    printer (centronics mode)
280-------------------------------------------------*/
281
282WRITE_LINE_DEVICE_HANDLER( centronics_prime_w )
283{
284   assert(((const centronics_interface *)device->static_config())->is_ibmpc == FALSE);
285
286   /* reset printer if line is low */
287   if (state == FALSE)
288      DEVICE_RESET_CALL( centronics );
289}
290
291
292/*-------------------------------------------------
293    centronics_init_w - initialize and reset
294    printer (ibm mode)
295-------------------------------------------------*/
296
297WRITE_LINE_DEVICE_HANDLER( centronics_init_w )
298{
299   assert(((const centronics_interface *)device->static_config())->is_ibmpc == TRUE);
300
301   /* reset printer if line is low */
302   if (state == FALSE)
303      DEVICE_RESET_CALL( centronics );
304}
305
306
307/*-------------------------------------------------
308    centronics_autofeed_w - auto line feed
309-------------------------------------------------*/
310
311WRITE_LINE_DEVICE_HANDLER( centronics_autofeed_w )
312{
313   centronics_state *centronics = get_safe_token(device);
314   assert(((const centronics_interface *)device->static_config())->is_ibmpc == TRUE);
315
316   centronics->auto_fd = state;
317}
318
319
320/*-------------------------------------------------
321    centronics_ack_r - return the state of the
322    ack line
323-------------------------------------------------*/
324
325READ_LINE_DEVICE_HANDLER( centronics_ack_r )
326{
327   centronics_state *centronics = get_safe_token(device);
328   return centronics->ack;
329}
330
331
332/*-------------------------------------------------
333    centronics_busy_r - return the state of the
334    busy line
335-------------------------------------------------*/
336
337READ_LINE_DEVICE_HANDLER( centronics_busy_r )
338{
339   centronics_state *centronics = get_safe_token(device);
340   return centronics->busy;
341}
342
343
344/*-------------------------------------------------
345    centronics_pe_r - return the state of the
346    pe line
347-------------------------------------------------*/
348
349READ_LINE_DEVICE_HANDLER( centronics_pe_r )
350{
351   centronics_state *centronics = get_safe_token(device);
352   return centronics->pe;
353}
354
355
356/*-------------------------------------------------
357    centronics_not_busy_r - return the state of the
358    not busy line
359-------------------------------------------------*/
360
361READ_LINE_DEVICE_HANDLER( centronics_not_busy_r )
362{
363   centronics_state *centronics = get_safe_token(device);
364   return !centronics->busy;
365}
366
367
368/*-------------------------------------------------
369    centronics_vcc_r - return the state of the
370    vcc line
371-------------------------------------------------*/
372
373READ_LINE_DEVICE_HANDLER( centronics_vcc_r )
374{
375   /* always return high */
376   return TRUE;
377}
378
379
380/*-------------------------------------------------
381    centronics_fault_r - return the state of the
382    fault line
383-------------------------------------------------*/
384
385READ_LINE_DEVICE_HANDLER( centronics_fault_r )
386{
387   centronics_state *centronics = get_safe_token(device);
388   return centronics->fault;
389}
390
391DEFINE_LEGACY_DEVICE(CENTRONICS, centronics);
src/mess/machine/ctronics.h
r11450r11451
1/***************************************************************************
2
3    Centronics printer interface
4
5***************************************************************************/
6
7#ifndef __CTRONICS_H__
8#define __CTRONICS_H__
9
10#include "devcb.h"
11
12
13/***************************************************************************
14    TYPE DEFINITIONS
15***************************************************************************/
16
17typedef struct _centronics_interface centronics_interface;
18struct _centronics_interface
19{
20   int is_ibmpc;
21
22   devcb_write_line out_ack_func;
23   devcb_write_line out_busy_func;
24   devcb_write_line out_not_busy_func;
25};
26
27
28/***************************************************************************
29    FUNCTION PROTOTYPES
30***************************************************************************/
31WRITE8_DEVICE_HANDLER( centronics_data_w );
32READ8_DEVICE_HANDLER( centronics_data_r );
33
34/* access to the individual bits */
35WRITE_LINE_DEVICE_HANDLER( centronics_d0_w );
36WRITE_LINE_DEVICE_HANDLER( centronics_d1_w );
37WRITE_LINE_DEVICE_HANDLER( centronics_d2_w );
38WRITE_LINE_DEVICE_HANDLER( centronics_d3_w );
39WRITE_LINE_DEVICE_HANDLER( centronics_d4_w );
40WRITE_LINE_DEVICE_HANDLER( centronics_d5_w );
41WRITE_LINE_DEVICE_HANDLER( centronics_d6_w );
42WRITE_LINE_DEVICE_HANDLER( centronics_d7_w );
43
44WRITE_LINE_DEVICE_HANDLER( centronics_strobe_w );
45WRITE_LINE_DEVICE_HANDLER( centronics_prime_w );
46WRITE_LINE_DEVICE_HANDLER( centronics_init_w );
47WRITE_LINE_DEVICE_HANDLER( centronics_autofeed_w );
48
49READ_LINE_DEVICE_HANDLER( centronics_ack_r );
50READ_LINE_DEVICE_HANDLER( centronics_busy_r );
51READ_LINE_DEVICE_HANDLER( centronics_pe_r );
52READ_LINE_DEVICE_HANDLER( centronics_not_busy_r );
53READ_LINE_DEVICE_HANDLER( centronics_vcc_r );
54READ_LINE_DEVICE_HANDLER( centronics_fault_r );
55
56
57/***************************************************************************
58    DEVICE CONFIGURATION MACROS
59***************************************************************************/
60
61DECLARE_LEGACY_DEVICE(CENTRONICS, centronics);
62
63#define MCFG_CENTRONICS_ADD(_tag, _intf) \
64   MCFG_DEVICE_ADD(_tag, CENTRONICS, 0) \
65   MCFG_DEVICE_CONFIG(_intf)
66
67
68/***************************************************************************
69    DEFAULT INTERFACES
70***************************************************************************/
71
72extern const centronics_interface standard_centronics;
73
74
75#endif /* __CTRONICS_H__ */
src/mess/machine/dc.c
r11450r11451
1/*
2
3    dc.c - Sega Dreamcast hardware
4
5    MESS (DC home console) hardware overrides (GD-ROM drive etc)
6
7    c230048 - 5 is written, want 6
8    c0d9d9e - where bad happens, from routine @ c0da260
9
10    c0d9d8e - R0 on return is the value to put in
11
12    cfffee0 - stack location when bad happens
13
14*/
15
16#include "emu.h"
17#include "cdrom.h"
18#include "debugger.h"
19#include "includes/dc.h"
20#include "cpu/sh4/sh4.h"
21#include "sound/aica.h"
22#include "includes/naomi.h"
23#include "machine/gdrom.h"
24#include "imagedev/chd_cd.h"
25
26#define ATAPI_CYCLES_PER_SECTOR (5000)   // TBD for Dreamcast
27
28#define ATAPI_STAT_BSY      0x80
29#define ATAPI_STAT_DRDY    0x40
30#define ATAPI_STAT_DMARDDF 0x20
31#define ATAPI_STAT_SERVDSC 0x10
32#define ATAPI_STAT_DRQ     0x08
33#define ATAPI_STAT_CORR    0x04
34#define ATAPI_STAT_CHECK   0x01
35
36#define ATAPI_INTREASON_COMMAND 0x01
37#define ATAPI_INTREASON_IO      0x02
38#define ATAPI_INTREASON_RELEASE 0x04
39
40#define ATAPI_REG_DATA      0
41#define ATAPI_REG_FEATURES   1
42#define ATAPI_REG_INTREASON   2
43#define ATAPI_REG_SAMTAG   3
44#define ATAPI_REG_COUNTLOW   4
45#define ATAPI_REG_COUNTHIGH   5
46#define ATAPI_REG_DRIVESEL   6
47#define ATAPI_REG_CMDSTATUS   7
48#define ATAPI_REG_ERROR      16   // read-only ERROR (write is FEATURES)
49
50#define ATAPI_REG_MAX 24
51
52#define ATAPI_XFER_PIO      0x00
53#define ATAPI_XFER_PIO_FLOW   0x08
54#define ATAPI_XFER_MULTI_DMA   0x20
55#define ATAPI_XFER_ULTRA_DMA   0x40
56
57#define ATAPI_DATA_SIZE ( 64 * 1024 )
58
59static UINT8 *atapi_regs;
60static emu_timer *atapi_timer;
61static SCSIInstance *gdrom_device;
62static UINT8 *atapi_data;
63static int atapi_data_ptr, atapi_data_len, atapi_xferlen, atapi_xferbase, atapi_cdata_wait, atapi_xfermod;
64static UINT32 gdrom_alt_status;
65static UINT8 xfer_mode = ATAPI_XFER_PIO;
66
67#define MAX_TRANSFER_SIZE ( 63488 )
68
69extern UINT32 dc_sysctrl_regs[0x200/4];
70
71extern UINT32 g1bus_regs[0x100/4];
72
73static void gdrom_raise_irq(running_machine &machine)
74{
75   dc_sysctrl_regs[SB_ISTEXT] |= IST_EXT_GDROM;
76   dc_update_interrupt_status(machine);
77}
78
79static TIMER_CALLBACK( atapi_xfer_end )
80{
81   UINT8 sector_buffer[ 4096 ];
82
83   atapi_timer->adjust(attotime::never);
84
85   printf("atapi_xfer_end atapi_xferlen = %d, atapi_xfermod=%d\n", atapi_xfermod, atapi_xferlen );
86
87   mame_printf_debug("ATAPI: xfer_end.  xferlen = %d, atapi_xfermod = %d\n", atapi_xferlen, atapi_xfermod);
88
89   while (atapi_xferlen > 0 )
90   {
91      struct sh4_ddt_dma ddtdata;
92
93      // get a sector from the SCSI device
94      SCSIReadData( gdrom_device, sector_buffer, 2048 );
95
96      atapi_xferlen -= 2048;
97
98      // perform the DMA
99      ddtdata.destination = atapi_xferbase;   // destination address
100      ddtdata.length = 2048/4;
101      ddtdata.size = 4;
102      ddtdata.buffer = sector_buffer;
103      ddtdata.direction=1;   // 0 source to buffer, 1 buffer to destination
104      ddtdata.channel= -1;   // not used
105      ddtdata.mode= -1;      // copy from/to buffer
106      printf("ATAPI: DMA one sector to %x, %x remaining\n", atapi_xferbase, atapi_xferlen);
107      sh4_dma_ddt(machine.device("maincpu"), &ddtdata);
108
109      atapi_xferbase += 2048;
110   }
111
112   if (atapi_xfermod > MAX_TRANSFER_SIZE)
113   {
114      atapi_xferlen = MAX_TRANSFER_SIZE;
115      atapi_xfermod = atapi_xfermod - MAX_TRANSFER_SIZE;
116   }
117   else
118   {
119      atapi_xferlen = atapi_xfermod;
120      atapi_xfermod = 0;
121   }
122
123   if (atapi_xferlen > 0)
124   {
125      printf("ATAPI: starting next piece of multi-part transfer\n");
126      atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
127      atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
128
129      atapi_timer->adjust(machine.device<cpu_device>("maincpu")->cycles_to_attotime((ATAPI_CYCLES_PER_SECTOR * (atapi_xferlen/2048))));
130   }
131   else
132   {
133      printf("ATAPI: Transfer completed, dropping DRQ\n");
134      atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRDY;
135      gdrom_alt_status = ATAPI_STAT_DRDY;
136      atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO | ATAPI_INTREASON_COMMAND;
137
138      g1bus_regs[SB_GDST]=0;
139      dc_sysctrl_regs[SB_ISTNRM] |= IST_DMA_GDROM;
140      dc_update_interrupt_status(machine);
141   }
142
143   gdrom_raise_irq(machine);
144
145   printf( "atapi_xfer_end: %d %d\n", atapi_xferlen, atapi_xfermod );
146}
147
148static READ32_HANDLER( atapi_r )
149{
150   running_machine &machine = space->machine();
151   int reg, data;
152
153   if (mem_mask == 0x0000ffff)   // word-wide command read
154   {
155//      mame_printf_debug("ATAPI: packet read = %04x\n", atapi_data[atapi_data_ptr]);
156
157      // assert IRQ and drop DRQ
158      if (atapi_data_ptr == 0 && atapi_data_len == 0)
159      {
160         // get the data from the device
161         if( atapi_xferlen > 0 )
162         {
163            SCSIReadData( gdrom_device, atapi_data, atapi_xferlen );
164            atapi_data_len = atapi_xferlen;
165         }
166
167         if (atapi_xfermod > MAX_TRANSFER_SIZE)
168         {
169            atapi_xferlen = MAX_TRANSFER_SIZE;
170            atapi_xfermod = atapi_xfermod - MAX_TRANSFER_SIZE;
171         }
172         else
173         {
174            atapi_xferlen = atapi_xfermod;
175            atapi_xfermod = 0;
176         }
177
178//          printf( "atapi_r: atapi_xferlen=%d\n", atapi_xferlen );
179         if( atapi_xferlen != 0 )
180         {
181            atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC;
182            gdrom_alt_status = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC;
183            atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
184         }
185         else
186         {
187            //mame_printf_debug("ATAPI: dropping DRQ\n");
188            atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
189            gdrom_alt_status = 0;
190            atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
191         }
192
193         atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
194         atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
195
196         gdrom_raise_irq(machine);
197      }
198
199      if( atapi_data_ptr < atapi_data_len )
200      {
201         data = atapi_data[atapi_data_ptr++];
202         data |= ( atapi_data[atapi_data_ptr++] << 8 );
203         if( atapi_data_ptr >= atapi_data_len )
204         {
205//              printf( "atapi_r: read all bytes\n" );
206            atapi_data_ptr = 0;
207            atapi_data_len = 0;
208
209            if( atapi_xferlen == 0 )
210            {
211               atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
212               gdrom_alt_status = 0;
213               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
214               gdrom_raise_irq(machine);
215            }
216         }
217      }
218      else
219      {
220         data = 0;
221      }
222   }
223   else
224   {
225      reg = offset;
226
227      // get read-only side of read-only/write-only registers from elsewhere
228      if (reg == ATAPI_REG_FEATURES)
229      {
230         reg = ATAPI_REG_ERROR;
231      }
232      data = atapi_regs[reg];
233
234      #if 0
235      switch( reg )
236      {
237      case ATAPI_REG_DATA:
238         printf( "atapi_r: data=%02x\n", data );
239         break;
240      case ATAPI_REG_ERROR:
241         printf( "atapi_r: error=%02x\n", data );
242         break;
243      case ATAPI_REG_INTREASON:
244         printf( "atapi_r: intreason=%02x\n", data );
245         break;
246      case ATAPI_REG_SAMTAG:
247         printf( "atapi_r: samtag=%02x\n", data );
248         break;
249      case ATAPI_REG_COUNTLOW:
250         printf( "atapi_r: countlow=%02x\n", data );
251         break;
252      case ATAPI_REG_COUNTHIGH:
253         printf( "atapi_r: counthigh=%02x\n", data );
254         break;
255      case ATAPI_REG_DRIVESEL:
256         printf( "atapi_r: drivesel=%02x\n", data );
257         break;
258      case ATAPI_REG_CMDSTATUS:
259         printf( "atapi_r: cmdstatus=%02x\n", data );
260         break;
261      }
262      #endif
263
264      mame_printf_debug("ATAPI: read reg %d = %x (PC=%x)\n", reg, data, cpu_get_pc(&space->device()));
265   }
266
267//  printf( "atapi_r( %08x, %08x ) %08x\n", offset, mem_mask, data );
268   return data;
269}
270
271static WRITE32_HANDLER( atapi_w )
272{
273   running_machine &machine = space->machine();
274   int reg;
275
276//  printf( "atapi_w( %08x, %08x, %08x )\n", offset, mem_mask, data );
277
278   if (mem_mask == 0x0000ffff)   // word-wide command write
279   {
280//      printf("atapi_w: data=%04x\n", data );
281
282//      printf("ATAPI: packet write %04x\n", data);
283      atapi_data[atapi_data_ptr++] = data & 0xff;
284      atapi_data[atapi_data_ptr++] = data >> 8;
285
286      if (atapi_cdata_wait)
287      {
288//                  printf("ATAPI: waiting, ptr %d wait %d\n", atapi_data_ptr, atapi_cdata_wait);
289         if (atapi_data_ptr == atapi_cdata_wait)
290         {
291            // send it to the device
292            SCSIWriteData( gdrom_device, atapi_data, atapi_cdata_wait );
293
294            // assert IRQ
295            gdrom_raise_irq(machine);
296
297            // not sure here, but clear DRQ at least?
298            atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
299         }
300      }
301
302      else if ( atapi_data_ptr == 12 )
303      {
304         int phase;
305
306//          printf("atapi_w: command %02x\n", atapi_data[0]&0xff );
307
308         // reset data pointer for reading SCSI results
309         atapi_data_ptr = 0;
310         atapi_data_len = 0;
311
312         // send it to the SCSI device
313         SCSISetCommand( gdrom_device, atapi_data, 12 );
314         SCSIExecCommand( gdrom_device, &atapi_xferlen );
315         SCSIGetPhase( gdrom_device, &phase );
316
317         if (atapi_xferlen != -1)
318         {
319            printf("ATAPI: SCSI command %02x returned %d bytes from the device\n", atapi_data[0]&0xff, atapi_xferlen);
320
321            // store the returned command length in the ATAPI regs, splitting into
322            // multiple transfers if necessary
323            atapi_xfermod = 0;
324            if (atapi_xferlen > MAX_TRANSFER_SIZE)
325            {
326               atapi_xfermod = atapi_xferlen - MAX_TRANSFER_SIZE;
327               atapi_xferlen = MAX_TRANSFER_SIZE;
328            }
329
330            atapi_regs[ATAPI_REG_COUNTLOW] = atapi_xferlen & 0xff;
331            atapi_regs[ATAPI_REG_COUNTHIGH] = (atapi_xferlen>>8)&0xff;
332
333            gdrom_alt_status = 0;   // (I guess?)
334
335            if (atapi_xferlen == 0)
336            {
337               // if no data to return, set the registers properly
338               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRDY;
339               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO|ATAPI_INTREASON_COMMAND;
340            }
341            else
342            {
343               // indicate data ready: set DRQ and DMA ready, and IO in INTREASON
344               if (atapi_regs[ATAPI_REG_FEATURES] & 0x01)   // DMA feature
345               {
346                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_BSY | ATAPI_STAT_DRDY | ATAPI_STAT_SERVDSC;
347               }
348               else
349               {
350                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_SERVDSC | ATAPI_STAT_DRQ;
351               }
352               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_IO;
353            }
354
355            switch( phase )
356            {
357            case SCSI_PHASE_DATAOUT:
358               atapi_cdata_wait = atapi_xferlen;
359               break;
360            }
361
362            // perform special ATAPI processing of certain commands
363            switch (atapi_data[0]&0xff)
364            {
365               case 0x00: // BUS RESET / TEST UNIT READY
366               case 0xbb: // SET CDROM SPEED
367                  atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
368                  break;
369
370               case 0x45: // PLAY
371                  atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_BSY;
372                  atapi_timer->adjust( downcast<cpu_device *>(&space->device())->cycles_to_attotime(ATAPI_CYCLES_PER_SECTOR ) );
373                  break;
374            }
375
376            // assert IRQ
377            gdrom_raise_irq(machine);
378         }
379         else
380         {
381                     printf("ATAPI: SCSI device returned error!\n");
382
383            atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ | ATAPI_STAT_CHECK;
384            atapi_regs[ATAPI_REG_ERROR] = 0x50;   // sense key = ILLEGAL REQUEST
385            atapi_regs[ATAPI_REG_COUNTLOW] = 0;
386            atapi_regs[ATAPI_REG_COUNTHIGH] = 0;
387         }
388      }
389   }
390   else
391   {
392      reg = offset;
393#if 0
394      switch( reg )
395      {
396      case ATAPI_REG_DATA:
397         printf( "atapi_w: data=%02x\n", data );
398             break;
399          case ATAPI_REG_FEATURES:
400         printf( "atapi_w: features=%02x\n", data );
401             break;
402          case ATAPI_REG_INTREASON:
403         printf( "atapi_w: intreason=%02x\n", data );
404             break;
405          case ATAPI_REG_SAMTAG:
406         printf( "atapi_w: samtag=%02x\n", data );
407             break;
408          case ATAPI_REG_COUNTLOW:
409         printf( "atapi_w: countlow=%02x\n", data );
410             break;
411          case ATAPI_REG_COUNTHIGH:
412         printf( "atapi_w: counthigh=%02x\n", data );
413             break;
414          case ATAPI_REG_DRIVESEL:
415         printf( "atapi_w: drivesel=%02x\n", data );
416             break;
417          case ATAPI_REG_CMDSTATUS:
418         printf( "atapi_w: cmdstatus=%02x\n", data );
419         break;
420      }
421#endif
422      atapi_regs[reg] = data;
423//      mame_printf_debug("ATAPI: reg %d = %x (offset %x mask %x PC=%x)\n", reg, data, offset, mem_mask, cpu_get_pc(&space->device()));
424
425      if (reg == ATAPI_REG_CMDSTATUS)
426      {
427         printf("ATAPI command %x issued! (PC=%x)\n", data, cpu_get_pc(&space->device()));
428
429         switch (data)
430         {
431            case 0xa0:   // PACKET
432               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ;
433               gdrom_alt_status = ATAPI_STAT_DRQ;
434               atapi_regs[ATAPI_REG_INTREASON] = ATAPI_INTREASON_COMMAND;
435
436               atapi_data_ptr = 0;
437               atapi_data_len = 0;
438
439               /* we have no data */
440               atapi_xferlen = 0;
441               atapi_xfermod = 0;
442
443               atapi_cdata_wait = 0;
444               break;
445
446            case 0xa1:   // IDENTIFY PACKET DEVICE
447               atapi_regs[ATAPI_REG_CMDSTATUS] = ATAPI_STAT_DRQ;
448               gdrom_alt_status = ATAPI_STAT_DRQ;
449
450               atapi_data_ptr = 0;
451               atapi_data_len = 512;
452
453               /* we have no data */
454               atapi_xferlen = 0;
455               atapi_xfermod = 0;
456
457               memset( atapi_data, 0, atapi_data_len );
458
459               atapi_data[ 0 ^ 1 ] = 0x86;   // ATAPI device, cmd set 6 compliant, DRQ within 3 ms of PACKET command
460               atapi_data[ 1 ^ 1 ] = 0x00;
461
462               memset( &atapi_data[ 46 ], ' ', 8 );
463               atapi_data[ 46 ^ 1 ] = 'S';
464               atapi_data[ 47 ^ 1 ] = 'E';
465
466               memset( &atapi_data[ 54 ], ' ', 40 );
467               atapi_data[ 54 ^ 1 ] = 'C';
468               atapi_data[ 55 ^ 1 ] = 'D';
469               atapi_data[ 56 ^ 1 ] = '-';
470               atapi_data[ 57 ^ 1 ] = 'R';
471               atapi_data[ 58 ^ 1 ] = 'O';
472               atapi_data[ 59 ^ 1 ] = 'M';
473               atapi_data[ 60 ^ 1 ] = ' ';
474               atapi_data[ 61 ^ 1 ] = 'D';
475               atapi_data[ 62 ^ 1 ] = 'R';
476               atapi_data[ 63 ^ 1 ] = 'I';
477               atapi_data[ 64 ^ 1 ] = 'V';
478               atapi_data[ 65 ^ 1 ] = 'E';
479               atapi_data[ 66 ^ 1 ] = ' ';
480               atapi_data[ 67 ^ 1 ] = ' ';
481               atapi_data[ 68 ^ 1 ] = ' ';
482               atapi_data[ 69 ^ 1 ] = ' ';
483               atapi_data[ 70 ^ 1 ] = '6';
484               atapi_data[ 71 ^ 1 ] = '.';
485               atapi_data[ 72 ^ 1 ] = '4';
486               atapi_data[ 73 ^ 1 ] = '2';
487
488               atapi_data[ 98 ^ 1 ] = 0x04; // IORDY may be disabled
489               atapi_data[ 99 ^ 1 ] = 0x00;
490
491               atapi_regs[ATAPI_REG_COUNTLOW] = 0;
492               atapi_regs[ATAPI_REG_COUNTHIGH] = 2;
493
494               gdrom_raise_irq(space->machine());
495               break;
496
497            case 0xef:   // SET FEATURES
498               // set xfer mode?
499               if (atapi_regs[ATAPI_REG_FEATURES] == 0x03)
500               {
501                  printf("Set transfer mode to %x\n", atapi_regs[ATAPI_REG_COUNTLOW] & 0xf8);
502                  xfer_mode = atapi_regs[ATAPI_REG_COUNTLOW] & 0xf8;
503               }
504               else
505               {
506                  printf("ATAPI: Unknown set features %x\n", atapi_regs[ATAPI_REG_FEATURES]);
507               }
508
509               atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
510               gdrom_alt_status = 0;   // is this correct?
511
512               atapi_data_ptr = 0;
513               atapi_data_len = 0;
514
515               gdrom_raise_irq(space->machine());
516               break;
517
518            default:
519               mame_printf_debug("ATAPI: Unknown IDE command %x\n", data);
520               break;
521         }
522      }
523   }
524}
525
526static void dreamcast_atapi_exit(running_machine& machine)
527{
528   if (gdrom_device != NULL)
529   {
530      SCSIDeleteInstance( gdrom_device );
531   }
532}
533
534void dreamcast_atapi_init(running_machine &machine)
535{
536   atapi_regs = auto_alloc_array(machine, UINT8,  ATAPI_REG_MAX );
537   memset(atapi_regs, 0, sizeof(atapi_regs));
538
539   atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
540   atapi_regs[ATAPI_REG_ERROR] = 1;
541   atapi_regs[ATAPI_REG_COUNTLOW] = 0x14;
542   atapi_regs[ATAPI_REG_COUNTHIGH] = 0xeb;
543
544   atapi_data_ptr = 0;
545   atapi_data_len = 0;
546   atapi_cdata_wait = 0;
547
548   atapi_timer = machine.scheduler().timer_alloc(FUNC(atapi_xfer_end));
549   atapi_timer->adjust(attotime::never);
550
551   gdrom_device = NULL;
552
553   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(dreamcast_atapi_exit),&machine));
554
555   atapi_data = auto_alloc_array(machine, UINT8,  ATAPI_DATA_SIZE );
556
557   state_save_register_global_pointer(machine,  atapi_regs, ATAPI_REG_MAX );
558   state_save_register_global_pointer(machine,  atapi_data, ATAPI_DATA_SIZE / 2 );
559   state_save_register_global(machine,  atapi_data_ptr );
560   state_save_register_global(machine,  atapi_data_len );
561   state_save_register_global(machine,  atapi_xferlen );
562   state_save_register_global(machine,  atapi_xferbase );
563   state_save_register_global(machine,  atapi_cdata_wait );
564   state_save_register_global(machine,  atapi_xfermod );
565}
566
567void dreamcast_atapi_reset(running_machine &machine)
568{
569   atapi_regs[ATAPI_REG_CMDSTATUS] = 0;
570   atapi_regs[ATAPI_REG_ERROR] = 1;
571   atapi_regs[ATAPI_REG_COUNTLOW] = 0x14;
572   atapi_regs[ATAPI_REG_COUNTHIGH] = 0xeb;
573
574   atapi_data_ptr = 0;
575   atapi_data_len = 0;
576   atapi_cdata_wait = 0;
577
578   atapi_xferlen = 0;
579   atapi_xfermod = 0;
580
581   if ( cd_get_cdrom_file(machine.device( "cdrom" )) != NULL )
582   {
583      SCSIAllocInstance( machine, &SCSIClassGDROM, &gdrom_device, "cdrom" );
584   }
585   else
586   {
587      gdrom_device = NULL;
588   }
589}
590
591/*
592
593 GDROM regsters:
594
595 5f7018: alternate status/device control
596 5f7080: data
597 5f7084: error/features
598 5f7088: interrupt reason/sector count
599 5f708c: sector number
600 5f7090: byte control low
601 5f7094: byte control high
602 5f7098: drive select
603 5f709c: status/command
604
605c002910 - ATAPI packet writes
606c002796 - aux status read after that
607c000776 - DMA triggered to c008000
608
609*/
610
611READ64_HANDLER( dc_mess_gdrom_r )
612{
613   UINT32 off;
614
615   if ((int)~mem_mask & 1)
616   {
617      off=(offset << 1) | 1;
618   }
619   else
620   {
621      off=offset << 1;
622   }
623
624//  printf("gdrom_r: @ %x (off %x), mask %llx (PC %x)\n", offset, off, mem_mask, cpu_get_pc(&space->device()));
625
626   if (offset == 3)
627   {
628      return gdrom_alt_status;
629   }
630   else if (off >= 0x20)
631   {
632      return atapi_r(space, off-0x20, 0xff);
633   }
634
635   return 0;
636}
637
638WRITE64_HANDLER( dc_mess_gdrom_w )
639{
640   UINT32 dat,off;
641
642   if ((int)~mem_mask & 1)
643   {
644      dat=(UINT32)(data >> 32);
645      off=(offset << 1) | 1;
646   }
647   else
648   {
649      dat=(UINT32)data;
650      off=offset << 1;
651   }
652
653//  printf("GDROM: [%08x=%x]write %llx to %x, mask %llx (PC %x)\n", 0x5f7000+off*4, dat, data, offset, mem_mask, cpu_get_pc(&space->device()));
654
655   if (off >= 0x20)
656   {
657      atapi_w(space, off-0x20, dat, (UINT32)mem_mask);
658   }
659}
660
661// register decode helpers
662
663// this accepts only 32-bit accesses
664INLINE int decode_reg32_64(running_machine &machine, UINT32 offset, UINT64 mem_mask, UINT64 *shift)
665{
666   int reg = offset * 2;
667
668   *shift = 0;
669
670   // non 32-bit accesses have not yet been seen here, we need to know when they are
671   if ((mem_mask != U64(0xffffffff00000000)) && (mem_mask != U64(0x00000000ffffffff)))
672   {
673      mame_printf_verbose("%s:Wrong mask!\n", machine.describe_context());
674//      debugger_break(machine);
675   }
676
677   if (mem_mask == U64(0xffffffff00000000))
678   {
679      reg++;
680      *shift = 32;
681   }
682
683   return reg;
684}
685
686READ64_HANDLER( dc_mess_g1_ctrl_r )
687{
688   int reg;
689   UINT64 shift;
690
691   reg = decode_reg32_64(space->machine(), offset, mem_mask, &shift);
692   mame_printf_verbose("G1CTRL:  Unmapped read %08x\n", 0x5f7400+reg*4);
693   return (UINT64)g1bus_regs[reg] << shift;
694}
695
696WRITE64_HANDLER( dc_mess_g1_ctrl_w )
697{
698   int reg;
699   UINT64 shift;
700   UINT32 old,dat;
701
702   reg = decode_reg32_64(space->machine(), offset, mem_mask, &shift);
703   dat = (UINT32)(data >> shift);
704   old = g1bus_regs[reg];
705
706   g1bus_regs[reg] = dat; // 5f7400+reg*4=dat
707   mame_printf_verbose("G1CTRL: [%08x=%x] write %" I64FMT "x to %x, mask %" I64FMT "x\n", 0x5f7400+reg*4, dat, data, offset, mem_mask);
708   switch (reg)
709   {
710   case SB_GDST:
711      if (dat & 1 && g1bus_regs[SB_GDEN] == 1) // 0 -> 1
712      {
713         if (g1bus_regs[SB_GDDIR] == 0)
714         {
715            printf("G1CTRL: unsupported transfer\n");
716            return;
717         }
718
719         atapi_xferbase = g1bus_regs[SB_GDSTAR];
720         atapi_timer->adjust(space->machine().device<cpu_device>("maincpu")->cycles_to_attotime((ATAPI_CYCLES_PER_SECTOR * (atapi_xferlen/2048))));
721      }
722      break;
723   }
724}
725
src/mess/machine/msm8251.c
r11450r11451
1/*********************************************************************
2
3    msm8251.c
4
5    MSM/Intel 8251 Universal Synchronous/Asynchronous Receiver Transmitter code
6
7*********************************************************************/
8
9#include "emu.h"
10#include "msm8251.h"
11
12
13/***************************************************************************
14    MACROS
15***************************************************************************/
16
17#define VERBOSE 0
18
19#define LOG(x)   do { if (VERBOSE) logerror x; } while (0)
20
21
22/***************************************************************************
23    TYPE DEFINITIONS
24***************************************************************************/
25
26typedef struct _msm8251_t msm8251_t;
27struct _msm8251_t
28{
29   devcb_resolved_read_line   in_rxd_func;
30   devcb_resolved_write_line   out_txd_func;
31   devcb_resolved_read_line   in_dsr_func;
32   devcb_resolved_write_line   out_dtr_func;
33   devcb_resolved_write_line   out_rts_func;
34   devcb_resolved_write_line   out_rxrdy_func;
35   devcb_resolved_write_line   out_txrdy_func;
36   devcb_resolved_write_line   out_txempty_func;
37   devcb_resolved_write_line   out_syndet_func;
38
39   /* flags controlling how msm8251_control_w operates */
40   UINT8 flags;
41   /* offset into sync_bytes used during sync byte transfer */
42   UINT8 sync_byte_offset;
43   /* number of sync bytes written so far */
44   UINT8 sync_byte_count;
45   /* the sync bytes written */
46   UINT8 sync_bytes[2];
47   /* status of msm8251 */
48   UINT8 status;
49   UINT8 command;
50   /* mode byte - bit definitions depend on mode - e.g. synchronous, asynchronous */
51   UINT8 mode_byte;
52
53   /* data being received */
54   UINT8 data;
55
56   /* receive reg */
57   serial_receive_register receive_reg;
58   /* transmit reg */
59   serial_transmit_register transmit_reg;
60
61   data_form form;
62
63   /* the serial connection that data is transfered over */
64   /* this is usually connected to the serial device */
65   serial_connection connection;
66};
67
68
69
70/***************************************************************************
71    PROTOTYPES
72***************************************************************************/
73
74static void msm8251_in_callback(running_machine &machine, int id, unsigned long state);
75static void msm8251_update_tx_empty(device_t *device);
76static void msm8251_update_tx_ready(device_t *device);
77
78
79
80/***************************************************************************
81    INLINE FUNCTIONS
82***************************************************************************/
83
84INLINE msm8251_t *get_token(device_t *device)
85{
86   assert(device != NULL);
87   assert(device->type() == MSM8251);
88
89   return (msm8251_t *) downcast<legacy_device_base *>(device)->token();
90}
91
92
93INLINE const msm8251_interface *get_interface(device_t *device)
94{
95   assert(device != NULL);
96   assert(device->type() == MSM8251);
97
98   return (const msm8251_interface *) device->static_config();
99}
100
101
102/***************************************************************************
103    GLOBAL VARIABLES
104***************************************************************************/
105
106const msm8251_interface default_msm8251_interface = { DEVCB_NULL, };
107
108
109/***************************************************************************
110    IMPLEMENTATION
111***************************************************************************/
112
113/*-------------------------------------------------
114    msm8251_in_callback
115-------------------------------------------------*/
116
117static void msm8251_in_callback(running_machine &machine, int id, unsigned long state)
118{
119   device_t *device;
120   msm8251_t *uart;
121   int changed;
122
123   /* NPW 29-Nov-2008 - These two lines are a hack and indicate why our "serial" infrastructure needs to be updated */
124   device = machine.device("uart");
125   uart = get_token(device);
126
127   changed = uart->connection.input_state^state;
128
129   uart->connection.input_state = state;
130
131   /* did cts change state? */
132   if (changed & SERIAL_STATE_CTS)
133   {
134      /* yes */
135      /* update tx ready */
136      /* msm8251_update_tx_ready(device); */
137   }
138}
139
140
141
142/*-------------------------------------------------
143    DEVICE_START( msm8251 )
144-------------------------------------------------*/
145
146static DEVICE_START( msm8251 )
147{
148   msm8251_t *uart = get_token(device);
149   const msm8251_interface *intf = get_interface(device);
150
151   serial_helper_setup();
152
153   // resolve callbacks
154   uart->out_rxrdy_func.resolve(intf->out_rxrdy_func, *device);
155   uart->out_txrdy_func.resolve(intf->out_txrdy_func, *device);
156   uart->out_txempty_func.resolve(intf->out_txempty_func, *device);
157
158   /* setup this side of the serial connection */
159   serial_connection_init(device->machine(),&uart->connection);
160   serial_connection_set_in_callback(device->machine(),&uart->connection, msm8251_in_callback);
161   uart->connection.input_state = 0;
162}
163
164
165
166/*-------------------------------------------------
167    msm8251_update_rx_ready
168-------------------------------------------------*/
169
170static void msm8251_update_rx_ready(device_t *device)
171{
172   msm8251_t *uart = get_token(device);
173   int state;
174
175   state = uart->status & MSM8251_STATUS_RX_READY;
176
177   /* masked? */
178   if ((uart->command & (1<<2))==0)
179   {
180      state = 0;
181   }
182
183   uart->out_rxrdy_func(state != 0);
184}
185
186
187
188/*-------------------------------------------------
189    msm8251_receive_clock
190-------------------------------------------------*/
191
192void msm8251_receive_clock(device_t *device)
193{
194   msm8251_t *uart = get_token(device);
195
196   /* receive enable? */
197   if (uart->command & (1<<2))
198   {
199      //logerror("MSM8251\n");
200      /* get bit received from other side and update receive register */
201      receive_register_update_bit(&uart->receive_reg, get_in_data_bit(uart->connection.input_state));
202
203      if (uart->receive_reg.flags & RECEIVE_REGISTER_FULL)
204      {
205         receive_register_extract(&uart->receive_reg, &uart->form);
206         msm8251_receive_character(device, uart->receive_reg.byte_received);
207      }
208   }
209}
210
211
212
213/*-------------------------------------------------
214    msm8251_transmit_clock
215-------------------------------------------------*/
216
217void msm8251_transmit_clock(device_t *device)
218{
219   msm8251_t *uart = get_token(device);
220
221   /* transmit enable? */
222   if (uart->command & (1<<0))
223   {
224
225      /* transmit register full? */
226      if ((uart->status & MSM8251_STATUS_TX_READY)==0)
227      {
228         /* if transmit reg is empty */
229         if ((uart->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)!=0)
230         {
231            /* set it up */
232            transmit_register_setup(&uart->transmit_reg, &uart->form, uart->data);
233            /* msm8251 transmit reg now empty */
234            uart->status |=MSM8251_STATUS_TX_EMPTY;
235            /* ready for next transmit */
236            uart->status |=MSM8251_STATUS_TX_READY;
237
238            msm8251_update_tx_empty(device);
239            msm8251_update_tx_ready(device);
240         }
241      }
242
243      /* if transmit is not empty... transmit data */
244      if ((uart->transmit_reg.flags & TRANSMIT_REGISTER_EMPTY)==0)
245      {
246   //      logerror("MSM8251\n");
247         transmit_register_send_bit(device->machine(),&uart->transmit_reg, &uart->connection);
248      }
249   }
250
251#if 0
252   /* hunt mode? */
253   /* after each bit has been shifted in, it is compared against the current sync byte */
254   if (uart->command & (1<<7))
255   {
256      /* data matches sync byte? */
257      if (uart->data == uart->sync_bytes[uart->sync_byte_offset])
258      {
259         /* sync byte matches */
260         /* update for next sync byte? */
261         uart->sync_byte_offset++;
262
263         /* do all sync bytes match? */
264         if (uart->sync_byte_offset == uart->sync_byte_count)
265         {
266            /* ent hunt mode */
267            uart->command &=~(1<<7);
268         }
269      }
270      else
271      {
272         /* if there is no match, reset */
273         uart->sync_byte_offset = 0;
274      }
275   }
276#endif
277}
278
279
280
281/*-------------------------------------------------
282    msm8251_update_tx_ready
283-------------------------------------------------*/
284
285static void msm8251_update_tx_ready(device_t *device)
286{
287   msm8251_t *uart = get_token(device);
288
289   /* clear tx ready state */
290   int tx_ready;
291
292   /* tx ready output is set if:
293        DB Buffer Empty &
294        CTS is set &
295        Transmit enable is 1
296    */
297
298   tx_ready = 0;
299
300   /* transmit enable? */
301   if ((uart->command & (1<<0))!=0)
302   {
303      /* other side has rts set (comes in as CTS at this side) */
304      if (uart->connection.input_state & SERIAL_STATE_CTS)
305      {
306         if (uart->status & MSM8251_STATUS_TX_EMPTY)
307         {
308            /* enable transfer */
309            tx_ready = 1;
310         }
311      }
312   }
313
314   uart->out_txrdy_func(tx_ready);
315}
316
317
318
319/*-------------------------------------------------
320    msm8251_update_tx_empty
321-------------------------------------------------*/
322
323static void msm8251_update_tx_empty(device_t *device)
324{
325   msm8251_t *uart = get_token(device);
326
327   if (uart->status & MSM8251_STATUS_TX_EMPTY)
328   {
329      /* tx is in marking state (high) when tx empty! */
330      set_out_data_bit(uart->connection.State, 1);
331      serial_connection_out(device->machine(),&uart->connection);
332   }
333
334   uart->out_txempty_func((uart->status & MSM8251_STATUS_TX_EMPTY) != 0);
335}
336
337
338
339/*-------------------------------------------------
340    DEVICE_RESET( msm8251 )
341-------------------------------------------------*/
342
343static DEVICE_RESET( msm8251 )
344{
345   msm8251_t *uart = get_token(device);
346
347   LOG(("MSM8251: Reset\n"));
348
349   /* what is the default setup when the 8251 has been reset??? */
350
351   /* msm8251 datasheet explains the state of tx pin at reset */
352   /* tx is set to 1 */
353   set_out_data_bit(uart->connection.State,1);
354
355   /* assumption, rts is set to 1 */
356   uart->connection.State &= ~SERIAL_STATE_RTS;
357   serial_connection_out(device->machine(), &uart->connection);
358
359   transmit_register_reset(&uart->transmit_reg);
360   receive_register_reset(&uart->receive_reg);
361   /* expecting mode byte */
362   uart->flags |= MSM8251_EXPECTING_MODE;
363   /* not expecting a sync byte */
364   uart->flags &= ~MSM8251_EXPECTING_SYNC_BYTE;
365
366   /* no character to read by cpu */
367   /* transmitter is ready and is empty */
368   uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
369   uart->mode_byte = 0;
370   uart->command = 0;
371
372   /* update tx empty pin output */
373   msm8251_update_tx_empty(device);
374   /* update rx ready pin output */
375   msm8251_update_rx_ready(device);
376   /* update tx ready pin output */
377   msm8251_update_tx_ready(device);
378}
379
380
381
382/*-------------------------------------------------
383    WRITE8_DEVICE_HANDLER(msm8251_control_w)
384-------------------------------------------------*/
385
386WRITE8_DEVICE_HANDLER(msm8251_control_w)
387{
388   msm8251_t *uart = get_token(device);
389
390   if (uart->flags & MSM8251_EXPECTING_MODE)
391   {
392      if (uart->flags & MSM8251_EXPECTING_SYNC_BYTE)
393      {
394         LOG(("MSM8251: Sync byte\n"));
395
396         LOG(("Sync byte: %02x\n", data));
397         /* store sync byte written */
398         uart->sync_bytes[uart->sync_byte_offset] = data;
399         uart->sync_byte_offset++;
400
401         if (uart->sync_byte_offset == uart->sync_byte_count)
402         {
403            /* finished transfering sync bytes, now expecting command */
404            uart->flags &= ~(MSM8251_EXPECTING_MODE | MSM8251_EXPECTING_SYNC_BYTE);
405            uart->sync_byte_offset = 0;
406         //  uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
407         }
408      }
409      else
410      {
411         LOG(("MSM8251: Mode byte\n"));
412
413         uart->mode_byte = data;
414
415         /* Synchronous or Asynchronous? */
416         if ((data & 0x03)!=0)
417         {
418            /*  Asynchronous
419
420                    bit 7,6: stop bit length
421                        0 = inhibit
422                        1 = 1 bit
423                        2 = 1.5 bits
424                        3 = 2 bits
425                    bit 5: parity type
426                        0 = parity odd
427                        1 = parity even
428                    bit 4: parity test enable
429                        0 = disable
430                        1 = enable
431                    bit 3,2: character length
432                        0 = 5 bits
433                        1 = 6 bits
434                        2 = 7 bits
435                        3 = 8 bits
436                    bit 1,0: baud rate factor
437                        0 = defines command byte for synchronous or asynchronous
438                        1 = x1
439                        2 = x16
440                        3 = x64
441                */
442
443            LOG(("MSM8251: Asynchronous operation\n"));
444
445            LOG(("Character length: %d\n", (((data>>2) & 0x03)+5)));
446
447            if (data & (1<<4))
448            {
449               LOG(("enable parity checking\n"));
450            }
451            else
452            {
453               LOG(("parity check disabled\n"));
454            }
455
456            if (data & (1<<5))
457            {
458               LOG(("even parity\n"));
459            }
460            else
461            {
462               LOG(("odd parity\n"));
463            }
464
465            {
466               UINT8 stop_bit_length;
467
468               stop_bit_length = (data>>6) & 0x03;
469
470               switch (stop_bit_length)
471               {
472                  case 0:
473                  {
474                     /* inhibit */
475                     LOG(("stop bit: inhibit\n"));
476                  }
477                  break;
478
479                  case 1:
480                  {
481                     /* 1 */
482                     LOG(("stop bit: 1 bit\n"));
483                  }
484                  break;
485
486                  case 2:
487                  {
488                     /* 1.5 */
489                     LOG(("stop bit: 1.5 bits\n"));
490                  }
491                  break;
492
493                  case 3:
494                  {
495                     /* 2 */
496                     LOG(("stop bit: 2 bits\n"));
497                  }
498                  break;
499               }
500            }
501
502            uart->form.word_length = ((data>>2) & 0x03)+5;
503            uart->form.parity = SERIAL_PARITY_NONE;
504            switch ((data>>6) & 0x03)
505            {
506               case 0:
507               case 1:
508                  uart->form.stop_bit_count =  1;
509                  break;
510               case 2:
511               case 3:
512                  uart->form.stop_bit_count =  2;
513                  break;
514            }
515            receive_register_setup(&uart->receive_reg, &uart->form);
516
517
518#if 0
519            /* data bits */
520            uart->receive_char_length = (((data>>2) & 0x03)+5);
521
522            if (data & (1<<4))
523            {
524               /* parity */
525               uart->receive_char_length++;
526            }
527
528            /* stop bits */
529            uart->receive_char_length++;
530
531            uart->receive_flags &=~MSM8251_TRANSFER_RECEIVE_SYNCHRONISED;
532            uart->receive_flags |= MSM8251_TRANSFER_RECEIVE_WAITING_FOR_START_BIT;
533#endif
534            /* not expecting mode byte now */
535            uart->flags &= ~MSM8251_EXPECTING_MODE;
536//              uart->status = MSM8251_STATUS_TX_EMPTY | MSM8251_STATUS_TX_READY;
537         }
538         else
539         {
540            /*  bit 7: Number of sync characters
541                        0 = 1 character
542                        1 = 2 character
543                    bit 6: Synchronous mode
544                        0 = Internal synchronisation
545                        1 = External synchronisation
546                    bit 5: parity type
547                        0 = parity odd
548                        1 = parity even
549                    bit 4: parity test enable
550                        0 = disable
551                        1 = enable
552                    bit 3,2: character length
553                        0 = 5 bits
554                        1 = 6 bits
555                        2 = 7 bits
556                        3 = 8 bits
557                    bit 1,0 = 0
558                */
559            LOG(("MSM8251: Synchronous operation\n"));
560
561            /* setup for sync byte(s) */
562            uart->flags |= MSM8251_EXPECTING_SYNC_BYTE;
563            uart->sync_byte_offset = 0;
564            if (data & 0x07)
565            {
566               uart->sync_byte_count = 1;
567            }
568            else
569            {
570               uart->sync_byte_count = 2;
571            }
572
573         }
574      }
575   }
576   else
577   {
578      /* command */
579      LOG(("MSM8251: Command byte\n"));
580
581      uart->command = data;
582
583      LOG(("Command byte: %02x\n", data));
584
585      if (data & (1<<7))
586      {
587         LOG(("hunt mode\n"));
588      }
589
590      if (data & (1<<5))
591      {
592         LOG(("/rts set to 0\n"));
593      }
594      else
595      {
596         LOG(("/rts set to 1\n"));
597      }
598
599      if (data & (1<<2))
600      {
601         LOG(("receive enable\n"));
602      }
603      else
604      {
605         LOG(("receive disable\n"));
606      }
607
608      if (data & (1<<1))
609      {
610         LOG(("/dtr set to 0\n"));
611      }
612      else
613      {
614         LOG(("/dtr set to 1\n"));
615      }
616
617      if (data & (1<<0))
618      {
619         LOG(("transmit enable\n"));
620      }
621      else
622      {
623         LOG(("transmit disable\n"));
624      }
625
626
627      /*  bit 7:
628                0 = normal operation
629                1 = hunt mode
630            bit 6:
631                0 = normal operation
632                1 = internal reset
633            bit 5:
634                0 = /RTS set to 1
635                1 = /RTS set to 0
636            bit 4:
637                0 = normal operation
638                1 = reset error flag
639            bit 3:
640                0 = normal operation
641                1 = send break character
642            bit 2:
643                0 = receive disable
644                1 = receive enable
645            bit 1:
646                0 = /DTR set to 1
647                1 = /DTR set to 0
648            bit 0:
649                0 = transmit disable
650                1 = transmit enable
651        */
652
653      uart->connection.State &=~SERIAL_STATE_RTS;
654      if (data & (1<<5))
655      {
656         /* rts set to 0 */
657         uart->connection.State |= SERIAL_STATE_RTS;
658      }
659
660      uart->connection.State &=~SERIAL_STATE_DTR;
661      if (data & (1<<1))
662      {
663         uart->connection.State |= SERIAL_STATE_DTR;
664      }
665
666      if ((data & (1<<0))==0)
667      {
668         /* held in high state when transmit disable */
669         set_out_data_bit(uart->connection.State,1);
670      }
671
672
673      /* refresh outputs */
674      serial_connection_out(device->machine(), &uart->connection);
675
676      if (data & (1<<4))
677      {
678         uart->status &= ~(MSM8251_STATUS_PARITY_ERROR | MSM8251_STATUS_OVERRUN_ERROR | MSM8251_STATUS_FRAMING_ERROR);
679      }
680
681      if (data & (1<<6))
682      {
683         device->reset();
684      }
685
686      msm8251_update_rx_ready(device);
687      msm8251_update_tx_ready(device);
688
689   }
690}
691
692
693
694/*-------------------------------------------------
695    READ8_DEVICE_HANDLER(msm8251_status_r)
696-------------------------------------------------*/
697
698READ8_DEVICE_HANDLER(msm8251_status_r)
699{
700   msm8251_t *uart = get_token(device);
701
702   LOG(("status: %02x\n", uart->status));
703   return uart->status;
704}
705
706
707
708/*-------------------------------------------------
709    WRITE8_DEVICE_HANDLER(msm8251_data_w)
710-------------------------------------------------*/
711
712WRITE8_DEVICE_HANDLER(msm8251_data_w)
713{
714   msm8251_t *uart = get_token(device);
715
716   uart->data = data;
717
718   logerror("write data: %02x\n",data);
719
720   /* writing clears */
721   uart->status &=~MSM8251_STATUS_TX_READY;
722
723   /* if transmitter is active, then tx empty will be signalled */
724
725   msm8251_update_tx_ready(device);
726}
727
728
729
730/*-------------------------------------------------
731    msm8251_receive_character - called when last
732    bit of data has been received
733-------------------------------------------------*/
734
735void msm8251_receive_character(device_t *device, UINT8 ch)
736{
737   msm8251_t *uart = get_token(device);
738
739   logerror("msm8251 receive char: %02x\n",ch);
740
741   uart->data = ch;
742
743   /* char has not been read and another has arrived! */
744   if (uart->status & MSM8251_STATUS_RX_READY)
745   {
746      uart->status |= MSM8251_STATUS_OVERRUN_ERROR;
747   }
748   uart->status |= MSM8251_STATUS_RX_READY;
749
750   msm8251_update_rx_ready(device);
751}
752
753
754
755/*-------------------------------------------------
756    READ8_DEVICE_HANDLER(msm8251_data_r) - read data
757-------------------------------------------------*/
758
759READ8_DEVICE_HANDLER(msm8251_data_r)
760{
761   msm8251_t *uart = get_token(device);
762
763   logerror("read data: %02x, STATUS=%02x\n",uart->data,uart->status);
764   /* reading clears */
765   uart->status &= ~MSM8251_STATUS_RX_READY;
766
767   msm8251_update_rx_ready(device);
768   return uart->data;
769}
770
771
772
773/*-------------------------------------------------
774    msm8251_connect_to_serial_device - initialise
775    transfer using serial device - set the callback
776    which will be called when serial device has
777    updated it's state
778-------------------------------------------------*/
779
780void msm8251_connect_to_serial_device(device_t *device, device_t *image)
781{
782   msm8251_t *uart = get_token(device);
783   serial_device_connect(image, &uart->connection);
784}
785
786
787
788/*-------------------------------------------------
789    msm8251_connect
790-------------------------------------------------*/
791
792void msm8251_connect(device_t *device, serial_connection *other_connection)
793{
794   msm8251_t *uart = get_token(device);
795   serial_connection_link(device->machine(), &uart->connection, other_connection);
796}
797
798
799/*-------------------------------------------------
800    DEVICE_GET_INFO( msm8251 )
801-------------------------------------------------*/
802
803DEVICE_GET_INFO( msm8251 )
804{
805   switch (state)
806   {
807      /* --- the following bits of info are returned as 64-bit signed integers --- */
808      case DEVINFO_INT_TOKEN_BYTES:               info->i = sizeof(msm8251_t);            break;
809      case DEVINFO_INT_INLINE_CONFIG_BYTES:         info->i = 0;                        break;
810
811      /* --- the following bits of info are returned as pointers to data or functions --- */
812      case DEVINFO_FCT_START:                     info->start = DEVICE_START_NAME(msm8251);   break;
813      case DEVINFO_FCT_STOP:                     /* Nothing */                        break;
814      case DEVINFO_FCT_RESET:                     info->reset = DEVICE_RESET_NAME(msm8251);   break;
815
816      /* --- the following bits of info are returned as NULL-terminated strings --- */
817      case DEVINFO_STR_NAME:                     strcpy(info->s, "Intel 8251 UART");            break;
818      case DEVINFO_STR_FAMILY:                  strcpy(info->s, "Intel 8251 UART");            break;
819      case DEVINFO_STR_VERSION:                  strcpy(info->s, "1.0");                     break;
820      case DEVINFO_STR_SOURCE_FILE:               strcpy(info->s, __FILE__);                     break;
821      case DEVINFO_STR_CREDITS:                  /* Nothing */                        break;
822   }
823}
824
825DEFINE_LEGACY_DEVICE(MSM8251, msm8251);
src/mess/machine/msm8251.h
r11450r11451
1/*********************************************************************
2
3    msm8251.h
4
5    MSM/Intel 8251 Universal Synchronous/Asynchronous Receiver Transmitter code
6
7*********************************************************************/
8
9#ifndef __MSM8251_H__
10#define __MSM8251_H__
11
12#include "machine/serial.h"
13
14
15/***************************************************************************
16    CONSTANTS
17***************************************************************************/
18
19DECLARE_LEGACY_DEVICE(MSM8251, msm8251);
20
21#define MSM8251_EXPECTING_MODE 0x01
22#define MSM8251_EXPECTING_SYNC_BYTE 0x02
23
24#define MSM8251_STATUS_FRAMING_ERROR 0x020
25#define MSM8251_STATUS_OVERRUN_ERROR 0x010
26#define MSM8251_STATUS_PARITY_ERROR 0x08
27#define MSM8251_STATUS_TX_EMPTY      0x04
28#define MSM8251_STATUS_RX_READY   0x02
29#define MSM8251_STATUS_TX_READY   0x01
30
31#define MCFG_MSM8251_ADD(_tag, _intrf) \
32   MCFG_DEVICE_ADD(_tag, MSM8251, 0) \
33   MCFG_DEVICE_CONFIG(_intrf)
34
35#define MCFG_MSM8251_REMOVE(_tag) \
36   MCFG_DEVICE_REMOVE(_tag)
37
38
39/***************************************************************************
40    TYPE DEFINITIONS
41***************************************************************************/
42
43typedef struct _msm8251_interface msm8251_interface;
44struct _msm8251_interface
45{
46   devcb_read_line      in_rxd_func;
47   devcb_write_line   out_txd_func;
48   devcb_read_line      in_dsr_func;
49   devcb_write_line   out_dtr_func;
50   devcb_write_line   out_rts_func;
51   devcb_write_line   out_rxrdy_func;
52   devcb_write_line   out_txrdy_func;
53   devcb_write_line   out_txempty_func;
54   devcb_write_line   out_syndet_func;
55};
56
57
58/***************************************************************************
59    PROTOTYPES
60***************************************************************************/
61
62extern const msm8251_interface default_msm8251_interface;
63
64/* read data register */
65READ8_DEVICE_HANDLER(msm8251_data_r);
66
67/* read status register */
68READ8_DEVICE_HANDLER(msm8251_status_r);
69
70/* write data register */
71WRITE8_DEVICE_HANDLER(msm8251_data_w);
72
73/* write control word */
74WRITE8_DEVICE_HANDLER(msm8251_control_w);
75
76/* The 8251 has seperate transmit and receive clocks */
77/* use these two functions to update the msm8251 for each clock */
78/* on NC100 system, the clocks are the same */
79void msm8251_transmit_clock(device_t *device);
80void msm8251_receive_clock(device_t *device);
81
82/* connecting to serial output */
83void msm8251_connect_to_serial_device(device_t *device, device_t *image);
84void msm8251_connect(device_t *device, serial_connection *other_connection);
85
86void msm8251_receive_character(device_t *device, UINT8 ch);
87
88#endif /* __MSM8251_H__ */
src/mess/includes/sg1000.h
r11450r11451
1#ifndef __SG1000__
2#define __SG1000__
3
4#include "machine/ram.h"
5
6#define SCREEN_TAG      "screen"
7#define Z80_TAG         "z80"
8#define SN76489A_TAG   "sn76489a"
9#define UPD765_TAG      "upd765"
10#define CASSETTE_TAG   "cassette"
11#define UPD8251_TAG      "upd8251"
12#define UPD9255_TAG      "upd9255"
13#define UPD9255_0_TAG   "upd9255_0"
14#define UPD9255_1_TAG   "upd9255_1"
15#define CENTRONICS_TAG   "centronics"
16
17#define IS_CARTRIDGE_TV_DRAW(ptr) \
18   (!strncmp("annakmn", (const char *)&ptr[0x13b3], 7))
19
20#define IS_CARTRIDGE_THE_CASTLE(ptr) \
21   (!strncmp("ASCII 1986", (const char *)&ptr[0x1cc3], 10))
22
23#define IS_CARTRIDGE_BASIC_LEVEL_III(ptr) \
24   (!strncmp("SC-3000 BASIC Level 3 ver 1.0", (const char *)&ptr[0x6a20], 29))
25
26#define IS_CARTRIDGE_MUSIC_EDITOR(ptr) \
27   (!strncmp("PIANO", (const char *)&ptr[0x0841], 5))
28
29class sg1000_state : public driver_device
30{
31public:
32   sg1000_state(const machine_config &mconfig, device_type type, const char *tag)
33      : driver_device(mconfig, type, tag),
34        m_maincpu(*this, Z80_TAG),
35        m_ram(*this, RAM_TAG)
36   { }
37
38   required_device<cpu_device> m_maincpu;
39   required_device<device_t> m_ram;
40
41   virtual void machine_start();
42
43   void install_cartridge(UINT8 *ptr, int size);
44
45   DECLARE_WRITE8_MEMBER( tvdraw_axis_w );
46   DECLARE_READ8_MEMBER( tvdraw_status_r );
47   DECLARE_READ8_MEMBER( tvdraw_data_r );
48   DECLARE_READ8_MEMBER( joysel_r );
49
50   /* keyboard state */
51   UINT8 m_keylatch;
52
53   /* TV Draw state */
54   UINT8 m_tvdraw_data;
55};
56
57class sc3000_state : public sg1000_state
58{
59public:
60   sc3000_state(const machine_config &mconfig, device_type type, const char *tag)
61      : sg1000_state(mconfig, type, tag),
62        m_cassette(*this, CASSETTE_TAG)
63   { }
64
65   required_device<device_t> m_cassette;
66
67   virtual void machine_start();
68
69   void install_cartridge(UINT8 *ptr, int size);
70
71   DECLARE_READ8_MEMBER( ppi_pa_r );
72   DECLARE_READ8_MEMBER( ppi_pb_r );
73   DECLARE_WRITE8_MEMBER( ppi_pc_w );
74};
75
76class sf7000_state : public sc3000_state
77{
78public:
79   sf7000_state(const machine_config &mconfig, device_type type, const char *tag)
80      : sc3000_state(mconfig, type, tag),
81        m_fdc(*this, UPD765_TAG),
82        m_centronics(*this, CENTRONICS_TAG),
83        m_floppy0(*this, FLOPPY_0)
84   { }
85
86   required_device<device_t> m_fdc;
87   required_device<device_t> m_centronics;
88   required_device<device_t> m_floppy0;
89
90   virtual void machine_start();
91   virtual void machine_reset();
92
93   DECLARE_READ8_MEMBER( ppi_pa_r );
94   DECLARE_WRITE8_MEMBER( ppi_pc_w );
95   DECLARE_WRITE_LINE_MEMBER( fdc_intrq_w );
96
97   /* floppy state */
98   int m_fdc_irq;
99   int m_fdc_index;
100};
101
102#endif
src/mess/includes/sms.h
r11450r11451
1/*****************************************************************************
2 *
3 * includes/sms.h
4 *
5 ****************************************************************************/
6
7#ifndef SMS_H_
8#define SMS_H_
9
10#define LOG_REG
11#define LOG_PAGING
12#define LOG_COLOR
13
14#define NVRAM_SIZE             (0x08000)
15#define CPU_ADDRESSABLE_SIZE   (0x10000)
16
17#define MAX_CARTRIDGES        16
18
19class sms_state : public driver_device
20{
21public:
22   sms_state(const machine_config &mconfig, device_type type, const char *tag)
23   : driver_device(mconfig, type, tag) { }
24
25   // device_ts
26   device_t *m_main_cpu;
27   device_t *m_control_cpu;
28   device_t *m_vdp;
29   device_t *m_ym;
30   device_t *m_main_scr;
31   device_t *m_left_lcd;
32   device_t *m_right_lcd;
33
34   UINT8 m_bios_page_count;
35   UINT8 m_fm_detect;
36   UINT8 m_ctrl_reg;
37   int m_paused;
38   UINT8 m_bios_port;
39   UINT8 *m_BIOS;
40   UINT8 *m_mapper_ram;
41   UINT8 m_mapper[4];
42   // we are going to use 1-6, same as bank numbers. Notice, though, that most mappers
43   // only work on 16K banks and, hence, banks 4-6 are not always directly set
44   // (they often use bank3 + 0x2000 and bank5 + 0x2000)
45   UINT8 *m_banking_bios[7];
46   UINT8 *m_banking_cart[7];
47   UINT8 *m_banking_none[7];
48   UINT8 m_gg_sio[5];
49   UINT8 m_store_control;
50   UINT8 m_input_port0;
51   UINT8 m_input_port1;
52
53   // for gamegear LCD persistence hack
54   bitmap_t *m_tmp_bitmap;
55   bitmap_t *m_prev_bitmap;
56
57   // for 3D glass binocular hack
58   bitmap_t *m_prevleft_bitmap;
59   bitmap_t *m_prevright_bitmap;
60
61   /* Model identifiers */
62   UINT8 m_is_gamegear;
63   UINT8 m_is_region_japan;
64   UINT8 m_has_bios_0400;
65   UINT8 m_has_bios_2000;
66   UINT8 m_has_bios_full;
67   UINT8 m_has_bios;
68   UINT8 m_has_fm;
69
70   /* Data needed for Rapid Fire Unit support */
71   emu_timer *m_rapid_fire_timer;
72   UINT8 m_rapid_fire_state_1;
73   UINT8 m_rapid_fire_state_2;
74
75   /* Data needed for Paddle Control controller */
76   UINT32 m_last_paddle_read_time;
77   UINT8 m_paddle_read_state;
78
79   /* Data needed for Sports Pad controller */
80   UINT32 m_last_sports_pad_time_1;
81   UINT32 m_last_sports_pad_time_2;
82   UINT8 m_sports_pad_state_1;
83   UINT8 m_sports_pad_state_2;
84   UINT8 m_sports_pad_last_data_1;
85   UINT8 m_sports_pad_last_data_2;
86   UINT8 m_sports_pad_1_x;
87   UINT8 m_sports_pad_1_y;
88   UINT8 m_sports_pad_2_x;
89   UINT8 m_sports_pad_2_y;
90
91   /* Data needed for Light Phaser */
92   emu_timer *m_lphaser_1_timer;
93   emu_timer *m_lphaser_2_timer;
94   UINT8 m_lphaser_1_latch;
95   UINT8 m_lphaser_2_latch;
96   int m_lphaser_x_offs;   /* Needed to 'calibrate' lphaser; set at cart loading */
97
98   /* Data needed for SegaScope (3D glasses) */
99   UINT8 m_sscope_state;
100
101   /* Data needed for Terebi Oekaki (TV Draw) */
102   UINT8 m_tvdraw_data;
103
104   /* Cartridge slot info */
105   UINT8 m_current_cartridge;
106   struct
107   {
108      UINT8 *ROM;        /* Pointer to ROM image data */
109      UINT32 size;       /* Size of the ROM image */
110      UINT8 features;    /* on-cartridge special hardware */
111      UINT8 *cartSRAM;   /* on-cartridge SRAM */
112      UINT8 sram_save;   /* should be the contents of the on-cartridge SRAM be saved */
113      UINT8 *cartRAM;    /* additional on-cartridge RAM (64KB for Ernie Els Golf) */
114      UINT32 ram_size;   /* size of the on-cartridge RAM */
115      UINT8 ram_page;    /* currently swapped in cartridge RAM */
116   } m_cartridge[MAX_CARTRIDGES];
117};
118
119
120/*----------- defined in machine/sms.c -----------*/
121
122/* Function prototypes */
123WRITE8_HANDLER( sms_cartram_w );
124WRITE8_HANDLER( sms_cartram2_w );
125WRITE8_HANDLER( sms_fm_detect_w );
126READ8_HANDLER( sms_fm_detect_r );
127READ8_HANDLER( sms_input_port_0_r );
128READ8_HANDLER( sms_input_port_1_r );
129WRITE8_HANDLER( sms_ym2413_register_port_0_w );
130WRITE8_HANDLER( sms_ym2413_data_port_0_w );
131WRITE8_HANDLER( sms_io_control_w );
132READ8_HANDLER( sms_count_r );
133WRITE8_HANDLER( sms_sscope_w );
134READ8_HANDLER( sms_sscope_r );
135WRITE8_HANDLER( sms_mapper_w );
136READ8_HANDLER( sms_mapper_r );
137WRITE8_HANDLER( sms_bios_w );
138WRITE8_HANDLER( gg_sio_w );
139READ8_HANDLER( gg_sio_r );
140READ8_HANDLER( gg_input_port_2_r );
141
142INPUT_CHANGED( lgun1_changed );
143INPUT_CHANGED( lgun2_changed );
144
145void sms_pause_callback( running_machine &machine );
146void sms_store_int_callback( running_machine &machine, int state );
147
148DEVICE_START( sms_cart );
149DEVICE_IMAGE_LOAD( sms_cart );
150
151MACHINE_START( sms );
152MACHINE_RESET( sms );
153
154READ8_HANDLER( sms_store_cart_select_r );
155WRITE8_HANDLER( sms_store_cart_select_w );
156READ8_HANDLER( sms_store_select1 );
157READ8_HANDLER( sms_store_select2 );
158READ8_HANDLER( sms_store_control_r );
159WRITE8_HANDLER( sms_store_control_w );
160
161#define IO_EXPANSION    (0x80)   /* Expansion slot enable (1= disabled, 0= enabled) */
162#define IO_CARTRIDGE    (0x40)   /* Cartridge slot enable (1= disabled, 0= enabled) */
163#define IO_CARD         (0x20)   /* Card slot disabled (1= disabled, 0= enabled) */
164#define IO_WORK_RAM     (0x10)   /* Work RAM disabled (1= disabled, 0= enabled) */
165#define IO_BIOS_ROM     (0x08)   /* BIOS ROM disabled (1= disabled, 0= enabled) */
166#define IO_CHIP         (0x04)   /* I/O chip disabled (1= disabled, 0= enabled) */
167
168
169DRIVER_INIT( sg1000m3 );
170DRIVER_INIT( sms1 );
171DRIVER_INIT( smsj );
172DRIVER_INIT( sms2kr );
173DRIVER_INIT( smssdisp );
174DRIVER_INIT( gamegear );
175DRIVER_INIT( gamegeaj );
176
177VIDEO_START( sms1 );
178VIDEO_START( gamegear );
179SCREEN_UPDATE( sms1 );
180SCREEN_UPDATE( sms );
181SCREEN_UPDATE( gamegear );
182
183#endif /* SMS_H_ */
src/mess/video/smsvdp.c
r11450r11451
1/*********************************************************************
2
3    smsvdp.c
4
5    Implementation of video hardware chip used by Sega Master System
6
7**********************************************************************/
8
9/*
10    For more information, please see:
11    - http://cgfm2.emuviews.com/txt/msvdp.txt
12    - http://www.smspower.org/forums/viewtopic.php?p=44198
13
14A scanline contains the following sections:
15  - horizontal sync     1  ED      => HSYNC high/increment line counter/generate interrupts/etc
16  - left blanking       2  ED-EE
17  - color burst        14  EE-EF
18  - left blanking       8  F5-F9
19  - left border        13  F9-FF
20  - active display    256  00-7F
21  - right border       15  80-87
22  - right blanking      8  87-8B
23  - horizontal sync    25  8B-97   => HSYNC low
24
25
26NTSC frame timing
27                       256x192         256x224        256x240 (doesn't work on real hardware)
28  - vertical blanking   3  D5-D7        3  E5-E7       3  EE-F0
29  - top blanking       13  D8-E4       13  E8-F4      13  F1-FD
30  - top border         27  E5-FF       11  F5-FF       3  FD-FF
31  - active display    192  00-BF      224  00-DF     240  00-EF
32  - bottom border      24  C0-D7        8  E0-E7       0  F0-F0
33  - bottom blanking     3  D8-DA        3  E8-EA       3  F0-F2
34
35
36PAL frame timing
37                       256x192         256x224        256x240
38  - vertical blanking   3  BA-BC        3  CA-CC       3  D2-D4
39  - top blanking       13  BD-C9       13  CD-D9      13  D5-E1
40  - top border         54  CA-FF       38  DA-FF      30  E2-FF
41  - active display    192  00-BF      224  00-DF     240  00-EF
42  - bottom border      48  C0-EF       32  E0-FF      24  F0-07
43  - bottom blanking     3  F0-F2        3  00-02       3  08-0A
44
45  TODO:
46    - implement differences between SMS1_VDP & SMS_VDP/GG_VDP
47
48*/
49
50#include "emu.h"
51#include "video/smsvdp.h"
52
53#define IS_SMS1_VDP           (smsvdp->features & MODEL_315_5124)
54#define IS_SMS2_VDP           (smsvdp->features & MODEL_315_5246)
55#define IS_GAMEGEAR_VDP       (smsvdp->features & MODEL_315_5378)
56
57#define STATUS_VINT           0x80   /* Pending vertical interrupt flag */
58#define STATUS_SPROVR         0x40   /* Sprite overflow flag */
59#define STATUS_SPRCOL         0x20   /* Object collision flag */
60#define STATUS_HINT           0x02   /* Pending horizontal interrupt flag */
61
62#define VINT_HPOS             23
63#define HINT_HPOS             23
64#define VCOUNT_CHANGE_HPOS    22
65#define VINT_FLAG_HPOS        7
66#define SPROVR_HPOS           6
67#define SPRCOL_BASEHPOS       42
68#define DISPLAY_CB_HPOS       5  /* fix X-Scroll latchtime (Flubba's VDPTest) */
69
70#define GG_CRAM_SIZE          0x40   /* 32 colors x 2 bytes per color = 64 bytes */
71#define SMS_CRAM_SIZE         0x20   /* 32 colors x 1 bytes per color = 32 bytes */
72#define MAX_CRAM_SIZE         0x40
73
74#define VRAM_SIZE             0x4000
75
76#define PRIORITY_BIT          0x1000
77#define BACKDROP_COLOR        ((smsvdp->vdp_mode == 4 ? 0x10 : 0x00) + (smsvdp->reg[0x07] & 0x0f))
78
79#define NUM_OF_REGISTER       0x10  /* 16 registers */
80
81#define INIT_VCOUNT           0
82#define VERTICAL_BLANKING     1
83#define TOP_BLANKING          2
84#define TOP_BORDER            3
85#define ACTIVE_DISPLAY_V      4
86#define BOTTOM_BORDER         5
87#define BOTTOM_BLANKING       6
88
89static const UINT8 sms_ntsc_192[7] = { 0xd5, 3, 13, 27, 192, 24, 3 };
90static const UINT8 sms_ntsc_224[7] = { 0xe5, 3, 13, 11, 224,  8, 3 };
91static const UINT8 sms_ntsc_240[7] = { 0xee, 3, 13,  3, 240,  0, 3 };
92static const UINT8 sms_pal_192[7]  = { 0xba, 3, 13, 54, 192, 48, 3 };
93static const UINT8 sms_pal_224[7]  = { 0xca, 3, 13, 38, 224, 32, 3 };
94static const UINT8 sms_pal_240[7]  = { 0xd2, 3, 13, 30, 240, 24, 3 };
95
96
97typedef struct _smsvdp_t smsvdp_t;
98struct _smsvdp_t
99{
100   UINT32           features;
101   UINT8            reg[NUM_OF_REGISTER];     /* All the registers */
102   UINT8            status;                   /* Status register */
103   UINT8            reg9copy;                 /* Internal copy of register 9 */
104   UINT8            addrmode;                 /* Type of VDP action */
105   UINT16           addr;                     /* Contents of internal VDP address register */
106   UINT8            cram_mask;                /* Mask to switch between SMS and GG CRAM sizes */
107   int              cram_dirty;               /* Have there been any changes to the CRAM area */
108   int              pending;
109   UINT8            buffer;
110   int              gg_sms_mode;              /* Shrunk SMS screen on GG lcd mode flag */
111   int              irq_state;                /* The status of the IRQ line of the VDP */
112   int              vdp_mode;                 /* Current mode of the VDP: 0,1,2,3,4 */
113   int              y_pixels;                 /* 192, 224, 240 */
114   UINT8            line_counter;
115   UINT8            hcounter;
116   memory_region            *VRAM;                    /* Pointer to VRAM */
117   memory_region            *CRAM;                    /* Pointer to CRAM */
118   const UINT8      *sms_frame_timing;
119   bitmap_t         *tmpbitmap;
120   UINT8            *collision_buffer;
121
122   /* line_buffer will be used to hold 5 lines of line data. Line #0 is the regular blitting area.
123       Lines #1-#4 will be used as a kind of cache to be used for vertical scaling in the gamegear
124       sms compatibility mode. */
125   int              *line_buffer;
126   int              current_palette[32];
127   smsvdp_int_cb    int_callback;
128   smsvdp_pause_cb  pause_callback;
129   emu_timer        *smsvdp_display_timer;
130};
131
132static TIMER_CALLBACK( smsvdp_display_callback );
133static void sms_refresh_line( running_machine &machine, smsvdp_t *smsvdp, bitmap_t *bitmap, int offsetx, int offsety, int line );
134static void sms_update_palette( smsvdp_t *smsvdp );
135
136
137/*****************************************************************************
138    INLINE FUNCTIONS
139*****************************************************************************/
140
141INLINE smsvdp_t *get_safe_token(device_t *device)
142{
143   assert(device != NULL);
144   assert(device->type() == SMSVDP);
145
146   return (smsvdp_t *)downcast<legacy_device_base *>(device)->token();
147}
148
149INLINE const smsvdp_interface *get_interface(device_t *device)
150{
151   assert(device != NULL);
152   assert((device->type() == SMSVDP));
153   return (const smsvdp_interface *) device->static_config();
154}
155
156/*************************************
157 *
158 *  Utilities
159 *
160 *************************************/
161
162static void set_display_settings( device_t *device )
163{
164   smsvdp_t *smsvdp = get_safe_token(device);
165
166   screen_device *screen = device->machine().first_screen();
167   int height = screen->height();
168   int M1, M2, M3, M4;
169   M1 = smsvdp->reg[0x01] & 0x10;
170   M2 = smsvdp->reg[0x00] & 0x02;
171   M3 = smsvdp->reg[0x01] & 0x08;
172   M4 = smsvdp->reg[0x00] & 0x04;
173   smsvdp->y_pixels = 192;
174   if (M4)
175   {
176      /* mode 4 */
177      smsvdp->vdp_mode = 4;
178      if (M2 && (IS_SMS2_VDP || IS_GAMEGEAR_VDP))
179      {
180         if (M1 && !M3)
181            smsvdp->y_pixels = 224;   /* 224-line display */
182         else if (!M1 && M3)
183            smsvdp->y_pixels = 240;   /* 240-line display */
184      }
185   }
186   else
187   {
188      /* original TMS9918 mode */
189      if (!M1 && !M2 && !M3)
190      {
191         smsvdp->vdp_mode = 0;
192      }
193      else
194//      if (M1 && !M2 && !M3)
195//      {
196//          smsvdp->vdp_mode = 1;
197//      }
198//      else
199      if (!M1 && M2 && !M3)
200      {
201         smsvdp->vdp_mode = 2;
202//      }
203//      else
204//      if (!M1 && !M2 && M3)
205//      {
206//          smsvdp->vdp_mode = 3;
207      }
208      else
209      {
210         logerror("Unknown video mode detected (M1 = %c, M2 = %c, M3 = %c, M4 = %c)\n", M1 ? '1' : '0', M2 ? '1' : '0', M3 ? '1' : '0', M4 ? '1' : '0');
211      }
212   }
213
214   switch (smsvdp->y_pixels)
215   {
216   case 192:
217      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_192 : sms_ntsc_192;
218      break;
219
220   case 224:
221      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_224 : sms_ntsc_224;
222      break;
223
224   case 240:
225      smsvdp->sms_frame_timing = (height == PAL_Y_PIXELS) ? sms_pal_240 : sms_ntsc_240;
226      break;
227   }
228   smsvdp->cram_dirty = 1;
229}
230
231
232READ8_DEVICE_HANDLER( sms_vdp_vcount_r )
233{
234   smsvdp_t *smsvdp = get_safe_token(device);
235   int vpos = device->machine().primary_screen->vpos();
236
237   if (device->machine().primary_screen->hpos() < VCOUNT_CHANGE_HPOS)
238   {
239      vpos--;
240      if (vpos < 0)
241         vpos += device->machine().primary_screen->height();
242   }
243
244   return (smsvdp->sms_frame_timing[INIT_VCOUNT] + vpos) & 0xff;
245}
246
247
248READ8_DEVICE_HANDLER( sms_vdp_hcount_latch_r )
249{
250   smsvdp_t *smsvdp = get_safe_token(device);
251
252   return smsvdp->hcounter;
253}
254
255WRITE8_DEVICE_HANDLER( sms_vdp_hcount_latch_w )
256{
257   smsvdp_t *smsvdp = get_safe_token(device);
258
259   smsvdp->hcounter = data;
260}
261
262
263void sms_vdp_set_ggsmsmode( device_t *device, int mode )
264{
265   smsvdp_t *smsvdp = get_safe_token(device);
266
267   smsvdp->gg_sms_mode = mode;
268   smsvdp->cram_mask = (IS_GAMEGEAR_VDP && !smsvdp->gg_sms_mode) ? (GG_CRAM_SIZE - 1) : (SMS_CRAM_SIZE - 1);
269}
270
271
272static TIMER_CALLBACK( smsvdp_set_status )
273{
274   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
275
276   smsvdp->status |= (UINT8) param;
277}
278
279
280static TIMER_CALLBACK( smsvdp_check_hint )
281{
282   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
283
284   if (smsvdp->line_counter == 0x00)
285   {
286      smsvdp->line_counter = smsvdp->reg[0x0a];
287      smsvdp->status |= STATUS_HINT;
288   }
289   else
290   {
291      smsvdp->line_counter--;
292   }
293
294   if ((smsvdp->status & STATUS_HINT) && (smsvdp->reg[0x00] & 0x10))
295   {
296      smsvdp->irq_state = 1;
297
298      if (smsvdp->int_callback)
299         smsvdp->int_callback(machine, ASSERT_LINE);
300   }
301}
302
303
304static TIMER_CALLBACK( smsvdp_check_vint )
305{
306   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
307
308   if ((smsvdp->status & STATUS_VINT) && (smsvdp->reg[0x01] & 0x20))
309   {
310      smsvdp->irq_state = 1;
311
312      if (smsvdp->int_callback)
313         smsvdp->int_callback(machine, ASSERT_LINE);
314   }
315}
316
317
318static TIMER_CALLBACK( smsvdp_display_callback )
319{
320   smsvdp_t *smsvdp = (smsvdp_t *) ptr;
321
322   rectangle rec;
323   int vpos = machine.primary_screen->vpos();
324   int vpos_limit = smsvdp->sms_frame_timing[VERTICAL_BLANKING] + smsvdp->sms_frame_timing[TOP_BLANKING]
325                  + smsvdp->sms_frame_timing[TOP_BORDER] + smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V]
326                  + smsvdp->sms_frame_timing[BOTTOM_BORDER] + smsvdp->sms_frame_timing[BOTTOM_BLANKING];
327
328   rec.min_y = rec.max_y = vpos;
329
330   /* Check if we're on the last line of a frame */
331   if (vpos == vpos_limit - 1)
332   {
333      smsvdp->line_counter = smsvdp->reg[0x0a];
334      if (smsvdp->pause_callback)
335         smsvdp->pause_callback(machine);
336
337      return;
338   }
339
340   vpos_limit -= smsvdp->sms_frame_timing[BOTTOM_BLANKING];
341
342   /* Check if we're below the bottom border */
343   if (vpos >= vpos_limit)
344   {
345      smsvdp->line_counter = smsvdp->reg[0x0a];
346      return;
347   }
348
349   vpos_limit -= smsvdp->sms_frame_timing[BOTTOM_BORDER];
350
351   /* Check if we're in the bottom border area */
352   if (vpos >= vpos_limit)
353   {
354      if (vpos == vpos_limit)
355      {
356         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, HINT_HPOS), FUNC(smsvdp_check_hint),0 ,smsvdp);
357      }
358      else
359      {
360         smsvdp->line_counter = smsvdp->reg[0x0a];
361      }
362
363      if (vpos == vpos_limit + 1)
364      {
365         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, VINT_FLAG_HPOS), FUNC(smsvdp_set_status), (int)STATUS_VINT, smsvdp);
366         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, VINT_HPOS), FUNC(smsvdp_check_vint), 0, smsvdp);
367      }
368
369      sms_update_palette(smsvdp);
370
371      /* Draw left border */
372      rec.min_x = LBORDER_START;
373      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
374      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
375
376      /* Draw right border */
377      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
378      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
379      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
380
381      /* Draw middle of the border */
382      /* We need to do this through the regular drawing function so it will */
383      /* be included in the gamegear scaling functions */
384      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit - smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V], vpos - (vpos_limit - smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V]));
385      return;
386   }
387
388   vpos_limit -= smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V];
389
390   /* Check if we're in the active display area */
391   if (vpos >= vpos_limit)
392   {
393      if (vpos == vpos_limit)
394      {
395         smsvdp->reg9copy = smsvdp->reg[0x09];
396      }
397
398      machine.scheduler().timer_set(machine.primary_screen->time_until_pos(vpos, HINT_HPOS), FUNC(smsvdp_check_hint),0, smsvdp);
399
400      sms_update_palette(smsvdp);
401
402      /* Draw left border */
403      rec.min_x = LBORDER_START;
404      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
405      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
406
407      /* Draw right border */
408      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
409      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
410      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
411
412      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit, vpos - vpos_limit);
413
414      return;
415   }
416
417   vpos_limit -= smsvdp->sms_frame_timing[TOP_BORDER];
418
419   /* Check if we're in the top border area */
420   if (vpos >= vpos_limit)
421   {
422      smsvdp->line_counter = smsvdp->reg[0x0a];
423      sms_update_palette(smsvdp);
424
425      /* Draw left border */
426      rec.min_x = LBORDER_START;
427      rec.max_x = LBORDER_START + LBORDER_X_PIXELS - 1;
428      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
429
430      /* Draw right border */
431      rec.min_x = LBORDER_START + LBORDER_X_PIXELS + 256;
432      rec.max_x = rec.min_x + RBORDER_X_PIXELS - 1;
433      bitmap_fill(smsvdp->tmpbitmap, &rec, machine.pens[smsvdp->current_palette[BACKDROP_COLOR]]);
434
435      /* Draw middle of the border */
436      /* We need to do this through the regular drawing function so it will */
437      /* be included in the gamegear scaling functions */
438      sms_refresh_line(machine, smsvdp, smsvdp->tmpbitmap, LBORDER_START + LBORDER_X_PIXELS, vpos_limit + smsvdp->sms_frame_timing[TOP_BORDER], vpos - (vpos_limit + smsvdp->sms_frame_timing[TOP_BORDER]));
439      return;
440   }
441
442   /* we're in the vertical or top blanking area */
443   smsvdp->line_counter = smsvdp->reg[0x0a];
444}
445
446
447READ8_DEVICE_HANDLER( sms_vdp_data_r )
448{
449   smsvdp_t *smsvdp = get_safe_token(device);
450   UINT8 temp;
451
452   /* SMS 2 & GG behaviour. Seems like the latched data is passed straight through */
453   /* to the address register when in the middle of doing a command.               */
454   /* Cosmic Spacehead needs this, among others                                    */
455   /* Clear pending write flag */
456   smsvdp->pending = 0;
457
458   /* Return read buffer contents */
459   temp = smsvdp->buffer;
460
461   /* Load read buffer */
462   smsvdp->buffer = smsvdp->VRAM->u8((smsvdp->addr & 0x3fff));
463
464   /* Bump internal address register */
465   smsvdp->addr += 1;
466   return temp;
467}
468
469
470READ8_DEVICE_HANDLER( sms_vdp_ctrl_r )
471{
472   smsvdp_t *smsvdp = get_safe_token(device);
473
474   UINT8 temp = smsvdp->status;
475
476   /* Clear pending write flag */
477   smsvdp->pending = 0;
478
479   smsvdp->status &= ~(STATUS_VINT | STATUS_SPROVR | STATUS_SPRCOL | STATUS_HINT);
480
481   if (smsvdp->irq_state == 1)
482   {
483      smsvdp->irq_state = 0;
484
485      if (smsvdp->int_callback)
486         smsvdp->int_callback(device->machine(), CLEAR_LINE);
487   }
488
489   /* low 5 bits return non-zero data (it fixes PGA Tour Golf course map introduction) */
490   return temp | 0x1f;
491}
492
493
494WRITE8_DEVICE_HANDLER( sms_vdp_data_w )
495{
496   smsvdp_t *smsvdp = get_safe_token(device);
497   int address;
498
499   /* SMS 2 & GG behaviour. Seems like the latched data is passed straight through */
500   /* to the address register when in the middle of doing a command.               */
501   /* Cosmic Spacehead needs this, among others                                    */
502   /* Clear pending write flag */
503   smsvdp->pending = 0;
504
505   switch(smsvdp->addrmode)
506   {
507      case 0x00:
508      case 0x01:
509      case 0x02:
510         address = (smsvdp->addr & 0x3fff);
511         smsvdp->VRAM->u8(address) = data;
512         break;
513
514      case 0x03:
515         address = smsvdp->addr & smsvdp->cram_mask;
516         if (data != smsvdp->CRAM->u8(address))
517         {
518            smsvdp->CRAM->u8(address) = data;
519            smsvdp->cram_dirty = 1;
520         }
521         break;
522   }
523
524   smsvdp->buffer = data;
525   smsvdp->addr += 1;
526}
527
528
529WRITE8_DEVICE_HANDLER( sms_vdp_ctrl_w )
530{
531   smsvdp_t *smsvdp = get_safe_token(device);
532
533   int reg_num;
534
535   if (smsvdp->pending == 0)
536   {
537      smsvdp->addr = (smsvdp->addr & 0xff00) | data;
538      smsvdp->pending = 1;
539   }
540   else
541   {
542      /* Clear pending write flag */
543      smsvdp->pending = 0;
544
545      smsvdp->addrmode = (data >> 6) & 0x03;
546      smsvdp->addr = (data << 8) | (smsvdp->addr & 0xff);
547      switch (smsvdp->addrmode)
548      {
549      case 0:      /* VRAM reading mode */
550         smsvdp->buffer = smsvdp->VRAM->u8(smsvdp->addr & 0x3fff);
551         smsvdp->addr += 1;
552         break;
553
554      case 1:      /* VRAM writing mode */
555         break;
556
557      case 2:      /* VDP register write */
558         reg_num = data & 0x0f;
559         smsvdp->reg[reg_num] = smsvdp->addr & 0xff;
560         if (reg_num == 0 && smsvdp->addr & 0x02)
561            logerror("overscan enabled.\n");
562
563         if (reg_num == 0 || reg_num == 1)
564            set_display_settings(device);
565
566         if (reg_num == 1)
567         {
568            device->machine().scheduler().timer_set(device->machine().primary_screen->time_until_pos(device->machine().primary_screen->vpos(), VINT_HPOS), FUNC(smsvdp_check_vint),0 ,smsvdp);
569         }
570         smsvdp->addrmode = 0;
571         break;
572
573      case 3:      /* CRAM writing mode */
574         break;
575      }
576   }
577}
578
579
580static void sms_refresh_line_mode4( smsvdp_t *smsvdp, int *line_buffer, int *priority_selected, int line )
581{
582   int tile_column;
583   int x_scroll, y_scroll, x_scroll_start_column;
584   int pixel_x, pixel_plot_x;
585   int bit_plane_0, bit_plane_1, bit_plane_2, bit_plane_3;
586   int scroll_mod;
587   UINT16 name_table_address;
588   UINT8 *name_table;
589
590   if (smsvdp->y_pixels != 192)
591   {
592      name_table_address = ((smsvdp->reg[0x02] & 0x0c) << 10) | 0x0700;
593      scroll_mod = 256;
594   }
595   else
596   {
597      name_table_address = (smsvdp->reg[0x02] << 10) & 0x3800;
598      scroll_mod = 224;
599   }
600
601   if (IS_SMS1_VDP)
602      name_table_address = name_table_address & (((smsvdp->reg[0x02] & 0x01) << 10) | 0x3bff);
603
604   /* if top 2 rows of screen not affected by horizontal scrolling, then x_scroll = 0 */
605   /* else x_scroll = reg[0x08]                                                       */
606   x_scroll = (((smsvdp->reg[0x00] & 0x40) && (line < 16)) ? 0 : 0x0100 - smsvdp->reg[0x08]);
607
608   x_scroll_start_column = (x_scroll >> 3);          /* x starting column tile */
609
610   /* Draw background layer */
611   for (tile_column = 0; tile_column < 33; tile_column++)
612   {
613      UINT16 tile_data;
614      int tile_selected, palette_selected, horiz_selected, vert_selected, priority_select;
615      int tile_line;
616
617      /* Rightmost 8 columns for SMS (or 2 columns for GG) not affected by */
618      /* vertical scrolling when bit 7 of reg[0x00] is set */
619      y_scroll = ((smsvdp->reg[0x00] & 0x80) && (tile_column > 23)) ? 0 : smsvdp->reg9copy;
620
621      name_table = smsvdp->VRAM->base() + name_table_address + ((((line + y_scroll) % scroll_mod) >> 3) << 6);
622
623      tile_line = ((tile_column + x_scroll_start_column) & 0x1f) * 2;
624      tile_data = name_table[tile_line] | (name_table[tile_line + 1] << 8);
625
626      tile_selected = (tile_data & 0x01ff);
627      priority_select = tile_data & PRIORITY_BIT;
628      palette_selected = (tile_data >> 11) & 0x01;
629      vert_selected = (tile_data >> 10) & 0x01;
630      horiz_selected = (tile_data >> 9) & 0x01;
631
632      tile_line = line - ((0x07 - (y_scroll & 0x07)) + 1);
633      if (vert_selected)
634         tile_line = 0x07 - tile_line;
635
636      bit_plane_0 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x00);
637      bit_plane_1 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x01);
638      bit_plane_2 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x02);
639      bit_plane_3 = smsvdp->VRAM->u8(((tile_selected << 5) + ((tile_line & 0x07) << 2)) + 0x03);
640
641      for (pixel_x = 0; pixel_x < 8 ; pixel_x++)
642      {
643         UINT8 pen_bit_0, pen_bit_1, pen_bit_2, pen_bit_3;
644         UINT8 pen_selected;
645
646         pen_bit_0 = (bit_plane_0 >> (7 - pixel_x)) & 0x01;
647         pen_bit_1 = (bit_plane_1 >> (7 - pixel_x)) & 0x01;
648         pen_bit_2 = (bit_plane_2 >> (7 - pixel_x)) & 0x01;
649         pen_bit_3 = (bit_plane_3 >> (7 - pixel_x)) & 0x01;
650
651         pen_selected = (pen_bit_3 << 3 | pen_bit_2 << 2 | pen_bit_1 << 1 | pen_bit_0);
652         if (palette_selected)
653            pen_selected |= 0x10;
654
655
656         if (!horiz_selected)
657         {
658            pixel_plot_x = pixel_x;
659         }
660         else
661         {
662            pixel_plot_x = 7 - pixel_x;
663         }
664         pixel_plot_x = (0 - (x_scroll & 0x07) + (tile_column << 3) + pixel_plot_x);
665         if (pixel_plot_x >= 0 && pixel_plot_x < 256)
666         {
667//              logerror("%x %x\n", pixel_plot_x + pixel_offset_x, pixel_plot_y);
668            line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
669            priority_selected[pixel_plot_x] = priority_select | (pen_selected & 0x0f);
670         }
671      }
672   }
673}
674
675static void sms_refresh_mode4_sprites( running_machine &machine, smsvdp_t *smsvdp, int *line_buffer, int *priority_selected, int pixel_plot_y, int line )
676{
677   int sprite_index;
678   int pixel_x, pixel_plot_x;
679   int sprite_x, sprite_y, sprite_line, sprite_tile_selected, sprite_height, sprite_zoom;
680   int sprite_col_occurred, sprite_col_x;
681   int sprite_buffer[8], sprite_buffer_count, sprite_buffer_index;
682   int bit_plane_0, bit_plane_1, bit_plane_2, bit_plane_3;
683   UINT8 *sprite_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x05] << 7) & 0x3f00);
684
685   /* Draw sprite layer */
686   sprite_height = (smsvdp->reg[0x01] & 0x02 ? 16 : 8);
687   sprite_zoom = 1;
688
689   if (smsvdp->reg[0x01] & 0x01)      /* sprite doubling */
690      sprite_zoom = 2;
691
692   sprite_buffer_count = 0;
693   for (sprite_index = 0; (sprite_index < 64) && (sprite_table[sprite_index] != 0xd0 || smsvdp->y_pixels != 192) && (sprite_buffer_count < 9); sprite_index++)
694   {
695      sprite_y = sprite_table[sprite_index] + 1; /* sprite y position starts at line 1 */
696
697      if (sprite_y > 240)
698         sprite_y -= 256; /* wrap from top if y position is > 240 */
699
700      if ((line >= sprite_y) && (line < (sprite_y + sprite_height * sprite_zoom)))
701      {
702         if (sprite_buffer_count < 8)
703         {
704            sprite_buffer[sprite_buffer_count] = sprite_index;
705         }
706         else if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
707         {
708            /* Too many sprites per line */
709            machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPROVR_HPOS), FUNC(smsvdp_set_status), (int)STATUS_SPROVR, smsvdp);
710         }
711         sprite_buffer_count++;
712      }
713   }
714
715   /* Check if display is disabled */
716   if (!(smsvdp->reg[0x01] & 0x40))
717      return;
718
719   if (sprite_buffer_count > 8)
720      sprite_buffer_count = 8;
721
722   memset(smsvdp->collision_buffer, 0, SMS_X_PIXELS);
723   sprite_buffer_count--;
724
725   for (sprite_buffer_index = sprite_buffer_count; sprite_buffer_index >= 0; sprite_buffer_index--)
726   {
727      sprite_index = sprite_buffer[sprite_buffer_index];
728      sprite_y = sprite_table[sprite_index] + 1; /* sprite y position starts at line 1 */
729
730      if (sprite_y > 240)
731         sprite_y -= 256; /* wrap from top if y position is > 240 */
732
733      sprite_x = sprite_table[0x80 + (sprite_index << 1)];
734
735      if (smsvdp->reg[0x00] & 0x08)
736         sprite_x -= 0x08;    /* sprite shift */
737
738      sprite_tile_selected = sprite_table[0x81 + (sprite_index << 1)];
739
740      if (smsvdp->reg[0x06] & 0x04)
741         sprite_tile_selected += 256; /* pattern table select */
742
743      if (smsvdp->reg[0x01] & 0x02)
744         sprite_tile_selected &= 0x01fe; /* force even index */
745
746      sprite_line = (line - sprite_y) / sprite_zoom;
747
748      if (sprite_line > 0x07)
749         sprite_tile_selected += 1;
750
751      bit_plane_0 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x00);
752      bit_plane_1 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x01);
753      bit_plane_2 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x02);
754      bit_plane_3 = smsvdp->VRAM->u8(((sprite_tile_selected << 5) + ((sprite_line & 0x07) << 2)) + 0x03);
755
756      sprite_col_occurred = 0;
757      sprite_col_x = 0;
758
759      for (pixel_x = 0; pixel_x < 8 ; pixel_x++)
760      {
761         UINT8 pen_bit_0, pen_bit_1, pen_bit_2, pen_bit_3;
762         int pen_selected;
763
764         pen_bit_0 = (bit_plane_0 >> (7 - pixel_x)) & 0x01;
765         pen_bit_1 = (bit_plane_1 >> (7 - pixel_x)) & 0x01;
766         pen_bit_2 = (bit_plane_2 >> (7 - pixel_x)) & 0x01;
767         pen_bit_3 = (bit_plane_3 >> (7 - pixel_x)) & 0x01;
768
769         pen_selected = (pen_bit_3 << 3 | pen_bit_2 << 2 | pen_bit_1 << 1 | pen_bit_0) | 0x10;
770
771         if (pen_selected == 0x10)      /* Transparent palette so skip draw */
772         {
773            continue;
774         }
775
776         if (smsvdp->reg[0x01] & 0x01)
777         {
778            /* sprite doubling is enabled */
779            pixel_plot_x = sprite_x + (pixel_x << 1);
780
781            /* check to prevent going outside of active display area */
782            if (pixel_plot_x < 0 || pixel_plot_x > 255)
783            {
784               continue;
785            }
786
787            if (!(priority_selected[pixel_plot_x] & PRIORITY_BIT))
788            {
789               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
790               line_buffer[pixel_plot_x + 1] = smsvdp->current_palette[pen_selected];
791            }
792            else
793            {
794               if (priority_selected[pixel_plot_x] == PRIORITY_BIT)
795               {
796                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
797               }
798               if (priority_selected[pixel_plot_x + 1] == PRIORITY_BIT)
799               {
800                  line_buffer[pixel_plot_x + 1] = smsvdp->current_palette[pen_selected];
801               }
802            }
803            if (smsvdp->collision_buffer[pixel_plot_x] != 1)
804            {
805               smsvdp->collision_buffer[pixel_plot_x] = 1;
806            }
807            else
808            {
809               if (!sprite_col_occurred)
810               {
811                  sprite_col_occurred = 1;
812                  sprite_col_x = pixel_plot_x;
813               }
814            }
815            if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
816            {
817               smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
818            }
819            else
820            {
821               if (!sprite_col_occurred)
822               {
823                  sprite_col_occurred = 1;
824                  sprite_col_x = pixel_plot_x;
825               }
826            }
827         }
828         else
829         {
830            pixel_plot_x = sprite_x + pixel_x;
831
832            /* check to prevent going outside of active display area */
833            if (pixel_plot_x < 0 || pixel_plot_x > 255)
834            {
835               continue;
836            }
837
838            if (!(priority_selected[pixel_plot_x] & PRIORITY_BIT))
839            {
840               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
841            }
842            else
843            {
844               if (priority_selected[pixel_plot_x] == PRIORITY_BIT)
845               {
846                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
847               }
848            }
849            if (smsvdp->collision_buffer[pixel_plot_x] != 1)
850            {
851               smsvdp->collision_buffer[pixel_plot_x] = 1;
852            }
853            else
854            {
855               if (!sprite_col_occurred)
856               {
857                  sprite_col_occurred = 1;
858                  sprite_col_x = pixel_plot_x;
859               }
860            }
861         }
862      }
863      if (sprite_col_occurred)
864         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPRCOL_BASEHPOS + sprite_col_x), FUNC(smsvdp_set_status), (int)STATUS_SPRCOL, smsvdp);
865   }
866
867   /* Fill column 0 with overscan color from reg[0x07] */
868   if (smsvdp->reg[0x00] & 0x20)
869   {
870      line_buffer[0] = smsvdp->current_palette[BACKDROP_COLOR];
871      line_buffer[1] = smsvdp->current_palette[BACKDROP_COLOR];
872      line_buffer[2] = smsvdp->current_palette[BACKDROP_COLOR];
873      line_buffer[3] = smsvdp->current_palette[BACKDROP_COLOR];
874      line_buffer[4] = smsvdp->current_palette[BACKDROP_COLOR];
875      line_buffer[5] = smsvdp->current_palette[BACKDROP_COLOR];
876      line_buffer[6] = smsvdp->current_palette[BACKDROP_COLOR];
877      line_buffer[7] = smsvdp->current_palette[BACKDROP_COLOR];
878   }
879}
880
881
882static void sms_refresh_tms9918_sprites( running_machine &machine, smsvdp_t *smsvdp, int *line_buffer, int pixel_plot_y, int line )
883{
884   int pixel_plot_x;
885   int sprite_col_occurred, sprite_col_x;
886   int sprite_height, sprite_buffer_count, sprite_index, sprite_buffer[5], sprite_buffer_index;
887   UINT8 *sprite_table, *sprite_pattern_table;
888
889   /* Draw sprite layer */
890   sprite_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x05] & 0x7f) << 7);
891   sprite_pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x06] & 0x07) << 11);
892   sprite_height = 8;
893
894   if (smsvdp->reg[0x01] & 0x02)                         /* Check if SI is set */
895      sprite_height = sprite_height * 2;
896   if (smsvdp->reg[0x01] & 0x01)                         /* Check if MAG is set */
897      sprite_height = sprite_height * 2;
898
899   sprite_buffer_count = 0;
900   for (sprite_index = 0; (sprite_index < 32 * 4) && (sprite_table[sprite_index] != 0xd0) && (sprite_buffer_count < 5); sprite_index += 4)
901   {
902      int sprite_y = sprite_table[sprite_index] + 1;
903
904      if (sprite_y > 240)
905         sprite_y -= 256;
906
907      if ((line >= sprite_y) && (line < (sprite_y + sprite_height)))
908      {
909         if (sprite_buffer_count < 5)
910         {
911            sprite_buffer[sprite_buffer_count] = sprite_index;
912         }
913         else if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
914         {
915            /* Too many sprites per line */
916            machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPROVR_HPOS), FUNC(smsvdp_set_status), (int)STATUS_SPROVR, smsvdp);
917         }
918         sprite_buffer_count++;
919      }
920   }
921
922   /* Check if display is disabled */
923   if (!(smsvdp->reg[0x01] & 0x40))
924      return;
925
926   if (sprite_buffer_count > 4)
927      sprite_buffer_count = 4;
928
929   memset(smsvdp->collision_buffer, 0, SMS_X_PIXELS);
930   sprite_buffer_count--;
931
932   for (sprite_buffer_index = sprite_buffer_count; sprite_buffer_index >= 0; sprite_buffer_index--)
933   {
934      int pen_selected;
935      int sprite_line, pixel_x, sprite_x, sprite_tile_selected;
936      int sprite_y;
937      UINT8 pattern;
938
939      sprite_index = sprite_buffer[sprite_buffer_index];
940      sprite_y = sprite_table[sprite_index] + 1;
941
942      if (sprite_y > 240)
943         sprite_y -= 256;
944
945      sprite_x = sprite_table[sprite_index + 1];
946      pen_selected = sprite_table[sprite_index + 3] & 0x0f;
947
948      if (IS_GAMEGEAR_VDP)
949         pen_selected |= 0x10;
950
951      if (sprite_table[sprite_index + 3] & 0x80)
952         sprite_x -= 32;
953
954      sprite_tile_selected = sprite_table[sprite_index + 2];
955      sprite_line = line - sprite_y;
956
957      if (smsvdp->reg[0x01] & 0x01)
958         sprite_line >>= 1;
959
960      if (smsvdp->reg[0x01] & 0x02)
961      {
962         sprite_tile_selected &= 0xfc;
963
964         if (sprite_line > 0x07)
965         {
966            sprite_tile_selected += 1;
967            sprite_line -= 8;
968         }
969      }
970
971      pattern = sprite_pattern_table[sprite_tile_selected * 8 + sprite_line];
972
973      sprite_col_occurred = 0;
974      sprite_col_x = 0;
975
976      for (pixel_x = 0; pixel_x < 8; pixel_x++)
977      {
978         if (smsvdp->reg[0x01] & 0x01)
979         {
980            pixel_plot_x = sprite_x + pixel_x * 2;
981            if (pixel_plot_x < 0 || pixel_plot_x > 255)
982            {
983               continue;
984            }
985
986            if (pen_selected && (pattern & (1 << (7 - pixel_x))))
987            {
988               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
989
990               if (smsvdp->collision_buffer[pixel_plot_x] != 1)
991               {
992                  smsvdp->collision_buffer[pixel_plot_x] = 1;
993               }
994               else
995               {
996                  if (!sprite_col_occurred)
997                  {
998                     sprite_col_occurred = 1;
999                     sprite_col_x = pixel_plot_x;
1000                  }
1001               }
1002
1003               line_buffer[pixel_plot_x+1] = smsvdp->current_palette[pen_selected];
1004
1005               if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
1006               {
1007                  smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
1008               }
1009               else
1010               {
1011                  if (!sprite_col_occurred)
1012                  {
1013                     sprite_col_occurred = 1;
1014                     sprite_col_x = pixel_plot_x;
1015                  }
1016               }
1017            }
1018         }
1019         else
1020         {
1021            pixel_plot_x = sprite_x + pixel_x;
1022
1023            if (pixel_plot_x < 0 || pixel_plot_x > 255)
1024            {
1025               continue;
1026            }
1027
1028            if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1029            {
1030               line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1031
1032               if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1033               {
1034                  smsvdp->collision_buffer[pixel_plot_x] = 1;
1035               }
1036               else
1037               {
1038                  if (!sprite_col_occurred)
1039                  {
1040                     sprite_col_occurred = 1;
1041                     sprite_col_x = pixel_plot_x;
1042                  }
1043               }
1044            }
1045         }
1046      }
1047
1048      if (smsvdp->reg[0x01] & 0x02)
1049      {
1050         sprite_tile_selected += 2;
1051         pattern = sprite_pattern_table[sprite_tile_selected * 8 + sprite_line];
1052         sprite_x += (smsvdp->reg[0x01] & 0x01 ? 16 : 8);
1053
1054         for (pixel_x = 0; pixel_x < 8; pixel_x++)
1055         {
1056            if (smsvdp->reg[0x01] & 0x01)
1057            {
1058               pixel_plot_x = sprite_x + pixel_x * 2;
1059
1060               if (pixel_plot_x < 0 || pixel_plot_x > 255)
1061               {
1062                  continue;
1063               }
1064
1065               if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1066               {
1067                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1068
1069                  if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1070                  {
1071                     smsvdp->collision_buffer[pixel_plot_x] = 1;
1072                  }
1073                  else
1074                  {
1075                     if (!sprite_col_occurred)
1076                     {
1077                        sprite_col_occurred = 1;
1078                        sprite_col_x = pixel_plot_x;
1079                     }
1080                  }
1081
1082                  line_buffer[pixel_plot_x+1] = smsvdp->current_palette[pen_selected];
1083
1084                  if (smsvdp->collision_buffer[pixel_plot_x + 1] != 1)
1085                  {
1086                     smsvdp->collision_buffer[pixel_plot_x + 1] = 1;
1087                  }
1088                  else
1089                  {
1090                     if (!sprite_col_occurred)
1091                     {
1092                        sprite_col_occurred = 1;
1093                        sprite_col_x = pixel_plot_x;
1094                     }
1095                  }
1096               }
1097            }
1098            else
1099            {
1100               pixel_plot_x = sprite_x + pixel_x;
1101
1102               if (pixel_plot_x < 0 || pixel_plot_x > 255)
1103               {
1104                  continue;
1105               }
1106
1107               if (pen_selected && (pattern & (1 << (7 - pixel_x))))
1108               {
1109                  line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1110
1111                  if (smsvdp->collision_buffer[pixel_plot_x] != 1)
1112                  {
1113                     smsvdp->collision_buffer[pixel_plot_x] = 1;
1114                  }
1115                  else
1116                  {
1117                     if (!sprite_col_occurred)
1118                     {
1119                        sprite_col_occurred = 1;
1120                        sprite_col_x = pixel_plot_x;
1121                     }
1122                  }
1123               }
1124            }
1125         }
1126      }
1127      if (sprite_col_occurred)
1128         machine.scheduler().timer_set(machine.primary_screen->time_until_pos(pixel_plot_y + line, SPRCOL_BASEHPOS + sprite_col_x), FUNC(smsvdp_set_status), (int)STATUS_SPRCOL, smsvdp);
1129   }
1130}
1131
1132
1133static void sms_refresh_line_mode2( smsvdp_t *smsvdp, int *line_buffer, int line )
1134{
1135   int tile_column;
1136   int pixel_x, pixel_plot_x;
1137   UINT8 *name_table, *color_table, *pattern_table;
1138   int pattern_mask, color_mask, pattern_offset;
1139
1140   /* Draw background layer */
1141   name_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x02] & 0x0f) << 10) + ((line >> 3) * 32);
1142   color_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x03] & 0x80) << 6);
1143   color_mask = ((smsvdp->reg[0x03] & 0x7f) << 3) | 0x07;
1144   pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x04] & 0x04) << 11);
1145   pattern_mask = ((smsvdp->reg[0x04] & 0x03) << 8) | 0xff;
1146   pattern_offset = (line & 0xc0) << 2;
1147
1148   for (tile_column = 0; tile_column < 32; tile_column++)
1149   {
1150      UINT8 pattern;
1151      UINT8 colors;
1152
1153      pattern = pattern_table[(((pattern_offset + name_table[tile_column]) & pattern_mask) * 8) + (line & 0x07)];
1154      colors = color_table[(((pattern_offset + name_table[tile_column]) & color_mask) * 8) + (line & 0x07)];
1155
1156      for (pixel_x = 0; pixel_x < 8; pixel_x++)
1157      {
1158         UINT8 pen_selected;
1159
1160         if (pattern & (1 << (7 - pixel_x)))
1161         {
1162            pen_selected = colors >> 4;
1163         }
1164         else
1165         {
1166            pen_selected = colors & 0x0f;
1167         }
1168
1169         if (!pen_selected)
1170            pen_selected = BACKDROP_COLOR;
1171
1172         pixel_plot_x = (tile_column << 3) + pixel_x;
1173
1174         if (IS_GAMEGEAR_VDP)
1175            pen_selected |= 0x10;
1176
1177         line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1178      }
1179   }
1180}
1181
1182
1183static void sms_refresh_line_mode0( smsvdp_t *smsvdp, int *line_buffer, int line)
1184{
1185   int tile_column;
1186   int pixel_x, pixel_plot_x;
1187   UINT8 *name_table, *color_table, *pattern_table;
1188
1189   /* Draw background layer */
1190   name_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x02] & 0x0f) << 10) + ((line >> 3) * 32);
1191   color_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x03] << 6) & (VRAM_SIZE - 1));
1192   pattern_table = smsvdp->VRAM->base() + ((smsvdp->reg[0x04] << 11) & (VRAM_SIZE - 1));
1193
1194   for (tile_column = 0; tile_column < 32; tile_column++)
1195   {
1196      UINT8 pattern;
1197      UINT8 colors;
1198
1199      pattern = pattern_table[(name_table[tile_column] * 8) + (line & 0x07)];
1200      colors = color_table[name_table[tile_column] >> 3];
1201
1202      for (pixel_x = 0; pixel_x < 8; pixel_x++)
1203      {
1204         int pen_selected;
1205
1206         if (pattern & (1 << (7 - pixel_x)))
1207            pen_selected = colors >> 4;
1208         else
1209            pen_selected = colors & 0x0f;
1210
1211         if (IS_GAMEGEAR_VDP)
1212            pen_selected |= 0x10;
1213
1214         pixel_plot_x = (tile_column << 3) + pixel_x;
1215         line_buffer[pixel_plot_x] = smsvdp->current_palette[pen_selected];
1216      }
1217   }
1218}
1219
1220
1221static void sms_refresh_line( running_machine &machine, smsvdp_t *smsvdp, bitmap_t *bitmap, int pixel_offset_x, int pixel_plot_y, int line )
1222{
1223   int x;
1224   int *blitline_buffer = smsvdp->line_buffer;
1225   int priority_selected[256];
1226
1227   switch( smsvdp->vdp_mode )
1228   {
1229   case 0:
1230      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1231         sms_refresh_line_mode0(smsvdp, blitline_buffer, line);
1232      sms_refresh_tms9918_sprites(machine, smsvdp, blitline_buffer, pixel_plot_y, line);
1233      break;
1234
1235   case 2:
1236      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1237         sms_refresh_line_mode2(smsvdp, blitline_buffer, line);
1238      sms_refresh_tms9918_sprites(machine, smsvdp, blitline_buffer, pixel_plot_y, line);
1239      break;
1240
1241   case 4:
1242   default:
1243      memset(priority_selected, 0, sizeof(priority_selected));
1244      if (line >= 0 && line < smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1245         sms_refresh_line_mode4(smsvdp, blitline_buffer, priority_selected, line);
1246      sms_refresh_mode4_sprites(machine, smsvdp, blitline_buffer, priority_selected, pixel_plot_y, line);
1247      break;
1248   }
1249
1250   /* Check if display is disabled or we're below/above active area */
1251   if (!(smsvdp->reg[0x01] & 0x40) || line < 0 || line >= smsvdp->sms_frame_timing[ACTIVE_DISPLAY_V])
1252   {
1253      for (x = 0; x < 256; x++)
1254      {
1255         blitline_buffer[x] = smsvdp->current_palette[BACKDROP_COLOR];
1256      }
1257   }
1258
1259   if (IS_GAMEGEAR_VDP && smsvdp->gg_sms_mode)
1260   {
1261      int *combineline_buffer = smsvdp->line_buffer + ((line & 0x03) + 1) * 256;
1262      int plot_x = 48;
1263
1264      /* Do horizontal scaling */
1265      for (x = 8; x < 248;)
1266      {
1267         int combined;
1268
1269         /* Take red and green from first pixel, and blue from second pixel */
1270         combined = (blitline_buffer[x] & 0x00ff) | (blitline_buffer[x + 1] & 0x0f00);
1271         combineline_buffer[plot_x] = combined;
1272
1273         /* Take red from second pixel, and green and blue from third pixel */
1274         combined = (blitline_buffer[x + 1] & 0x000f) | (blitline_buffer[x + 2] & 0x0ff0);
1275         combineline_buffer[plot_x + 1] = combined;
1276         x += 3;
1277         plot_x += 2;
1278      }
1279
1280      /* Do vertical scaling for a screen with 192 or 224 lines
1281           Lines 0-2 and 221-223 have no effect on the output on the GG screen.
1282           We will calculate the gamegear lines as follows:
1283           GG_0 = 1/6 * SMS_3 + 1/3 * SMS_4 + 1/3 * SMS_5 + 1/6 * SMS_6
1284           GG_1 = 1/6 * SMS_4 + 1/3 * SMS_5 + 1/3 * SMS_6 + 1/6 * SMS_7
1285           GG_2 = 1/6 * SMS_6 + 1/3 * SMS_7 + 1/3 * SMS_8 + 1/6 * SMS_9
1286           GG_3 = 1/6 * SMS_7 + 1/3 * SMS_8 + 1/3 * SMS_9 + 1/6 * SMS_10
1287           GG_4 = 1/6 * SMS_9 + 1/3 * SMS_10 + 1/3 * SMS_11 + 1/6 * SMS_12
1288           .....
1289           GG_142 = 1/6 * SMS_216 + 1/3 * SMS_217 + 1/3 * SMS_218 + 1/6 * SMS_219
1290           GG_143 = 1/6 * SMS_217 + 1/3 * SMS_218 + 1/3 * SMS_219 + 1/6 * SMS_220
1291        */
1292      {
1293         int gg_line;
1294         int my_line = pixel_plot_y + line - (TBORDER_START + NTSC_224_TBORDER_Y_PIXELS);
1295         int *line1, *line2, *line3, *line4;
1296
1297         /* First make sure there's enough data to draw anything */
1298         /* We need one more line of data if we're on line 8, 11, 14, 17, etc */
1299         if (my_line < 6 || my_line > 220 || ((my_line - 8) % 3 == 0))
1300         {
1301            return;
1302         }
1303
1304         gg_line = ((my_line - 6) / 3) * 2;
1305
1306         /* If we're on SMS line 7, 10, 13, etc we're on an odd GG line */
1307         if (my_line % 3)
1308         {
1309            gg_line++;
1310         }
1311
1312         /* Calculate the line we will be drawing on */
1313         pixel_plot_y = TBORDER_START + NTSC_192_TBORDER_Y_PIXELS + 24 + gg_line;
1314
1315         /* Setup our source lines */
1316         line1 = smsvdp->line_buffer + (((my_line - 3) & 0x03) + 1) * 256;
1317         line2 = smsvdp->line_buffer + (((my_line - 2) & 0x03) + 1) * 256;
1318         line3 = smsvdp->line_buffer + (((my_line - 1) & 0x03) + 1) * 256;
1319         line4 = smsvdp->line_buffer + (((my_line - 0) & 0x03) + 1) * 256;
1320
1321         for (x = 0 + 48; x < 160 + 48; x++)
1322         {
1323            rgb_t   c1 = machine.pens[line1[x]];
1324            rgb_t   c2 = machine.pens[line2[x]];
1325            rgb_t   c3 = machine.pens[line3[x]];
1326            rgb_t   c4 = machine.pens[line4[x]];
1327            *BITMAP_ADDR32(bitmap, pixel_plot_y, pixel_offset_x + x) =
1328               MAKE_RGB((RGB_RED(c1) / 6 + RGB_RED(c2) / 3 + RGB_RED(c3) / 3 + RGB_RED(c4) / 6 ),
1329                  (RGB_GREEN(c1) / 6 + RGB_GREEN(c2) / 3 + RGB_GREEN(c3) / 3 + RGB_GREEN(c4) / 6 ),
1330                  (RGB_BLUE(c1) / 6 + RGB_BLUE(c2) / 3 + RGB_BLUE(c3) / 3 + RGB_BLUE(c4) / 6 ) );
1331         }
1332         return;
1333      }
1334      blitline_buffer = combineline_buffer;
1335   }
1336
1337   for (x = 0; x < 256; x++)
1338   {
1339      *BITMAP_ADDR32(bitmap, pixel_plot_y + line, pixel_offset_x + x) = machine.pens[blitline_buffer[x]];
1340   }
1341}
1342
1343
1344// This is only used by Light Phaser. Should it be moved elsewhere?
1345int sms_vdp_check_brightness(device_t *device, int x, int y)
1346{
1347   /* brightness of the lightgray color in the frame drawn by Light Phaser games */
1348   const UINT8 sensor_min_brightness = 0x7f;
1349
1350   /* TODO: Check how Light Phaser behaves for border areas. For Gangster Town, should */
1351   /* a shot at right border (HC~=0x90) really appear at active scr, near to left border? */
1352   if (x < LBORDER_START + LBORDER_X_PIXELS || x >= LBORDER_START + LBORDER_X_PIXELS + 256)
1353      return 0;
1354
1355   smsvdp_t *smsvdp = get_safe_token(device);
1356   rgb_t color = *BITMAP_ADDR32(smsvdp->tmpbitmap, y, x);
1357
1358   /* reference: http://www.w3.org/TR/AERT#color-contrast */
1359   UINT8 brightness = (RGB_RED(color) * 0.299) + (RGB_GREEN(color) * 0.587) + (RGB_BLUE(color) * 0.114);
1360   //printf ("color brightness: %2X for x %d y %d\n", brightness, x, y);
1361
1362   return (brightness >= sensor_min_brightness) ? 1 : 0;
1363}
1364
1365
1366static void sms_update_palette( smsvdp_t *smsvdp )
1367{
1368   int i;
1369
1370   /* Exit if palette is has no changes */
1371   if (smsvdp->cram_dirty == 0)
1372   {
1373      return;
1374   }
1375   smsvdp->cram_dirty = 0;
1376
1377   if (smsvdp->vdp_mode != 4 && ! IS_GAMEGEAR_VDP)
1378   {
1379      for(i = 0; i < 16; i++)
1380      {
1381         smsvdp->current_palette[i] = 64 + i;
1382      }
1383      return;
1384   }
1385
1386   if (IS_GAMEGEAR_VDP)
1387   {
1388      if (smsvdp->gg_sms_mode)
1389      {
1390         for (i = 0; i < 32; i++)
1391         {
1392            smsvdp->current_palette[i] = ((smsvdp->CRAM->u8(i) & 0x30) << 6) | ((smsvdp->CRAM->u8(i) & 0x0c ) << 4) | ((smsvdp->CRAM->u8(i) & 0x03) << 2);
1393         }
1394      }
1395      else
1396      {
1397         for (i = 0; i < 32; i++)
1398         {
1399            smsvdp->current_palette[i] = ((smsvdp->CRAM->u8(i * 2 + 1) << 8) | smsvdp->CRAM->u8(i * 2)) & 0x0fff;
1400         }
1401      }
1402   }
1403   else
1404   {
1405      for (i = 0; i < 32; i++)
1406      {
1407         smsvdp->current_palette[i] = smsvdp->CRAM->u8(i) & 0x3f;
1408      }
1409   }
1410}
1411
1412
1413UINT32 sms_vdp_update( device_t *device, bitmap_t *bitmap, const rectangle *cliprect )
1414{
1415   smsvdp_t *smsvdp = get_safe_token(device);
1416   copybitmap(bitmap, smsvdp->tmpbitmap, 0, 0, 0, 0, cliprect);
1417   return 0;
1418}
1419
1420
1421/*****************************************************************************
1422    DEVICE INTERFACE
1423*****************************************************************************/
1424
1425static DEVICE_START( smsvdp )
1426{
1427   smsvdp_t *smsvdp = get_safe_token(device);
1428   const smsvdp_interface *intf = get_interface(device);
1429
1430   screen_device *screen = device->machine().first_screen();
1431   int width = screen->width();
1432   int height = screen->height();
1433
1434   smsvdp->features = intf->model;
1435   smsvdp->int_callback = intf->int_callback;
1436   smsvdp->pause_callback = intf->pause_callback;
1437
1438   /* Allocate video RAM */
1439   smsvdp->VRAM = device->machine().region_alloc("vdp_vram", VRAM_SIZE, 1, ENDIANNESS_LITTLE);
1440   smsvdp->CRAM = device->machine().region_alloc("vdp_cram", MAX_CRAM_SIZE, 1, ENDIANNESS_LITTLE);
1441   smsvdp->line_buffer = auto_alloc_array(device->machine(), int, 256 * 5);
1442
1443   smsvdp->collision_buffer = auto_alloc_array(device->machine(), UINT8, SMS_X_PIXELS);
1444   smsvdp->sms_frame_timing = auto_alloc_array(device->machine(), UINT8, 7);
1445
1446   /* Make temp bitmap for rendering */
1447   smsvdp->tmpbitmap = auto_bitmap_alloc(device->machine(), width, height, BITMAP_FORMAT_INDEXED32);
1448
1449   smsvdp->smsvdp_display_timer = device->machine().scheduler().timer_alloc(FUNC(smsvdp_display_callback), smsvdp);
1450   smsvdp->smsvdp_display_timer->adjust(screen->time_until_pos(0, DISPLAY_CB_HPOS), 0, screen->scan_period());
1451
1452   device->save_item(NAME(smsvdp->status));
1453   device->save_item(NAME(smsvdp->reg9copy));
1454   device->save_item(NAME(smsvdp->addrmode));
1455   device->save_item(NAME(smsvdp->addr));
1456   device->save_item(NAME(smsvdp->cram_mask));
1457   device->save_item(NAME(smsvdp->cram_dirty));
1458   device->save_item(NAME(smsvdp->pending));
1459   device->save_item(NAME(smsvdp->buffer));
1460   device->save_item(NAME(smsvdp->gg_sms_mode));
1461   device->save_item(NAME(smsvdp->irq_state));
1462   device->save_item(NAME(smsvdp->vdp_mode));
1463   device->save_item(NAME(smsvdp->y_pixels));
1464   device->save_item(NAME(smsvdp->line_counter));
1465   device->save_item(NAME(smsvdp->hcounter));
1466   device->save_item(NAME(smsvdp->reg));
1467   device->save_item(NAME(smsvdp->current_palette));
1468   device->save_pointer(NAME(smsvdp->line_buffer), 256 * 5);
1469   device->save_pointer(NAME(smsvdp->collision_buffer), SMS_X_PIXELS);
1470   device->save_item(NAME(*smsvdp->tmpbitmap));
1471}
1472
1473static DEVICE_RESET( smsvdp )
1474{
1475   smsvdp_t *smsvdp = get_safe_token(device);
1476   int i;
1477
1478   /* Most register are 0x00 at power-up */
1479   for (i = 0; i < NUM_OF_REGISTER; i++)
1480      smsvdp->reg[i] = 0x00;
1481
1482   smsvdp->reg[0x02] = 0x0e;
1483   smsvdp->reg[0x0a] = 0xff;
1484
1485   smsvdp->status = 0;
1486   smsvdp->reg9copy = 0;
1487   smsvdp->addrmode = 0;
1488   smsvdp->addr = 0;
1489   smsvdp->gg_sms_mode = 0;
1490   smsvdp->cram_mask = (IS_GAMEGEAR_VDP && !smsvdp->gg_sms_mode) ? (GG_CRAM_SIZE - 1) : (SMS_CRAM_SIZE - 1);
1491   smsvdp->cram_dirty = 1;
1492   smsvdp->pending = 0;
1493   smsvdp->buffer = 0;
1494   smsvdp->irq_state = 0;
1495   smsvdp->line_counter = 0;
1496   smsvdp->hcounter = 0;
1497
1498   for (i = 0; i < 0x20; i++)
1499      smsvdp->current_palette[i] = 0;
1500
1501   set_display_settings(device);
1502
1503   /* Clear RAM */
1504   memset(smsvdp->VRAM->base(), 0, VRAM_SIZE);
1505   memset(smsvdp->CRAM->base(), 0, MAX_CRAM_SIZE);
1506   memset(smsvdp->line_buffer, 0, 256 * 5 * sizeof(int));
1507}
1508
1509DEVICE_GET_INFO( smsvdp )
1510{
1511   switch (state)
1512   {
1513      /* --- the following bits of info are returned as 64-bit signed integers --- */
1514      case DEVINFO_INT_TOKEN_BYTES:         info->i = sizeof(smsvdp_t);               break;
1515
1516      /* --- the following bits of info are returned as pointers to data or functions --- */
1517      case DEVINFO_FCT_START:               info->start = DEVICE_START_NAME(smsvdp);      break;
1518      case DEVINFO_FCT_STOP:               /* Nothing */                           break;
1519      case DEVINFO_FCT_RESET:               info->reset = DEVICE_RESET_NAME(smsvdp);      break;
1520
1521      /* --- the following bits of info are returned as NULL-terminated strings --- */
1522      case DEVINFO_STR_NAME:               strcpy(info->s, "Sega Master SYstem / Game Gear VDP");            break;
1523      case DEVINFO_STR_FAMILY:            strcpy(info->s, "Sega MS VDP");               break;
1524      case DEVINFO_STR_VERSION:            strcpy(info->s, "1.0");                     break;
1525      case DEVINFO_STR_SOURCE_FILE:         strcpy(info->s, __FILE__);                  break;
1526      case DEVINFO_STR_CREDITS:            strcpy(info->s, "Copyright MAME / MESS Team");         break;
1527   }
1528}
1529
1530DEFINE_LEGACY_DEVICE(SMSVDP, smsvdp);
src/mess/video/smsvdp.h
r11450r11451
1/*************************************************************************
2
3    smsvdp.h
4
5    Implementation of Sega VDP chip used in Master System and Game Gear
6
7**************************************************************************/
8
9#ifndef __SMSVDP_H__
10#define __SMSVDP_H__
11
12#include "devcb.h"
13
14
15/***************************************************************************
16    CONSTANTS
17***************************************************************************/
18
19
20#define MODEL_315_5124         0x0001
21#define MODEL_315_5246         0x0002
22#define MODEL_315_5378         0x0004
23
24#define SMS_X_PIXELS         342      /* 342 pixels */
25#define NTSC_Y_PIXELS         262      /* 262 lines */
26#define PAL_Y_PIXELS         313      /* 313 lines */
27#define LBORDER_START         (1 + 2 + 14 + 8)
28#define LBORDER_X_PIXELS      (0x0d)      /* 13 pixels */
29#define RBORDER_X_PIXELS      (0x0f)      /* 15 pixels */
30#define TBORDER_START         (3 + 13)
31#define NTSC_192_TBORDER_Y_PIXELS   (0x1b)      /* 27 lines */
32#define NTSC_192_BBORDER_Y_PIXELS   (0x18)      /* 24 lines */
33#define NTSC_224_TBORDER_Y_PIXELS   (0x0b)      /* 11 lines */
34#define NTSC_224_BBORDER_Y_PIXELS   (0x08)      /* 8 lines */
35#define PAL_192_TBORDER_Y_PIXELS   (0x36)      /* 54 lines */
36#define PAL_192_BBORDER_Y_PIXELS   (0x30)      /* 48 lines */
37#define PAL_224_TBORDER_Y_PIXELS   (0x26)      /* 38 lines */
38#define PAL_224_BBORDER_Y_PIXELS   (0x20)      /* 32 lines */
39#define PAL_240_TBORDER_Y_PIXELS   (0x1e)      /* 30 lines */
40#define PAL_240_BBORDER_Y_PIXELS   (0x18)      /* 24 lines */
41
42
43/***************************************************************************
44    TYPE DEFINITIONS
45***************************************************************************/
46
47typedef void (*smsvdp_int_cb)( running_machine &machine, int state );
48typedef void (*smsvdp_pause_cb)( running_machine &machine );
49
50typedef struct _smsvdp_interface smsvdp_interface;
51struct _smsvdp_interface
52{
53   UINT32             model;                /* Select model/features for the emulation */
54   smsvdp_int_cb      int_callback;         /* Interrupt callback function */
55   smsvdp_pause_cb    pause_callback;       /* Pause callback function */
56};
57
58/***************************************************************************
59    DEVICE CONFIGURATION MACROS
60***************************************************************************/
61
62DECLARE_LEGACY_DEVICE(SMSVDP, smsvdp);
63
64#define MCFG_SMSVDP_ADD(_tag, _interface) \
65   MCFG_DEVICE_ADD(_tag, SMSVDP, 0) \
66   MCFG_DEVICE_CONFIG(_interface)
67
68
69/***************************************************************************
70    DEVICE I/O FUNCTIONS
71***************************************************************************/
72
73/* prototypes */
74
75UINT32 sms_vdp_update( device_t *device, bitmap_t *bitmap, const rectangle *cliprect );
76READ8_DEVICE_HANDLER( sms_vdp_vcount_r );
77READ8_DEVICE_HANDLER( sms_vdp_hcount_latch_r );
78WRITE8_DEVICE_HANDLER( sms_vdp_hcount_latch_w );
79READ8_DEVICE_HANDLER( sms_vdp_data_r );
80WRITE8_DEVICE_HANDLER( sms_vdp_data_w );
81READ8_DEVICE_HANDLER( sms_vdp_ctrl_r );
82WRITE8_DEVICE_HANDLER( sms_vdp_ctrl_w );
83void sms_vdp_set_ggsmsmode( device_t *device, int mode );
84int sms_vdp_check_brightness( device_t *device, int x, int y );
85
86#endif /* __SMSVDP_H__ */
src/mess/formats/basicdsk.c
r11450r11451
1/*********************************************************************
2
3    formats/basicdsk.c
4
5    Floppy format code for basic disks
6
7*********************************************************************/
8
9#include <stdlib.h>
10#include <string.h>
11#include <assert.h>
12
13#include "basicdsk.h"
14
15static floperr_t basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen);
16static floperr_t basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam);
17static floperr_t basicdsk_read_indexed_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen);
18static floperr_t basicdsk_write_indexed_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam);
19static floperr_t basicdsk_get_sector_length(floppy_image *floppy, int head, int track, int sector, UINT32 *sector_length);
20static floperr_t basicdsk_get_indexed_sector_info(floppy_image *floppy, int head, int track, int sector_index, int *cylinder, int *side, int *sector, UINT32 *sector_length, unsigned long *flags);
21static int basicdsk_get_heads_per_disk(floppy_image *floppy);
22static int basicdsk_get_tracks_per_disk(floppy_image *floppy);
23static floperr_t basicdsk_format_track(floppy_image *floppy, int head, int track, option_resolution *params);
24
25
26
27#define BASICDSK_TAG   "basicdsktag"
28
29struct basicdsk_tag
30{
31   struct basicdsk_geometry geometry;
32};
33
34
35
36/********************************************************************/
37
38static const struct basicdsk_geometry *get_geometry(floppy_image *floppy)
39{
40   const struct basicdsk_tag *tag;
41   tag = (const basicdsk_tag *)floppy_tag(floppy);
42   return &tag->geometry;
43}
44
45
46
47floperr_t basicdsk_construct(floppy_image *floppy, const struct basicdsk_geometry *geometry)
48{
49   struct basicdsk_tag *tag;
50   struct FloppyCallbacks *format;
51
52   assert(geometry->heads);
53   assert(geometry->tracks);
54   assert(geometry->sectors);
55
56   tag = (struct basicdsk_tag *) floppy_create_tag(floppy, sizeof(struct basicdsk_tag));
57   if (!tag)
58      return FLOPPY_ERROR_OUTOFMEMORY;
59   tag->geometry = *geometry;
60
61   /* set up format callbacks */
62   format = floppy_callbacks(floppy);
63   format->read_sector = basicdsk_read_sector;
64   format->write_sector = basicdsk_write_sector;
65   format->read_indexed_sector = basicdsk_read_indexed_sector;
66   format->write_indexed_sector = basicdsk_write_indexed_sector;
67   format->get_sector_length = basicdsk_get_sector_length;
68   format->get_heads_per_disk = basicdsk_get_heads_per_disk;
69   format->get_tracks_per_disk = basicdsk_get_tracks_per_disk;
70   format->get_indexed_sector_info = basicdsk_get_indexed_sector_info;
71   format->format_track = basicdsk_format_track;
72
73   return FLOPPY_ERROR_SUCCESS;
74}
75
76
77
78static floperr_t get_offset(floppy_image *floppy, int head, int track, int sector, int sector_is_index, UINT64 *offset)
79{
80   const struct basicdsk_geometry *geom;
81   UINT64 offs;
82
83   geom = get_geometry(floppy);
84
85   /* translate the sector to a raw sector */
86   if (!sector_is_index)
87   {
88      sector -= geom->first_sector_id;
89   }
90
91   if (geom->translate_sector)
92      sector = geom->translate_sector(floppy, sector);
93
94   /* check to see if we are out of range */
95   if ((head < 0) || (head >= geom->heads) || (track < 0) || (track >= geom->tracks)
96         || (sector < 0) || (sector >= geom->sectors))
97      return FLOPPY_ERROR_SEEKERROR;
98
99   if (geom->translate_offset)
100      offs = geom->translate_offset(floppy, geom, track, head, sector);
101   else
102   {
103      offs = 0;
104      offs += track;
105      offs *= geom->heads;
106      offs += head;
107      offs *= geom->sectors;
108      offs += sector;
109   }
110   offs *= geom->sector_length;
111   offs += geom->offset;
112
113   if (offset)
114      *offset = offs;
115   return FLOPPY_ERROR_SUCCESS;
116}
117
118
119
120static int internal_basicdsk_translate_sector_interleave(floppy_image *floppy, int sector)
121{
122   const struct basicdsk_geometry *geom = get_geometry(floppy);
123   if (sector >= geom->sectors)
124      return sector;
125   return geom->sector_map[sector];
126}
127
128
129
130static floperr_t internal_basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, int sector_is_index, void *buffer, size_t buflen)
131{
132   UINT64 offset;
133   floperr_t err;
134
135   err = get_offset(floppy, head, track, sector, sector_is_index, &offset);
136   if (err)
137      return err;
138   floppy_image_read(floppy, buffer, offset, buflen);
139   return FLOPPY_ERROR_SUCCESS;
140}
141
142
143
144static floperr_t internal_basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, int sector_is_index, const void *buffer, size_t buflen, int ddam)
145{
146   UINT64 offset;
147   floperr_t err;
148
149   err = get_offset(floppy, head, track, sector, sector_is_index, &offset);
150   if (err)
151      return err;
152
153   floppy_image_write(floppy, buffer, offset, buflen);
154   return FLOPPY_ERROR_SUCCESS;
155}
156
157
158
159static floperr_t basicdsk_read_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen)
160{
161   return internal_basicdsk_read_sector(floppy, head, track, sector, FALSE, buffer, buflen);
162}
163
164static floperr_t basicdsk_write_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam)
165{
166   return internal_basicdsk_write_sector(floppy, head, track, sector, FALSE, buffer, buflen, ddam);
167}
168
169static floperr_t basicdsk_read_indexed_sector(floppy_image *floppy, int head, int track, int sector, void *buffer, size_t buflen)
170{
171   return internal_basicdsk_read_sector(floppy, head, track, sector, TRUE, buffer, buflen);
172}
173
174static floperr_t basicdsk_write_indexed_sector(floppy_image *floppy, int head, int track, int sector, const void *buffer, size_t buflen, int ddam)
175{
176   return internal_basicdsk_write_sector(floppy, head, track, sector, TRUE, buffer, buflen, ddam);
177}
178
179
180
181static floperr_t basicdsk_format_track(floppy_image *floppy, int head, int track, option_resolution *params)
182{
183   floperr_t err = FLOPPY_ERROR_SUCCESS;
184   UINT8 local_buffer[512];
185   void *alloc_buffer = NULL;
186   void *buffer;
187   UINT32 sector_length;
188   int sector;
189   const struct basicdsk_geometry *geometry;
190
191   geometry = get_geometry(floppy);
192
193   sector_length = geometry->sector_length;
194
195   if (sector_length > sizeof(local_buffer))
196   {
197      alloc_buffer = malloc(sector_length);
198      if (!alloc_buffer)
199      {
200         err = FLOPPY_ERROR_OUTOFMEMORY;
201         goto done;
202      }
203      buffer = alloc_buffer;
204   }
205   else
206   {
207      alloc_buffer = NULL;
208      buffer = local_buffer;
209   }
210
211   memset(buffer, floppy_get_filler(floppy), sector_length);
212
213   for (sector = 0; sector < geometry->sectors; sector++)
214   {
215      err = basicdsk_write_sector(floppy, head, track, sector + geometry->first_sector_id, buffer, sector_length, 0);
216      if (err)
217         goto done;
218   }
219
220done:
221   if (alloc_buffer)
222      free(alloc_buffer);
223   return err;
224}
225
226
227
228static int basicdsk_get_heads_per_disk(floppy_image *floppy)
229{
230   return get_geometry(floppy)->heads;
231}
232
233
234
235static int basicdsk_get_tracks_per_disk(floppy_image *floppy)
236{
237   return get_geometry(floppy)->tracks;
238}
239
240
241
242static floperr_t basicdsk_get_sector_length(floppy_image *floppy, int head, int track, int sector, UINT32 *sector_length)
243{
244   floperr_t err;
245
246   err = get_offset(floppy, head, track, sector, FALSE, NULL);
247   if (err)
248      return err;
249
250   if (sector_length)
251      *sector_length = get_geometry(floppy)->sector_length;
252   return FLOPPY_ERROR_SUCCESS;
253}
254
255
256
257static floperr_t basicdsk_get_indexed_sector_info(floppy_image *floppy, int head, int track, int sector_index, int *cylinder, int *side, int *sector, UINT32 *sector_length, unsigned long *flags)
258{
259   const struct basicdsk_geometry *geom = get_geometry(floppy);
260
261   if (geom->translate_sector)
262      sector_index = geom->translate_sector(floppy, sector_index);
263
264   sector_index += geom->first_sector_id;
265
266   if (cylinder)
267      *cylinder = track;
268   if (side)
269      *side = head;
270   if (sector)
271      *sector = sector_index;
272   if (flags) {
273      /* TODO: read DAM or DDAM and determine flags */
274      *flags = 0;
275      if (geom->get_ddam)
276         *flags = geom->get_ddam(floppy, geom, track, head, sector_index);
277   }
278   return basicdsk_get_sector_length(floppy, head, track, sector_index, sector_length);
279}
280
281
282
283/********************************************************************
284 * Generic Basicdsk Constructors
285 ********************************************************************/
286
287static void basicdsk_default_geometry(const struct FloppyFormat *format, struct basicdsk_geometry *geometry)
288{
289   optreserr_t err;
290   int sector_length;
291   memset(geometry, 0, sizeof(*geometry));
292
293   err = option_resolution_getdefault(format->param_guidelines, PARAM_HEADS,         &geometry->heads);
294   assert(!err);
295   err = option_resolution_getdefault(format->param_guidelines, PARAM_TRACKS,         &geometry->tracks);
296   assert(!err);
297   err = option_resolution_getdefault(format->param_guidelines, PARAM_SECTORS,         &geometry->sectors);
298   assert(!err);
299   err = option_resolution_getdefault(format->param_guidelines, PARAM_FIRST_SECTOR_ID,   &geometry->first_sector_id);
300   assert(!err);
301   err = option_resolution_getdefault(format->param_guidelines, PARAM_INTERLEAVE,      &geometry->interleave);
302   if (err!=0) {
303      geometry->interleave = 1;
304   }
305   err = option_resolution_getdefault(format->param_guidelines, PARAM_SECTOR_LENGTH,   &sector_length);
306   assert(!err);
307   geometry->sector_length = sector_length;
308
309   if (geometry->interleave > 1)
310   {
311      int sector = 0;
312
313      for (int i = 0; i < geometry->sectors; i++)
314      {
315         geometry->sector_map[i] = sector;
316
317         sector += geometry->interleave;
318
319         if (sector >= geometry->sectors)
320            sector -= geometry->sectors;
321      }
322
323      geometry->translate_sector = internal_basicdsk_translate_sector_interleave;
324   }
325}
326
327
328
329FLOPPY_CONSTRUCT(basicdsk_construct_default)
330{
331   struct basicdsk_geometry geometry;
332   basicdsk_default_geometry(format, &geometry);
333   return basicdsk_construct(floppy, &geometry);
334}
335
336
337
338FLOPPY_IDENTIFY(basicdsk_identify_default)
339{
340   UINT64 expected_size;
341   struct basicdsk_geometry geometry;
342
343   basicdsk_default_geometry(format, &geometry);
344
345   expected_size = geometry.sector_length;
346   expected_size *= geometry.heads;
347   expected_size *= geometry.tracks;
348   expected_size *= geometry.sectors;
349   *vote = (floppy_image_size(floppy) == expected_size) ? 100 : 0;
350   return FLOPPY_ERROR_SUCCESS;
351}
352
src/mess/formats/basicdsk.h
r11450r11451
1/*********************************************************************
2
3    formats/basicdsk.h
4
5    Floppy format code for basic disks
6
7*********************************************************************/
8
9#ifndef BASICDSK_H
10#define BASICDSK_H
11
12#include "imagedev/flopimg.h"
13
14struct basicdsk_geometry
15{
16   int heads;
17   int tracks;
18   int sectors;
19   int first_sector_id;
20   int interleave;
21   int sector_map[256];
22   UINT32 sector_length;
23   UINT64 offset;
24
25   int (*translate_sector)(floppy_image *floppy, int sector);
26   UINT64 (*translate_offset)(floppy_image *floppy, const struct basicdsk_geometry *geom, int track, int head, int sector);
27   UINT64 (*get_ddam)(floppy_image *floppy, const struct basicdsk_geometry *geom, int track, int head, int sector);
28};
29
30floperr_t basicdsk_construct(floppy_image *floppy, const struct basicdsk_geometry *geometry);
31
32FLOPPY_IDENTIFY(basicdsk_identify_default);
33FLOPPY_CONSTRUCT(basicdsk_construct_default);
34
35#endif /* BASICDSK_H */
src/mess/mess.mak
r11450r11451
495495   $(MAME_DRIVERS)/vectrex.o   \
496496   $(MAME_VIDEO)/vectrex.o      \
497497   $(MAME_MACHINE)/vectrex.o   \
498   $(MAME_VIDEO)/smsvdp.o       \
499   $(MAME_MACHINE)/segasms.o    \
500   $(MAME_DRIVERS)/segasms.o    \
501   $(MAME_DRIVERS)/sg1000.o    \
502   $(MAME_DRIVERS)/dc.o       \
503   $(MAME_MACHINE)/dccons.o    \
504   $(MAME_MACHINE)/gdrom.o    \
505   $(MAME_FORMATS)/basicdsk.o    \
498506
499507#-------------------------------------------------
500508# the following files are general components and
r11450r11451
512520   $(MESS_FORMATS)/d88_dsk.o   \
513521   $(MESS_FORMATS)/fdi_dsk.o   \
514522   $(MESS_DEVICES)/microdrv.o   \
515   $(MESS_FORMATS)/basicdsk.o   \
516523   $(MESS_FORMATS)/coco_cas.o   \
517524   $(MESS_FORMATS)/coco_dsk.o   \
518525   $(MESS_FORMATS)/pc_dsk.o   \
r11450r11451
522529   $(MESS_MACHINE)/8530scc.o   \
523530   $(MESS_MACHINE)/at45dbxx.o   \
524531   $(MESS_MACHINE)/ay31015.o   \
525   $(MESS_MACHINE)/ctronics.o   \
526532   $(MESS_MACHINE)/er59256.o   \
527533   $(MESS_MACHINE)/hd63450.o   \
528534   $(MESS_MACHINE)/i82371ab.o   \
r11450r11451
538544   $(MESS_MACHINE)/mc6854.o   \
539545   $(MESS_MACHINE)/mm58274c.o   \
540546   $(MESS_MACHINE)/mpc105.o   \
541   $(MESS_MACHINE)/msm8251.o   \
542547   $(MESS_MACHINE)/mos6530.o   \
543   $(MESS_MACHINE)/upd765.o   \
544548   $(MESS_MACHINE)/ncr5380.o   \
545549   $(MESS_MACHINE)/pc_lpt.o   \
546550   $(MESS_MACHINE)/pc_mouse.o   \
547551   $(MESS_MACHINE)/pcf8593.o   \
548552   $(MESS_MACHINE)/rs232.o      \
549553   $(MESS_MACHINE)/scsibus.o   \
550   $(MESS_MACHINE)/serial.o   \
551554   $(MESS_MACHINE)/smartmed.o   \
552555   $(MESS_MACHINE)/smc92x4.o   \
553556   $(MESS_MACHINE)/sst39vfx.o   \
r11450r11451
13851388
13861389$(MESSOBJ)/sega.a:            \
13871390   $(MAME_DRIVERS)/saturn.o   \
1388   $(MESS_VIDEO)/smsvdp.o      \
1389   $(MESS_MACHINE)/sms.o      \
1390   $(MESS_DRIVERS)/sms.o      \
1391   $(MESS_DRIVERS)/sg1000.o   \
1392   $(MESS_DRIVERS)/dc.o      \
1393   $(MESS_MACHINE)/dc.o      \
1394   $(MESS_MACHINE)/gdrom.o      \
13951391
13961392$(MESSOBJ)/sgi.a:            \
13971393   $(MESS_MACHINE)/sgi.o      \
r11450r11451
18861882$(MESS_DRIVERS)/sc2.o:      $(MESS_LAYOUT)/sc2.lh
18871883$(MESS_DRIVERS)/savia84.o:   $(MESS_LAYOUT)/savia84.lh
18881884$(MESS_DRIVERS)/selz80.o:   $(MESS_LAYOUT)/selz80.lh
1889$(MESS_DRIVERS)/sms.o:      $(MESS_LAYOUT)/sms1.lh
1885$(MAME_DRIVERS)/segasms.o:  $(MAME_LAYOUT)/sms1.lh
18901886$(MESS_DRIVERS)/stopthie.o:   $(MESS_LAYOUT)/stopthie.lh
18911887$(MESS_DRIVERS)/super80.o:   $(MESS_LAYOUT)/super80.lh
18921888$(MESS_DRIVERS)/supercon.o:   $(MESS_LAYOUT)/supercon.lh

Previous 15994 Revisions Next


© 1998-2018 The MESS Team