Try to check for IDE drive 0 responding to drive 1 commands.
[seabios.git] / src / ata.c
index eba9972a5057c2efc641ee8de837cf8a171884a4..3b609c5b73ad1644b1fdcaf86fdb6d71d14cc86f 100644 (file)
--- a/src/ata.c
+++ b/src/ata.c
@@ -3,13 +3,20 @@
 // Copyright (C) 2008  Kevin O'Connor <kevin@koconnor.net>
 // Copyright (C) 2002  MandrakeSoft S.A.
 //
-// This file may be distributed under the terms of the GNU GPLv3 license.
+// This file may be distributed under the terms of the GNU LGPLv3 license.
 
-#include "ata.h" // ATA_*
 #include "types.h" // u8
 #include "ioport.h" // inb
-#include "util.h" // BX_INFO
+#include "util.h" // dprintf
 #include "cmos.h" // inb_cmos
+#include "pic.h" // enable_hwirq
+#include "biosvar.h" // GET_EBDA
+#include "pci.h" // pci_find_class
+#include "pci_ids.h" // PCI_CLASS_STORAGE_OTHER
+#include "pci_regs.h" // PCI_INTERRUPT_LINE
+#include "boot.h" // add_bcv_hd
+#include "disk.h" // struct ata_s
+#include "atabits.h" // ATA_CB_STAT
 
 #define TIMEOUT 0
 #define BSY 1
 #define NOT_BSY_NOT_DRQ 4
 #define NOT_BSY_RDY 5
 
-#define IDE_TIMEOUT 32000u //32 seconds max for IDE ops
+#define IDE_SECTOR_SIZE 512
+#define CDROM_SECTOR_SIZE 2048
 
-#define DEBUGF1(fmt, args...) bprintf(0, fmt , ##args)
-#define DEBUGF(fmt, args...)
+#define IDE_TIMEOUT 32000 //32 seconds max for IDE ops
 
-// XXX - lots of redundancy in this file.
+struct ata_s ATA VAR16_32;
 
-static int
-await_ide(u8 when_done, u16 base, u16 timeout)
+
+/****************************************************************
+ * Helper functions
+ ****************************************************************/
+
+// Wait for the specified ide state
+static inline int
+await_ide(u8 mask, u8 flags, u16 base, u16 timeout)
 {
-    u32 time=0, last=0;
-    // for the times you're supposed to throw one away
-    u16 status = inb(base + ATA_CB_STAT);
+    u64 end = calc_future_tsc(timeout);
     for (;;) {
-        status = inb(base+ATA_CB_STAT);
-        time++;
-        u8 result;
-        if (when_done == BSY)
-            result = status & ATA_CB_STAT_BSY;
-        else if (when_done == NOT_BSY)
-            result = !(status & ATA_CB_STAT_BSY);
-        else if (when_done == NOT_BSY_DRQ)
-            result = !(status & ATA_CB_STAT_BSY) && (status & ATA_CB_STAT_DRQ);
-        else if (when_done == NOT_BSY_NOT_DRQ)
-            result = !(status & ATA_CB_STAT_BSY) && !(status & ATA_CB_STAT_DRQ);
-        else if (when_done == NOT_BSY_RDY)
-            result = !(status & ATA_CB_STAT_BSY) && (status & ATA_CB_STAT_RDY);
-        else if (when_done == TIMEOUT)
-            result = 0;
-
-        if (result)
-            return 0;
-        // mod 2048 each 16 ms
-        if (time>>16 != last) {
-            last = time >>16;
-            DEBUGF("await_ide: (TIMEOUT,BSY,!BSY,!BSY_DRQ,!BSY_!DRQ,!BSY_RDY)"
-                   " %d time= %d timeout= %d\n"
-                   , when_done, time>>11, timeout);
-        }
-        if (status & ATA_CB_STAT_ERR) {
-            DEBUGF("await_ide: ERROR (TIMEOUT,BSY,!BSY,!BSY_DRQ"
-                   ",!BSY_!DRQ,!BSY_RDY) %d time= %d timeout= %d\n"
-                   , when_done, time>>11, timeout);
+        u8 status = inb(base+ATA_CB_STAT);
+        if ((status & mask) == flags)
+            return status;
+        if (rdtscll() > end) {
+            dprintf(1, "IDE time out\n");
             return -1;
         }
-        if ((timeout == 0) || ((time>>11) > timeout))
-            break;
     }
-    BX_INFO("IDE time out\n");
-    return -1;
 }
 
+// Wait for the device to be not-busy.
+static int
+await_not_bsy(u16 base)
+{
+    return await_ide(ATA_CB_STAT_BSY, 0, base, IDE_TIMEOUT);
+}
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : software reset
-// ---------------------------------------------------------------------------
-// ATA-3
-// 8.2.1 Software reset - Device 0
+// Wait for the device to be ready.
+static int
+await_rdy(u16 base)
+{
+    return await_ide(ATA_CB_STAT_RDY, ATA_CB_STAT_RDY, base, IDE_TIMEOUT);
+}
 
-void
-ata_reset(u16 device)
+// Wait for ide state - pauses for one ata cycle first.
+static inline int
+pause_await_not_bsy(u16 iobase1, u16 iobase2)
 {
-    u16 iobase1, iobase2;
-    u8  channel, slave, sn, sc;
-    u8  type;
+    // Wait one PIO transfer cycle.
+    inb(iobase2 + ATA_CB_ASTAT);
 
-    channel = device / 2;
-    slave = device % 2;
+    return await_not_bsy(iobase1);
+}
 
-    iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    iobase2 = GET_EBDA(ata.channels[channel].iobase2);
+// Wait for ide state - pause for 400ns first.
+static inline int
+ndelay_await_not_bsy(u16 iobase1)
+{
+    ndelay(400);
+    return await_not_bsy(iobase1);
+}
 
-    // Reset
+// Reset a drive
+void
+ata_reset(int driveid)
+{
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
 
-    // 8.2.1 (a) -- set SRST in DC
+    dprintf(6, "ata_reset driveid=%d\n", driveid);
+    // Pulse SRST
     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN | ATA_CB_DC_SRST, iobase2+ATA_CB_DC);
-
-    // 8.2.1 (b) -- wait for BSY
-    await_ide(BSY, iobase1, 20);
-
-    // 8.2.1 (f) -- clear SRST
+    udelay(5);
     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
-
-    type=GET_EBDA(ata.devices[device].type);
-    if (type != ATA_TYPE_NONE) {
-
-        // 8.2.1 (g) -- check for sc==sn==0x01
-        // select device
-        outb(slave?ATA_CB_DH_DEV1:ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
-        sc = inb(iobase1+ATA_CB_SC);
-        sn = inb(iobase1+ATA_CB_SN);
-
-        if ( (sc==0x01) && (sn==0x01) ) {
-            if (type == ATA_TYPE_ATA) //ATA
-                await_ide(NOT_BSY_RDY, iobase1, IDE_TIMEOUT);
-            else //ATAPI
-                await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
+    mdelay(2);
+
+    // wait for device to become not busy.
+    int status = await_not_bsy(iobase1);
+    if (status < 0)
+        goto done;
+    if (slave) {
+        // Change device.
+        u64 end = calc_future_tsc(IDE_TIMEOUT);
+        for (;;) {
+            outb(ATA_CB_DH_DEV1, iobase1 + ATA_CB_DH);
+            status = ndelay_await_not_bsy(iobase1);
+            if (status < 0)
+                goto done;
+            if (inb(iobase1 + ATA_CB_DH) == ATA_CB_DH_DEV1)
+                break;
+            // Change drive request failed to take effect - retry.
+            if (rdtscll() > end) {
+                dprintf(1, "ata_reset slave time out\n");
+                goto done;
+            }
         }
-
-        // 8.2.1 (h) -- wait for not BSY
-        await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
     }
 
+    // On a user-reset request, wait for RDY if it is an ATA device.
+    u8 type=GET_GLOBAL(ATA.devices[driveid].type);
+    if (type == ATA_TYPE_ATA)
+        status = await_rdy(iobase1);
+
+done:
     // Enable interrupts
     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
+
+    dprintf(6, "ata_reset exit status=%x\n", status);
 }
 
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : execute a data command
-// ---------------------------------------------------------------------------
-      // returns
-      // 0 : no error
-      // 1 : BUSY bit set
-      // 2 : read error
-      // 3 : expected DRQ=1
-      // 4 : no sectors left to read/verify
-      // 5 : more sectors to read/verify
-      // 6 : no sectors left to write
-      // 7 : more sectors to write
+/****************************************************************
+ * ATA send command
+ ****************************************************************/
 
 struct ata_pio_command {
-    void *far_buffer;
-    u8 biosid;
-
     u8 feature;
     u8 sector_count;
     u8 lba_low;
@@ -157,19 +155,33 @@ struct ata_pio_command {
     u8 lba_high2;
 };
 
+// Send an ata command to the drive.
 static int
-send_cmd(struct ata_pio_command *cmd)
+send_cmd(int driveid, struct ata_pio_command *cmd)
 {
-    u16 biosid = cmd->biosid;
-    u8 channel = biosid / 2;
-    u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-
-    u8 status = inb(iobase1 + ATA_CB_STAT);
-    if (status & ATA_CB_STAT_BSY)
-        return 1;
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
 
+    // Disable interrupts
     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
+
+    // Select device
+    int status = await_not_bsy(iobase1);
+    if (status < 0)
+        return status;
+    u8 newdh = ((cmd->device & ~ATA_CB_DH_DEV1)
+                | (slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0));
+    u8 olddh = inb(iobase1 + ATA_CB_DH);
+    outb(newdh, iobase1 + ATA_CB_DH);
+    if ((olddh ^ newdh) & (1<<4)) {
+        // Was a device change - wait for device to become not busy.
+        status = ndelay_await_not_bsy(iobase1);
+        if (status < 0)
+            return status;
+    }
+
     if (cmd->command & 0x04) {
         outb(0x00, iobase1 + ATA_CB_FR);
         outb(cmd->sector_count2, iobase1 + ATA_CB_SC);
@@ -182,93 +194,121 @@ send_cmd(struct ata_pio_command *cmd)
     outb(cmd->lba_low, iobase1 + ATA_CB_SN);
     outb(cmd->lba_mid, iobase1 + ATA_CB_CL);
     outb(cmd->lba_high, iobase1 + ATA_CB_CH);
-    outb(cmd->device, iobase1 + ATA_CB_DH);
     outb(cmd->command, iobase1 + ATA_CB_CMD);
 
-    await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
+    status = ndelay_await_not_bsy(iobase1);
+    if (status < 0)
+        return status;
 
-    status = inb(iobase1 + ATA_CB_STAT);
     if (status & ATA_CB_STAT_ERR) {
-        DEBUGF("send_cmd : read error\n");
-        return 2;
+        dprintf(6, "send_cmd : read error (status=%02x err=%02x)\n"
+                , status, inb(iobase1 + ATA_CB_ERR));
+        return -4;
     }
     if (!(status & ATA_CB_STAT_DRQ)) {
-        DEBUGF("send_cmd : DRQ not set (status %02x)\n"
-               , (unsigned) status);
-        return 3;
+        dprintf(6, "send_cmd : DRQ not set (status %02x)\n", status);
+        return -5;
     }
 
     return 0;
 }
 
-static int
-ata_transfer(struct ata_pio_command *cmd)
+
+/****************************************************************
+ * ATA transfers
+ ****************************************************************/
+
+// Read and discard x number of bytes from an io channel.
+static void
+insx_discard(int iobase1, int bytes)
 {
-    DEBUGF("ata_transfer id=%d cmd=%d lba=%d count=%d buf=%p\n"
-           , cmd->biosid, cmd->command
-           , (cmd->lba_high << 16) | (cmd->lba_mid << 8) | cmd->lba_low
-           , cmd->sector_count, cmd->far_buffer);
+    int count, i;
+    if (CONFIG_ATA_PIO32) {
+        count = bytes / 4;
+        for (i=0; i<count; i++)
+            inl(iobase1);
+    } else {
+        count = bytes / 2;
+        for (i=0; i<count; i++)
+            inw(iobase1);
+    }
+}
 
-    // Reset count of transferred data
-    SET_EBDA(ata.trsfsectors,0);
-    SET_EBDA(ata.trsfbytes,0L);
+// Transfer 'count' blocks (of 'blocksize' bytes) to/from drive
+// 'driveid'.  If 'skipfirst' or 'skiplast' is set then the first
+// and/or last block may be partially transferred.  This function is
+// inlined because all the callers use different forms and because the
+// large number of parameters would consume a lot of stack space.
+static __always_inline int
+ata_transfer(int driveid, int iswrite, int count, int blocksize
+             , int skipfirst, int skiplast, void *buf_fl)
+{
+    dprintf(16, "ata_transfer id=%d write=%d count=%d bs=%d"
+            " skipf=%d skipl=%d buf=%p\n"
+            , driveid, iswrite, count, blocksize
+            , skipfirst, skiplast, buf_fl);
 
-    int ret = send_cmd(cmd);
-    if (ret)
-        return ret;
+    // Reset count of transferred data
+    SET_EBDA(sector_count, 0);
 
-    u16 biosid = cmd->biosid;
-    u8 channel  = biosid / 2;
-    u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-    u8 mode     = GET_EBDA(ata.devices[biosid].mode);
-    int iswrite = (cmd->command & ~0x40) == ATA_CMD_WRITE_SECTORS;
-    u8 current = 0;
-    u16 count = cmd->sector_count;
-    u8 status;
-    void *far_buffer = cmd->far_buffer;
+    u8 channel  = driveid / 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
+    int current = 0;
+    int status;
     for (;;) {
+        int bsize = blocksize;
+        if (skipfirst && current == 0) {
+            insx_discard(iobase1, skipfirst);
+            bsize -= skipfirst;
+        }
+        if (skiplast && current == count-1)
+            bsize -= skiplast;
+
         if (iswrite) {
             // Write data to controller
-            DEBUGF("Write sector id=%d dest=%p\n", biosid, far_buffer);
-            if (mode == ATA_MODE_PIO32)
-                outsl_far(iobase1, far_buffer, 512 / 4);
+            dprintf(16, "Write sector id=%d dest=%p\n", driveid, buf_fl);
+            if (CONFIG_ATA_PIO32)
+                outsl_fl(iobase1, buf_fl, bsize / 4);
             else
-                outsw_far(iobase1, far_buffer, 512 / 2);
+                outsw_fl(iobase1, buf_fl, bsize / 2);
         } else {
             // Read data from controller
-            DEBUGF("Read sector id=%d dest=%p\n", biosid, far_buffer);
-            if (mode == ATA_MODE_PIO32)
-                insl_far(iobase1, far_buffer, 512 / 4);
+            dprintf(16, "Read sector id=%d dest=%p\n", driveid, buf_fl);
+            if (CONFIG_ATA_PIO32)
+                insl_fl(iobase1, buf_fl, bsize / 4);
             else
-                insw_far(iobase1, far_buffer, 512 / 2);
-            await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
+                insw_fl(iobase1, buf_fl, bsize / 2);
         }
-        far_buffer += 512;
+        buf_fl += bsize;
+
+        if (skiplast && current == count-1)
+            insx_discard(iobase1, skiplast);
+
+        status = pause_await_not_bsy(iobase1, iobase2);
+        if (status < 0)
+            // Error
+            return status;
 
         current++;
-        SET_EBDA(ata.trsfsectors,current);
-        count--;
-        status = inb(iobase1 + ATA_CB_STAT);
-        if (count == 0)
+        SET_EBDA(sector_count, current);
+        if (current == count)
             break;
-        status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ
-                   | ATA_CB_STAT_ERR);
-        if (status != (ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ)) {
-            DEBUGF("ata_transfer : more sectors left (status %02x)\n"
-                   , (unsigned) status);
-            return 5;
+        status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR);
+        if (status != ATA_CB_STAT_DRQ) {
+            dprintf(6, "ata_transfer : more sectors left (status %02x)\n"
+                    , status);
+            return -6;
         }
     }
 
-    status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DF
-               | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR);
+    status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_DF | ATA_CB_STAT_DRQ
+               | ATA_CB_STAT_ERR);
     if (!iswrite)
         status &= ~ATA_CB_STAT_DF;
-    if (status != ATA_CB_STAT_RDY ) {
-        DEBUGF("ata_transfer : no sectors left (status %02x)\n"
-               , (unsigned) status);
-        return 4;
+    if (status != 0) {
+        dprintf(6, "ata_transfer : no sectors left (status %02x)\n", status);
+        return -7;
     }
 
     // Enable interrupts
@@ -276,392 +316,253 @@ ata_transfer(struct ata_pio_command *cmd)
     return 0;
 }
 
-inline int
-ata_cmd_data(u16 biosid, u16 command, u32 lba, u16 count, void *far_buffer)
+static noinline int
+ata_transfer_disk(const struct disk_op_s *op)
+{
+    return ata_transfer(op->driveid, op->command == ATA_CMD_WRITE_SECTORS
+                        , op->count, IDE_SECTOR_SIZE, 0, 0, op->buf_fl);
+}
+
+static noinline int
+ata_transfer_cdrom(const struct disk_op_s *op)
+{
+    return ata_transfer(op->driveid, 0, op->count, CDROM_SECTOR_SIZE
+                        , 0, 0, op->buf_fl);
+}
+
+static noinline int
+ata_transfer_cdemu(const struct disk_op_s *op, int before, int after)
+{
+    int vcount = op->count * 4 - before - after;
+    int ret = ata_transfer(op->driveid, 0, op->count, CDROM_SECTOR_SIZE
+                           , before*512, after*512, op->buf_fl);
+    if (ret) {
+        SET_EBDA(sector_count, 0);
+        return ret;
+    }
+    SET_EBDA(sector_count, vcount);
+    return 0;
+}
+
+
+/****************************************************************
+ * ATA hard drive functions
+ ****************************************************************/
+
+static int
+send_cmd_disk(const struct disk_op_s *op)
 {
-    u8 slave   = biosid % 2;
+    u64 lba = op->lba;
 
     struct ata_pio_command cmd;
-    cmd.far_buffer = far_buffer;
-    cmd.biosid = biosid;
+    memset(&cmd, 0, sizeof(cmd));
 
-    if (count >= (1<<8) || lba + count >= (1<<28)) {
-        cmd.sector_count2 = count >> 8;
+    cmd.command = op->command;
+    if (op->count >= (1<<8) || lba + op->count >= (1<<28)) {
+        cmd.sector_count2 = op->count >> 8;
         cmd.lba_low2 = lba >> 24;
-        cmd.lba_mid2 = 0;
-        cmd.lba_high2 = 0;
+        cmd.lba_mid2 = lba >> 32;
+        cmd.lba_high2 = lba >> 40;
 
-        command |= 0x04;
+        cmd.command |= 0x04;
         lba &= 0xffffff;
     }
 
     cmd.feature = 0;
-    cmd.sector_count = count;
+    cmd.sector_count = op->count;
     cmd.lba_low = lba;
     cmd.lba_mid = lba >> 8;
     cmd.lba_high = lba >> 16;
-    cmd.device = ((slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0)
-                  | ((lba >> 24) & 0xf) | ATA_CB_DH_LBA);
-    cmd.command = command;
-    return ata_transfer(&cmd);
+    cmd.device = ((lba >> 24) & 0xf) | ATA_CB_DH_LBA;
+
+    return send_cmd(op->driveid, &cmd);
 }
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : execute a packet command
-// ---------------------------------------------------------------------------
-      // returns
-      // 0 : no error
-      // 1 : error in parameters
-      // 2 : BUSY bit set
-      // 3 : error
-      // 4 : not ready
-static inline int
-__ata_cmd_packet(u16 biosid, u8 *cmdbuf, u8 cmdlen
-                 , u16 header, u32 length, void *far_buffer)
+// Read/write count blocks from a harddrive.
+int
+ata_cmd_data(struct disk_op_s *op)
 {
-    DEBUGF("ata_cmd_packet d=%d cmdlen=%d h=%d l=%d buf=%p\n"
-           , biosid, cmdlen, header, length, far_buffer);
+    int ret = send_cmd_disk(op);
+    if (ret)
+        return ret;
+    return ata_transfer_disk(op);
+}
 
-    u8 channel = biosid / 2;
-    u8 slave = biosid % 2;
 
-    // The header length must be even
-    if (header & 1) {
-        DEBUGF("ata_cmd_packet : header must be even (%04x)\n", header);
-        return 1;
-    }
+/****************************************************************
+ * ATAPI functions
+ ****************************************************************/
 
-    u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-    u8 mode     = GET_EBDA(ata.devices[biosid].mode);
+// Low-level atapi command transmit function.
+static int
+send_atapi_cmd(int driveid, u8 *cmdbuf, u8 cmdlen, u16 blocksize)
+{
+    u8 channel = driveid / 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
 
     struct ata_pio_command cmd;
     cmd.sector_count = 0;
     cmd.feature = 0;
     cmd.lba_low = 0;
-    cmd.lba_mid = 0xf0;
-    cmd.lba_high = 0xff;
-    cmd.device = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
+    cmd.lba_mid = blocksize;
+    cmd.lba_high = blocksize >> 8;
+    cmd.device = 0;
     cmd.command = ATA_CMD_PACKET;
 
-    cmd.biosid = biosid;
-    int ret = send_cmd(&cmd);
+    int ret = send_cmd(driveid, &cmd);
     if (ret)
         return ret;
 
-    // Reset count of transferred data
-    SET_EBDA(ata.trsfsectors,0);
-    SET_EBDA(ata.trsfbytes,0L);
-
     // Send command to device
-    outsw_far(iobase1, MAKE_FARPTR(GET_SEG(SS), (u32)cmdbuf), cmdlen / 2);
-
-    u8 status;
-    u16 loops = 0;
-    for (;;) {
-        if (loops == 0) {//first time through
-            status = inb(iobase2 + ATA_CB_ASTAT);
-            await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
-        } else
-            await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
-        loops++;
-
-        status = inb(iobase1 + ATA_CB_STAT);
-        inb(iobase1 + ATA_CB_SC);
-
-        // Check if command completed
-        if(((inb(iobase1 + ATA_CB_SC)&0x7)==0x3) &&
-           ((status & (ATA_CB_STAT_RDY | ATA_CB_STAT_ERR)) == ATA_CB_STAT_RDY))
-            break;
+    outsw_fl(iobase1, MAKE_FLATPTR(GET_SEG(SS), cmdbuf), cmdlen / 2);
 
-        if (status & ATA_CB_STAT_ERR) {
-            DEBUGF("ata_cmd_packet : error (status %02x)\n", status);
-            return 3;
-        }
-
-        // Get the byte count
-        u16 lcount =  (((u16)(inb(iobase1 + ATA_CB_CH))<<8)
-                       + inb(iobase1 + ATA_CB_CL));
-
-        // adjust to read what we want
-        u16 lbefore, lafter;
-        if (header > lcount) {
-            lbefore=lcount;
-            header-=lcount;
-            lcount=0;
-        } else {
-            lbefore=header;
-            header=0;
-            lcount-=lbefore;
-        }
-
-        if (lcount > length) {
-            lafter=lcount-length;
-            lcount=length;
-            length=0;
-        } else {
-            lafter=0;
-            length-=lcount;
-        }
-
-        // Save byte count
-        u16 count = lcount;
-
-        DEBUGF("Trying to read %04x bytes (%04x %04x %04x) to %p\n"
-               , lbefore+lcount+lafter, lbefore, lcount, lafter, far_buffer);
-
-        // If counts not dividable by 4, use 16bits mode
-        u8 lmode = mode;
-        if (lbefore & 0x03) lmode=ATA_MODE_PIO16;
-        if (lcount  & 0x03) lmode=ATA_MODE_PIO16;
-        if (lafter  & 0x03) lmode=ATA_MODE_PIO16;
-
-        // adds an extra byte if count are odd. before is always even
-        if (lcount & 0x01) {
-            lcount+=1;
-            if ((lafter > 0) && (lafter & 0x01)) {
-                lafter-=1;
-            }
-        }
-
-        if (lmode == ATA_MODE_PIO32) {
-            lcount>>=2; lbefore>>=2; lafter>>=2;
-        } else {
-            lcount>>=1; lbefore>>=1; lafter>>=1;
-        }
-
-        int i;
-        for (i=0; i<lbefore; i++)
-            if (lmode == ATA_MODE_PIO32)
-                inl(iobase1);
-            else
-                inw(iobase1);
-
-        if (lmode == ATA_MODE_PIO32)
-            insl_far(iobase1, far_buffer, lcount);
-        else
-            insw_far(iobase1, far_buffer, lcount);
-
-        for (i=0; i<lafter; i++)
-            if (lmode == ATA_MODE_PIO32)
-                inl(iobase1);
-            else
-                inw(iobase1);
-
-        // Compute new buffer address
-        far_buffer += count;
+    int status = pause_await_not_bsy(iobase1, iobase2);
+    if (status < 0)
+        return status;
 
-        // Save transferred bytes count
-        SET_EBDA(ata.trsfsectors, loops);
+    if (status & ATA_CB_STAT_ERR) {
+        u8 err = inb(iobase1 + ATA_CB_ERR);
+        // skip "Not Ready"
+        if (err != 0x20)
+            dprintf(6, "send_atapi_cmd : read error (status=%02x err=%02x)\n"
+                    , status, err);
+        return -2;
     }
-
-    // Final check, device must be ready
-    if ( (status & (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DF
-                    | ATA_CB_STAT_DRQ | ATA_CB_STAT_ERR) )
-         != ATA_CB_STAT_RDY ) {
-        DEBUGF("ata_cmd_packet : not ready (status %02x)\n"
-               , (unsigned) status);
-        return 4;
+    if (!(status & ATA_CB_STAT_DRQ)) {
+        dprintf(6, "send_atapi_cmd : DRQ not set (status %02x)\n", status);
+        return -3;
     }
 
-    // Enable interrupts
-    outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
     return 0;
 }
 
-int
-ata_cmd_packet(u16 biosid, u8 *cmdbuf, u8 cmdlen
-               , u32 length, void *far_buffer)
-{
-    return __ata_cmd_packet(biosid, cmdbuf, cmdlen, 0, length, far_buffer);
-}
-
-static void
-build_cdrom_cmd(u8 *atacmd, u32 lba, u16 count)
+// Low-level cdrom read atapi command transmit function.
+static int
+send_cmd_cdrom(const struct disk_op_s *op)
 {
-    memset(atacmd, 0, 12);
-    atacmd[0]=0x28;                     // READ command
-    atacmd[7]=(count & 0xff00) >> 8;    // Sectors
-    atacmd[8]=(count & 0x00ff);         // Sectors
-    atacmd[2]=(lba & 0xff000000) >> 24; // LBA
-    atacmd[3]=(lba & 0x00ff0000) >> 16;
-    atacmd[4]=(lba & 0x0000ff00) >> 8;
-    atacmd[5]=(lba & 0x000000ff);
+    u8 atacmd[12];
+    memset(atacmd, 0, sizeof(atacmd));
+
+    atacmd[0]=0x28;                         // READ command
+    atacmd[7]=(op->count & 0xff00) >> 8;    // Sectors
+    atacmd[8]=(op->count & 0x00ff);
+    atacmd[2]=(op->lba & 0xff000000) >> 24; // LBA
+    atacmd[3]=(op->lba & 0x00ff0000) >> 16;
+    atacmd[4]=(op->lba & 0x0000ff00) >> 8;
+    atacmd[5]=(op->lba & 0x000000ff);
+
+    return send_atapi_cmd(op->driveid, atacmd, sizeof(atacmd)
+                          , CDROM_SECTOR_SIZE);
 }
 
 // Read sectors from the cdrom.
 int
-cdrom_read(u16 biosid, u32 lba, u32 count, void *far_buffer)
+cdrom_read(struct disk_op_s *op)
 {
-    u8 atacmd[12];
-    build_cdrom_cmd(atacmd, lba, count);
-    return ata_cmd_packet(biosid, atacmd, sizeof(atacmd)
-                          , count*2048, far_buffer);
+    int ret = send_cmd_cdrom(op);
+    if (ret)
+        return ret;
+
+    return ata_transfer_cdrom(op);
 }
 
 // Pretend the cdrom has 512 byte sectors (instead of 2048) and read
 // sectors.
 int
-cdrom_read_512(u16 biosid, u32 vlba, u32 count, void *far_buffer)
+cdrom_read_512(struct disk_op_s *op)
 {
-    u32 slba = vlba / 4;
-    u16 before = vlba % 4;
-    u32 elba = (vlba + count - 1) / 4;
-
-    u8 atacmd[12];
-    build_cdrom_cmd(atacmd, slba, elba - slba + 1);
+    u32 vlba = op->lba;
+    u32 vcount = op->count;
+    u32 lba = op->lba = vlba / 4;
+    u32 velba = vlba + vcount - 1;
+    u32 elba = velba / 4;
+    op->count = elba - lba + 1;
+    int before = vlba % 4;
+    int after = 3 - (velba % 4);
+
+    dprintf(16, "cdrom_read_512: id=%d vlba=%d vcount=%d buf=%p lba=%d elba=%d"
+            " count=%d before=%d after=%d\n"
+            , op->driveid, vlba, vcount, op->buf_fl, lba, elba
+            , op->count, before, after);
+
+    int ret = send_cmd_cdrom(op);
+    if (ret)
+        return ret;
 
-    int status = __ata_cmd_packet(biosid, atacmd, sizeof(atacmd)
-                                  , before*512, count*512, far_buffer);
-    if (status) {
-        SET_EBDA(ata.trsfsectors, 0);
-        return status;
-    }
-    SET_EBDA(ata.trsfsectors, count);
-    return 0;
+    return ata_transfer_cdemu(op, before, after);
 }
 
-
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : device detection
-// ---------------------------------------------------------------------------
-
-static void
-report_model(u8 devid, u8 *buffer)
+// Send a simple atapi command to a drive.
+int
+ata_cmd_packet(int driveid, u8 *cmdbuf, u8 cmdlen
+               , u32 length, void *buf_fl)
 {
-    u8 model[41];
+    int ret = send_atapi_cmd(driveid, cmdbuf, cmdlen, length);
+    if (ret)
+        return ret;
 
-    // Read model name
-    int i;
-    for (i=0; i<40; i+=2) {
-        model[i] = buffer[i+54+1];
-        model[i+1] = buffer[i+54];
-    }
+    return ata_transfer(driveid, 0, 1, length, 0, 0, buf_fl);
+}
 
-    // Reformat
-    model[40] = 0x00;
-    for (i=39; i>0; i--) {
-        if (model[i] != 0x20)
-            break;
-        model[i] = 0x00;
-    }
 
-    u8 channel = devid / 2;
-    u8 slave = devid % 2;
-    // XXX - model on stack not %cs
-    printf("ata%d %s: %s", channel, slave ? " slave" : "master", model);
-}
+/****************************************************************
+ * Disk geometry translation
+ ****************************************************************/
 
 static u8
-get_ata_version(u8 *buffer)
+get_translation(int driveid)
 {
-    u16 ataversion = *(u16*)&buffer[160];
-    u8 version;
-    for (version=15; version>0; version--)
-        if (ataversion & (1<<version))
-            break;
-    return version;
-}
+    if (! CONFIG_COREBOOT) {
+        // Emulators pass in the translation info via nvram.
+        u8 channel = driveid / 2;
+        u8 translation = inb_cmos(CMOS_BIOS_DISKTRANSFLAG + channel/2);
+        translation >>= 2 * (driveid % 4);
+        translation &= 0x03;
+        return translation;
+    }
 
-static void
-init_drive_atapi(u8 devid)
-{
-    SET_EBDA(ata.devices[devid].type,ATA_TYPE_ATAPI);
-
-    // Temporary values to do the transfer
-    SET_EBDA(ata.devices[devid].device,ATA_DEVICE_CDROM);
-    SET_EBDA(ata.devices[devid].mode, ATA_MODE_PIO16);
-
-    // Now we send a IDENTIFY command to ATAPI device
-    u8 buffer[0x0200];
-    memset(buffer, 0, sizeof(buffer));
-    u16 ret = ata_cmd_data(devid, ATA_CMD_IDENTIFY_DEVICE_PACKET
-                           , 1, 1
-                           , MAKE_FARPTR(GET_SEG(SS), (u32)buffer));
-    if (ret != 0)
-        BX_PANIC("ata-detect: Failed to detect ATAPI device\n");
-
-    u8 type      = buffer[1] & 0x1f;
-    u8 removable = (buffer[0] & 0x80) ? 1 : 0;
-    u8 mode      = buffer[96] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
-    u16 blksize  = 2048;
-
-    SET_EBDA(ata.devices[devid].device, type);
-    SET_EBDA(ata.devices[devid].removable, removable);
-    SET_EBDA(ata.devices[devid].mode, mode);
-    SET_EBDA(ata.devices[devid].blksize, blksize);
+    // On COREBOOT, use a heuristic to determine translation type.
+    u16 heads = GET_GLOBAL(ATA.devices[driveid].pchs.heads);
+    u16 cylinders = GET_GLOBAL(ATA.devices[driveid].pchs.cylinders);
+    u16 spt = GET_GLOBAL(ATA.devices[driveid].pchs.spt);
 
-    // fill cdidmap
-    u8 cdcount = GET_EBDA(ata.cdcount);
-    SET_EBDA(ata.idmap[1][cdcount], devid);
-    SET_EBDA(ata.cdcount, ++cdcount);
-
-    report_model(devid, buffer);
-    u8 version = get_ata_version(buffer);
-    if (GET_EBDA(ata.devices[devid].device)==ATA_DEVICE_CDROM)
-        printf(" ATAPI-%d CD-Rom/DVD-Rom\n", version);
-    else
-        printf(" ATAPI-%d Device\n", version);
+    if (cylinders <= 1024 && heads <= 16 && spt <= 63)
+        return ATA_TRANSLATION_NONE;
+    if (cylinders * heads <= 131072)
+        return ATA_TRANSLATION_LARGE;
+    return ATA_TRANSLATION_LBA;
 }
 
 static void
-init_drive_ata(u8 devid)
+setup_translation(int driveid)
 {
-    SET_EBDA(ata.devices[devid].type,ATA_TYPE_ATA);
-
-    // Temporary values to do the transfer
-    SET_EBDA(ata.devices[devid].device, ATA_DEVICE_HD);
-    SET_EBDA(ata.devices[devid].mode, ATA_MODE_PIO16);
-
-    // Now we send a IDENTIFY command to ATA device
-    u8 buffer[0x0200];
-    memset(buffer, 0, sizeof(buffer));
-    u16 ret = ata_cmd_data(devid, ATA_CMD_IDENTIFY_DEVICE
-                           , 1, 1
-                           , MAKE_FARPTR(GET_SEG(SS), (u32)buffer));
-    if (ret)
-        BX_PANIC("ata-detect: Failed to detect ATA device\n");
-
-    u8 removable  = (buffer[0] & 0x80) ? 1 : 0;
-    u8 mode       = buffer[96] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
-    u16 blksize   = *(u16*)&buffer[10];
-
-    u16 cylinders = *(u16*)&buffer[1*2]; // word 1
-    u16 heads     = *(u16*)&buffer[3*2]; // word 3
-    u16 spt       = *(u16*)&buffer[6*2]; // word 6
-
-    u32 sectors   = *(u32*)&buffer[60*2]; // word 60 and word 61
-
-    SET_EBDA(ata.devices[devid].device,ATA_DEVICE_HD);
-    SET_EBDA(ata.devices[devid].removable, removable);
-    SET_EBDA(ata.devices[devid].mode, mode);
-    SET_EBDA(ata.devices[devid].blksize, blksize);
-    SET_EBDA(ata.devices[devid].pchs.heads, heads);
-    SET_EBDA(ata.devices[devid].pchs.cylinders, cylinders);
-    SET_EBDA(ata.devices[devid].pchs.spt, spt);
-    SET_EBDA(ata.devices[devid].sectors, sectors);
-
-    u8 channel = devid / 2;
-    u8 slave = devid % 2;
-    u8 translation = inb_cmos(CMOS_BIOS_DISKTRANSFLAG + channel/2);
-    u8 shift;
-    for (shift=devid%4; shift>0; shift--)
-        translation >>= 2;
-    translation &= 0x03;
-
-    SET_EBDA(ata.devices[devid].translation, translation);
-
-    BX_INFO("ata%d-%d: PCHS=%u/%d/%d translation="
+    u8 translation = get_translation(driveid);
+    SET_GLOBAL(ATA.devices[driveid].translation, translation);
+
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    u16 heads = GET_GLOBAL(ATA.devices[driveid].pchs.heads);
+    u16 cylinders = GET_GLOBAL(ATA.devices[driveid].pchs.cylinders);
+    u16 spt = GET_GLOBAL(ATA.devices[driveid].pchs.spt);
+    u64 sectors = GET_GLOBAL(ATA.devices[driveid].sectors);
+
+    dprintf(1, "ata%d-%d: PCHS=%u/%d/%d translation="
             , channel, slave, cylinders, heads, spt);
     switch (translation) {
     case ATA_TRANSLATION_NONE:
-        BX_INFO("none");
+        dprintf(1, "none");
         break;
     case ATA_TRANSLATION_LBA:
-        BX_INFO("lba");
+        dprintf(1, "lba");
         spt = 63;
-        sectors /= 63;
-        heads = sectors / 1024;
+        if (sectors > 63*255*1024) {
+            heads = 255;
+            cylinders = 1024;
+            break;
+        }
+        u32 sect = (u32)sectors / 63;
+        heads = sect / 1024;
         if (heads>128)
             heads = 255;
         else if (heads>64)
@@ -672,10 +573,10 @@ init_drive_ata(u8 devid)
             heads = 32;
         else
             heads = 16;
-        cylinders = sectors / heads;
+        cylinders = sect / heads;
         break;
     case ATA_TRANSLATION_RECHS:
-        BX_INFO("r-echs");
+        dprintf(1, "r-echs");
         // Take care not to overflow
         if (heads==16) {
             if (cylinders>61439)
@@ -686,8 +587,8 @@ init_drive_ata(u8 devid)
         // then go through the large bitshift process
     case ATA_TRANSLATION_LARGE:
         if (translation == ATA_TRANSLATION_LARGE)
-            BX_INFO("large");
-        while(cylinders > 1024) {
+            dprintf(1, "large");
+        while (cylinders > 1024) {
             cylinders >>= 1;
             heads <<= 1;
 
@@ -700,129 +601,370 @@ init_drive_ata(u8 devid)
     // clip to 1024 cylinders in lchs
     if (cylinders > 1024)
         cylinders = 1024;
-    BX_INFO(" LCHS=%d/%d/%d\n", cylinders, heads, spt);
+    dprintf(1, " LCHS=%d/%d/%d\n", cylinders, heads, spt);
 
-    SET_EBDA(ata.devices[devid].lchs.heads, heads);
-    SET_EBDA(ata.devices[devid].lchs.cylinders, cylinders);
-    SET_EBDA(ata.devices[devid].lchs.spt, spt);
+    SET_GLOBAL(ATA.devices[driveid].lchs.heads, heads);
+    SET_GLOBAL(ATA.devices[driveid].lchs.cylinders, cylinders);
+    SET_GLOBAL(ATA.devices[driveid].lchs.spt, spt);
+}
 
-    // fill hdidmap
-    u8 hdcount = GET_EBDA(ata.hdcount);
-    SET_EBDA(ata.idmap[0][hdcount], devid);
-    SET_EBDA(ata.hdcount, ++hdcount);
 
-    u32 sizeinmb = GET_EBDA(ata.devices[devid].sectors);
-    sizeinmb >>= 11;
+/****************************************************************
+ * ATA detect and init
+ ****************************************************************/
 
-    report_model(devid, buffer);
-    u8 version = get_ata_version(buffer);
+// Extract common information from IDENTIFY commands.
+static void
+extract_identify(int driveid, u16 *buffer)
+{
+    dprintf(3, "Identify w0=%x w2=%x\n", buffer[0], buffer[2]);
+
+    // Read model name
+    char *model = ATA.devices[driveid].model;
+    int maxsize = ARRAY_SIZE(ATA.devices[driveid].model);
+    int i;
+    for (i=0; i<maxsize/2; i++) {
+        u16 v = buffer[27+i];
+        model[i*2] = v >> 8;
+        model[i*2+1] = v & 0xff;
+    }
+    model[maxsize-1] = 0x00;
+
+    // Trim trailing spaces from model name.
+    for (i=maxsize-2; i>0 && model[i] == 0x20; i--)
+        model[i] = 0x00;
+
+    // Extract ATA/ATAPI version.
+    u16 ataversion = buffer[80];
+    u8 version;
+    for (version=15; version>0; version--)
+        if (ataversion & (1<<version))
+            break;
+    ATA.devices[driveid].version = version;
+
+    // Common flags.
+    SET_GLOBAL(ATA.devices[driveid].removable, (buffer[0] & 0x80) ? 1 : 0);
+}
+
+static int
+init_drive_atapi(int driveid, u16 *buffer)
+{
+    // Send an IDENTIFY_DEVICE_PACKET command to device
+    memset(buffer, 0, IDE_SECTOR_SIZE);
+    struct disk_op_s dop;
+    dop.driveid = driveid;
+    dop.command = ATA_CMD_IDENTIFY_DEVICE_PACKET;
+    dop.count = 1;
+    dop.lba = 1;
+    dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);
+    int ret = ata_cmd_data(&dop);
+    if (ret)
+        return ret;
+
+    // Success - setup as ATAPI.
+    extract_identify(driveid, buffer);
+    SET_GLOBAL(ATA.devices[driveid].type, ATA_TYPE_ATAPI);
+    SET_GLOBAL(ATA.devices[driveid].device, (buffer[0] >> 8) & 0x1f);
+    SET_GLOBAL(ATA.devices[driveid].blksize, CDROM_SECTOR_SIZE);
+
+    // fill cdidmap
+    u8 cdcount = GET_GLOBAL(ATA.cdcount);
+    SET_GLOBAL(ATA.idmap[1][cdcount], driveid);
+    SET_GLOBAL(ATA.cdcount, cdcount+1);
+
+    // Report drive info to user.
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    printf("ata%d-%d: %s ATAPI-%d %s\n", channel, slave
+           , ATA.devices[driveid].model, ATA.devices[driveid].version
+           , (ATA.devices[driveid].device == ATA_DEVICE_CDROM
+              ? "CD-Rom/DVD-Rom" : "Device"));
+
+    return 0;
+}
+
+static int
+init_drive_ata(int driveid, u16 *buffer)
+{
+    // Send an IDENTIFY_DEVICE command to device
+    memset(buffer, 0, IDE_SECTOR_SIZE);
+    struct disk_op_s dop;
+    dop.driveid = driveid;
+    dop.command = ATA_CMD_IDENTIFY_DEVICE;
+    dop.count = 1;
+    dop.lba = 1;
+    dop.buf_fl = MAKE_FLATPTR(GET_SEG(SS), buffer);
+    int ret = ata_cmd_data(&dop);
+    if (ret)
+        return ret;
+
+    // Success - setup as ATA.
+    extract_identify(driveid, buffer);
+    SET_GLOBAL(ATA.devices[driveid].type, ATA_TYPE_ATA);
+    SET_GLOBAL(ATA.devices[driveid].device, ATA_DEVICE_HD);
+    SET_GLOBAL(ATA.devices[driveid].blksize, IDE_SECTOR_SIZE);
+
+    SET_GLOBAL(ATA.devices[driveid].pchs.cylinders, buffer[1]);
+    SET_GLOBAL(ATA.devices[driveid].pchs.heads, buffer[3]);
+    SET_GLOBAL(ATA.devices[driveid].pchs.spt, buffer[6]);
+
+    u64 sectors;
+    if (buffer[83] & (1 << 10)) // word 83 - lba48 support
+        sectors = *(u64*)&buffer[100]; // word 100-103
+    else
+        sectors = *(u32*)&buffer[60]; // word 60 and word 61
+    SET_GLOBAL(ATA.devices[driveid].sectors, sectors);
+
+    // Setup disk geometry translation.
+    setup_translation(driveid);
+
+    // Report drive info to user.
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    char *model = ATA.devices[driveid].model;
+    printf("ata%d-%d: %s ATA-%d Hard-Disk ", channel, slave, model
+           , ATA.devices[driveid].version);
+    u64 sizeinmb = sectors >> 11;
     if (sizeinmb < (1 << 16))
-        printf(" ATA-%d Hard-Disk (%u MBytes)\n", version, sizeinmb);
+        printf("(%u MiBytes)\n", (u32)sizeinmb);
     else
-        printf(" ATA-%d Hard-Disk (%u GBytes)\n", version, sizeinmb >> 10);
+        printf("(%u GiBytes)\n", (u32)(sizeinmb >> 10));
+
+    // Register with bcv system.
+    add_bcv_hd(driveid, model);
+
+    return 0;
 }
 
-static void
-init_drive_unknown(u8 devid)
+static int
+powerup_await_non_bsy(u16 base, u64 end)
 {
-    SET_EBDA(ata.devices[devid].type,ATA_TYPE_UNKNOWN);
-
-    u8 channel = devid / 2;
-    u8 slave = devid % 2;
-    printf("ata%d %s: Unknown device\n", channel, slave ? " slave" : "master");
+    u8 orstatus = 0;
+    u8 status;
+    for (;;) {
+        status = inb(base+ATA_CB_STAT);
+        if (!(status & ATA_CB_STAT_BSY))
+            break;
+        orstatus |= status;
+        if (orstatus == 0xff) {
+            dprintf(1, "powerup IDE floating\n");
+            return orstatus;
+        }
+        if (rdtscll() > end) {
+            dprintf(1, "powerup IDE time out\n");
+            return -1;
+        }
+    }
+    dprintf(6, "powerup iobase=%x st=%x\n", base, status);
+    return status;
 }
 
-void
+static void
 ata_detect()
 {
-#if CONFIG_MAX_ATA_INTERFACES > 0
-    SET_EBDA(ata.channels[0].iface,ATA_IFACE_ISA);
-    SET_EBDA(ata.channels[0].iobase1,0x1f0);
-    SET_EBDA(ata.channels[0].iobase2,0x3f0);
-    SET_EBDA(ata.channels[0].irq,14);
-#endif
-#if CONFIG_MAX_ATA_INTERFACES > 1
-    SET_EBDA(ata.channels[1].iface,ATA_IFACE_ISA);
-    SET_EBDA(ata.channels[1].iobase1,0x170);
-    SET_EBDA(ata.channels[1].iobase2,0x370);
-    SET_EBDA(ata.channels[1].irq,15);
-#endif
-#if CONFIG_MAX_ATA_INTERFACES > 2
-    SET_EBDA(ata.channels[2].iface,ATA_IFACE_ISA);
-    SET_EBDA(ata.channels[2].iobase1,0x1e8);
-    SET_EBDA(ata.channels[2].iobase2,0x3e0);
-    SET_EBDA(ata.channels[2].irq,12);
-#endif
-#if CONFIG_MAX_ATA_INTERFACES > 3
-    SET_EBDA(ata.channels[3].iface,ATA_IFACE_ISA);
-    SET_EBDA(ata.channels[3].iobase1,0x168);
-    SET_EBDA(ata.channels[3].iobase2,0x360);
-    SET_EBDA(ata.channels[3].irq,11);
-#endif
-#if CONFIG_MAX_ATA_INTERFACES > 4
-#error Please fill the ATA interface informations
-#endif
-
     // Device detection
-    u8 devid;
-    for(devid=0; devid<CONFIG_MAX_ATA_DEVICES; devid++) {
-        u8 channel = devid / 2;
-        u8 slave = devid % 2;
-
-        u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-        u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
+    u64 end = calc_future_tsc(IDE_TIMEOUT);
+    int driveid, last_reset_driveid=-1;
+    for(driveid=0; driveid<CONFIG_MAX_ATA_DEVICES; driveid++) {
+        u8 channel = driveid / 2;
+        u8 slave = driveid % 2;
+
+        u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+        if (!iobase1)
+            break;
 
-        // Disable interrupts
-        outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
+        // Wait for not-bsy.
+        int status = powerup_await_non_bsy(iobase1, end);
+        if (status < 0)
+            continue;
+        u8 newdh = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
+        outb(newdh, iobase1+ATA_CB_DH);
+        ndelay(400);
+        status = powerup_await_non_bsy(iobase1, end);
+        if (status < 0)
+            continue;
 
-        // Look for device
-        outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
-        outb(0x55, iobase1+ATA_CB_SC);
-        outb(0xaa, iobase1+ATA_CB_SN);
-        outb(0xaa, iobase1+ATA_CB_SC);
-        outb(0x55, iobase1+ATA_CB_SN);
+        // Check if ioport registers look valid.
+        outb(newdh, iobase1+ATA_CB_DH);
+        u8 dh = inb(iobase1+ATA_CB_DH);
         outb(0x55, iobase1+ATA_CB_SC);
         outb(0xaa, iobase1+ATA_CB_SN);
-
-        // If we found something
         u8 sc = inb(iobase1+ATA_CB_SC);
         u8 sn = inb(iobase1+ATA_CB_SN);
-
-        if (sc != 0x55 || sn != 0xaa)
+        dprintf(6, "ata_detect drive=%d sc=%x sn=%x dh=%x\n"
+                , driveid, sc, sn, dh);
+        if (sc != 0x55 || sn != 0xaa || dh != newdh)
             continue;
 
         // reset the channel
-        ata_reset(devid);
-
-        // check for ATA or ATAPI
-        outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
-        sc = inb(iobase1+ATA_CB_SC);
-        sn = inb(iobase1+ATA_CB_SN);
-        if (sc!=0x01 || sn!=0x01) {
-            init_drive_unknown(devid);
-            continue;
+        if (slave && driveid == last_reset_driveid + 1) {
+            // The drive was just reset - no need to reset it again.
+        } else {
+            ata_reset(driveid);
+            last_reset_driveid = driveid;
         }
-        u8 cl = inb(iobase1+ATA_CB_CL);
-        u8 ch = inb(iobase1+ATA_CB_CH);
-        u8 st = inb(iobase1+ATA_CB_STAT);
-
-        if (cl==0x14 && ch==0xeb)
-            init_drive_atapi(devid);
-        else if (cl==0x00 && ch==0x00 && st!=0x00)
-            init_drive_ata(devid);
-        else if (cl==0xff && ch==0xff)
-            // None
+
+        // check for ATAPI
+        u16 buffer[256];
+        int ret = init_drive_atapi(driveid, buffer);
+        if (!ret) {
+            // Found an ATAPI drive.
+        } else {
+            u8 st = inb(iobase1+ATA_CB_STAT);
+            if (!st)
+                // Status not set - can't be a valid drive.
+                continue;
+
+            // Wait for RDY.
+            ret = await_rdy(iobase1);
+            if (ret < 0)
+                continue;
+
+            // check for ATA.
+            ret = init_drive_ata(driveid, buffer);
+            if (ret)
+                // No ATA drive found
+                continue;
+        }
+
+        u16 resetresult = buffer[93];
+        dprintf(6, "ata_detect resetresult=%04x\n", resetresult);
+        if (!slave && (resetresult & 0xdf61) == 0x4041)
+            // resetresult looks valid and device 0 is responding to
+            // device 1 requests - device 1 must not be present - skip
+            // detection.
+            driveid++;
+    }
+
+    printf("\n");
+}
+
+static void
+ata_init()
+{
+    memset(&ATA, 0, sizeof(ATA));
+
+    // hdidmap and cdidmap init.
+    u8 device;
+    for (device=0; device < CONFIG_MAX_ATA_DEVICES; device++) {
+        SET_GLOBAL(ATA.idmap[0][device], CONFIG_MAX_ATA_DEVICES);
+        SET_GLOBAL(ATA.idmap[1][device], CONFIG_MAX_ATA_DEVICES);
+    }
+
+    // Scan PCI bus for ATA adapters
+    int count=0;
+    int bdf, max;
+    foreachpci(bdf, max) {
+        if (pci_config_readw(bdf, PCI_CLASS_DEVICE) != PCI_CLASS_STORAGE_IDE)
             continue;
-        else
-            init_drive_unknown(devid);
+        if (count >= ARRAY_SIZE(ATA.channels))
+            break;
+
+        u8 irq = pci_config_readb(bdf, PCI_INTERRUPT_LINE);
+        SET_GLOBAL(ATA.channels[count].irq, irq);
+        SET_GLOBAL(ATA.channels[count].pci_bdf, bdf);
+
+        u8 prog_if = pci_config_readb(bdf, PCI_CLASS_PROG);
+        u32 port1, port2;
+
+        if (prog_if & 1) {
+            port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_0) & ~3;
+            port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_1) & ~3;
+        } else {
+            port1 = 0x1f0;
+            port2 = 0x3f0;
+        }
+        SET_GLOBAL(ATA.channels[count].iobase1, port1);
+        SET_GLOBAL(ATA.channels[count].iobase2, port2);
+        dprintf(1, "ATA controller %d at %x/%x (dev %x prog_if %x)\n"
+                , count, port1, port2, bdf, prog_if);
+        count++;
+
+        if (prog_if & 4) {
+            port1 = pci_config_readl(bdf, PCI_BASE_ADDRESS_2) & ~3;
+            port2 = pci_config_readl(bdf, PCI_BASE_ADDRESS_3) & ~3;
+        } else {
+            port1 = 0x170;
+            port2 = 0x370;
+        }
+        dprintf(1, "ATA controller %d at %x/%x (dev %x prog_if %x)\n"
+                , count, port1, port2, bdf, prog_if);
+        SET_GLOBAL(ATA.channels[count].iobase1, port1);
+        SET_GLOBAL(ATA.channels[count].iobase2, port2);
+        count++;
     }
+}
 
-    // Store the device count
-    SET_BDA(disk_count, GET_EBDA(ata.hdcount));
+void
+hard_drive_setup()
+{
+    if (!CONFIG_ATA)
+        return;
 
-    printf("\n");
+    dprintf(3, "init hard drives\n");
+    ata_init();
+    ata_detect();
+
+    SET_BDA(disk_control_byte, 0xc0);
+
+    enable_hwirq(14, entry_76);
+}
+
+
+/****************************************************************
+ * Drive mapping
+ ****************************************************************/
+
+// Fill in Fixed Disk Parameter Table (located in ebda).
+static void
+fill_fdpt(int driveid)
+{
+    if (driveid > 1)
+        return;
+
+    u16 nlc   = GET_GLOBAL(ATA.devices[driveid].lchs.cylinders);
+    u16 nlh   = GET_GLOBAL(ATA.devices[driveid].lchs.heads);
+    u16 nlspt = GET_GLOBAL(ATA.devices[driveid].lchs.spt);
+
+    u16 npc   = GET_GLOBAL(ATA.devices[driveid].pchs.cylinders);
+    u16 nph   = GET_GLOBAL(ATA.devices[driveid].pchs.heads);
+    u16 npspt = GET_GLOBAL(ATA.devices[driveid].pchs.spt);
+
+    struct fdpt_s *fdpt = &get_ebda_ptr()->fdpt[driveid];
+    fdpt->precompensation = 0xffff;
+    fdpt->drive_control_byte = 0xc0 | ((nph > 8) << 3);
+    fdpt->landing_zone = npc;
+    fdpt->cylinders = nlc;
+    fdpt->heads = nlh;
+    fdpt->sectors = nlspt;
+
+    if (nlc == npc && nlh == nph && nlspt == npspt)
+        // no logical CHS mapping used, just physical CHS
+        // use Standard Fixed Disk Parameter Table (FDPT)
+        return;
+
+    // complies with Phoenix style Translated Fixed Disk Parameter
+    // Table (FDPT)
+    fdpt->phys_cylinders = npc;
+    fdpt->phys_heads = nph;
+    fdpt->phys_sectors = npspt;
+    fdpt->a0h_signature = 0xa0;
+
+    // Checksum structure.
+    u8 sum = checksum(fdpt, sizeof(*fdpt)-1);
+    fdpt->checksum = -sum;
+}
+
+// Map a drive (that was registered via add_bcv_hd)
+void
+map_drive(int driveid)
+{
+    // fill hdidmap
+    u8 hdcount = GET_BDA(hdcount);
+    dprintf(3, "Mapping driveid %d to %d\n", driveid, hdcount);
+    SET_GLOBAL(ATA.idmap[0][hdcount], driveid);
+    SET_BDA(hdcount, hdcount + 1);
 
-    // FIXME : should use bios=cmos|auto|disable bits
-    // FIXME : should know about translation bits
-    // FIXME : move hard_drive_post here
+    // Fill "fdpt" structure.
+    fill_fdpt(hdcount);
 }