; COFFEE (Extended 2x COFF [AKA ELF]) OS FreePascal loader for 32-bit OS modes tripped from GRUB.
; This is nearly complete. We do not use RM drops as there is no need to ATM.
; APM Poweroff, though it works in REAL MODE is hardly supported these days and with GRUB loading us is
; impossible to get back to.(Crashes Pascal exit due to remapped IRQs)
; If we manage a way to turn this ELF kernel confabulation into a PE COFF COM file instead, then
; we can use APM off methods. Until then, we use ACPI or nothing until have ACPI off.
; NOTE: ACPI code for VirtualBox/QEMU/ and Bochs is used, however. This is a fairly easy
; address to find. not so much with the real thing, but we shall see.
;
; -CopyLEFT and opensource based on existing OS loaders (CC) by Richard Jasmin AKA "Jazz"
; (frazzledjazz@gmail.com)
;

;
; We are in 32bits protected mode
;
bits 32

extern IDTPtr
  
MULTIBOOT_MODULE_ALIGN       equ     1<<0
MULTIBOOT_MEMORY_MAP            equ     1<<1
MULTIBOOT_GRAPHICS_FIELDS       equ     1<<2

MULTIBOOT_INFO_MEMORY_MAP            equ     1<<40
MULTIBOOT_INFO_BOOTDEV		equ	1<<2
MULTIBOOT_INFO_DRIVE_INFO      equ      1<< 80
MULTIBOOT_INFO_CONFIG_TABLE    equ      1<<100
MULTIBOOT_ADDRESS_FIELDS        equ     1<<16
MULTIBOOT_INFO_VIDEO_INFO	equ	1<<800
MULTIBOOT_INFO_ELF_SHDR      equ         1<< 20
MULTIBOOT_UNSUPPORTED  equ 0x0000fffc

MULTIBOOT_HEADER_MAGIC          equ     0x1BADB002
MULTIBOOT_HEADER_FLAGS          equ     MULTIBOOT_MODULE_ALIGN|MULTIBOOT_MEMORY_MAP|MULTIBOOT_GRAPHICS_FIELDS

MULTIBOOT_CHECKSUM       equ     -(MULTIBOOT_HEADER_MAGIC + MULTIBOOT_HEADER_FLAGS)

KERNEL_STACKSIZE                equ	0x32000 ; 32K stack...does VMM needs this changed? lets see..
USER_STACKSIZE			equ	0x32000 ;user mode stack
section .text

;
; Multiboot header
;
align 4
dd MULTIBOOT_HEADER_MAGIC
dd MULTIBOOT_HEADER_FLAGS
dd MULTIBOOT_CHECKSUM

global _start
extern MultiBootInfo
extern MagicNumber
extern PASCALMAIN

_start:

        cli ; interrupts OFF until further notice!
        mov edx, KERNEL_STACK+KERNEL_STACKSIZE  ;Create kernel stack
         mov  [MagicNumber],eax                 ; Multiboot magic number
         mov  [MultiBootInfo],ebx               ; Multiboot info
	 mov ecx,USER_STACK+USER_STACKSIZE ;Create User-mode stack

        call PASCALMAIN                        ; Call kernel entrypoint
	
        jmp $ ; go nowhere

; macro for ISRs without error code
%macro ISRWithoutErrorCode 1
global isr%1
isr%1:
;  cli
  push byte 0
  push byte %1
; mov ebx,[48+esp]
;  cmp word [ebx - 2],$80CD
  jmp ISRCommonStub   ; we got here on anoher interrupt, so handle other interrupts (jne)
 ; jmp  SysCallCommonStub 
%endmacro

; macro for ISRs with error code
%macro ISRWithErrorCode 1
global isr%1
isr%1:
;  cli
  push byte %1
; mov ebx,[48+esp]
;  cmp word [ebx - 2],$80CD
  jmp ISRCommonStub   ; we got here on anoher interrupt, so handle other interrupts (jne)
;  jmp  SysCallCommonStub 
%endmacro

ISRWithoutErrorCode  0 ; Division By Zero Exception
ISRWithoutErrorCode  1 ; Debug Exception
ISRWithoutErrorCode  2 ; Non Maskable Interrupt Exception
ISRWithoutErrorCode  3 ; Breakpoint Exception
ISRWithoutErrorCode  4 ; Into Detected Overflow Exception
ISRWithoutErrorCode  5 ; Out of Bounds Exception/PrintScreen
ISRWithoutErrorCode  6 ; Invalid Opcode Exception
ISRWithoutErrorCode  7 ; Processor Extension Not Available
ISRWithErrorCode     8 ; DOUBLE FAULT-possibly TRIPLE FAULT
ISRWithoutErrorCode  9 ; Keyboard/ CoProcessor Code Error
ISRWithErrorCode    10 ; Video Mode/CoProcessor Error
ISRWithErrorCode    11 ; Segment Not Present /Alignment Error/NotImp Exception
ISRWithErrorCode    12 ; Machine Check/Segfault Exception
ISRWithErrorCode    13 ; General Protection Fault Exception
ISRWithErrorCode    14 ; Page Fault Exception
ISRWithoutErrorCode 15 ; Unknown Interrupt /Reserved Exception
ISRWithoutErrorCode 16 ; Extended Keyboard Exception
ISRWithoutErrorCode 17 ; Reserved
ISRWithoutErrorCode 18 ; Machine Check Exception
ISRWithoutErrorCode 19 ; Bootstrap Reserved.Trip to reboot machine.
ISRWithoutErrorCode 20 ; Reserved
ISRWithoutErrorCode 21 ; Unused- for DOS
ISRWithoutErrorCode 22 ;  DOS Terminate Address-UNUSED
ISRWithoutErrorCode 23 ;  CTRL-Break Handler
ISRWithoutErrorCode 24 ; Critical DiskIO Error Handler
ISRWithoutErrorCode 25 ; ABS Disk Read
ISRWithoutErrorCode 26 ;  ABS Disk Write
ISRWithoutErrorCode 27 ; Dos TSR-UNUSED
ISRWithoutErrorCode 28 ; DOS (Delay) routine.Reprogrammed to ours.
ISRWithoutErrorCode 29 ; Fast Console Write 
ISRWithoutErrorCode 30 ; Reserved
ISRWithoutErrorCode 31 ; DPMI memory routines
ISRWithoutErrorCode 80 ;(Syscalls) 80h=128

; This is our common ISR stub. It saves the processor state, sets
; up for kernel mode segments, calls the Pascal-level ISR handler,
; and finally restores the stack frame.
extern ISRHandler
extern StartESP

ISRCommonStub:
  pusha
  cli
  push ds
  push es
  push fs
  push gs

  mov  ax,0x10
  mov  ds,ax
  mov  es,ax
  mov  fs,ax
  mov  gs,ax
  mov  eax,esp
  push eax

  mov  eax,ISRHandler
  call eax

  pop  eax
; TSS not saved upon return to ring3, so do it.

; lea eax,[esp + 76]	; 19 dwords == 76 bytes
; mov [ESP],eax      ; Ring 0 ESP value after IRET

  pop  gs
  pop  fs
  pop  es
  pop  ds

  popa
  add  esp,8 
  sti
  iret


; macro for IRQs, IRQ 0 corresponds to ISR 32, IRQ 1 to ISR 33, and so on
%macro IRQ 1
global irq%1
irq%1:
 ; cli
  push byte 0
  push byte %1+32
  jmp  IRQCommonStub
%endmacro

; Enables A20 line
;ENABLE_A20: 
;        MOV             AL,0D1H
;        OUT             64h, AL
;        MOV             AL, 0DFH
;        OUT             60h, AL

; Disables A20 line
;DISABLE_A20: 
;        MOV             AL, 0D1H
;        OUT             64h, AL
;        MOV             AL, 0DDH
;        OUT             60h, AL

; Enables non-maskable interrupts
;ENABLE_NMI:
;        MOV             AL, 0DH
;        OUT             070H, AL
;        JMP             $+2

; Disables non-maskable interrupts
;DISABLE_NMI:
;        MOV             AL, 8FH
;        OUT             070H, AL
;        JMP             $+2

IRQ  0 ; Timer (110ms intervals, 18.2 per second)
IRQ  1 ; Keyboard
IRQ  2 ; slave 8259 or EGA/VGA vertical retrace
IRQ  3 ; COM2 or COM4
IRQ  4 ; COM1 or COM3 or mouse
IRQ  5 ; fixed disk or LPT2
IRQ  6 ; floppy disk
IRQ  7 ; LPT1
IRQ  8 ; Real Time Clock
IRQ  9 ;  software redirected to IRQ2
IRQ 10 ; ???
IRQ 11 ; ???
IRQ 12 ; PS/2 mouse
IRQ 13 ;  numeric coprocessor error 
IRQ 14 ; fixed disk controller
IRQ 15 ;  second fixed disk controller

extern IRQHandler
IRQCommonStub:
  pusha
  cli
  push ds
  push es
  push fs
  push gs

  mov  ax,0x10
  mov  ds,ax
  mov  es,ax
  mov  fs,ax
  mov  gs,ax
  mov  eax,esp
  push eax

  mov  eax,IRQHandler
  call eax

  pop  eax
; TSS not saved upon return to ring3, so do it.

; lea eax,[esp + 76]	; 19 dwords == 76 bytes
; mov [ESP],eax      ; Ring 0 ESP value after IRET

  pop  gs
  pop  fs
  pop  es
  pop  ds

  popa
  add  esp,8
  sti
  iret
 
extern GDTPtr
global FlushGDT
FlushGDT:
;  cli
  lgdt [GDTPtr]
  jmp  0x08:flush
flush:
  mov  ax,0x10 ;notice this is defined in the gdt. (kernel ring0)
  mov  ds,ax
  mov  es,ax
  mov  fs,ax
  mov  gs,ax
  mov  ss,ax
 ; sti
  ret

;this may in fact be the correct way, we are @ instruction 0
; Lets get the rest of VMM online first, so we can tell.
; This is STRAIGHT from the C in JamesM's kernel demo
;
;
;THIS IS HOW ITS DONE BOYS!!
;extern UserESP
;global switch_to_user_mode
;switch_to_user_mode:
;   cli -there is especial way to turn interrupts on for user mode, sti will NOT do it.
 ;  mov dword ax,$23 
 ;  mov word ds,ax
 ;  mov word es,ax
;   mov word fs,ax
;   mov word gs,ax
;   mov eax,UserESP
;   push dword $23 
;   push dword eax     
;   pushf
;   push dword $1b
;   jmp  0x1b:user
;   iret
;user:
;
;

extern UserESP
global switch_to_user_mode
switch_to_user_mode:
   cli ;there is especial way to turn interrupts on for user mode, sti will NOT do it.
   mov dword eax,$23 
   mov word ds,ax
   mov word es,ax
   mov word fs,ax
   mov word gs,ax
   mov eax,UserESP
   push dword $23      
   pushf
   push dword $1b
   push dword eax 
   push dword $23 
   iret
jmp  0x1b:user
user:

extern kernel_directory
global page_on
page_on:
 
    mov eax,kernel_directory
    mov cr3, eax  ;cr3 now contains kernel_directory(and 1mb address maps)    


   mov      ecx, 0C0000080h
   rdmsr
   bts      eax, 8
   wrmsr

    mov eax,cr0
    bts      eax, 31       
  ;  or eax,0x8000000 ;one too many zeroes??
    mov cr0,eax ;enable paging....
ret


global copy_page_physical
copy_page_physical:
   push ebx              ; According to __cdecl, we must preserve the contents of EBX.
   pushf                 ; push EFLAGS, so we can pop it and reenable interrupts
                         ; later, if they were enabled anyway.
  ; cli                    Disable interrupts, so we aren't interrupted.
                         ; Load these in BEFORE we disable paging!
   mov ebx, [esp+12]     ; Source address
   mov ecx, [esp+16]     ; Destination address

   mov edx, cr0          ; Get the control register...
   and edx, 0x7fffffff   ; and...
   mov cr0, edx          ; Disable paging.

   mov edx, 1024         ; 1024*4bytes = 4096 bytes to copy

.loopPagePys:
   mov eax, [ebx]        ; Get the word at the source address
   mov [ecx], eax        ; Store it at the dest address
   add ebx, 4            ; Source address += sizeof(word)
   add ecx, 4            ; Dest address += sizeof(word)
   dec edx               ; One less word to do
   jnz .loopPagePys

   mov edx, cr0          ; Get the control register again
   or  edx, 0x80000000   ; and...
   mov cr0, edx          ; Enable paging.

   popf                  ; Pop EFLAGS back.
   pop ebx               ; Get the original value of EBX back.
 ;  sti
   ret

extern TssPtr

global FlushTSS
FlushTSS:
 mov ax, 0x2b      ; Load the index of our TSS structure - The index is
                     ; 0x28, as it is the 5th selector and each is 8 bytes
                     ; long, but we set the bottom two bits (+3)
                     ; so that it has an RPL of 3, not zero.
   ltr ax            ; Load into the task state register.
   ret 

section .data

section .bss
;
; Kernel stack location
;
align 32


KERNEL_STACK:
  resb KERNEL_STACKSIZE

USER_STACK:
  resb USER_STACKSIZE

