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