Higher-half questions.

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Higher-half questions.

Post by 01000101 »

Currently my OS has a nice 1:1 paging scheme setup... and that is only there because of the LMode requirement for it to exist.

I've been looking over various ways to put the kernel into higher memory (> 1mb), and most/all have to do with placing the kernel in low memory, and then using paging to make it 'seem' like it is in high-mem, but really it is low memory, but with a virtual address that is high.

Question A: Say I place my kernel at 0x10000, and it is larger than the leftover addressable/usable space (< 0xb8000/0xa0000). How would I copy it from the floppy, into memory (before it sets up the paging), without it overwriting critical reserved memory regions?

Question B: I've tried using Unreal mode to load the kernel and transfer 18k chunks piece by piece into high memory, but I always get strange errors relating to registers being 4-bytes wide, but stack pushes and pops are only 2-bytes wide (also, the 'ret' instruction produces varying stack pops from 2-4 bytes). Should I continue this route, or is it better to fully switch back and forth between real and protected mode (int 0x13 = real mode, memcpy = pmode)?

Basically, I need a solution to having a large enough kernel, that I can NOT load into low memory all at once as it will overwrite critical regions or go beyond the addressable 1mb.

Also, from what I understand, I really have no interest into GDT trick... as it is just that, a trick that must be corrected and patched up as soon as a more permanent setup has been installed.

Pseudo code or ASM code is definitely welcome.
User avatar
~
Member
Member
Posts: 1228
Joined: Tue Mar 06, 2007 11:17 am
Libera.chat IRC: ArcheFire

Re: Higher-half questions.

Post by ~ »

Also, don't forget to make sure A20 is really enabled. Note that if you fail to do it, and if you try to copy your kernel at the start of the second megabyte, at 0x100000, you will actually be writing to address 0, crashing your system.

A free RAM region under real mode just after booting ranges from 0x500 to 0x9FFFF, ending just before the 0xA0000, as is explained here:
http://www.osdever.net/tutorials/brunma ... ial_02.php

It's 654,080 bytes, or 638.75 KB that could be fully used with enough care.

The easiest at boot time should be to place a 512-byte buffer just at the 0x500 mark, since it's extremely easy to access in all circumstances and for all the necessary BIOS disk calls.

The boot code is placed at 0x7C00 and is 512 bytes long.

So, you could copy your kernel in 512-byte chunks.

You could put this buffer just below your boot code (0x7C00-512) or just above (0x7C00+512), set unreal mode, and then put the kernel chunks one after another into its final, higher location.

I like to leave the first megabyte untouched for things like making a mirror for V86 monitors... and then I copy the kernel at a location like 0x100000 (1048576), the start of the second megabyte in system RAM.

Unreal Mode isn't very difficult. If you want simplicity, just set DS and ES to 0 (when back i (Un)real Mode) and load your general purpose registers with the physical addresses. Don't forget to use instructions like:

Code: Select all

rep lodsb
rep stosb
rep lodsw
rep stosw
rep lodsd
rep stosd
...if you want to use 16-bit segments, specially for the counter in (E)CX, and then SI/DI.

If you want to use 32-bit ECX counter in Unreal Mode, use these prefixes:

Code: Select all

a32 rep lodsb
a32 rep stosb
a32 rep lodsw
a32 rep stosw
a32 rep lodsd
a32 rep stosd
Using a32 should force the behavior of REP LODS* / REP STOS*, etc., to be like in full 32-bit mode at CPL 0 using its respective registers, DS:ESI, ES:EDI and ECX.

You could also use PUSH WORD ? / PUSH DWORD ? / POP WORD ? / POP DWORD ?, or just use a register to pop the same amount of bytes it has (except for 8-bit registers I think, so if possible, somebody please clarify it if incorrect).


If you have DOS to test, you can run the following code to set up a good Unreal Mode:

Code: Select all

;;Unreal mode enabling sample for DOS.
;;
;; Characteristics:
;;
;;   DOS-Free Ready? [???]
;;;

org 100h
bits 16

push eax
push ds
push es

 cli
 call enableA20
 cli


 xor eax,eax
 mov ax,ds
 shl eax,4
 push eax

 pop eax
 mov ebx,GDT
 add eax,ebx
 mov [GDT+2],eax


  lgdt[GDT]                  ;{6}

    ;Set CR0's PE bit:
    ;Set CR0's PE bit:
      mov eax,cr0   ;{3}
      inc ax        ;{1}
      mov cr0,eax   ;{3}

    ;Set 32-bit memory:
    ;Set 32-bit memory:
      push byte SELDat32 ;{2}
      pop ds             ;{1}
      push ds            ;{1}
      pop es             ;{1}



    ;Back to (Un)real mode:
    ;Back to (Un)real mode:
      dec ax       ;{1}
      mov cr0,eax  ;{3}


pop es
pop ds
pop eax
sti




mov ah,0x4C
int 0x21


;;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
        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
        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)
      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



enableA20:
	;; This subroutine will enable the A20 address line in the keyboard
	;; controller.  Takes no arguments.  Returns 0 in EAX on success, 
	;; -1 on failure.  Written for use in 16-bit code, see lines marked
	;; with 32-BIT for use in 32-bit code.

	pusha

	;; Make sure interrupts are disabled
	cli

	;; Keep a counter so that we can make up to 5 attempts to turn
	;; on A20 if necessary
	mov CX, 5

	.startAttempt1:		
	;; Wait for the controller to be ready for a command
	.commandWait1:
	xor AX, AX
	in AL, 64h
	bt AX, 1
	jc .commandWait1

	;; Tell the controller we want to read the current status.
	;; Send the command D0h: read output port.
	mov AL, 0D0h
	out 64h, AL

	;; Wait for the controller to be ready with a byte of data
	.dataWait1:
	xor AX, AX
	in AL, 64h
	bt AX, 0
	jnc .dataWait1

	;; Read the current port status from port 60h
	xor AX, AX
	in AL, 60h

	;; Save the current value of (E)AX
	push AX			; 16-BIT
	;; push EAX		; 32-BIT

	;; Wait for the controller to be ready for a command
	.commandWait2:
	in AL, 64h
	bt AX, 1
	jc .commandWait2

	;; Tell the controller we want to write the status byte again
	mov AL, 0D1h
	out 64h, AL	

	;; Wait for the controller to be ready for the data
	.commandWait3:
	xor AX, AX
	in AL, 64h
	bt AX, 1
	jc .commandWait3

	;; Write the new value to port 60h.  Remember we saved the old
	;; value on the stack
	pop AX			; 16-BIT
	;; pop EAX		; 32-BIT

	;; Turn on the A20 enable bit
	or AL, 00000010b
	out 60h, AL

	;; Finally, we will attempt to read back the A20 status
	;; to ensure it was enabled.

	;; Wait for the controller to be ready for a command
	.commandWait4:
	xor AX, AX
	in AL, 64h
	bt AX, 1
	jc .commandWait4

	;; Send the command D0h: read output port.
	mov AL, 0D0h
	out 64h, AL	

	;; Wait for the controller to be ready with a byte of data
	.dataWait2:
	xor AX, AX
	in AL, 64h
	bt AX, 0
	jnc .dataWait2

	;; Read the current port status from port 60h
	xor AX, AX
	in AL, 60h

	;; Is A20 enabled?
	bt AX, 1

	;; Check the result.  If carry is on, A20 is on.
	jc .success

	;; Should we retry the operation?  If the counter value in ECX
	;; has not reached zero, we will retry
	loop .startAttempt1


	;; Well, our initial attempt to set A20 has failed.  Now we will
	;; try a backup method (which is supposedly not supported on many
	;; chipsets, but which seems to be the only method that works on
	;; other chipsets).


	;; Keep a counter so that we can make up to 5 attempts to turn
	;; on A20 if necessary
	mov CX, 5

	.startAttempt2:
	;; Wait for the keyboard to be ready for another command
	.commandWait6:
	xor AX, AX
	in AL, 64h
	bt AX, 1
	jc .commandWait6

	;; Tell the controller we want to turn on A20
	mov AL, 0DFh
	out 64h, AL

	;; Again, we will attempt to read back the A20 status
	;; to ensure it was enabled.

	;; Wait for the controller to be ready for a command
	.commandWait7:
	xor AX, AX
	in AL, 64h
	bt AX, 1
	jc .commandWait7

	;; Send the command D0h: read output port.
	mov AL, 0D0h
	out 64h, AL	

	;; Wait for the controller to be ready with a byte of data
	.dataWait3:
	xor AX, AX
	in AL, 64h
	bt AX, 0
	jnc .dataWait3

	;; Read the current port status from port 60h
	xor AX, AX
	in AL, 60h

	;; Is A20 enabled?
	bt AX, 1

	;; Check the result.  If carry is on, A20 is on, but we might warn
	;; that we had to use this alternate method
	jc .warn

	;; Should we retry the operation?  If the counter value in ECX
	;; has not reached zero, we will retry
	loop .startAttempt2


	;; OK, we weren't able to set the A20 address line.  Do you want
	;; to put an error message here?
	jmp .fail


	.warn:
	;; Here you may or may not want to print a warning message about
	;; the fact that we had to use the nonstandard alternate enabling
	;; method

	.success:
	sti
	popa
	xor EAX, EAX
	ret

	.fail:
	sti
	popa
	mov EAX, -1
	ret

Then, you can use the following DOS program to tesf if it worked and understand it better, by writing to high memory locations and using 32-bit register for addressing offsets in memory:


Code: Select all

;;Unreal mode presence testing for DOS.
;;
;; Characteristics:
;;
;;   DOS-Free Ready? [YES]
;;    * Just remove the INT 21h calls and its parameters
;;      and put some other appropriate code.
;;;



org 100h
bits 16

push ds   ;Save data segment
push es   ;Save extra data segment

xor ax,ax  ;Set to 0
mov ds,ax  ;Set base data segment to 0 for unreal mode
mov es,ax  ;Set base data segment to 0 for unreal mode

                         ;Test if we can reach very much memory in 16-bit mode
                         ;and also test for A20 enabled by using an odd megabyte


;;Clear any past test results
;;;
  mov eax,1048576*3
  mov dword[eax],0    ;Our intended address
  mov eax,1048576*2
  mov dword[eax],0    ;An A20-disabled wrapped address



mov eax,1048576*3
mov dword[eax],"1@2@" ;Place here a colorful "12"
mov ebx,[eax]         ;Store for later comparison


mov eax,1048576*2     ;See the pontetially wrapped up address
mov ecx,[eax]         ;Store for the comparison



pop es
pop ds

cmp ebx,ecx           ;Compare to see
jnz noA20error        ;If they are different, A20 is enabled an all is OK
mov dx,gateError
mov ah,9
int 0x21
jmp ended


noA20error:
mov dx,testPass
mov ah,9
int 0x21
ended:


push ds
push es
xor ax,ax
mov ds,ax
mov es,ax



;;If we have Unreal Mode in place, the following instruction
;;will print "12" at the top of  the default 80x25 text mode
;;screen.
;;
;;Otherwise, DOS or any real mode environment will halt or reboot, etc...
;;or just fail to print "12"
;;;
  mov eax,1048576*3
  a32 mov ebx,[eax] ;Try to recover our colorful "12" like in Unreal Mode

  mov eax,0xB8000
  mov dword[eax],ebx  ;Try to put it at 0xB8000 like in Unreal Mode



pop es   ;Restore extra data segment
pop ds   ;Restore data segment



mov ah,0x4C
int 0x21



gateError db "Looks like an A20 issue, from addr. 0x300000 to 0x200000.",13,10,"$"
testPass  db "Unreal Mode/Gate A20 test ended successfuly.",13,10,"$"
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

OK, so getting into Unreal mode was really not that hard, I think I was just over-analyzing the method of switching between real, unreal, and protected mode.

Now I have a different issue.

I redesigned my bootloader so that it loads my kernel (in 18k chunks) up to 0x1000000. This works perfectly, I can run my OS fine from the high-mem without any (noticable) issues. Unfortunately, now my SMP code fails due to the bootloader (which is also the AP trampoline code) being at ORG 0x7C00 and it being boot into by the AP's at 0x10000 (as the memory reference vector for the IPIs can't span to the 0x7C00 range). Here's a basic memory layout of my OS.

Code: Select all

0x7C00 = bootloader

After the BSP goes through the bootloader, it loads the bootloader into 0x10000.
Then it loads the OS into high mem at 0x1000000.

0x10000 = bootloader copy
0x1000000 = kernel

Then the kernel boots the other CPU's into vector 1:0 == 0x1000:0x0000 == 0x10000.
But once they go through the trampoline code (which works, and has for a long time) 
fails with an ">>PANIC<< load_seg_reg(): invalid segment register passed!".  
I am almost 100% sure that it has to do with my GDT descriptor pointing to a (now) invalid offset to the actual GDT structure.  
The AP's make it right up to the far jump into protected mode, and then they fail with the above error in bochs.

If you would like, i can post the entire bootloader code, I would really like to figure this out as I rather enjoy having my OS in high memory. 8)
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Higher-half questions.

Post by Combuster »

hmm, the kernel loaded at 16M physical?

You use paging?
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

I setup paging in the BSP's P-Mode (because of long mode), but it is a 1:1 map all the way up to 8GB (using 2MB pages).
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: Higher-half questions.

Post by Brendan »

Hi,
01000101 wrote:I redesigned my bootloader so that it loads my kernel (in 18k chunks) up to 0x1000000. This works perfectly, I can run my OS fine from the high-mem without any (noticable) issues. Unfortunately, now my SMP code fails due to the bootloader (which is also the AP trampoline code) being at ORG 0x7C00 and it being boot into by the AP's at 0x10000 (as the memory reference vector for the IPIs can't span to the 0x7C00 range).
The AP's trampoline only needs to be about 5 bytes. You can store a "jmp 0x0000:AP_entry_point_in_bootloader" instruction at 0x00010000 with "mov dword [0x00010000], 0x????????" and "mov dword [0x00010004], 0x????????" instructions, or copy this jump instruction from your boot loader to 0x00010000. Then, inside your boot loader (starting from the AP CPU's entry point) you can load sane segment registers, load the same GDT, IDT, PLM4, etc as the BSP, and enter long mode, and then jump to the kernel's AP entry point.


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

You're very correct, I was looking at the problem all wrong, so of course I came to think of a wrong solution. I have that fixed, but now I have an even more frustrating issue. My code works perfect in BOCHS, but doesn't leave the bootsector... or even get into PMODE on my real hardware (intel xeon e5405, 1gb mem, supermicro server mobo). It doesn't triple fault, I think it just hangs somewhere, unless triple-faulting in (un)real mode is caught by the IDT?

Here is my (heavily commented) code for the bootsector, I can not figure this out for the life of me. In BOCHS, the BSP enters the high-mem kernel, loads everything, init's AP's (which load fine and get to the high-mem kernel as well), and then everything halts. On real hardware, it boots, and hangs. I put debugging text, and it seems that it is my MEMCPY function, and the only thing I can figure out there, is that it does NOT like the EDI/ESI pair as they are 32-bit memory locations. Why would it read the 32-bit (unreal mode) memory pointers in BOCHS, but not real hardware? that is why I thought it was the A20 not being properly initialized, but I tried two seperate methods of setting it up.

btw, this thing is stuffed to the gills with code, and I assemble with the -Ox (nasm) optimization just to fit everything with 512 bytes.

Code: Select all

[cpu x64]
[bits 16]

[org 0x7c00]


start:
    cli
    cmp word [0x7e00], 0xBEEF           ; if true, it's an AP
    jne boot                            ; if not, jump to BSP boot
    jmp 0x0000:0x7d23                   ; calculated offest to "PBOOT:"




;------------GDT Table---------------;

GDTD:

GDT_size DW 0x27

GDT_base DD GDT_START



GDT_START:

; NULL
       dd 	  0x0

       dd 	  0x0

; CODE32

       dw     0xFFFF        

       dw     0x0          

       db     0x0            

       db     0x9A            

       db     0xCF             

       db     0x0              

; DATA32

	   dw     0xFFFF          

	   dw     0x0          

	   db     0x0          

	   db     0x92            

	   db     0xCF           

       db     0x0              

; CODE64
	   dw 	  0xFFFF
	   dw 	  0x0000
	   db 	  0x00
	   db 	  0x9A
	   db 	  0x2F
	   db 	  0x00
; DATA64
	   dw 	  0xFFFF
	   dw 	  0x0000
	   db 	  0x00
	   db 	  0x92
	   db 	  0x2F
	   db 	  0x00
GDT_END:

;----------End GDT Table-------------;



boot:                
                            ; ------ initialize registers + stack ------                    
    a16 mov sp, 0x9F00      ; set stack to 0:0x9F00

    call enable_A20         ; enable A20 the old-fashioned way (fast a20 has no varying effects)
    a32 call xor_regs       ; clear all general purpose registers (EAX-EDX)
    
enter_PMODE: 
    a32 mov eax, cr0        ; set bit 0 in CR0 to enable PMODE
    a16 or al, 1            
    a32 mov cr0, eax
    
 .continue:
    a16 mov bx, 0x10        ; load ds with 0x10 (GDT entry #2 [datasel32]) 
    a16 mov ds, bx
    
    a16 and al, 0xFE        ; unset bit 0 in CR0 to disable PMODE
    a32 mov cr0, eax   
    
    a16 mov ds, cx          ; load ds, es, and ss with 0
    a16 mov es, bx
    a16 mov ss, bx
        
    a32 call xor_regs       ; clear regs

    sti                     ; enable interrupts
  .floppy_reset:            ; reset the floppy drive
    int 0x13
    a16 cmp ah, 0           ; error?
    jne .floppy_reset
   
                            ; ------ int 0x13 f(2) ------ 
                            ; -- ES:BX = Destination Seg:Off
                            ; -- AH = Function Number
                            ; -- AL = # of Sectors to load
                            ; -- CH = Start Cylinder
                            ; -- CL = Start Sector
                            ; -- DH = Start Head
                            ; -- DL = Drive Number (0 for FloppyA)
   
  .init_load_stage2:
    a32 mov edi, dword 0x1000000    ; high-mem start address (16MB)
    a16 mov ax, 0x1000      ; setup ES:BX (0x1000:0x0000) at 0x10000 (low-mem buffer)
    a16 mov es, ax
    a16 mov ax, 0x0212      ; function = 2, sector count = 18 (full head)
    a16 mov cx, 1           ; start cyl = 0, start sector = 1
    a16 xor dx, dx          ; start head = 0, drive = 0 (FloppyA)
    
  .load_stage2:
    a16 xor bx, bx          ; always set bx (offset) to 0
    int 0x13
    a32 call memcpy         ; copy the mem from 0x10000 -> 0x1000000 in 18k chunks
    a16 mov ax, 0x0212      ; reload function number and sector count
    a16 inc dh              ; increase current head
    a16 cmp dh, 2           ; if > 1, set head = 0 and increase current cylinder
    jne .load_stage2
    a16 xor dh, dh
    a16 inc ch
    a16 cmp ch, 0x06        ; if 6 cylinders have been loaded, exit
    jne .load_stage2

    mov cx, 0x0001          ; load the first 18 sectors to 0x10000 for the AP's
    xor dx, dx              ; if I was less lazy, and had more room to play with - 
    xor bx, bx              ; I would set AL = 1 and only load the bootsector
    int 0x13
    
    cli                     ; disable interrupts from here on out
    
    jmp PBOOT               ; jump over functions

memcpy:
    push word cx            ; push cx.  no need to push (e)bx as it gets nulled - 
                            ; in the floppy int code.

    a32 mov esi, dword 0x10000  ; set source address to low-mem (0x10000)
    a32 mov ecx, dword 0x2400   ; set count to 18k (0x2400)

  .loop:
    a32 mov ebx, dword [esi]        ; copy dword from 0x10000+ to ebx
    a32 mov dword [a32 edi], ebx    ; copy ebx to 0x1000000+
    a32 add esi, dword 4            ; update source pointer
    a32 add edi, dword 4            ; update dest pointer
    a32 sub ecx, dword 4            ; update counter
    a32 cmp ecx, dword 0            ; if counter is still > 0, keep looping
    jne .loop
    
    pop word cx             ; pop cx to reload start sector/cylinder
    a32 ret                 ; exit function
    
xor_regs:
    a32 xor ax, ax          ; ax = 0
    a32 xor bx, bx          ; bx = 0
    a32 xor cx, cx          ; cx = 0
    a32 xor dx, dx          ; dx = 0
    a32 ret
 
        
enable_A20:                 ; taken from previous post as a 'control' a20 function.  
                            ; fast A20 functions do exactly the same thing, but neither 
                            ; have any noticable adverse or positive effects on the loading.
                            ; btw, this is temporary, and in no way am I trying to 
                            ; take this code for any long-term use, just needed to use a 
                            ; working peice of code to make sure it wasn't my A20 function. 
        call    a20wait
        mov     al,0xAD
        out     0x64,al

        call    a20wait
        mov     al,0xD0
        out     0x64,al

        call    a20wait2
        in      al,0x60
        push    ax

        call    a20wait
        mov     al,0xD1
        out     0x64,al

        call    a20wait
        pop     ax
        or      al,2
        out     0x60,al

        call    a20wait
        mov     al,0xAE
        out     0x64,al

        call    a20wait
        ret

a20wait:
        in      al,0x64
        test    al,2
        jnz     a20wait
        ret


a20wait2:
        in      al,0x64
        test    al,1
        jz      a20wait2
        ret       

PBOOT:                      ; function to init PMODE

    cld                     ; clear direction flag (recommended by some book I read... I think)

    mov eax,cr0             ; load CR0 into EAX

    or al,1                 ; set the protection bit

    mov cr0,eax             ; reload CR0



    lgdt[GDTD]              ; load the GDT



    jmp 0x08:FLUSH          ; far jump to set CS to 0x08 (CODE32)



[bits 32]

FLUSH:

    mov ax,0x10             ; set ds, es, and ss to 0x10 (DATA32)

    mov ds,ax

    mov es,ax

    mov ss,ax

    cmp word [0x7e00], 0xBEEF   ; is AP? jump over page creation code, and just enable it
    je enable_paging


;---------- Map Memory Up To 0x200000000 (8GB) -------------;
    mov	dword [70000h],71000h + 111b

    mov eax, 0x72000 + 0111b
    mov ebx, 0x71000
    mov cx, 8

create_pdp:
    mov [ebx], eax
    add eax, 0x1000
    add ebx, 8
    dec ecx
    cmp ecx, 0
    jne create_pdp


    mov eax, 10000111b
    mov ebx, 0x72000
    mov ecx, 4096

create_page:
    mov [ebx], eax
    add eax, 0x200000
    add ebx, 8
    dec ecx
    cmp ecx, 0
    jne create_page

enable_paging: 
   mov eax, 0x0
   mov cr2, eax

   mov ax, 10100000b		; set PAE
   mov cr4, eax             ; load CR4

   mov edx, 0x00070000		; point CR3 to PML4
   mov cr3, edx             ; load CR3

   mov ecx,0xC0000080		; set MSR address

   rdmsr			        ; read MSR
   or ax,0x0100             ; set long mode bit
   wrmsr                    ; write MSR

   mov ebx, cr0			    ; load CR0 into EBX
   or ebx, 0x80000000		; set the paging bit
   mov cr0, ebx			    ; reload CR0
   
   jmp 0x18:goto_kernel     ; far jump to set CS to 0x18 (CODE64)

[bits 64]
goto_kernel:
   mov ax, 0x20             ; set ds, es, and ss to 0x20 (DATA64)
   mov ds, ax
   mov es, ax
   mov ss, ax

   mov esp, 0x90000         ; set stack to 0x90000
   
jump_to_kernel:
   jmp 0x1000200            ; jump to 0x1000200 (where the high-mem kernel resides)





TIMES 510-($-$$) DB 0       ; set the rest of the space to 0



dw 0xAA55                   ; bootsector signature
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

update: I used that in QEMU (x86_64 guest) and it worked fine.

That means that for the most part, this code is good and works, but for some reason, it does not like my real hardware... it almost definitely has to do with the unreal mode code as most of the rest of the code is present in my working bootloader for the stable tree of my OS.
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Higher-half questions.

Post by Combuster »

If its the AP startup that gives problems, have you made sure its not the IPI code that faults, i.e. you actually get to boot those additional cores into realmode? I've been breaking my own head over the code not working on real hardware while it did in bochs.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
User avatar
Brendan
Member
Member
Posts: 8561
Joined: Sat Jan 15, 2005 12:00 am
Location: At his keyboard!
Contact:

Re: Higher-half questions.

Post by Brendan »

Hi,
01000101 wrote:It doesn't triple fault, I think it just hangs somewhere, unless triple-faulting in (un)real mode is caught by the IDT?
In real mode (and unreal mode) most BIOS "exception handlers" will simply return with an IRET, which causes another exception, which causes another IRET, which causes another exception, which causes, um, I forgot. :)

I noticed a few things...

Code: Select all

start:
    cli
    cmp word [0x7e00], 0xBEEF           ; if true, it's an AP
    jne boot                            ; if not, jump to BSP boot
    jmp 0x0000:0x7d23                   ; calculated offest to "PBOOT:"
For the BSP, nothing reloads CS so you don't know if the value in CS will be 0x07C0 or 0x0000. This may or may not matter.

For the AP, the trampoline code sets CS appropriately, so there no need to use a far jump. It would make sense to reverse the branch - for example:

Code: Select all

start:
    cli
    cmp word [0x7e00], 0xBEEF           ; if true, it's an AP
    je 0x7d23
    jmp 0x0000:boot
Or even better, determine if the value in CS matters and use near jumps in both cases. However, if you use a "CS:" segment override prefix or jump to a fixed address (e.g. "jmp [eax]") then the value in CS will matter.

Code: Select all

    jmp 0x0000:0x7d23                   ; calculated offest to "PBOOT:"
In general this is a pain in the neck - any time you change anything you'd need to re-calculate the offset by hand. I see no reason why you can't just use:

Code: Select all

    jmp 0x0000:PBOOT

Of course an even better idea would be to use "jmp 0x0000:PBOOT" as the trampoline (e.g. copy this jump to 0x10000), so you don't need to worry about doing "cmp word [0x7e00], 0xBEEF". Also, what values do different BIOSs leave in DS when they start a boot loader, and exactly which addresses might the "cmp word [DS:0x7e00], 0xBEEF" instruction refer to?

You're missing the BIOS Parameter Block (BPB). This table is optional, but Windows tends to think the disk is corrupt and refuses to format the disk unless the BPB is present (and sane); which causes compatability problem for people that use Windows. For example, it might cost people a floppy disk each time they test your OS if they don't have a (non-Windows) computer to reformat them afterwards.

Code: Select all

;------------GDT Table---------------;

GDTD:

GDT_size DW 0x27

GDT_base DD GDT_START



GDT_START:

; NULL
       dd 	  0x0

       dd 	  0x0
This isn't aligned correctly, and you could save some bytes by doing this:

Code: Select all

;------------GDT Table---------------;

    align 4

GDT_START:

; NULL descriptor *and* GDTD

GDTD:
GDT_size: DW GDT_END - GDT_START - 1
GDT_base: DW GDT_START
       dd 	  0x0
Also note that I wrote "GDT_base: DW GDT_START" here, because the default operand size is 16-bit when you do "lgdt [GDTD]" so the highest 16-bits are ignored anyway. Doesn't matter much either way in this context though.

Code: Select all

boot:                
                            ; ------ initialize registers + stack ------                    
    a16 mov sp, 0x9F00      ; set stack to 0:0x9F00
Is the "a16" prefix necessary here? I'm fairly sure the assembler knows that "sp" is 16-bit, so unless you messed up the "bits 16" somewhere...

The same applies to all the other "a16", "a32", "o16" and "o32" prefixes - none of them look necessary, and they just make the code look messy. The only reason to use any of these prefixes is with string instructions - for example "a32 rep stosd" in 16-bit code so that it uses ESI/EDI instead of SI/DI, but that's only because these instructions don't have any operands.

For mixed size jump instructions just use size specifiers (for example, in real mode, use "jmp far dword 0x1234:0x56789ABC" rather than "a32 jmp far 0x1234:0x56789ABC", because the assembler might generate an "a32" prefix followed by a 16-bit "jmp far 0x1234:0x9ABC" which will make the CPU jump to the wrong place - I'm not sure about this - I don't use these prefixes unless I have to).

Code: Select all

    call xor_regs       ; clear all general purpose registers (EAX-EDX)
Why do you clear EAX and then load something into it straight after? Do you actually need to clear any of the registers, or could you just delete every "call xor_regs" instruction (and then delete the "xor_regs" routine too)? If you do need to clear a few registers, then how many registers would need to be cleared before "call xor_regs" saves space instead of costing space?

Code: Select all

enter_PMODE: 
    a32 mov eax, cr0        ; set bit 0 in CR0 to enable PMODE
    a16 or al, 1            
    a32 mov cr0, eax
    
 .continue:
    a16 mov bx, 0x10        ; load ds with 0x10 (GDT entry #2 [datasel32]) 
    a16 mov ds, bx
    
    a16 and al, 0xFE        ; unset bit 0 in CR0 to disable PMODE
    a32 mov cr0, eax   
    
    a16 mov ds, cx          ; load ds, es, and ss with 0
    a16 mov es, bx
    a16 mov ss, bx
Ok. First, this code should be called "enable_unreal_mode" or something. It's currently called "enter_PMODE" but it doesn't enter protected mode (at least not for long). The ".continue:" label isn't referenced by anything. After you change CR0 (e.g. when you enable protected mode *and* when you disable protected mode) you should do a "jmp" to flush the instruction cache (especially for 80486, but not necessarily just for 80486) - I'm guessing that's what the ".continue:" label was originally used for (but there isn't even a label where protected mode is disabled). The only segment register you touch is DS, but for some reason when you get back to real mode you reset ES and SS too.

Maybe:

Code: Select all

set_DS_flat:
    mov eax, cr0            ; set bit 0 in CR0 to enable PMODE
    mov cx, 0x10            ; cx = 0x10 (GDT entry #2 [datasel32]) 
    mov ebx, eax
	xor dx,dx
    or al, 1
    mov cr0, eax
    jmp .flush1
.flush1:
    mov ds, cx
    mov cr0, ebx
    jmp .flush2
.flush2:
    mov ds, dx             ; load ds with zero
Your ".floppy_reset" code is used before you attempt to load anything, even though you know the BIOS just used the floppy to load your code without any problem - might be nice to shift this elsewhere, so that the floppy is only ever reset if there's a disk error.

I don't understand what the "if there's an error try random BIOS functions" idea is... ;) Here's your code:

Code: Select all

  .floppy_reset:            ; reset the floppy drive
    int 0x13
    a16 cmp ah, 0           ; error?
    jne .floppy_reset       ;   yes, use Int 0x13 again with some random value in AH (Huh???)
This is also another spot where doing "xor ah,ah" will probably take up less space than doing "call xor_regs".

Code: Select all

                            ; ------ int 0x13 f(2) ------ 
                            ; -- ES:BX = Destination Seg:Off
                            ; -- AH = Function Number
                            ; -- AL = # of Sectors to load
                            ; -- CH = Start Cylinder
                            ; -- CL = Start Sector
                            ; -- DH = Start Head
                            ; -- DL = Drive Number (0 for FloppyA)
When the BIOS (or whatever) loads your boot sector it stores a "BIOS device number" in DL. You should store this value somewhere and then use it instead of assuming that the device number is zero. That way a chain-loader could boot your OS from the second floppy.

Code: Select all

    a16 mov ax, 0x0212      ; reload function number and sector count
    a16 inc dh              ; increase current head
    a16 cmp dh, 2           ; if > 1, set head = 0 and increase current cylinder
    jne .load_stage2
    a16 xor dh, dh
    a16 inc ch
    a16 cmp ch, 0x06        ; if 6 cylinders have been loaded, exit
    jne .load_stage2
Yeah - if you had a BIOS Parameter Block (BPB) then your code could use values from the BPB to support just about all floppy disk formats (where you have an installer that just sets the right values in the BPB - e.g. "formatBootFloppy <size>").

Also, loading entire tracks is faster, but it's also a little less reliable. For example, if the first sector can be read without errors half the time and the last sector can be read without error half the time, then there'll be a 75% chance that reading the whole track will fail. If 4 sectors in the track can only be read half the time, then there'd be 93.75% chance that reading the whole track will fail. This means retrying a lot. In the same situation (lots of unreliable sectors) if you read single sectors you can drastically reduce the time spent failing and retrying. For this reason I attempt to load the entire track in one go, but if that doesn't work I attempt to load the track one sector at a time; and if loading the entire track in one go fails too often I'll give up and load everything one sector at a time. Mostly, slowly getting the job done is better than quickly going nowhere...

Of course my previous code supported "redundant floppies", where the sectors on one side of the disk are a mirror image of the sectors on the other side of the disk. If you combine this with the "one sector at a time if we have to" idea then you end up with a very good chance of booting, even on very unreliable floppies (which isn't such a bad idea considering that floppy disks are the most unreliable type of storage that's ever existed).

I didn't check any of the code to setup paging structures. It's much easier to use Bochs debugger (the "x <flags> <address>" command) to examine the linear address space to make sure it works right.

Code: Select all

   mov eax, 0x0
   mov cr2, eax
There's no real need to clear CR2 - if you get a page fault the CPU will set CR2, and if you don't get a page fault then you don't need to care what CR2 contains.

Code: Select all

   or ax,0x0100             ; set long mode bit
Could maybe use "or ah,0x01" to save a byte.

Code: Select all

memcpy:
    push word cx            ; push cx.  no need to push (e)bx as it gets nulled - 
                            ; in the floppy int code.

    a32 mov esi, dword 0x10000  ; set source address to low-mem (0x10000)
    a32 mov ecx, dword 0x2400   ; set count to 18k (0x2400)

  .loop:
    a32 mov ebx, dword [esi]        ; copy dword from 0x10000+ to ebx
    a32 mov dword [a32 edi], ebx    ; copy ebx to 0x1000000+
    a32 add esi, dword 4            ; update source pointer
    a32 add edi, dword 4            ; update dest pointer
    a32 sub ecx, dword 4            ; update counter
    a32 cmp ecx, dword 0            ; if counter is still > 0, keep looping
    jne .loop
    
    pop word cx             ; pop cx to reload start sector/cylinder
    a32 ret                 ; exit function
Um, no. Instead of setting the DS segment limit to 4 GiB, set the ES segment limit to 4 GiB and then use "a32 rep movsd" (or even "es: a32 rep movsd" if the source is above 1 MiB too). That should improve speed a little and save some bytes (as long as you remember that 32-bit "rep movsd" uses ECX instead of CX).

Next is "enable_A20:". Probably the easiest thing for me to do is point you towards a post I made yesterday about A20. I think that covers everything (just ignore the "DOS stuff" at the beginning of the post).

Code: Select all

goto_kernel:
   mov ax, 0x20             ; set ds, es, and ss to 0x20 (DATA64)
   mov ds, ax
   mov es, ax
   mov ss, ax

   mov esp, 0x90000         ; set stack to 0x90000
That's a bad place for a stack. How big is the EBDA? I don't know and neither do you. On "many CPU" systems the EBDA tends to be a lot larger than it is in "a few CPUs" systems. What happens when your stack trashes the EBDA (what effect would it have on the BIOS's SMM code and/or ACPI)? What happens when the BIOS's SMM code and/or ACPI trashes your stack? Hmmm - probably best not to find out - BIOS Int 0x12 might be fun.

Finally, error messages are good - it's probably why someone invented "printf()". If something really doesn't work then display an error message; and if you think something might not work display a progress message (e.g. display "I'm about to start the kernel" before you start the kernel, so that if it locks up the user has at least some idea of where it went wrong). For errors, I'd also consider making some noise with the PC speaker (so people can tell that their headless server won't be booting soon).
01000101 wrote:btw, this thing is stuffed to the gills with code, and I assemble with the -Ox (nasm) optimization just to fit everything with 512 bytes.
Hehe. Most beginners try to fit everything into 512 bytes. Most experienced OS developers know it's never worth the hassle. The only thing you need to do in the first sector of the boot loader is to load the second sector of the boot loader (or maybe the second stage).


Cheers,

Brendan
For all things; perfection is, and will always remain, impossible to achieve in practice. However; by striving for perfection we create things that are as perfect as practically possible. Let the pursuit of perfection be our guide.
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

Normally I wouldn't be trying to stuff all the boot code into the bootsector, but when I ran into all the troubles from unreal mode, I decided it would be better to keep things all in one spot for debugging and such.

You have pointed out some good points that I will begin looking into. A few of the things you pointed our were just remenissance of old attempts.

I used the a16/32 markers as just that... markers for myself to pick things out when I was trying to use extended registers.

I stripped down ALOT of the 'safety' features (such as the floppy code) to save space and to minimalize complexity while I try to figure out the issue at hand. Also, the floppy reset function is very admittedly flawed on second glance haha. :lol:

I think using beep codes would be much easier as it would allow me to not have to switch the KVM port over when I need to debug.
User avatar
01000101
Member
Member
Posts: 1599
Joined: Fri Jun 22, 2007 12:47 pm
Contact:

Re: Higher-half questions.

Post by 01000101 »

I ended up fixing the issues with the loader. Now I have my kernel loaded at 0x1000000 and with full SMP support (trampoline code). So now I have a much greater flexibility when it comes to the size of my OS. Thanks for the help!
Post Reply