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