Skip to content

Instantly share code, notes, and snippets.

@oriapp
Created January 9, 2023 15:55
Show Gist options
  • Save oriapp/8dacf966a09f429c99b78da52c73972b to your computer and use it in GitHub Desktop.
Save oriapp/8dacf966a09f429c99b78da52c73972b to your computer and use it in GitHub Desktop.
FAT16 ata lba write
; ata_lba_write - Write a sector to an ATA device using LBA mode
;
; @device: ATA device (0 for primary, 1 for secondary)
; @lba: LBA address of the sector to write
; @buffer: pointer to the buffer containing the data to write
;
; Returns: CF set on error, CF clear on success
global ata_lba_write
section .text
ata_lba_write:
; Save registers
pushad
; Backup the LBA
mov ebx, [lba]
; Send the highest 8 bits of the LBA to the hard disk controller
shr ebx, 24
or ebx, 0xE0
mov dx, 0x1F6
out dx, bl
; Finished sending the highest 8 bits of the LBA
; Send the total sectors to write
mov ebx, [buffer]
mov ecx, dword [ebx]
mov dx, 0x1F2
out dx, cl
; Finished sending the total sectors to write
; Send more bits of the LBA
mov ebx, [lba]
mov dx, 0x1F3
out dx, bl
; Finished sending more bits of the LBA
; Send more bits of the LBA
mov ebx, [lba]
shr ebx, 8
mov dx, 0x1F4
out dx, bl
; Finished sending more bits of the LBA
; Send upper 16 bits of the LBA
mov ebx, [lba]
shr ebx, 16
mov dx, 0x1F5
out dx, bl
; Finished sending upper 16 bits of the LBA
mov dx, 0x1F7
mov al, 0x30
out dx, al
; Write all sectors from memory
.next_sector:
push ecx
; Checking if we need to write
.try_again:
mov dx, 0x1F7
in al, dx
test al, 8
jz .try_again
; We need to write 256 words at a time
mov ecx, 256 ; 256 words is 512 bytes (: i.e one sector
; ^ Do the outsw instruction 256 times
mov dx, 0x1F0
rep outsw ; Output word from ES:(E)DI to I/O port specified in DX
; Writing from "0x0100000" to port 0x1F0
pop ecx
loop .next_sector
; End of writing sectors from memory
ret
@oriapp
Copy link
Author

oriapp commented Jan 9, 2023

returns 0 on success and 1 on error. The error code is stored in the CF register.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment