Academic Operating System

We are developing an operating system for my personal research and practical education. For the academic purpose, this motivation is similar to MINIX, but we do not focus on theories. Our main objective is to provide knowledges on hardware-related programming. This is one of the most difficult and complex parts when we start the development of operating system from scratch.

The source code is available at the public github repository.

Checkpoint 6: Execute a boot monitor and enter 32/64-bit mode

Boot monitor provides an entry point to the operating system. In this checkpoint, the boot monitor waits user's interaction to choose the boot option. After the boot option is specified, the software tries to enter 32/64-bit mode unless the option is power off. In the 64-bit mode, we can use “C”!

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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*_
 * Copyright (c) 2015 Hirochika Asai <asai@jar.jp>
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

	.set	IVT_IRQ0,0x08	/* IRQ0 = 0x08 (BIOS default) */
	.set	IVT_IRQ8,0x70	/* IRQ0 = 0x70 (BIOS default) */
	.set	KBD_LCTRL,0x1d	/* Left ctrl */
	.set	KBD_LSHIFT,0x2a	/* Left shift */
	.set	KBD_RSHIFT,0x36	/* Right shift */
	.set	KBD_CAPS,0x3a	/* Caps lock */
	.set	KBD_RCTRL,0x5a	/* Right ctrl */
	.set	KBD_UP,0x48	/* Up */
	.set	KBD_LEFT,0x4b	/* Left */
	.set	KBD_RIGHT,0x4d	/* Right */
	.set	KBD_DOWN,0x50	/* Down */
	.set	VGA_TEXT_COLOR_80x25,0x03
	.set	BOOT_TIMEOUT,3	/* Timeout in seconds */
	.set	NUM_RETRIES,3		/* # of retries for disk read */
	.set	ERRCODE_TIMEOUT,0x80	/* Error code: Timeout */
	.set	SECTOR_SIZE,0x200	/* 512 bytes / sector */

	.text

	.code16
	.globl	bootmon		/* Entry point */

/*
 * Boot monitor (from BIOS)
 *   %cs:%ip=0x0900:0x0000 (=0x9000)
 *   %dl: drive
 */
bootmon:
	/* Save parameters from IPL */
	movb	%dl,drive

	/* Set video mode to 16bit color text mode */
	movb	VGA_TEXT_COLOR_80x25,%al
	movb	$0x00,%ah
	int	$0x10

	/* Enable A20 */
	call	enable_a20

	/* Print out boot option message */
	movw	$0,%ax
	movw	%ax,%ds
	movw	$msg_bootopt,%si
	call	putstr

	/* Setup the timer interrupt handler */
	xorw	%ax,%ax
	movw	%ax,%es
	movw	$intr_irq0,%ax
	movw	$(IVT_IRQ0+0),%bx
	call	setup_intvec

	/* Setup the keyboard interrupt handler */
	xorw	%ax,%ax
	movw	%ax,%es
	movw	$intr_irq1,%ax
	movw	$(IVT_IRQ0+1),%bx
	call	setup_intvec

	/* Initialize the counter */
	movw	$BOOT_TIMEOUT*100,(counter)	/* 99 seconds (in centisecond) */

	/* Start the timer */
	call	init_pit

	/* Wait for keyboard interrupts */
1:
	sti
	hlt
	cli
	movb	(bootmode),%al
	cmpb	$'1',%al	/* If `1' is pressed */
	je	2f
	cmpb	$'2',%al	/* If `2' is pressed */
	je	3f
	cmpw	$0,(counter)	/* If the counter reached zero */
	je	2f
	jmp	1b
2:
	/* Boot */
	jmp	entry16
3:
	/* Power off */
	call	poweroff	/* Call power off function */
	jmp	1b		/* If failed, then go back */



/* Initialize programmable interval timer */
init_pit:
	pushw	%ax
	movb	$(0x00|0x30|0x06),%al
	outb	%al,$0x43
	movw	$0x2e9b,%ax	/* Frequency=100Hz: 1193181.67/100 */
	outb	%al,$0x40	/* Counter 0 (least significant 4 bits) */
	movb	%ah,%al		/* Get most significant 4 bits */
	outb	%al,$0x40	/* Counter 0 (most significant 4 bits) */
	popw	%ax
	ret

/*
 * Setup interrupt vector
 *   %es: code segment
 *   %ax: instruction pointer
 *   %bx: interrupt vector number
 */
setup_intvec:
	pushw	%bx
	shlw	$2,%bx
	movw	%ax,(%bx)
	addw	$2,%bx
	movw	%es,(%bx)
	popw	%bx
	ret

/*
 * Timer interrupt handler
 */
intr_irq0:
	/* Save registers to the stack */
	pushw	%ax
	pushw	%bx
	pushw	%cx
	pushw	%dx
	pushw	%ds
	pushw	%si

	movw	(counter),%ax	/* Get the previous counter value */
	testw	%ax,%ax
	jz	1f		/* Jump if the counter reaches zero */
	decw	%ax		/* Decrease the counter by one */
	movw	%ax,(counter)	/* Save the counter */
1:
	movb	$100,%dl	/* Convert centisecond to second */
	divb	%dl		/*  Q=%al, R=%ah */
	xorb	%ah,%ah
	movb	$10,%dl
	divb	%dl		/* Q(%al) = tens digit, R(%ah) = unit digit */
	addb	$'0',%al	/* To ascii */
	addb	$'0',%ah	/* To ascii */
	movw	%ax,msg_count

	xorw	%ax,%ax
	movw	%ax,%ds
	movw	$msg_countdown,%si
	call	putbstr

	/* EOI for PIC1 */
	movb	$0x20,%al
	outb	%al,$0x20

	/* Restore registers */
	popw	%si
	popw	%dx
	popw	%dx
	popw	%cx
	popw	%bx
	popw	%ax
	iret

/*
 * Keyboard interrupt handler
 */
intr_irq1:
	pushw	%ax
	pushw	%bx
	xorw	%ax,%ax		/* Zero */
	inb	$0x60,%al	/* Scan code from the keyboard controller */
1:
	movb	%al,%bl		/* Ignore the flag */
	and	$0x7f,%bl	/*  indicating released in %bl */
	cmpb	$KBD_LSHIFT,%bl	/* Left shift */
	je	4f		/* Jump if left shift */
	cmpb	$KBD_RSHIFT,%bl	/* Right shift */
	je	4f		/* Jump if right shift */
	/* Otherwise */
	testb	$0x80,%al	/* Released? */
	jnz	6f		/*  Yes, then ignore the key */
	cmpb	$0,(keyboard_shift)	/* Shift key is released? */
	je	2f		/*  Yes, then use base keymap */
	movw	$keymap_shift,%bx	/*  Otherwise, use shifted keymap */
	jmp	3f
2:
	movw	$keymap_base,%bx	/* Use base keymap */
3:
	addw	%ax,%bx
	movb	(%bx),%al	/* Get ascii code from the keyboard code */
	movb	%al,(bootmode)
	call	putc		/* Print out the character */
	movb	$0x08,%al	/* Print backspace */
	call	putc		/*  for the next input */
	jmp	6f
4:
	testb	$0x80,%al	/* Released? */
	jnz	5f		/*  Yes, then clear shift key */
	movb	$1,(keyboard_shift)	/* Set shift key */
	jmp	6f
5:
	movb	$0,(keyboard_shift)	/* Clear shift key */
6:
	movb	$0x20,%al	/* Notify */
	outb	%al,$0x20	/*  End-Of-Interrupt (EOI) */
	popw	%bx
	popw	%ax
	iret


/* Power off the machine using APM */
poweroff:
	/* Disable PIC */
	call	disable_pic

	/* Power off with APM */
	movw	$0x5301,%ax	/* Connect APM interface */
	movw	$0x0,%bx	/* Specify system BIOS */
	int	$0x15		/* Return error code in %ah with CF */
	jc	1f		/* Error */

	movw	$0x530e,%ax	/* Set APM version */
	movw	$0x0,%bx	/* Specify system BIOS */
	movw	$0x102,%cx	/* Version 1.2 */
	int	$0x15		/* Return error code in %ah with CF */
	jc	1f		/* Error */

	movw	$0x5308,%ax	/* Enable power management */
	movw	$0x1,%bx	/* All devices managed by the system BIOS */
	movw	$0x1,%cx	/* Enable */
	int	$0x15		/* Ignore errors */

	movw	$0x5307,%ax	/* Set power state */
	movw	$0x1,%bx	/* All devices managed by the system BIOS */
	movw	$0x3,%cx	/* Off */
	int	$0x15
1:
	ret			/* Return on error */


/* Disable i8259 PIC */
disable_pic:
	pushw	%ax
	movb	$0xff,%al
	outb	%al,$0xa1
	movb	$0xff,%al
	outb	%al,$0x21
	popw	%ax
	ret


/* Display the read error message (%ah = error code) */
read_error:
	movb	%ah,%al
	movw	$error_code,%di
	xorw	%bx,%bx
	movw	%bx,%es
	call	hex8
	movw	$msg_error,%si	/* %ds:(%si) -> error message */
	call	putstr		/* Display error message at %si and then halt */


/* Halt */
halt:
	hlt
	jmp	halt

/* Display a null-terminated string */
putstr:
putstr.load:
	lodsb			/* Load %al from %ds:(%si), then incl %si */
	testb	%al,%al		/* Stop at null */
	jnz	putstr.putc	/* Call the function to output %al */
	ret			/* Return if null is reached */
putstr.putc:
	call	putc		/* Output a character %al */
	jmp	putstr		/* Go to next character */
putc:
	pushw	%bx		/* Save %bx */
	movw	$0x7,%bx	/* %bh: Page number for text mode */
				/* %bl: Color code for graphics mode */
	movb	$0xe,%ah	/* BIOS: Put char in tty mode */
	int	$0x10		/* Call BIOS, print a character in %al */
	popw	%bx		/* Restore %bx */
	ret

/*
 * Display a null-terminated string at the bottom-line
 *   %ds:%si --> 0xb800:**
  */
putbstr:
	/* Save registers */
	pushw	%ax
	pushw	%es
	pushw	%di
	movw	$0xb800,%ax	/* Memory 0xb8000 */
	movw	%ax,%es
	movw	$(80*24*2),%di	/* 24th (zero-numbering) line */
putbstr.load:
	lodsb			/* Load %al from %ds:(%si) , then incl %si */
	testb	%al,%al		/* Stop at null */
	jnz	putbstr.putc	/* Call the function to output %al */
	/* Restore registers */
	popw	%di
	popw	%es
	popw	%ax
	ret
putbstr.putc:
	movb	$0x7,%ah
	stosw			/* Write %ax to [%di], then add 2 to %di */
	jmp     putbstr.load


/* Convert %al to hex characters, saving the result to [%di] */
hex8:
	pushw	%ax		/* Save %ax */
	shrb	$0x4,%al	/* Get most significant 4 bits in %al */
	call	hex8.allsb4	/* Convert the least significant 4 bits in */
				/*  %al to a hex character */
	popw	%ax		/* Restore %ax */
hex8.allsb4:
	andb	$0xf,%al	/* Get least significant 4 bits in %al */
	cmpb	$0xa,%al	/* CF=1 if %al < $0xa (0..9) */
	sbbb	$0x69,%al	/* %al <= %al - ($0x69 + CF) */
	das			/* BCD (N.B., %al - 0x60 if AF is not set) */
	orb	$0x20,%al	/* To lower case */
	stosb			/* Save char to %es:[%di] and inc %di */
	ret


/* Enable A20 address line */
enable_a20:
	cli
	pushw	%ax
	pushw	%cx
	xorw	%cx,%cx
1:
	incw	%cx		/* Try until %cx overflows (2^16 times) */
	jz	3f		/*  Failed to enable a20 */
	inb	$0x64,%al	/* Get status from the keyboard controller */
	testb	$0x2,%al	/* Busy? */
	jnz	1b		/* Yes, busy.  Then try again */
	movb	$0xd1,%al	/* Command: Write output port (0x60 to P2) */
	outb	%al,$0x64	/* Write the command to the command register */
2:
	inb	$0x64,%al	/* Get status from the keyboard controller */
	testb	$0x2,%al	/* Busy? */
	jnz	2b		/* Yes, busy.  Then try again */
	movb	$0xdf,%al	/* Command: Enable A20 */
	outb	%al,$0x60	/* Write to P2 via 0x60 output port */
3:
	popw	%cx
	popw	%ax
	sti
	ret


/* Read %cx sectors starting at LBA %ax on drive %dl into %es:[%bx] */
read:
	pushw	%bp		/* Save the base pointer*/
	movw	%sp,%bp		/* Copy the stack pointer to the base pointer */
	/* Save general purpose registers */
	movw	%ax,-2(%bp)
	movw	%bx,-4(%bp)
	movw	%cx,-6(%bp)
	movw	%dx,-8(%bp)
	/* Prepare space for local variables */
	/* u16 cx -10(%bp) */
	/* u16 counter -12(%bp) */
	subw	$12,%sp

	/* Reset counter */
	xorw	%ax,%ax
	movw	%ax,-12(%bp)

	/* Set number of sectors to be read */
	movw	%cx,-10(%bp)
1:
	movw	-2(%bp),%ax	/* Restore %ax */
	addw	-12(%bp),%ax	/* Current LBA */
	call	lba2chs		/* Convert LBA (%ax) to CHS (%cx,%dh) */
	call	read_sector	/* Read a sector */
	addw	$SECTOR_SIZE,%bx
	movw	-12(%bp),%ax	/* Get */
	incw	%ax		/*  and increase the current LBA %ax */
	movw	%ax,-12(%bp)	/*  then write back */
	cmpw	-10(%bp),%ax
	jb	1b		/* Need to read more sectors */

	/* Restore the saved registers */
	movw	-8(%bp),%dx
	movw	-6(%bp),%cx
	movw	-4(%bp),%bx
	movw	-2(%bp),%ax
	movw	%bp,%sp		/* Restore the stack pointer and base pointer */
	popw	%bp
	ret


/* Read one sector from CHS (specified by %dh and %cx) specified on drive %dl to
 * %es:[%bx]
 */
read_sector:
	pushw	%bp		/* Save the base pointer*/
	movw	%sp,%bp		/* Copy the stack pointer to the base pointer */
	/* Save registers */
	movw	%ax,-2(%bp)
	/* Prepare space for local variables */
	/* u16 retries -4(%bp) */
	/* u16 error -6(%bp) */
	subw	$6,%sp
	/* Reset retry counter */
	xorw	%ax,%ax
	movw	%ax,-4(%bp)
1:
	/* Read a sector from the drive */
	movb	$0x02,%ah	/* Function: Read sectors from drive */
	movb	$0x01,%al	/* # of sectors to be read */
	int	$0x13
	jnc	2f		/* Jump if success */
	movw	%ax,-6(%bp)	/* Save the return code */
	movw	-4(%bp),%ax	/* Get */
	incw	%ax		/*  and increase the number of retries */
	movw	%ax,-4(%bp)	/*  then write back */
	cmpw	$NUM_RETRIES,%ax
	movw	-6(%bp),%ax	/* Restore the return code */
	ja	read_error	/* Exceeding the maximum number of retries */
	cmpb	$ERRCODE_TIMEOUT,%ah
	je	read_error	/* Timeout */
2:
	/* Restore the saved registers */
	movw	-2(%bp),%ax
	movw	%bp,%sp		/* Restore the stack pointer and base pointer */
	popw	%bp
	ret


/* Calculate CHS (%cx[7:6]%cx[15:8] ,%dh, %cx[5:0]) from LBA (%ax) */
lba2chs:
	/* Save registers */
	pushw	%ax
	pushw	%bx
	pushw	%dx
	/* Compute sector number */
	xorw	%bx,%bx
	movw	%bx,%dx
	movw	%bx,%cx
	movb	sectors,%bl
	divw	%bx		/* %dx:%ax / %bx; %ax:quotient, %dx:remainder */
	incb	%dl		/* Sector number is one-based numbering */
	movb	%dl,%cl		/* Sector: %cx[5:0] */
	/* Compute head and track (cylinder) numbers */
	xorw	%bx,%bx
	movw	%bx,%dx
	movb	heads,%bl
	divw	%bx		/* %dx:%ax / %bx; %ax:cylinder, %dx:head */
	movb	%al,%ch		/* Cylinder[7:0]: %cx[15:8] */
	movb	%ah,%bl		/* Take the least significant two bits */
	shlb	$6,%bl		/*  from %ah, and copy to %bl[7:6] */
	orb	%bl,%cl		/* Cylinder[9:8]: %cx[7:6]*/
	movw	%dx,%bx		/* Save the remainer to %bx */
	popw	%dx		/* Restore %dx */
	movb	%bl,%dh		/* Head */
	/* Restore registers */
	popw	%bx
	popw	%ax
	ret



	.data

/* Messages */
msg_bootopt:
	.ascii	"Welcome to Academic Operating System!\r\n\n"
	.ascii	"Select one:\r\n"
	.ascii	"    1: Boot (64 bit mode)\r\n"
	.ascii	"    2: Power off\r\n"
	.asciz	"Press key:[ ]\x08\x08"
msg_countdown:
	.ascii	"AOS will boot in "
msg_count:
	.asciz	"00 sec."

msg_error:
	.ascii  "Disk read error: 0x"
error_code:
        .asciz  "00\r\r"


/* Drive information */
drive:
	.byte	0
heads:
	.byte	0
cylinders:
	.word	0
sectors:
	.byte	0


/* Saved boot mode */
bootmode:
	.byte	0

/* Counter */
counter:
	.word	0

/* Keymap (US) */
keymap_base:
	.ascii	"  1234567890-=  qwertyuiop[]  as"
	.ascii	"dfghjkl;'` \\zxcvbnm,./          "
	.ascii	"                                "
	.ascii	"                                "
keymap_shift:
	.ascii	"  !@#$%^&*()_+  QWERTYUIOP{}  AS"
	.ascii	"DFGHJKL:\"~ |ZXCVBNM<>?          "
	.ascii	"                                "
	.ascii	"                                "

/* Keybaord status */
keyboard_shift:
	.byte	0
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
/*_
 * Copyright (c) 2015 Hirochika Asai <asai@jar.jp>
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

	.text

	.code16
	.globl	entry16

/* Entry point */
entry16:
	cli

	/* Setup temporary IDT and GDT */
	lidt	(idtr)
	lgdt	(gdtr)

	/* Enter the protected mode */
	movl	%cr0,%eax
	orb	$0x1,%al		/* Enable protected mode */
	movl	%eax,%cr0

	/* Go into protected mode and flush the pipeline */
	ljmpl	$0x10,$entry32

	.data

/* Pseudo interrupt descriptor table */
idtr:
	.word	0x0
	.long	0x0

gdt:
	.word	0x0,0x0,0x0,0x0		/* Null descriptor */
	.word	0xffff,0x0,0x9a00,0xaf	/* Code64 descriptor */
	.word	0xffff,0x0,0x9a00,0xcf	/* Code32 descriptor */
	.word	0xffff,0x0,0x9a00,0x8f	/* Code16 descriptor */
	.word	0xffff,0x0,0x9200,0xcf	/* Data */
gdt.1:
/* Pseudo global descriptor table */
gdtr:
	.word	gdt.1 - gdt - 1		/* Limit */
	.long	gdt			/* Address */
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
117
118
/*_
 * Copyright (c) 2015 Hirochika Asai <asai@jar.jp>
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

	.set	KERNEL_PGT,0x00079000	/* Page table */
	.set	P_DATA_SIZE,0x10000	/* Data size for each processor */
	.set	P_DATA_BASE,0x1000000	/* Data base for each processor */
	.set	P_STACK_GUARD,0x10

	.text

	.code32
	.globl	entry32

/* Entry point */
entry32:
	cli

	/* Mask all interrupts (i8259) */
	movb	$0xff,%al
	outb	%al,$0x21
	movb	$0xff,%al
	outb	%al,$0xa1

	/* %cs is automatically set after the long jump operation */
	movl	$0x20,%eax
	movl	%eax,%ss
	movl	%eax,%ds
	movl	%eax,%es
	movl	%eax,%fs
	movl	%eax,%gs

	/* Obtain APIC ID */
	movl	$0xfee00000,%edx
	movl	0x20(%edx),%eax		/* APIC ID */
	shrl	$24,%eax
	/* P6 family and Pentium processors: [27:24] */
	/* Pentium 4 processors, Xeon processors, and later processors: [31:24] */

	/* Setup stack with 16 byte guard */
	addl	$1,%eax
	movl	$P_DATA_SIZE,%ebx
	mull	%ebx			/* [%edx|%eax] = %eax * %ebx */
	addl	$P_DATA_BASE,%eax
	subl	$P_STACK_GUARD,%eax
	movl	%eax,%esp

	/* Enable PAE */
	movl	$0x20,%eax		/* CR4[bit 5] = PAE */
	movl	%eax,%cr4

/* Create 64bit page table */
pg_setup:
	movl	$KERNEL_PGT,%ebx	/* Low 12 bit must be zero */
	movl	%ebx,%edi
	xorl	%eax,%eax
	movl	$(512*8*6/4),%ecx
	rep	stosl			/* Initialize %ecx*4 bytes from %edi */
					/*  with %eax */
	/* Level 4 page map */
	leal	0x1007(%ebx),%eax
	movl	%eax,(%ebx)
	/* Page directory pointers (PDPE) */
	leal	0x1000(%ebx),%edi
	leal	0x2007(%ebx),%eax
	movl	$4,%ecx
pg_setup.1:
	movl	%eax,(%edi)
	addl	$8,%edi
	addl	$0x1000,%eax
	loop	pg_setup.1
	/* Page directories (PDE) */
	leal	0x2000(%ebx),%edi
	movl	$0x183,%eax
	movl	$(512*4),%ecx
pg_setup.2:
	movl	%eax,(%edi)
	addl	$8,%edi
	addl	$0x00200000,%eax
	loop	pg_setup.2

	/* Set page table register */
	movl	%ebx,%cr3

	/* Enable long mode */
	movl	$0xc0000080,%ecx	/* EFER MSR number */
	rdmsr				/* Read from 64 bit-specific register */
	btsl	$8,%eax			/* LME bit = 1 */
	wrmsr

	/* Activate page translation and long mode */
	movl	$0x80000001,%eax
	movl	%eax,%cr0

	/* Load code64 descriptor */
	pushl	$0x08
	pushl	$entry64
	lret

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
/*_
 * Copyright (c) 2015 Hirochika Asai <asai@jar.jp>
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

	.text

	.code64
	.globl	entry64
	.globl	_ljmp
	.globl	_hlt

/* Entry point */
entry64:
	cli

	xorl	%eax,%eax
	movl	%eax,%ds
	movl	%eax,%es
	movl	%eax,%ss
	movl	%eax,%fs
	movl	%eax,%gs

	/* Clear screen */
	movl	$0xb8000,%edi
	movw	$0x0f20,%ax
	movl	$80*25,%ecx
	rep	stosw

	/* Reset cursor */
	movw	$0x000f,%ax	/* %al=0xf: cursor location low, %ah: xx00 */
	movw	$0x3d4,%dx
	outw	%ax,%dx
	movw	$0x000e,%ax	/* %al=0xe: cursor location high, %ah: 00xx */
	movw	$0x3d4,%dx
	outw	%ax,%dx

	/* Get into the C code */
	call	_centry

1:
	hlt
	jmp	1b

/* void ljmp(u64 selector, u64 address); */
_ljmp:
	pushq	%rdi
	pushq	%rsi
	lretq

/* void hlt(void); */
_hlt:
	hlt
	ret
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
/*_
 * Copyright (c) 2015 Hirochika Asai <asai@jar.jp>
 * All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

typedef unsigned short u16;

void hlt(void);

/*
 * Entry point for C code
 */
void
centry(void)
{
    /* Print message */
    u16 *base;
    char *msg = "Congraturations!  Welcome to the 64-bit world!";
    int offset;

    base = (u16 *)0xb8000;
    offset = 0;
    while ( msg[offset] ) {
        *(base + offset) = 0x0700 | msg[offset];
        offset++;
    }

    /* Sleep forever */
    for ( ;; ) {
        hlt();
    }
}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * End:
 * vim600: sw=4 ts=4 fdm=marker
 * vim<600: sw=4 ts=4
 */

The status register contains status flags of the keyboard controller; bit 0: Output buffer full, bit 1: Input buffer full, bit 2: System flag (cleared after a power-on reset), bit 3: Command/data (0: data byte, 1: command byte), bit 4: Inhibit switch (0: keyboard is inhibited, 1: keyboard is not inhibited), bit 5: Transmit time out (0: no transmit time out error, 1: transmit time out error), bit 6: Receive time out (0: no receive time out error, 1: receive time out error), and bit 7: Parity error (0: odd parity (no error), 1: even parity (error)).

The history of A20 is found at A20 - a pain from the past. As described above, the most classical way to enable/disable A20 is done through the output port of the 8042 (PS/2) keyboard controller. In SMSC Keyboard controller, output port is defined as follows; bit 0: System reset, bit 1: Gate A20, bit 2: Undefined, bit 3: Undefined, bit 4: Output buffer full, bit 5: Input buffer empty, bit 6: Keyboard clock (output), and bit 7: Keyboard data (output). A20 is enabled/disabled by setting/clearing the bit 1. The system reset (bit 0) must be set, otherwise the machine will be reset. As for the other bits of this port, it may not effect the system, but DFh and DDh are usually used as enable and disable commands, respectively.

In the procedure, first, the OUT instruction with the D1h command (Write Output Port) is written to the port 64h, the command register of the keyboard controller, and then DFh (all bits except input buffer empty are set) is written to the output port through 60h output port.

Basically, peripheral devices provide its I/O access through in/out instructions and/or memory mapped I/O. We have used in/out instructions to access PIC, PIT, and keyboard controller in the previous checkpoints. In this checkpoint, we use the memory mapped I/O instead of BIOS calls to display a message text on the video screen. In bootmon.s, we have setup the video mode to the 16 bit color text mode through the INT 10h BIOS call. In this mode, it displays 80x25 characters on the screen, and each character is represented in 16 bit value (8 bit attribute (foreground and background color) and 8 bit ASCII code) The physical address range from 0xb8000 to 0xb8f9f is mapped to the video screen, i.e., the top left and bottom right characters are mapped to 0xb8000 and 0xb8f9e, respectively.