Change license from GPLv3 to LGPLv3.
[seabios.git] / src / ata.c
index 25327fc173266bb40d1cc00d746a6cbb1aaf92f2..0b0bdc1fd80031de1bca88022870a29529d95c3b 100644 (file)
--- a/src/ata.c
+++ b/src/ata.c
@@ -3,13 +3,19 @@
 // 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 "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_SECTOR_SIZE 512
+#define CDROM_SECTOR_SIZE 2048
+
 #define IDE_TIMEOUT 32000u //32 seconds max for IDE ops
 
-#define DEBUGF1(fmt, args...) bprintf(0, fmt , ##args)
-#define DEBUGF(fmt, args...)
+struct ata_s ATA VAR16_32;
+
 
-// XXX - lots of redundancy in this file.
+/****************************************************************
+ * Helper functions
+ ****************************************************************/
 
+// Wait for the specified ide state
 static int
 await_ide(u8 when_done, 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;
+        u8 status = inb(base+ATA_CB_STAT);
+        u8 result = 0;
         if (when_done == BSY)
             result = status & ATA_CB_STAT_BSY;
         else if (when_done == NOT_BSY)
@@ -45,50 +54,48 @@ await_ide(u8 when_done, u16 base, u16 timeout)
             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);
-        }
+            return status;
         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);
+            dprintf(1, "await_ide: ERROR (TIMEOUT,BSY,!BSY,!BSY_DRQ"
+                    ",!BSY_!DRQ,!BSY_RDY) %d status=%x timeout=%d\n"
+                    , when_done, status, timeout);
             return -1;
         }
-        if ((timeout == 0) || ((time>>11) > timeout))
+        if (rdtscll() >= end)
             break;
     }
-    BX_INFO("IDE time out\n");
-    return -1;
+    dprintf(1, "IDE time out\n");
+    return -2;
 }
 
+// Wait for ide state - pauses for one ata cycle first.
+static __always_inline int
+pause_await_ide(u8 when_done, u16 iobase1, u16 iobase2, u16 timeout)
+{
+    // Wait one PIO transfer cycle.
+    inb(iobase2 + ATA_CB_ASTAT);
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : software reset
-// ---------------------------------------------------------------------------
-// ATA-3
-// 8.2.1 Software reset - Device 0
+    return await_ide(when_done, iobase1, timeout);
+}
 
-void
-ata_reset(u16 device)
+// Wait for ide state - pause for 400ns first.
+static __always_inline int
+ndelay_await_ide(u8 when_done, u16 iobase1, u16 timeout)
 {
-    u16 iobase1, iobase2;
-    u8  channel, slave, sn, sc;
-    u8  type;
-
-    channel = device / 2;
-    slave = device % 2;
+    ndelay(400);
+    return await_ide(when_done, iobase1, timeout);
+}
 
-    iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    iobase2 = GET_EBDA(ata.channels[channel].iobase2);
+// 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);
 
     // Reset
 
@@ -96,565 +103,713 @@ ata_reset(u16 device)
     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);
+    int status = await_ide(BSY, iobase1, 20);
+    dprintf(6, "ata_reset(1) status=%x\n", status);
 
     // 8.2.1 (f) -- clear SRST
     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);
-        }
-
-        // 8.2.1 (h) -- wait for not BSY
-        await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
+    // 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);
+    mdelay(50);
+    u8 sc = inb(iobase1+ATA_CB_SC);
+    u8 sn = inb(iobase1+ATA_CB_SN);
+
+    // For predetermined ATA drives - wait for ready.
+    if (sc==0x01 && sn==0x01) {
+        u8 type=GET_GLOBAL(ATA.devices[driveid].type);
+        if (type == ATA_TYPE_ATA)
+            await_ide(NOT_BSY_RDY, iobase1, IDE_TIMEOUT);
     }
 
+    // 8.2.1 (h) -- wait for not BSY
+    status = await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
+    dprintf(6, "ata_reset(2) status=%x\n", status);
+
     // Enable interrupts
     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
 }
 
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : execute a data-in 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
-u16
-ata_cmd_data_in(u16 device, u16 command, u16 count, u16 cylinder
-                , u16 head, u16 sector, u32 lba, u16 segment, u16 offset)
-{
-    DEBUGF("ata_cmd_data_in d=%d cmd=%d count=%d c=%d h=%d s=%d"
-           " lba=%d seg=%x off=%x\n"
-           , device, command, count, cylinder, head, sector
-           , lba, segment, offset);
+/****************************************************************
+ * ATA send command
+ ****************************************************************/
 
-    u8 channel = device / 2;
-    u8 slave   = device % 2;
+struct ata_pio_command {
+    u8 feature;
+    u8 sector_count;
+    u8 lba_low;
+    u8 lba_mid;
+    u8 lba_high;
+    u8 device;
+    u8 command;
 
-    u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-    u8 mode     = GET_EBDA(ata.devices[device].mode);
+    u8 sector_count2;
+    u8 lba_low2;
+    u8 lba_mid2;
+    u8 lba_high2;
+};
 
-    // Reset count of transferred data
-    SET_EBDA(ata.trsfsectors,0);
-    SET_EBDA(ata.trsfbytes,0L);
-    u8 current = 0;
+// Send an ata command to the drive.
+static int
+send_cmd(int driveid, struct ata_pio_command *cmd)
+{
+    u8 channel = driveid / 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
 
-    u8 status = inb(iobase1 + ATA_CB_STAT);
+    int status = inb(iobase1 + ATA_CB_STAT);
     if (status & ATA_CB_STAT_BSY)
-        return 1;
+        return -3;
 
+    // Disable interrupts
     outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
 
-    // sector will be 0 only on lba access. Convert to lba-chs
-    if (sector == 0) {
-        if ((count >= 1 << 8) || (lba + count >= 1UL << 28)) {
-            outb(0x00, iobase1 + ATA_CB_FR);
-            outb((count >> 8) & 0xff, iobase1 + ATA_CB_SC);
-            outb(lba >> 24, iobase1 + ATA_CB_SN);
-            outb(0, iobase1 + ATA_CB_CL);
-            outb(0, iobase1 + ATA_CB_CH);
-            command |= 0x04;
-            count &= (1UL << 8) - 1;
-            lba &= (1UL << 24) - 1;
-        }
-        sector = (u16) (lba & 0x000000ffL);
-        cylinder = (u16) ((lba>>8) & 0x0000ffffL);
-        head = ((u16) ((lba>>24) & 0x0000000fL)) | ATA_CB_DH_LBA;
+    // Select device
+    u8 device = inb(iobase1 + ATA_CB_DH);
+    outb(cmd->device, iobase1 + ATA_CB_DH);
+    if ((device ^ cmd->device) & (1 << 4))
+        // Wait for device to become active.
+        mdelay(50);
+
+    if (cmd->command & 0x04) {
+        outb(0x00, iobase1 + ATA_CB_FR);
+        outb(cmd->sector_count2, iobase1 + ATA_CB_SC);
+        outb(cmd->lba_low2, iobase1 + ATA_CB_SN);
+        outb(cmd->lba_mid2, iobase1 + ATA_CB_CL);
+        outb(cmd->lba_high2, iobase1 + ATA_CB_CH);
     }
+    outb(cmd->feature, iobase1 + ATA_CB_FR);
+    outb(cmd->sector_count, iobase1 + ATA_CB_SC);
+    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->command, iobase1 + ATA_CB_CMD);
 
-    outb(0x00, iobase1 + ATA_CB_FR);
-    outb(count, iobase1 + ATA_CB_SC);
-    outb(sector, iobase1 + ATA_CB_SN);
-    outb(cylinder & 0x00ff, iobase1 + ATA_CB_CL);
-    outb(cylinder >> 8, iobase1 + ATA_CB_CH);
-    outb((slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0) | (u8) head
-         , iobase1 + ATA_CB_DH);
-    outb(command, iobase1 + ATA_CB_CMD);
-
-    await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
-    status = inb(iobase1 + ATA_CB_STAT);
+    status = ndelay_await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
+    if (status < 0)
+        return status;
 
     if (status & ATA_CB_STAT_ERR) {
-        DEBUGF("ata_cmd_data_in : read error\n");
-        return 2;
-    } else if ( !(status & ATA_CB_STAT_DRQ) ) {
-        DEBUGF("ata_cmd_data_in : DRQ not set (status %02x)\n"
-               , (unsigned) status);
-        return 3;
+        dprintf(6, "send_cmd : read error\n");
+        return -4;
     }
+    if (!(status & ATA_CB_STAT_DRQ)) {
+        dprintf(6, "send_cmd : DRQ not set (status %02x)\n"
+                , (unsigned) status);
+        return -5;
+    }
+
+    return 0;
+}
+
 
-    // FIXME : move seg/off translation here
+/****************************************************************
+ * ATA transfers
+ ****************************************************************/
 
-    irq_enable();
+// Read and discard x number of bytes from an io channel.
+static void
+insx_discard(int mode, int iobase1, int bytes)
+{
+    int count, i;
+    if (mode == ATA_MODE_PIO32) {
+        count = bytes / 4;
+        for (i=0; i<count; i++)
+            inl(iobase1);
+    } else {
+        count = bytes / 2;
+        for (i=0; i<count; i++)
+            inw(iobase1);
+    }
+}
 
-    while (1) {
+// 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 *far_buffer)
+{
+    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, far_buffer);
 
-        if (offset > 0xf800) {
-            offset -= 0x800;
-            segment += 0x80;
+    // Reset count of transferred data
+    SET_EBDA(sector_count, 0);
+
+    u8 channel  = driveid / 2;
+    u16 iobase1 = GET_GLOBAL(ATA.channels[channel].iobase1);
+    u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
+    u8 mode     = GET_GLOBAL(ATA.devices[driveid].mode);
+    int current = 0;
+    int status;
+    for (;;) {
+        int bsize = blocksize;
+        if (skipfirst && current == 0) {
+            insx_discard(mode, iobase1, skipfirst);
+            bsize -= skipfirst;
         }
+        if (skiplast && current == count-1)
+            bsize -= skiplast;
+
+        if (iswrite) {
+            // Write data to controller
+            dprintf(16, "Write sector id=%d dest=%p\n", driveid, far_buffer);
+            if (mode == ATA_MODE_PIO32)
+                outsl_far(iobase1, far_buffer, bsize / 4);
+            else
+                outsw_far(iobase1, far_buffer, bsize / 2);
+        } else {
+            // Read data from controller
+            dprintf(16, "Read sector id=%d dest=%p\n", driveid, far_buffer);
+            if (mode == ATA_MODE_PIO32)
+                insl_far(iobase1, far_buffer, bsize / 4);
+            else
+                insw_far(iobase1, far_buffer, bsize / 2);
+        }
+        far_buffer += bsize;
 
-        if (mode == ATA_MODE_PIO32)
-            insl_seg(iobase1, segment, offset, 512 / 4);
-        else
-            insw_seg(iobase1, segment, offset, 512 / 2);
-        offset += 512;
+        if (skiplast && current == count-1)
+            insx_discard(mode, iobase1, skiplast);
+
+        status = pause_await_ide(NOT_BSY, iobase1, iobase2, IDE_TIMEOUT);
+        if (status < 0)
+            // Error
+            return status;
 
         current++;
-        SET_EBDA(ata.trsfsectors,current);
-        count--;
-        await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
-        status = inb(iobase1 + ATA_CB_STAT);
-        if (count == 0) {
-            if ( (status & (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ
-                            | ATA_CB_STAT_ERR) )
-                 != ATA_CB_STAT_RDY ) {
-                DEBUGF("ata_cmd_data_in : no sectors left (status %02x)\n"
-                       , (unsigned) status);
-                return 4;
-            }
+        SET_EBDA(sector_count, current);
+        if (current == count)
             break;
-        }
-        else {
-            if ( (status & (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ
-                            | ATA_CB_STAT_ERR) )
-                 != (ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ) ) {
-                DEBUGF("ata_cmd_data_in : more sectors left (status %02x)\n"
-                       , (unsigned) status);
-                return 5;
-            }
-            continue;
+        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)) {
+            dprintf(6, "ata_transfer : more sectors left (status %02x)\n"
+                    , (unsigned) status);
+            return -6;
         }
     }
+
+    status &= (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | 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 ) {
+        dprintf(6, "ata_transfer : no sectors left (status %02x)\n"
+                , (unsigned) status);
+        return -7;
+    }
+
     // Enable interrupts
     outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
     return 0;
 }
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : execute a data-out 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
-u16
-ata_cmd_data_out(u16 device, u16 command, u16 count, u16 cylinder
-                 , u16 head, u16 sector, u32 lba, u16 segment, u16 offset)
+static noinline int
+ata_transfer_disk(const struct disk_op_s *op)
 {
-    DEBUGF("ata_cmd_data_out d=%d cmd=%d count=%d c=%d h=%d s=%d"
-           " lba=%d seg=%x off=%x\n"
-           , device, command, count, cylinder, head, sector
-           , lba, segment, offset);
+    return ata_transfer(op->driveid, op->command == ATA_CMD_WRITE_SECTORS
+                        , op->count, IDE_SECTOR_SIZE, 0, 0, op->far_buffer);
+}
 
-    u8 channel = device / 2;
-    u8 slave   = device % 2;
+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->far_buffer);
+}
 
-    u16 iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    u16 iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-    u8 mode     = GET_EBDA(ata.devices[device].mode);
+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->far_buffer);
+    if (ret) {
+        SET_EBDA(sector_count, 0);
+        return ret;
+    }
+    SET_EBDA(sector_count, vcount);
+    return 0;
+}
 
-    // Reset count of transferred data
-    SET_EBDA(ata.trsfsectors,0);
-    SET_EBDA(ata.trsfbytes,0L);
-    u8 current = 0;
 
-    u8 status = inb(iobase1 + ATA_CB_STAT);
-    if (status & ATA_CB_STAT_BSY)
-        return 1;
+/****************************************************************
+ * ATA hard drive functions
+ ****************************************************************/
 
-    outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
+static noinline int
+send_cmd_disk(const struct disk_op_s *op)
+{
+    u8 slave = op->driveid % 2;
+    u64 lba = op->lba;
 
-    // sector will be 0 only on lba access. Convert to lba-chs
-    if (sector == 0) {
-        if ((count >= 1 << 8) || (lba + count >= 1UL << 28)) {
-            outb(0x00, iobase1 + ATA_CB_FR);
-            outb((count >> 8) & 0xff, iobase1 + ATA_CB_SC);
-            outb(lba >> 24, iobase1 + ATA_CB_SN);
-            outb(0, iobase1 + ATA_CB_CL);
-            outb(0, iobase1 + ATA_CB_CH);
-            command |= 0x04;
-            count &= (1UL << 8) - 1;
-            lba &= (1UL << 24) - 1;
-        }
-        sector = (u16) (lba & 0x000000ffL);
-        cylinder = (u16) ((lba>>8) & 0x0000ffffL);
-        head = ((u16) ((lba>>24) & 0x0000000fL)) | ATA_CB_DH_LBA;
+    struct ata_pio_command cmd;
+    memset(&cmd, 0, sizeof(cmd));
+
+    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 = lba >> 32;
+        cmd.lba_high2 = lba >> 40;
+
+        cmd.command |= 0x04;
+        lba &= 0xffffff;
     }
 
-    outb(0x00, iobase1 + ATA_CB_FR);
-    outb(count, iobase1 + ATA_CB_SC);
-    outb(sector, iobase1 + ATA_CB_SN);
-    outb(cylinder & 0x00ff, iobase1 + ATA_CB_CL);
-    outb(cylinder >> 8, iobase1 + ATA_CB_CH);
-    outb((slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0) | (u8) head
-         , iobase1 + ATA_CB_DH);
-    outb(command, iobase1 + ATA_CB_CMD);
+    cmd.feature = 0;
+    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);
 
-    await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
-    status = inb(iobase1 + ATA_CB_STAT);
+    return send_cmd(op->driveid, &cmd);
+}
 
-    if (status & ATA_CB_STAT_ERR) {
-        DEBUGF("ata_cmd_data_out : read error\n");
-        return 2;
-    } else if ( !(status & ATA_CB_STAT_DRQ) ) {
-        DEBUGF("ata_cmd_data_out : DRQ not set (status %02x)\n"
-               , (unsigned) status);
-        return 3;
-    }
+// Read/write count blocks from a harddrive.
+__always_inline int
+ata_cmd_data(struct disk_op_s *op)
+{
+    int ret = send_cmd_disk(op);
+    if (ret)
+        return ret;
+    return ata_transfer_disk(op);
+}
 
-    // FIXME : move seg/off translation here
 
-    irq_enable();
+/****************************************************************
+ * ATAPI functions
+ ****************************************************************/
 
-    while (1) {
+// Low-level atapi command transmit function.
+static __always_inline int
+send_atapi_cmd(int driveid, u8 *cmdbuf, u8 cmdlen, u16 blocksize)
+{
+    u8 channel = driveid / 2;
+    u8 slave = 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 = blocksize;
+    cmd.lba_high = blocksize >> 8;
+    cmd.device = slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0;
+    cmd.command = ATA_CMD_PACKET;
+
+    int ret = send_cmd(driveid, &cmd);
+    if (ret)
+        return ret;
 
-        if (offset > 0xf800) {
-            offset -= 0x800;
-            segment += 0x80;
-        }
+    // Send command to device
+    outsw_far(iobase1, MAKE_FARPTR(GET_SEG(SS), (u32)cmdbuf), cmdlen / 2);
 
-        if (mode == ATA_MODE_PIO32)
-            outsl_seg(iobase1, segment, offset, 512 / 4);
-        else
-            outsw_seg(iobase1, segment, offset, 512 / 2);
-        offset += 512;
+    int status = pause_await_ide(NOT_BSY_DRQ, iobase1, iobase2, IDE_TIMEOUT);
+    if (status < 0)
+        return status;
 
-        current++;
-        SET_EBDA(ata.trsfsectors,current);
-        count--;
-        status = inb(iobase1 + ATA_CB_STAT);
-        if (count == 0) {
-            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_data_out : no sectors left (status %02x)\n"
-                       , (unsigned) status);
-                return 6;
-            }
-            break;
-        } else {
-            if ( (status & (ATA_CB_STAT_BSY | ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ
-                            | ATA_CB_STAT_ERR) )
-                 != (ATA_CB_STAT_RDY | ATA_CB_STAT_DRQ) ) {
-                DEBUGF("ata_cmd_data_out : more sectors left (status %02x)\n"
-                       , (unsigned) status);
-                return 7;
-            }
-            continue;
-        }
-    }
-    // Enable interrupts
-    outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
     return 0;
 }
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : execute a packet command
-// ---------------------------------------------------------------------------
-      // returns
-      // 0 : no error
-      // 1 : error in parameters
-      // 2 : BUSY bit set
-      // 3 : error
-      // 4 : not ready
-u16
-ata_cmd_packet(u16 device, u8 *cmdbuf, u8 cmdlen, u16 header
-               , u32 length, u8 inout, u16 bufseg, u16 bufoff)
+// Low-level cdrom read atapi command transmit function.
+static int
+send_cmd_cdrom(const struct disk_op_s *op)
 {
-    u16 iobase1, iobase2;
-    u16 lcount, lbefore, lafter, count;
-    u8  channel, slave;
-    u8  status, mode, lmode;
-    u32 transfer;
-
-    channel = device / 2;
-    slave = device % 2;
-
-    // Data out is not supported yet
-    if (inout == ATA_DATA_OUT) {
-        BX_INFO("ata_cmd_packet: DATA_OUT not supported yet\n");
-        return 1;
-    }
+    u8 atacmd[12];
+    memset(atacmd, 0, sizeof(atacmd));
 
-    // The header length must be even
-    if (header & 1) {
-        DEBUGF("ata_cmd_packet : header must be even (%04x)\n", header);
-        return 1;
-    }
+    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);
 
-    iobase1 = GET_EBDA(ata.channels[channel].iobase1);
-    iobase2 = GET_EBDA(ata.channels[channel].iobase2);
-    mode    = GET_EBDA(ata.devices[device].mode);
-    transfer= 0L;
+    return send_atapi_cmd(op->driveid, atacmd, sizeof(atacmd)
+                          , CDROM_SECTOR_SIZE);
+}
 
-    if (cmdlen < 12)
-        cmdlen=12;
-    if (cmdlen > 12)
-        cmdlen=16;
-    cmdlen>>=1;
+// Read sectors from the cdrom.
+__always_inline int
+cdrom_read(struct disk_op_s *op)
+{
+    int ret = send_cmd_cdrom(op);
+    if (ret)
+        return ret;
 
-    // Reset count of transferred data
-    SET_EBDA(ata.trsfsectors,0);
-    SET_EBDA(ata.trsfbytes,0L);
+    return ata_transfer_cdrom(op);
+}
 
-    status = inb(iobase1 + ATA_CB_STAT);
-    if (status & ATA_CB_STAT_BSY)
-        return 2;
+// Pretend the cdrom has 512 byte sectors (instead of 2048) and read
+// sectors.
+__always_inline int
+cdrom_read_512(struct disk_op_s *op)
+{
+    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->far_buffer, lba, elba
+            , op->count, before, after);
+
+    int ret = send_cmd_cdrom(op);
+    if (ret)
+        return ret;
+
+    return ata_transfer_cdemu(op, before, after);
+}
 
-    outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2 + ATA_CB_DC);
-    outb(0x00, iobase1 + ATA_CB_FR);
-    outb(0x00, iobase1 + ATA_CB_SC);
-    outb(0x00, iobase1 + ATA_CB_SN);
-    outb(0xfff0 & 0x00ff, iobase1 + ATA_CB_CL);
-    outb(0xfff0 >> 8, iobase1 + ATA_CB_CH);
-    outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1 + ATA_CB_DH);
-    outb(ATA_CMD_PACKET, iobase1 + ATA_CB_CMD);
-
-    // Device should ok to receive command
-    await_ide(NOT_BSY_DRQ, iobase1, IDE_TIMEOUT);
-    status = inb(iobase1 + ATA_CB_STAT);
+// Send a simple atapi command to a drive.
+int
+ata_cmd_packet(int driveid, u8 *cmdbuf, u8 cmdlen
+               , u32 length, void *far_buffer)
+{
+    int ret = send_atapi_cmd(driveid, cmdbuf, cmdlen, length);
+    if (ret)
+        return ret;
 
-    if (status & ATA_CB_STAT_ERR) {
-        DEBUGF("ata_cmd_packet : error, status is %02x\n", status);
-        return 3;
-    } else if ( !(status & ATA_CB_STAT_DRQ) ) {
-        DEBUGF("ata_cmd_packet : DRQ not set (status %02x)\n"
-               , (unsigned) status);
-        return 4;
-    }
+    return ata_transfer(driveid, 0, 1, length, 0, 0, far_buffer);
+}
 
-    // Send command to device
-    irq_enable();
 
-    outsw_seg(iobase1, GET_SEG(SS), (u32)cmdbuf, cmdlen);
+/****************************************************************
+ * ATA detect and init
+ ****************************************************************/
 
-    if (inout == ATA_DATA_NO) {
-        await_ide(NOT_BSY, iobase1, IDE_TIMEOUT);
-        status = inb(iobase1 + ATA_CB_STAT);
-    } else {
-        u16 loops = 0;
-        u8 sc;
-        while (1) {
-
-            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);
-            sc = 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;
+static void
+report_model(int driveid, u8 *buffer)
+{
+    u8 model[41];
 
-            if (status & ATA_CB_STAT_ERR) {
-                DEBUGF("ata_cmd_packet : error (status %02x)\n", status);
-                return 3;
-            }
-
-            // Normalize address
-            bufseg += (bufoff / 16);
-            bufoff %= 16;
-
-            // Get the byte count
-            lcount =  ((u16)(inb(iobase1 + ATA_CB_CH))<<8)+inb(iobase1 + ATA_CB_CL);
-
-            // adjust to read what we want
-            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
-            count = lcount;
-
-            DEBUGF("Trying to read %04x bytes (%04x %04x %04x) "
-                   , lbefore+lcount+lafter, lbefore, lcount, lafter);
-            DEBUGF("to 0x%04x:0x%04x\n", bufseg, bufoff);
-
-            // If counts not dividable by 4, use 16bits mode
-            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_seg(iobase1, bufseg, bufoff, lcount);
-            else
-                insw_seg(iobase1, bufseg, bufoff, lcount);
+    // Read model name
+    int i;
+    for (i=0; i<40; i+=2) {
+        model[i] = buffer[i+54+1];
+        model[i+1] = buffer[i+54];
+    }
 
-            for (i=0; i<lafter; i++)
-                if (lmode == ATA_MODE_PIO32)
-                    inl(iobase1);
-                else
-                    inw(iobase1);
+    // Reformat
+    model[40] = 0x00;
+    for (i=39; i>0; i--) {
+        if (model[i] != 0x20)
+            break;
+        model[i] = 0x00;
+    }
 
-            // Compute new buffer address
-            bufoff += count;
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    // XXX - model on stack not %cs
+    printf("ata%d %s: %s", channel, slave ? " slave" : "master", model);
+}
 
-            // Save transferred bytes count
-            transfer += count;
-            SET_EBDA(ata.trsfbytes,transfer);
-        }
-    }
+static u8
+get_ata_version(u8 *buffer)
+{
+    u16 ataversion = *(u16*)&buffer[160];
+    u8 version;
+    for (version=15; version>0; version--)
+        if (ataversion & (1<<version))
+            break;
+    return version;
+}
 
-    // 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;
-    }
+static void
+init_drive_atapi(int driveid)
+{
+    SET_GLOBAL(ATA.devices[driveid].type, ATA_TYPE_ATAPI);
 
-    // Enable interrupts
-    outb(ATA_CB_DC_HD15, iobase2+ATA_CB_DC);
-    return 0;
+    // Temporary values to do the transfer
+    SET_GLOBAL(ATA.devices[driveid].device,ATA_DEVICE_CDROM);
+    SET_GLOBAL(ATA.devices[driveid].mode, ATA_MODE_PIO16);
+
+    // Now we send a IDENTIFY command to ATAPI device
+    u8 buffer[0x0200];
+    memset(buffer, 0, sizeof(buffer));
+    struct disk_op_s dop;
+    dop.driveid = driveid;
+    dop.command = ATA_CMD_IDENTIFY_DEVICE_PACKET;
+    dop.count = 1;
+    dop.lba = 1;
+    dop.far_buffer = MAKE_FARPTR(GET_SEG(SS), (u32)buffer);
+    u16 ret = ata_cmd_data(&dop);
+    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  = CDROM_SECTOR_SIZE;
+
+    SET_GLOBAL(ATA.devices[driveid].device, type);
+    SET_GLOBAL(ATA.devices[driveid].removable, removable);
+    SET_GLOBAL(ATA.devices[driveid].mode, mode);
+    SET_GLOBAL(ATA.devices[driveid].blksize, blksize);
+
+    // fill cdidmap
+    u8 cdcount = GET_GLOBAL(ATA.cdcount);
+    SET_GLOBAL(ATA.idmap[1][cdcount], driveid);
+    SET_GLOBAL(ATA.cdcount, ++cdcount);
+
+    report_model(driveid, buffer);
+    u8 version = get_ata_version(buffer);
+    if (GET_GLOBAL(ATA.devices[driveid].device)==ATA_DEVICE_CDROM)
+        printf(" ATAPI-%d CD-Rom/DVD-Rom\n", version);
+    else
+        printf(" ATAPI-%d Device\n", version);
 }
 
-u16
-cdrom_read(u16 device, u32 lba, u32 count, u16 segment, u16 offset, u16 skip)
+static void
+fill_fdpt(int driveid)
 {
-    u16 sectors = (count + 2048 - 1) / 2048;
+    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 extended_bios_data_area_s *ebda = get_ebda_ptr();
+    ebda->fdpt[driveid].precompensation = 0xffff;
+    ebda->fdpt[driveid].drive_control_byte = 0xc0 | ((nph > 8) << 3);
+    ebda->fdpt[driveid].landing_zone = npc;
+    ebda->fdpt[driveid].cylinders = nlc;
+    ebda->fdpt[driveid].heads = nlh;
+    ebda->fdpt[driveid].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)
+    ebda->fdpt[driveid].phys_cylinders = npc;
+    ebda->fdpt[driveid].phys_heads = nph;
+    ebda->fdpt[driveid].phys_sectors = npspt;
+    ebda->fdpt[driveid].a0h_signature = 0xa0;
+
+    // Checksum structure.
+    u8 sum = checksum((u8*)&ebda->fdpt[driveid], sizeof(ebda->fdpt[driveid])-1);
+    ebda->fdpt[driveid].checksum = -sum;
+}
 
-    u8 atacmd[12];
-    memset(atacmd, 0, sizeof(atacmd));
-    atacmd[0]=0x28;                      // READ command
-    atacmd[7]=(sectors & 0xff00) >> 8;   // Sectors
-    atacmd[8]=(sectors & 0x00ff);        // Sectors
-    atacmd[2]=(lba & 0xff000000) >> 24;  // LBA
-    atacmd[3]=(lba & 0x00ff0000) >> 16;
-    atacmd[4]=(lba & 0x0000ff00) >> 8;
-    atacmd[5]=(lba & 0x000000ff);
-
-    return ata_cmd_packet(device, atacmd, sizeof(atacmd)
-                          , skip, count, ATA_DATA_IN
-                          , segment, offset);
+static u8
+get_translation(int driveid)
+{
+    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;
+    }
+
+    // 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);
+
+    if (cylinders <= 1024 && heads <= 16 && spt <= 63)
+        return ATA_TRANSLATION_NONE;
+    if (cylinders * heads <= 131072)
+        return ATA_TRANSLATION_LARGE;
+    return ATA_TRANSLATION_LBA;
 }
 
-// ---------------------------------------------------------------------------
-// ATA/ATAPI driver : device detection
-// ---------------------------------------------------------------------------
+static void
+setup_translation(int driveid)
+{
+    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:
+        dprintf(1, "none");
+        break;
+    case ATA_TRANSLATION_LBA:
+        dprintf(1, "lba");
+        spt = 63;
+        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)
+            heads = 128;
+        else if (heads>32)
+            heads = 64;
+        else if (heads>16)
+            heads = 32;
+        else
+            heads = 16;
+        cylinders = sect / heads;
+        break;
+    case ATA_TRANSLATION_RECHS:
+        dprintf(1, "r-echs");
+        // Take care not to overflow
+        if (heads==16) {
+            if (cylinders>61439)
+                cylinders=61439;
+            heads=15;
+            cylinders = (u16)((u32)(cylinders)*16/15);
+        }
+        // then go through the large bitshift process
+    case ATA_TRANSLATION_LARGE:
+        if (translation == ATA_TRANSLATION_LARGE)
+            dprintf(1, "large");
+        while (cylinders > 1024) {
+            cylinders >>= 1;
+            heads <<= 1;
+
+            // If we max out the head count
+            if (heads > 127)
+                break;
+        }
+        break;
+    }
+    // clip to 1024 cylinders in lchs
+    if (cylinders > 1024)
+        cylinders = 1024;
+    dprintf(1, " LCHS=%d/%d/%d\n", cylinders, heads, 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);
+}
 
-void
-ata_detect()
+static void
+init_drive_ata(int driveid)
 {
-    u8  hdcount, cdcount, device, type;
-    u8  buffer[0x0200];
-    memset(buffer, 0, sizeof(buffer));
+    SET_GLOBAL(ATA.devices[driveid].type, ATA_TYPE_ATA);
 
-#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
+    // Temporary values to do the transfer
+    SET_GLOBAL(ATA.devices[driveid].device, ATA_DEVICE_HD);
+    SET_GLOBAL(ATA.devices[driveid].mode, ATA_MODE_PIO16);
 
-    // Device detection
-    hdcount=cdcount=0;
+    // Now we send a IDENTIFY command to ATA device
+    u8 buffer[0x0200];
+    memset(buffer, 0, sizeof(buffer));
+    struct disk_op_s dop;
+    dop.driveid = driveid;
+    dop.command = ATA_CMD_IDENTIFY_DEVICE;
+    dop.count = 1;
+    dop.lba = 1;
+    dop.far_buffer = MAKE_FARPTR(GET_SEG(SS), (u32)buffer);
+    u16 ret = ata_cmd_data(&dop);
+    if (ret)
+        BX_PANIC("ata-detect: Failed to detect ATA device\n");
+
+    u8 removable  = (buffer[0] & 0x80) ? 1 : 0;
+    u8 mode       = buffer[48*2] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
+    u16 blksize   = IDE_SECTOR_SIZE;
+
+    u16 cylinders = *(u16*)&buffer[1*2]; // word 1
+    u16 heads     = *(u16*)&buffer[3*2]; // word 3
+    u16 spt       = *(u16*)&buffer[6*2]; // word 6
+
+    u64 sectors;
+    if (*(u16*)&buffer[83*2] & (1 << 10)) // word 83 - lba48 support
+        sectors = *(u64*)&buffer[100*2]; // word 100-103
+    else
+        sectors = *(u32*)&buffer[60*2]; // word 60 and word 61
+
+    SET_GLOBAL(ATA.devices[driveid].device, ATA_DEVICE_HD);
+    SET_GLOBAL(ATA.devices[driveid].removable, removable);
+    SET_GLOBAL(ATA.devices[driveid].mode, mode);
+    SET_GLOBAL(ATA.devices[driveid].blksize, blksize);
+    SET_GLOBAL(ATA.devices[driveid].pchs.heads, heads);
+    SET_GLOBAL(ATA.devices[driveid].pchs.cylinders, cylinders);
+    SET_GLOBAL(ATA.devices[driveid].pchs.spt, spt);
+    SET_GLOBAL(ATA.devices[driveid].sectors, sectors);
+
+    // Setup disk geometry translation.
+    setup_translation(driveid);
+
+    // fill hdidmap
+    u8 hdcount = GET_BDA(hdcount);
+    SET_GLOBAL(ATA.idmap[0][hdcount], driveid);
+    SET_BDA(hdcount, ++hdcount);
+
+    // Fill "fdpt" structure.
+    fill_fdpt(driveid);
+
+    // Report drive info to user.
+    u64 sizeinmb = GET_GLOBAL(ATA.devices[driveid].sectors) >> 11;
+    report_model(driveid, buffer);
+    u8 version = get_ata_version(buffer);
+    if (sizeinmb < (1 << 16))
+        printf(" ATA-%d Hard-Disk (%u MiBytes)\n", version, (u32)sizeinmb);
+    else
+        printf(" ATA-%d Hard-Disk (%u GiBytes)\n", version
+               , (u32)(sizeinmb >> 10));
+}
 
-    for(device=0; device<CONFIG_MAX_ATA_DEVICES; device++) {
-        u16 iobase1, iobase2;
-        u8  channel, slave, shift;
-        u8  sc, sn, cl, ch, st;
+static void
+init_drive_unknown(int driveid)
+{
+    SET_GLOBAL(ATA.devices[driveid].type, ATA_TYPE_UNKNOWN);
 
-        channel = device / 2;
-        slave = device % 2;
+    u8 channel = driveid / 2;
+    u8 slave = driveid % 2;
+    printf("ata%d %s: Unknown device\n", channel, slave ? " slave" : "master");
+}
 
-        iobase1 =GET_EBDA(ata.channels[channel].iobase1);
-        iobase2 =GET_EBDA(ata.channels[channel].iobase2);
+static void
+ata_detect()
+{
+    // Device detection
+    int driveid;
+    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);
+        u16 iobase2 = GET_GLOBAL(ATA.channels[channel].iobase2);
+        if (!iobase1)
+            break;
 
         // Disable interrupts
         outb(ATA_CB_DC_HD15 | ATA_CB_DC_NIEN, iobase2+ATA_CB_DC);
 
         // Look for device
         outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
+        mdelay(50);
         outb(0x55, iobase1+ATA_CB_SC);
         outb(0xaa, iobase1+ATA_CB_SN);
         outb(0xaa, iobase1+ATA_CB_SC);
@@ -663,238 +818,109 @@ ata_detect()
         outb(0xaa, iobase1+ATA_CB_SN);
 
         // If we found something
-        sc = inb(iobase1+ATA_CB_SC);
-        sn = inb(iobase1+ATA_CB_SN);
-
-        if ( (sc == 0x55) && (sn == 0xaa) ) {
-            SET_EBDA(ata.devices[device].type,ATA_TYPE_UNKNOWN);
-
-            // reset the channel
-            ata_reset(device);
-
-            // 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)) {
-                cl = inb(iobase1+ATA_CB_CL);
-                ch = inb(iobase1+ATA_CB_CH);
-                st = inb(iobase1+ATA_CB_STAT);
-
-                if ((cl==0x14) && (ch==0xeb)) {
-                    SET_EBDA(ata.devices[device].type,ATA_TYPE_ATAPI);
-                } else if ((cl==0x00) && (ch==0x00) && (st!=0x00)) {
-                    SET_EBDA(ata.devices[device].type,ATA_TYPE_ATA);
-                } else if ((cl==0xff) && (ch==0xff)) {
-                    SET_EBDA(ata.devices[device].type,ATA_TYPE_NONE);
-                }
-            }
-        }
+        u8 sc = inb(iobase1+ATA_CB_SC);
+        u8 sn = inb(iobase1+ATA_CB_SN);
+        dprintf(6, "ata_detect(1) drive=%d sc=%x sn=%x\n", driveid, sc, sn);
 
-        type=GET_EBDA(ata.devices[device].type);
-
-        // Now we send a IDENTIFY command to ATA device
-        if(type == ATA_TYPE_ATA) {
-            u32 sectors;
-            u16 cylinders, heads, spt, blksize;
-            u8  translation, removable, mode;
-
-            //Temporary values to do the transfer
-            SET_EBDA(ata.devices[device].device,ATA_DEVICE_HD);
-            SET_EBDA(ata.devices[device].mode, ATA_MODE_PIO16);
-
-            u16 ret = ata_cmd_data_in(device,ATA_CMD_IDENTIFY_DEVICE
-                                      , 1, 0, 0, 0, 0L
-                                      , GET_SEG(SS), (u32)buffer);
-            if (ret)
-                BX_PANIC("ata-detect: Failed to detect ATA device\n");
-
-            removable = (buffer[0] & 0x80) ? 1 : 0;
-            mode      = buffer[96] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
-            blksize   = *(u16*)&buffer[10];
-
-            cylinders = *(u16*)&buffer[1*2]; // word 1
-            heads     = *(u16*)&buffer[3*2]; // word 3
-            spt       = *(u16*)&buffer[6*2]; // word 6
-
-            sectors   = *(u32*)&buffer[60*2]; // word 60 and word 61
-
-            SET_EBDA(ata.devices[device].device,ATA_DEVICE_HD);
-            SET_EBDA(ata.devices[device].removable, removable);
-            SET_EBDA(ata.devices[device].mode, mode);
-            SET_EBDA(ata.devices[device].blksize, blksize);
-            SET_EBDA(ata.devices[device].pchs.heads, heads);
-            SET_EBDA(ata.devices[device].pchs.cylinders, cylinders);
-            SET_EBDA(ata.devices[device].pchs.spt, spt);
-            SET_EBDA(ata.devices[device].sectors, sectors);
-            BX_INFO("ata%d-%d: PCHS=%u/%d/%d translation=", channel, slave,cylinders, heads, spt);
-
-            translation = inb_cmos(CMOS_BIOS_DISKTRANSFLAG + channel/2);
-            for (shift=device%4; shift>0; shift--)
-                translation >>= 2;
-            translation &= 0x03;
-
-            SET_EBDA(ata.devices[device].translation, translation);
-
-            switch (translation) {
-            case ATA_TRANSLATION_NONE:
-                BX_INFO("none");
-                break;
-            case ATA_TRANSLATION_LBA:
-                BX_INFO("lba");
-                break;
-            case ATA_TRANSLATION_LARGE:
-                BX_INFO("large");
-                break;
-            case ATA_TRANSLATION_RECHS:
-                BX_INFO("r-echs");
-                break;
-            }
-            switch (translation) {
-            case ATA_TRANSLATION_NONE:
-                break;
-            case ATA_TRANSLATION_LBA:
-                spt = 63;
-                sectors /= 63;
-                heads = sectors / 1024;
-                if (heads>128) heads = 255;
-                else if (heads>64) heads = 128;
-                else if (heads>32) heads = 64;
-                else if (heads>16) heads = 32;
-                else heads=16;
-                cylinders = sectors / heads;
-                break;
-            case ATA_TRANSLATION_RECHS:
-                // Take care not to overflow
-                if (heads==16) {
-                    if(cylinders>61439) cylinders=61439;
-                    heads=15;
-                    cylinders = (u16)((u32)(cylinders)*16/15);
-                }
-                // then go through the large bitshift process
-            case ATA_TRANSLATION_LARGE:
-                while(cylinders > 1024) {
-                    cylinders >>= 1;
-                    heads <<= 1;
-
-                    // If we max out the head count
-                    if (heads > 127) break;
-                }
-                break;
-            }
-            // clip to 1024 cylinders in lchs
-            if (cylinders > 1024)
-                cylinders=1024;
-            BX_INFO(" LCHS=%d/%d/%d\n", cylinders, heads, spt);
-
-            SET_EBDA(ata.devices[device].lchs.heads, heads);
-            SET_EBDA(ata.devices[device].lchs.cylinders, cylinders);
-            SET_EBDA(ata.devices[device].lchs.spt, spt);
-
-            // fill hdidmap
-            SET_EBDA(ata.idmap[0][hdcount], device);
-            hdcount++;
-        }
+        if (sc != 0x55 || sn != 0xaa)
+            continue;
 
-        // Now we send a IDENTIFY command to ATAPI device
-        if(type == ATA_TYPE_ATAPI) {
+        // reset the channel
+        ata_reset(driveid);
 
-            u8  type, removable, mode;
-            u16 blksize;
+        // check for ATA or ATAPI
+        outb(slave ? ATA_CB_DH_DEV1 : ATA_CB_DH_DEV0, iobase1+ATA_CB_DH);
+        mdelay(50);
+        sc = inb(iobase1+ATA_CB_SC);
+        sn = inb(iobase1+ATA_CB_SN);
+        dprintf(6, "ata_detect(2) drive=%d sc=%x sn=%x\n", driveid, sc, sn);
+        if (sc!=0x01 || sn!=0x01) {
+            init_drive_unknown(driveid);
+            continue;
+        }
+        u8 cl = inb(iobase1+ATA_CB_CL);
+        u8 ch = inb(iobase1+ATA_CB_CH);
+        u8 st = inb(iobase1+ATA_CB_STAT);
+        dprintf(6, "ata_detect(3) drive=%d sc=%x sn=%x cl=%x ch=%x st=%x\n"
+                , driveid, sc, sn, cl, ch, st);
+
+        if (cl==0x14 && ch==0xeb)
+            init_drive_atapi(driveid);
+        else if (cl==0x00 && ch==0x00 && st!=0x00)
+            init_drive_ata(driveid);
+        else if (cl==0xff && ch==0xff)
+            // None
+            continue;
+        else
+            init_drive_unknown(driveid);
+    }
 
-            //Temporary values to do the transfer
-            SET_EBDA(ata.devices[device].device,ATA_DEVICE_CDROM);
-            SET_EBDA(ata.devices[device].mode, ATA_MODE_PIO16);
+    printf("\n");
+}
 
-            u16 ret = ata_cmd_data_in(device,ATA_CMD_IDENTIFY_DEVICE_PACKET
-                                      , 1, 0, 0, 0, 0L
-                                      , GET_SEG(SS), (u32)buffer);
-            if (ret != 0)
-                BX_PANIC("ata-detect: Failed to detect ATAPI device\n");
+static void
+ata_init()
+{
+    // 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);
+    }
 
-            type      = buffer[1] & 0x1f;
-            removable = (buffer[0] & 0x80) ? 1 : 0;
-            mode      = buffer[96] ? ATA_MODE_PIO32 : ATA_MODE_PIO16;
-            blksize   = 2048;
+    // 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;
 
-            SET_EBDA(ata.devices[device].device, type);
-            SET_EBDA(ata.devices[device].removable, removable);
-            SET_EBDA(ata.devices[device].mode, mode);
-            SET_EBDA(ata.devices[device].blksize, blksize);
+        u8 irq = pci_config_readb(bdf, PCI_INTERRUPT_LINE);
+        SET_GLOBAL(ATA.channels[count].irq, irq);
+        SET_GLOBAL(ATA.channels[count].pci_bdf, bdf);
 
-            // fill cdidmap
-            SET_EBDA(ata.idmap[1][cdcount], device);
-            cdcount++;
-        }
+        u8 prog_if = pci_config_readb(bdf, PCI_CLASS_PROG);
+        u32 port1, port2;
 
-        u32 sizeinmb = 0;
-        u16 ataversion;
-        u8  c, i, version=0, model[41];
-
-        switch (type) {
-        case ATA_TYPE_ATA:
-            sizeinmb = GET_EBDA(ata.devices[device].sectors);
-            sizeinmb >>= 11;
-        case ATA_TYPE_ATAPI:
-            // Read ATA/ATAPI version
-            ataversion=((u16)(buffer[161])<<8) | buffer[160];
-            for(version=15;version>0;version--) {
-                if ((ataversion&(1<<version))!=0)
-                    break;
-            }
-
-            // Read model name
-            for (i=0;i<20;i++) {
-                model[i*2] = buffer[(i*2)+54+1];
-                model[(i*2)+1] = buffer[(i*2)+54];
-            }
-
-            // Reformat
-            model[40] = 0x00;
-            for (i=39;i>0;i--) {
-                if (model[i]==0x20)
-                    model[i] = 0x00;
-                else
-                    break;
-            }
-            break;
+        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;
         }
-
-        switch (type) {
-        case ATA_TYPE_ATA:
-            printf("ata%d %s: ",channel,slave?" slave":"master");
-            i=0;
-            while ((c=model[i++]))
-                printf("%c",c);
-            if (sizeinmb < (1UL<<16))
-                printf(" ATA-%d Hard-Disk (%u MBytes)\n", version, (u16)sizeinmb);
-            else
-                printf(" ATA-%d Hard-Disk (%u GBytes)\n", version, (u16)(sizeinmb>>10));
-            break;
-        case ATA_TYPE_ATAPI:
-            printf("ata%d %s: ",channel,slave?" slave":"master");
-            i=0;
-            while ((c=model[i++]))
-                printf("%c",c);
-            if (GET_EBDA(ata.devices[device].device)==ATA_DEVICE_CDROM)
-                printf(" ATAPI-%d CD-Rom/DVD-Rom\n",version);
-            else
-                printf(" ATAPI-%d Device\n",version);
-            break;
-        case ATA_TYPE_UNKNOWN:
-            printf("ata%d %s: Unknown device\n",channel,slave?" slave":"master");
-            break;
+        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 devices counts
-    SET_EBDA(ata.hdcount, hdcount);
-    SET_EBDA(ata.cdcount, cdcount);
-    SET_BDA(disk_count, 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);
 
-    // FIXME : should use bios=cmos|auto|disable bits
-    // FIXME : should know about translation bits
-    // FIXME : move hard_drive_post here
+    enable_hwirq(14, entry_76);
 }