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