Page 1 of 1

Loading Sectors: Floppy Real Mode

Posted: Sat May 31, 2008 10:03 pm
by Omega

Code: Select all

        mov ah, 02h             ; READ SECTOR-command
        mov al, 11h             ; Number of sectors to read
        mov ch, 0               ; Cylinder = 0
        mov cl, 02h             ; Sector = 2
        mov dh, 0               ; Head = 0
        int 13h                 ; Call interrupt 13h
Hi. This is Rmode code to read sectors from floppy disk and I am not sure what is wrong. When I assemble/compile my work and once it becomes 18 or more sectors big:
Creating floppy image...
1 sectors, 512 bytes read from file x86boot.bin...
18 sectors, 9056 bytes read from file kernel.bin...
Press any key to continue . . .
...the printf(s) in my main() function does not print; and it appears that the application just freezes. It won't respond to key presses at all and no error is shown; it just freezes and thats all. As long as my project remains 17 sectors or less, my settings (shown above) work just fine and everything works well as expected.

I realize this is a sector loading issue and the code above is the culprit, but no matter what I set the values to it does nothing. Thanks

Posted: Sun Jun 01, 2008 2:07 am
by jnc100
Where are you loading your kernel to? Are you overwriting your bootloader code or your stack?

Regards,
John.

Posted: Sun Jun 01, 2008 2:09 am
by Omega
Sorry, here is the whole function:

Code: Select all

reset_drive:
        mov ah, 0               ; RESET-command
        int 13h                 ; Call interrupt 13h
        or ah, ah               ; Check for error code
        jnz reset_drive         ; Try again if ah != 0

        mov ax, 0
        mov es, ax
        mov bx, 0x1000          ; We load our code at offset: 0:1000h

        mov ah, 02h             ; READ SECTOR-command
        mov al, 11h             ; Number of sectors to read
        mov ch, 0               ; Cylinder = 0
        mov cl, 02h             ; Sector = 2
        mov dh, 0               ; Head = 0
        int 13h                 ; Call interrupt 13h
        or ah, ah               ; Check for error code
        jnz reset_drive         ; Try again if ah != 0
Then I:

1. Enable A20
2. Enable GDT
3. Set Pmode bit
4. Jmp to 32 Bit
5. Jmp to offset 0:1000h

thanks. let me know if you need more info.

Posted: Sun Jun 01, 2008 8:17 am
by bontanu
The first rule in OS development (as in software development) is to play it safe simple and dumb. If you do not do it then you will suffer the consequences... in OS development 10x more faster than is standard software development.

The second rule in OS development is that you only start this when you already have a huge experience in general programming and already have created a few huge standard applications.

The chances of "success" in OS development are zero/null/nada and hence the only reason for this activity is that you know so much in programming that you feel like you need to suffer from the latest and darkest places of programming... And trust me you will suffer when you meet today hardware and "standards".


To help with your issue:
=======================

1) If you load at 0x1000 then sooner or later you might overwrite 0x7C00 where your boot sector was loaded by BIOS. If you did not relocated your code below 0x1000 then you will be in trouble.


2) Hardware is not always capable to read multiple sectors especially if you cross a TRACK boundary.

Hence it might fail on the 18 sector :D You do need to keep track of tracks and sectors when reading many sectors in one single operation. Hint: 1+17 = 18

You could read one single sector at a time. This will be simple, and slow but it will work on ALL hardware.

To make things worst SOME BIOS are capable of doing this but many DO NOT. Yes even today BIOSes. The reason for this is that they only care for the way Windows and Linux does read floppy like this. Nobody cares for the way YOU want to do things they only care for the ways Windows and Linux do things.

3) the Hardware DMA channel used by floppy disk can not cross 64K boundary. If you read multiple sectors you also have to keep track of loading address and avoid 64K borders.

Make yourself a gift: start simple and improve later.

Maybe read one sector at a time and at 0x8000 and above and never ever assume that anything works "as you want it". In hardware low level world devices work "as the device wants" and there is nothing you can do about it.

There is NO glory and nothing but a lot of grunt work to be done in OS dev... and of course a lot of understanding to be done. But you will never understand it without experience and with an attitude like: "oh dear it just happens like this...let me see IF I am capable of understanding WHY?"

Things like this "just happen" at all OS development levels and this floppy example is only the tip of the iceberg... more such "unknown surprises" expect you on the road ahead.

Posted: Sun Jun 01, 2008 8:54 am
by svdmeer
vst_0201 wrote:Sorry, here is the whole function:

Code: Select all

reset_drive:
        mov ah, 0               ; RESET-command
        int 13h                 ; Call interrupt 13h
        or ah, ah               ; Check for error code
        jnz reset_drive         ; Try again if ah != 0

        mov ax, 0
        mov es, ax
        mov bx, 0x1000          ; We load our code at offset: 0:1000h

        mov ah, 02h             ; READ SECTOR-command
        mov al, 11h             ; Number of sectors to read
        mov ch, 0               ; Cylinder = 0
        mov cl, 02h             ; Sector = 2
        mov dh, 0               ; Head = 0
        int 13h                 ; Call interrupt 13h
        or ah, ah               ; Check for error code
        jnz reset_drive         ; Try again if ah != 0
Then I:

1. Enable A20
2. Enable GDT
3. Set Pmode bit
4. Jmp to 32 Bit
5. Jmp to offset 0:1000h

thanks. let me know if you need more info.
You are entering protectedmode from your bootsector. That won't work when your OS (especially your kernel) becomes larger. It also won't work when you are loading your kernel from a filesystem, because most filesystems use a part of the bootsector further limiting space. And if you make your code safe (see the above post with recommendations of bontanu, take them very seriously because he's right) your bootsector code will grow fast. There will be no space left to switch to pmode.

You have to do it in a second part of the bootloader or the kernel itself.

Generally it isn't a bad idea to use checksums in the modules you load. The binaries I load at boottime contain checksums to be sure they are (completely) in memory like I expect, so I have not any strange crashes caused by faulty or incompletely loaded binaries.

Posted: Sun Jun 01, 2008 1:13 pm
by Omega
Right, it was what I suspected it would be. I was avoiding that route as I prefer my initial attempt; however, I am sure I will find more benefit to the change more than just memory management (which is enough to convince).

I like your checksum description. Do you have code I could look at to get the feel for what you are doing? thanks

Posted: Tue Jun 03, 2008 6:44 am
by svdmeer
vst_0201 wrote:Right, it was what I suspected it would be. I was avoiding that route as I prefer my initial attempt; however, I am sure I will find more benefit to the change more than just memory management (which is enough to convince).

I like your checksum description. Do you have code I could look at to get the feel for what you are doing? thanks
The checksum mechanism is done with several pieces of software.

Every binary of my OS has a basic header:

Code: Select all

begin:		db 'SMN'
		db 0			; headerspec
		dw 2			; main-type: boot-files
		dw 1			; sub-type: bootloader
		dd (end-begin) ; size
		dd copyright
MD5		dd 0,0,0,0		; MD5
checksum	dd 0			; Checksum 32-bit
		times (40)+$$-$ db 0 ; Fill with zeroes
		jmp codestart
codestart: 
        ; code and data here
end:
Because of the header-data you can't jump the first byte. My entry-point for flat binaries is at offset 40, with a jump to codestart. I can make the header bigger without giving up an universal entrypoint for flat binaries.
In that header there is place for a MD5sum and checksum. I will use MD5 from the (more advanched) bootloader and the OS itself. When a simple checksum is needed and I want to use it with a small piece of code I use checksum (only used in bootfiles, in the OS itself MD5sums will used to self-check the integrity of files).

To calculate checksum, I wrote a small C-utility.

Code: Select all

int fd;
unsigned char *buffer; // !! allocate memory
unsigned int filesize; // !! open file (fd) and get size of file
unsigned int checksum;
unsigned int t,ofs;

/* Read file */

		printf("Reading contents of file...");
		buffer=malloc(filesize);
		lseek(fd,0,SEEK_SET);
		read(fd,buffer,filesize);
		printf("OK\n");


/* Calculate checksum */
		printf("Calculating checksum...");
		checksum=0;
		ofs=0;

		for (t=(filesize-20); t>0; t--) {
			checksum+=( ((int)buffer[ofs]>>(t & 15)) | ((int)buffer[ofs]<<(16-(t & 15))) ) & 0xffff; 
			ofs++;
			if (ofs==16) ofs=36;
		}

		printf("OK (%X)\n",checksum);
Just a couple of fragments of my code because calculating the checksum is only one of the possibility's of the utility. Important is the checksum algoritm. I skip offsets 16 - 36 because that 20 bytes contain the MD5sum and the checksum itself. The checksum-calcultation looks like complicated, but in assembly it's much easier to understand.

I have 2 versions of the checksum check, both with 16-bit 8086 compatible code, because those checks are done before the check for a 386 cpu. If you know (or assume) you have a 386 or higher CPU, you can use 32-bit registers and make the code much simpler.

Very simple version for checking small binaries (max 64 kb):

Code: Select all

; ****************
; *** Checksum ***
; ****************
		mov si,begin
		xor bx,bx
		xor dx,dx
		cld
		mov cx,(end-begin)-20

next_checksumS: cmp si,MD5
		jne skip_checksums
		add si,20
skip_checksums: lodsb
		mov ah,0
		push cx
		and cl,15
		ror ax,cl
		add bx,ax
		adc dx,0
		pop cx
		loop next_checksumS

		cmp [checksum],bx
		jne show_error_LE
		cmp [checksum+2],dx
		jne show_error_LE
A larger one, also 8086 compatible 16-bit code but with unlimited size (but of course limited by realmode memory access):

Code: Select all

CPU 8086
BITS 16
ORG 0h

begin:		db 'SMN'
		db 0			; headerspec
		dw 2			; main-type: bootfiles
		dw 1			; sub-type
		dd (end-begin) ; size
		dd copyright
MD5		dd 0,0,0,0		; MD5
checksum	dd 0			; Checksum 32-bit
		times (40)+$$-$ db 0 ; Fill with zeroes
		jmp codestart

		%include "../checksum.inc"

; ******************
; *** Self check ***
; ******************
codestart:		mov ax,0x1000
		call Checksum
		or ax,ax
		jz ChecksumError
checksum.inc:

Code: Select all

; AX = segment
Checksum:	push ax
		push ds
		xor si,si
		push ax
		mov ds,ax
		xor bx,bx
		xor dx,dx
		cld

		mov cx,[ds:8]
		mov ax,[ds:10]
		sub cx,20+16
		sbb ax,0
		push cx
		push ax

		mov ax,16
		push ax
		xor ax,ax
		push ax

		call Checksum_piece
		pop ax
		pop ax

		mov si,4
		mov ax,ds
		inc ax
		inc ax
		mov ds,ax

		call Checksum_piece
		pop ax
		pop ax


		pop ds
		mov ax,[ds:32]
		mov cx,[ds:34]
		pop ds

		cmp ax,bx
		jne ChecksumError
		cmp cx,dx
		jne ChecksumError
		pop ax
		ret

ChecksumError:	pop ax
		xor ax,ax
		ret

Checksum_piece: push bp
		mov bp,sp

Checksum_next:	cmp si,16
		jne CSinParagraph
		xor si,si
		mov ax,ds
		inc ax
		mov ds,ax
CSinParagraph:	lodsb
		mov ah,0
		push cx
		and cl,15
		ror ax,cl
		add bx,ax
		adc dx,0
		pop cx
		dec cl

		sub word [ss:bp+6],1
		sbb word [ss:bp+4],0

		cmp word [ss:bp+6],0
		jne Checksum_next
		cmp word [ss:bp+4],0
		jne Checksum_next

		pop bp
		ret


The checksum-algorithm is based on rotations of bits. You can make it much simpler by only adding values of bytes. But with rotation of bytes, swapped bytes cause a checksum-error. The way you want to calculate your checksums is personal, you can choose every algorithm you want. This is just an example. I hope you can use these examples, because I cut away pieces of code to post only the checksum code here.

I added 450 kb's of random crap to my bootloader file, and even that large file, fragmented on a FAT12-filesystems, loads passing the checksum-test. So I know my files are loaded ok by the bootsector and FAT12-loader.

NOTE: I'm thinking about letting the first part of the header out of the checksum, so calculating can start at offset 36, after the checksum. That will make the routines much simpler..

Re: Loading Sectors: Floppy Real Mode

Posted: Sat Jun 28, 2008 4:38 pm
by Omega
Where is my mind? I am sorry for the late reply, I totally forgot I asked you this. Thanks a lot for the detailed explanation. I saved this page in my dev folder for later reference. :)

Re: Loading Sectors: Floppy Real Mode

Posted: Sat Jun 28, 2008 9:42 pm
by ChazZeromus
1) If you load at 0x1000 then sooner or later you might overwrite 0x7C00 where your boot sector was loaded by BIOS. If you did not relocated your code below 0x1000 then you will be in trouble.
0x7C00 is the exact location in which the BIOS loads the code, 0x1000 is the real-address-segment so it's not actually at 0x1000 but rather 0x10000. Just a reminder :wink:

Re: Loading Sectors: Floppy Real Mode

Posted: Tue Jul 01, 2008 11:01 am
by Ready4Dis
ChazZeromus wrote:
1) If you load at 0x1000 then sooner or later you might overwrite 0x7C00 where your boot sector was loaded by BIOS. If you did not relocated your code below 0x1000 then you will be in trouble.
0x7C00 is the exact location in which the BIOS loads the code, 0x1000 is the real-address-segment so it's not actually at 0x1000 but rather 0x10000. Just a reminder :wink:
Grr, bad information, please make it stop. No, 0x1000 is the value he is loading into BX which is the OFFSET, not the segment. He is loading ES with the value stored in AX, which is set to 0x0000! So the address IS 0x1000, and not 0x10000 as you suggest! Trying to correct someone that is right with wrong information just confuses more people. So, just a reminder to you, please make sure you know what you're talking about before correcting someone else :wink: