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