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