%include "gdtnasm.inc"
;; Loads loader.bin from the filesystem in FAT12

[BITS 16]
  ORG 0x500
  jmp     0:START
     
BytesPerSector        dw 0x0200
SectorsPerCluster     db 0x01
ReservedSectors       dw 0x0001
TotalFATs             db 0x02
MaxRootEntries        dw 0x00E0
TotalSectorsSmall     dw 0x0B40
MediaDescriptor       db 0xF0
SectorsPerFAT         dw 0x0009
SectorsPerTrack       dw 0x0012
NumHeads              dw 0x0002
HiddenSectors         dd 0x00000000
TotalSectorsLarge     dd 0x00000000
DriveNumber           db 0x00
     
START:
; code located at 0000:7C00, adjust segment registers
  cli
  xor     ax,ax
  mov     ds, ax
  mov     es, ax
  mov     fs, ax
  mov     gs, ax
  mov     ss, ax
  mov     sp, 0xF000
  sti
; post message
LOAD_ROOT:
     ; compute size of root directory and store in "cx"
  xor     cx, cx
  xor     dx, dx
  mov     ax, 0x0020                          ; 32 byte directory entry
  mul     WORD [MaxRootEntries]               ; total size of directory
  div     WORD [BytesPerSector]               ; sectors used by directory
  xchg    ax, cx
     ; compute location of root directory and store in "ax"
  mov     al, BYTE [TotalFATs]                ; number of FATs
  mul     WORD [SectorsPerFAT]                ; sectors used by FATs
  add     ax, WORD [ReservedSectors]          ; adjust for bootsector
  mov     WORD [datasector], ax               ; base of root directory
  add     WORD [datasector], cx
; read root directory into memory (7C00:0200)
  mov     bx, 0x1000                          ; copy root dir above bootcode
  call    ReadSectors
; browse root directory for binary image
  mov     cx, WORD [MaxRootEntries]           ; load loop counter
  mov     di, 0x1000                          ; locate first root entry
.LOOP:
  push    cx
  mov     cx, 0x000B                          ; eleven character name
  mov     si, ImageName                       ; image name to find
  push    di
  rep  cmpsb                                       ; test for entry match
  pop     di
  je      LOAD_FAT
  pop     cx
  add     di, 0x0020                          ; queue next directory entry
  loop    .LOOP
  jmp     FAILURE
LOAD_FAT:
; save starting cluster of boot image
  mov     dx, WORD [di + 0x001A]
  mov     WORD [cluster], dx                  ; file's first cluster
; compute size of FAT and store in "cx"
  xor     ax, ax
  mov     al, BYTE [TotalFATs]                ; number of FATs
  mul     WORD [SectorsPerFAT]                ; sectors used by FATs
  mov     cx, ax
; compute location of FAT and store in "ax"
  mov     ax, WORD [ReservedSectors]          ; adjust for bootsector
; read FAT into memory (7C00:0200)
  mov     bx, 0x1000                          ; copy FAT above bootcode
  call    ReadSectors
; read image file into memory (0050:0000)
  mov     ax, 0xfe0
  mov     es, ax                              ; destination for image
  mov     bx, 0x0000                          ; destination for image
  push    bx
LOAD_IMAGE:
  mov     ax, WORD [cluster]                  ; cluster to read
  pop     bx                                  ; buffer to read into
  call    ClusterLBA                          ; convert cluster to LBA
  xor     cx, cx
  mov     cl, BYTE [SectorsPerCluster]        ; sectors to read
  call    ReadSectors
  mov bx,es
  add bx,0x20
  mov es,bx
  xor bx,bx
  push    bx
; compute next cluster
  mov     ax, WORD [cluster]                  ; identify current cluster
  mov     cx, ax                              ; copy current cluster
  mov     dx, ax                              ; copy current cluster
  shr     dx, 0x0001                          ; divide by two
  add     cx, dx                              ; sum for (3/2)
  mov     bx, 0x1000                          ; location of FAT in memory
  add     bx, cx                              ; index into FAT
  mov     dx, WORD [bx]                       ; read two bytes from FAT
  test    ax, 0x0001
  jnz     .ODD_CLUSTER
.EVEN_CLUSTER:
  and     dx, 0000111111111111b               ; take low twelve bits
  jmp     .DONE
.ODD_CLUSTER:
  shr     dx, 0x0004                          ; take high twelve bits
.DONE:
  mov     WORD [cluster], dx                  ; store new cluster
  cmp     dx, 0x0FF0                          ; test for end of file
  jb      LOAD_IMAGE
DONE:
  jmp a20
FAILURE:
  mov     si, msgFailure
  call    DisplayMessage
  mov     ah, 0x00
  int     0x16                                ; await keypress
  int     0x19                                ; warm boot computer
     
;*************************************************************************
; PROCEDURE DisplayMessage
; display ASCIIZ string at "ds:si" via BIOS
;*************************************************************************
DisplayMessage:
  lodsb                                       ; load next character
  or      al, al                              ; test for NUL character
  jz      .DONE
  mov     ah, 0x0E                            ; BIOS teletype
  mov     bh, 0x00                            ; display page 0
  mov     bl, 0x07                            ; text attribute
  int     0x10                                ; invoke BIOS
  jmp     DisplayMessage
.DONE:
  ret
     
;*************************************************************************
; PROCEDURE ReadSectors
; reads "cx" sectors from disk starting at "ax" into memory location "es:bx"
;*************************************************************************
ReadSectors:
.MAIN
  mov     di, 0x0005                          ; five retries for error
.SECTORLOOP
  push    ax
  push    bx
  push    cx
  call    LBACHS
  mov     ah, 0x02                            ; BIOS read sector
  mov     al, 0x01                            ; read one sector
  mov     ch, BYTE [absoluteTrack]            ; track
  mov     cl, BYTE [absoluteSector]           ; sector
  mov     dh, BYTE [absoluteHead]             ; head
  mov     dl, BYTE [DriveNumber]              ; drive
  int     0x13                                ; invoke BIOS
  jnc     .SUCCESS                            ; test for read error
  xor     ax, ax                              ; BIOS reset disk
  int     0x13                                ; invoke BIOS
  dec     di                                  ; decrement error counter
  pop     cx
  pop     bx
  pop     ax
  jnz     .SECTORLOOP                         ; attempt to read again
  int     0x18
.SUCCESS
  mov     si, msgProgress
  call    DisplayMessage
  pop     cx
  pop     bx
  pop     ax
  add     bx, WORD [BytesPerSector]           ; queue next buffer
  inc     ax                                  ; queue next sector
  loop    .MAIN                               ; read next sector
  ret
     
;*************************************************************************
; PROCEDURE ClusterLBA
; convert FAT cluster into LBA addressing scheme
; LBA = (cluster - 2) * sectors per cluster
;*************************************************************************
ClusterLBA:
  sub     ax, 0x0002                          ; zero base cluster number
  xor     cx, cx
  mov     cl, BYTE [SectorsPerCluster]        ; convert byte to word
  mul     cx
  add     ax, WORD [datasector]               ; base data sector
  ret
     
;*************************************************************************
; PROCEDURE LBACHS
; convert "ax" LBA addressing scheme to CHS addressing scheme
; absolute sector = (logical sector / sectors per track) + 1
; absolute head   = (logical sector / sectors per track) MOD number of heads
; absolute track  = logical sector / (sectors per track * number of heads)
;*************************************************************************
LBACHS:
  xor     dx, dx                              ; prepare dx:ax for operation
  div     WORD [SectorsPerTrack]              ; calculate
  inc     dl                                  ; adjust for sector 0
  mov     BYTE [absoluteSector], dl
  xor     dx, dx                              ; prepare dx:ax for operation
  div     WORD [NumHeads]                     ; calculate
  mov     BYTE [absoluteHead], dl
  mov     BYTE [absoluteTrack], al
  ret

absoluteSector db 0x00
absoluteHead   db 0x00
absoluteTrack  db 0x00
     
datasector  dw 0x0000
cluster     dw 0x0000
ImageName   db "KERNEL  BIN"
msgProgress db ".", 0x00
msgFailure  db 0x0D, 0x0A, "ERROR : Press Any Key to Reboot", 0x00
     
a20:
sidt [0x9000]

; First get into protected mode
cli                             ;{0}
n5:     in      al, 0x64                ;Enable A20 {4A} {5}
        test    al, 2
        jnz     n5
        mov     al, 0xD1
        out     0x64, al
n6:     in      al, 0x64
        test    al, 2
        jnz     n6
        mov     al, 0xDF
        out     0x60, al
        lgdt    [gdtinfo]               ;Load GDT
        mov     ecx, CR0                ;Switch to protected mode
        inc     cx
        mov     CR0, ecx
        jmp     (flat_code-gdt_table):pmode1
[bits 32]
        pmode1:

        mov     ax, flat_data-gdt_table ; Selector for 4Gb data seg
        mov     ds, ax                  ; {2} Extend limit for ds
        mov     es, ax                  ; Extend limit for es
        mov     fs, ax                  ; fs and...
        mov     gs, ax                  ; gs
        mov     ss, ax                  ; gs
        mov     esp,0xf000

        mov edx,0x3f2 ;; turn off floppy motor
        mov al,0x0c
        out dx,al


;lets convert the ELF file to a linear binary so we can execute it
        cmp dword [0x10000],464c457fh  ; The ELF signature is \07fELF
        jne ldr_ELF_err            ; Ugh... not an ELF file !!!
        cmp word [0x10000+4],101h    ; It should be statically linked etc.
        jne ldr_ELF_err
        cmp byte [0x10000+6],1
        jne ldr_ELF_err

jmp short skip_err_handler
        ldr_ELF_err:

        mov word [0xb8000],0x0700 + 'E';
        mov word [0xb8002],0x0700 + 'L';
        mov word [0xb8004],0x0700 + 'F';

        cli
        hlt
        skip_err_handler:        
        mov dword eax, [0x10000+18h]
        mov [krnl_entry], eax

        xor ecx,ecx                     ; Get the number of sections in cx
        mov cx,[0x10000+2ch]

sectionloop:
        dec cx                          ; Next section
        push cx                         ; Save cx on the stack while we load
                                        ; the section into memory

        xor eax,eax
        mov word ax,[0x10000+2ah]        ; Get the program header entry size
        mul cx                          ; Calculate the offset from the start
                                        ; of the program header table
        mov ebx,[0x10000+1ch]        ; Get the PHT offset in ebx
        add ebx,eax                     ; Add it to our PHT entry offset
        add ebx,0x10000              ; Calculate the address of the entry
        cmp dword [ebx],1                ; Does this section have to be
                                        ; loaded into memory ?
        jne nextsect                    ; No, next section
        mov dword ecx,[ebx+4h]           ; Get the offset of the segment in
                                        ; the ELF file
        mov dword ebp,[ebx+10h]          ; Get the size of the segment in the
                                        ; ELF file
        mov dword edi,[ebx+8h]           ; Get the memory address of the sect.
        mov dword eax,[ebx+14h]          ; Get the size of the section in
        mov ebx,eax                     ; the memory into ebx

; ds:dx  = Address of ASCIIZ filename
; es:edi = Where in memory to put it
; ecx    = Offset in file to start reading (bytes)
; ebp    = Length of segment to read (bytes)
;
; Returns:
; eax    = Length of file that was loaded
; eax    = 0 if an error occured


        push ebp
        pusha
        mov esi, 0x10000
        add esi, ecx
        mov ecx, ebp
        call memcopy
        popa
        pop eax
        sub ebx,eax                     ; This amount needs to be zeroed
        jz nextsect                     ; It's ok, next section
        add edi,eax                     ; Zero the memory from this address
        xor ax,ax                       ; edi is an absolute address
        mov ecx,ebx
        call zero_memblock              ; Zero the rest of the section
nextsect:
        pop cx                          ; Restore our section count
        or cx,cx                        ; Was this the last one ?
        jnz sectionloop

;; Ok, done unzipping, jump into kernel
        mov dword esp,0x90000
        mov ebp,esp

        push dword 2
        popfd
        cli ;; just to make sure
        mov eax, [krnl_entry]

        call eax

        cli
        hlt
hang:jmp hang

zero_memblock:
        push eax                ; Save the registers
        push edi
        push ecx
        xor eax,eax             ; Fill the memory with zeros (0x0)
        cld                     ; Clear the direction flag; rep increments di
        a32 rep stosb           ; Fill the memory (one byte at a time)
        pop ecx
        pop edi
        pop eax
        ret                     ; Return to the main program

memcopy:
        pusha
memcopy_loop:
        mov al, [esi]
        mov [edi], al
        inc edi
        inc esi
        loop memcopy_loop
        popa
        ret


gdtinfo:

dw      gdtlength
dd      gdt_table

;********* GDT TABLE
gdt_table:

null_desc       desc    0,0,0

flat_code       desc    0, 0xFFFFF, D_CODE + D_READ + D_BIG + D_BIG_LIM

flat_data       desc    0, 0xFFFFF, D_DATA + D_WRITE + D_BIG + D_BIG_LIM

rm_code         desc    0, 0xFFFFF, D_CODE + D_READ

rm_data         desc    0, 0xFFFFF, D_DATA + D_WRITE

gdtlength equ $ - gdt_table - 1
;********* END GDT TABLE
krnl_entry      dd      0
