;XIX System 19 Bootloader - Version pre-Alpha
;Copyright (C) 2010 Brian D. Knopp
;
;This program is free software: you can redistribute it and/or modify
;it under the terms of the GNU General Public License as published by
;the Free Software Foundation, using version 3 of the License.
;
;This program is distributed in the hope that it will be useful,
;but WITHOUT ANY WARRANTY; without even the implied warranty of
;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;GNU General Public License for more details.
;
;You should have received a copy of the GNU General Public License
;along with this program.  If not, see <http://www.gnu.org/licenses/>.
;
;
;This version of the XIX System 19 Bootloader is used
;specifically to setup a suitable environment to load
;the XIX Kernel and execute it.  Future features
;include the ability to detect the best route to perform
;its appointed duty by BIOS ID, error handling/reporting
;and multi-boot features.
;
;For full documentation, read the source-enclosed
;bootloader.ldr.doc file

[BITS 16]	;Assembler Directive denoting this as 16-bet Real Mode
[ORG 00h]  ;MODIFY	;Assembler Directive denoting this as existing at 7E00h

begin:		;function to jump over the data section and into the main boot sequence
	jmp 8000h:boot  ;MODIFY


;Section for Functions
prntstr:	;function to print a string loaded into AL
	mov ah, 0Eh		;load 0Eh (teletype) into AH

	mov bh, 00h		;set page number to 0 (page 1)
	mov bl, 0Ah		;set attribute to Green Text, Black Background, non-flashing

	.nxtchar		;label to repeat int 10h
	cld			;clear direction flag
	lodsb			;load string in SI, into AL
	or al, al		;check to see if AL = null char (set zero if true)

	jz .ret			;jump over int 10h and exit function

	int 10h			;call int 10h to print the string
	jmp .nxtchar		;repeat the routine if null character is not yet present

	.ret			;label to jump to, to get out of the loop
ret

a20en:		;function to enable the A20 Gate
	cli			;clear interrupts to disallow interuption of procedure

	in al, 92h		;open AL to port 92h
	or al, 02h		;send value 02h to AL register
	out 92h, al		;close AL port 92h

	sti			;re-enable interupts

	lea si, [a20mess] 	;load the A20 Message into SI register
	call prntstr		;print the string
ret

krnlod:		;function to load the kernel into memory
	jmp .rstdsk		;jump over error messages

	.rsterr
	lea si, [dskrsterr]	;load the error string into SI
	call prntstr		;print the string
	cli			;clear interupts
	hlt			;enter unrecoverable halt

	.rstdsk
	mov ah, 00h		;function to reset disk controller
	mov dl, [bootdrv]	;drive to reset controller
	
	int 13h			;call int 13h to reset disk
	jc.rsterr		;if carry flag is set (reset unsuccessfull) go to error routine
	
	jmp .rddsk		;jump over error function to read the disk

	.rderr			;label to jump to if error occurs
	lea si, [krnloderr]	;load the error sting into SI
	call prntstr		;print the string
	cli			;clear interupts
	hlt			;enter unrecoverable halt

	.rddsk
	mov ax, 9200h		;load 9200h into AX register (can't directly manipulate ES)
	mov es, ax		;set ES to contents of AX (location of memory to read to)
	xor bx, bx		;set offset to 0000h

	mov ah, 02h		;place 02h (read function) into AH
	mov al, 12h		;read 18 sectors
	mov ch, 00h		;read from cylinder 1
	mov cl, 04h		;read from sector 4
	mov dh, 00h		;read from head 0
	mov dl, [bootdrv]	;read from drive

	int 13h			;call int 13h to read from disk
	jc .rderr		;if carry flag is set (read unsuccessfull) go to error routine

	lea si, [krnmess]	;load the address of the Kernel Load Message into SI
	call prntstr		;print the string	
ret

gdtset:		;function to setup and load the Global Descriptor Table
pusha

push ds     ;MODIFY
push es     ;MODIFY

	mov si, gdt		;start of GDT table into SI register
	mov di, [gdtbse]	;locate GDT at 500h in memory
	mov cx, [gdtsze]	;size of the GDT (defined my fancy footwork)
        inc cx            ;MODIFY: one more byte to accout the formule in

        mov ax,8000h  ;MODIFY
        mov ds,ax     ;MODIFY
	xor ax, ax		;clear ax register		
	mov es, ax


	cld			;clear the direction flag
	rep movsb		;move byte from DS:SI to ES:DI


pop es     ;MODIFY
pop ds     ;MODIFY
	lgdt[gdtr]		;load the Global Descriptor Table


	lea si, [gdtmess]	;load the address of the GDT Setup Message into SI
	call prntstr		;print the string

popa
ret


;Section for Strings
sysmess db 'XIX System 19 Bootloader - Version pre-Alpha',13,10,0	;System Information String
									;13 = char return
									;10 = new line
									;0 = null character (terminate)

a20mess db 'A20 Gate Successfully Enabled.',13,10,0

krnmess db 'Kernel Loading Successful.',13,10,0

dskrsterr db 'ERROR - Reset of Disk Unsuccessfull - ABORT',13,10,10,0

krnloderr db 'ERROR - Kernel Loading Unsuccessfull - ABORT',13,10,10,0

gdtmess db 'Global Descriptor Table Successfully Setup.',13,10,0

pmodmess db 'Will now enable Protected Mode, and boot the Kernel...',13,10,10,0


;Section for Variables
bootdrv db 0		;variable to hold boot drive number

;Section for Descriptor Tables
gdtr:
gdtsze dw gdtend-gdt-1	;size of GDT is C0h (192 bytes), each descriptor is 64-bytes long
gdtbse dd 500h		;where GDT is located at (500h)

gdt:
null	equ $-gdt	;this is the null descriptor
	dd 0x0000	;fill the null selector with 00h properties
	dd 0x0000

code	equ $-gdt  	;code segment with 4GB flat memory model
	dw 0xFFFF	;first word of limit field (use with second to denote 4GB size)
	dw 0x0000	;first word of the base field (Descriptor begins at 00h)
	db 0x00		;third byte of the base field
	db 0x9A		;first byte of attribute flags: (present,ring0,predef,nonconforming,read/execute,not accessed)
	db 0xCF		;second word of the limit/attribute field: (Fh limit2, 4kb granularity,32bit,zero, available)
	db 0x00		;forth byte of the base field

data	equ $-gdt	;data segment with 4GB flat memory model
	dw 0xFFFF	;first word of limit field (use with second to denote 4GB size)
	dw 0x0000	;first word of the base field (Descriptor begins at 00h)
	db 0x00		;third byte of the base field
	db 0x92		;first byte of attribute flags: (present,ring0,predef,nonexpdown,read/write,not accessed)
	db 0xCF		;second word of the limit/attribute field: (Fh limit2, 4kb granularity,32bit,zero, available)
	db 0x00		;forth byte of the base field
gdtend:		;empty function to denote end of GDT in memory


;Main Program
boot:





;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
;;;INIT: Setup Unreal Mode
 ;NOTE:
 ;    For the full reference and updates see:
 ;
 ; http://126.sytes.net/projects/x86/OS/LowEST/x86s/unreal86.asm
 ;
 ; http://126.sytes.net/projects/x86/OS/LowEST
 ;;


 ;Set up CS, DS and ES to the
 ;exact same value:
 ;;
  push cs
  push cs
  pop ds
  pop es


 pushad
 call clearscreen


;push ds
;xor ax,ax
;mov ds,ax
;a32 o32 mov dword[0xB8000],"aBcD"
;pop ds
;cli
;hlt



 ;;Prepare our Protected-Mode-Ready GDTR and selectors
 ;;to DOS/Real Mode addressing for load and set easy
 ;;32-bit base addresses selectors for using like in
 ;;DOS.
 ;;;
   call ConfigGDTselectors

 cli               ;Disable our interrupts...
  call enableA20   ;                         ...to enable Gate A20


;;;INIT: Here we will finally enter full 32-bit Protected Mode
;;;INIT: Here we will finally enter full 32-bit Protected Mode
;;;INIT: Here we will finally enter full 32-bit Protected Mode

  ;;Save our Real Mode Segment Registers:
  ;;Save our Real Mode Segment Registers:
  ;;Save our Real Mode Segment Registers:
  ;;;
   push ds
   push es
   push fs
   push gs


   ;;Save original SS in the BP register.
   ;;If we want to use it freely, we MUST
   ;;push it into the Protected Mode stack
   ;;only and only after setting it properly:
   ;;;
    push cs     ;Store original CS segment value
    pop bp      ;Put it in lower 16 bits of EBP
    shl ebp,16  ;Move it to higher 16 bits of EBP

    mov bp,ss          ;Save SS in BP (lower 16 bits of EBP)
    mov [oldesp],esp   ;Save original ESP in a Real Mode variable

    ;;;;
    ;;;;At this point, EBP contains the original values of CS and SS.
    ;;;;The lower 16 bits (usual BP register) contain the SS value.
    ;;;;The higher 16 bits contain the CS value.
    ;;;;;;
    ;:;;;;;


  ;;Load our GDT:
  ;;Load our GDT:
  ;;Load our GDT:
  ;;;
   lgdt [GDT]



  ;;Enable PE Bit and Thus, Initial Protected Mde:
  ;;Enable PE Bit and Thus, Initial Protected Mde:
  ;;Enable PE Bit and Thus, Initial Protected Mde:
  ;;;
   mov eax,cr0
   inc ax
   mov cr0,eax


  ;;Enter to Full Basic Protected Mode using a DOS Base-addressed Code Selector:
  ;;Enter to Full Basic Protected Mode using a DOS Base-addressed Code Selector:
  ;;Enter to Full Basic Protected Mode using a DOS Base-addressed Code Selector:
  ;;;
   a32 jmp dword SELCod32DOS:bits32


  bits 32  ;Now we use 32-bit instructions
  bits32:  ;This is our label for 32-bit PM Entry Point



   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
   ;;;INIT: Protected Mode CPU Configuration Examples
     ;;This is a sample of how to load 32-bit
     ;;data segments with a DOS Base-addressed
     ;;Data Selector:
     ;;;
      mov ax,SELDat32DOS
      mov ds,ax
      mov es,ax
      mov fs,ax
      mov gs,ax


     ;;Set up a Protected Mode Stack in a high address:
     ;;;
      mov ax,SELDat32        ;Our full 4GB data segment
      mov ss,ax              ;Put it into SS
      mov esp,(1048576*2)-1  ;Our Protected Mode Stack Pointer at end of stack


      ;;Safeguard original SS value in our Protected Mode Stack (VitalOper#SS):
      ;;Safeguard original SS value in our Protected Mode Stack (VitalOper#SS):
      ;;Safeguard original SS value in our Protected Mode Stack (VitalOper#SS):
      ;;;
        push ebp





      ;;Restore original SS value into BP (VitalOper#SS):
      ;;Restore original SS value into BP (VitalOper#SS):
      ;;Restore original SS value into BP (VitalOper#SS):
      ;;;
        pop ebp

   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples
   ;;;END:  Protected Mode CPU Configuration Examples


     ;;Now we jump to a 16-bit Protected Mode code
     ;;area, for preparation to return to Real Mode,
     ;;using a selector base Address according to where
     ;;DOS put us:
     ;;;
      jmp SELCod16DOS:bits16


  bits 16  ;Now we use 16-bit instructions
  bits16:  ;This is our label for 16-bit PM Entry Point


   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use
   ;;;INIT: At this stage we must not make any further calls or stack use

     ;;Temporarily take our DOS-like 32-bit selector
     ;;into DS to reload the original ESP value we
     ;;saved in the [oldesp] variable which is found
     ;;at a Real-Mode reachable address:
     ;;;
      mov ax,SELDat32DOS        ;Take it
      mov ds,ax                 ;Load DS
      mov esp,[oldesp]          ;Our opportunity to get the original ESP value




     ;;Here we will leave our code segments with
     ;;32-bit addressable data segments. Without
     ;;it, we would return to Real Mode and not
     ;;to Unreal Mode if we used "SELDat16" or
     ;;"SELDat16DOS" instead of SELDat32:
     ;;;
      mov ax,SELDat32
      mov ds,ax
      mov es,ax
      mov fs,ax
      mov gs,ax


     ;;Configure SS back so it has a 16-bit
     ;;address size for Real Mode, so that
     ;;there are no strange problems and
     ;;lockups:
     ;;;
      mov ax,SELDat16
      mov ss,ax


  ;;Disable PE Bit and thus, go back to (Un)real Mode:
  ;;Disable PE Bit and thus, go back to (Un)real Mode:
  ;;Disable PE Bit and thus, go back to (Un)real Mode:
  ;;;
   mov eax,cr0
   dec ax
   mov cr0,eax



  ;;We must reload SS only after
  ;;disabling Protected Mode; otherwise,
  ;;loading it with its original Real Mode
  ;;value would be considered as loading an
  ;;invalid data selector into SS
  ;;;
    mov ss,bp


   ;;Attemtp to further flush the Protected Mode
   ;;Instruction Queue to stabilize (Un)real Mode:
   ;;;
    ror ebp,16       ;Get original CS value stored into EBP
    push bp          ;Push the CS value for far jump/return
    push word exit_  ;Push the code offset into CS segment for far jump/return
    ror ebp,16       ;Put the EBP value back
    retf             ;Far return to flush Protected Mode
    exit_:           ;(this is the only reliable way to alter back the code CS segment
                     ;in which basically consists "flushing the instruction queue")
    



   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use
   ;;;END:  At this stage we must not make any further calls or stack use



  ;;Restore our Real Mode Segment Registers:
  ;;Restore our Real Mode Segment Registers:
  ;;Restore our Real Mode Segment Registers:
  ;;;
   pop gs
   pop fs
   pop es
   pop ds






 popad

 ;;;INIT: Custom program directives; MODIFY for something suitable for another program
 ;;;INIT: Custom program directives; MODIFY for something suitable for another program
 ;;;INIT: Custom program directives; MODIFY for something suitable for another program

 sti          ;Enable our interrupts...
; mov ah,0x4C  ;                        ...to return...
; int 0x21     ;                                       ...to DOS.
;  int 20h
  jmp 8000h:boot2

 ;;;END:  Custom program directives; MODIFY for something suitable for another program
 ;;;END:  Custom program directives; MODIFY for something suitable for another program
 ;;;END:  Custom program directives; MODIFY for something suitable for another program


;;;END:  Here we will finally enter full 32-bit Protected Mode
;;;END:  Here we will finally enter full 32-bit Protected Mode
;;;END:  Here we will finally enter full 32-bit Protected Mode









;;INIT: Data/Constants definitions and Arch. Structures
;;INIT: Data/Constants definitions and Arch. Structures
;;INIT: Data/Constants definitions and Arch. Structures
   ;INIT: GDT
   ;INIT: GDT
   ;INIT: GDT
     GDT:
      SELNull equ 0    ;As you may see, we have used
        GDT_size:      ;the Null Selector as the GDT
          dw GDTsize   ;pointer to load with LGDT.
        GDT_actualPtr: ;
          dd GDT       ;You can see that the WORD at
          dw 0x0000    ;the end of these 8 bytes are
                       ;2 padding bytes with 0x0000.

      SELCod32 equ 8
      SelCod32:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10011010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 11001111b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELDat32 equ 16
      SelDat32:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10010010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 11001111b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELCod16 equ 24
      SelCod16:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10011010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 00001111b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELDat16 equ 32
      SelDat16:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10010010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 00000000b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)



      SELCod32DOS equ 40
      SelCod32DOS:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10011010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 11001111b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELDat32DOS equ 48
      SelDat32DOS:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10010010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 11000000b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELCod16DOS equ 56
      SelCod16DOS:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10011010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 00000000b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      SELDat16DOS equ 64
      SelDat16DOS:
        dw 0FFFFh       ; bits 0-15 length (Bytes 0-1)
        dw 00000h       ; bits 0-15 base addr (Bytes 2-3)
        db 0            ; bits 16-23 base addr (Byte 4)
        db 10010010b    ; bits 0-3 Type, 4 DT, 5-6 DPL & 7 P (Byte 5)
        db 00000000b    ; bits 16-19 length into 0-3, 6 D & 7 G (Byte 6)
        db 0            ; bits 24-31 base addr (Byte 7)

      GDT_end:

      GDTsize equ (GDT_end-GDT)-1
   ;END:  GDT
   ;END:  GDT
   ;END:  GDT
;;END:  Data/Constants definitions and Arch. Structures
;;END:  Data/Constants definitions and Arch. Structures
;;END:  Data/Constants definitions and Arch. Structures

























ConfigGDTselectors:
 push eax

 ;NOTE: For this routine, both DS and CS
 ;      must contain the exact same value!


 ;We will clear EAX to extend the
 ;value of 16-bit DS to 32-bit; then
 ;we will shift it 4 bits left to
 ;multiply it by 16, and so we will
 ;convert the Real Mode value in DS
 ;to a linear 20 or 32-bit-compliant
 ;address:
 ;;
  xor eax,eax
  mov ax,ds
  shl eax,4


 ;Save our original linear DS
 ;;
  push eax

   ;This is a segment for accessing data
   ;from the base address our program uses
   ;which might not be 0; we put the value
   ;of base address bits 0-15 for the GDT
   ;selectors for 16 and 32-bit data, for
   ;use in a DOS environment (or the environment
   ;of our bootloader using the base address
   ;configuration of DS --which is the main data
   ;segment register-- from Real Mode):
   ;;
    mov [SelDat32DOS+2],ax
    mov [SelDat16DOS+2],ax


   ;Now put bits of EAX 16-31 right into AX:
   ;;
    shr eax,16


   ;Do the same with bits 16-23 of base address
   ;for the GDT selectors for 16 and 32-bit "DOS"
   ;or "bootloader" data (which base address almost
   ;certainly might not be 0):
   ;;
    mov [SelDat32DOS+4],al
    mov [SelDat16DOS+4],al

   ;And the same with bits 24-31:
   ;;
    mov [SelDat32DOS+7],ah
    mov [SelDat16DOS+7],ah

 ;Restore our original linear DS
 ;;
  pop eax



 ;This is to convert the offset in which our
 ;GDT resides in this module to a linear address.
 ;Previously, we had converted DS to a 20-bit
 ;linear address in EAX, and by adding it to the
 ;GDT address found in this module, we get the
 ;correct direct physical pointer to the GDT, which
 ;is required to be so by the LGDT instruction (it
 ;requires a 6-byte variable which 4 first bytes
 ;are a variable that contains this GDT physical
 ;location):
 ;;
  add eax,GDT
;  add eax,80000h
  mov [GDT_actualPtr],eax


 ;-----------------------------------------------
 ;-----------------------------------------------
 ;-----------------------------------------------


 ;We will do the very same thing we just did with
 ;the Real Mode DS, but now with CS: convert it
 ;to a linear address and put it into a code segment
 ;selector in the GDT.
 ;
 ;It provides us with certain grade of relocatability
 ;for our program, which means that it should adapt
 ;to any Real Mode segments setup without changes:
 ;
 ;;
  xor eax,eax
  mov ax,cs
  shl eax,4


 ;Put bits 0-15 into the 16 and 32-bit
 ;selectors local to "DOS" or "bootloader"
 ;execution environments:
 ;;
  mov [SelCod32DOS+2],ax
  mov [SelCod16DOS+2],ax


 ;Now take the higher 16 bits of EAX in AX:
 ;;
  shr eax,16


 ;Put bits 16-23 into the 16 and 32-bit
 ;selectors local to "DOS" or "bootloader"
 ;execution environments:
 ;;
  mov [SelCod32DOS+4],al
  mov [SelCod16DOS+4],al


 ;Put bits 24-31 into the 16 and 32-bit
 ;selectors local to "DOS" or "bootloader"
 ;execution environments:
 ;;
  mov [SelCod32DOS+7],ah
  mov [SelCod16DOS+7],ah


 ;All other GDT selector fields were
 ;preconfigured and hardcoded from
 ;the source code.
 ;
 ;We have finished this duty...
 ;;

 pop eax
ret

























;This function waits until the
;Keybard Controller is ready to
;accept commands.
;;
;;;
  KeybCtrl_waitUntilCommandable:
  push ax


  .waitUntilReady:
   in al,0x64    ;Port 0x64 is the Status
                 ;Register of the keyboard
                 ;controller port located
                 ;on the motherboard.


   test al,00000010b ;We see if bit 1 of the returned
                     ;byte at 0x64 is set to 1, which
                     ;means that the controller is NOT
                     ;ready to accept commands. It means
                     ;"Input Buffer Full (port 0x60 or 0x64);
                     ;don't write yet".



   jnz .waitUntilReady  ;Repeat until bit 1 of byte from
                        ;port 0x64 is cleared to 0 or, in
                        ;other words, until the keyboard
                        ;controller is ready to accept
                        ;commands. It would mean "Input
                        ;Buffer Empty (port 0x60 or 0x64); can
                        ;be written".

     ;Note that writing the Input Buffer through
     ;port 0x64 causes the byte to be interpreted
     ;as a command.
     ;
     ;And if we write the Input Buffer through
     ;port 0x60 causes the byte to be interpreted
     ;as data, usually as a parameter to an immediate
     ;previously sent command at port 0x64.

  pop ax
    ret

























;This function waits until the
;Keybard Controller has a data
;byte ready for us to gather.
;;
;;;
  KeybCtrl_waitForDataForUs:
  push ax



  .waitUntilReady:
   in al,0x64    ;Port 0x64 is the Status
                 ;Register of the keyboard
                 ;controller port located
                 ;on the motherboard.


   test al,00000001b ;We see if bit 0 of the returned
                     ;byte at 0x64 is set to 0, which
                     ;means that the controller does NOT
                     ;have a data byte for us yet. It means
                     ;"Output Buffer Empty (port 0x60);
                     ;don't read yet".



   jz .waitUntilReady   ;Repeat until bit 0 of byte from
                        ;port 0x64 is set to 1 or, in
                        ;other words, until the keyboard
                        ;controller has a data byte to
                        ;give us. It would mean "Output
                        ;Buffer Full (port 0x60); can
                        ;be read".
  pop ax
    ret

























enableA20:
;;;Wait for controller to accept
;;;commands
;;
;
 call KeybCtrl_waitUntilCommandable


;;;Write Output Port (Command -- Step 1/2):
;;;Write Output Port (Command -- Step 1/2):
;;;Write Output Port (Command -- Step 1/2):
  mov al,0xD1    ;This command is to write the
                 ;status byte. This command is
                 ;called WRITE OUTPUT PORT.

  out 0x64,al    ;Here we send the command, and
                 ;it gets processed.


;;;Wait for controller to accept
;;;commands
;;
;
 call KeybCtrl_waitUntilCommandable


;;;Write The Output Port (Command Parameter -- Step 2/2):
;;;Write The Output Port (Command Parameter -- Step 2/2):
;;;Write The Output Port (Command Parameter -- Step 2/2):
  mov al,11111111b ;This is a data byte to serve
                   ;as a parameter to the previous
                   ;controller command (0xD1). We
                   ;are setting the necessary bits
                   ;here to the normal operation
                   ;of the controller, and, of course,
                   ;it is here that we enable the A20
                   ;Address Line by setting its bit
                   ;to 1.
  ;bit 0-Normal           (1) or Reset CPU (0)
  ;bit 1-Enable A20       (1) or Disable A20 (0)
  ;bit 2-Data to Mouse    (1) or Disabled (0)
  ;bit 3-Mouse Clock      (1) or Disabled (0)
  ;bit 4-IRQ1 Active      (1) or IRQ1 Inactive (0)
  ;bit 5-IRQ12 Active     (1) or IRQ12 Inactive (0)
  ;bit 6-Keyboard Clock   (1) or Disabled (0)
  ;bit 7-Data to Keyboard (1) or Disabled (0)


  out 0x60,al    ;We send this bit-set to the
                 ;data port of the keyboard. At
                 ;this point is where really the
                 ;A20 line gets enabled.


ret


oldesp dd 0














clearscreen:
 pushf
 pusha
  ;//Try to clear the screen:
  ;;;
    mov ah,6       ;//VIDEO - SCROLL UP WINDOW
    mov al,0       ;//number of lines by which to scroll up
                   ;//(00h = clear entire window)
    mov bh,0x7     ;//attribute used to write blank lines
                   ;//at bottom of window
    xor cx,cx      ;//row,column of window's upper left corner
    mov dx,0x1950  ;//80x25 ;DH,DL row,column of window's
                   ;//lower right corner
     int 10h

  ;//Set position of cursor at top of screen:
  ;;;
    mov ah,2   ;//VIDEO - SET CURSOR POSITION
    mov bh,0   ;//page number
               ;//   0-3 in modes 2&3
               ;//   0-7 in modes 0&1
               ;//   0 in graphics modes
    xor dx,dx  ;//DH,DL row (00h is top), column (00h is left)
      int 10h
 popa
 popf
ret
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode
;;;END:  Setup Unreal Mode



















































boot2:
	mov [bootdrv], dl	;save starting drive into variable [bootdrv]

	mov ax,8000h		;setup segment registers
	mov ds,ax
	mov es,ax
	mov fs,ax
	mov gs,ax


	mov ax, 0000h		;stack grows down from 7C00h
    	mov ss, ax

    	mov sp, 7C00h		;stack size is 0200h bytes
	mov bp, 7C00h
 
    	cld			;clear the direction flag

	lea si, [sysmess]	;load effective address of string sysmess into SI
	call prntstr		;call function to print the string

	call a20en		;call the function to enable the A20 Gate

;	call krnlod  ;MODIFY		;call the function to load the kernel

	call gdtset		;call the function to setup the Global Descripter Table	

	lea si, [pmodmess]	;load the PMode enabling message
	call prntstr		;print the string

	
	pmoden:			;inline function to enable Protected Mode
		cli			;permanently clear interrupts
		mov eax, cr0		;move contents of ControlRegister0 into ExtendedAX register
		or al, 1		;compare AL to value 1
		mov cr0, eax		;move CR0 into EAX register

	a32 jmp dword code:(_pmode+80000h)  ;MODIFY		;jump to 32 bit code to straighten out EIP

	[bits 32]
	_pmode  ;MODIFY
		mov ax, data		;align all data segments with the data descriptor
		mov ds, ax
		mov es, ax
		mov fs, ax
		mov gs, ax
;mov dword[0xB8000],"1234"  ;MODIFY
cli  ;MODIFY
hlt  ;MODIFY


		mov ss, ax		;align stack segment with data descriptor
		mov eax, 7C00h		;align base and stack pointers
		mov esp, eax
		mov ebp, eax

		jmp code:9200h	;jump to residence of Kernel
		hlt		;halt processor from executing this binary

;set bootloader to 1024 bytes (2 segments) long
times 1024-($-$$) db 0 ;MODIFY		;fill unused space upto 1024 bytes with 0