/*1* Copyright (c) 2008 Luigi Rizzo (mostly documentation)2* Copyright (c) 2002 Bruce M. Simpson3* Copyright (c) 1998 Robert Nordier4* All rights reserved.5*6* Redistribution and use in source and binary forms are freely7* permitted provided that the above copyright notice and this8* paragraph and the following disclaimer are duplicated in all9* such forms.10*11* This software is provided "AS IS" and without any express or12* implied warranties, including, without limitation, the implied13* warranties of merchantability and fitness for a particular14* purpose.15*/1617/* build options: */1819#ifdef PXE /* enable PXE/INT18 booting with F6 */20#define SAVE_MORE_MEMORY21#endif222324#ifdef VOLUME_SERIAL /* support Volume serial number */25#define B0_BASE 0x1ae /* move the internal data area */26#define SAVE_MEMORY27#else28#define B0_BASE 0x1b229#endif3031#ifdef TEST /* enable some test code */32#define SAVE_MEMORY33#define SAVE_MORE_MEMORY34#endif3536/*37* Note - this code uses many tricks to save space and fit in one sector.38* This includes using side effects of certain instructions, reusing39* register values from previous operations, etc.40* Be extremely careful when changing the code, even for simple things.41*/4243/*44* BOOT BLOCK STRUCTURE45*46* This code implements a Master Boot Record (MBR) for an Intel/PC disk.47* It is 512 bytes long and it is normally loaded by the BIOS (or another48* bootloader) at 0:0x7c00. This code depends on %cs:%ip being 0:0x7c0049*50* The initial chunk of instructions is used as a signature by external51* tools (e.g. boot0cfg) which can manipulate the block itself.52*53* The area at offset 0x1b2 contains a magic string ('Drive '), also54* used as a signature to detect the block, and some variables that can55* be updated by boot0cfg (and optionally written back to the disk).56* These variables control the operation of the bootloader itself,57* e.g. which partitions to enable, the timeout, the use of LBA58* (called 'packet') or CHS mode, whether to force a drive number,59* and whether to write back the user's selection back to disk.60*61* As in every Master Boot Record, the partition table is at 0x1be,62* made of four 16-byte entries each containing:63*64* OFF SIZE DESCRIPTION65* 0 1 status (0x80: bootable, 0: non bootable)66* 1 3 start sector CHS67* 8:head, 6:sector, 2:cyl bit 9..8, 8:cyl bit 7..068* 4 1 partition type69* 5 3 end sector CHS70* 8 4 LBA of first sector71* 12 4 partition size in sectors72*73* and followed by the two bytes 0x55, 0xAA (MBR signature).74*/757677/*78* BOOT BLOCK OPERATION79*80* On entry, the registers contain the following values:81*82* %cs:%ip 0:0x7c0083* %dl drive number (0x80, 0x81, ... )84* %si pointer to the partition table from which we were loaded.85* Some boot code (e.g. syslinux) use this info to relocate86* themselves, so we want to pass a valid one to the next stage.87* NOTE: the use of %si is not a standard.88*89* This boot block first relocates itself at a different address (0:0x600),90* to free the space at 0:0x7c00 for the next stage boot block.91*92* It then initializes some memory at 0:0x800 and above (pointed by %bp)93* to store the original drive number (%dl) passed to us, and to construct a94* fake partition entry. The latter is used by the disk I/O routine and,95* in some cases, passed in %si to the next stage boot code.96*97* The variables at 0x1b2 are accessed as negative offsets from %bp.98*99* After the relocation, the code scans the partition table printing100* out enabled partition or disks, and waits for user input.101*102* When a partition is selected, or a timeout expires, the currently103* selected partition is used to load the next stage boot code,104* %dl and %si are set appropriately as when we were called, and105* control is transferred to the newly loaded code at 0:0x7c00.106*/107108/*109* CONSTANTS110*111* NHRDRV is the address in segment 0 where the BIOS writes the112* total number of hard disks in the system.113* LOAD is the original load address and cannot be changed.114* ORIGIN is the relocation address. If you change it, you also need115* to change the value passed to the linker in the Makefile116* PRT_OFF is the location of the partition table (from the MBR standard).117* B0_OFF is the location of the data area, known to boot0cfg so118* it cannot be changed. Computed as a negative offset from 0x200119* MAGIC is the signature of a boot block.120*/121122.set NHRDRV,0x475 # Number of hard drives123.set ORIGIN,0x600 # Execution address124.set LOAD,0x7c00 # Load address125126.set PRT_OFF,0x1be # Partition table127.set B0_OFF,(B0_BASE-0x200) # Offset of boot0 data128129.set MAGIC,0xaa55 # Magic: bootable130131.set KEY_ENTER,0x1c # Enter key scan code132.set KEY_F1,0x3b # F1 key scan code133.set KEY_1,0x02 # #1 key scan code134135.set ASCII_BEL,'#' # ASCII code for <BEL>136.set ASCII_CR,0x0D # ASCII code for <CR>137138/*139* Offsets of variables in the block at B0_OFF, and in the volatile140* data area, computed as displacement from %bp.141* We need to define them as constant as the assembler cannot142* compute them in its single pass.143*/144.set _NXTDRV, B0_OFF+6 # Next drive145.set _OPT, B0_OFF+7 # Default option146.set _SETDRV, B0_OFF+8 # Drive to force147.set _FLAGS, B0_OFF+9 # Flags148.set SETDRV, 0x20 # the 'setdrv' flag149.set NOUPDATE, 0x40 # the 'noupdate' flag150.set USEPACKET, 0x80 # the 'packet' flag151152/* ticks is at a fixed position */153.set _TICKS, (PRT_OFF - 0x200 - 2) # Timeout ticks154.set _MNUOPT, 0x10 # Saved menu entries155156.set TLEN, (desc_ofs - bootable_ids) # size of bootable ids157.globl start # Entry point158.code16 # This runs in real mode159160/*161* MAIN ENTRY POINT162* Initialise segments and registers to known values.163* segments start at 0.164* The stack is immediately below the address we were loaded to.165* NOTE: the initial section of the code (up to movw $LOAD,%sp)166* is used by boot0cfg, together with the 'Drive ' string and167* the 0x55, 0xaa at the end, as an identifier for version 1.0168* of the boot code. Do not change it.169* In version 1.0 the parameter table (_NEXTDRV etc) is at 0x1b9170*/171start: cld # String ops inc172xorw %ax,%ax # Zero173movw %ax,%es # Address174movw %ax,%ds # data175movw %ax,%ss # Set up176movw $LOAD,%sp # stack177178/*179* Copy this code to the address it was linked for, 0x600 by default.180*/181movw %sp,%si # Source182movw $start,%di # Destination183movw $0x100,%cx # Word count184rep # Relocate185movsw # code186/*187* After the code, (i.e. at %di+0, 0x800) create a partition entry,188* initialized to LBA 0 / CHS 0:0:1.189* Set %bp to point to the partition and also, with negative offsets,190* to the variables embedded in the bootblock (nextdrv and so on).191*/192movw %di,%bp # Address variables193movb $0x8,%cl # Words to clear194rep # Zero195stosw # them196incb -0xe(%di) # Set the S field to 1197198jmp main-LOAD+ORIGIN # Jump to relocated code199200main:201#if defined(SIO) && COMSPEED != 0202/*203* Init the serial port. bioscom preserves the driver number in DX.204*/205movw $COMSPEED,%ax # defined by Makefile206callw bioscom207#endif208209/*210* If the 'setdrv' flag is set in the boot sector, use the drive211* number from the boot sector at 'setdrv_num'.212* Optionally, do the same if the BIOS gives us an invalid number213* (note though that the override prevents booting from a floppy214* or a ZIP/flash drive in floppy emulation).215* The test costs 4 bytes of code so it is disabled by default.216*/217testb $SETDRV,_FLAGS(%bp) # Set drive number?218#ifndef CHECK_DRIVE /* disable drive checks */219jz save_curdrive # no, use the default220#else221jnz disable_update # Yes222testb %dl,%dl # Drive number valid?223js save_curdrive # Possibly (0x80 set)224#endif225/*226* Disable updates if the drive number is forced.227*/228disable_update: orb $NOUPDATE,_FLAGS(%bp) # Disable updates229movb _SETDRV(%bp),%dl # Use stored drive number230231/*232* Whatever drive we decided to use, store it at (%bp). The byte233* is normally used for the state of the partition (0x80 or 0x00),234* but we abuse it as it is very convenient to access at offset 0.235* The value is read back after 'check_selection'236*/237save_curdrive: movb %dl, (%bp) # Save drive number238pushw %dx # Also in the stack239#ifdef TEST /* test code, print internal bios drive */240rolb $1, %dl241movw $drive, %si242call putkey243#endif244callw putn # Print a newline245/*246* Start out with a pointer to the 4th byte of the first table entry247* so that after 4 iterations it's beyond the end of the sector248* and beyond a 256 byte boundary. We use the latter trick to check for249* end of the loop without using an extra register (see start.5).250*/251movw $(partbl+0x4),%bx # Partition table (+4)252xorw %dx,%dx # Item number253254/*255* Loop around on the partition table, printing values until we256* pass a 256 byte boundary.257*/258read_entry: movb %ch,-0x4(%bx) # Zero active flag (ch == 0)259btw %dx,_FLAGS(%bp) # Entry enabled?260jnc next_entry # No261movb (%bx),%al # Load type262test %al, %al # skip empty partition263jz next_entry264/*265* Scan the table of bootable ids, which starts at %di and has266* length TLEN. On a match, %di points to the element following the267* match; the corresponding offset to the description is $(TLEN-1)268* bytes ahead. We use a count of TLEN+1 so if we don't find a match269* within the first TLEN entries, we hit the 'unknown' entry.270*/271movw $bootable_ids,%di # Lookup tables272movb $(TLEN+1),%cl # Number of entries273repne # Locate274scasb # type275/*276* Get the matching element in the next array.277* The byte at $(TLEN-1)(%di) contains the offset of the description278* string from %di, so we add the number and print the string.279*/280addw $(TLEN-1), %di # Adjust281movb (%di),%cl # Partition282addw %cx,%di # description283callw putx # Display it284285next_entry: incw %dx # Next item286addb $0x10,%bl # Next entry287jnc read_entry # Till done288/*289* We are past a 256 byte boundary: the partition table is finished.290* Add one to the drive number and check it is valid.291* Note that if we started from a floppy, %dl was 0 so we still292* get an entry for the next drive, which is the first Hard Disk.293*/294popw %ax # Drive number295subb $0x80-0x1,%al # Does next296cmpb NHRDRV,%al # drive exist? (from BIOS?)297jb print_drive # Yes298/*299* If this is the only drive, don't display it as an option.300*/301decw %ax # Already drive 0?302jz print_prompt # Yes303/*304* If it was illegal or we cycled through them, go back to drive 0.305*/306xorb %al,%al # Drive 0307/*308* Whatever drive we selected, make it an ascii digit and save it309* back to the "nxtdrv" location in case we want to save it to disk.310* This digit is also part of the printed drive string, so add 0x80311* to indicate end of string.312*/313print_drive: addb $'0'|0x80,%al # Save next314movb %al,_NXTDRV(%bp) # drive number315movw $drive,%di # Display316callw putx # item317/*318* Menu is complete, display a prompt followed by current selection.319* 'decw %si' makes the register point to the space after 'Boot: '320* so we do not see an extra CRLF on the screen.321*/322print_prompt: movw $prompt,%si # Display323callw putstr # prompt324movb _OPT(%bp),%dl # Display325decw %si # default326callw putkey # key327jmp start_input # Skip beep328329/*330* Here we have the code waiting for user input or a timeout.331*/332beep: movb $ASCII_BEL,%al # Input error, print or beep333callw putchr334335start_input:336/*337* Actual Start of input loop. Take note of time338*/339xorb %ah,%ah # BIOS: Get340int $0x1a # system time341movw %dx,%di # Ticks when342addw _TICKS(%bp),%di # timeout343read_key:344/*345* Busy loop, looking for keystrokes but keeping one eye on the time.346*/347#ifndef SIO348movb $0x1,%ah # BIOS: Check349int $0x16 # for keypress350#else /* SIO */351movb $0x03,%ah # BIOS: Read COM352call bioscom353testb $0x01,%ah # Check line status354# (bit 1 indicates input)355#endif /* SIO */356jnz got_key # Have input357xorb %ah,%ah # BIOS: int 0x1a, 00358int $0x1a # get system time359cmpw %di,%dx # Timeout?360jb read_key # No361362/*363* Timed out or default selection364*/365use_default: movb _OPT(%bp),%al # Load default366orb $NOUPDATE,_FLAGS(%bp) # Disable updates367jmp check_selection # Join common code368369/*370* Get the keystroke.371* ENTER or CR confirm the current selection (same as a timeout).372* Otherwise convert F1..F6 (or '1'..'6') to 0..5 and check if the373* selection is valid.374* The SIO code uses ascii chars, the console code uses scancodes.375*/376got_key:377#ifndef SIO378xorb %ah,%ah # BIOS: int 0x16, 00379int $0x16 # get keypress380movb %ah,%al # move scan code to %al381cmpb $KEY_ENTER,%al382#else383movb $0x02,%ah # BIOS: Receive384call bioscom385cmpb $ASCII_CR,%al386#endif387je use_default # enter -> default388/*389* Check if the key is acceptable, and loop back if not.390* The console (non-SIO) code looks at scancodes and accepts391* both F1..F6 and 1..6 (the latter costs 6 bytes of code),392* relying on the fact that F1..F6 have higher scancodes than 1..6393* The SIO code only takes 1..6394*/395#ifdef SIO /* SIO mode, use ascii values */396subb $'1',%al # Subtract '1' ascii code397#else /* console mode -- use scancodes */398subb $KEY_F1,%al /* Subtract F1 scan code */399#if !defined(ONLY_F_KEYS)400cmpb $0x5,%al # F1..F6401jna 3f # Yes402subb $(KEY_1 - KEY_F1),%al # Less #1 scan code4033:404#endif /* ONLY_F_KEYS */405#endif /* SIO */406check_selection:407cmpb $0x5,%al # F1..F6 or 1..6 ?408#ifdef PXE /* enable PXE/INT18 using F6 */409jne 1f;410int $0x18 # found F6, try INT184111:412#endif /* PXE */413jae beep # Not in F1..F5, beep414415/*416* We have a selection. If it's a bad selection go back to complain.417* The bits in MNUOPT were set when the options were printed.418* Anything not printed is not an option.419*/420cbtw # Extend (%ah=0 used later)421btw %ax,_MNUOPT(%bp) # Option enabled?422jnc beep # No423/*424* Save the info in the original tables425* for rewriting to the disk.426*/427movb %al,_OPT(%bp) # Save option428429/*430* Make %si and %bx point to the fake partition at LBA 0 (CHS 0:0:1).431* Because the correct address is already in %bp, just use it.432* Set %dl with the drive number saved in byte 0.433* If we have pressed F5 or 5, then this is a good, fake value434* to present to the next stage boot code.435*/436movw %bp,%si # Partition for write437movb (%si),%dl # Drive number, saved above438movw %si,%bx # Partition for read439cmpb $0x4,%al # F5/#5 pressed?440pushf # Save results for later441je 1f # Yes, F5442443/*444* F1..F4 was pressed, so make %bx point to the currently445* selected partition, and leave the drive number unchanged.446*/447shlb $0x4,%al # Point to448addw $partbl,%ax # selected449xchgw %bx,%ax # partition450movb $0x80,(%bx) # Flag active451/*452* If not asked to do a write-back (flags 0x40) don't do one.453* Around the call, save the partition pointer to %bx and454* restore to %si which is where the next stage expects it.455*/4561: pushw %bx # Save457testb $NOUPDATE,_FLAGS(%bp) # No updates?458jnz 2f # skip update459movw $start,%bx # Data to write460movb $0x3,%ah # Write sector461callw intx13 # to disk4622: popw %si # Restore463464/*465* If going to next drive, replace drive with selected one.466* Remember to un-ascii it. Hey 0x80 is already set, cool!467*/468popf # Restore %al test results469jne 3f # If not F5/#5470movb _NXTDRV(%bp),%dl # Next drive471subb $'0',%dl # number472/*473* Load selected bootsector to the LOAD location in RAM. If read474* fails or there is no 0x55aa marker, treat it as a bad selection.475*/4763: movw $LOAD,%bx # Address for read477movb $0x2,%ah # Read sector478callw intx13 # from disk479jc beep # If error480cmpw $MAGIC,0x1fe(%bx) # Bootable?481jne beep # No482pushw %si # Save ptr to selected part.483callw putn # Leave some space484popw %si # Restore, next stage uses it485jmp *%bx # Invoke bootstrap486487/*488* Display routines489* putkey prints the option selected in %dl (F1..F5 or 1..5) followed by490* the string at %si491* putx: print the option in %dl followed by the string at %di492* also record the drive as valid.493* putn: print a crlf494* putstr: print the string at %si495* putchr: print the char in al496*/497498/*499* Display the option and record the drive as valid in the options.500* That last point is done using the btsw instruction which does501* a test and set. We don't care for the test part.502*/503putx: btsw %dx,_MNUOPT(%bp) # Enable menu option504movw $item,%si # Display505callw putkey # key506movw %di,%si # Display the rest507callw putstr # Display string508509putn: movw $crlf,%si # To next line510jmp putstr511512putkey:513#ifndef SIO514movb $'F',%al # Display515callw putchr # 'F'516#endif517movb $'1',%al # Prepare518addb %dl,%al # digit519520putstr.1: callw putchr # Display char521putstr: lodsb # Get byte522testb $0x80,%al # End of string?523jz putstr.1 # No524andb $~0x80,%al # Clear MSB then print last525526putchr:527#ifndef SIO528pushw %bx # Save529movw $0x7,%bx # Page:attribute530movb $0xe,%ah # BIOS: Display531int $0x10 # character532popw %bx # Restore533#else /* SIO */534movb $0x01,%ah # BIOS: Send character535bioscom:536pushw %dx # Save537xorw %dx,%dx # Use COM1538int $0x14 # BIOS: Serial I/O539popw %dx # Restore540#endif /* SIO */541retw # To caller542543/* One-sector disk I/O routine */544545/*546* %dl: drive, %si partition entry, %es:%bx transfer buffer.547* Load the CHS values and possibly the LBA address from the block548* at %si, and use the appropriate method to load the sector.549* Don't use packet mode for a floppy.550*/551intx13: # Prepare CHS parameters552movb 0x1(%si),%dh # Load head553movw 0x2(%si),%cx # Load cylinder:sector554movb $0x1,%al # Sector count555pushw %si # Save556movw %sp,%di # Save557#ifndef CHECK_DRIVE /* floppy support */558testb %dl, %dl # is this a floppy ?559jz 1f # Yes, use CHS mode560#endif561testb $USEPACKET,_FLAGS(%bp) # Use packet interface?562jz 1f # No563pushl $0x0 # Set the564pushl 0x8(%si) # LBA address565pushw %es # Set the transfer566pushw %bx # buffer address567push $0x1 # Block count568push $0x10 # Packet size569movw %sp,%si # Packet pointer570decw %ax # Verify off571orb $0x40,%ah # Use disk packet5721: int $0x13 # BIOS: Disk I/O573movw %di,%sp # Restore574popw %si # Restore575retw # To caller576577/*578* Various menu strings. 'item' goes after 'prompt' to save space.579* Also use shorter versions to make room for the PXE/INT18 code.580*/581prompt:582#ifdef PXE583.ascii "F6 PXE\r"584#endif585.ascii "\nBoot:"586item: .ascii " "; .byte ' '|0x80587crlf: .ascii "\r"; .byte '\n'|0x80588589/* Partition type tables */590591bootable_ids:592/*593* These values indicate bootable types we know about.594* Corresponding descriptions are at desc_ofs:595* Entries don't need to be sorted.596*/597.byte 0x83, 0xa5, 0xa6, 0xa9, 0x06, 0x07, 0x0b598#ifndef SAVE_MORE_MEMORY599.byte 0x05 # extended partition600#endif601#ifndef SAVE_MEMORY /* other DOS partitions */602.byte 0x01 # FAT12603.byte 0x04 # FAT16 < 32M604#endif605606desc_ofs:607/*608* Offsets that match the known types above, used to point to the609* actual partition name. The last entry must point to os_misc,610* which is used for non-matching names.611*/612.byte os_linux-. # 131, Linux613.byte os_freebsd-. # 165, FreeBSD614.byte os_bsd-. # 166, OpenBSD615.byte os_bsd-. # 169, NetBSD616.byte os_dos-. # 6, FAT16 >= 32M617.byte os_win-. # 7, NTFS618.byte os_win-. # 11, FAT32619620#ifndef SAVE_MORE_MEMORY621.byte os_ext-. # 5, DOS Ext622#endif623#ifndef SAVE_MEMORY624.byte os_dos-. # 1, FAT12 DOS625.byte os_dos-. # 4, FAT16 <32M626#endif627.byte os_misc-. # Unknown628629/*630* And here are the strings themselves. The last byte of631* the string has bit 7 set.632*/633os_misc: .byte '?'|0x80634os_dos:635#ifndef SAVE_MORE_MEMORY /* 'DOS' remapped to 'WIN' if no room */636.ascii "DO"; .byte 'S'|0x80637#endif638os_win: .ascii "Wi"; .byte 'n'|0x80639os_linux: .ascii "Linu"; .byte 'x'|0x80640os_freebsd: .ascii "Free"641os_bsd: .ascii "BS"; .byte 'D'|0x80642#ifndef SAVE_MORE_MEMORY643os_ext: .ascii "EX"; .byte 'T'|0x80644#endif645646.org (0x200 + B0_OFF),0x90647/*648* The boot0 version 1.0 parameter table.649* Do not move it nor change the "Drive " string, boot0cfg650* uses its offset and content to identify the boot sector.651* The other fields are sometimes changed before writing back to the drive652* Be especially careful that nxtdrv: must come after drive:, as it653* is part of the same string.654*/655drive: .ascii "Drive "656nxtdrv: .byte 0x0 # Next drive number657opt: .byte 0x0 # Option658setdrv_num: .byte 0x80 # Drive to force659flags: .byte FLAGS # Flags660#ifdef VOLUME_SERIAL661.byte 0xa8,0xa8,0xa8,0xa8 # Volume Serial Number662#endif663ticks: .word TICKS # Delay664665.org PRT_OFF666/*667* Here is the 64 byte MBR partition table.668*/669partbl: .fill 0x40,0x1,0x0 # Partition table670.word MAGIC # Magic number671.org 0x200 # again, safety check672endblock:673674675