1# 2# Copyright (c) 2001 John Baldwin <jhb@FreeBSD.org> 3# All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions 7# are met: 8# 1. Redistributions of source code must retain the above copyright 9# notice, this list of conditions and the following disclaimer. 10# 2. Redistributions in binary form must reproduce the above copyright 11# notice, this list of conditions and the following disclaimer in the 12# documentation and/or other materials provided with the distribution. 13# 3. Neither the name of the author nor the names of any co-contributors 14# may be used to endorse or promote products derived from this software 15# without specific prior written permission. 16# 17# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 21# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27# SUCH DAMAGE. 28# 29 30# $FreeBSD$ 31 32# 33# This program is a freestanding boot program to load an a.out binary 34# from a CD-ROM booted with no emulation mode as described by the El 35# Torito standard. Due to broken BIOSen that do not load the desired 36# number of sectors, we try to fit this in as small a space as possible. 37# 38# Basically, we first create a set of boot arguments to pass to the loaded 39# binary. Then we attempt to load /boot/loader from the CD we were booted 40# off of. 41# 42 43#include <bootargs.h> 44 45# 46# Memory locations. 47# 48 .set MEM_PAGE_SIZE,0x1000 # memory page size, 4k 49 .set MEM_ARG,0x900 # Arguments at start 50 .set MEM_ARG_BTX,0xa100 # Where we move them to so the 51 # BTX client can see them 52 .set MEM_ARG_SIZE,0x18 # Size of the arguments 53 .set MEM_BTX_ADDRESS,0x9000 # where BTX lives 54 .set MEM_BTX_ENTRY,0x9010 # where BTX starts to execute 55 .set MEM_BTX_OFFSET,MEM_PAGE_SIZE # offset of BTX in the loader 56 .set MEM_BTX_CLIENT,0xa000 # where BTX clients live 57# 58# a.out header fields 59# 60 .set AOUT_TEXT,0x04 # text segment size 61 .set AOUT_DATA,0x08 # data segment size 62 .set AOUT_BSS,0x0c # zero'd BSS size 63 .set AOUT_SYMBOLS,0x10 # symbol table 64 .set AOUT_ENTRY,0x14 # entry point 65 .set AOUT_HEADER,MEM_PAGE_SIZE # size of the a.out header 66# 67# Segment selectors. 68# 69 .set SEL_SDATA,0x8 # Supervisor data 70 .set SEL_RDATA,0x10 # Real mode data 71 .set SEL_SCODE,0x18 # PM-32 code 72 .set SEL_SCODE16,0x20 # PM-16 code 73# 74# BTX constants 75# 76 .set INT_SYS,0x30 # BTX syscall interrupt 77# 78# Constants for reading from the CD. 79# 80 .set ERROR_TIMEOUT,0x80 # BIOS timeout on read 81 .set NUM_RETRIES,3 # Num times to retry 82 .set SECTOR_SIZE,0x800 # size of a sector 83 .set SECTOR_SHIFT,11 # number of place to shift 84 .set BUFFER_LEN,0x100 # number of sectors in buffer 85 .set MAX_READ,0x10000 # max we can read at a time 86 .set MAX_READ_SEC,MAX_READ >> SECTOR_SHIFT 87 .set MEM_READ_BUFFER,0x9000 # buffer to read from CD 88 .set MEM_VOLDESC,MEM_READ_BUFFER # volume descriptor 89 .set MEM_DIR,MEM_VOLDESC+SECTOR_SIZE # Lookup buffer 90 .set VOLDESC_LBA,0x10 # LBA of vol descriptor 91 .set VD_PRIMARY,1 # Primary VD 92 .set VD_END,255 # VD Terminator 93 .set VD_ROOTDIR,156 # Offset of Root Dir Record 94 .set DIR_LEN,0 # Offset of Dir Record length 95 .set DIR_EA_LEN,1 # Offset of EA length 96 .set DIR_EXTENT,2 # Offset of 64-bit LBA 97 .set DIR_SIZE,10 # Offset of 64-bit length 98 .set DIR_NAMELEN,32 # Offset of 8-bit name len 99 .set DIR_NAME,33 # Offset of dir name 100# 101# We expect to be loaded by the BIOS at 0x7c00 (standard boot loader entry 102# point) 103# 104 .code16 105 .globl start 106 .org 0x0, 0x0 107# 108# Program start. 109# 110start: cld # string ops inc 111 xor %ax,%ax # zero %ax 112 mov %ax,%ss # setup the 113 mov $start,%sp # stack 114 mov %ax,%ds # setup the 115 mov %ax,%es # data segments 116 mov %dl,drive # Save BIOS boot device 117 mov $msg_welcome,%si # %ds:(%si) -> welcome message 118 call putstr # display the welcome message 119# 120# Setup the arguments that the loader is expecting from boot[12] 121# 122 mov $msg_bootinfo,%si # %ds:(%si) -> boot args message 123 call putstr # display the message 124 mov $MEM_ARG,%bx # %ds:(%bx) -> boot args 125 mov %bx,%di # %es:(%di) -> boot args 126 xor %eax,%eax # zero %eax 127 mov $(MEM_ARG_SIZE/4),%cx # Size of arguments in 32-bit 128 # dwords 129 rep # Clear the arguments 130 stosl # to zero 131 mov drive,%dl # Store BIOS boot device 132 mov %dl,0x4(%bx) # in kargs->bootdev 133 or $KARGS_FLAGS_CD,0x8(%bx) # kargs->bootflags |= 134 # KARGS_FLAGS_CD 135# 136# Load Volume Descriptor 137# 138 mov $VOLDESC_LBA,%eax # Set LBA of first VD 139load_vd: push %eax # Save %eax 140 mov $1,%dh # One sector 141 mov $MEM_VOLDESC,%ebx # Destination 142 call read # Read it in 143 cmpb $VD_PRIMARY,(%bx) # Primary VD? 144 je have_vd # Yes 145 pop %eax # Prepare to 146 inc %eax # try next 147 cmpb $VD_END,(%bx) # Last VD? 148 jne load_vd # No, read next 149 mov $msg_novd,%si # No VD 150 jmp error # Halt 151have_vd: # Have Primary VD 152# 153# Try to look up the loader binary using the paths in the loader_paths 154# array. 155# 156 mov $loader_paths,%si # Point to start of array 157lookup_path: push %si # Save file name pointer 158 call lookup # Try to find file 159 pop %di # Restore file name pointer 160 jnc lookup_found # Found this file 161 xor %al,%al # Look for next 162 mov $0xffff,%cx # path name by 163 repnz # scanning for 164 scasb # nul char 165 mov %di,%si # Point %si at next path 166 mov (%si),%al # Get first char of next path 167 or %al,%al # Is it double nul? 168 jnz lookup_path # No, try it. 169 mov $msg_failed,%si # Failed message 170 jmp error # Halt 171lookup_found: # Found a loader file 172# 173# Load the binary into the buffer. Due to real mode addressing limitations 174# we have to read it in 64k chunks. 175# 176 mov DIR_SIZE(%bx),%eax # Read file length 177 add $SECTOR_SIZE-1,%eax # Convert length to sectors 178 shr $SECTOR_SHIFT,%eax 179 cmp $BUFFER_LEN,%eax 180 jbe load_sizeok 181 mov $msg_load2big,%si # Error message 182 call error 183load_sizeok: movzbw %al,%cx # Num sectors to read 184 mov DIR_EXTENT(%bx),%eax # Load extent 185 xor %edx,%edx 186 mov DIR_EA_LEN(%bx),%dl 187 add %edx,%eax # Skip extended 188 mov $MEM_READ_BUFFER,%ebx # Read into the buffer 189load_loop: mov %cl,%dh 190 cmp $MAX_READ_SEC,%cl # Truncate to max read size 191 jbe load_notrunc 192 mov $MAX_READ_SEC,%dh 193load_notrunc: sub %dh,%cl # Update count 194 push %eax # Save 195 call read # Read it in 196 pop %eax # Restore 197 add $MAX_READ_SEC,%eax # Update LBA 198 add $MAX_READ,%ebx # Update dest addr 199 jcxz load_done # Done? 200 jmp load_loop # Keep going 201load_done: 202# 203# Turn on the A20 address line 204# 205 call seta20 # Turn A20 on 206# 207# Relocate the loader and BTX using a very lazy protected mode 208# 209 mov $msg_relocate,%si # Display the 210 call putstr # relocation message 211 mov MEM_READ_BUFFER+AOUT_ENTRY,%edi # %edi is the destination 212 mov $(MEM_READ_BUFFER+AOUT_HEADER),%esi # %esi is 213 # the start of the text 214 # segment 215 mov MEM_READ_BUFFER+AOUT_TEXT,%ecx # %ecx = length of the text 216 # segment 217 push %edi # Save entry point for later 218 lgdt gdtdesc # setup our own gdt 219 cli # turn off interrupts 220 mov %cr0,%eax # Turn on 221 or $0x1,%al # protected 222 mov %eax,%cr0 # mode 223 ljmp $SEL_SCODE,$pm_start # long jump to clear the 224 # instruction pre-fetch queue 225 .code32 226pm_start: mov $SEL_SDATA,%ax # Initialize 227 mov %ax,%ds # %ds and 228 mov %ax,%es # %es to a flat selector 229 rep # Relocate the 230 movsb # text segment 231 add $(MEM_PAGE_SIZE - 1),%edi # pad %edi out to a new page 232 and $~(MEM_PAGE_SIZE - 1),%edi # for the data segment 233 mov MEM_READ_BUFFER+AOUT_DATA,%ecx # size of the data segment 234 rep # Relocate the 235 movsb # data segment 236 mov MEM_READ_BUFFER+AOUT_BSS,%ecx # size of the bss 237 xor %eax,%eax # zero %eax 238 add $3,%cl # round %ecx up to 239 shr $2,%ecx # a multiple of 4 240 rep # zero the 241 stosl # bss 242 mov MEM_READ_BUFFER+AOUT_ENTRY,%esi # %esi -> relocated loader 243 add $MEM_BTX_OFFSET,%esi # %esi -> BTX in the loader 244 mov $MEM_BTX_ADDRESS,%edi # %edi -> where BTX needs to go 245 movzwl 0xa(%esi),%ecx # %ecx -> length of BTX 246 rep # Relocate 247 movsb # BTX 248 ljmp $SEL_SCODE16,$pm_16 # Jump to 16-bit PM 249 .code16 250pm_16: mov $SEL_RDATA,%ax # Initialize 251 mov %ax,%ds # %ds and 252 mov %ax,%es # %es to a real mode selector 253 mov %cr0,%eax # Turn off 254 and $~0x1,%al # protected 255 mov %eax,%cr0 # mode 256 ljmp $0,$pm_end # Long jump to clear the 257 # instruction pre-fetch queue 258pm_end: sti # Turn interrupts back on now 259# 260# Copy the BTX client to MEM_BTX_CLIENT 261# 262 xor %ax,%ax # zero %ax and set 263 mov %ax,%ds # %ds and %es 264 mov %ax,%es # to segment 0 265 mov $MEM_BTX_CLIENT,%di # Prepare to relocate 266 mov $btx_client,%si # the simple btx client 267 mov $(btx_client_end-btx_client),%cx # length of btx client 268 rep # Relocate the 269 movsb # simple BTX client 270# 271# Copy the boot[12] args to where the BTX client can see them 272# 273 mov $MEM_ARG,%si # where the args are at now 274 mov $MEM_ARG_BTX,%di # where the args are moving to 275 mov $(MEM_ARG_SIZE/4),%cx # size of the arguments in longs 276 rep # Relocate 277 movsl # the words 278# 279# Save the entry point so the client can get to it later on 280# 281 pop %eax # Restore saved entry point 282 stosl # and add it to the end of 283 # the arguments 284# 285# Now we just start up BTX and let it do the rest 286# 287 mov $msg_jump,%si # Display the 288 call putstr # jump message 289 ljmp $0,$MEM_BTX_ENTRY # Jump to the BTX entry point 290 291# 292# Lookup the file in the path at [SI] from the root directory. 293# 294# Trashes: All but BX 295# Returns: CF = 0 (success), BX = pointer to record 296# CF = 1 (not found) 297# 298lookup: mov $VD_ROOTDIR+MEM_VOLDESC,%bx # Root directory record 299 push %si 300 mov $msg_lookup,%si # Display lookup message 301 call putstr 302 pop %si 303 push %si 304 call putstr 305 mov $msg_lookup2,%si 306 call putstr 307 pop %si 308lookup_dir: lodsb # Get first char of path 309 cmp $0,%al # Are we done? 310 je lookup_done # Yes 311 cmp $'/',%al # Skip path separator. 312 je lookup_dir 313 dec %si # Undo lodsb side effect 314 call find_file # Lookup first path item 315 jnc lookup_dir # Try next component 316 mov $msg_lookupfail,%si # Not found message 317 call putstr 318 stc # Set carry 319 ret 320 jmp error 321lookup_done: mov $msg_lookupok,%si # Success message 322 call putstr 323 clc # Clear carry 324 ret 325 326# 327# Lookup file at [SI] in directory whose record is at [BX]. 328# 329# Trashes: All but returns 330# Returns: CF = 0 (success), BX = pointer to record, SI = next path item 331# CF = 1 (not found), SI = preserved 332# 333find_file: mov DIR_EXTENT(%bx),%eax # Load extent 334 xor %edx,%edx 335 mov DIR_EA_LEN(%bx),%dl 336 add %edx,%eax # Skip extended attributes 337 mov %eax,rec_lba # Save LBA 338 mov DIR_SIZE(%bx),%eax # Save size 339 mov %eax,rec_size 340 xor %cl,%cl # Zero length 341 push %si # Save 342ff.namelen: inc %cl # Update length 343 lodsb # Read char 344 cmp $0,%al # Nul? 345 je ff.namedone # Yes 346 cmp $'/',%al # Path separator? 347 jnz ff.namelen # No, keep going 348ff.namedone: dec %cl # Adjust length and save 349 mov %cl,name_len 350 pop %si # Restore 351ff.load: mov rec_lba,%eax # Load LBA 352 mov $MEM_DIR,%ebx # Address buffer 353 mov $1,%dh # One sector 354 call read # Read directory block 355 incl rec_lba # Update LBA to next block 356ff.scan: mov %ebx,%edx # Check for EOF 357 sub $MEM_DIR,%edx 358 cmp %edx,rec_size 359 ja ff.scan.1 360 stc # EOF reached 361 ret 362ff.scan.1: cmpb $0,DIR_LEN(%bx) # Last record in block? 363 je ff.nextblock 364 push %si # Save 365 movzbw DIR_NAMELEN(%bx),%si # Find end of string 366ff.checkver: cmpb $'0',DIR_NAME-1(%bx,%si) # Less than '0'? 367 jb ff.checkver.1 368 cmpb $'9',DIR_NAME-1(%bx,%si) # Greater than '9'? 369 ja ff.checkver.1 370 dec %si # Next char 371 jnz ff.checkver 372 jmp ff.checklen # All numbers in name, so 373 # no version 374ff.checkver.1: movzbw DIR_NAMELEN(%bx),%cx 375 cmp %cx,%si # Did we find any digits? 376 je ff.checkdot # No 377 cmpb $';',DIR_NAME-1(%bx,%si) # Check for semicolon 378 jne ff.checkver.2 379 dec %si # Skip semicolon 380 mov %si,%cx 381 mov %cl,DIR_NAMELEN(%bx) # Adjust length 382 jmp ff.checkdot 383ff.checkver.2: mov %cx,%si # Restore %si to end of string 384ff.checkdot: cmpb $'.',DIR_NAME-1(%bx,%si) # Trailing dot? 385 jne ff.checklen # No 386 decb DIR_NAMELEN(%bx) # Adjust length 387ff.checklen: pop %si # Restore 388 movzbw name_len,%cx # Load length of name 389 cmp %cl,DIR_NAMELEN(%bx) # Does length match? 390 je ff.checkname # Yes, check name 391ff.nextrec: add DIR_LEN(%bx),%bl # Next record 392 adc $0,%bh 393 jmp ff.scan 394ff.nextblock: subl $SECTOR_SIZE,rec_size # Adjust size 395 jnc ff.load # If subtract ok, keep going 396 ret # End of file, so not found 397ff.checkname: lea DIR_NAME(%bx),%di # Address name in record 398 push %si # Save 399 repe cmpsb # Compare name 400 je ff.match # We have a winner! 401 pop %si # Restore 402 jmp ff.nextrec # Keep looking. 403ff.match: add $2,%sp # Discard saved %si 404 clc # Clear carry 405 ret 406 407# 408# Load DH sectors starting at LBA EAX into [EBX]. 409# 410# Trashes: EAX 411# 412read: push %si # Save 413 push %cx # Save since some BIOSs trash 414 mov %eax,edd_lba # LBA to read from 415 mov %ebx,%eax # Convert address 416 shr $4,%eax # to segment 417 mov %ax,edd_addr+0x2 # and store 418read.retry: call twiddle # Entertain the user 419 push %dx # Save 420 mov $edd_packet,%si # Address Packet 421 mov %dh,edd_len # Set length 422 mov drive,%dl # BIOS Device 423 mov $0x42,%ah # BIOS: Extended Read 424 int $0x13 # Call BIOS 425 pop %dx # Restore 426 jc read.fail # Worked? 427 pop %cx # Restore 428 pop %si 429 ret # Return 430read.fail: cmp $ERROR_TIMEOUT,%ah # Timeout? 431 je read.retry # Yes, Retry. 432read.error: mov %ah,%al # Save error 433 mov $hex_error,%di # Format it 434 call hex8 # as hex 435 mov $msg_badread,%si # Display Read error message 436 437# 438# Display error message at [SI] and halt. 439# 440error: call putstr # Display message 441halt: hlt 442 jmp halt # Spin 443 444# 445# Display a null-terminated string. 446# 447# Trashes: AX, SI 448# 449putstr: push %bx # Save 450putstr.load: lodsb # load %al from %ds:(%si) 451 test %al,%al # stop at null 452 jnz putstr.putc # if the char != null, output it 453 pop %bx # Restore 454 ret # return when null is hit 455putstr.putc: call putc # output char 456 jmp putstr.load # next char 457 458# 459# Display a single char. 460# 461putc: mov $0x7,%bx # attribute for output 462 mov $0xe,%ah # BIOS: put_char 463 int $0x10 # call BIOS, print char in %al 464 ret # Return to caller 465 466# 467# Output the "twiddle" 468# 469twiddle: push %ax # Save 470 push %bx # Save 471 mov twiddle_index,%al # Load index 472 mov $twiddle_chars,%bx # Address table 473 inc %al # Next 474 and $3,%al # char 475 mov %al,twiddle_index # Save index for next call 476 xlat # Get char 477 call putc # Output it 478 mov $8,%al # Backspace 479 call putc # Output it 480 pop %bx # Restore 481 pop %ax # Restore 482 ret 483 484# 485# Enable A20. Put an upper limit on the amount of time we wait for the 486# keyboard controller to get ready (65K x ISA access time). If 487# we wait more than that amount, the hardware is probably 488# legacy-free and simply doesn't have a keyboard controller. 489# Thus, the A20 line is already enabled. 490# 491seta20: cli # Disable interrupts 492 xor %cx,%cx # Clear 493seta20.1: inc %cx # Increment, overflow? 494 jz seta20.3 # Yes 495 in $0x64,%al # Get status 496 test $0x2,%al # Busy? 497 jnz seta20.1 # Yes 498 mov $0xd1,%al # Command: Write 499 out %al,$0x64 # output port 500seta20.2: in $0x64,%al # Get status 501 test $0x2,%al # Busy? 502 jnz seta20.2 # Yes 503 mov $0xdf,%al # Enable 504 out %al,$0x60 # A20 505seta20.3: sti # Enable interrupts 506 ret # To caller 507 508# 509# Convert AL to hex, saving the result to [EDI]. 510# 511hex8: pushl %eax # Save 512 shrb $0x4,%al # Do upper 513 call hex8.1 # 4 514 popl %eax # Restore 515hex8.1: andb $0xf,%al # Get lower 4 516 cmpb $0xa,%al # Convert 517 sbbb $0x69,%al # to hex 518 das # digit 519 orb $0x20,%al # To lower case 520 stosb # Save char 521 ret # (Recursive) 522 523# 524# BTX client to start btxldr 525# 526 .code32 527btx_client: mov $(MEM_ARG_BTX-MEM_BTX_CLIENT+MEM_ARG_SIZE-4), %esi 528 # %ds:(%esi) -> end 529 # of boot[12] args 530 mov $(MEM_ARG_SIZE/4),%ecx # Number of words to push 531 std # Go backwards 532push_arg: lodsl # Read argument 533 push %eax # Push it onto the stack 534 loop push_arg # Push all of the arguments 535 cld # In case anyone depends on this 536 pushl MEM_ARG_BTX-MEM_BTX_CLIENT+MEM_ARG_SIZE # Entry point of 537 # the loader 538 push %eax # Emulate a near call 539 mov $0x1,%eax # 'exec' system call 540 int $INT_SYS # BTX system call 541btx_client_end: 542 .code16 543 544 .p2align 4 545# 546# Global descriptor table. 547# 548gdt: .word 0x0,0x0,0x0,0x0 # Null entry 549 .word 0xffff,0x0,0x9200,0xcf # SEL_SDATA 550 .word 0xffff,0x0,0x9200,0x0 # SEL_RDATA 551 .word 0xffff,0x0,0x9a00,0xcf # SEL_SCODE (32-bit) 552 .word 0xffff,0x0,0x9a00,0x8f # SEL_SCODE16 (16-bit) 553gdt.1: 554# 555# Pseudo-descriptors. 556# 557gdtdesc: .word gdt.1-gdt-1 # Limit 558 .long gdt # Base 559# 560# EDD Packet 561# 562edd_packet: .byte 0x10 # Length 563 .byte 0 # Reserved 564edd_len: .byte 0x0 # Num to read 565 .byte 0 # Reserved 566edd_addr: .word 0x0,0x0 # Seg:Off 567edd_lba: .quad 0x0 # LBA 568 569drive: .byte 0 570 571# 572# State for searching dir 573# 574rec_lba: .long 0x0 # LBA (adjusted for EA) 575rec_size: .long 0x0 # File size 576name_len: .byte 0x0 # Length of current name 577 578twiddle_index: .byte 0x0 579 580msg_welcome: .asciz "CD Loader 1.2\r\n\n" 581msg_bootinfo: .asciz "Building the boot loader arguments\r\n" 582msg_relocate: .asciz "Relocating the loader and the BTX\r\n" 583msg_jump: .asciz "Starting the BTX loader\r\n" 584msg_badread: .ascii "Read Error: 0x" 585hex_error: .asciz "00\r\n" 586msg_novd: .asciz "Could not find Primary Volume Descriptor\r\n" 587msg_lookup: .asciz "Looking up " 588msg_lookup2: .asciz "... " 589msg_lookupok: .asciz "Found\r\n" 590msg_lookupfail: .asciz "File not found\r\n" 591msg_load2big: .asciz "File too big\r\n" 592msg_failed: .asciz "Boot failed\r\n" 593twiddle_chars: .ascii "|/-\\" 594loader_paths: .asciz "/BOOT/LOADER" 595 .asciz "/boot/loader" 596 .byte 0 597 598