; This is the lobotomized bootloader, without pretty boot screens

; the MBR program MUST have done the following:
; set DL to the "drive number" of the boot drive
; set BX -> LBAstart of booted partition table entry
; loaded this bootloader at 0x500 (NOT 0x7c00!!!)


; There is legacy code in this bootloader to support sector sizes other than
; 512 bytes. My current understanding is: that is no longer an IDE supported
; feature (as of ver. 6 of the IDE specs) for hard drives ... only for CDs.
; I left the code here just in case that concept is ever resurrected. OS ver 1.x does not support it.
; If BIOS EIDE 64 bit LBA is ever specified, there will be a partition table
;   redesign required, and the support for it is already here, mostly.

; TODO:
; -- getting video mode info -- http://www.osdev.org/osfaq2/index.php/GettingVbeModeInfo
; -- use bios info to find the total size of usable memory (must be mult of 64K!), and untouchable sections (store at other_tbl)
; -- use bios info (INT 1e pointer) & cmos to get floppy info
; -- add in the 2 memory test sections (make sure not to overwrite the MBR! Start at 0x7e00 -- MBR tests 0x500 to 0x7c00)
; -- rewrite getroot for multiple rdcont's
; -- put timeouts on the waits in addy20
; -- signature checking, range checking -- error messages
; -- get keyboard input (int 16h) in order to
; -- Stop on a keystroke, and allow the user to choose a non-default bootload:
;     user chooses boot filename, is allowed to enter singlestep mode,
;     and specifies the post-boot setup program command line
; -- fully activate 48 bit lba support when upgrading OS to 64 bit CPU, just 32 bit support (2 TB) for now
; -- is it possible to set up the bootloader & mbr to cooperate on a "proprietary" 48 bit partition table?


first_sz_tbl	equ	0x2300
other_tbl	equ	0x2514
DAPACK		equ	0x7bf0
db_add		equ	0x7bf4
GDTINFO		equ	0x7bd4
LBAlen		equ	0x7bd4
LBAstart	equ	0x7bd0
TotMem		equ	0x7bce
OSFilNam	equ	0x7bbe
BigSect		equ	0x7bbd
ClustrSh	equ	0x7bbc
SStepf		equ	0x7bbb
ATblf		equ	0x7bba		; includes partition # (bottom 2 bits)
PCIcnt		equ	0x7bb9
DrvNum		equ	0x7bb8
ATBLB		equ	0x7ba0
RTCTime		equ	0x7b9e
initcl		equ	0x7b4e
volptr		equ	0x7b4c


SEGMENT START USE16		;At 0:0500

	cli
	xor	eax, eax
	mov	ss, ax
	mov	ds, ax
	mov	es, ax
	mov si, 0xb000
	mov	fs, si
	mov sp, 0x7c00

; build the workspaces and pre-initialized data structures on the stack
; NOTE: stack grows from top down, so all structures are pushed in reverse order

;Format of disk address packet:
;Offset	Size	Description
; 00h	BYTE	size of packet (10h)
; 01h	BYTE	reserved (0)
; 02h	WORD	number of blocks to transfer (max 127, 63.5K usually)
; 04h	DWORD	-> transfer buffer
; 08h	DWORD	starting LBA
; 0ch	DWORD	reserved for 48 or 64 bit LBAs (0)

	push	ax			; first 64bits of LBA all 0 for now
	push	ax
	push	ax
	push	ax

	push	ax			; then 32 bits of memory address load point
	push	other_tbl

	push	1			; read one sector
	push	0x0010			; addy here = 0x7bf0


; GDT entry (8 bytes, 8K entries, 64Kb max size)
;  subField                Final location
;  ------------------      --------------
;  Limit[0..15]                 0..15		always FFFF
;  Limit[16..19]               48..51		always F
;  Minor attribute bits        52..55		always C (Gran=4K, 32bit)
;  Major attribute bits        40..47
;     low nibble				9 for code, 3 for data
;    high nibble				always 9, S flag, Priv=0, Present
;  Base[0..23]                 16..39		always 0
;  Base[24..31]                56..63		always 0

;	dword	0	; 1st gdt entry is never accessed
;	dword	0
;	dword	0FFFFH		; code gdt entry
;	dword	00CF9900H	; (may need to make this 'readable', to handle paging)
;	dword	0FFFFH		; data gdt entry
;	dword	00CF9300H

	xor	ecx, ecx
	xor	edi, edi
	mov	bp, 0xffff
	mov	al, 0xcf

	push	ax
	push	0x9300
	push	cx
	push	bp
	push	ax
	push	0x9900
	push	cx
	push	bp
	push	cx
	push	cx
	push	cx
	push	cx
	mov	si, sp		; save ptr to GDT = 0x7bd8

; GDTINFO is only used once, and can be immediately overwritten with useful stuff

	push	si
	mov	ax, 23		; (sizeof GDT) -1
	push	ax

	lgdt [GDTINFO]		; now I can reuse the GDTINFO space
	sub	sp, 4		; need the 4 from GDTINFO and 4 more

; 32bit Partition LBAstart (4b) = 0x7bd0
; 32bit Partition length, in sectors (4b) = 0x7bd4

	mov	di, sp		; copy LBAstart, LBAlen from si into "sp"

; construct the "partition number" from the low byte of si (=0xbe to 0xee)
	mov	al, dl
	mov	edx, eax	; zero out all of edx except dl = drive letter

	mov	si, bx
	shr	bx, 4		; bl = 0xc? to 0xf?
	and	bx, 3
	movsw			; copy LBAstart into my memory area from
	movsw			; specified partition table entry
	movsw			; copy LBAlen, too
	movsw

; total memory on system (2b) = 0x7bce
	push	0x1e0		; for bochs -- HIHI

; OS short file name (16b) = 0x7bbe
	push	cx
	push	cx
	push	cx
	push	cx
	push	cx
	push	0x21		; !
	push	0x676e		; ng
	push	0x6142		; Ba (reversed, of course)

; non-512 byte sector flags (hard drive has > 512b sectors (1b), artificial cluster shift (1b))
; -- both bytes are shift values, to multiply 512 by powers of 2
	push	cx		; = 0x7bbc

; sstep flag, boot partition number, ATBLB flag bits
	push	bx		; = 0x7bba

; "drive number" (0x80 for primary), PCI bus count
	push	dx		; = 0x7bb8

; ATBLB: 12 words	; strng#, len, start lba (8b) repeated 2 times
; RTC minutes and seconds (1b each)
; initcl: 80 bytes to store an initial command line for the console
	sub	sp, 106
	; store a default command into initcl
	mov	bx, sp
	mov	[bx], word 0x4e49	; 'IN' reversed
	mov	[bx+2], word 0x5449	; 'IT' reversed
	mov	[bx+4], cx
	; zero out the high dwords on the 64 bit LBA storage (the rest is reset automatically)
	mov 	[bx+90], cx
	mov	[bx+92], cx
	mov 	[bx+102], cx
	mov	[bx+104], cx

; volptr: points to 4b system base date, followed by triple-zero terminated volume name for logical drive = 0x7b42
	push	vnamp

; ****** DONE WITH INITIALIZING STORAGE AREA ******

	mov bp, 0x8820		; HIHI just faking the display for now in bochs!!

	mov bx, m_boot		; display boot message
	call dsperr
	; move display point to next line
	add bp, 0xa0

; use some INT13 command to find the size of a sector, for booting off a CD or something?
; this code NEEDS to know how many sectors fit in 32k!

	in al, 0x61		; first method to enable the keyboard
	mov dh, al		; Save keyboard status byte
	bt ax, 7		; keyboard disable is top bit of the byte
	jnc ADDY20
	and dh, 0x7f		; remove bit to enable keyboard
	mov al, dh
	out 0x61, al
; Note: there is a few ns delay after the "out" calls in this bootloader, but not much!
	call io_delay

; turn on the A20 address line of the CPU -- if it isn't on already
; do an ACK on any byte taken off port 60, also allow the BIOS to accept, ACK
;  & buffer all other bytes when INTs are turned on.

ADDY20:

	mov CX, 5		; 5 retries on 1st method

method1:			; check if A20 is set, if not, try to set it
.cwait1:			; wait for controller "ready"
	in AL, 0x64
	bt AX, 1
	jc short .cwait1

	mov AL, 0xD0		; request controller status
	out 0x64, AL
	call io_delay

.dwait1:			; wait for data to be available
	in AL, 0x64		; bit 0 of port 64h is the flag
	bt AX, 0
	jnc short .dwait1

	in AL, 0x60		; ding! Data is ready. Read it from port 60
	mov AH, AL		; and store it for later use

	mov al, dh		; ack receipt of the byte to the controller
	or al, 80h		; Disable
	out 61h, al
	call io_delay
	mov al, dh		; Enable
	out 61h, al
	call io_delay

	bt AX, 9		; has the A20 enable bit ALREADY been set successfully?
	jc short memtst1	; If bit is on, A20 is on.

.cwait2:			; wait for controller "ready" again
	in AL, 0x64
	bt AX, 1
	jc short .cwait2

	mov AL, 0xD1		; command to write a new status byte (with A20 bit!)
	out 0x64, AL
	call io_delay

.dwait2:			; wait until controller can accept the byte
	in AL, 0x64
	bt AX, 1
	jc short .dwait2

	mov AL, AH		; reload the saved current status byte
	or AL, 2		; flip on the A20 enable bit
	out 0x60, AL		; and ram it back into the controller
	call io_delay

	loop method1		; Go back and check if it worked.


	mov CX, 5		; Method #1 didn't work. Take 5 shots at method #2.

method2:
.cwait4:
	in AL, 0x64		; wait for "ready"
	bt AX, 1
	jc short .cwait4

	mov AL, 0xDF		; enable A20 command
	out 0x64, AL
	call io_delay

; verify that method2 worked

.cwait5:
	in AL, 0x64		; wait for "ready"
	bt AX, 1
	jc short .cwait5

	mov AL, 0xD0		; request status
	out 0x64, AL
	call io_delay

.dwait4:
	in AL, 0x64		; wait for the data
	bt AX, 0
	jnc short .dwait4

	in AL, 0x60		; Yay! More data
	mov ah, al

	mov al, dh		; ack receipt of the byte to the controller
	or al, 80h		;Disable
	out 61h, al
	call io_delay
	mov al, dh		;Enable
	out 61h, al
	call io_delay

	bt AX, 9		; check that A20 enabled bit
	jc short memtst1
	loop method2		; Method2 failed too! Retry a few times.

	mov BX, m_a20
	call dsperr		; display an error message, so the user can hit reset

	jmp ADDY20		; start over -- no other choice, except a halt


memtst1:
; erase any possible error message from A20 section above. It worked now.
; keyboard may even need command 0xAE to port 64 (another enable)
; and/or 0xF4 to port 60
; HIHI Specify keyboard scanset #1 (F0 01 to port 60)

	xor DH, DH
	mov bx, m_clr
	call dsperr		; this outputs a blank line on top of any error

; Verify the integrity of low memory (from 0:7e00 up to 9:FFFF) HIHI -- don't trample 0x7c00!
; leave out the secondary bios memory area just under 0xa0000?

	; make sure there are zeros after the first two size tables
	mov cx, 138
	xor eax, eax
	mov di, first_sz_tbl +512
	rep stosd

SIZMAP:
; verify that system has extended int 13H command set?
; This is a waste of time. Just try reading, I think. Crap if no workie.
;	mov AH, 41h
;	mov BX, 55AAh
;	mov DL, 80h
;	int 13h

;	1st size map sector has already been loaded by MBR into first_sz_tbl

; use lba info from MBR Partition Table to load 2nd Size Table
; read 2nd size table into 0x2514 (1 sector)

; HIHI check signature byte, and whether this is 8b lba

;	mov dh, 0		; set sz3 flag false (already done)
	mov si, LBAstart
	mov edi, [si]
	add edi, [si+4]		; calculate absolute LBA addy of partition ending sector
	dec edi			; LBAstart + partition size -1
	mov SI, DAPACK		; address of "disk address packet"
;	mov [si+2], byte 1	; number of sectors = 1
;	mov [si+4], word other_tbl	; destination buffer
	mov [si+8], edi		; last sector of partition holds 2nd size table blk #1
	mov AH, 42h
;	mov DL, 80h		; drive number -- loaded by MBR!
	sti
	int 13h
	jnc short .cmps12

	mov bx, m_ei13
	call dsperr		; display "no extended int13" error
	jmp short SIZMAP

.cmps12:

; compare size tables 1 & 2 for equality (skip 1st 4 bytes)

	mov si, first_sz_tbl +4
	mov di, ClustrSh
	mov cl, [si+5]			; grab the size table format byte
	and cl, 7			; bottom 3 bits are artificial shift value
	mov [di], cl			; store it, unless size tbl 1 is bad
	mov di, other_tbl +4		; 2nd size table +4
	mov cx, 127
	rep cmpsd
	jcxz getPCI	; if match, get PCI info -- if not, get 3rd size table

	; check flag to see if size table 3 has already been done, die if so
	test dh, dh
	jne short .sizbad
; set defaults to load 3rd size table after 2nd, using 1st size table data

	mov si, db_add
	mov word [si], first_sz_tbl +1064	; addy of start of 3rd size tbl
	mov bx, first_sz_tbl+8			; 1st size table (skip header)

.lsz:
; set ax to the string number to locate in the size table (size=0, string =0)
	xor ax, ax
	call snlocat
; if there is an error, then jump to checking the 2nd size table against the 3rd.
; (just so long as I haven't already been checking the 3rd)

	jnc .ld3rd
	test dh, dh
	je short .cmps23

	jmp short .sizbad

.ld3rd:
; lba of 3rd size table= lba of start of 0-0 string + (string length << shift)

	mov ax, [bx]		; string length
	mov si, ClustrSh	; need to include artificial cluster shft in LBA calc.
	mov cl, [si]
	shl eax, cl		; upper word of eax has been zeroed previously
	add eax, [bx+2]
	mov SI, DAPACK		; address of "disk address packet"
	mov [si+8], eax
	mov AH, 42h		; AL is unused
;	mov DL, 80h		; drive number -- loaded by MBR
	int 13h
	jnc short .cmps13

.sizbad:
	mov bx, m_sz
	call dsperr			; display size table fatal error
	mov si, db_add			; fix DAPACK before going back to SIZMAP
	mov word [si], other_tbl	; addy of start of 2nd size table
	jmp short SIZMAP

.cmps13:
	test dh, dh		; if 2nd time loading sz3, then jump to .cmps12
	jne short .cmps12
	mov dh, 1		; set the sz3 flag

; compare size tables 1 & 3 for equality (skip 1st 4 bytes)

	mov si, first_sz_tbl +4
	mov di, first_sz_tbl +1068
	mov cx, 127
	rep cmpsd
	jcxz getPCI		; exact match?

; NO MATCH!
.cmps23:
; Assume first size table is BAD. Therefore 3rd size table was loaded wrong.
; Use the 2nd size table to recalculate the position of the 3rd, and load 3rd again.
; Load 3rd on top of 1st, and compare "1st" and 2nd again. If fail, then die.

	mov bx, other_tbl +8		; using data from 2nd size table (skip header)
	mov di, ClustrSh
	mov cl, [bx-3]			; grab the size table format byte
	and cl, 7			; bottom 3 bits are artificial shift value
	mov [di], cl			; store it!
	mov si, db_add
	mov word [si], first_sz_tbl
	jmp short .lsz

getPCI:
; PCI info that's easiest to get from the BIOS:
	je short getroot		; HIHI -- bochs doesn't emulate this INT and will crash
	mov ax, 0xb101
	int 0x1a			; get PCI bus info
	jc short nopci

; check signature bytes
	cmp dx, 0x4350
	jne short nopci

; check for error code, AH=00 is good
	test ah, ah
	jne short nopci

; info is here, then. CL is the PCI bus count -1
; BH is the PCI major version number of the chipset
; BL is the PCI minor version number
; AL bit 0 means "use configuration method 1" -- should always be set
; bit 1 means "use config method 2" -- should never be set
; bit 4 means use special cycle method 1
; bit 5 means use special cycle method 2

	mov si, PCIcnt
	mov [si], cl
	jmp short getroot
nopci:
	mov bx, m_nopci
	call dsperr
	hlt
	jmp ADDY20


getroot:			; at addy 0x708

;trace the clusters of the root directory, and convert to lba
	mov ax, 0x2			; starting CLUSTER for root directory, 2-0
	xor bx, bx			; in two pieces (string offset 0)
	call traccls
	jc short .szerr
	cmp eax, 0x2000001		; make sure ending cluster is correct
	je short rdroot

.szerr:
	mov bx, m_rootb
	call dsperr
	jmp short getroot

rdroot:		; read in the root directory

; HIHI add up lengths of all the chunks and verify total length < 64K (with shift)
; The traccls A tables tromple all over memory above page 1, so it can't be > 1 page!

	mov bx, 0x8000
	mov dx, other_tbl	; addy of lba table
rdrlp:
	mov di, dx
	mov cx, [ds:di+8]	; load the # of sectors to read in this chunk
	jcxz rdrdon		; 0 means done

	mov ax, dx
	call rdcont		; total size <= 32K, therefore no need to subloop
	jnc short rdrok		; HIHI, extend that to 64K and do the subloop

	mov bx, m_read
	call dsperr
	jmp short getroot

rdrok:
	add dx, 12		; increment to next lba chunk
	jmp short rdrlp

rdrdon:
	mov si, 0x8004		; point at signature
	lodsw			; put signature in ax, and increment si past the dir header
	cmp ax, 0xf1d1		; verify signature == 0xF1D1 = 2 byte signature for Dir
;	je short scroot

;	mov bx, ?? root directory corrupted (bad signature)
;	call dsperr
;	jmp short getroot

scroot:
;scan the root directory to find the start cluster of the kernel file
	mov cx, [si-6]		; put the self reported # of entries into cx

scnxtr:
	mov ax, [si]			; load length of dir entry
	test ax, ax
	jne short scmpfn

	mov bx, m_nfnd			; didn't find requested boot file
	call dsperr
	jmp short getroot		; HIHI go back and ask the user to input it

scmpfn:
	; HIHI verify that ax is a mult of 4, or the dir is corrupted
	; compare short file name with 'Bang!' or whatever the user entered for boot file.
	mov bx, OSFilNam
	; HIHI need a segment set to 0x1000 for bx
	mov di, [bx]
	cmp di, [si+26]
	jne short scnomat
	mov di, [bx+2]
	cmp di, [si+28]
	jne short scnomat
	mov di, [bx+4]
	cmp di, [si+30]
	jne short scnomat
	mov di, [bx+6]
	cmp di, [si+32]
	jne short scnomat
	mov di, [bx+8]
	cmp di, [si+34]
	jne short scnomat
	mov di, [bx+10]
	cmp di, [si+36]
	jne short scnomat

; got a match!
	mov eax, [si+2]			; get the starting cluster
	mov cx, 0x1000			; copy root dir out of first mem page
	mov es, cx			; ds is always 0, es should be 0x1000
	mov si, 0x8000			; from addy 0:8000
	xor di, di			; to addy 1:0000
	mov cx, 0x2000			; 32K of longs = 8K
	rep movsd			; copy 32K root directory to page 1

	mov bx, ax
	bswap eax
	call traccls			; load up the lba table for reading the OS
	jnc short osread

	mov bx, m_osb		; HIHI filesystem error in os file -- get new os file
	call dsperr
	jmp getroot

scnomat:
	add bx, ax
	loop scnxtr

	; HIHI test [bx] to make sure it's 0?
	mov bx, m_nfnd
	call dsperr
	jmp getroot ; HIHI -- jump back to getting user input

osread:		; addy here = ???

	mov BX, m_ld		; create cute display
	call dsperr
	bswap ebp		; don't move back to beginning of line yet
	add BP, 4		; move display point to print dots

	xor cx, cx		; initialize everything
	mov si, ClustrSh
	mov cl, [si]
	mov di, 0x0a00		; start pointer >> 8 (units are 256b)
	bswap edi
	xor dx, dx		; accumulator for total blocks
	mov bx, other_tbl	; addy of lba table
	bswap ECX		; save the blocksize shift for future use

.osrlp0:
	xor eax, eax
	cmp [bx+8], eax		; final lba entry (length = zero)?
	jne short .osras
	mov ax, dx
	bswap EAX		; save the total os length in blocks
	jmp short .osrc
.osras:
	mov eax, [bx+8]
	add bx, 12
	cmp eax, 1024		; the theoretical biggest length
	jbe short .osros1

	jmp osread		; HIHI need error message here -- fix screen, too
.osros1:
	add dx, ax
	mov ax, dx
; HIHI verify total length <= 512K (with shift)
	bswap ECX
	shl ax, cl		; shift total length to measure 512b blocks
	bswap ECX
	cmp ax, 1024
	jbe short .osrlp0

; HIHI need same error message and death here -- fix screen, too
	jmp osread

.osrc:					; read each chunk
	sub bx, 12
	mov ax, [bx+8]
	bswap EDI			; recover old start pointer (>>8)
	bswap EBX			; temporary storage
	bswap ECX			; recover blocksize shift
	shl ax, cl			; convert blockcount to 512s
	bswap ECX			; save blocksize shift again
	shl ax, 1			; convert 512s to 256s
	sub di, ax			; find new start pointer (>>8)
	mov bx, di
	mov al, bh			; grab page number
	shl ax, 12			; convert it to segment number for es
	mov es, ax
	mov ah, bl			; ax = bx << 8 (low byte of ax is always 0)
	bswap EBX
	bswap EDI			; save new start pointer
	mov di, ax			; and set the di copy offset
	mov cx, [bx+8]
	mov ax, bx
.osrlp1:
	push cx				; save # of remaining blocks in chunk
	mov dx, 64			; 32K worth of blocks (unshifted)
	bswap ECX			; retrieve the blocksize shift
	shr dx, cl			; convert to real disk blocks
	bswap ECX			; retrieve the total block count
	cmp cx, dx
	jbe short .osdor
	mov cx, dx			; keep it down to 32K per read
.osdor:
	push bx
	mov bx, 0x8000			; read into mem addy 32K to 64K
	mov dx, cx			; save the # of blocks about to be read
	call rdcont
	jnc short .osrok

	mov bx, m_read
	call dsperr
	jmp getroot

.osrok:					; now copy cx=dx blocks to next mem dest.
	mov bx, dx
	bswap ECX			; convert to 512b blocks
	shl bx, cl			; (biggest it could be is 32K)
	bswap ECX
	mov si, 0x8000			; point si at the beginning of new data
	mov cx, bx			; convert 512b blocks to words
	shl cx, 8
	sub ax, cx			; rdcont set ax=0
	sub ax, cx			; 64K - # of bytes to copy
	cmp di, ax
	jae short .os2part
	rep movsw
	jmp short .osrdon

.os2part:
	; calculate the value (64K - di)/2 into bx = # of WORDS left on page es
	mov bx, di
	neg bx
	shr bx, 1
	push cx
	mov cx, bx
	rep movsw
	pop cx
	mov ax, es
	add ax, 0x1000
	mov es, ax
	mov byte [fs:bp], 0x2e	; print a dot whenever a page switches
	add bp, 4

	; di should always have rolled over to 0 at this point, exactly
	sub cx, bx
	jle short .osrdon	; but that might be the end of the copy, too
	rep movsw

.osrdon:
	xor ax, ax		; for rdcont
	pop bx			; recover lba table pointer
	pop cx			; recover total blocks in chunk
	sub cx, dx		; reduce by # of blocks read
	jg short .osrlp1	; more left in this chunk?
	cmp bx, other_tbl	; more chunks left to do?
	jg .osrc

	bswap edi		; recover start pointer
	mov bx, di
	mov dl, bh
	shl dx, 12
	mov es, dx
	shl bx, 8
	mov dx, di		; save start pointer for later
	mov ax, [es:bx]		; verify signature, 1st two bytes of file
	cmp ax, 0xD5D5		; 0xD5D5 = 2 byte signature for OS
	je short infosav

	mov bx, m_osinv		; file failed OS signature test
	call dsperr
	jmp osread		; HIHI jump back and let user choose a different OS file

infosav:
; HIHI get total memory size and save upper word into totmem (must be mult of 64K)
; get and save memory hole info (into first_sz_tbl+532 -- there is 23K of space there!)
; GET VIDEO MODES NOW!!
; set the keyboard to scanset #1 here! HIHI
; MUST NOT TOUCH EDX! It's my pointer to the OS entrypoint.

; Set the Real Time Clock (in cmos) to read in hex, get minutes & seconds, disable NMI
; NMI is only used for memory parity errors, and hardware crashes. Unrecoverable?

	cli		; disable interrupts at cpu, now that they are being corrupted
	; (and all the INT calls are complete)
	mov si, RTCTime
	mov AL, 0x8b			; get configuration byte
	out 0x70, al
	call io_delay

	in al, 0x71
	mov ah, al
	and ah, 0xe			; kill all the interrupt bits, and DST
;	or ah, 6			; turn on hex and 24 hr bits -- HIHI setting the 4 bit crashes bochs! :-\
;	mov al, 0x8b
;	out 0x70, al
;	call io_delay
;	mov al, ah
;	out 0x71, al			; and write setting to cmos
;	call io_delay

	mov AL, 0x82			; disable NMI and read minutes
	out 0x70, AL
	call io_delay

	in AL, 0x71			; minutes in AL
	mov [si], al
	mov AL, 0x80			; disable NMI and read seconds
	out 0x70, AL
	call io_delay

	in AL, 0x71			; seconds in AL
	mov [si+1], al

	mov bp, 0xb00		; get the upper word set to 000b:
	bswap ebp	; and at the same time, recover the saved line position
	add BP, 0xa0	; move display point to next line, but a 32 bit address. ;)


; probably shouldn't set data segment registers yet

; disable paging (bit31), enable protected mode (bit 0)
; (direct mapping. No "virtual" address translations. No page faults.)

	MOV EAX, CR0
	OR EAX, 1		; prot mode on
	AND EAX, 0x7fffffff	; no paging
	MOV CR0, EAX

	JMP 0008:MEMTST	; far jump to set CS into protected mode

; dsperr dumps the error message bytes (pointed by AX) to b8000 video text memory

dsperr:
; destroys: BX, upper words of EBP and EAX

	bswap EAX		; save these two working registers the cheap way
	mov AX, BP
	bswap EBP
	mov BP, AX
.msglp:
	MOV AL, [BX]
	inc BX
	test AL, AL
	je short .stop
	mov [FS:BP], AL
	inc BP
	inc BP
	jmp short .msglp
.stop:
	bswap EAX		; restore the saved value of AX
	; (then back the pointer up to the beginning of the line again)
	bswap EBP
	ret

m_boot:	db	'booting Bang! - preparing to load kernel',0
m_a20:	db	'Could not set A20 - fatal',0
m_clr:	db	'                                                   ',0
m_ei13:	db	'No INT 13h LBA extensions, cannot read disk - fatal',0
m_sz:	db	'Disk is corrupted, no size tables match - fatal',0
m_ld:	db	'loading 64k blocks: ',0
m_rootb: db	'Filesystem root directory entry is corrupt - fatal',0
m_read: db	'Hardware error when reading disk - fatal',0
m_nfnd: db	'Could not find specified OS file in root directory',0
m_osb:	db	'Filesystem entry for specified OS file is corrupt',0
m_osinv: db	'Specified boot file is not a valid OS boot file',0
m_nopci: db	'No PCI bus detected, cannot boot on this computer - fatal',0


; io_delay wastes a few clock cycles, to allow the IOPort bus to "settle"
io_delay:
	push cx
	mov cx, 2
iodlylp:
	xor ax, 0xf000
	xor ax, 0xf00
	xor ax, 0xf0
	xor ax, 0xf
	xor ax, 0xffff		; ax is now unchanged from before
	loop iodlylp
	pop cx
	ret

; snlocat finds a requested string definition in a size table

snlocat:
; input: ax = string number to search for, bx -> size table (past header)
; return: carry flag set if not found, otherwise bx -> table entry +2
; destroys: upper word of ecx

	bswap ECX
	mov cx, 12			; table record size
	test byte [bx-4], 0x80		; does disk have 8 byte LBAs? (test format byte)
	je short snretry
	mov cx, 20
snretry:
	test dword [bx], 0xffffffff
	jne short .sncnt		; are the string # and length both 0?
	test dword [bx+4], 0xffffffff
	jne short .sncnt		; is the start LBA also 0?
	test dword [bx+8], 0xffffffff
	jne short .sncnt		; reached end of size table?
	stc				; set error flag
	bswap ECX
	ret
.sncnt:
	cmp [bx], ax
	je short .snfnd
	add bx, cx
	jmp short snretry	; not a match, try next table entry
.snfnd:
	add bx, 2		; found match! Point bx properly -- this will also set cf
	bswap ECX
	ret

; rdcont reads a specified number of contiguous LBA blocks to memory

rdcont:
; input: cx = total number of blocks, bx -> memory read buffer
;        ax -> starting LBA, SI= wrkspc
; return: carry flag set if unable to read all blocks
; destroys: eax, ebx, cx, si, upper word of ebp
; upper word of edx is forced to 0 -- it should be that way anyhow
; LBA in DAPACK is advanced beyond last block read, and ax is zeroed
; if ax is zero, the contiguous read point in DAPACK is used
; important: bx is only in the 1st segment!

	push dx			; preserve dx
	xor dx, dx
	bswap EBP		; save the screen location
	mov bp, DrvNum
	mov dl, [bp]		; put drive letter in dl
	mov SI, DAPACK		; address of "disk address packet"

	test ax, ax	; if ax is a null pointer, use the lba value saved in DAPACK
	je short .rdcmo

	push dx				; load lbas from pointer value in ax
	bswap ebx
	mov bx, ax
	mov edx, [bx]			; get low dword of lba
	mov [SI+8], edx			; store lba (4 byte)

	mov edx, [bx+4]			; get high dword of 8 byte lba (if used)
	mov bx, first_sz_tbl+4		; using 8 byte lbas?
	test byte [bx], 0x80
	je short .rdpdx
	mov dword [SI+12], edx		; store high dword of 8 byte lba
.rdpdx:
	xor edx, edx			; 0 out high word of edx
	pop dx
	bswap ebx
.rdcmo:

	mov [SI+2], cx		; blks to read
	mov [SI+4], bx		; buffer address
	mov AH, 42h
	int 13h			; int 13h destroys upper words of many registers!
	jnc short .rdcok

	bswap EBP
	xor ax, ax		; ax is corrupted anyway. May as well return 0.
	pop dx			; restore dx
	ret

.rdcok:
	mov dx, [SI+2]		; number of blks actually read
	; HIHI if dx>cx error? I never call this routine asking for more than 64

	add [SI+8], edx		; upper word of edx is always 0

; 8 byte LBA stuff:
	jnc short .rdcfin
	; check the carry bit, & if set, add one to hiLBA!
	push bx
	mov bx, first_sz_tbl+4
	test byte [bx], 0x80
	pop bx
	je short .rdcfin
	inc dword [SI+12]

.rdcfin:
	mov ax, dx		; preserve # of blocks read in ax
	shl dx, 9		; convert # of blocks to bytes
	push cx
	mov cl, [bp+5]		; include blocksize shift
	shl dx, cl
	pop cx
	add bx, dx

	xor dx, dx
	mov dl, [bp]		; put the drive letter back into DL,
	sub cx, ax		; cx = # of blocks still to read
	jg short .rdcmo

.rddone:
	bswap EBP		; the sub cleared cf
	xor ax, ax		; only want to use the LBA value in DAPACK, now
	pop dx			; restore dx
	ret


traccls:
; input: ax = high word of 1st cluster, bx = low word of 1st cluster
; return: carry flag set if trace fails, eax = last cluster, bswapped
; LBA chunks of file (in order) are stored, in the "other table" memory area
;   format: 4 or 8 byte start LBA, 4 byte contiguous block count, repeat.
; destroys: eax, ebx, ecx, edi, dx (upper word forced to 0)

; verify that the requested A table is already in memory
	mov si, other_tbl-12	; save point for LBAs as they are read
	xor ecx, ecx		; fake first entry in table (guaranteed not contig with nxt entry)
	; (need to clear upper cx, since it may have been set in snlocat)
	mov cx, si		; (20 bytes below other_tbl have been pre-zeroed)
	mov si, ATBLB

trclp:
	mov dx, bx		; save the subcluster number here
	bswap EBX		; and here, too!
	xor bx, bx
	test byte [si+26], 32	; is the first A table valid?
	je short .trcat2
	cmp ax, [si]		; 1st ATBLB entry
	jne short .trcat2
	mov bh, 0x20
	mov es, bx
	mov bx, si		; point bx to correct ATBLB entry
	jmp short .trcnxtc

.trcat2:
	test byte [si+26], 64	; is the 2nd A table valid?
	je short .trclda
	cmp ax, [si+ 12]	; 2nd ATBLB entry
	jne short .trclda
	mov bh, 0x60
	mov es, bx
	mov bx, ATBLB +12	; point bx to correct ATBLB entry
	jmp short .trcnxtc

.trclda:
; overwrite the last invalid A table, or the first one if none are invalid
	mov bh, 0x60
	test byte [si+26], 64	; is the 2nd A table valid?
	je short .trccla
	mov bh, 0x20		; overwrite 1st A table

.trccla:
	push cx
	push dx			; save one more copy of the subcluster number
	call ldatbl		; load the A table from disk
	pop bx
	bswap ebx		; reload the subcluster number into upper ebx
	pop cx
	jnc short .trcsbx
	xor eax, eax		; error return
	ret
.trcsbx:			; find A table entry again -- assume it's the 1st
	mov bx, ATBLB		; point bx to first ATBLB entry
	mov si, bx
	test byte [si+26], 32	; is it valid?
	je short .trcsb2
	cmp ax, [bx]		; is it the right table?
	je short .trcnxtc

.trcsb2:
	mov bx, ATBLB +12	; point bx to correct (2nd) ATBLB entry


.trcnxtc:
; OK, es and up to 3 more memory pages contain the A table to find the current
; cluster in -- to chain to the cluster after that.
;

; if I want, I can compare [bx+2] against dx here, to make sure dx is valid
; dx was already loaded with the cluster number.
	test ax, ax		; if this is the 0-0 string, need to dec DX
	jne .trcdx
	dec dx
.trcdx:
	bswap EDX		; save the subcluster number temporarily
	mov dl, [si+28]		; artificial cluster size shift value
	mov si, cx		; si now points at the output table
	mov cl, al		; get cluster size nibble in cl
	and cl, 0xf	; how many blocks in the cluster? (as a shift)
	add cl, dl		; do artificial size increase
	xor dx, dx		; make sure upper word of EDX is zero again
	bswap EDX
	shl edx, cl	; edx now holds the block offset from start of string

	add edx, [bx+4]		; add string start LBA
	mov [si+12], edx	; store new lba at next table position
	mov edx, [bx+8]
	jc short .trc2tb	; did addition cross an FFFFFFFF boundary?
	mov dword [si+16], edx	; no, just store high lba without modification
	jmp short .trcctg
.trc2tb:
	inc edx			; yes, increment the upper dword
	mov [si+16], edx

.trcctg:			; is this cluster contiguous with the previous one?
	mov edx, [si]		; start lba (low 4b) of previous read
	add edx, [si+8]		; length of previous read
	jc short .trcc2tb	; did it cross an FFFFFFFF boundary?

	cmp edx, [si+12]	; does it match the current start LBA?
	jne short .trcnctg
	mov edx, [si+4]
	cmp edx, [si+16]	; do the high lba dwords match?
	jne short .trcnctg
	mov edx, 1		; Yes! It IS contiguous.
	shl edx, cl
	add [si+8], edx		; Add to the previously stored read operation.
; HIHI verify that this doesn't go over 1300
	jmp .trclk

.trcc2tb:
	cmp edx, [si+12]	; does it match the current start LBA?
	jne short .trcnctg
	mov edx, [si+4]		; increment the old high lba
	inc edx
	cmp edx, [si+16]	; do the high lba dwords match?
	jne short .trcnctg
	mov edx, 1		; Yes! It IS contiguous.
	shl edx, cl
	add [si+8], edx		; Add to the previously stored read operation.
; HIHI verify that this doesn't go over 1300
	jmp short .trclk

.trcnctg:
	mov edx, 1		; No. Not contiguous.
	shl edx, cl
	add si, 12		; bump to new table entry
; HIHI verify that si doesn't go higher than bootld size + 12K -- 1024 entries at 12b per
	mov [si+8], edx		; insert length

.trclk:
	xor dx, dx		; upper word is still 0
;	mov [si+12], edx		this long always gets reset anyway
	mov [si+16], edx	; set end of table, if needed
	mov [si+20], edx	; (this is the really important one)
	bswap EBX		; recover the subcluster number
	mov dx, bx		; put it in dx
	; calculate the dword offset into the A table!

	test ax, ax
	jne short .trcnsb
	dec dx			; if this is string 0-0 subtract 1 -- didn't save it before
.trcnsb:
	shl edx, 2		; 4 bytes per A table entry
	cmp edx, 0xffff		; on first page?
	jb short .trcfp
	bswap edx		; get access to upper word. Save lower.
	shl dx, 4		; turn 0x0100 into 0x1000
	mov cx, es		; what es page was I on?
	add dx, cx		; increment it
	mov es, dx
	bswap edx		; get the page dword offset back
.trcfp:
	mov cx, si
	mov si, ATBLB
	push bx
	mov bx, dx

	mov edi, [es:bx]	; get the new cluster # off the A table!

	pop bx
	test edi, edi		; is it 0?
	jne short .trcnz

	stc			; illegal. Traced to an "unallocated" cluster.
	xor eax, eax
	ret

.trcnz:
	cmp edi, 0xffffffff	; eof?
	jne short .trcnxt
	bswap EAX		; DONE!!! Set ax properly and return.
	mov ax, bx		; the above cmp cleared the carry bit
	ret

.trcnxt:
	mov bx, di
	bswap edi
	mov ax, di
	jmp trclp


; loads an A table into one of 2 memory "slots"

ldatbl:
; input: ax = string # of A table, bx = 1st memory page number to store
;        si = ATBLB
; return: carry flag set if load fails
; destroys: ebx, ecx, edi, high word of eax, si

;read A table into es page, and maybe next 3 pages
;  (mem can hold 2 A tables at most)

	mov cx, bx
	shr cx, 14		; either 0 or 1
	mov es, bx		; store first 64K of A table on es page (2 or 6)
	mov gs, bx		; need to recover es after loading data

	mov bx, first_sz_tbl+8	; this is the validated size table
	call snlocat		; ax is already set properly
	jnc .ldacs0
	ret			; couldn't find ax string in size table

.ldacs0:
	test cx, cx
	jne .ldacs1
	; copy string info into ATBLB, from size table
	mov [si], ax		; string # -> ATBLB
	mov di, ax		; save string # to test against signature
	mov ax, [bx]		; ax now holds string length of A table
	mov [si+2], ax		; string length -> ATBLB
	mov ecx, [bx+2]		; get start LBA
	mov [si+4], ecx		; store start LBA -> ATBLB
	or byte [si+26], 32
; 8 byte LBA stuff:
	mov si, first_sz_tbl+4	; format byte for size table
	test byte [si], 0x80	; 8 byte LBAs?
	mov si, ATBLB
	je short .ldcblk

	mov ecx, [bx+6]		; get start LBA upper dword
	mov [si+8], ecx		; store -> ATBLB
	add bx, 4
	jmp short .ldcblk

.ldacs1:
	; copy string info into ATBLB, from size table
	mov [si+12], ax		; string # -> ATBLB
	mov di, ax		; save string # to test against signature
	mov ax, [bx]		; ax now holds string length of A table
	mov [si+14], ax		; string length -> ATBLB
	mov ecx, [bx+2]		; get start LBA
	mov [si+16], ecx	; store start LBA -> ATBLB
	or byte [si+26], 64

; 8 byte LBA stuff:
	mov si, first_sz_tbl+4	; format byte for size table
	test byte [si], 0x80	; 8 byte LBAs?
	mov si, ATBLB
	je short .ldcblk

	mov ecx, [bx+6]		; get start LBA upper dword
	mov [si+20], ecx	; store -> ATBLB
	add bx, 4

.ldcblk:
	add bx, 6		; point bx at A table LBA entry in size table
	push dx			; preserve dx
	mov dx, bx		; save that bx pointer in dx

	; calculate number of blocks in A table into ax (I only want to scan forward)

	shr ax, 7	; divide string length by 128 = size of 1st table copy in "blocks"
	mov cl, [si+29]	; is a block bigger than 512? If so, divide some more.
	shr ax, cl
	inc ax		; should equal 512 for 65535 length, and 512b blocks

	mov bx, 64	; how many blocks are in 32K?
	shr bx, cl	; if a block is bigger than 512 bytes
	mov cx, ax	; total number of blocks still to read

;	dec ax		; verify that (cx-1)/bx is <= 8
;	push dx
;	xor dx, dx
;	div bx
;	pop dx
;	cmp ax, 8
;	jbe .ldoks
;	stc		; trying to load more than 256K. Error!
;	bswap eax	; recover low word of ax
;	ret
;.ldoks:

	mov ax, dx	; start lba pointer goes in ax
	pop dx		; restore dx

; The section below is "readlba" for the A tables

; It is not pretty. There are 3 sections. The first deals with the very first block of
; the A table, that contains the 4 header bytes. Verify, then toss all 4. This helps when indexing the table.
; The second section simply copies 32K into the page.
; The third deals with the memory page transition. Because of the header bytes, the
; copy is always 4 bytes below a page boundary. So, it copies 4 bytes to get to
; the page boundary, and then the rest of the 32K onto the next page, then loops
; back to section 2.

	cmp bx, cx
	jbe short .ldar1	; is there less than 32K left to read?
	mov bx, cx
.ldar1:
	bswap ecx	; total blks left to read stored in upper word of ecx

	push bx		; save the number of blocks being read this time
	mov cx, bx
	mov bx, 0x8000

	call rdcont
	jnc .ldcpy1

	pop bx		; rdcont error. Fix the stack & die.
	mov cx, gs
	mov es, cx
	bswap eax	; recover low word of ax
	ret
.ldcpy1:
	; successful read -- copy ds:si to es:di the fast way & skip the header

	mov si, 0x8000
	mov cx, 16382		; copy 32K minus 4 bytes, using shorts

	mov bx, [si]
	; HIHI bl should equal A7 -- test and crash if wrong?
	; bh should equal the high byte of the string length
	mov bx, [si+2]
	; HIHI bx should be equal to the string # in di

	add si, 4
	bswap edi		; save string # in upper word of edi
	xor di, di

	rep movsw

; di will finish at es:7ffc

	bswap ecx
	pop bx
	sub cx, bx	; blks still to read, after reading this batch
	jg short .ldalp

	mov cx, gs		; the sub cleared cf
	mov es, cx
	bswap edi		; recover string #
	mov ax, di
	ret

.ldalp:
	; rdcont 32K again
	cmp bx, cx
	jbe short .ldar2	; is there less than 32K left to read?
	mov bx, cx
.ldar2:
	bswap ecx	; total blks left in ecx again

	push bx		; # of current read blks
	mov cx, bx
	mov bx, 0x8000

	call rdcont
	jnc .ldcpy2

	pop bx		; fix the stack, if crashing
	mov cx, gs
	mov es, cx
	bswap edi	; recover low word of ax
	mov ax, di
	ret
.ldcpy2:
	; successful read again -- copy

	mov si, 0x8000
	mov cx, 16384		; copy 32K, using shorts
	rep movsw

; di will finish at es:fffc

	bswap ecx
	pop bx
	sub cx, bx	; blks still to read, after reading this batch
	jg short .ldas3

	mov cx, gs		; the sub cleared cf
	mov es, cx
	bswap edi		; recover string #
	mov ax, di
	ret

.ldas3:

	; rdcont 32K again
	cmp bx, cx
	jbe short .ldar3	; is there less than 32K left to read?
	mov bx, cx
.ldar3:
	bswap ecx	; total blks left in ecx again

	push bx		; # of current read blks
	mov cx, bx
	mov bx, 0x8000

	call rdcont
	jnc .ldcpy3

	pop bx		; fix the stack if crashing
	mov cx, gs
	mov es, cx
	bswap edi	; recover string #
	mov ax, di
	ret
.ldcpy3:
	; successful read again -- copy

	mov si, 0x8000
	movsd			; copy the 4 remaining bytes on the page
; di will just exactly overflow the page (=0), here

	mov bx, es		; bx is available
	add bx, 0x1000		; add 0x1000 to page num
	mov es, bx

	mov cx, 16382		; copy rest of 32K minus 4 bytes, using shorts
	rep movsw

	bswap ecx
	pop bx
	sub cx, bx	; blks still to read, after reading this batch
	jg short .ldalp

	mov cx, gs		; the sub cleared cf
	mov es, cx
	bswap edi		; recover string #
	mov ax, di
	ret

SEGMENT PROT USE32

MEMTST:
; point register DS to the 3rd entry in the GDT, the "data" entry
; now that the processor is in pmode, it will load the hidden parts correctly

	MOV BX, 16
	mov ds, bx
	mov es, bx
	mov fs, bx
	mov gs, bx
	mov ss, bx

; MUST initialize the PICs -- send ICW1 = 0x11
	mov AL, 0x11	; ICW1 command for pic1
	out 0x20, AL
	call io_dly32
	out 0xA0, AL	; ICW1 command for pic2
	call io_dly32

	mov AL, 0x20	; map IRQ0 on PIC1 to Int0x20, and 7 more consecutively
	out 0x21, AL
	call io_dly32
	mov AL, 0x28	; map IRQ8 on PIC2 to Int0x28 and consecutively
	out 0xA1, AL
	call io_dly32

	mov AL, 4	; set IRQ2 on PIC1 connection to slave IRQ9, PIC2
	out 0x21, AL
	call io_dly32
	mov AL, 2
	out 0xA1, AL
	call io_dly32

; then send the init commands to turn them on
; one of my sources says to send both these codes to port 0x20 and A0
; the other says send them to 0x21 & A1 -- and THAT one is right!

	mov AL, 1	; init command for pic1
	out 0x21, AL
	call io_dly32
	out 0xA1, AL	; init command for pic2
	call io_dly32

	xor AL, AL	; 0 = enable interrupts (0xff to disable)
	out 0x21, AL	; enable all hardware IRQs on PIC1
	call io_dly32
	out 0xA1, AL	; enable all hardware IRQs on PIC2
	call io_dly32
; (but remember that interrupts are still blocked at the cpu!)

		; recover the os start pointer (>>8)
	shl edx, 8		; unshift it, now it's a 32bit addy
	mov esi, edx		; save a copy in esi to pass to the kernel

	add edx, 2		; kernel init entry point -- edx + 2
	JMP EDX			; run the kernel!

; io_dly32 is a PMODE version of io_delay
io_dly32:
	push ecx
	mov ecx, 2
dlylp32:
	xor ax, 0xf000
	xor ax, 0xf00
	xor ax, 0xf0
	xor ax, 0xf
	xor ax, 0xffff		; ax is now unchanged from before
	loop dlylp32
	pop ecx
	ret

; NASM ERROR!!
; The assembler keeps misaligning the ending tables!
; It inserts 3 nop commands here, where it doesn't need any.

align 4

;	db	0x90		; kludge to manually realign memory

vnamp:
	dd	0
	db	'e',0,0,0

