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