Skip to content

IDEDisk Driver

opencode edited this page Nov 15, 2026 · 7 revisions

IDEDisk Driver

JNode's primary IDE/ATA disk driver providing block-level access to PATA devices via LBA addressing with both PIO and DMA transfer modes.

Overview

The IDEDiskDriver is a critical JNode driver that manages Parallel ATA (PATA) disk devices. It extends the Driver class and implements the IDEDeviceAPI, providing the bridge between JNode's block device layer and hardware IDE controllers. The driver supports both 28-bit and 48-bit LBA addressing, enabling access to disks larger than 128GB.

Key Components

File Purpose
fs/src/driver/org/jnode/driver/block/ide/disk/IDEDiskDriver.java Main driver class
fs/src/driver/org/jnode/driver/block/ide/disk/IDEDiskPartitionDevice.java Partition device representation
fs/src/driver/org/jnode/driver/block/ide/disk/IDEDiskPartitionDriver.java Partition driver
fs/src/driver/org/jnode/driver/bus/ide/IDEBus.java Command queue processing bus
fs/src/driver/org/jnode/driver/bus/ide/DefaultIDEIO.java Register/status I/O and deadline-based waitUntilStatus
fs/src/driver/org/jnode/driver/bus/ide/IDEConstants.java ATA register definitions, commands, timeouts
fs/src/driver/org/jnode/driver/bus/ide/command/IDERWSectorsCommand.java Read/write sector commands, DRQ polling and error mapping
fs/src/driver/org/jnode/driver/bus/ide/command/IDEWriteMultipleFUACommand.java WRITE MULTIPLE FUA EXT (0xCE)
fs/src/driver/org/jnode/driver/bus/ide/command/IDEFlushCacheCommand.java FLUSH CACHE / FLUSH CACHE EXT barrier
fs/src/driver/org/jnode/driver/bus/ide/IDEDriveDescriptor.java Drive identification data, FUA/multiple-mode capability

How It Works

Device Startup

When startDevice() is called, the driver:

  1. Creates an IDEDiskBus (internal Bus subclass) wrapping the IDEDevice
  2. Reads the MBR boot sector via LBA sector 0
  3. Creates an IBMPartitionTable from the boot sector
  4. Registers partition devices for each valid partition entry
  5. Handles extended partitions by iterating through chained partition tables
protected void startDevice() throws DriverException {
    final IDEDevice dev = (IDEDevice) getDevice();
    diskBus = new IDEDiskBus(dev);
    dev.registerAPI(IDEDeviceAPI.class,
        new IDEDeviceBlockAlignmentSupport<IBMPartitionTableEntry>(this, SECTOR_SIZE));

    final IDEDriveDescriptor descr = dev.getDescriptor();
    is48bit = descr.supports48bitAddressing();
    maxSector = descr.getSectorsAddressable();

    // Read boot sector, create partition table, register partitions
    final byte[] bs = new byte[SECTOR_SIZE];
    read(0, ByteBuffer.wrap(bs));
    this.pt = factory.createIBMPartitionTable(bs, dev);
    // ... register partitions
}

Data Transfer

The transfer() method handles block reads/writes with the following flow:

  1. Validates offset/length alignment to 512-byte sector boundaries
  2. Splits large transfers into chunks respecting the maximum sector count:
    • 256 sectors for 28-bit addressing
    • 65536 sectors for 48-bit addressing
  3. Creates IDEReadSectorsCommand or IDEWriteSectorsCommand for each chunk
  4. Executes commands via bus.executeAndWait() with a 10-second timeout
  5. Handles errors by throwing IOException
protected void transfer(long devOffset, ByteBuffer buf, boolean isWrite) throws IOException {
    final long lbaStart = devOffset / SECTOR_SIZE;
    final int sectors = length / SECTOR_SIZE;
    final int maxSectorCount = is48bit ? MAX_SECTOR_COUNT_48 : MAX_SECTOR_COUNT_28;

    while (length > 0) {
        final int partSectorCount = Math.min(length / SECTOR_SIZE, maxSectorCount);
        final IDERWSectorsCommand cmd = isWrite ?
            new IDEWriteSectorsCommand(primary, master, is48bit, partLbaStart, partSectorCount, buf) :
            new IDEReadSectorsCommand(primary, master, is48bit, partLbaStart, partSectorCount, buf);
        bus.executeAndWait(cmd, IDE_DATA_XFER_TIMEOUT);
        // ...
    }
}

Command Queue Architecture

IDEBus manages a QueueProcessorThread that sequentially processes IDE commands:

  • Commands are added via execute(command)
  • Synchronous wait via executeAndWait(command, timeout)
  • IRQ handler (handleInterrupt) signals command completion
  • Software reset via softwareReset() if commands timeout

ATA Register Interface

IDEConstants defines all ATA register offsets and command codes:

Register Offset Purpose
Data 0x1F0/0x170 16-bit data I/O
Error/Feature 1 Read errors, write features
Sector Count 2 Number of sectors (LBA low)
LBA Low 3 LBA bits 0-7
LBA Mid 4 LBA bits 8-15
LBA High 5 LBA bits 16-23
Drive/Head 6 Drive selection, LBA bit 24-27
Status/Command 7 Read status, write commands

LBA Addressing Modes

28-bit LBA: Uses Drive/Head register for LBA bits 24-27

io.setSelectReg(SEL_LBA | getSelect() | ((int)(lbaStart >> 24) & 0xF));

48-bit LBA: Writes registers twice (high then low)

io.setSectorCountReg((sectorCount >> 8) & 0xFF); // high byte
io.setLbaLowReg((int)((lbaStart >> 24) & 0xFF));
// ... more high bytes ...
io.setSectorCountReg((sectorCount >> 0) & 0xFF); // low byte
io.setLbaLowReg((int)((lbaStart >> 0) & 0xFF));
// ... more low bytes ...

Gotchas

  1. Double boot sector read: The driver reads sector 0 twice as a workaround for an unknown first-read failure (IDEDiskDriver.java:106-112). The exact cause is unclear but may relate to controller initialization.

  2. Partition unregistration on stop: stopDevice() manually iterates the device manager to find and unregister partition children, rather than using a hierarchical shutdown mechanism.

  3. DMA mode disabled: DMA support is commented out in the codebase (//dma = descr.supportsDMA()). The driver currently uses PIO mode exclusively, despite having DMA command definitions in IDEConstants (e.g., CMD_READDMA, CMD_WRITEDMA).

  4. Command timeout handling: waitUntilFinished() relies on the queue-processor thread completing the command; on timeout IDEBus sets ERR_ABORT and resets the bus. A controller left busy can still affect later commands.

  5. Error mapping is now sector-aware: a mid-transfer error is reported with the chunk LBA plus failedSector. getFailedSector() returns -1 when no sector was recorded.

  6. Write-back is the default: with neither jnode.ide.writethrough nor jnode.ide.fua set, a write returns before the data is durable. Use sync, unmount, or close the file handle to reach FLUSH CACHE.

  7. jnode.ide.fua is independent of write-through. The .github/qemu/jnode.properties comment is stale: it says FUA has no effect when writethrough=false, but the driver resolves FUA whenever jnode.ide.fua=true, and an unavailable FUA request forces a per-write flush.

  8. waitUntilStatus() always fast-fails on ST_ERROR, regardless of the requested mask/value, and reads the alternate status twice per iteration.

Write-Back Default and Barriers (2026-11)

IDEDiskDriver.writeThrough now defaults to false. The properties are parsed strictly:

writeThrough = "true".equals(
    VmIOContext.getGlobalProperties().getProperty("jnode.ide.writethrough"));
fuaRequested = "true".equals(
    VmIOContext.getGlobalProperties().getProperty("jnode.ide.fua"));
Setting Per-write behaviour
default (writethrough=false, fua=false) bare WRITE, no per-write FLUSH
jnode.ide.writethrough=true WRITE, then one flush() after the whole transfer loop
jnode.ide.fua=true and device supports FUA WRITE MULTIPLE FUA EXT (0xCE), no flush
jnode.ide.fua=true but FUA unavailable/rejected write-back, but fuaRequested forces a per-write flush() (fail-closed)

enableFua() requires ATA, 48-bit addressing, word 84 bit 14 set with bit 15 clear and bit 6 set, and multiple mode enabled (IDESetMultipleModeCommand with sector count 1 if needed). supportsFUA() is the capability check.

flush() uses IDEFlushCacheCommand → CMD_FLUSH_CACHE_EXT on 48-bit devices, else CMD_FLUSH_CACHE; it waits for ST_BUSY=0 and checks ST_ERROR/ST_DEVICE_FAULT.

Durability barriers are:

  • FileHandleImpl.close() → FSFile.flush() → BlockDeviceAPI.flush()
  • AbstractFileSystem.close() / FatFileSystem.flush()
  • the sync shell command
  • stopDevice()

Everything written since the last barrier is lost on power failure. A write-through flush happens once at the end of the split transfer loop, not between 48-bit chunks.

Sync Command

shell/src/shell/org/jnode/shell/command/driver/system/SyncCommand.java exposes:

sync

It flushes all dirty file buffers, the mounted filesystems and then the block device, issuing FLUSH CACHE to the controller.

Unmount Command

shell/src/shell/org/jnode/shell/command/driver/system/UmountCommand.java:

umount /devices/hdb1

It flushes dirty buffers, issues FLUSH CACHE, then unmounts the filesystem from the VFS.

Event-Driven Wait (2026-11)

The 2026-08 full-polling design has been replaced for synchronous command waits. The scheduler-pump daemon and the masked-IRQ setup remain, but executeAndWait() no longer sleep-polls.

Before and after

  • Before: IDEBus.executeAndWait() did execute(command), then looped Thread.sleep(20) while polling command.isFinished(). DefaultIDEIO.waitUntilStatus() slept 10 ms per poll.
  • Now: executeAndWait() calls execute(), returns immediately if command.isFinished(), otherwise calls command.waitUntilFinished(timeout). IDECommand extends org.jnode.util.Command; notifyFinished() is synchronized and notifyAll()s, and waitUntilFinished() loops on wait(timeout) with a deadline re-check.

The queue processor runs cmd.setup(...) itself and commands call notifyFinished()/setError() from setup, so completion no longer depends on IRQ delivery or a scheduler reschedule. setError() also notifies.

DefaultIDEIO.waitUntilStatus(mask, value, timeout, message) now:

  • computes an absolute deadline and re-reads the alternate status each iteration
  • fast-fails on ST_ERROR with TimeoutException("IDE error " + hex(errorReg))
  • escalates from Thread.yield() (< 1 ms) to 1 ms sleeps (< 10 ms) to 10 ms sleeps
  • costs one status read and no sleep when the condition is already satisfied

This removes the expected ~10 ms per synchronous command. Waits remain bounded by IDE_DATA_XFER_TIMEOUT (10 s, or 1 s for IDE_TIMEOUT).

DRQ and sector error mapping (2026-11)

The old PIO path waited only for BSY=0 and then blindly transferred 256 words, so a device error surfaced late as ERR_ABORT. Current commands use pollDataPhase():

  1. waitUntilStatus(ST_BUSY | ST_DATA_REQUEST, ST_DATA_REQUEST, ...) — wait for BSY=0 and DRQ=1.
  2. checkDeviceState(io, sectorIndex) — ST_ERROR → getErrorReg(); ST_DEVICE_FAULT or !ST_DEVICE_READY → ERR_ABORT; otherwise success.
  3. On failure, setFailedSector(i) runs before setError(error), giving the plain failedSector field a happens-before edge through the command monitor.

A mid-transfer ST_ERROR from waitUntilStatus is caught, checked with hasDeviceError(), and routed through checkDeviceState so the failing sector is recorded; genuine timeouts are rethrown. Read, write and FUA commands finish with pollWait(io, true, sectorCount - 1) to validate final completion. IDEDiskDriver reports:

IOException("IDE read|write error:" + cmd.getError() + " at lba " + (partLbaStart + failed))

IDEBus.softwareReset() now waits the ACS-4 400 ns, polls ST_BUSY=0, and logs the SC/SN/CL/CH diagnostic signature plus ATA-vs-ATAPI.

Scheduler-Pump Daemon (still required)

A scheduler-pump daemon thread in VmIsolate runs an infinite Thread.yield() loop at MIN_PRIORITY. Yieldpoints reach VmProcessor.reschedule → IRQManager.dispatchInterrupts, which keeps pending device IRQs moving for untimed waits. It lives in VmIsolate.run() so it covers every user-mode entry path.

Immediate EOI for IDE IRQs (still required)

vm-ints.asm has def_irq_count_eoi, which sends EOI immediately after counting IRQ14/15. Immediate EOI prevents the in-service bit from blocking lower-priority lines while completion interrupts are still arriving.

Class Method Role
IDEBus executeAndWait() Submits and waits on the command monitor
Command waitUntilFinished()/notifyFinished() Monitor-based completion
DefaultIDEIO waitUntilStatus() Deadline-based status wait with fast-fail
IDERWSectorsCommand pollDataPhase(), checkDeviceState() DRQ wait + error mapping
IDEConstants CTR_NIEN nIEN control constant
VmIsolate startSchedulerPump() Daemon yield-loop for scheduler/IRQ liveness

Related Pages

Clone this wiki locally