Show PCI info when reporting ATA controllers.
[seabios.git] / src / ata.c
1 // Low level ATA disk access
2 //
3 // Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
4 // Copyright (C) 2002  MandrakeSoft S.A.
5 //
6 // This file may be distributed under the terms of the GNU GPLv3 license.
7
8 #include "ata.h" // ATA_*
9 #include "types.h" // u8
10 #include "ioport.h" // inb
11 #include "util.h" // dprintf
12 #include "cmos.h" // inb_cmos
13 #include "pic.h" // unmask_pic2
14 #include "biosvar.h" // GET_EBDA
15 #include "pci.h" // pci_find_class
16 #include "pci_ids.h" // PCI_CLASS_STORAGE_OTHER
17 #include "pci_regs.h" // PCI_INTERRUPT_LINE
18
19 #define TIMEOUT 0
20 #define BSY 1
21 #define NOT_BSY 2
22 #define NOT_BSY_DRQ 3
23 #define NOT_BSY_NOT_DRQ 4
24 #define NOT_BSY_RDY 5
25
26 #define IDE_SECTOR_SIZE 512
27 #define CDROM_SECTOR_SIZE 2048
28
29 #define IDE_TIMEOUT 32000u //32 seconds max for IDE ops
30
31
32 /****************************************************************
33  * Helper functions
34  ****************************************************************/
35
36 // Wait for the specified ide state
37 static int
38 await_ide(u8 when_done, u16 base, u16 timeout)
39 {
40     u32 time=0, last=0;
41     for (;;) {
42         u8 status = inb(base+ATA_CB_STAT);
43         time++;
44         u8 result = 0;
45         if (when_done == BSY)
46             result = status & ATA_CB_STAT_BSY;
47         else if (when_done == NOT_BSY)
48             result = !(status & ATA_CB_STAT_BSY);
49         else if (when_done == NOT_BSY_DRQ)
50             result = !(status & ATA_CB_STAT_BSY) && (status & ATA_CB_STAT_DRQ);
51         else if (when_done == NOT_BSY_NOT_DRQ)
52             result = !(status & ATA_CB_STAT_BSY) && !(status & ATA_CB_STAT_DRQ);
53         else if (when_done == NOT_BSY_RDY)
54             result = !(status & ATA_CB_STAT_BSY) && (status & ATA_CB_STAT_RDY);
55
56         if (result)
57             return status;
58         // mod 2048 each 16 ms
59         if (time>>16 != last) {
60             last = time >>16;
61             dprintf(6, "await_ide: (TIMEOUT,BSY,!BSY,!BSY_DRQ"
62                     ",!BSY_!DRQ,!BSY_RDY) %d time= %d timeout= %d\n"
63                     , when_done, time>>11, timeout);
64         }
65         if (status & ATA_CB_STAT_ERR) {
66             dprintf(1, "await_ide: ERROR (TIMEOUT,BSY,!BSY,!BSY_DRQ"
67                     ",!BSY_!DRQ,!BSY_RDY) %d status=%x time= %d timeout= %d\n"
68                     , when_done, status, time>>11, timeout);
69             return -1;
70         }
71         if (timeout == 0 || (time>>11) > timeout)
72             break;
73     }
74     dprintf(1, "IDE time out\n");
75     return -2;
76 }
77
78 // Wait for ide state - pauses for one ata cycle first.
79 static __always_inline int
80 pause_await_ide(u8 when_done, u16 iobase1, u16 iobase2, u16 timeout)
81 {
82     // Wait one PIO transfer cycle.
83     inb(iobase2 + ATA_CB_ASTAT);
84
85     return await_ide(when_done, iobase1, timeout);
86 }
87
88 // Delay for x nanoseconds
89 static void
90 nsleep(u32 delay)
91 {
92     // XXX - how to implement ndelay?
93     while (delay--)
94         nop();
95 }
96
97 // Wait for ide state - pause for 400ns first.
98 static __always_inline int
99 ndelay_await_ide(u8 when_done, u16 iobase1, u16 timeout)
100 {
101     nsleep(400);
102     return await_ide(when_done, iobase1, timeout);
103 }
104
105 // Delay for x milliseconds
106 static void
107 msleep(u32 delay)
108 {
109     usleep(delay * 1000);
110 }
111
112 // Reset a drive
113 void
114 ata_reset(int driveid)
115 {
116     u8 channel = driveid / 2;
117     u8 slave = driveid % 2;
118     u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
119     u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
120
121     // Reset
122
123     // 8.2.1 (a) -- set SRST in DC
124     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN | ATA_CB_DC_SRST, iobase2+ATA_CB_DC);
125
126     // 8.2.1 (b) -- wait for BSY
127     int status = await_ide(BSY, iobase1, 20);
128     dprintf(6, "ata_reset(1) status=%x\n", status);
129
130     // 8.2.1 (f) -- clear SRST
131     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
132
133     // 8.2.1 (g) -- check for sc==sn==0x01
134     // select device
135     outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
136     msleep(50);
137     u8 sc = inb(iobase1+ATA_CB_SC);
138     u8 sn = inb(iobase1+ATA_CB_SN);
139
140     // For predetermined ATA drives - wait for ready.
141     if (sc==0x01 && sn==0x01) {
142         u8 type=GET_EBDA(ata.devices[driveid].type);
143         if (type == ATA_TYPE_ATA)
144             await_ide(NOT_BSY_RDY, iobase1, IDE_TIMEOUT);
145     }
146
147     // 8.2.1 (h) -- wait for not BSY
148     status = await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
149     dprintf(6, "ata_reset(2) status=%x\n", status);
150
151     // Enable interrupts
152     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
153 }
154
155
156 /****************************************************************
157  * ATA send command
158  ****************************************************************/
159
160 struct ata_op_s {
161     u64 lba;
162     void *far_buffer;
163     u16 driveid;
164     u16 count;
165 };
166
167 struct ata_pio_command {
168     u8 feature;
169     u8 sector_count;
170     u8 lba_low;
171     u8 lba_mid;
172     u8 lba_high;
173     u8 device;
174     u8 command;
175
176     u8 sector_count2;
177     u8 lba_low2;
178     u8 lba_mid2;
179     u8 lba_high2;
180 };
181
182 // Send an ata command to the drive.
183 static int
184 send_cmd(int driveid, struct ata_pio_command *cmd)
185 {
186     u8 channel = driveid / 2;
187     u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
188     u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
189
190     int status = inb(iobase1 + ATA_CB_STAT);
191     if (status & ATA_CB_STAT_BSY)
192         return -3;
193
194     // Disable interrupts
195     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
196
197     // Select device
198     u8 device = inb(iobase1 + ATA_CB_DH);
199     outb(cmd->device, iobase1 + ATA_CB_DH);
200     if ((device ^ cmd->device) & (1 << 4))
201         // Wait for device to become active.
202         msleep(50);
203
204     if (cmd->command & 0x04) {
205         outb(0x00, iobase1 + ATA_CB_FR);
206         outb(cmd->sector_count2, iobase1 + ATA_CB_SC);
207         outb(cmd->lba_low2, iobase1 + ATA_CB_SN);
208         outb(cmd->lba_mid2, iobase1 + ATA_CB_CL);
209         outb(cmd->lba_high2, iobase1 + ATA_CB_CH);
210     }
211     outb(cmd->feature, iobase1 + ATA_CB_FR);
212     outb(cmd->sector_count, iobase1 + ATA_CB_SC);
213     outb(cmd->lba_low, iobase1 + ATA_CB_SN);
214     outb(cmd->lba_mid, iobase1 + ATA_CB_CL);
215     outb(cmd->lba_high, iobase1 + ATA_CB_CH);
216     outb(cmd->command, iobase1 + ATA_CB_CMD);
217
218     status = ndelay_await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
219     if (status < 0)
220         return status;
221
222     if (status & ATA_CB_STAT_ERR) {
223         dprintf(6, "send_cmd : read error\n");
224         return -4;
225     }
226     if (!(status & ATA_CB_STAT_DRQ)) {
227         dprintf(6, "send_cmd : DRQ not set (status %02x)\n"
228                 , (unsigned) status);
229         return -5;
230     }
231
232     return 0;
233 }
234
235
236 /****************************************************************
237  * ATA transfers
238  ****************************************************************/
239
240 // Read and discard x number of bytes from an io channel.
241 static void
242 insx_discard(int mode, int iobase1, int bytes)
243 {
244     int count, i;
245     if (mode == ATA_MODE_PIO32) {
246         count = bytes / 4;
247         for (i=0; i<count; i++)
248             inl(iobase1);
249     } else {
250         count = bytes / 2;
251         for (i=0; i<count; i++)
252             inw(iobase1);
253     }
254 }
255
256 // Transfer 'count' blocks (of 'blocksize' bytes) to/from drive
257 // 'driveid'.  If 'skipfirst' or 'skiplast' is set then the first
258 // and/or last block may be partially transferred.  This function is
259 // inlined because all the callers use different forms and because the
260 // large number of parameters would consume a lot of stack space.
261 static __always_inline int
262 ata_transfer(int driveid, int iswrite, int count, int blocksize
263              , int skipfirst, int skiplast, void *far_buffer)
264 {
265     dprintf(16, "ata_transfer id=%d write=%d count=%d bs=%d"
266             " skipf=%d skipl=%d buf=%p\n"
267             , driveid, iswrite, count, blocksize
268             , skipfirst, skiplast, far_buffer);
269
270     // Reset count of transferred data
271     SET_EBDA(ata.trsfsectors, 0);
272
273     u8 channel  = driveid / 2;
274     u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
275     u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
276     u8 mode     = GET_EBDA(ata.devices[driveid].mode);
277     int current = 0;
278     int status;
279     for (;;) {
280         int bsize = blocksize;
281         if (skipfirst && current == 0) {
282             insx_discard(mode, iobase1, skipfirst);
283             bsize -= skipfirst;
284         }
285         if (skiplast && current == count-1)
286             bsize -= skiplast;
287
288         if (iswrite) {
289             // Write data to controller
290             dprintf(16, "Write sector id=%d dest=%p\n", driveid, far_buffer);
291             if (mode == ATA_MODE_PIO32)
292                 outsl_far(iobase1, far_buffer, bsize / 4);
293             else
294                 outsw_far(iobase1, far_buffer, bsize / 2);
295         } else {
296             // Read data from controller
297             dprintf(16, "Read sector id=%d dest=%p\n", driveid, far_buffer);
298             if (mode == ATA_MODE_PIO32)
299                 insl_far(iobase1, far_buffer, bsize / 4);
300             else
301                 insw_far(iobase1, far_buffer, bsize / 2);
302         }
303         far_buffer += bsize;
304
305         if (skiplast && current == count-1)
306             insx_discard(mode, iobase1, skiplast);
307
308         status = pause_await_ide(NOT_BSY, iobase1, iobase2, IDE_TIMEOUT);
309         if (status < 0)
310             // Error
311             return status;
312
313         current++;
314         SET_EBDA(ata.trsfsectors, current);
315         if (current == count)
316             break;
317         status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ
318                    | ATA_CB_STAT_ERR);
319         if (status != (ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ)) {
320             dprintf(6, "ata_transfer : more sectors left (status %02x)\n"
321                     , (unsigned) status);
322             return -6;
323         }
324     }
325
326     status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DF
327                | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR);
328     if (!iswrite)
329         status &= ~ATA_CB_STAT_DF;
330     if (status != ATA_CB_STAT_RDY ) {
331         dprintf(6, "ata_transfer : no sectors left (status %02x)\n"
332                 , (unsigned) status);
333         return -7;
334     }
335
336     // Enable interrupts
337     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
338     return 0;
339 }
340
341 static noinline int
342 ata_transfer_disk(const struct ata_op_s *op, int iswrite)
343 {
344     return ata_transfer(op->driveid, iswrite, op->count, IDE_SECTOR_SIZE
345                         , 0, 0, op->far_buffer);
346 }
347
348 static noinline int
349 ata_transfer_cdrom(const struct ata_op_s *op)
350 {
351     return ata_transfer(op->driveid, 0, op->count, CDROM_SECTOR_SIZE
352                         , 0, 0, op->far_buffer);
353 }
354
355 static noinline int
356 ata_transfer_emu(const struct ata_op_s *op, int before, int after)
357 {
358     int vcount = op->count * 4 - before - after;
359     int ret = ata_transfer(op->driveid, 0, op->count, CDROM_SECTOR_SIZE
360                            , before*512, after*512, op->far_buffer);
361     if (ret) {
362         SET_EBDA(ata.trsfsectors, 0);
363         return ret;
364     }
365     SET_EBDA(ata.trsfsectors, vcount);
366     return 0;
367 }
368
369
370 /****************************************************************
371  * ATA hard drive functions
372  ****************************************************************/
373
374 static noinline int
375 send_cmd_disk(const struct ata_op_s *op, u16 command)
376 {
377     u8 slave = op->driveid % 2;
378     u64 lba = op->lba;
379
380     struct ata_pio_command cmd;
381     memset(&cmd, 0, sizeof(cmd));
382
383     cmd.command = command;
384     if (op->count >= (1<<8) || lba + op->count >= (1<<28)) {
385         cmd.sector_count2 = op->count >> 8;
386         cmd.lba_low2 = lba >> 24;
387         cmd.lba_mid2 = lba >> 32;
388         cmd.lba_high2 = lba >> 40;
389
390         cmd.command |= 0x04;
391         lba &= 0xffffff;
392     }
393
394     cmd.feature = 0;
395     cmd.sector_count = op->count;
396     cmd.lba_low = lba;
397     cmd.lba_mid = lba >> 8;
398     cmd.lba_high = lba >> 16;
399     cmd.device = ((slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0)
400                   | ((lba >> 24) & 0xf) | ATA_CB_DH_LBA);
401
402     return send_cmd(op->driveid, &cmd);
403 }
404
405 // Read/write count blocks from a harddrive.
406 __always_inline int
407 ata_cmd_data(int driveid, u16 command, u64 lba, u16 count, void *far_buffer)
408 {
409     struct ata_op_s op;
410     op.driveid = driveid;
411     op.lba = lba;
412     op.count = count;
413     op.far_buffer = far_buffer;
414
415     int ret = send_cmd_disk(&op, command);
416     if (ret)
417         return ret;
418
419     int iswrite = command == ATA_CMD_WRITE_SECTORS;
420     return ata_transfer_disk(&op, iswrite);
421 }
422
423
424 /****************************************************************
425  * ATAPI functions
426  ****************************************************************/
427
428 // Low-level atapi command transmit function.
429 static __always_inline int
430 send_atapi_cmd(int driveid, u8 *cmdbuf, u8 cmdlen, u16 blocksize)
431 {
432     u8 channel = driveid / 2;
433     u8 slave = driveid % 2;
434     u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
435     u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
436
437     struct ata_pio_command cmd;
438     cmd.sector_count = 0;
439     cmd.feature = 0;
440     cmd.lba_low = 0;
441     cmd.lba_mid = blocksize;
442     cmd.lba_high = blocksize >> 8;
443     cmd.device = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
444     cmd.command = ATA_CMD_PACKET;
445
446     int ret = send_cmd(driveid, &cmd);
447     if (ret)
448         return ret;
449
450     // Send command to device
451     outsw_far(iobase1, MAKE_FARPTR(GET_SEG(SS), (u32)cmdbuf), cmdlen / 2);
452
453     int status = pause_await_ide(NOT_BSY_DRQ, iobase1, iobase2, IDE_TIMEOUT);
454     if (status < 0)
455         return status;
456
457     return 0;
458 }
459
460 // Low-level cdrom read atapi command transmit function.
461 static int
462 send_cmd_cdrom(const struct ata_op_s *op)
463 {
464     u8 atacmd[12];
465     memset(atacmd, 0, sizeof(atacmd));
466
467     atacmd[0]=0x28;                         // READ command
468     atacmd[7]=(op->count & 0xff00) >> 8;    // Sectors
469     atacmd[8]=(op->count & 0x00ff);
470     atacmd[2]=(op->lba & 0xff000000) >> 24; // LBA
471     atacmd[3]=(op->lba & 0x00ff0000) >> 16;
472     atacmd[4]=(op->lba & 0x0000ff00) >> 8;
473     atacmd[5]=(op->lba & 0x000000ff);
474
475     return send_atapi_cmd(op->driveid, atacmd, sizeof(atacmd)
476                           , CDROM_SECTOR_SIZE);
477 }
478
479 // Read sectors from the cdrom.
480 __always_inline int
481 cdrom_read(int driveid, u32 lba, u32 count, void *far_buffer)
482 {
483     struct ata_op_s op;
484     op.driveid = driveid;
485     op.lba = lba;
486     op.count = count;
487     op.far_buffer = far_buffer;
488
489     int ret = send_cmd_cdrom(&op);
490     if (ret)
491         return ret;
492
493     return ata_transfer_cdrom(&op);
494 }
495
496 // Pretend the cdrom has 512 byte sectors (instead of 2048) and read
497 // sectors.
498 __always_inline int
499 cdrom_read_512(int driveid, u32 vlba, u32 vcount, void *far_buffer)
500 {
501     u32 velba = vlba + vcount - 1;
502     u32 lba = vlba / 4;
503     u32 elba = velba / 4;
504     int count = elba - lba + 1;
505     int before = vlba % 4;
506     int after = 3 - (velba % 4);
507
508     struct ata_op_s op;
509     op.driveid = driveid;
510     op.lba = lba;
511     op.count = count;
512     op.far_buffer = far_buffer;
513
514     dprintf(16, "cdrom_read_512: id=%d vlba=%d vcount=%d buf=%p lba=%d elba=%d"
515             " count=%d before=%d after=%d\n"
516             , driveid, vlba, vcount, far_buffer, lba, elba
517             , count, before, after);
518
519     int ret = send_cmd_cdrom(&op);
520     if (ret)
521         return ret;
522
523     return ata_transfer_emu(&op, before, after);
524 }
525
526 // Send a simple atapi command to a drive.
527 int
528 ata_cmd_packet(int driveid, u8 *cmdbuf, u8 cmdlen
529                , u32 length, void *far_buffer)
530 {
531     int ret = send_atapi_cmd(driveid, cmdbuf, cmdlen, length);
532     if (ret)
533         return ret;
534
535     return ata_transfer(driveid, 0, 1, length, 0, 0, far_buffer);
536 }
537
538
539 /****************************************************************
540  * ATA detect and init
541  ****************************************************************/
542
543 static void
544 report_model(int driveid, u8 *buffer)
545 {
546     u8 model[41];
547
548     // Read model name
549     int i;
550     for (i=0; i<40; i+=2) {
551         model[i] = buffer[i+54+1];
552         model[i+1] = buffer[i+54];
553     }
554
555     // Reformat
556     model[40] = 0x00;
557     for (i=39; i>0; i--) {
558         if (model[i] != 0x20)
559             break;
560         model[i] = 0x00;
561     }
562
563     u8 channel = driveid / 2;
564     u8 slave = driveid % 2;
565     // XXX - model on stack not %cs
566     printf("ata%d %s: %s", channel, slave ? " slave" : "master", model);
567 }
568
569 static u8
570 get_ata_version(u8 *buffer)
571 {
572     u16 ataversion = *(u16*)&buffer[160];
573     u8 version;
574     for (version=15; version>0; version--)
575         if (ataversion & (1<<version))
576             break;
577     return version;
578 }
579
580 static void
581 init_drive_atapi(int driveid)
582 {
583     SET_EBDA(ata.devices[driveid].type, ATA_TYPE_ATAPI);
584
585     // Temporary values to do the transfer
586     SET_EBDA(ata.devices[driveid].device,ATA_DEVICE_CDROM);
587     SET_EBDA(ata.devices[driveid].mode, ATA_MODE_PIO16);
588
589     // Now we send a IDENTIFY command to ATAPI device
590     u8 buffer[0x0200];
591     memset(buffer, 0, sizeof(buffer));
592     u16 ret = ata_cmd_data(driveid, ATA_CMD_IDENTIFY_DEVICE_PACKET
593                            , 1, 1
594                            , MAKE_FARPTR(GET_SEG(SS), (u32)buffer));
595     if (ret != 0)
596         BX_PANIC("ata-detect: Failed to detect ATAPI device\n");
597
598     u8 type      = buffer[1] & 0x1f;
599     u8 removable = (buffer[0] & 0x80) ? 1 : 0;
600     u8 mode      = buffer[96] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
601     u16 blksize  = CDROM_SECTOR_SIZE;
602
603     SET_EBDA(ata.devices[driveid].device, type);
604     SET_EBDA(ata.devices[driveid].removable, removable);
605     SET_EBDA(ata.devices[driveid].mode, mode);
606     SET_EBDA(ata.devices[driveid].blksize, blksize);
607
608     // fill cdidmap
609     u8 cdcount = GET_EBDA(ata.cdcount);
610     SET_EBDA(ata.idmap[1][cdcount], driveid);
611     SET_EBDA(ata.cdcount, ++cdcount);
612
613     report_model(driveid, buffer);
614     u8 version = get_ata_version(buffer);
615     if (GET_EBDA(ata.devices[driveid].device)==ATA_DEVICE_CDROM)
616         printf(" ATAPI-%d CD-Rom/DVD-Rom\n", version);
617     else
618         printf(" ATAPI-%d Device\n", version);
619 }
620
621 static void
622 fill_fdpt(int driveid)
623 {
624     if (driveid > 1)
625         return;
626
627     u16 nlc   = GET_EBDA(ata.devices[driveid].lchs.cylinders);
628     u16 nlh   = GET_EBDA(ata.devices[driveid].lchs.heads);
629     u16 nlspt = GET_EBDA(ata.devices[driveid].lchs.spt);
630
631     u16 npc   = GET_EBDA(ata.devices[driveid].pchs.cylinders);
632     u16 nph   = GET_EBDA(ata.devices[driveid].pchs.heads);
633     u16 npspt = GET_EBDA(ata.devices[driveid].pchs.spt);
634
635     SET_EBDA(fdpt[driveid].precompensation, 0xffff);
636     SET_EBDA(fdpt[driveid].drive_control_byte, 0xc0 | ((nph > 8) << 3));
637     SET_EBDA(fdpt[driveid].landing_zone, npc);
638     SET_EBDA(fdpt[driveid].cylinders, nlc);
639     SET_EBDA(fdpt[driveid].heads, nlh);
640     SET_EBDA(fdpt[driveid].sectors, nlspt);
641
642     if (nlc == npc && nlh == nph && nlspt == npspt)
643         // no logical CHS mapping used, just physical CHS
644         // use Standard Fixed Disk Parameter Table (FDPT)
645         return;
646
647     // complies with Phoenix style Translated Fixed Disk Parameter
648     // Table (FDPT)
649     SET_EBDA(fdpt[driveid].phys_cylinders, npc);
650     SET_EBDA(fdpt[driveid].phys_heads, nph);
651     SET_EBDA(fdpt[driveid].phys_sectors, npspt);
652     SET_EBDA(fdpt[driveid].a0h_signature, 0xa0);
653
654     // Checksum structure.
655     u8 *p = MAKE_FARPTR(SEG_EBDA, offsetof(struct extended_bios_data_area_s
656                                            , fdpt[driveid]));
657     u8 sum = checksum(p, FIELD_SIZEOF(struct extended_bios_data_area_s
658                                       , fdpt[driveid]) - 1);
659     SET_EBDA(fdpt[driveid].checksum, -sum);
660 }
661
662 static u8
663 get_translation(int driveid)
664 {
665     if (! CONFIG_COREBOOT) {
666         // Emulators pass in the translation info via nvram.
667         u8 channel = driveid / 2;
668         u8 translation = inb_cmos(CMOS_BIOS_DISKTRANSFLAG + channel/2);
669         translation >>= 2 * (driveid % 4);
670         translation &= 0x03;
671         return translation;
672     }
673
674     // On COREBOOT, use a heuristic to determine translation type.
675     u16 heads = GET_EBDA(ata.devices[driveid].pchs.heads);
676     u16 cylinders = GET_EBDA(ata.devices[driveid].pchs.cylinders);
677     u16 spt = GET_EBDA(ata.devices[driveid].pchs.spt);
678
679     if (cylinders <= 1024 && heads <= 16 && spt <= 63)
680         return ATA_TRANSLATION_NONE;
681     if (cylinders * heads <= 131072)
682         return ATA_TRANSLATION_LARGE;
683     return ATA_TRANSLATION_LBA;
684 }
685
686 static void
687 setup_translation(int driveid)
688 {
689     u8 translation = get_translation(driveid);
690     SET_EBDA(ata.devices[driveid].translation, translation);
691
692     u8 channel = driveid / 2;
693     u8 slave = driveid % 2;
694     u16 heads = GET_EBDA(ata.devices[driveid].pchs.heads);
695     u16 cylinders = GET_EBDA(ata.devices[driveid].pchs.cylinders);
696     u16 spt = GET_EBDA(ata.devices[driveid].pchs.spt);
697     u64 sectors = GET_EBDA(ata.devices[driveid].sectors);
698
699     dprintf(1, "ata%d-%d: PCHS=%u/%d/%d translation="
700             , channel, slave, cylinders, heads, spt);
701     switch (translation) {
702     case ATA_TRANSLATION_NONE:
703         dprintf(1, "none");
704         break;
705     case ATA_TRANSLATION_LBA:
706         dprintf(1, "lba");
707         spt = 63;
708         if (sectors > 63*255*1024) {
709             heads = 255;
710             cylinders = 1024;
711             break;
712         }
713         u32 sect = (u32)sectors / 63;
714         heads = sect / 1024;
715         if (heads>128)
716             heads = 255;
717         else if (heads>64)
718             heads = 128;
719         else if (heads>32)
720             heads = 64;
721         else if (heads>16)
722             heads = 32;
723         else
724             heads = 16;
725         cylinders = sect / heads;
726         break;
727     case ATA_TRANSLATION_RECHS:
728         dprintf(1, "r-echs");
729         // Take care not to overflow
730         if (heads==16) {
731             if (cylinders>61439)
732                 cylinders=61439;
733             heads=15;
734             cylinders = (u16)((u32)(cylinders)*16/15);
735         }
736         // then go through the large bitshift process
737     case ATA_TRANSLATION_LARGE:
738         if (translation == ATA_TRANSLATION_LARGE)
739             dprintf(1, "large");
740         while (cylinders > 1024) {
741             cylinders >>= 1;
742             heads <<= 1;
743
744             // If we max out the head count
745             if (heads > 127)
746                 break;
747         }
748         break;
749     }
750     // clip to 1024 cylinders in lchs
751     if (cylinders > 1024)
752         cylinders = 1024;
753     dprintf(1, " LCHS=%d/%d/%d\n", cylinders, heads, spt);
754
755     SET_EBDA(ata.devices[driveid].lchs.heads, heads);
756     SET_EBDA(ata.devices[driveid].lchs.cylinders, cylinders);
757     SET_EBDA(ata.devices[driveid].lchs.spt, spt);
758 }
759
760 static void
761 init_drive_ata(int driveid)
762 {
763     SET_EBDA(ata.devices[driveid].type, ATA_TYPE_ATA);
764
765     // Temporary values to do the transfer
766     SET_EBDA(ata.devices[driveid].device, ATA_DEVICE_HD);
767     SET_EBDA(ata.devices[driveid].mode, ATA_MODE_PIO16);
768
769     // Now we send a IDENTIFY command to ATA device
770     u8 buffer[0x0200];
771     memset(buffer, 0, sizeof(buffer));
772     u16 ret = ata_cmd_data(driveid, ATA_CMD_IDENTIFY_DEVICE
773                            , 1, 1
774                            , MAKE_FARPTR(GET_SEG(SS), (u32)buffer));
775     if (ret)
776         BX_PANIC("ata-detect: Failed to detect ATA device\n");
777
778     u8 removable  = (buffer[0] & 0x80) ? 1 : 0;
779     u8 mode       = buffer[48*2] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
780     u16 blksize   = IDE_SECTOR_SIZE;
781
782     u16 cylinders = *(u16*)&buffer[1*2]; // word 1
783     u16 heads     = *(u16*)&buffer[3*2]; // word 3
784     u16 spt       = *(u16*)&buffer[6*2]; // word 6
785
786     u64 sectors;
787     if (*(u16*)&buffer[83*2] & (1 << 10)) // word 83 - lba48 support
788         sectors = *(u64*)&buffer[100*2]; // word 100-103
789     else
790         sectors = *(u32*)&buffer[60*2]; // word 60 and word 61
791
792     SET_EBDA(ata.devices[driveid].device, ATA_DEVICE_HD);
793     SET_EBDA(ata.devices[driveid].removable, removable);
794     SET_EBDA(ata.devices[driveid].mode, mode);
795     SET_EBDA(ata.devices[driveid].blksize, blksize);
796     SET_EBDA(ata.devices[driveid].pchs.heads, heads);
797     SET_EBDA(ata.devices[driveid].pchs.cylinders, cylinders);
798     SET_EBDA(ata.devices[driveid].pchs.spt, spt);
799     SET_EBDA(ata.devices[driveid].sectors, sectors);
800
801     // Setup disk geometry translation.
802     setup_translation(driveid);
803
804     // fill hdidmap
805     u8 hdcount = GET_EBDA(ata.hdcount);
806     SET_EBDA(ata.idmap[0][hdcount], driveid);
807     SET_EBDA(ata.hdcount, ++hdcount);
808
809     // Fill "fdpt" structure.
810     fill_fdpt(driveid);
811
812     // Report drive info to user.
813     u64 sizeinmb = GET_EBDA(ata.devices[driveid].sectors) >> 11;
814     report_model(driveid, buffer);
815     u8 version = get_ata_version(buffer);
816     if (sizeinmb < (1 << 16))
817         printf(" ATA-%d Hard-Disk (%u MiBytes)\n", version, (u32)sizeinmb);
818     else
819         printf(" ATA-%d Hard-Disk (%u GiBytes)\n", version
820                , (u32)(sizeinmb >> 10));
821 }
822
823 static void
824 init_drive_unknown(int driveid)
825 {
826     SET_EBDA(ata.devices[driveid].type, ATA_TYPE_UNKNOWN);
827
828     u8 channel = driveid / 2;
829     u8 slave = driveid % 2;
830     printf("ata%d %s: Unknown device\n", channel, slave ? " slave" : "master");
831 }
832
833 static void
834 ata_detect()
835 {
836     // Device detection
837     int driveid;
838     for(driveid=0; driveid<CONFIG_MAX_ATA_DEVICES; driveid++) {
839         u8 channel = driveid / 2;
840         u8 slave = driveid % 2;
841
842         u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
843         u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
844         if (!iobase1)
845             break;
846
847         // Disable interrupts
848         outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
849
850         // Look for device
851         outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
852         msleep(50);
853         outb(0x55, iobase1+ATA_CB_SC);
854         outb(0xaa, iobase1+ATA_CB_SN);
855         outb(0xaa, iobase1+ATA_CB_SC);
856         outb(0x55, iobase1+ATA_CB_SN);
857         outb(0x55, iobase1+ATA_CB_SC);
858         outb(0xaa, iobase1+ATA_CB_SN);
859
860         // If we found something
861         u8 sc = inb(iobase1+ATA_CB_SC);
862         u8 sn = inb(iobase1+ATA_CB_SN);
863         dprintf(6, "ata_detect(1) drive=%d sc=%x sn=%x\n", driveid, sc, sn);
864
865         if (sc != 0x55 || sn != 0xaa)
866             continue;
867
868         // reset the channel
869         ata_reset(driveid);
870
871         // check for ATA or ATAPI
872         outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
873         msleep(50);
874         sc = inb(iobase1+ATA_CB_SC);
875         sn = inb(iobase1+ATA_CB_SN);
876         dprintf(6, "ata_detect(2) drive=%d sc=%x sn=%x\n", driveid, sc, sn);
877         if (sc!=0x01 || sn!=0x01) {
878             init_drive_unknown(driveid);
879             continue;
880         }
881         u8 cl = inb(iobase1+ATA_CB_CL);
882         u8 ch = inb(iobase1+ATA_CB_CH);
883         u8 st = inb(iobase1+ATA_CB_STAT);
884         dprintf(6, "ata_detect(3) drive=%d sc=%x sn=%x cl=%x ch=%x st=%x\n"
885                 , driveid, sc, sn, cl, ch, st);
886
887         if (cl==0x14 && ch==0xeb)
888             init_drive_atapi(driveid);
889         else if (cl==0x00 && ch==0x00 && st!=0x00)
890             init_drive_ata(driveid);
891         else if (cl==0xff && ch==0xff)
892             // None
893             continue;
894         else
895             init_drive_unknown(driveid);
896     }
897
898     printf("\n");
899 }
900
901 static void
902 ata_init()
903 {
904     // hdidmap and cdidmap init.
905     u8 device;
906     for (device=0; device < CONFIG_MAX_ATA_DEVICES; device++) {
907         SET_EBDA(ata.idmap[0][device], CONFIG_MAX_ATA_DEVICES);
908         SET_EBDA(ata.idmap[1][device], CONFIG_MAX_ATA_DEVICES);
909     }
910
911     // Scan PCI bus for ATA adapters
912     int count=0, bdf=-1;
913     u16 classid = PCI_CLASS_STORAGE_OTHER; // SATA first
914     while (count<CONFIG_MAX_ATA_INTERFACES-1) {
915         bdf = pci_find_class(classid, bdf+1);
916         if (bdf < 0) {
917             if (classid == PCI_CLASS_STORAGE_IDE)
918                 // Done
919                 break;
920             classid = PCI_CLASS_STORAGE_IDE; // PATA controllers
921             bdf = -1;
922             continue;
923         }
924
925         u8 irq = pci_config_readb(bdf, PCI_INTERRUPT_LINE);
926         SET_EBDA(ata.channels[count].irq, irq);
927         SET_EBDA(ata.channels[count].pci_bdf, bdf);
928
929         u8 prog_if = pci_config_readb(bdf, PCI_CLASS_PROG);
930         u32 port1, port2;
931
932         if (classid != PCI_CLASS_STORAGE_IDE || prog_if & 1) {
933             port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_0) & ~3;
934             port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_1) & ~3;
935         } else {
936             port1 = 0x1f0;
937             port2 = 0x3f0;
938         }
939         SET_EBDA(ata.channels[count].iobase1, port1);
940         SET_EBDA(ata.channels[count].iobase2, port2);
941         dprintf(1, "ATA controller %d at %x/%x (dev %x class %x/%x)\n"
942                 , count, port1, port2, bdf, classid, prog_if);
943         count++;
944
945         if (classid != PCI_CLASS_STORAGE_IDE || prog_if & 4) {
946             port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_2) & ~3;
947             port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_3) & ~3;
948         } else {
949             port1 = 0x170;
950             port2 = 0x370;
951         }
952         dprintf(1, "ATA controller %d at %x/%x (dev %x class %x/%x)\n"
953                 , count, port1, port2, bdf, classid, prog_if);
954         SET_EBDA(ata.channels[count].iobase1, port1);
955         SET_EBDA(ata.channels[count].iobase2, port2);
956         count++;
957     }
958 }
959
960 void
961 hard_drive_setup()
962 {
963     if (!CONFIG_ATA)
964         return;
965
966     dprintf(3, "init hard drives\n");
967     ata_init();
968     ata_detect();
969
970     // Store the device count
971     SET_BDA(disk_count, GET_EBDA(ata.hdcount));
972
973     SET_BDA(disk_control_byte, 0xc0);
974
975     // Enable IRQ14 (handle_76)
976     unmask_pic2(PIC2_IRQ14);
977 }