[BITS 16]

[org 7C00h]

jmp start
nop	; needs to be 3 bytes before BPB


; ****BEGIN BPB (BIOS PARAMETER BLOCK)****


db 'DRAGON23' 	; OEM identifier (8 bytes)

dw 512 			; bytes per sector

db 64 			; logical sectors per cluster (64 = 32768 bytes)

dw 8 			; number of reserved sectors, (boot sector (1) + FSInfoStructure (1) + extended boot loader (2)) * backup of previous sectors (2) = 8

db 1 			; number of FATS (conserve precious space and I don't care about redundancy right now lol)

dw 0			; number of root entries (how long the root directory list is. FAT32 is arbitrarily long so it should be 0)

dw 0			; number of logical sectors on disk, limit is FFFF which is nearly 32MB, for FAT32 you use BigNumberOfSectors later on in the extended part

db 0F8h			; media descriptor; F8 is for hard drive or "fixed disk"

dw 0			; this field is zero for FAT32 drives, and BigSectorsPerFAT contains the actual value

dw 0			; sectors per head, we're doing LBA partitioning instead of CHS so this doesn't matter

dw 0			; heads per cylindar, same reason as above

dd 0			; hidden sectors before partition, 0 if only one partition

dd 2000000h		; BigNumberOfSectors (total logical sectors) for FAT32 10000h = 65536 bytes


; ****BEGIN FAT32 EBPB (EXTENDED BIOS PARAMETER BLOCK) AND END BPB****


dd 64				; Sectors per FAT, I just set it to a single cluster

dw 4F00h			; Flags/Drive description. idk I just set the bits for LBA access

dw 0				; FAT Version number

dd 2				; The cluster number of the root directory, usually 2

dw 1				; The Logical LBA of the FSInfo structure, starts at 0 which is the main boot sector (mbr)

dw 6				; The Logical LBA of the backup boot sector

times 12 db 0		; RESERVED, 12 Bytes

db 0				; Drive number, value is arbitrary for fat32

db 0				; Flags in Windows NT, Reserved

db 29h				; Signature for fat32, must be 0x28 or 0x29

dd 0				; VolumeID 'Serial' number, used for tracking volumes between computers

db "DRAGONFIRE "	; Volume label string, 11 Bytes

db "DRAGON23"		; System identifier string, 8 Bytes


; ****END FAT32 EBPB****


bootDrive db 0		; store where we booted from

; error messages
ERROR_READING_DRIVE db 'Error reading drive!', 0
FATAL_ERROR_MESSAGE db 'FATALITY: Please press any button to reboot...', 0

; *** segments gets shifted << by 4 bits before added to the offset (register or immediate address (can be specified such as ds:ax or ds:0x18)) ***

start:
	cli						; disable bios interrupts
	mov ax, 0x0			; we're loaded at 7C00 so we must set are segments to that, remember, esgments get shifted left 4bits so 7C0 become 7C00
	mov ds, ax				; set data segment
	mov es, ax				; set extra segment
	mov ss, ax				; set up 704B stack space before this bootloader, stacks grow downwards (lower addresses is higher in stack)
	mov sp, 7C00h			; stack has 704B before it reaches the bios data area so be careful!
	mov	[bootDrive], dl 	; now that the segments are set up properly and the CPU can interpret are addresses references correctly, we can retain the drive from where we've booted from into memory, given to us by the BIOS
	sti						; restore bios interrupts

	call set_up_screen		; make sure we're in a good video mode (at least for BIOS...) and choose a background and text color and clear the screen
	call reset_cursor		; make sure cursor is in the beginning position
	call reset_disk			; make sure disk is ready to be read from

	mov ah, 02h		; super secret hex for the read disk command
	mov al, 3		; how many sectors to read?
	mov ch, 0		; which cylnder?
	mov cl, 2		; which sector do we start reading from?
	mov dh, 0		; which head?
	mov bx, 7E00h	; es:bx where we loading this stuff? in this case, we're loading directly after the first 512 bytes that were loaded by the BIOS, so we get the rest of the bootloader
	int 13h			; BIOS disk operation interrupt

	cmp al, 3		; BIOS returns how many sectors actually read into al
	jne error_reading_drive

	mov ah, 01h		; super secret hex for checking if the last disk operating completed successfully or not
	mov dl, [bootDrive]
	int 13h			; BIOS disk operation interrupt

	jc error_reading_drive	; carry flag is set on problem

	jmp memory_detection	; yay everything's ok

error_reading_drive:
	mov si, ERROR_READING_DRIVE
	call print_string
	jmp fatal_error

print_string:	; Routine: output string in ds:si to screen, ended by a null byte (0)
	push si ; the BIOS call(s) may destroy the si register
	call get_cursor_position
	test dl, dl			; is dl (column) 0? If not we should move the cursor down
	je .pre_repeat
	call move_cursor_down

	.pre_repeat:
		pop si
		mov ah, 0Eh 	; BIOS print character hex code

	.repeat:
		lodsb			; Get character from string
		cmp al, 0
		je .done		; If char is zero, end of string
		int 10h			; Otherwise, print it
		jmp .repeat

	.done:
		ret

reset_cursor:
	xor dx, dx
	mov ah, 2
	mov bh, 1 ; display page number
	int 10h
	ret

get_cursor_position:
	xor bh, bh
	mov ah, 3
	int 10h
	ret

move_cursor_down:
	call get_cursor_position
	inc dh 		; move down the cursor
	xor dl, dl 	; reset cursor column
	mov bh, 1 ; display page number
	mov ah, 2 	; set ah to the appropriate value for the BIOS to move the cursor
	int 10h 	; call the bios
	ret

reset_disk:
	mov	ah, 0		; reset disk function
	mov	dl, [bootDrive]
	int	0x13
	jc reset_disk	; If Carry Flag (CF) is set, there was an error. Try resetting again
	ret

set_up_screen:
	xor ah, ah		; code for bios
	mov al, 3		; video mode
	int 10h
	mov ah, 5
	mov al, 1
	int 10h
	mov ah, 7		; mode for scrolling down window and setting color
	mov al, 25		; lines to scroll down
	mov bh, 08Fh	; text white and background dark gray
	mov ch, 0		; start at line 0
	xor cl, cl		; leftmost column
	mov dh, 25		; paint till the bottom
	mov dl, 80		; paint all the way accross
	int 10h
	ret

user_pause:
	xor ax, ax
	int 16h
	ret

fatal_error:
	mov si, FATAL_ERROR_MESSAGE
	call print_string
	call user_pause

reboot:
	xor ax, ax
	int 19h

times 510-($-$$) db 0	; Pad remainder of boot sector with 0s
dw 0xAA55				; The standard PC boot signature

; ***BEGIN FS INFO STRUCTURE ***

dd 41615252h ; FS information sector signature (0x52 0x52 0x61 0x41 = "RRaA") For as long as the FS Information Sector is located in logical sector 1, the location, where the FAT typically started in FAT12 and FAT16 filesystems (with only one reserved sectors), the presence of this signature ensures that early versions of DOS will never attempt to mount a FAT32 volume, as they expect the values in cluster 0 and cluster 1 to follow certain bit patterns, which are not met by this signature.

times 480 db 0 ; reserved

dd 61417272h ; FS information sector signature (0x72 0x72 0x41 0x61 = "rrAa")

dd 0FFFFFFFFh ; Last known number of free data clusters on the volume, or 0xFFFFFFFF if unknown. Should be set to 0xFFFFFFFF during format and updated by the operating system later on. Must not be absolutely relied upon to be correct in all scenarios. Before using this value, the operating system should sanity check this value to be at least smaller or equal to the volume's count of clusters.

dd 0FFFFFFFFh ; Number of the most recently known to be allocated data cluster. Should be set to 0xFFFFFFFF during format and updated by the operating system later on. With 0xFFFFFFFF the system should start at cluster 0x00000002. Must not be absolutely relied upon to be correct in all scenarios. Before using this value, the operating system should sanity check this value to be a valid cluster number on the volume.

times 12 db 0 ; reserved

dd 0AA550000h ; FS information sector signature (0x00 0x00 0x55 0xAA)[19][nb 8] (All four bytes should match before the contents of this sector should be assumed to be in valid format.)

; ***END FS INFO STRUCTURE ***

; ***SECOND BOOTLOADER PART***

memory_detection:
	xor eax, eax 			; ensure eax is clear before we begin
	xor ebx, ebx
	mov eax, 0E820h 		; set up bios hex identifier for the function that detects memory, even higher than 4GB
	mov edx, 0x534D4150 	; i have no idea
	mov ecx, 24 			; list size in bytes, last dword for acpi 3.0
	mov di, 8400h			; set up ES:DI to point to destination buffer for the memory list
	int 15h 				; call memory detecting interrupt
	jc .fail				; carry set on first call means "unsupported function"
	cmp eax, 0x534D4150 	; eax should be set to what edx was, if not it failed
	jne .fail
	test ebx, ebx			; test is more efficient than cmp, 0 supposedly (bitwise AND)
	je .fail				; ebx = 0 implies list is only 1 entry long (worthless), is set to 0 at the end of the list

	.success:
		mov byte [memoryListCounter], 1
		cmp ecx, 24
		jne .no_ACPI3
		je .ACPI3

	.loop_detect_memory:
		call .is_finished?
		jc .finished
		mov eax, 0xE820			; eax, ecx get trashed on every int 0x15 call
		mov edx, 0x0534D4150	; Some BIOSes trash this register maybe
		mov ecx, 24				; ask for 24 bytes again
		int 15h
		mov al, [memoryListCounter]
		inc al
		cmp al, 0FFh
		jae .print_memory_list_length_error
		mov [memoryListCounter], al
		cmp ecx, 24
		jne .no_ACPI3
		je .ACPI3

	.no_ACPI3:
		add di, 20
		mov ax, 0
		stosw
		mov ax, 1 ; we need to set the end of it to 1 in order to be compatible with ACPI 3.0
		stosw ; increment di by the list size while being compatible with ACPI 3.0, unconventionally but efficient
		mov si, di
		sub si, 16
		jmp .test_invalid_entry

	.ACPI3:
		mov si, di
		add si, 8
		add di, 24 ; increment di by the list size

	; expects si to point to the spot in the memory entry that is the length of the memory region
	; an invalid entry is returned if the length of the memory region is 0
	.test_invalid_entry:
		lodsw
		cmp ax, 0
		jne .loop_detect_memory
		lodsw
		cmp ax, 0
		jne .loop_detect_memory ; if still equal it's an invalid entry and we'll continue down to skip the entry

	.skip_entry:
		sub di, 24
		call .is_finished? ; if so we need to zero out the rubish data
		jnc .loop_detect_memory
		mov si, di
		xor ax, ax
		mov cx, 12 ; 12 because the list size is 24 bytes and we're storing words which is 2 bytes
		rep stosw
		jmp .finished

	; returns with carry set if finished
	.is_finished?:
		jc conditional_return		; carry set means "end of list already reached"
		stc
		cmp ebx, 0
		je conditional_return
		clc
		ret

	.finished:
		call check_CPU
		jc .print_long_mode_error
		jmp enter_long_mode

	.fail:
		mov si, MEMORY_DETECTION_FAILED
		call print_string
		jmp fatal_error

	; error message functions

	.print_memory_list_length_error:
		mov si, MEMORY_LIST_TOO_LONG
		call print_string
		jmp fatal_error

	.print_long_mode_error:
		mov si, NO_LONG_MODE
		call print_string
		jmp fatal_error
 
 
; Checks whether CPU supports long mode or not.
 
; Returns with carry set if CPU doesn't support long mode.
 
check_CPU:
    ; Check whether CPUID is supported or not.
    pushfd               ; Get flags in EAX register.
 
    pop eax
    mov ecx, eax  
    xor eax, 0x200000 
    push eax 
    popfd
 
    pushfd
    pop eax
    xor eax, ecx
    shr eax, 21
    and eax, 1           ; Check whether bit 21 is set or not. If EAX now contains 0, CPUID isn't supported.
    push ecx
    popfd
 
    test eax, eax
    jz .no_long_mode
 
    mov eax, 0x80000000
    cpuid
 
    cmp eax, 0x80000001  ; Check whether extended function 0x80000001 is available are not.
    jb .no_long_mode       ; If not, long mode not supported.
 
    mov eax, 0x80000001
    cpuid
    test edx, 1 << 29    ; Test if the LM-bit, is set or not.
    jz .no_long_mode       ; If not Long mode not supported.
 
    ret
 
.no_long_mode:
    stc
    ret

conditional_return:
	ret ; this is used since there is no "return if equal/ne instruction"

user_pause_before_kernel:
	mov si, CONTINUE_BOOTING_KERNEL?
	call print_string
	xor ax, ax	; special BIOS hex for wait for input is 0
	int 16h
	ret

; can think of this area below, before the start, as our variable setup that we've (hopefully) successfully loaded this part of the bootloaer into memory

PRIMARY_VARIABLE_STORAGE_AREA:

	; messages related to 64 bit mode
	NO_LONG_MODE db 'Your processor is not capable of 64 bit mode!', 0

	; messages related to memory detection
	MEMORY_DETECTION_FAILED db 'BIOS memory detection function failed!', 0
	MEMORY_LIST_TOO_LONG db 'BIOS memory detection function returned too many entries!', 0

	CONTINUE_BOOTING_KERNEL? db 'All systems are go! Please press any key to continue booting into kernel...', 0

	memoryListCounter db 0	; place to store how long our memory detection function list is

; entering long mode below

; idk...
%define PAGE_PRESENT    (1 << 0)
%define PAGE_WRITE      (1 << 1)
 
%define CODE_SEG     0x0008
%define DATA_SEG     0x0010

ALIGN 4
IDT:
    .Length       dw 0
    .Base         dd 0
 
; Function to switch directly to long mode from real mode.
; Identity maps the first 2MiB.
; Uses Intel syntax.
 
; es:edi    Should point to a valid page-aligned 16KiB buffer, for the PML4, PDPT, PD and a PT.
; ss:esp    Should point to memory that can be used as a small (1 dword ) stack

enter_long_mode:
	mov di, 9000h		; set destination index to after our 2048 byte bootloader and leave room for our memory list inbetween 8400h and 9000h
	push di				; REP STOSD alters DI.
    mov ecx, 0x1000
    xor eax, eax
    cld
    rep stosd
    pop di				; Get DI back.

; Build the Page Map Level 4.
; es:di points to the Page Map Level 4 table.
lea eax, [es:di + 0x1000]         ; Put the address of the Page Directory Pointer Table in to EAX.
or eax, PAGE_PRESENT | PAGE_WRITE ; Or EAX with the flags - present flag, writable flag.
mov [es:di], eax                  ; Store the value of EAX as the first PML4E.


; Build the Page Directory Pointer Table.
lea eax, [es:di + 0x2000]         ; Put the address of the Page Directory in to EAX.
or eax, PAGE_PRESENT | PAGE_WRITE ; Or EAX with the flags - present flag, writable flag.
mov [es:di + 0x1000], eax         ; Store the value of EAX as the first PDPTE.


; Build the Page Directory.
lea eax, [es:di + 0x3000]         ; Put the address of the Page Table in to EAX.
or eax, PAGE_PRESENT | PAGE_WRITE ; Or EAX with the flags - present flag, writeable flag.
mov [es:di + 0x2000], eax         ; Store to value of EAX as the first PDE.


push di                           ; Save DI for the time being.
lea di, [di + 0x3000]             ; Point DI to the page table.
mov eax, PAGE_PRESENT | PAGE_WRITE    ; Move the flags into EAX - and point it to 0x0000.

; Build the Page Table.
LoopPageTable:
    mov [es:di], eax
    add eax, 0x1000
    add di, 8
    cmp eax, 0x200000                 ; If we did all 2MiB, end.
    jb LoopPageTable
 
    pop di                            ; Restore DI.
 
    ; Disable IRQs
    mov al, 0xFF                      ; Out 0xFF to 0xA1 and 0x21 to disable all IRQs.
    out 0xA1, al
    out 0x21, al
 
    lidt [IDT]                        ; Load a zero length IDT so that any NMI causes a triple fault.
 
    ; Enter long mode.
    mov eax, 10100000b                ; Set the PAE and PGE bit.
    mov cr4, eax
 
    mov edx, edi                      ; Point CR3 at the PML4.
    mov cr3, edx
 
    mov ecx, 0xC0000080               ; Read from the EFER MSR. 
    rdmsr    
 
    or eax, 0x00000100                ; Set the LME bit.
    wrmsr
 
    mov ebx, cr0                      ; Activate long mode -
    or ebx,0x80000001                 ; - by enabling paging and protection simultaneously.
    mov cr0, ebx                    
 
    lgdt [GDT.Pointer]                ; Load GDT.Pointer defined below.
 
    jmp CODE_SEG:LongMode             ; Load CS with 64 bit segment and flush the instruction cache
 
 
; Global Descriptor Table
GDT:
	.Null:
	    dq 0x0000000000000000             ; Null Descriptor - should be present.
	 
	.Code:
	    dq 0x0020980000000000             ; 64-bit code descriptor. 
	    dq 0x0000900000000000             ; 64-bit data descriptor. 
	 
	ALIGN 4
	    dw 0                              ; Padding to make the "address of the GDT" field aligned on a 4-byte boundary
	 
	.Pointer:
	    dw $ - GDT - 1                    ; 16-bit Size (Limit) of GDT.
	    dd GDT                            ; 32-bit Base Address of GDT. (CPU will zero extend to 64-bit)
 
 
[BITS 64]      
LongMode:
    mov ax, DATA_SEG
    mov ds, ax
    mov es, ax
    mov fs, ax
    mov gs, ax
 
    ; Blank out the screen to a blue color.
    mov edi, 0xB8000
    mov rcx, 500                      ; Since we are clearing QWORDs over here, we put the count as Count/4.
    mov rax, 0x1F201F201F201F20       ; Set the value to set the screen to: Blue background, white foreground, blank spaces.
    rep stosq                         ; Clear the entire screen. 
 
    ; Display "Hello World!"
    mov edi, 0x00b8000              
 
    mov rax, 0x1F6C1F6C1F651F48    
    mov [edi],rax
 
    mov rax, 0x1F6F1F571F201F6F
    mov [edi + 8], rax
 
    mov rax, 0x1F211F641F6C1F72
    mov [edi + 16], rax

    ; call user_pause_before_kernel
	jmp $

times 33554432-($-$$) db 0	; pad out 32mb