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