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