BITS 16

org 7C00h

jmp 0x0:start ; do a far jump to clear any funky BIOS loading (make sure we're addressing correctly); some BIOS's load us differently ie. 07C0h:0000h vs 0000h:7C00h

ERROR_READING_DRIVE db 'Error reading drive!!!', 0

bootDrive db 0			; store where we booted from

cursorLocation db 0		; place in memory to store the current cursor position so we don't lose it

; *** 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_video_mode		; make sure we're in a good video mode (at least for BIOS...)
	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 check if 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 SECOND_BOOTLOADER_PART	; yay everything's ok

error_reading_drive:	; booooo
	mov si, ERROR_READING_DRIVE
	call print_string
	call permanent_halt	;(

print_string:	; Routine: output string in ds:si to screen, ended by 0 byte (null)
	mov ah, 0Eh 				; BIOS print character hex code
	mov dx, [cursorLocation]	; get saved cursor location

	.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:
		call move_cursor_down
		ret

reset_cursor:
	mov dx, 0
	mov byte [cursorLocation], 0
	mov ah, 2
	int 10h
	ret

move_cursor_down:
	mov dx, [cursorLocation]
	inc dh 		; move down the cursor
	mov dl, 0 	; reset cursor column
	mov [cursorLocation], dx
	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_video_mode:
	mov ah, 0
	mov al, 12
	int 10h
	ret

permanent_halt:
	hlt
	jmp permanent_halt

times 510-($-$$) db 0	; Pad remainder of boot sector with 0s
dw 0xAA55		; The standard PC boot signature

SECOND_BOOTLOADER_PART:

first_detect_memory:
	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			; ebx = 0 implies list is only 1 entry long (worthless)
	je .fail
	jmp .success

	.loop_detect_memory:
		mov eax, 0xE820			; eax, ecx get trashed on every int 0x15 call
		mov ecx, 24				; ask for 24 bytes again
		int 15h
		inc byte [listSize]
		;mov edx, 0x0534D4150	; Some BIOSes trash this register maybe (leaving commented out unless needed)
		stc						; set carry flag
		call test_memory_detection_success
		jnc .finished
		jmp .loop_detect_memory

	.success:
		mov byte [listSize], 1
		mov si, MEMORY_DETECTION_SUCCESS	; Put string position into SI
		call print_string					; Call our string-printing routine
		call print_memory_entry_byte_length
		mov eax, dword [es:0800h]
		call eax_to_binary_string
		mov si, byteString
		call print_string
		jmp .loop_detect_memory

	.finished:
		mov si, WAIT_FOR_INPUT
		call print_string
		xor ax, ax	; special BIOS hex for wait for input is 0
		int 16h
		call check_CPU
		jc print_long_mode_error
		jnc print_long_mode_available
		call permanent_halt

	.fail:
		mov si, MEMORY_DETECTION_FAILED
		call print_string
		call permanent_halt

print_long_mode_error:
	mov si, NO_LONG_MODE
	call print_string
	ret

print_long_mode_available:
	mov si, LONG_MODE_AVAILABLE
	call print_string
	ret

eax_to_binary_string:
    mov ebx, byteString
    xor ecx, ecx
    mov ecx, 32

	.conversion_loop:
	    mov dl, '0' ; replace '0' with 0 if you don't want an ASCII string
	    rol eax, 1
	    adc dl, 0
	    mov byte [ebx], dl
	    inc ebx
	    loop .conversion_loop
    
    ret

print_memory_entry_byte_length:
	cmp cl, 24
	je .print_24
	cmp cl, 20
	je .print_20
	jmp .print_unknown_memory_size

	.print_24:
		mov si, ACPI_IS_24
		call print_string
		ret

	.print_20:
		mov si, ACPI_IS_20
		call print_string
		ret

	.print_unknown_memory_size:
		mov si, ACPI_UNUSUAL_MEMORY_SIZE
		call print_string
		ret

test_memory_detection_success:
	jc .finished		; carry set means "end of list already reached"
	cmp ebx, 0
	je .finished
	ret

	.finished:
		clc ; clear carry flag
		mov si, MEMORY_DETECTION_FINISHED
		call print_string
		ret
 
 
; 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

; can think of this area below, before the start, as our variable setup, we set the data segment to this area, after we're sure that we've successfully loaded the other 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
	LONG_MODE_AVAILABLE db '64 bit mode available!', 0

	; messages related to memory detection
	MEMORY_DETECTION_SUCCESS db 'BIOS memory detection function successful!', 0
	MEMORY_DETECTION_FAILED db 'BIOS memory detection function failed!', 0
	MEMORY_DETECTION_FINISHED db 'BIOS memory detection function finished!', 0
	ACPI_IS_24 db 'ACPI list entry size, in bytes, is 24', 0
	ACPI_IS_20 db 'ACPI list entry size, in bytes, is 20', 0
	ACPI_UNUSUAL_MEMORY_SIZE db 'Unusual ACPI list entry size!', 0

	byteString dw 0 		; place to store the converted byte to string in the function below
	db 0 					; end byteString

	; messages for input
	WAIT_FOR_INPUT db 'Please press enter to continue...', 0

	listSize db 0			; place to store how long our memory detection function list is

times 2048-($-$$) db 0