#1# Copyright (c) 2001 John Baldwin <[email protected]>2#3# Redistribution and use in source and binary forms, with or without4# modification, are permitted provided that the following conditions5# are met:6# 1. Redistributions of source code must retain the above copyright7# notice, this list of conditions and the following disclaimer.8# 2. Redistributions in binary form must reproduce the above copyright9# notice, this list of conditions and the following disclaimer in the10# documentation and/or other materials provided with the distribution.11#12# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND13# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE14# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE15# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE16# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL17# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS18# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)19# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT20# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY21# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF22# SUCH DAMAGE.23#2425#26# This program is a freestanding boot program to load an a.out binary27# from a CD-ROM booted with no emulation mode as described by the El28# Torito standard. Due to broken BIOSen that do not load the desired29# number of sectors, we try to fit this in as small a space as possible.30#31# Basically, we first create a set of boot arguments to pass to the loaded32# binary. Then we attempt to load /boot/loader from the CD we were booted33# off of.34#3536#include <bootargs.h>3738#39# Memory locations.40#41.set MEM_PAGE_SIZE,0x1000 # memory page size, 4k42.set MEM_ARG,0x900 # Arguments at start43.set MEM_ARG_BTX,0xa100 # Where we move them to so the44# BTX client can see them45.set MEM_ARG_SIZE,0x18 # Size of the arguments46.set MEM_BTX_ADDRESS,0x9000 # where BTX lives47.set MEM_BTX_ENTRY,0x9010 # where BTX starts to execute48.set MEM_BTX_OFFSET,MEM_PAGE_SIZE # offset of BTX in the loader49.set MEM_BTX_CLIENT,0xa000 # where BTX clients live50#51# a.out header fields52#53.set AOUT_TEXT,0x04 # text segment size54.set AOUT_DATA,0x08 # data segment size55.set AOUT_BSS,0x0c # zero'd BSS size56.set AOUT_SYMBOLS,0x10 # symbol table57.set AOUT_ENTRY,0x14 # entry point58.set AOUT_HEADER,MEM_PAGE_SIZE # size of the a.out header59#60# Segment selectors.61#62.set SEL_SDATA,0x8 # Supervisor data63.set SEL_RDATA,0x10 # Real mode data64.set SEL_SCODE,0x18 # PM-32 code65.set SEL_SCODE16,0x20 # PM-16 code66#67# BTX constants68#69.set INT_SYS,0x30 # BTX syscall interrupt70#71# Constants for reading from the CD.72#73.set ERROR_TIMEOUT,0x80 # BIOS timeout on read74.set NUM_RETRIES,3 # Num times to retry75.set SECTOR_SIZE,0x800 # size of a sector76.set SECTOR_SHIFT,11 # number of place to shift77.set BUFFER_LEN,0x100 # number of sectors in buffer78.set MAX_READ,0x10000 # max we can read at a time79.set MAX_READ_SEC,MAX_READ >> SECTOR_SHIFT80.set MEM_READ_BUFFER,0x9000 # buffer to read from CD81.set MEM_VOLDESC,MEM_READ_BUFFER # volume descriptor82.set MEM_DIR,MEM_VOLDESC+SECTOR_SIZE # Lookup buffer83.set VOLDESC_LBA,0x10 # LBA of vol descriptor84.set VD_PRIMARY,1 # Primary VD85.set VD_END,255 # VD Terminator86.set VD_ROOTDIR,156 # Offset of Root Dir Record87.set DIR_LEN,0 # Offset of Dir Record length88.set DIR_EA_LEN,1 # Offset of EA length89.set DIR_EXTENT,2 # Offset of 64-bit LBA90.set DIR_SIZE,10 # Offset of 64-bit length91.set DIR_NAMELEN,32 # Offset of 8-bit name len92.set DIR_NAME,33 # Offset of dir name93#94# We expect to be loaded by the BIOS at 0x7c00 (standard boot loader entry95# point)96#97.code1698.globl start99.org 0x0, 0x0100#101# Program start.102#103start: cld # string ops inc104xor %ax,%ax # zero %ax105mov %ax,%ss # setup the106mov $start,%sp # stack107mov %ax,%ds # setup the108mov %ax,%es # data segments109mov %dl,drive # Save BIOS boot device110mov $msg_welcome,%si # %ds:(%si) -> welcome message111call putstr # display the welcome message112#113# Setup the arguments that the loader is expecting from boot[12]114#115mov $msg_bootinfo,%si # %ds:(%si) -> boot args message116call putstr # display the message117mov $MEM_ARG,%bx # %ds:(%bx) -> boot args118mov %bx,%di # %es:(%di) -> boot args119xor %eax,%eax # zero %eax120mov $(MEM_ARG_SIZE/4),%cx # Size of arguments in 32-bit121# dwords122rep # Clear the arguments123stosl # to zero124mov drive,%dl # Store BIOS boot device125mov %dl,0x4(%bx) # in kargs->bootdev126orb $KARGS_FLAGS_CD,0x8(%bx) # kargs->bootflags |=127# KARGS_FLAGS_CD128#129# Load Volume Descriptor130#131mov $VOLDESC_LBA,%eax # Set LBA of first VD132load_vd: push %eax # Save %eax133mov $1,%dh # One sector134mov $MEM_VOLDESC,%ebx # Destination135call read # Read it in136cmpb $VD_PRIMARY,(%bx) # Primary VD?137je have_vd # Yes138pop %eax # Prepare to139inc %eax # try next140cmpb $VD_END,(%bx) # Last VD?141jne load_vd # No, read next142mov $msg_novd,%si # No VD143jmp error # Halt144have_vd: # Have Primary VD145#146# Try to look up the loader binary using the paths in the loader_paths147# array.148#149mov $loader_paths,%si # Point to start of array150lookup_path: push %si # Save file name pointer151call lookup # Try to find file152pop %di # Restore file name pointer153jnc lookup_found # Found this file154xor %al,%al # Look for next155mov $0xffff,%cx # path name by156repnz # scanning for157scasb # nul char158mov %di,%si # Point %si at next path159mov (%si),%al # Get first char of next path160or %al,%al # Is it double nul?161jnz lookup_path # No, try it.162mov $msg_failed,%si # Failed message163jmp error # Halt164lookup_found: # Found a loader file165#166# Load the binary into the buffer. Due to real mode addressing limitations167# we have to read it in 64k chunks.168#169mov DIR_SIZE(%bx),%eax # Read file length170add $SECTOR_SIZE-1,%eax # Convert length to sectors171shr $SECTOR_SHIFT,%eax172cmp $BUFFER_LEN,%eax173jbe load_sizeok174mov $msg_load2big,%si # Error message175call error176load_sizeok: movzbw %al,%cx # Num sectors to read177mov DIR_EXTENT(%bx),%eax # Load extent178xor %edx,%edx179mov DIR_EA_LEN(%bx),%dl180add %edx,%eax # Skip extended181mov $MEM_READ_BUFFER,%ebx # Read into the buffer182load_loop: mov %cl,%dh183cmp $MAX_READ_SEC,%cl # Truncate to max read size184jbe load_notrunc185mov $MAX_READ_SEC,%dh186load_notrunc: sub %dh,%cl # Update count187push %eax # Save188call read # Read it in189pop %eax # Restore190add $MAX_READ_SEC,%eax # Update LBA191add $MAX_READ,%ebx # Update dest addr192jcxz load_done # Done?193jmp load_loop # Keep going194load_done:195#196# Turn on the A20 address line197#198call seta20 # Turn A20 on199#200# Relocate the loader and BTX using a very lazy protected mode201#202mov $msg_relocate,%si # Display the203call putstr # relocation message204mov MEM_READ_BUFFER+AOUT_ENTRY,%edi # %edi is the destination205mov $(MEM_READ_BUFFER+AOUT_HEADER),%esi # %esi is206# the start of the text207# segment208mov MEM_READ_BUFFER+AOUT_TEXT,%ecx # %ecx = length of the text209# segment210push %edi # Save entry point for later211lgdt gdtdesc # setup our own gdt212cli # turn off interrupts213mov %cr0,%eax # Turn on214or $0x1,%al # protected215mov %eax,%cr0 # mode216ljmp $SEL_SCODE,$pm_start # long jump to clear the217# instruction pre-fetch queue218.code32219pm_start: mov $SEL_SDATA,%ax # Initialize220mov %ax,%ds # %ds and221mov %ax,%es # %es to a flat selector222rep # Relocate the223movsb # text segment224add $(MEM_PAGE_SIZE - 1),%edi # pad %edi out to a new page225and $~(MEM_PAGE_SIZE - 1),%edi # for the data segment226mov MEM_READ_BUFFER+AOUT_DATA,%ecx # size of the data segment227rep # Relocate the228movsb # data segment229mov MEM_READ_BUFFER+AOUT_BSS,%ecx # size of the bss230xor %eax,%eax # zero %eax231add $3,%cl # round %ecx up to232shr $2,%ecx # a multiple of 4233rep # zero the234stosl # bss235mov MEM_READ_BUFFER+AOUT_ENTRY,%esi # %esi -> relocated loader236add $MEM_BTX_OFFSET,%esi # %esi -> BTX in the loader237mov $MEM_BTX_ADDRESS,%edi # %edi -> where BTX needs to go238movzwl 0xa(%esi),%ecx # %ecx -> length of BTX239rep # Relocate240movsb # BTX241ljmp $SEL_SCODE16,$pm_16 # Jump to 16-bit PM242.code16243pm_16: mov $SEL_RDATA,%ax # Initialize244mov %ax,%ds # %ds and245mov %ax,%es # %es to a real mode selector246mov %cr0,%eax # Turn off247and $~0x1,%al # protected248mov %eax,%cr0 # mode249ljmp $0,$pm_end # Long jump to clear the250# instruction pre-fetch queue251pm_end: sti # Turn interrupts back on now252#253# Copy the BTX client to MEM_BTX_CLIENT254#255xor %ax,%ax # zero %ax and set256mov %ax,%ds # %ds and %es257mov %ax,%es # to segment 0258mov $MEM_BTX_CLIENT,%di # Prepare to relocate259mov $btx_client,%si # the simple btx client260mov $(btx_client_end-btx_client),%cx # length of btx client261rep # Relocate the262movsb # simple BTX client263#264# Copy the boot[12] args to where the BTX client can see them265#266mov $MEM_ARG,%si # where the args are at now267mov $MEM_ARG_BTX,%di # where the args are moving to268mov $(MEM_ARG_SIZE/4),%cx # size of the arguments in longs269rep # Relocate270movsl # the words271#272# Save the entry point so the client can get to it later on273#274pop %eax # Restore saved entry point275stosl # and add it to the end of276# the arguments277#278# Now we just start up BTX and let it do the rest279#280mov $msg_jump,%si # Display the281call putstr # jump message282ljmp $0,$MEM_BTX_ENTRY # Jump to the BTX entry point283284#285# Lookup the file in the path at [SI] from the root directory.286#287# Trashes: All but BX288# Returns: CF = 0 (success), BX = pointer to record289# CF = 1 (not found)290#291lookup: mov $VD_ROOTDIR+MEM_VOLDESC,%bx # Root directory record292push %si293mov $msg_lookup,%si # Display lookup message294call putstr295pop %si296push %si297call putstr298mov $msg_lookup2,%si299call putstr300pop %si301lookup_dir: lodsb # Get first char of path302cmp $0,%al # Are we done?303je lookup_done # Yes304cmp $'/',%al # Skip path separator.305je lookup_dir306dec %si # Undo lodsb side effect307call find_file # Lookup first path item308jnc lookup_dir # Try next component309mov $msg_lookupfail,%si # Not found message310call putstr311stc # Set carry312ret313jmp error314lookup_done: mov $msg_lookupok,%si # Success message315call putstr316clc # Clear carry317ret318319#320# Lookup file at [SI] in directory whose record is at [BX].321#322# Trashes: All but returns323# Returns: CF = 0 (success), BX = pointer to record, SI = next path item324# CF = 1 (not found), SI = preserved325#326find_file: mov DIR_EXTENT(%bx),%eax # Load extent327xor %edx,%edx328mov DIR_EA_LEN(%bx),%dl329add %edx,%eax # Skip extended attributes330mov %eax,rec_lba # Save LBA331mov DIR_SIZE(%bx),%eax # Save size332mov %eax,rec_size333xor %cl,%cl # Zero length334push %si # Save335ff.namelen: inc %cl # Update length336lodsb # Read char337cmp $0,%al # Nul?338je ff.namedone # Yes339cmp $'/',%al # Path separator?340jnz ff.namelen # No, keep going341ff.namedone: dec %cl # Adjust length and save342mov %cl,name_len343pop %si # Restore344ff.load: mov rec_lba,%eax # Load LBA345mov $MEM_DIR,%ebx # Address buffer346mov $1,%dh # One sector347call read # Read directory block348incl rec_lba # Update LBA to next block349ff.scan: mov %ebx,%edx # Check for EOF350sub $MEM_DIR,%edx351cmp %edx,rec_size352ja ff.scan.1353stc # EOF reached354ret355ff.scan.1: cmpb $0,DIR_LEN(%bx) # Last record in block?356je ff.nextblock357push %si # Save358movzbw DIR_NAMELEN(%bx),%si # Find end of string359ff.checkver: cmpb $'0',DIR_NAME-1(%bx,%si) # Less than '0'?360jb ff.checkver.1361cmpb $'9',DIR_NAME-1(%bx,%si) # Greater than '9'?362ja ff.checkver.1363dec %si # Next char364jnz ff.checkver365jmp ff.checklen # All numbers in name, so366# no version367ff.checkver.1: movzbw DIR_NAMELEN(%bx),%cx368cmp %cx,%si # Did we find any digits?369je ff.checkdot # No370cmpb $';',DIR_NAME-1(%bx,%si) # Check for semicolon371jne ff.checkver.2372dec %si # Skip semicolon373mov %si,%cx374mov %cl,DIR_NAMELEN(%bx) # Adjust length375jmp ff.checkdot376ff.checkver.2: mov %cx,%si # Restore %si to end of string377ff.checkdot: cmpb $'.',DIR_NAME-1(%bx,%si) # Trailing dot?378jne ff.checklen # No379decb DIR_NAMELEN(%bx) # Adjust length380ff.checklen: pop %si # Restore381movzbw name_len,%cx # Load length of name382cmp %cl,DIR_NAMELEN(%bx) # Does length match?383je ff.checkname # Yes, check name384ff.nextrec: add DIR_LEN(%bx),%bl # Next record385adc $0,%bh386jmp ff.scan387ff.nextblock: subl $SECTOR_SIZE,rec_size # Adjust size388jnc ff.load # If subtract ok, keep going389ret # End of file, so not found390ff.checkname: lea DIR_NAME(%bx),%di # Address name in record391push %si # Save392repe cmpsb # Compare name393je ff.match # We have a winner!394pop %si # Restore395jmp ff.nextrec # Keep looking.396ff.match: add $2,%sp # Discard saved %si397clc # Clear carry398ret399400#401# Load DH sectors starting at LBA EAX into [EBX].402#403# Trashes: EAX404#405read: push %si # Save406push %cx # Save since some BIOSs trash407mov %eax,edd_lba # LBA to read from408mov %ebx,%eax # Convert address409shr $4,%eax # to segment410mov %ax,edd_addr+0x2 # and store411read.retry: call twiddle # Entertain the user412push %dx # Save413mov $edd_packet,%si # Address Packet414mov %dh,edd_len # Set length415mov drive,%dl # BIOS Device416mov $0x42,%ah # BIOS: Extended Read417int $0x13 # Call BIOS418pop %dx # Restore419jc read.fail # Worked?420pop %cx # Restore421pop %si422ret # Return423read.fail: cmp $ERROR_TIMEOUT,%ah # Timeout?424je read.retry # Yes, Retry.425read.error: mov %ah,%al # Save error426mov $hex_error,%di # Format it427call hex8 # as hex428mov $msg_badread,%si # Display Read error message429430#431# Display error message at [SI] and halt.432#433error: call putstr # Display message434halt: hlt435jmp halt # Spin436437#438# Display a null-terminated string.439#440# Trashes: AX, SI441#442putstr: push %bx # Save443putstr.load: lodsb # load %al from %ds:(%si)444test %al,%al # stop at null445jnz putstr.putc # if the char != null, output it446pop %bx # Restore447ret # return when null is hit448putstr.putc: call putc # output char449jmp putstr.load # next char450451#452# Display a single char.453#454putc: mov $0x7,%bx # attribute for output455mov $0xe,%ah # BIOS: put_char456int $0x10 # call BIOS, print char in %al457ret # Return to caller458459#460# Output the "twiddle"461#462twiddle: push %ax # Save463push %bx # Save464mov twiddle_index,%al # Load index465mov $twiddle_chars,%bx # Address table466inc %al # Next467and $3,%al # char468mov %al,twiddle_index # Save index for next call469xlat # Get char470call putc # Output it471mov $8,%al # Backspace472call putc # Output it473pop %bx # Restore474pop %ax # Restore475ret476477#478# Enable A20. Put an upper limit on the amount of time we wait for the479# keyboard controller to get ready (65K x ISA access time). If480# we wait more than that amount, the hardware is probably481# legacy-free and simply doesn't have a keyboard controller.482# Thus, the A20 line is already enabled.483#484seta20: cli # Disable interrupts485xor %cx,%cx # Clear486seta20.1: inc %cx # Increment, overflow?487jz seta20.3 # Yes488in $0x64,%al # Get status489test $0x2,%al # Busy?490jnz seta20.1 # Yes491mov $0xd1,%al # Command: Write492out %al,$0x64 # output port493seta20.2: in $0x64,%al # Get status494test $0x2,%al # Busy?495jnz seta20.2 # Yes496mov $0xdf,%al # Enable497out %al,$0x60 # A20498seta20.3: sti # Enable interrupts499ret # To caller500501#502# Convert AL to hex, saving the result to [EDI].503#504hex8: pushl %eax # Save505shrb $0x4,%al # Do upper506call hex8.1 # 4507popl %eax # Restore508hex8.1: andb $0xf,%al # Get lower 4509cmpb $0xa,%al # Convert510sbbb $0x69,%al # to hex511das # digit512orb $0x20,%al # To lower case513stosb # Save char514ret # (Recursive)515516#517# BTX client to start btxldr518#519.code32520btx_client: mov $(MEM_ARG_BTX-MEM_BTX_CLIENT+MEM_ARG_SIZE-4), %esi521# %ds:(%esi) -> end522# of boot[12] args523mov $(MEM_ARG_SIZE/4),%ecx # Number of words to push524std # Go backwards525push_arg: lodsl # Read argument526push %eax # Push it onto the stack527loop push_arg # Push all of the arguments528cld # In case anyone depends on this529pushl MEM_ARG_BTX-MEM_BTX_CLIENT+MEM_ARG_SIZE # Entry point of530# the loader531push %eax # Emulate a near call532mov $0x1,%eax # 'exec' system call533int $INT_SYS # BTX system call534btx_client_end:535.code16536537.p2align 4538#539# Global descriptor table.540#541gdt: .word 0x0,0x0,0x0,0x0 # Null entry542.word 0xffff,0x0,0x9200,0xcf # SEL_SDATA543.word 0xffff,0x0,0x9200,0x0 # SEL_RDATA544.word 0xffff,0x0,0x9a00,0xcf # SEL_SCODE (32-bit)545.word 0xffff,0x0,0x9a00,0x8f # SEL_SCODE16 (16-bit)546gdt.1:547#548# Pseudo-descriptors.549#550gdtdesc: .word gdt.1-gdt-1 # Limit551.long gdt # Base552#553# EDD Packet554#555edd_packet: .byte 0x10 # Length556.byte 0 # Reserved557edd_len: .byte 0x0 # Num to read558.byte 0 # Reserved559edd_addr: .word 0x0,0x0 # Seg:Off560edd_lba: .quad 0x0 # LBA561562drive: .byte 0563564#565# State for searching dir566#567rec_lba: .long 0x0 # LBA (adjusted for EA)568rec_size: .long 0x0 # File size569name_len: .byte 0x0 # Length of current name570571twiddle_index: .byte 0x0572573msg_welcome: .asciz "CD Loader 1.2\r\n\n"574msg_bootinfo: .asciz "Building the boot loader arguments\r\n"575msg_relocate: .asciz "Relocating the loader and the BTX\r\n"576msg_jump: .asciz "Starting the BTX loader\r\n"577msg_badread: .ascii "Read Error: 0x"578hex_error: .asciz "00\r\n"579msg_novd: .asciz "Could not find Primary Volume Descriptor\r\n"580msg_lookup: .asciz "Looking up "581msg_lookup2: .asciz "... "582msg_lookupok: .asciz "Found\r\n"583msg_lookupfail: .asciz "File not found\r\n"584msg_load2big: .asciz "File too big\r\n"585msg_failed: .asciz "Boot failed\r\n"586twiddle_chars: .ascii "|/-\\"587loader_paths: .asciz "/BOOT/LOADER"588.asciz "/boot/loader"589.byte 0590591592593