summaryrefslogtreecommitdiff
path: root/boot/arch/amd64/mbr/mbr.S
blob: ee58525887095971d4a6781f7eeeec7ea77a483f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* Segment constants */
#define BOOT_SEG       0x7C0    /* Segment we reside on startup */
#define BOOT_RELOC_SEG 0x7A0    /* Relocation segment */

    .code16
_start:
    /* Normalize CS + other selectors */
    ljmp $BOOT_SEG,$1f
1:  xor %ax, %ax
    mov %ax, %ss
    mov %ax, %gs
    mov %ax, %fs

    /*
     * The second stage bootloader expects to be loaded to 0x7C00 but since we are
     * already executing at this address we'll need to relocate ourselves first before
     * we clobber it.
     */
    mov $BOOT_SEG, %ax
    mov %ax, %ds
    mov $BOOT_RELOC_SEG, %ax
    mov %ax, %es
    xor %si, %si
    xor %di, %di
    mov $0x200, %cx
    cld
    rep movsb

    /* Jump to our relocated self */
    ljmp $BOOT_RELOC_SEG,$reloc
reloc:
    /* Save the drive number */
    mov %dl, drive_num

    /* Set our stack */
    mov $0x7C00, %sp

    /* Write out our boot string */
    mov $boot_msg, %si
    call putstr

    /* Load two sectors */
    movw $2, dap_blkcnt
    movl $1, dap_lba_low
    call disk_read_lba

1:  cli
    hlt
    jmp 1b

/*
 * Read sectors from the disk
 */
disk_read_lba:
    pusha
    mov $dap, %si
    mov $0x42, %ah
    mov drive_num, %dl
    int $0x13
    jc .error
    popa
    ret
.error:
    mov $disk_err_msg, %si
    call putstr
1:  cli
    hlt
    jmp 1b

/*
 * Write a string to the console
 *
 * %si:  String to write
 *
 * XXX: Clobbers %AL
 */
putstr:
    lodsb
    or %al, %al
    jz 1f
    call putchr
    jmp putstr
1:  ret

/*
 * Write a single character to the console
 *
 * %al: Character to write
 */
putchr:
    mov $0x0E, %ah
    xor %bh, %bh
    int $0x10
    ret

dap:
    .byte 0x10
    .byte 0x00
dap_blkcnt:
    .word 0
dap_destptr:
    .word 0x7C00
dap_destseg:
    .word 0x0000
dap_lba_low:
    .long 0
dap_lba_high:
    .long 0

drive_num: .byte 0x00
boot_msg: .ascii "booting\r\n\0"
disk_err_msg: .ascii "\r\n!!!disk error!!!\r\n\0"

    .org 510
    .byte 0x55
    .byte 0xAA