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