File: kern.tex

package info (click to toggle)
oskit 0.97.20000202-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 58,008 kB
  • ctags: 172,612
  • sloc: ansic: 832,827; asm: 7,640; sh: 3,920; yacc: 3,664; perl: 1,457; lex: 427; makefile: 337; csh: 141; awk: 78
file content (6013 lines) | stat: -rw-r--r-- 225,154 bytes parent folder | download
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
%
% Copyright (c) 1996-1999 University of Utah and the Flux Group.
% All rights reserved.
% 
% The University of Utah grants you the right to copy and reproduce this
% document or portions thereof for academic, research, evaluation, and
% personal use only, provided that (1) the title page appears prominently,
% and (2) these copyright and permission notices are retained in all copies.
% To arrange for alternate terms, contact the University of Utah at
% csl-dist@cs.utah.edu or +1-801-585-3271.
%
\label{kern}

\section{Introduction}

The kernel support library, {\tt libkern.a},
supplies a variety of functions and other definitions
that are primarily of use in OS kernels.
(In contrast, the other parts of the \oskit{}
are more generic components useful in a variety of environments
{\em including}, but not limited to, OS kernels.)
The kernel support library contains all the code necessary
to create a minimal working ``kernel''
that boots and sets up the machine for a generic ``OS-friendly'' environment.
For example, on the x86,
the kernel support library provides code
to get into protected mode, set up default descriptor tables, etc.
The library also includes a remote debugging stub,
providing convenient source-level debugging of the kernel over a serial line
using GDB's serial-line remote debugging protocol.
As always, all components of this library are optional and replaceable,
so although some pieces may be unusable in some environments,
others should still work fine.

\subsection{Machine-dependence of code and interfaces}

This library contains a much higher percentage of machine-dependent code
than the other libraries in the toolkit,
primarily because this library deals with heavily machine-dependent facilities
such as page tables, interrupt vector tables, trap handling, etc.
The library attempts to hide {\em some} machine-dependent details from the OS
by providing generic, machine-independent interfaces
to machine-dependent library code.
For example, regardless of the architecture and boot loading mechanism in use,
the kernel startup code included in the library
always sets up a generic C-compatible execution environment
and starts the kernel by calling the well-known {\tt main} routine,
just as in ordinary C programs.
However, the library makes no attempt to provide
a complete architecture-independence layer,
since such a layer would have to make too many assumptions
about the OS that is using it.
For example, although the library provides page table management routines,
these routines have fairly low-level, architecture-specific interfaces.

\subsection{Generic versus Base Environment code}

The functionality provided by the kernel support library
is divided into two main classes:
the generic support code, and the {\em base environment}.
The generic support contains simple routines and definitions
that are almost completely independent
of the particular OS environment in which they are used:
for example, the generic support includes
symbolic definitions for bits in processor registers and page tables,
C wrapper functions to access special-purpose processor registers, etc.
The generic support code should be usable in any OS that needs it.

The base environment code, on the other hand,
is somewhat less generic
in that it is designed to create, and function in,
a well-defined default or ``base'' kernel execution environment.
Out of necessity, this code makes more assumptions about how it is used,
and therefore it is more likely that parts of it
will not be usable to a particular client OS.
For example, on the x86 architecture,
the base environment code sets up a default global descriptor table
containing a ``standard'' set of basic, flat-model segment descriptors,
as well as a few extra slots reserved for use by the client OS.
This ``base GDT'' is likely to be sufficient for many kernels,
but may not be usable to kernels
that make more exotic uses of the processor's GDT.
In order to allow piecemeal replacement of the base environment as necessary,
the assumptions made by the code and the intermodule dependencies
are clearly documented in the sections covering the base environment code.

\subsection{Road Map}

Following is a brief summary of the main facilities provided by the library,
indexed by the section numbers of the sections describing each facility:
\begin{itemize}
\item[\ref{kern-mi-facil}]
	{\bf Machine-independent Facilities:}
	Types and constants describing machine-dependent information
	such as word size and page size.
	%XXX how about byte order.
	For example, types are provided which, if used properly,
	allow machine-independent code
	to compile easily on both 32-bit and 64-bit architectures.
	Also, functions are provided for various generic operations
	such as primitive multiprocessor synchronization
	and efficient bit field manipulation.
\item[\ref{kern-x86-generic}]
	{\bf\intel\ Generic Low-level Definitions:}
	Header files describing x86 processor data structures and registers,
	as well as functions to access and manipulate them.
	Includes:
	\begin{itemize}
	\item	Bit definitions of the contents of the flags,
		control, debug, and floating point registers.
	\item	Inline functions and macros to read and write
		the flags, control, debug, segment registers,
		and descriptor registers (IDTR, GDTR, LDTR, TR).
		%XXX how about MSRs and PM counters
	\item	Macros to read the Pentium timestamp counter
		(useful for fine-grained timing and benchmarking)
		and the stack pointer.
	\item	Structure definitions for architectural data structures
		such as far pointers, segment and gate descriptors,
		task state structures, floating point save areas,
		and page tables,
		as well as generic functions to set up these structures.
	\item	Symbolic definitions of the processor trap vectors.
	\item	Macros to access I/O ports
		using the x86's {\tt in} and {\tt out} instructions.
	\item	Assembly language support macros
		to smooth over the differences in target object formats,
		such as ELF versus {\tt a.out}.
	\end{itemize}
\item[\ref{kern-x86pc-generic}]
	{\bf\intelpc\ Generic Low-level Definitions:}
	Generic definitions for standard parts of the PC architecture,
	such as IRQ assignments, the programmable interrupt controller (PIC),
	and the keyboard controller.
\item[\ref{kern-x86-procman}]
	{\bf\intel\ Processor Identification and Management:}
	Functions to identify the CPU and available features,
	to enter and leave protected mode,
	and to enable and disable paging.
\item[\ref{kern-x86-base-firstsection}--\ref{kern-x86-base-lastsection}]
	{\bf\intel\ Base Environment Setup:}
	Functions that can be used individually or as a unit
	to set up a basic, minimal kernel execution environment
	on x86 processors:
	e.g., a minimal GDT, IDT, TSS, and kernel page tables.
\item[\ref{kern-x86pc-base-firstsection}--\ref{kern-x86pc-base-lastsection}]
	{\bf\intelpc\ Base Environment Setup:}
	Functions to set up a PC's programmable interrupt controller (PIC)
	and standard IRQ vectors,
	to manage a PC's low (1MB), middle (16MB) and upper memory,
	and to provide simple non-interrupt-driven console support.
\item[\ref{kern-x86pc-multiboot}]
	{\bf\intelpc\ MultiBoot Startup:}
	Complete startup code to allow the kernel to be booted
	from any MultiBoot-compliant boot loader easily.
	Includes code to parse options and environment variables
	passed to the kernel by the boot loader,
	and to find and use {\em boot modules} loaded with the kernel.
\item[\ref{kern-x86pc-biosboot}]
	{\bf\intelpc\ Raw BIOS Startup:}
	Complete startup code for boot loaders and other programs
	that need to be loaded directly by the BIOS at boot time.
	This startup code takes care of all aspects
	of switching from real to protected mode
	and setting up a 32-bit environment,
	and provides mechanisms to call back to 16-bit BIOS code
	by running the BIOS in either real mode or v86 mode (your choice).
\item[\ref{kern-x86pc-dosboot}]
	{\bf\intelpc\ DOS Startup:}
	This startup code is similar to the BIOS startup code,
	but it expects to be loaded in a 16-bit DOS environment:
	useful for DOS-based boot loaders, DOS extenders,
	or prototype kernels that run under DOS.
	Again, this code fully handles mode switching
	and provides DOS/BIOS callback mechanisms.
\item[\ref{gdb}]
	{\bf Kernel Debugging Facilities:}
	A generic, machine-independent remote GDB stub is provided
	which supports the standard serial-line GDB protocol.
	In addition, machine-dependent default trap handling
	and fault-safe memory access code is provided
	to allow the debugging stub to be used ``out of the box'' on x86 PCs.
\item[\ref{kern-anno}]
	{\bf Kernel Annotation Facility:}
	Macros and functions to associate additional information with ranges
	of kernel text or data.
	Annotations allow, for example, a kernel to mark a range of kernel
	text so that a special function is invoked whenever an exception
	or interrupt occurs within that range.
	This facility is useful for implementing rollback routines.
\end{itemize}

%XXX explain i16_ prefix and 16-bit code

%XXX document which header files can be included in assembly code

\apisec{Machine-independent Facilities}
\label{kern-mi-facil}

This section includes machine-independent types, constants, macros, and
functions that every supported architecture provides.
These are used extensively within the \oskit{} itself as well as by the
applications built on the \oskit{}.

\com{
XXX described back in intf.tex
\api{types.h}{C-language machine-dependent types}
\begin{apisyn}
	\cinclude{oskit/machine/types.h}
\end{apisyn}
\begin{apidesc}
	This header provides a number of C types
	that hide differences in word size and language conventions
	across different architectures and compilers.
	For example, by making proper use of these types,
	machine-independent code can be made
	to work cleanly on both 32- and 64-bit architectures.

	The following types are defined
	as integers of the same size as a pointer,
	which is also assumed to be the machine's natural word size.
	These types should be used by machine-independent code
	that manipulates pointers as integers
	or is otherwise dependent on the architectural pointer size.
	Note that on architectures that have both 32-bit and 64-bit variants,
	such as PowerPC and {\sc pa-risc},
	these types may have different sizes
	depending on the configuration of the \oskit{}.
	\begin{icsymlist}
	\item[oskit_addr_t]	An unsigned offset into virtual memory space.
	\item[oskit_size_t]	An unsigned size in virtual memory space, e.g.,
				a difference between two {\tt oskit_addr_t}'s.
	\item[oskit_ssize_t]	A signed size in virtual memory space.
	\item[oskit_reg_t]	An unsigned integer the same size as a processor register.
	\item[oskit_sreg_t]	A signed integer the same size as a processor register.
	\end{icsymlist}

	The following types are defined to be {\em exactly}
	of the size and variety their names imply,
	regardless of processor architecture or compiler:
	\begin{icsymlist}
	\item[oskit_s8_t]	A signed 8-bit integer.
	\item[oskit_s16_t]	A signed 16-bit integer.
	\item[oskit_s32_t]	A signed 32-bit integer.
	\item[oskit_s64_t]	A signed 64-bit integer.
	\item[oskit_u8_t]	An unsigned 8-bit integer.
	\item[oskit_u16_t]	An unsigned 16-bit integer.
	\item[oskit_u32_t]	An unsigned 32-bit integer.
	\item[oskit_u64_t]	An unsigned 64-bit integer.
	\item[oskit_f32_t]	A 32-bit floating point number.
	\item[oskit_f64_t]	A 64-bit floating point number.
	%XXX 128-bit float?
	\end{icsymlist}

	This file was originally derived from Mach's {\tt vm_types.h}.
\end{apidesc}
}

\api{page.h}{Page size definitions}
\label{page-h}
\begin{apisyn}
	\cinclude{oskit/machine/page.h}
\end{apisyn}
\begin{apidesc}
	This file provides of following symbols,
	which define the architectural page size
	of the architecture for which the \oskit{} is configured:
	\begin{icsymlist}
	\item[PAGE_SIZE]
		The number of bytes on each page.
		It can always be assumed to be a power of two.
	\item[PAGE_SHIFT]
		The number of low address bits {\em not} translated
		by the MMU hardware.
		{\tt PAGE_SIZE} is always $2^{\tt PAGE_SHIFT}$.
	\item[PAGE_MASK]
		A bit mask with the low-order {\tt PAGE_SHIFT} address bits set.
		Always equal to ${\tt PAGE_SIZE}-1$.  {\bf WARNING}:
		Some systems (like linux) define this to be
		${\tt ~\tilde{}~(PAGE_SIZE - 1)}$, be careful that the
		definitions match what the code expects!
	\end{icsymlist}

	In addition, the following macros are provided
	for convenience in performing page-related manipulations of addresses:
	\begin{csymlist}
	\item[atop({\em addr})]		\ttindex{atop}
		Converts a byte address into a page frame number,
		by dividing by {\tt PAGE_SIZE}.
	\item[ptoa({\em page})]		\ttindex{ptoa}
		Converts a page frame number
		into an integer ({\tt oskit_addr_t}) byte address,
		by multiplying by {\tt PAGE_SIZE}.
	\item[round_page({\em addr})]	\ttindex{round_page}
		Returns {\em addr} rounded up to the next higher page boundary.
		If {\em addr} is already on a page boundary,
		it is returned unchanged.
	\item[trunc_page({\em addr})]	\ttindex{trunc_page}
		Returns {\em addr} rounded down to the next lower page boundary.
		If {\em addr} is already on a page boundary,
		it is returned unchanged.
	\item[page_aligned({\em addr})]	\ttindex{page_aligned}
		Evaluates to true (nonzero) if {\em addr} is page aligned,
		or false (zero) if it isn't.
	\end{csymlist}

	Note that many modern architectures support multiple page sizes.
	On such architectures, the page size defined in this file
	is the {\em minimum} architectural page size,
	i.e., the finest granularity over which the MMU has control.
	Since there seems to be no sufficiently generic and useful way
	that this header file could provide symbols
	indicating which ``other'' page sizes the architecture supports,
	making good use of larger pages probably must be done
	in machine-dependent code.

	%XXX maybe _could_ describe superpages too...

	Some operating systems on some architectures
	do not actually support the minimum architectural page size in software;
	instead, they aggregate multiple architectural pages together
	into larger ``logical pages'' managed by the OS software.
	On such operating systems,
	it would be inappropriate for general OS or application code
	to use the {\tt PAGE_SIZE} value provided by {\tt oskit/page.h},
	since this value would be smaller (more fine-grained)
	than the OS software actually supports, and therefore inappropriate.
	However, this is purely a high-level OS issue;
	like other parts of the toolkit,
	no one is required to use this header file
	if it is inappropriate in a particular situation.

	This file was originally derived from Mach's {\tt vm_param.h}.
\end{apidesc}

\com{
XXX There is no proc_ops.h!
\api{bitops.h}{efficient bit field operations}
\begin{apisyn}
	\cinclude{oskit/bitops.h}
\end{apisyn}
\begin{apidesc}
	XXX currently proc_ops.h
\end{apidesc}
}

\api{spin_lock.h}{Spin locks}
\begin{apisyn}
	\cinclude{oskit/machine/spin_lock.h}
\end{apisyn}
\begin{apidesc}
	This file provides the architecture-dependent definition of the
	{\tt spin_lock_t} ``spin lock'' data type and
	associated manipulation macros.
	This facility provides a basic locking mechanism which can be
	used with preemptive threading or on a multi-processor.

	\begin{csymlist}
	\item[spin_lock_t]	\ttindex{spin_lock_t}
		Typedef for the spin lock data type.
	\item[spin_lock_init({\em s})]	\ttindex{spin_lock_init}
		Initialize a spin lock.
%		This sets the spin-lock to the SPIN_LOCK_INITIALIZER value.
	\item[spin_lock_locked({\em s})] \ttindex{spin_lock_locked}
		Check if a spin lock is locked.
	\item[spin_unlock({\em s})]	\ttindex{spin_unlock}
		Unlock a spin lock.
	\item[spin_try_lock({\em s})] 	\ttindex{spin_try_lock}
		Attempt to lock a spin lock.  Returns 0 if successful,
		nonzero if unsuccessful.
	\item[spin_lock({\em s})]	\ttindex{spin_lock}
		Busy wait until the lock is free.  On return the lock
		has been acquired.
	\end{csymlist}

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

%XXX inline.h

\api{queue.h}{Generic queues}
\begin{apisyn}
	\cinclude{oskit/queue.h}

	\cstruct{queue_entry}{
		struct queue_entry	*next;		/* next element */
		struct queue_entry	*prev;		/* previous element */
	};

	{\tt typedef struct queue_entry *\csymbol{queue_t};}\\
	{\tt typedef struct queue_entry \csymbol{queue_head_t};}\\
	{\tt typedef struct queue_entry \csymbol{queue_chain_t};}\\
	{\tt typedef struct queue_entry *\csymbol{queue_entry_t};}
\end{apisyn}
\begin{apidesc}
	Macros and structures for implementation of a ``queue'' data type.
	The implementation uses a doubly-linked list and supports
	operations to insert and delete anywhere in the list.

	\begin{csymlist}
	\item[queue_init({\em q})]	\ttindex{queue_init}
		Initialize the given queue.
	\item[queue_first({\em q})]	\ttindex{queue_first}
		Returns the first entry in the queue.
	\item[queue_next({\em q})]	\ttindex{queue_next}
		Returns the entry after an item in the queue.
	\item[queue_last({\em q})]	\ttindex{queue_last}
		Returns the last entry in the queue.
	\item[queue_prev({\em q})]	\ttindex{queue_prev}
		Returns the entry before an item in the queue.
	\item[queue_end({\em q, qe})]	\ttindex{queue_end}
		Tests whether a new entry is really the end of the queue.
	\item[queue_empty({\em q})]	\ttindex{queue_empty}
		Tests whether a queue is empty.
	\item[queue_enter({\em q, elt, type, field})]	\ttindex{queue_enter}
		Insert a new element at the tail of the queue.
	\item[queue_enter_first({\em head, elt, type, field})]
		\ttindex{queue_enter_first}
		Insert a new element at the head of the queue.
	\item[queue_enter_before({\em head, nelt, elt, type, field})]
		\ttindex{queue_enter_before}
		Insert a new element before the indicated element.
	\item[queue_enter_after({\em head, pelt, elt, type, field})]
		\ttindex{queue_enter_after}
		Insert a new element after the indicated element.
	\item[queue_remove({\em head, elt, type, field})]
		\ttindex{queue_remove}
		Remove an arbitrary item from the queue.
	\item[queue_remove_first({\em head, entry, type, field})]
		\ttindex{queue_remove_first}
		Remove and return the entry at the head of the queue.
	\item[queue_remove_last({\em head, entry, type, field})]
		\ttindex{queue_remove_last}
		Remove and return the entry at the tail of the queue.
	\item[queue_assign({\em to, from, type, field})]
		\ttindex{queue_assign}
		Move an element in a queue to a new piece of memory.
	\item[queue_iterate({\em head, elt, type, field})]
		\ttindex{queue_iterate}
		Iterate over each item in the queue.  Generates a
		'for' loop, setting elt to each item in turn (by
		reference).
	\end{csymlist}

	This header file is taken from CMU's Mach kernel.
\end{apidesc}


\api{debug.h}{debugging support facilities}
\begin{apisyn}
	\cinclude{oskit/debug.h}

\end{apisyn}
\begin{apidesc}
	This file contains simple macros and functions to assist in
	debugging.  Many of these facilities
	are intended to be used to ``annotate'' programs
	permanently or semi-permanently in ways that reflect
	the code's proper or desired behavior.
	These facilities typically change their behavior
	depending on whether the preprocessor symbol {\tt DEBUG} is defined:
	if it is defined, then extra code is introduced
	to check invariants and such;
	when {\tt DEBUG} is not defined,
	all of this debugging code is ``compiled out''
	so that it does not result in any size increase or efficiency loss
	in the resulting compiled code.

	The following macros and functions
	are intended to be used as permanent- or semi-permanent annotations
	to be sprinkled throughout ordinary code to increase its robustness
	and clarify its invariants and assumptions to human readers:
	\begin{csymlist}
	\com{
	\item[void panic(const~char *fmt, ...)]
		Panic.  Prints arguments as a printf() style message.
	Note: don't define panic() here, because it's a C library function;
	the prototype in debug.h is just to avoid cross-inclusion.
	(debug.h is included by practically everything;
	therefore its dependencies on other headers should be minimized.)
	}
	\item[assert({\em cond})]	\ttindex{assert}
		This is a standard {\tt assert} macro,
		like (and compatible with) the one provided
		in {\tt oskit/c/assert.h}.
		If {\tt DEBUG} is defined,
		this macro produces code that evaluates {\em cond}
		and calls {\tt panic} (see Section~\ref{panic})
		if the result is false (zero).
		When an assertion fails and causes a panic,
		the resulting message
		includes the source file name and line number
		of the assertion that failed,
		as well as the text of the {\em cond} expression
		used in the assertion.
		If {\tt DEBUG} is not defined,
		this macro evaluates to nothing (an empty statement),
		generating no code.

		Assertions are typically used
		to codify assumptions made by a code sequence,
		e.g., about the parameters to a function
		or the conditions on entry to or exit from a loop.
		By placing explicit {\tt assert} statements
		in well-chosen locations to verify
		that the code's invariants indeed hold,
		a thicker ``safety net'' is woven into the code,
		which tends to make bugs manifest themselves
		earlier and in much more obvious ways,
		rather than allowing incorrect results to ``trickle''
		through the program's execution for a long time,
		sometimes resulting in completely baffling behavior.
		Assertions can also act as a form of documentation,
		clearly describing to human readers
		the exact requirements and assumptions in a piece of code.
	\item[otsan()]			\ttindex{otsan}
		If {\tt DEBUG} is defined,
		this macro unconditionally causes a {\tt panic}
		with the message ``off the straight and narrow!,''
		along with the source file name and line number,
		if it is ever executed.
		It is intended to be placed at code locations
		that should never be reached
		if the code is functioning properly;
		e.g., as the {\tt default} case of a {\tt switch} statement
		for which the result of the conditional expression
		should {\em always} match one of the explicit case values.
		If {\tt DEBUG} is not defined,
		this macro evaluates to nothing.

\com{		XXX It would be even better
		if this could trigger a hint to the compiler
		``asserting'' that this code location is never reached,
		so don't bother generating code for it.
}%com
	\item[do_debug({\em stmt})]	\ttindex{do_debug}
		If {\tt DEBUG} is defined,
		this macro evaluates to {\em stmt};
		otherwise it evaluates to nothing.
		This macro is useful in situations
		where an {\tt \#ifdef DEBUG} $\dots$ {\tt \#endif} block
		would otherwise be used over just a few lines of code
		or a single statement:
		it produces the same effect,
		but is smaller and less visually intrusive.
	\end{csymlist}

	The following macros and functions
	are primarily intended to be used as temporary scaffolding
	during debugging, and removed from production code:
	\begin{csymlist}
	\item[void dump_stack_trace(void)]	\ttindex{dump_stack_trace}
		This function dumps a human-readable backtrace
		of the current function call stack
		to the console, using {\tt printf}.
		The exact content and format of the printed data
		is architecture-specific;
		however, the output is typically a list of
		instruction pointer or program counter values,
		each pointing into a function on the call stack,
		presumably to the return point
		after the function call to the next level.
		You can find out what function these addresses reside in
		by running the Unix {\tt nm} utility
		on the appropriate executable file image,
		sorting the resulting symbol list if necessary,
		and looking up the address in the sorted list.
		Alternatively, for more precise details,
		you can look up the exact instruction addresses
		in a disassembly of the executable file,
		e.g., by using GNU {\tt objdump} with the `{\tt -d}' option.
	\item[here()]				\ttindex{here}
		This macro generates code
		that simply prints the source file name and line number
		at which the macro was used.
		This macro can be extremely useful
		when trying to nail down the precise time or code location
		at which a particular bug manifests itself,
		or to determine the sequence of events leading up to it.
		By sprinkling around calls to the {\tt here} macro
		in appropriate places,
		the program will dump regular status reports of its location
		every time it hits one of these macros,
		effectively producing a log of ``interesting'' events
		(``interesting'' being defined according to
		the placement of the {\tt here} macro invocations).
		Using the {\tt here} macro this way
		is equivalent to the common practice
		of sprinkling {\tt printf}'s around and watching the output,
		except it is easier because the {\tt here} invocation
		in each place does not have to be ``tailored''
		to make it distinguishable from the other locations:
		each use of the {\tt here} macro is self-identifying.

		If {\tt DEBUG} is not defined,
		the {\tt here} macro is not defined at all;
		this makes it obvious when you've accidentally
		left invocations of this macro in a piece of code
		after it has been debugged.

	\item[debugmsg({\em printfargs})]	\ttindex{debugmsg}
		This macro is similar to {\tt here},
		except it allows a formatted message to be printed
		along with the source file name and line number.
		{\em printfargs} is a complete set of arguments
		to be passed to the {\tt printf} function,
		including parentheses: for example,
		`{\tt debugmsg(("foo is \%d", foo));}'.
		A newline is automatically appended
		to the end of the message.
		This macro is generally useful as a wrapper for {\tt printf}
		for printing temporary run-time status messages
		during execution of a program being debugged.

		As with {\tt here}, if {\tt DEBUG} is not defined,
		the {\tt debugmsg} macro is not defined at all,
		in order to make it obvious if any invocations
		are accidentally left in production code.
	\end{csymlist}

	Note that only {\tt panic} and {\tt dump_stack_trace}
	are real functions; the others are simply macros.

	%XXX struct_id stuff
\end{apidesc}

\api{base_critical}{simple critical section support}
\label{base-critical-h}
\label{base-critical-enter}
\label{base-critical-leave}
\begin{apisyn}
	\cinclude{oskit/base_critical.h}

	\funcproto void base_critical_enter(void);

	\funcproto void base_critical_leave(void);
\end{apisyn}
\begin{apidesc}
	Functions to implements a simple ``global critical region.''
	These functions are used throughout the \oskit{} to ensure
	proper serialization for various ``touchy'' but non-performance
	critical activities such as panicing, rebooting, debugging, etc.
	This critical region can safely be entered recursively;
	the only requirement is that {\tt enter}s match exactly
	with {\tt leave}s.

	The implementation of this module is machine-dependent,
	and generally disables interrupts and, on multiprocessors,
	grabs a recursive spin lock.
\end{apidesc}


\apisec{\intel\ Generic Low-level Definitions}
\label{kern-x86-generic}

This section covers useful macros, definitions, and routines that are
specific to the Intel x86 processor architecture
but that are independent of the interrupt control, bus structure, and
other ancillary functions traditionally associated with a ``PC.''
Those facilities are covered in section~\ref{kern-x86pc-generic}.

\com{
Template!
\api{.h}{}
\begin{apisym}
	\cinclude{oskit/.h}
\end{apisym}
\begin{apidesc}
	XXX This hasn't been written yet.
\end{apidesc}
}


\api{asm.h}{assembly language support macros}
\begin{apisyn}
	\cinclude{oskit/x86/asm.h}
\end{apisyn}
\begin{apidesc}
	This file contains convenience macros
	useful when writing x86 assembly language code in AT\&T/GAS syntax.
	This header file is directly derived from Mach,
	and similar headers are used in various BSD kernels.

	\paragraph{Symbol name extension:}
	The following macros allow assembly language code to be written
	that coexists with C code compiled for either ELF or {\tt a.out} format.
	In {\tt a.out} format,
	by convention an underscore ({\tt _}) is prefixed
	to each public symbol referenced or defined by the C compiler;
	however, the underscore prefix is not used in ELF format.
	\begin{csymlist}
	\item[EXT({\em name})]		\ttindex{EXT}
		Evaluates to {\tt _{\em name}} in {\tt a.out} format,
		or just {\tt\em name} in ELF.
		This macro is typically used
		when referring to public symbols defined in C code.
	\item[LEXT({\em name})]		\ttindex{LEXT}
		Evaluates to {\tt _{\em name}:} in {\tt a.out} format,
		or {\tt {\em name}:} in ELF.
		This macro is generally used
		when defining labels to be exported to C code.
	\item[SEXT({\em name})]		\ttindex{SEXT}
		Evaluates to the string literal
		{\tt "_{\em name}"} in {\tt a.out} format,
		or {\tt "{\em name}"} in ELF.
		This macro can be used in GCC inline assembly code,
		where the code is contained in a string constant;
		for example:
		{\tt asm("...; call "SEXT(foo)"; ...");}
	\end{csymlist}

	\paragraph{Alignment:}
	The following macros relate to alignment of code and data:
	\begin{csymlist}
	\item[TEXT_ALIGN]		\ttindex{TEXT_ALIGN}
		Evaluates to the preferred alignment of instruction entrypoints
		(e.g., functions or branch targets),
		as a power of two.
		Currently evaluates to 4 (16-byte alignment)
		if the symbol {\tt i486} is defined,
		or 2 (4-byte alignment) otherwise.
	\item[ALIGN]			\ttindex{ALIGN}
		A synonym for {\tt TEXT_ALIGN}.
	\item[DATA_ALIGN]		\ttindex{DATA_ALIGN}
		Evaluates to the preferred minimum alignment of data structures.
		Currently it is always defined as 2,
		although in some cases a larger value may be preferable,
		such as the processor's cache line size.
	\item[P2ALIGN({\em alignment})]	\ttindex{P2ALIGN}
		Assembly language code can use this macro
		to work around the fact that the {\tt .align} directive
		works differently in different x86 environments:
		sometimes {\tt .align} takes a byte count,
		whereas other times it takes a power of two (bit count).
		The {\tt P2ALIGN} macro {\em always} takes a power of two:
		for example, {\tt P2ALIGN(2)} means 4-byte alignment.
		By default, the {\tt P2ALIGN} macro
		uses the {\tt .p2align} directive supported by GAS;
		if a different assembler is being used,
		then {\tt P2ALIGN} should be redefined as
		either {\tt .align {\em alignment}}
		or {\tt .align 1<<({\em alignment})},
		depending on the assembler's interpretation of {\tt .align}.
	\end{csymlist}

	XXX S_ARG, B_ARG, frame stuff, ...

	XXX need to make the macros more easily overridable, using ifdefs.

	XXX need to clean out old trash still in the header file

        XXX IODELAY macro
\end{apidesc}

\api{eflags.h}{Processor flags register definitions}
\begin{apisyn}
	\cinclude{oskit/x86/eflags.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This header file can be used in assembly language code as well as C.
	The flags defined here correspond the the ones in the processor
	databooks.

	\begin{icsymlist}
	\item [EFL_CF]
		carry
	\item [EFL_PF]
		parity of low 8 bits
	\item [EFL_AF]
		carry out of bit 3
	\item [EFL_ZF]
		zero
	\item [EFL_SF]
		sign
	\item [EFL_TF]
		trace trap
	\item [EFL_IF]
		interrupt enable
	\item [EFL_DF]
		direction
	\item [EFL_OF]
		overflow
	\item [EFL_IOPL]
		IO privilege level mask.
		All 0's is the same as EFL_IOPL_KERNEL,
		while all 1's (or just EFL_IOPL) is the same as EFL_IOPL_USER.
	\item [EFL_NT]
		nested task
	\item [EFL_RF]
		resume without tracing
	\item [EFL_VM]
		virtual 8086 mode
	\item [EFL_AC]
		alignment check
	\item [EFL_VIF]
		virtual interrupt flag
	\item [EFL_VIP]
		virtual interrupt pending
	\item [EFL_ID]
		CPUID instruction support
	\end{icsymlist}
\end{apidesc}

\api{proc_reg.h}{Processor register definitions and accessor functions}
\begin{apisyn}
	\cinclude{oskit/x86/proc_reg.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This header file contains the definitions for the processor's
	control registers (CR0, CR4).
	It also contains macros for getting and setting the
	processor registers and flags.
	There is also a macro for reading the processor's
	cycle counter (on Pentium and above processors).

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

\api{debug_reg.h}{Debug register definitions and accessor functions}
\begin{apisyn}
	\cinclude{oskit/x86/debug_reg.h}
\end{apisyn}
\begin{apidesc}
	This provides the definitions for the processor's built-in
	debug registers.  There are also inline functions that allow
	the hardware-assisted breakpoints to be set.

	DR0 through DR3 are the breakpoint address registers;
	DR6 is the status register, and DR7 is the control register.

	\begin{csymlist}
	\item[get_dr0()]
		\ttindex{get_dr0}
		Returns the value in breakpoint address register 0.
	\item[get_dr1()]
		\ttindex{get_dr1}
		Returns the value in breakpoint address register 1.
	\item[get_dr2()]
		\ttindex{get_dr2}
		Returns the value in breakpoint address register 2.
	\item[get_dr3()]
		\ttindex{get_dr3}
		Returns the value in breakpoint address register 3.
	\item[get_dr6()]
		\ttindex{get_dr6}
		Returns the value in the debug status register.
	\item[get_dr7()]
		\ttindex{get_dr7}
		Returns the value in the debug control register.

	\item[set_dr0({\em val})]
		\ttindex{set_dr0}
		Sets the value in breakpoint address register 0 to {\em val}.
	\item[set_dr1({\em val})]
		\ttindex{set_dr1}
		Sets the value in breakpoint address register 1 to {\em val}.
	\item[set_dr2({\em val})]
		\ttindex{set_dr2}
		Sets the value in breakpoint address register 2 to {\em val}.
	\item[set_dr3({\em val})]
		\ttindex{set_dr3}
		Sets the value in breakpoint address register 3 to {\em val}.
	\item[set_dr6({\em val})]
		\ttindex{set_dr6}
		Sets the value in the debug status register to {\em val}.
	\item[set_dr7({\em val})]
		\ttindex{set_dr7}
		Sets the value in the debug control register to {\em val}.

	\item[set_b0({\em unsigned addr, unsigned len, unsigned rw})]
		\ttindex{set_b0}
		Enables breakpoint register 0.
		Sets {\tt dr0} to LINEAR address {\em addr}
		and updates {\tt dr7} to enable it.
		{\em rw} must be DR7_RW_INST, DR7_RW_WRITE, DR7_RW_IO,
		or DR7_RW_DATA indicating the condition to break on.
		{\em len} must be DR7_LEN_1, DR7_LEN_2, or DR7_LEN_4,
		indicating how many bytes are covered by the register.
	\item[set_b1({\em unsigned addr, unsigned len, unsigned rw})]
		\ttindex{set_b1}
		Enables breakpoint register 1.
	\item[set_b2({\em unsigned addr, unsigned len, unsigned rw})]
		\ttindex{set_b2}
		Enables breakpoint register 2.
	\item[set_b3({\em unsigned addr, unsigned len, unsigned rw})]
		\ttindex{set_b3}
		Enables breakpoint register 3.
	\end{csymlist}
\end{apidesc}

\api{fp_reg.h}{Floating point register definitions and accessor functions}
\begin{apisyn}
	\cinclude{oskit/x86/fp_reg.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This file contains the structure definition for saving the
	floating-point state and then restoring it.
	It also contains definitions for the x87 control and status
	registers.

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

\api{far_ptr.h}{Far (segment:offset) pointers}
\begin{apisyn}
	\cinclude{oskit/x86/far_ptr.h}
\end{apisyn}
\begin{apidesc}
	This contains struct definitions for creating ``far pointers.''
	Far pointers on the x86 are those that take an explicit
	segment in addition to the offset value.

	\begin{csymlist}
	\item[struct far_pointer_16]
		\ttindex{far_pointer_16}
		16-bit pointer structure which
		contains a 16-bit segment and a 16-bit offset.
		The address is computed as segment << 4 + offset.

	\item[struct far_pointer_32]
		\ttindex{far_pointer_32}
		48-bit pointer which contains
		a 32-bit offset and a 16-bit segment descriptor.
		Segmentation is used to determine what linear address
		is generated by these pointers.
	\end{csymlist}
\end{apidesc}

\api{pio.h}{Programmed I/O functions}
\begin{apisyn}
	\cinclude{oskit/x86/pio.h}
\end{apisyn}
\begin{apidesc}
	These are macros for accessing IO-space directly on the
	x86.  These instructions will generate traps if executed
	in user-mode without permissions (either IOPL in the eflags
	register or access via the io-bitmap in the tss).

	\begin{csymlist}
	\item[iodelay()]	\ttindex{iodelay}
		A macro used to delay the processor for a short period
		of time, generally to wait until programmed io can complete.
		The actual amount of time is indeterminate, since the delay is
		accomplished by doing an {\tt inb} from a nonexistent port,
		which depends on the processor and chipset.
		\footnote{
			The port used is 0x80, which was the
			page register for DMA channel 0
			on the PC and PC/XT (A16-A19).
			The PC/AT and newer computers use port
			0x87 for A16-A23 instead.
		}
		The nominal delay value is 1uS for most machines.

	\item[inl({\em port})]	\label{inl}\ttindex{inl}
		Returns 32-bit value from {\em port}
	\item[inw({\em port})]	\label{inw}\ttindex{inw}
		Returns 16-bit value from {\em port}
	\item[inb({\em port})]	\label{inb}\ttindex{inb}
		Returns 8-bit value from {\em port}

	\item[inl_p({\em port})]	\label{inl-p}\ttindex{inl_p}
		{\em inl} followed immediately by {\em iodelay}
	\item[inw_p({\em port})]	\label{inw-p}\ttindex{inw_p}
		{\em inw} followed immediately by {\em iodelay}
	\item[inb_p({\em port})]	\label{inb-p}\ttindex{inb_p}
		{\em inb} followed immediately by {\em iodelay}

	\item[outl({\em port}, {\em val})]	\label{outl}\ttindex{outl}
		Send 32-bit {\em val} out {\em port}.
	\item[outw({\em port}, {\em val})]	\label{outw}\ttindex{outw}
		Send 16-bit {\em val} out {\em port}.
	\item[outb({\em port}, {\em val})]	\label{outb}\ttindex{outb}
		Send 8-bit {\em val} out {\em port}.

	\item[outl_p({\em port})]	\label{outl-p}\ttindex{outl_p}
		{\em outl} followed immediately by {\em iodelay}
	\item[outw_p({\em port})]	\label{outw-p}\ttindex{outw_p}
		{\em outw} followed immediately by {\em iodelay}
	\item[outb_p({\em port})]	\label{outb-p}\ttindex{outb_p}
		{\em outb} followed immediately by {\em iodelay}
	\end{csymlist}

	The above macros have versions that begin with {\em i16_},
	which are defined to be the same.
	It may be desirable to use the i16_ versions in 16-bit code
	in place of the normal macros for clarity.

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

\api{seg.h}{Segment descriptor data structure definitions and constants}
\label{seg-h}
\begin{apisyn}
	\cinclude{oskit/x86/seg.h}
\end{apisyn}
\begin{apidesc}
	XXX

	\begin{csymlist}
	\item[struct x86_desc]
		\ttindex{x86_desc}
		Normal segment descriptors.
	\item[struct x86_gate]
		\ttindex{x86_gate}
		Trap, interrupt, and call gates.
	\item[struct pseudo_descriptor]
		\ttindex{pseudo_descriptor}
		Used to load the IDT and GDT (and LDT).
	\item[sel_idx(sel)]
		\ttindex{sel_idx}
		Converts the selector into an index in the descriptor table.
	\item[ISPL(s)]
		\ttindex{ISPL}
		Returns the selector's privilege level.
	\item[USERMODE(s, f)]
		\ttindex{USERMODE}
	\item[KERNELMODE(s, f)]
		\ttindex{KERNELMODE}
	\item[fill_descriptor(struct x86_desc *desc, unsigned base,
		unsigned limit, unsigned char access, unsigned char sizebits)]
		\ttindex{fill_descriptor}
		Fill a segment descriptor.
	\item[fill_descriptor_base(struct x86_desc *desc, unsigned base)]
		\ttindex{fill_descriptor_base}
		Set the base address in a segment descriptor.
	\item[fill_descriptor_limit(struct x86_desc *desc, unsigned limit)]
		\ttindex{fill_descriptor_limit}
		Set the limit in a segment descriptor.
	\item[fill_gate(struct x86_gate *gate, unsigned offset,
		unsigned short selector, unsigned char access,
		unsigned char word_count)]
		\ttindex{fill_gate}
		Fill an x86 gate descriptor.
	\end{csymlist}

	This header file is based on a file in CMU's Mach kernel.
\end{apidesc}

\api{gate_init.h}{Gate descriptor initialization support}
\label{gate-init-h}
\begin{apisyn}
	\cinclude{oskit/x86/gate_init.h}
\end{apisyn}
\begin{apidesc}
	This file contains the C structures and assembly-language macro
	definitions used to build x86 gate descriptor tables suitable for
	use by {\tt gate_init} (see Section~\ref{gate-init}).
	\begin{csymlist}
	\item[struct gate_init_entry]
		\ttindex{gate_init_entry}
		C structure describing a gate descriptor.
	\item[GATE_INITTAB_BEGIN(name)]
		\ttindex{GATE_INITTAB_BEGIN}
		Starts assembly-language definition of a gate descriptor table.
	\item[GATE_ENTRY(n, entry, type)]
		\ttindex{GATE_ENTRY}
		Initializes an element of a gate descriptor table.
	\item[GATE_INITTAB_END]
		\ttindex{GATE_INITTAB_END}
		Defines the end of a gate descriptor table.
	\end{csymlist}
	The assembly-language macros are designed to be used while writing
	trap entrypoint routines.
	See {\tt oskit/libkern/x86/base_trap_inittab.S}
	for example code that uses this facility.
\end{apidesc}

\api{trap.h}{Processor trap vectors}
\label{trap-h}
\begin{apisyn}
	\cinclude{oskit/x86/trap.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This contains the definitions for the trap numbers returned
	by the processor when something goes `wrong'.
	These can be used to determine the cause of the trap.

	\begin{csymlist}
	\item[T_DIVIDE_ERROR]
	\item[T_DEBUG]
	\item[T_NMI]
		non-maskable interrupt
	\item[T_INT3]
	\item[T_OVERFLOW]
		overflow test
	\item[T_OUT_OF_BOUNDS]
		bounds check
	\item[T_INVALID_OPCODE]
	\item[T_NO_FPU]
	\item[T_DOUBLE_FAULT]
	\item[T_FPU_FAULT]
	\item[T_INVALID_TSS]
	\item[T_SEGMENT_NOT_PRESENT]
	\item[T_STACK_FAULT]
	\item[T_GENERAL_PROTECTION]
	\item[T_PAGE_FAULT]
		T_PF_PROT: protection violation;
		T_PF_WRITE: write access;
		T_PF_USER: from user state
	\item[T_FLOATING_POINT_ERROR]
	\item[T_ALIGNMENT_CHECK]
	\item[T_MACHINE_CHECK]
	\end{csymlist}

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

\api{paging.h}{Page translation data structures and constants}
\begin{apidesc}
	XXX

	This header file is derived from Mach's {\tt intel/pmap.h}.
\end{apidesc}

\api{tss.h}{Processor task save state structure definition}
\begin{apisyn}
	\cinclude{oskit/x86/tss.h}

	\begin{verbatim}
	struct x86_tss {
		int	back_link;	/* previous task's segment, if nested */
		int	esp0;		/* initial stack pointer ... */
		int	ss0;		/* and segment for ring 0 */
		int	esp1;		/* initial stack pointer ... */
		int	ss1;		/* and segment for ring 1 */
		int	esp2;		/* initial stack pointer ... */
		int	ss2;		/* and segment for ring 2 */
		int	cr3;		/* CR3 - page table physical address */
		int	eip;		/* eip */
		int	eflags;		/* eflags */
		int	eax;		/* eax */
		int	ecx;		/* ecx */
		int	edx;		/* edx */
		int	ebx;		/* ebx */
		int	esp;		/* current stack pointer (ring 3) */
		int	ebp;		/* ebp */
		int	esi;		/* esi */
		int	edi;		/* edi */
		int	es;		/* es */
		int	cs;		/* cs */
		int	ss;		/* current stack segment (ring 3) */
		int	ds;		/* ds */
		int	fs;		/* fs */
		int	gs;		/* gs */
		int	ldt;		/* local descriptor table segment */
		unsigned short	trace_trap;	/* trap on switch to task */
		unsigned short	io_bit_map_offset; /* offset to IO perm bitmap */
	};
	\end{verbatim}
\end{apisyn}
\begin{apidesc}
	XXX

	XXX only the 32-bit version

	This contains the definition of a 32-bit tss.
	The tss used by the 80286 is incompatible with this.

	This header file is taken from CMU's Mach kernel.
\end{apidesc}


\apisec{\intelpc\ Generic Low-level Definitions}
\label{kern-x86pc-generic}

XXX

This section covers useful macros, definitions, and routines for
``PC''-specific features.

\api{irq_list.h}{Standard hardware interrupt assignments}
\label{irq-list-h}
\begin{apisyn}
	\cinclude{oskit/x86/pc/irq_list.h}
\end{apisyn}
\begin{apidesc}
	XXX

	Many of the interrupt vectors have pre-defined uses.
	The rest of them can be assigned to ISA, PCI, or other devices.
	This file contains the `defined' interrupt usages.
\end{apidesc}


\api{pic.h}{Programmable Interrupt Controller definitions}
\begin{apisyn}
	\cinclude{oskit/x86/pc/pic.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This contains definitions for the 8259(A) Programmable
	Interrupt Controller (PIC).
%	The APIC used by multi-processors is not included here.
	In addition to numerous constants, it also contains the
	prototypes for several functions and macros.

	\begin{csymlist}
	\item[pic_init(unsigned char master_base, unsigned char slave_base)]
		\label{pic-init}\ttindex{pic_init}
		MASTER_PIC_BASE and SLAVES_PIC_BASE are also defined,
		and may be passed in as parameters.
	\item[pic_disable_irq(unsigned char irq)]
		\label{pic-disable-irq}\ttindex{pic_disable_irq}
	\item[pic_enable_irq(unsigned char irq)]
		\label{pic-enable-irq}\ttindex{pic_enable_irq}
	\item[pic_test_irq(unsigned char irq)]
		\label{pic-test-irq}\ttindex{pic_test_irq}
	\item[pic_enable_all]
		\label{pic-enable-all}\ttindex{pic_enable_all}
	\item[pic_disable_all]
		\label{pic-disable-all}\ttindex{pic_disable_all}
	\item[pic_ack(irq)]
		\label{pic-ack}\ttindex{pic_ack}
	\end{csymlist}
\end{apidesc}


\api{keyboard.h}{PC keyboard definitions}
\begin{apisyn}
	\cinclude{oskit/x86/pc/keyboard.h}
\end{apisyn}
\begin{apidesc}
	XXX

	This header file contains the register definitions for the
	PC keyboard.  The port addresses are defined, along with
	the status and control bits.  This would be used by a keyboard
	device driver, or someone manipulating they keyboard directly.
	(ie, to turn on and off the keyboard LEDs).

	This header file is taken from CMU's Mach kernel.
\end{apidesc}

\api{rtc.h}{NVRAM Register locations}
\begin{apisyn}
        \cinclude{oskit/x86/pc/rtc.h}
\end{apisyn}
\begin{apidesc}
        This file is taken from FreeBSD (XXX cite?) and contains
        definitions for the standard NVRAM, or Real Time Clock,
        register locations.

	\begin{csymlist}
	\item[rtcin(unsigned char addr)]
		\ttindex{rtcin}
		Returns the 8-bit value from location {\em addr}.
	\item[rtcout(unsigned char addr, unsigned char val)]
		\ttindex{rtcout}
		Writes {\em val} to location {\em addr}.
	\end{csymlist}
\end{apidesc}

\apisec{\intel\ Processor Identification and Management}
\label{kern-x86-procman}

\api{cpu_info}{CPU identification data structure}
\label{cpu-info}
\begin{apisyn}
	\cinclude{oskit/x86/cpuid.h}

	\cstruct{cpu_info}{
		unsigned        stepping        : 4;	/* Stepping ID */
		unsigned        model           : 4;	/* Model */
		unsigned        family          : 4;	/* Family */
		unsigned        type            : 2;	/* Processor type */
		unsigned        feature_flags;		/* Features supported */
		char            vendor_id[12];		/* Vendor ID string */
		unsigned char   cache_config[16];	/* Cache information */
	};
\end{apisyn}
\begin{apidesc}
	This structure is used to hold identification information
	about x86 processors,
	such as information returned by the {\tt CPUID} instruction.
	The {\tt cpuid} toolkit function, described below,
	fills in an instance of this structure
	with information about the current processor.

	Note that it is expected that the {\tt cpu_info} structure
	will continue to grow in the future
	as new x86-architecture processors are released,
	so client code should not depend on this structure
	in ways that will break if the structure's size changes.

	The {\tt family} field describes the processor family:
	\begin{icsymlist}
	\item[CPU_FAMILY_386]
		A 386-class processor.
	\item[CPU_FAMILY_486]
		A 486-class processor.
	\item[CPU_FAMILY_PENTIUM]
		A Pentium-class (``586'') processor.
	\item[CPU_FAMILY_PENTIUM_PRO]
		A Pentium Pro-class (``686'') processor.
	\end{icsymlist}

	The {\tt type} field is one of the following:
	\begin{icsymlist}
	\item[CPU_TYPE_ORIGINAL]
		Original OEM processor.
	\item[CPU_TYPE_OVERDRIVE]
		OverDrive upgrade processor.
	\item[CPU_TYPE_DUAL]
		Dual processor.
	\end{icsymlist}

	The {\tt feature_flags} field is a bit field
	containing the following bits:
	\begin{icsymlist}
	\item[CPUF_ON_CHIP_FPU]
		Set if the CPU has a built-in floating point unit.
	\item[CPUF_VM86_EXT]
		Set if the virtual 8086 mode extensions are supported,
		i.e., the {\tt VIF} and {\tt VIP} flags register bits,
		and the {\tt VME} and {\tt PVI} bits in {\tt CR4}.
	\item[CPUF_IO_BKPTS]
		Set if I/O breakpoints are supported,
		i.e., the {\tt DR7_RW_IO} mode defined in {\tt x86/debug_reg.h}.
	\item[CPUF_4MB_PAGES]
		Set if 4MB superpages are supported,
		i.e., the {\tt INTEL_PDE_SUPERPAGE} page directory entry bit
		defined in {\tt x86/paging.h}.
	\item[CPUF_TS_COUNTER]
		Set if the on-chip timestamp counter
		and the {\tt RDTSC} instruction are available.
	\item[CPUF_PENTIUM_MSR]
		Set if the Pentium model specific registers are available.
	\item[CPUF_PAGE_ADDR_EXT]
		Set if the Pentium Pro's page addressing extensions
		(36-bit physical addresses and 2MB pages) are available.
	\item[CPUF_MACHINE_CHECK_EXCP]
		Set if the processor supports the Machine Check exception
		(vector 18, or {\tt T_MACHINE_CHECK} in {\tt x86/trap.h}).
	\item[CPUF_CMPXCHG8B]
		Set if the processor supports the {\tt CMPXCHG8B} instruction
		(also known as ``double-compare-and-swap'').
	\item[CPUF_LOCAL_APIC]
		Set if the processor has a built-in local APIC
		(Advanced Programmable Interrupt Controller),
		for symmetric multiprocessor support.
	\item[CPUF_MEM_RANGE_REGS]
		Set if the processor supports the memory type range registers.
	\item[CPUF_PAGE_GLOBAL_EXT]
		Set if the processor supports
		the global global paging extensions,
		i.e., the {\tt INTEL_PDE_GLOBAL} page table entry bit
		defined in {\tt x86/paging.h}.
	\item[CPUF_MACHINE_CHECK_ARCH]
		Set if the processor supports Intel's machine check architecture
		and the {\tt MCG_CAP} model-specific register.
	\item[CPUF_CMOVCC]
		Set if the processor supports the {\tt CMOV\em cc} instructions.
	\end{icsymlist}

	The {\tt cpuid.h} header file also contains symbolic definitions
	for other constants such as the cache configuration descriptor values;
	see the header file and the Intel documentation for details on these.
\end{apidesc}

\api{cpuid}{identify the current CPU}
\label{cpuid}
\begin{apisyn}
	\cinclude{oskit/x86/cpuid.h}

	\funcproto void cpuid(\outparam struct~cpu_info *out_info);
\end{apisyn}
\begin{apidesc}
	This function identifies the CPU on which it is running
	using Intel's recommended CPU identification procedure,
	and fills in the supplied structure with the information found.

	Note that since the {\tt cpuid} function is 32-bit code,
	it wouldn't run on anything less than an 80386 in the first place;
	therefore it doesn't bother to check for earlier processors.
\end{apidesc}
\begin{apiparm}
	\item[out_info]
		The CPU information structure to fill in.
\end{apiparm}

\api{cpu_info_format}{output a cpu_info structure in ASCII form}
\begin{apisyn}
	\cinclude{oskit/x86/cpuid.h}

	\funcproto void cpu_info_format(struct~cpu_info *info,
		        void (*formatter{)(void *data, const~char *fmt, ...)},
			void *data);
	%XXX fix function parameter formatting
\end{apisyn}
\begin{apidesc}
	This function takes the information in a {\tt cpu_info} structure
	and formats it as human-readable text.
	The {\em formatter} should be a pointer to a {\tt printf}-like function
	to be called to format the output data.
	The formatter function may be called multiple times
	to output all the relevant information.
\end{apidesc}
\begin{apiparm}
	\item[info]
		The filled-in CPU information structure to output.
	\item[formatter]
		The {\tt printf}-style formatted output function to call.
		It will be called with the opaque {\em data} pointer provided,
		a standard C format string ({\em fmt}),
		and optionally a set of data items to format.
	\item[data]
		An opaque pointer which is simply passed on
		to the {\em formatter} function.
\end{apiparm}

\api{cpu_info_min}{return the minimum feature set of two CPU information structures}
\begin{apisyn}
	\cinclude{oskit/x86/cpuid.h}

	\funcproto void cpu_info_min(struct~cpu_info *id1,
		struct~cpu_info *id2);
\end{apisyn}
\begin{apidesc}
	Determine the minimum (least-common-denominator) feature set of the
	two provided structures and return that.
	The new feature set is returned in {\em id1}.

	Typically used on SMP systems to determine the basic feature set
	common across all processors in the system regardless of type.
\end{apidesc}
\begin{apiparm}
	\item[id1, id2]
		The CPU information structures to compare.
\end{apiparm}

\api{cpu_info_dump}{pretty-print a CPU information structure to the console}
\begin{apisyn}
	\cinclude{oskit/x86/cpuid.h}

	\funcproto void cpu_info_dump(struct~cpu_info *info);
\end{apisyn}
\begin{apidesc}
	This function is merely a convenient front-end to {\tt cpu_info_format};
	it simply formats the CPU information and outputs it to the console
	using {\tt printf}.
\end{apidesc}

\api{i16_enter_pmode}{enter protected mode}
\begin{apisyn}
	\cinclude{oskit/x86/pmode.h}

	\funcproto void i16_enter_pmode(int prot_cs);
\end{apisyn}
\begin{apidesc}
	This 16-bit function switches the processor into protected mode
	by turning on the Protection Enable (PE) bit in CR0.
	The instruction that sets the PE bit
	is followed immediately by a jump instruction
	to flush the prefetch buffer,
	as recommended by Intel documentation.

	The function also initializes the CS register
	with the appropriate new protected-mode code segment,
	whose selector is specified in the {\em prot_cs} parameter.
	The {\em prot_cs} must evaluate to a constant,
	as it is used as an immediate operand
	in an inline assembly language code fragment.

	This routine does not perform any of the other steps
	in Intel's recommended mode switching procedure,
	such as setting up the GDT
	or reinitializing the data segment registers;
	these steps must be performed separately.
	The overall mode switching sequence
	is necessarily much more dependent on various OS-specific factors
	such as the layout of the GDT;
	therefore the \oskit{} does not attempt
	to provide a ``generic'' function to perform the entire switch.
	Instead, the full switching sequence is provided
	as part of the base environment setup code;
	see Section~\ref{i16-raw} for more details.
\end{apidesc}

\api{i16_leave_pmode}{leave protected mode}
\begin{apisyn}
	\cinclude{oskit/x86/pmode.h}

	\funcproto void i16_leave_pmode(int real_cs);
\end{apisyn}
\begin{apidesc}
	This 16-bit function switches the processor out of protected mode
	and back into real mode
	by turning off the Protection Enable (PE) bit in CR0.
	The instruction that clears the PE bit
	is followed immediately by a jump instruction
	to flush the prefetch buffer,
	as recommended by Intel documentation.
	At the same time,
	this function also initializes the CS register
	with the appropriate real-mode code segment,
	specified by the {\em real_cs} parameter.

	This routine does not perform any of the other steps
	in Intel's recommended mode switching procedure,
	such as reinitializing the data segment registers;
	these steps must be performed separately.
	See Section~\ref{i16-raw} for information on
	the full mode switch implementation
	provided by the base environment.
\end{apidesc}

\api{paging_enable}{enable page translation}
\label{paging-enable}
\begin{apisyn}
	\cinclude{oskit/x86/paging.h}

	\funcproto void paging_enable(oskit_addr_t pdir);
\end{apisyn}
\begin{apidesc}
	Loads the processor page directory using {\tt pdir} and
	turns on paging.

	The caller must already have created and initialized
	an appropriate initial page directory
	as described in Intel documentation.
	The \oskit{} provides convenient facilities
	that can be used to create x86 page directories and page tables;
	for more information, see Section~\ref{kern-x86-base-paging}.

	This function assumes that {\tt pdir} equivalently maps
	the physical memory that contains the currently executing code,
	the currently loaded GDT and IDT.
\end{apidesc}

\api{paging_disable}{disable page translation}
\label{paging-disable}
\begin{apisyn}
	\cinclude{oskit/x86/paging.h}

	\funcproto void paging_disable(void);
\end{apisyn}
\begin{apidesc}
	Turns paging off and flushes the TLB.

	This function assumes that the currently loaded page directory
	equivalently maps the physical memory that contains
	the currently executing code, the currently loaded GDT and IDT.
\end{apidesc}

\api{gate_init}{install gate descriptors}
\label{gate-init}
\begin{apisyn}
	\cinclude{oskit/x86/gate_init.h}

	\funcproto void gate_init(struct~x86_gate *dest,
		const~struct~gate_init_entry *src, unsigned entry_cs);
\end{apisyn}
\begin{apidesc}
	Install entries in a processor descriptor table
	from the specified array of gate descriptors
	(see Section~\ref{gate-init-h}).
	Typically used to initialize the processor IDT with trap and interrupt
	vectors (see Section~\ref{base-idt}).
\end{apidesc}
\begin{apiparm}
	\item[dest]
		Pointer to the x86 descriptor table to fill in.
	\item[src]
		Pointer to the {\tt gate_init_entry} array to copy from.
	\item[entry_cs]
		Code segment selector to associate with all entries.
\end{apiparm}
\begin{apidep}
	\item[fill_gate]	\ref{seg-h}
\end{apidep}

%XXX tty.h

\apisec{\intel\ Base Environment}
\label{kern-x86-base}
\label{kern-x86-base-firstsection}

The base environment code for the x86 architecture
is designed to assist the OS developer
in dealing with much of the ``x86 grunge''
that OS developers typically would rather not worry about.
The \oskit{} provides easy-to-use primitives
to set up and maintain various common flavors of x86 kernel environments
without unnecessarily constraining the OS implementation.
The base environment support on the x86 architecture is divided
into the three main categories:
segmentation, paging, and trap handling.
The base environment support code in each category
is largely orthogonal and easily separable,
although it is also designed to work well together.

\subsection{Memory Model}

The x86 architecture supports a very complex virtual memory model
involving both segmentation and paging;
one of the goals of the \oskit{}'s base environment support for the x86
is to smooth over some of this complexity,
hiding the details that the OS doesn't want to deal with
while still allowing the OS full freedom
to use the processor's virtual memory mechanisms as it sees fit.
This section describes
% the in general xxx
the memory models supported and assumed by the base environment.

First, here is a summary of several important terms
that are used heavily used in the following text;
for full details on virtual, linear, and physical addresses
on the x86 architecture,
see the appropriate processor manuals.
%XXX cite?
\begin{itemize}
\item	{\em Physical addresses}
	are the actual addresses seen on external I/O and memory busses,
	after segmentation and paging transformations have been applied.
\item	{\em Linear addresses}
	are absolute 32-bit addresses within the x86's paged address space,
	after segmentation has been applied but before page translation.
	The virtual addresses of simple ``paging-only'' architectures
	such as {\sc mips} correspond to linear addresses on the x86.
\item	{\em Virtual addresses}
	are the logical addresses used by program code to access memory.
	To read an instruction or access a data item,
	the processor first converts the virtual address
	into a linear address using the segmentation mechanism,
	then translates the linear address to a physical address
	using paging.
\item	{\em Kernel virtual addresses}
	are the virtual addresses normally used by kernel code
	to access its own functions and data structures:
	in other words,
	addresses accessed through the kernel's segment descriptors.
\end{itemize}

The \oskit{} provides a standard mechanism,
defined in {\tt base_vm.h} (see Section~\ref{base-vm}),
which is used throughout the base environment
to maintain considerable independence from the memory model in effect.
These facilities allow the base environment support code
to avoid various assumptions about
the relationships between kernel virtual addresses,
linear addresses, and physical addresses.
Client OS code can use these facilities as well if desired.

Of course, it is impractical for the base environment code
to avoid assumptions about the memory model completely.
In particular, the code assumes that,
for ``relevant'' code and data
(e.g., the functions implementing the base environment
and the data structures they manipulate),
kernel virtual addresses
can be converted to and from linear or physical addresses
by adding or subtracting an offset stored in a global variable.
However, the code does {\em not} assume
that these offsets are always the same
(the client OS is allowed to change them dynamically),
or that {\em all} available physical memory
is mapped into the kernel's virtual address space,
or that all linear memory is accessible
through the kernel's data segment descriptors.
Detailed information about the memory model assumptions
made by particular parts of the base environment support
are documented in the appropriate API sections.

If the \oskit{}'s startup code is being used to start the OS,
then the specific memory model in effect initially
depends on the startup environment,
described in later the appropriate sections.
For example, for kernels booted from a MultiBoot boot loader,
in the initial memory environment
virtual addresses, linear addresses, and physical addresses
are all exactly equal (the offsets are zero).
On the other hand, for kernels loaded from DOS,
linear addresses and physical addresses will still be equal
but kernel virtual addresses will be at some offset
depending on where in physical memory the kernel was loaded.
Regardless of the initial memory setup,
the client OS is free to change the memory model later as necessary.

XXX example memory maps

XXX explain how to change memory models at run-time

\api{base_vm.h}{definitions for the base virtual memory environment}
%XXX split this out into multiple man pages?
\label{base-vm}
\begin{apisyn}
	\cinclude{oskit/machine/base_vm.h}
\end{apisyn}
\begin{apidesc}
	This header file provides generic virtual memory-related definitions
	commonly used throughout the base environment,
	which apply to both segmentation and paging.
	In particular, this file defines a set of macros and global variables
	which allow the rest of the base environment code in the toolkit
	(and the client OS, if it chooses)
	to maintain independence from the memory model in effect.
	These facilities allow code
	to avoid various assumptions about
	the relationships between kernel virtual addresses,
	linear addresses, and physical addresses.

	The following variable and associated macros
	are provided to convert between linear and kernel virtual addresses.
	\begin{csymlist}
	\item[linear_base_va]		\ttindex{linear-base-va}
		This global variable defines
		the address in kernel virtual memory
		that corresponds to address 0 in linear memory.
		It is used by the following conversion macros;
		therefore, changing this variable
		changes the behavior of the associated macros.
	\item[lintokv({\em la})]	\ttindex{lintokv}
		This macro converts linear address {\em la}
		into a kernel virtual address
		and returns the result as an {\tt oskit_addr_t}.
	\item[kvtolin({\em va})]	\ttindex{kvtolin}
		For example,
		the segmentation initialization code uses {\tt kvtolin()}
		to calculate the linear addresses of segmentation structures
		to be used in segment descriptor or pseudo-descriptor structures
		provided to the processor.
	\end{csymlist}

	Similarly, the following variable and associated macros
	convert between {\em physical} and kernel virtual addresses.
	(Conversions between linear and physical addresses can be done
	by combining the two sets of macros.)
	\begin{csymlist}
	\item[phys_mem_va]		\ttindex{phys-mem-va}	\label{phys-mem-va}
		This global variable defines
		the address in kernel virtual memory
		that corresponds to address 0 in physical memory.
		It is used by the following conversion macros;
		therefore, changing this variable
		changes the behavior of the associated macros.
	\item[phystokv({\em pa})]	\ttindex{phystokv}	\label{phystokv}
		This macro converts physical address {\em pa}
		into a kernel virtual address
		and returns the result as an {\tt oskit_addr_t}.
		The macro makes the assumption
		that the specified physical address
		{\em can} be converted to a kernel virtual address this way:
		in OS kernels that do not direct-map all physical memory
		into the kernel's virtual address space,
		the caller must ensure that the supplied {\em pa}
		refers to a physical address that {\em is} mapped.
		For example, the primitive page table management code
		provided by the \oskit{}'s base environment
		uses this macro to access page table entries
		given the physical address of the page table;
		therefore, these functions can only be used
		if page tables are allocated from physical pages
		that are direct-mapped into the kernel's address space.
	\item[kvtophys({\em va})]	\ttindex{kvtophys}
		This macro converts kernel virtual address {\em va}
		into a physical address
		and returns the result as an {\tt oskit_addr_t}.
		The macro assumes that the virtual address
		{\em can} be converted directly to a physical address this way;
		the caller must ensure that this is the case.
		For example, some operating systems only direct-map
		the kernel's code and statically allocated data;
		in such kernels, {\em va} should only refer to
		statically-allocated variables or data structures.
		This is generally sufficient
		for the \oskit{}'s base environment code,
		which mostly operates on statically-allocated data structures;
		however, the OS must of course take its chosen memory model
		into consideration if it uses these macros as well.
	\end{csymlist}

	XXX real_cs

	Note that there is nothing in this header file
	that defines or relates to ``user-mode'' address spaces.
	This is because the base environment code in the \oskit{}
	is not concerned with user mode in any way;
	in fact, it doesn't even care
	whether or not the OS kernel implements user address spaces at all.
	For example, boot loaders or unprotected real-time kernels
	built using the \oskit{}
	probably do not need any notion of user mode at all.
\end{apidesc}

\api{base_cpu_setup}{initialize and activate the base CPU environment}
\label{base-cpu-setup}
\begin{apisyn}
	\cinclude{oskit/machine/base_cpu.h}

	\funcproto void base_cpu_setup(void);
\end{apisyn}
\begin{apidesc}
	This function provides a single entrypoint
	to initialize and activate all of the processor structures
	necessary for ordinary execution.
	This includes identifying the CPU,
	and initializing and activating the base GDT, IDT, and TSS,
	and reloading all segment registers as recommended by Intel.
	The call returns with the CS segment set to {\tt KERNEL_CS}
	(the default kernel code segment; see~\ref{base-gdt} for details),
	DS, ES, and SS set to {\tt KERNEL_DS}
	(the default kernel data segment),
	and FS and GS set to 0.
	After the {\tt base_cpu_setup} call completes,
	a full working kernel environment is in place:
	segment registers can be loaded,
	interrupts and traps can be fielded by the OS,
	privilege level changes can occur, etc.

	This function does {\em not} initialize or activate
	the processor's paging mechanism,
	since unlike the other mechanisms,
	paging is optional on the x86 and not needed in some environments
	(e.g., boot loaders or embedded kernels).

	The {\tt base_cpu_setup} function is actually just a simple wrapper
	that calls {\tt base_cpu_init} followed by {\tt base_cpu_load}.

	Note that it is permissible to call this function
	(and/or the more primitive functions it is built on)
	more than once.
	This is particularly useful
	when reconfiguring the kernel memory map.
	For example, a typical MultiBoot (or other 32-bit) kernel
	generally starts out with paging disabled,
	so it must run in the low range of linear/physical memory.
	However, after enabling page translation,
	the OS may later want to relocate itself
	to run at a higher address in linear memory
	so that application programs can use the low part
	(e.g., v86-mode programs).
	An easy way to do this with the \oskit{}
	is to call {\tt base_cpu_setup} once at the very beginning,
	to initialize the basic unpaged kernel environment,
	and then later, after paging is enabled
	and appropriate mappings have been established
	in high linear address space,
	modify the {\tt linear_base_va} variable (Section~\ref{base-vm})
	to reflect the kernel's new linear address base,
	and finally call {\tt base_cpu_setup} again
	to reinitialize and reload the processor tables
	according to the new memory map.

	%XXX say this in a more obvious place, or sprinkle pointers around.
\end{apidesc}
\begin{apidep}
	\item[base_cpu_init]	\ref{base-cpu-init}
	\item[base_cpu_load]	\ref{base-cpu-load}
\end{apidep}

\api{base_cpu_init}{initialize the base environment data structures}
\label{base-cpu-init}
\begin{apisyn}
	\cinclude{oskit/machine/base_cpu.h}

	\funcproto void base_cpu_init(void);
\end{apisyn}
\begin{apidesc}
	This function initializes all of the critical data structures
	used by the base environment,
	including {\tt base_cpuid}, {\tt base_idt}, {\tt base_gdt},
	and {\tt base_tss},
	but does not actually activate them
	or otherwise modify the processor's execution state.
	The {\tt base_cpu_load} function must be called later
	to initialize the processor with these structures.
	Separate initialization and activation functions are provided
	to allow the OS to customize the processor data structures if necessary
	before activating them.
\end{apidesc}
\begin{apidep}
	\item[cpuid]		\ref{cpuid}
	\item[base_trap_init]	\ref{base-trap-init}
	\item[base_gdt_init]	\ref{base-gdt-init}
	\item[base_tss_init]	\ref{base-tss-init}
\end{apidep}

\api{base_cpu_load}{activate the base processor execution environment}
\label{base-cpu-load}
\begin{apisyn}
	\cinclude{oskit/machine/base_cpu.h}

	\funcproto void base_cpu_load(void);
\end{apisyn}
\begin{apidesc}
	This function loads the critical base environment data structures
	(in particular, the GDT, IDT, and TSS)
	into the processor,
	and reinitializes all segment registers from the new GDT
	as recommended in Intel processor documentation.
	The structures must already have been set up
	by a call to {\tt base_cpu_init}
	and/or custom initialization code in the client OS.

	This function returns with the CS segment set to {\tt KERNEL_CS}
	(the default kernel code segment;
	see Section~\ref{base-gdt} for details),
	DS, ES, and SS set to {\tt KERNEL_DS}
	(the default kernel data segment),
	and FS and GS set to 0.
	After the {\tt base_cpu_load} call completes,
	a full working kernel environment is in place:
	segment registers can be loaded,
	interrupts and traps can be fielded by the OS,
	privilege level changes can occur, etc.
\end{apidesc}
\begin{apidep}
	\item[base_gdt_load]	\ref{base-gdt-load}
	\item[base_idt_load]	\ref{base-idt-load}
	\item[base_tss_load]	\ref{base-tss-load}
\end{apidep}

\api{base_cpuid}{global variable describing the processor}
\label{base-cpuid}
\begin{apisyn}
	\cinclude{oskit/machine/base_cpu.h}

	{\tt extern struct cpu_info \csymbol{base_cpuid};}
\end{apisyn}
\begin{apidesc}
	This is a global variable that is filled in by {\tt base_cpu_init}
	with information about the processor
	on which {\tt base_cpu_init} was called.
	(Alternatively, it can also be initialized manually by the OS
	simply by calling {\tt cpuid(\&base_cpuid)}).
	This structure is used by other parts of the kernel support library
	to determine whether or not certain processor features are available,
	such as 4MB superpages.
	See~\ref{cpu-info} for details on the contents of this structure.

	Note that in a multiprocessor system,
	this variable will reflect the boot processor.
	This is generally not a problem,
	since most SMPs use identical processors,
	or at least processors in the same generation,
	so that they appear equivalent to OS software.
	(For example, it is very unlikely that you'd find an SMP
	that mixes 486 and Pentium processors),
	However, if this ever turns out to be a problem,
	the OS can always override
	the {\tt cpuid} or {\tt base_cpu_init} function,
	or just modify the contents of the {\tt base_cpuid} variable
	after calling {\tt base_cpu_init}
	so that it reflects the least common denominator of all the processors.
\end{apidesc}

\api{base_stack.h}{default kernel stack}
\begin{apisyn}
	\cinclude{oskit/machine/base_stack.h}
\end{apisyn}
\begin{apidesc}
	Definitions related to the default kernel stack.
	\begin{csymlist}
	\item[BASE_STACK_SIZE]		\ttindex{BASE_STACK_SIZE}
		Preprocessor constant defining the size in bytes
		of the default kernel stack.
	\item[base_stack_start]		\ttindex{base_stack_start}
		C external variable declaration for
		the low-address end of the stack.
		On the x86, this is the end toward which the stack grows.
	\item[base_stack_end]		\ttindex{base_stack_end}
		C external variable declaration for
		the high-address end of the stack
		(\texttt{base_stack_start} + \texttt{BASE_STACK_SIZE}).
		On the x86, this is the end where the stack begins.
	\end{csymlist}

	This header file can be used in assembly language code as well as C.
\end{apidesc}

\apisec{\intel\ Base Environment: Segmentation Support}
\label{kern-x86-base-seg}

Although most modern operating systems
use a simple ``flat'' address space model,
the x86 enforces a segmentation model which cannot be disabled directly;
instead, it must be set up to emulate a flat address space model
if that is what the OS desires.
The base environment code provides functionality
to set up a simple flat-model processor environment
suitable for many types of kernels, both ``micro'' and ``macro.''
For example, it provides a default
global descriptor table (GDT)
containing various flat-model segments for the kernel's use,
as well as a default task state segment (TSS).

Furthermore, even though this base environment is often sufficient,
the client OS is not limited to using it exactly as provided by default:
the client kernel is given the flexibility to tweak various parameters,
such as virtual and linear memory layout,
as well as the freedom
to operate completely outside of the base environment when necessary.
For example, although the base environment provides a default TSS,
the OS is free to create its own TSS structures
and use them when running applications that need special facilities
such as v86 mode or I/O ports.
Alternatively, the OS could use the default processor data structures
only during startup,
and switch to its own complete, customized set after initialization.

The base environment code in the \oskit{}
generally assumes that it is running in a simple flat model,
in which only one code segment and one data segment
are used for all kernel code and data, respectively,
and that the code and data segments are synonymous
(they each map to the same range of linear addresses).
The OS is free to make more exotic uses of segmentation if it so desires,
as long as the \oskit{} code is run in a consistent environment.

XXX diagram of function call tree?

The base segmentation environment provided by the \oskit{}
is described in more detail in the following API sections.

\api{base_gdt}{default global descriptor table for the base environment}
\label{base-gdt}
\begin{apisyn}
	\cinclude{oskit/x86/base_gdt.h}

	{\tt extern struct x86_desc \csymbol{base_gdt}[GDTSZ];}
\end{apisyn}
\begin{apidesc}
	This variable is used in the base environment
	as the default global descriptor table.
	The default {\tt base_gdt} definition
	contains {\tt GDTSZ} selector slots,
	including the Intel-reserved, permanently unused slot 0.

	The following symbols are defined in {\tt base_gdt.h}
	to be segment selectors for the descriptors in the base GDT.
	These selectors can be converted to indices
	into the GDT descriptor array {\tt base_gdt} by dividing by 8
	(the processor reserves the low three bits of all selectors
	for other information).
	\begin{icsymlist}
	\item[BASE_TSS]
		A selector for the base task state segment ({\tt base_tss}).
		The {\tt BASE_TSS} segment descriptor
		is initialized by {\tt base_gdt_init},
		but the {\tt base_tss} structure itself
		is initialized by {\tt base_tss_init}
		and loaded into the processor by {\tt base_tss_load};
		see Section~\ref{base-tss} for more details.
	\item[KERNEL_CS]
		This is the default kernel code segment selector.
		It is initialized by {\tt base_gdt_init}
		to be a flat-model, 4GB, readable, ring 0 code segment;
		{\tt base_gdt_load} loads this segment into the CS register
		while reinitializing the processor's segment registers.
	\item[KERNEL_DS]
		This is the default kernel data segment selector.
		It is initialized by {\tt base_gdt_init}
		to be a flat-model, 4GB, writable, ring 0 data segment;
		{\tt base_gdt_load} loads this segment
		into the DS, ES, and SS registers
		while reinitializing the processor's segment registers.
	\item[KERNEL_16_CS]
		This selector is identical to {\tt KERNEL_CS}
		except that it is a 16-bit code segment
		(the processor defaults to 16-bit operand and addressing modes
		rather than 32-bit while running code in this segment),
		and it has a 64KB limit rather than 4GB.
		This selector is used when switching
		between real and protected mode,
		to provide an intermediate 16-bit protected mode
		execution context.
		It is unused in kernels that never execute in real mode
		(e.g., typical MultiBoot kernels).
	\item[KERNEL_16_DS]
		This selector is a data segment synonym for {\tt KERNEL_16_CS};
		it is generally only used
		when switching from protected mode back to real mode.
		It is used to ensure that the segment registers
		contain sensible real-mode values before performing the switch,
		as recommended in Intel literature.
	\item[LINEAR_CS]
		This selector is set up to be a ring 0 code segment
		that directly maps the entire linear address space:
		in other words, it has an offset of zero and a 4GB limit.
		In some environments, where kernel virtual addresses
		are the same as linear addresses,
		this selector is a synonym for {\tt KERNEL_CS}.
	\item[LINEAR_DS]
		This is a data segment otherwise identical to {\tt LINEAR_CS}.
	\item[USER_CS]
		This selector is left unused and uninitialized
		by the \oskit{};
		nominally, it is intended to be used
		as a code segment for unprivileged user-level code.
	\item[USER_DS]
		This selector is left unused and uninitialized
		by the \oskit{};
		nominally, it is intended to be used
		as a data segment for unprivileged user-level code.
	\end{icsymlist}

	If the client OS wants to make use of the base GDT
	but needs more selector slots for its own purposes,
	it can define its own instance of the {\tt base_gdt} variable
	so that it has room for more than {\tt GDTSZ} elements;
	{\tt base_gdt_init} will initialize
	only the first ``standard'' segment descriptors,
	leaving the rest for the client OS's use.
	%XXX The Client OS may also have to override {\tt base_gdt_load},
	% or reload the longer GDT afterwards...

	On multiprocessor systems,
	the client OS may want each processor to have its own GDT.
	In this case, the OS can create a separate clone of the base GDT
	for each additional processor besides the boot processor,
	and leave the boot processor using the base GDT.
	Alternatively, the OS could use the base GDT only during initialization,
	and switch {\em all} processors to custom GDTs later;
	this approach provides the most flexibility to the OS,
	since the custom GDTs can be arranged
	in whatever way is most convenient.
\end{apidesc}

\api{base_gdt_init}{initialize the base GDT to default values}
\label{base-gdt-init}
\begin{apisyn}
	\cinclude{oskit/x86/base_gdt.h}

	\funcproto void base_gdt_init(void);
	\funcproto void i16_base_gdt_init(void);
\end{apisyn}
\begin{apidesc}
	This function initializes the standard descriptors in the base GDT
	as described in Section~\ref{base-gdt}.

	For all of the standard descriptors
	except {\tt LINEAR_CS} and {\tt LINEAR_DS},
	the {\tt kvtolin} macro is used to compute
	the linear address to plug into the offset field of the descriptor:
	for {\tt BASE_TSS}, this is {\tt kvtolin(\&base_tss)};
	for the kernel code and data segments, it is {\tt kvtolin(0)}
	(i.e., the linear address corresponding to
	the beginning of kernel virtual address space).
	{\tt LINEAR_CS} and {\tt LINEAR_DS} are always given an offset of 0.

	A 16-bit version of this function, {\tt i16_base_gdt_init},
	is also provided so that the GDT can be initialized properly
	before the processor has been switched to protected mode.
	(Switching to protected mode on the x86
	according to Intel's recommended procedure
	requires a functional GDT to be already initialized and activated.)
\end{apidesc}
\begin{apidep}
	\item[fill_descriptor]	\ref{seg-h}
	\item[kvtolin]		\ref{base-vm}
	\item[base_gdt]		\ref{base-gdt}
	\item[base_tss]		\ref{base-tss}
\end{apidep}

\api{base_gdt_load}{load the base GDT into the CPU}
\label{base-gdt-load}
\begin{apisyn}
	\funcproto void base_gdt_load(void);
	\funcproto void i16_base_gdt_load(void);
\end{apisyn}
\begin{apidesc}
	This function loads the base GDT into the processor's GDTR,
	and then reinitializes all segment registers
	from the descriptors in the newly loaded GDT.
	It returns with the CS segment set to {\tt KERNEL_CS}
	(the default kernel code segment;
	see Section~\ref{base-gdt} for details),
	DS, ES, and SS set to {\tt KERNEL_DS}
	(the default kernel data segment),
	and FS and GS set to 0.
\end{apidesc}
\begin{apidep}
	\item[kvtolin]		\ref{base-vm}
	\item[base_gdt]		\ref{base-gdt}
\end{apidep}

\api{base_idt}{default interrupt descriptor table}
\label{base-idt}
\begin{apisyn}
	\cinclude{oskit/x86/base_idt.h}

	{\tt extern struct x86_desc \csymbol{base_idt}[IDTSZ];}
\end{apisyn}
\begin{apidesc}
	This global variable is used in the base environment
	as the default interrupt descriptor table.
	The default definition of {\tt base_idt} in the library
	contains the architecturally-defined maximum
	of 256 interrupt vectors ({\tt IDTSZ}).\rat{
		Although simple x86 PC kernels often only use
		the 32 processor trap vectors plus 16 interrupt vectors,
		{\em which} set of vectors are used for hardware interrupts
		tends to differ greatly between kernels.
		Some kernels also want to use well-known vectors
		for efficient system call emulation,
		such as 0x21 for DOS or 0x80 for Linux.
		Some bootstrap mechanisms, such as VCPI on DOS,
		must determine at run-time the set of vectors
		used for hardware interrupts,
		and therefore potentially need all 256 vectors to be available.
		Finally, making use of the enhanced interrupt facilities
		on Intel SMP Standard-compliant multiprocessors
		generally requires use of higher vector numbers,
		since vector numbers are tied to interrupt priorities.
		For all these reasons,
		we felt the default IDT should be of the maximum size,
		even though much of it is usually wasted.
	}

	The {\tt base_idt.h} header file does not define any symbols
	representing interrupt vector numbers.
	The lowest 32 vectors are the processor trap vectors defined by Intel;
	since these are not specific to the base environment,
	they are defined in the generic header file {\tt x86/trap.h}
	(see Section~\ref{trap-h}).
	Standard hardware interrupt vectors are PC-specific,
	and therefore are defined separately in {\tt x86/pc/irq_list.h}
	(see Section~\ref{irq-list-h}).
	For the same reason,
	there is no {\tt base_idt_init} function,
	only separate functions to initialize
	the trap vectors in the base IDT
	({\tt base_trap_init}, Section~\ref{base-trap-init}),
	and hardware interrupt vectors in the IDT
	({\tt base_irq_init}, Section~\ref{base-irq-init}).
\end{apidesc}

\api{base_idt_load}{load the base IDT into the current processor}
\label{base-idt-load}
\begin{apisyn}
	\cinclude{oskit/x86/base_idt.h}

	\funcproto void base_idt_load(void);
\end{apisyn}
\begin{apidesc}
	This function loads the {\tt base_idt} into the processor,
	so that subsequent traps and hardware interrupts
	will vector through it.
	It uses the {\tt kvtolin} macro
	to compute the proper linear address of the IDT
	to be loaded into the processor.
\end{apidesc}
\begin{apidep}
	\item[kvtolin]		\ref{base-vm}
	\item[base_idt]		\ref{base-idt}
\end{apidep}

\api{base_tss}{default task state segment}
\label{base-tss}
\begin{apisyn}
	\cinclude{oskit/x86/base_tss.h}

	{\tt extern struct x86_tss \csymbol{base_tss};}
\end{apisyn}
\begin{apidesc}
	The {\tt base_tss} variable
	provides a default task state segment
	that the OS can use for privilege level switching
	if it does not otherwise use the x86's task switching mechanisms.
	The x86 architecture requires every protected-mode OS
	to have at least one TSS even if no task switching is done;
	however, many x86 kernels
	do not use the processor's task switching features
	because it is faster to context switch manually.
	Even if special TSS segments are used sometimes
	(e.g., to take advantage of the I/O bitmap feature
	when running MS-DOS programs),
	the OS can still use a common TSS
	for all tasks that do not need to use these special features;
	this is the strategy taken by the Mach kernel, for example.
	The {\tt base_tss} provided by the toolkit
	serves in this role as a generic ``default'' TSS.

	The {\tt base_tss} is a minimal TSS,
	in that it contains no I/O bitmap or interrupt redirection map.
	XXX The toolkit also supports an alternate default TSS
	with a full I/O permission bitmap,
	but it isn't fully integrated or documented yet.
\end{apidesc}

\api{base_tss_init}{initialize the base task state segment}
\label{base-tss-init}
\begin{apisyn}
	\cinclude{oskit/x86/base_tss.h}

	\funcproto void base_tss_init(void);
\end{apisyn}
\begin{apidesc}
	The {\tt base_tss_init} function
	initializes the {\tt base_tss} to a valid minimal state.
	It sets the I/O permission bitmap offset
	to point past the end of the TSS,
	so that it will be interpreted by the processor as empty
	(no permissions for any I/O ports).
	It also initializes the ring 0 stack segment selector ({\tt ss0})
	to {\tt KERNEL_DS},
	and the ring 0 stack pointer ({\tt esp0})
	to the current stack pointer value at the time of the function call,
	to provide a minimal working context for trap handling.
	Once the OS kernel sets up a ``real'' kernel stack,
	it should reinitialize {\tt base_tss.esp0} to point to that.
\end{apidesc}
\begin{apidep}
	\item[base_tss]		\ref{base-tss}
\end{apidep}

\api{base_tss_load}{load the base TSS into the current processor}
\label{base-tss-load}
\begin{apisyn}
	\cinclude{oskit/x86/base_tss.h}

	\funcproto void base_tss_load(void);
\end{apisyn}
\begin{apidesc}
	This function activates the {\tt base_tss} in the processor
	using the {\tt LTR} instruction,
	after clear the busy bit
	in the {\tt BASE_TSS} segment descriptor
	to ensure that a spurious trap isn't generated.
\end{apidesc}
\begin{apidep}
	\item[base_gdt]		\ref{base-gdt}
\end{apidep}

\apisec{\intel\ Base Environment: Trap Handling}
\label{kern-x86-base-trap}

The first 32 vectors in the IDT are used to handle processor exceptions
(``traps'').
In the base \oskit{} environment,
these vectors are initialized from the
{\tt base_trap_inittab} array (\ref{base-trap-inittab})
using the {\tt base_trap_init} function (\ref{base-trap-init}).
By default,
each exception vector in the processor IDT is set to point to a
common assembly language stub that saves a standard trap frame
(\ref{trap-state}),
and calls a designated high-level handler specified
in the {\tt base_trap_handlers} table (\ref{base-trap-handlers}).
Initially, all the entries in this table point to
{\tt base_trap_default_handler} (\ref{base-trap-default-handler}).
Custom trap handlers can be installed by changing
the appropriate entry in the table.
The default action for all traps can be changed by overriding
{\tt base_trap_default_handler}.

This affords client OSes with a variety of choices for modifying the
behavior of trap handling.
By using the base trap environment unchanged
(i.e., the client OS is not expecting or handling traps),
all traps will produce a trap dump and panic.
This behavior is sufficient for most simple \oskit{} applications.
By setting entries {\tt base_trap_handlers},
the client can provide its own C language trap handlers while still using
the default {\tt trap_state} structure.
The \oskit{} remote GDB debugging package (\ref{gdb-trap}) does this.
Finally, the client OS can override {\tt base_trap_inittab} to allow for
different high-level handlers for every exception type and/or to permit
the use of a different trap state format.

\api{trap_state}{saved state format used by the default trap handler}
\label{trap-state}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

\com{XXX TeX capacity exceeded, sorry [parameter stack size=60].
	\cstruct{trap_state}{
		unsigned int	gs;	/* Saved GS register in low 16 bits */
		unsigned int	fs;	/* Saved FS register in low 16 bits */
		unsigned int	es;	/* Saved ES register in low 16 bits */
		unsigned int	ds;	/* Saved DS register in low 16 bits */
		unsigned int	edi;	/* Saved EDI register */
		unsigned int	esi;	/* Saved ESI register */
		unsigned int	ebp;	/* Saved EBP register */
		unsigned int	cr2;	/* Saved CR2 (page fault linear address) */
		unsigned int	ebx;	/* Saved EBX register */
		unsigned int	edx;	/* Saved EDX register */
		unsigned int	ecx;	/* Saved ECX register */
		unsigned int	eax;	/* Saved EAX register */
		unsigned int	trapno;	/* Processor trap number, 0-31 */
		unsigned int	err;	/* Processor error code, 0 if none */
		unsigned int	eip;	/* Saved instruction pointer */
		unsigned int	cs;	/* Saved code segment */
		unsigned int	eflags;	/* Saved flags register */
		unsigned int	esp;	/* Saved stack pointer if from user mode */
		unsigned int	ss;	/* Saved stack selector if from user mode  */
		unsigned int	v86_es;	/* Saved real-mode ES if from v86 mode */
		unsigned int	v86_ds;	/* Saved real-mode DS if from v86 mode */
		unsigned int	v86_fs;	/* Saved real-mode FS if from v86 mode */
		unsigned int	v86_gs;	/* Saved real-mode GS if from v86 mode */
	};
}%com
\begin{verbatim}
struct trap_state
{
	/* Saved segment registers */
	unsigned int    gs;
	unsigned int    fs;
	unsigned int    es;
	unsigned int    ds;

	/* PUSHA register state frame */
	unsigned int    edi;
	unsigned int    esi;
	unsigned int    ebp;
	unsigned int    cr2;	/* we save cr2 over esp for page faults */
	unsigned int    ebx;
	unsigned int    edx;
	unsigned int    ecx;
	unsigned int    eax;

	/* Processor trap number, 0-31.  */
	unsigned int    trapno;

	/* Error code pushed by the processor, 0 if none.  */
	unsigned int    err;

	/* Processor state frame */
	unsigned int    eip;
	unsigned int    cs;
	unsigned int    eflags;
	unsigned int    esp;
	unsigned int    ss;

	/* Virtual 8086 segment registers */
	unsigned int    v86_es;
	unsigned int    v86_ds;
	unsigned int    v86_fs;
	unsigned int    v86_gs;
};
\end{verbatim}
\end{apisyn}
\begin{apidesc}
	This structure defines the saved state frame
	pushed on the stack by the default trap entrypoints
	provided by the base environment
	(see Section~\ref{base-trap-inittab}).
	It is also used by the {\tt trap_dump} routine,
	which is used in the default environment
	to dump the saved register state and panic
	if an unexpected trap occurs;
	and by {\tt gdb_trap},
	the default trap handler for remote GDB debugging.

	This client OS is not obligated to use this structure
	as the saved state frame for traps it handles;
	if this structure is not used,
	then the OS must also override (or not use)
	the dependent routines mentioned above.

	The structure elements from {\tt err} down
	corresponds to the basic trap frames
	pushed on the stack by the x86 processor.
	(For traps in which the processor does not push an error code,
	the default trap entrypoint code sets {\tt err} to zero.)
	The structure elements from {\tt esp} down
	are only pushed by traps from lower privilege (rings 1--3),
	and the structure elements from {\tt v86_es} down
	are only pushed by traps from v86 mode.

	The rest of the state frame is pushed manually
	by the default trap entrypoint code.
	The saved integer register state is organized
	in a format compatible with the processor's {\tt PUSHA} instruction.
	However, in the slot that would otherwise hold the pushed {\tt ESP}
	(which is useless since it is the trap handler's stack pointer
	rather than the trapping code's stack pointer),
	the default trap handler saves the {\tt CR2} register
	(page fault linear address) during page faults.

	This trap state structure is borrowed from Mach.
\end{apidesc}

\api{base_trap_init}{initialize the processor trap vectors in the base IDT}
\label{base-trap-init}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

	\funcproto void base_trap_init(void);
\end{apisyn}
\begin{apidesc}
	This function initializes the processor trap vectors in the base IDT
	to the default trap entrypoints defined in {\tt base_trap_inittab}.
\end{apidesc}
\begin{apidep}
	\item[gate_init]		\ref{gate-init}
	\item[base_idt]			\ref{base-idt}
	\item[base_trap_inittab]	\ref{base-trap-inittab}
\end{apidep}

\api{base_trap_inittab}{initialization table for the default trap entrypoints}
\label{base-trap-inittab}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

	{\tt extern struct gate_init_entry \csymbol{base_trap_inittab}[];}
\end{apisyn}
\begin{apidesc}
	This gate initialization table (see Section~\ref{gate-init-h})
	encapsulates the base environment's default trap entrypoint code.
	This module provides IDT entrypoints
	for all of the processor-defined trap vectors;
	each entrypoint pushes a standard state frame on the stack
	(see Section~\ref{trap-state}),
	and then calls the C function pointed to
	by the corresponding entry in {\tt base_trap_handlers} array
	(see Section~\ref{base-trap-handlers}).
	Through these entrypoints, the \oskit{} provides the client OS
	with a convenient, uniform method of handling all processor traps
	in ordinary high-level C code.

	If a trap occurs and the trap entrypoint code
	finds that the corresponding entry in {\tt base_trap_handlers} is null,
	or if it points to a handler routine
	but the handler returns a nonzero value indicating failure,
	the entrypoint code calls {\tt trap_dump_panic}
	(see Section~\ref{trap-dump-panic})
	to dump the register state to the console and panic the kernel.
	This behavior is typically appropriate
	in kernels that do not expect traps to occur during proper operation
	(e.g., boot loaders or embedded operating systems),
	where a trap probably indicates a serious software bug.

	On the other hand, if a trap handler
	{\em is} present and returns success (zero),
	the entrypoint code restores the saved state
	and resumes execution of the trapping code.
	The trap handler may change the contents
	of the {\tt trap_state} structure passed by the entrypoint code;
	in this case, final contents of the structure
	on return from the trap handler
	will be the state restored.

	All of the IDT entries initialized by the {\tt base_trap_inittab}
	are trap gates rather than interrupt gates;
	therefore, if hardware interrupts are enabled when a trap occurs,
	then interrupts will still be enabled during the trap handler
	unless the trap handler explicitly disables them.
	If the OS wants interrupts to be disabled during trap handling,
	it can change the processor trap vectors in the IDT (vectors 0--31)
	into interrupt gates,
	or it can simply use its own trap entrypoint code instead.
\end{apidesc}
\begin{apidep}
	\item[struct trap_state]	\ref{trap-state}
	\item[base_trap_handlers]	\ref{base-trap-handlers}
	\item[trap_dump_panic]		\ref{trap-dump-panic}
\end{apidep}

\api{base_trap_handlers}{Array of handler routines for hardware traps}
\label{base-trap-handlers}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

	{\tt void (*\csymbol{base_trap_handlers}[BASE_TRAP_COUNT])
		(struct~trap_state *{\em ts});}
\end{apisyn}
\begin{apidesc}
	Contains a function pointer for every hardware trap vector.
	By default, all entries in this table point to
	{\tt base_trap_default_handler}, which will simply
	dump the register state to the console and panic.
	The client OS can set entries in this table
	to point to its own trap handler function(s),
	or to alternative trap handlers supplied by the \oskit{},
	such as the remote GDB debugging trap handler, {\tt gdb_trap}
	(see Section~\ref{gdb-trap}).
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the trap state structure to dump.
\end{apiparm}
\begin{apiret}
	The trap handler returns zero (success) to resume execution,
	or nonzero (failure) to cause the entrypoint code
	to dump the register state and panic the kernel.
\end{apiret}

\api{base_trap_default_handler}{default trap handler for unexpected traps}
\label{base-trap-default-handler}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_trap.h}

	\funcproto void base_trap_default_handler(struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	This routine is the default handler for all traps in the base
	environment.  It simply displays displays the trap state
	information and then calls panic.

	It is expected that the client OS will override entries in the {\tt
	base_trap_handlers} array for traps it cares about. Alternatively,
	the client OS may override the {\tt base_trap_default_handler}
	entrypoint entirely.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the processor state at the time of the interrupt.
\end{apiparm}
\begin{apidep}
	\item[struct trap_state]	\ref{trap-state}
\end{apidep}

\api{trap_dump}{dump a saved trap state structure}
\label{trap-dump}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

	\funcproto void trap_dump(const~struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	This function dumps the contents of the specified trap state frame
	to the console using the {\tt printf} function,
	in a simple human-readable form.
	The function is smart enough to determine
	whether the trap occurred from supervisor mode, user mode, or v86 mode,
	and interpret the saved state accordingly.
	For example, for traps from rings 1--3 or from v86 mode,
	the the original stack pointer is part of the saved state frame;
	however, for traps from ring 0,
	the original stack pointer is simply
	the end of the stack frame pushed by the processor,
	since no stack switch occurs in this case.

	In addition, for traps from ring 0,
	this routine also provides a hex dump of the top of the kernel stack
	as it appeared when the trap occurred;
	this stack dump can aid in tracking down the cause of a kernel bug.
	{\tt trap_dump} does not attempt to dump the stack
	for traps from user or v86 mode,
	because there seems to be no sufficiently generic way
	for it to access the appropriate user stack;
	in addition, in this case the trap might have been {\em caused}
	by a user-stack-related exception,
	in which case attempting to dump the user stack
	could lead to a recursive trap.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the trap state structure to dump.
\end{apiparm}
\begin{apidep}
	\item[struct trap_state]	\ref{trap-state}
	\item[printf]			\ref{printf}
\end{apidep}

\api{trap_dump_panic}{dump a saved trap state structure}
\label{trap-dump-panic}
\begin{apisyn}
	\cinclude{oskit/x86/base_trap.h}

	\funcproto void trap_dump_panic(const~struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	This function simply calls {\tt trap_dump} (Section~\ref{trap-dump})
	to dump the specified trap state frame,
	and then calls {\tt panic} (Section~\ref{panic}).
	It is invoked by the default trap entrypoint code
	(Section~\ref{base-trap-inittab})
	if a trap occurs when there is no interrupt handler,
	or if there is an interrupt handler but it returns a failure indication.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the trap state structure to dump.
\end{apiparm}
\begin{apidep}
	\item[trap_dump]		\ref{trap-dump}
	\item[panic]			\ref{panic}
\end{apidep}

\apisec{\intel\ Base Environment: Page Translation}
\label{kern-x86-base-paging}

XXX diagram of function call tree?

	XXX Although a ``base'' x86 paging environment is defined,
	it is not automatically initialized by {\tt base_cpu_init},
	and paging is not activated by {\tt base_cpu_load}.
	This is because unlike segmentation,
	paging is an optional feature on the x86 architecture,
	and many simple ``kernels'' such as boot loaders
	would prefer to ignore it completely.
	Therefore, client kernels that {\em do} want the base paging environment
	must call the functions to initialize and activate it manually,
	after the basic CPU segmentation environment is set up.

	XXX describe assumptions made about use of page tables,
	e.g. 4MB pages whenever possible,
	always modify/unmap _exactly_ the region that was mapped.

XXX assumes that mappings are only changed or unmapped
with the same size and offset as the original mapping.

XXX does not attempt to support page table sharing in any way,
since this code has no clue about the relationship between address spaces;
it only knows about page directories and page tables.

\api{base_paging_init}{create minimal kernel page tables and enable paging}
\label{base-paging-init}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void base_paging_init(void);
\end{apisyn}
\begin{apidesc}
	This function can be used to set up a minimal paging environment.
	It first allocates and clears an initial page directory
	using {\tt ptab_alloc} (see Section~\ref{ptab-alloc}),
	sets {\tt base_pdir_pa} to point to it (see Section~\ref{base-pdir-pa}),
	then direct-maps all known physical memory into this address space
	starting at linear address 0,
	allocating additional page tables as needed.
	Finally, this function enables the processor's paging mechanism,
	using the base page directory as the initial page directory.

	The global variable {\tt phys_mem_max} (see Section~\ref{phys-mem-max})
	is assumed to indicate the top of physical memory;
	all memory from 0 up to {\em at least} this address is mapped.
	The function actually rounds {\tt phys_mem_max} up
	to the next 4MB superpage boundary,
	so that on Pentium and higher processors,
	all physical memory can be mapped using 4MB superpages
	even if known physical memory does not end exactly on a 4MB boundary.
	Note that {\tt phys_mem_max} does not necessarily need to reflect
	all physical memory in the machine;
	for example, it is perfectly reasonable for the client OS
	to set it to some artificially lower value
	so that only that part of physical memory is direct-mapped.

	On Pentium and higher processors,
	this function sets the {\tt PSE} (page size extensions) bit in CR4
	in addition to the {\tt PG} (paging) bit,
	so that the 4MB page mappings used to map physical memory
	will work properly.
\end{apidesc}
\begin{apidep}
	\item[base_pdir_pa]		\ref{base-pdir-pa}
	\item[ptab_alloc]		\ref{ptab-alloc}
	\item[pdir_map_range]		\ref{pdir-map-range}
	\item[base_cpuid]		\ref{base-cpuid}
	\item[paging_enable]		\ref{paging-enable}
\end{apidep}

\api{base_pdir_pa}{initial kernel page directory}
\label{base-pdir-pa}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	{\tt extern oskit_addr_t \csymbol{base_pdir_pa};}
\end{apisyn}
\begin{apidesc}
	This variable is initialized by {\tt base_paging_init}
	(see Section~\ref{base-paging-init})
	to contain the physical address of the base page directory.
	This is the value that should be loaded
	into the processor's page directory base register (CR3)
	in order to run in the linear address space
	defined by this page directory.
	(The base page directory is automatically activated in this way
	during initialization;
	the client OS only needs to load the CR3 register itself
	if it wants to switch among multiple linear address spaces.)
	The {\tt pdir_find_pde} function (Section~\ref{pdir-find-pde})
	and other related functions can be used
	to manipulate the page directory and its associated page tables.

	Initially, the base page directory and its page tables
	directly map physical memory starting at linear address 0.
	The client OS is free to change the mappings after initialization,
	for example by adding new mappings
	outside of the physical address range,
	or by relocating the physical memory mappings
	to a different location in the linear address space
	as described in Section~\ref{base-cpu-setup}.

	Most ``real'' operating systems
	will need to create other, separate page directories
	and associated page tables
	to represent different address spaces or protection domains.
	However, the base page directory may still be useful,
	e.g., as a template for initializing the common kernel portion
	of other page directories,
	or as a ``kernel-only'' address space for use by kernel tasks, etc.
\end{apidesc}

\api{pdir_find_pde}{find an entry in a page directory given a linear address}
\label{pdir-find-pde}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto pd_entry_t *pdir_find_pde(oskit_addr_t pdir_pa,
					     oskit_addr_t la);
\end{apisyn}
\begin{apidesc}
	This primitive macro
	uses the appropriate bits in linear address {\em la} (bits 22--31)
	to look up a particular entry in the specified page directory.
	Note that this function takes the {\em physical} address
	of a page directory,
	but returns a {\em kernel virtual} address
	(i.e., an ordinary pointer to the selected page directory entry).
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory.
	\item[la]
		Linear address to be used to select a page directory entry.
\end{apiparm}
\begin{apiret}
	Returns a pointer to the selected page directory entry.
\end{apiret}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
\end{apidep}

\api{ptab_find_pte}{find an entry in a page table given a linear address}
\label{ptab-find-pte}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto pd_entry_t *ptab_find_pte(oskit_addr_t ptab_pa,
					     oskit_addr_t la);
\end{apisyn}
\begin{apidesc}
	This macro uses the appropriate bits in {\em la} (bits 12--21)
	to look up a particular entry in the specified page table.
	This macro is just like {\tt pdir_find_pde},
	except that it selects an entry
	based on the page table index bits in the linear address
	rather than the page directory index bits (bits 22--31).
	Note that this function takes the {\em physical} address
	of a page table,
	but returns a {\em kernel virtual} address
	(an ordinary pointer).
\end{apidesc}
\begin{apiparm}
	\item[ptab_pa]
		Physical address of the page table.
	\item[la]
		Linear address to be used to select a page table entry.
\end{apiparm}
\begin{apiret}
	Returns a pointer to the selected page table entry.
\end{apiret}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
\end{apidep}

\api{pdir_find_pte}{look up a page table entry from a page directory}
\label{pdir-find-pte}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto pt_entry_t *pdir_find_pte(oskit_addr_t pdir_pa,
					     oskit_addr_t la);
\end{apisyn}
\begin{apidesc}
	This function is a combination of {\tt pdir_find_pde}
	and {\tt ptab_find_pte}:
	it descends through {\em both} levels of the x86 page table hierarchy
	and finds the page table entry for the specified linear address.

	This function assumes that
	if the page directory entry selected by bits 22--31 of {\em la}
	is valid (the {\tt INTEL_PDE_VALID} bit is set),
	then that entry actually refers to a page table,
	and is {\em not} a 4MB page mapping.
	The caller must ensure that this is the case.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory.
	\item[la]
		Linear address to use to select the appropriate
		page directory and page table entries.
\end{apiparm}
\begin{apiret}
	Returns a pointer to the selected page table entry,
	or NULL if there is no page table for this linear address.
\end{apiret}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
\end{apidep}

\api{pdir_get_pte}{retrieve the contents of a page table entry}
\label{pdir-get-pte}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto pt_entry_t pdir_get_pte(oskit_addr_t pdir_pa, oskit_addr_t la);
\end{apisyn}
\begin{apidesc}
	This function is a simple extension of {\tt pdir_find_pte}:
	instead of returning the {\em address} of the selected page table entry,
	it returns the {\em contents} of the page table entry:
	i.e., the physical page frame in bits 12--31
	and the associated {\tt INTEL_PTE_*} flags in bits 0--11.
	If there is no page table in the page directory
	for the specified linear address,
	then this function returns 0,
	the same as if there {\em was} a page table
	but the selected page table entry was zero (invalid).

	As with {\tt pdir_find_pte},
	this function assumes that
	if the page directory entry selected by bits 22--31 of {\em la}
	is valid (the {\tt INTEL_PDE_VALID} bit is set),
	then that entry actually refers to a page table,
	and is {\em not} a 4MB page mapping.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory.
	\item[la]
		Linear address to use to select the appropriate
		page directory and page table entries.
\end{apiparm}
\begin{apiret}
	Returns the selected page table entry,
	or zero if there is no page table for this linear address.
	Also returns zero if the selected page table entry exists but is zero.
\end{apiret}
\begin{apidep}
	\item[pdir_find_pte]	\ref{pdir-find-pte}
\end{apidep}

\api{ptab_alloc}{allocate a page table page and clear it to zero}
\label{ptab-alloc}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto int ptab_alloc(\outparam oskit_addr_t *out_ptab_pa);
\end{apisyn}
\begin{apidesc}
	All of the following page mapping routines
	call this function to allocate new page tables
	as needed to create page mappings.
	It attempts to allocate a single page of physical memory,
	and if successful,
	returns 0 with the physical address of that page in {\tt *out_ptab_pa}.
	The newly allocated page is cleared to all zeros by this function.
	If this function is unsuccessful, it returns nonzero.

	The default implementation of this function
	assumes that the \oskit{}'s minimal C library ({\tt libc})
	and list-based memory manager ({\tt liblmm}) are being used
	to manage physical memory,
	and allocates page table pages from the {\tt malloc_lmm} memory pool
	(see Section~\ref{malloc-lmm}).
	However, in more complete OS environments,
	e.g., in which low physical memory conditions
	should trigger a page-out rather than failing immediately,
	this routine can be overridden to provide the desired behavior.
\end{apidesc}
\begin{apiparm}
	\item[out_ptab_pa]
		The address of a variable of type {\tt oskit_addr_t}
		into which this function will deposit
		the physical address of the allocated page,
		if the allocation was successful.
\end{apiparm}
\begin{apiret}
	Returns zero if the allocation was successful,
	or nonzero on failure.
\end{apiret}
\begin{apidep}
	\item[lmm_alloc_page]	\ref{lmm-alloc-page}
	\item[malloc_lmm]	\ref{malloc-lmm}
	\item[memset]		\ref{memset}
	\item[kvtophys]		\ref{base-vm}
\end{apidep}

\api{ptab_free}{free a page table allocated using ptab_alloc}
\label{ptab-free}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void ptab_free(oskit_addr_t ptab_pa);
\end{apisyn}
\begin{apidesc}
	The page mapping and unmapping functions
	described in the following sections
	call this routine to free a page table that is no longer needed;
	thus, this function is the partner of {\tt ptab_alloc}
	(see Section~\ref{ptab-alloc}).
	The default implementation again assumes
	that the {\tt malloc_lmm} memory pool
	is being used to manage physical memory.
	If the client OS overrides {\tt ptab_alloc}
	to use a different allocation mechanism,
	it should also override {\tt ptab_free} correspondingly.
\end{apidesc}
\begin{apiparm}
	\item[ptab_pa]
		The physical address of the page table page to free.
\end{apiparm}
\begin{apidep}
	\item[lmm_free_page]	\ref{lmm-free-page}
\end{apidep}

\api{pdir_map_page}{map a 4KB page into a linear address space}
\label{pdir-map-page}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto int pdir_map_page(oskit_addr_t pdir_pa, oskit_addr_t la,
				     pt_entry_t mapping);
\end{apisyn}
\begin{apidesc}
	This function creates a single 4KB page mapping
	in the linear address space represented by the specified page directory.
	If the page table covering the specified linear address does not exist
	(i.e., the selected page directory entry is invalid),
	then a new page table is allocated using {\tt ptab_alloc}
	and inserted into the page directory
	before the actual page mapping is inserted into the page table.
	Any new page tables created by this function
	are mapped into the page directory with permissions
	{\tt INTEL_PTE_USER | INTEL_PTE_WRITE}:
	full permissions are granted at the page directory level,
	although the specified {\em mapping} value,
	which is inserted into the selected page table entry,
	may restrict permissions at the individual page granularity.

	This function assumes that
	if the page directory entry selected by bits 22--31 of {\em la}
	is valid (the {\tt INTEL_PDE_VALID} bit is set),
	then that entry actually refers to a page table,
	and is {\em not} a 4MB page mapping.
	In other words,
	the caller should not attempt to create a 4KB page mapping
	in a part of the linear address space
	already covered by a valid 4MB superpage mapping.
	The caller must first unmap the 4MB superpage mapping,
	{\em then} map the 4KB page
	(which will cause a page table to be allocated).
	If the caller follows the guidelines
	described in Section~\ref{kern-x86-base-paging},
	then this requirement should not be a problem.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		acting as the root of the linear address space
		in which to make the requested page mapping.
	\item[la]
		Linear address at which to make the mapping.
		Only bits 12--31 are relevant to this function;
		bits 0--11 are ignored.
	\item[mapping]
		Contains the page table entry value
		to insert into the appropriate page table entry:
		the page frame number is in bits 12--31,
		and the {\tt INTEL_PTE_*} flags are in bits 0--11.
		XXX The caller {\em must} include {\tt INTEL_PTE_VALID};
		other flags may be set according to the desired behavior.
		(To unmap pages, use {\tt pdir_unmap_page} instead;
		see Section~\ref{pdir-unmap-page})
\end{apiparm}
\begin{apiret}
	If all goes well and the mapping is successful,
	this function returns zero.
	If this function needed to allocate a new page table
	but the {\tt ptab_alloc} function failed (returned nonzero),
	then this function passes back the return value from {\tt ptab_alloc}.
\end{apiret}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
	\item[ptab_alloc]	\ref{ptab-alloc}
\end{apidep}

\api{pdir_unmap_page}{unmap a single 4KB page mapping}
\label{pdir-unmap-page}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void pdir_unmap_page(oskit_addr_t pdir_pa, oskit_addr_t la);
\end{apisyn}
\begin{apidesc}
	This function invalidates a single 4KB page mapping
	in the linear address space represented by the specified page directory.
	The {\em la} parameter should fall in a page previous mapped with
	{\tt pdir_map_page}, otherwise the result of the call is undefined.
	XXX Is this overly restrictive?

	This function assumes that
	if the page directory entry selected by bits 22--31 of {\em la}
	is valid (the {\tt INTEL_PDE_VALID} bit is set),
	then that entry actually refers to a page table,
	and is {\em not} a 4MB page mapping.
	In other words,
	the caller should not attempt to destroy a 4KB page mapping
	in a part of the linear address space
	covered by a valid 4MB superpage mapping.
	Use {\tt pmap_unmap_range} to remove a 4MB superpage mapping.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		acting as the root of the linear address space
		from which the requested page mapping is to be removed.
	\item[la]
		Linear address contained in the page to be removed.
		Only bits 12--31 are relevant to this function;
		bits 0--11 are ignored.
\end{apiparm}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
	\item[ptab_free]	\ref{ptab-free}
\end{apidep}

\api{pdir_map_range}{map a contiguous range of physical addresses}
\label{pdir-map-range}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto int pdir_map_range(oskit_addr_t pdir_pa, oskit_addr_t la,
				      oskit_addr_t pa,
				      oskit_size_t size, pt_entry_t mapping_bits);
\end{apisyn}
\begin{apidesc}
	This function maps a range of linear addresses
	in the linear address space represented by the specified page directory
	onto a contiguous range of physical addresses.
	The linear (source) address, physical (destination) address,
	and mapping size must be multiples of the 4KB architectural page size,
	but other than that no restrictions are imposed
	on the location or size of the mapping range.
	If the processor description in the global {\tt base_cpuid} variable
	(see Section~\ref{base-cpuid})
	indicates that page size extensions are available,
	and the physical and linear addresses are properly aligned,
	then this function maps as much of the range as possible
	using 4MB superpage mappings instead of 4KB page mappings.
	Where 4KB page mappings are needed,
	this function allocates new page tables as necessary
	using {\tt ptab_alloc}.
	Any new page tables created by this function
	are mapped into the page directory with permissions
	{\tt INTEL_PTE_USER | INTEL_PTE_WRITE}:
	full permissions are granted at the page directory level,
	although the {\tt mapping_bits} may specify more restricted permissions
	for the actual page mappings.

	This function assumes that
	no valid mappings already exist in the specified linear address range;
	if any mappings {\em do} exist, this function may not work properly.
	If the caller follows the guidelines
	described in Section~\ref{kern-x86-base-paging},
	always unmapping previous mappings before creating new ones,
	then this requirement should not be a problem.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		acting as the root of the linear address space
		in which to make the requested mapping.
	\item[la]
		Starting linear address at which to make the mapping.
		Must be page-aligned.
	\item[pa]
		Starting physical address to map to.
		Must be page-aligned.
	\item[size]
		Size of the linear-to-physical mapping to create.
		Must be page-aligned.
	\item[mapping_bits]
		Permission bits to OR into each page or superpage mapping entry.
		The caller {\em must} include {\tt INTEL_PTE_VALID};
		other flags may be set according to the desired behavior.
		(To unmap ranges, use {\tt pdir_unmap_range} instead;
		see Section~\ref{pdir-unmap-range})
\end{apiparm}
\begin{apiret}
	If all goes well and the mapping is successful,
	this function returns zero.
	If this function needed to allocate a new page table
	but the {\tt ptab_alloc} function failed (returned nonzero),
	then this function passes back the return value from {\tt ptab_alloc}.
\end{apiret}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
	\item[ptab_alloc]	\ref{ptab-alloc}
	\item[base_cpuid]	\ref{base-cpuid}
\end{apidep}

\api{pdir_prot_range}{change the permissions on a mapped memory range}
\label{pdir-prot-range}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void pdir_prot_range(oskit_addr_t pdir_pa, oskit_addr_t la,
					oskit_size_t size,
					pt_entry_t new_mapping_bits);
\end{apisyn}
\begin{apidesc}
	This function can be used
	to modify the permissions and other attribute bits
	associated with a mapping range
	previously created with {\tt pdir_map_range}.
	The {\em la} and {\em size} parameters
	must be {\em exactly} the same as those passed
	to the {\tt pdir_map_range} used to create the mapping.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		acting as the root of the linear address space
		containing the mapping to modify.
	\item[la]
		Starting linear address of the mapping to modify.
		Must be exactly the same as the address
		specified to the {\tt pdir_map_range} call
		used to create this mapping.
	\item[size]
		Size of the mapping to modify.
		Must be exactly the same as the size
		specified to the {\tt pdir_map_range} call
		used to create this mapping.
	\item[new_mapping_bits]
		New permission flags to insert
		into each page or superpage mapping entry.
		The caller {\em must} include {\tt INTEL_PTE_VALID};
		other flags may be set according to the desired behavior.
		(To unmap ranges, use {\tt pdir_unmap_range};
		see Section~\ref{pdir-unmap-range})
\end{apiparm}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
\end{apidep}

\api{pdir_unmap_range}{remove a mapped range of linear addresses}
\label{pdir-unmap-range}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void pdir_unmap_range(oskit_addr_t pdir_pa, oskit_addr_t la,
					 oskit_size_t size);
\end{apisyn}
\begin{apidesc}
	This function removes a mapping range
	previously created using {\tt pdir_map_range}.
	The {\em la} and {\em size} parameters
	must be {\em exactly} the same as those passed
	to the {\tt pdir_map_range} used to create the mapping.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		acting as the root of the linear address space
		containing the mapping to destroy.
	\item[la]
		Starting linear address of the mapping to destroy.
		Must be exactly the same as the address
		specified to the {\tt pdir_map_range} call
		used to create this mapping.
	\item[size]
		Size of the mapping to destroy.
		Must be exactly the same as the size
		specified to the {\tt pdir_map_range} call
		used to create this mapping.
\end{apiparm}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
\end{apidep}

\api{pdir_clean_range}{free unused page table pages in a page directory}
\label{pdir-clean-range}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void pdir_clean_range(oskit_addr_t pdir_pa,
			                 oskit_addr_t la, oskit_size_t size);
\end{apisyn}
\begin{apidesc}
	This function scans the portion of the given page directory
	covering the given address range, looking for associated
	page table pages that are unnecessary and frees them.
	``Unnecessary'' page table pages are those which contain only entries
	for which {\tt INTEL_PTE_VALID} is not set.
	These pages are freed with {\tt ptab_free} and the corresponding page
	directory entries marked as invalid.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory.
	\item[la]
		Starting linear address of the region to clean.
		Must be page-aligned.
	\item[size]
		Size (in bytes) of the region to clean.
		The value passed is rounded up to whole pages.
		Use ``0'' for {\em la} and ``~(oskit_addr_t)0'' for
		{\em size} to clean the entire page directory.
\end{apiparm}
\begin{apidep}
	\item[pdir_find_pde]	\ref{pdir-find-pde}
	\item[ptab_find_pte]	\ref{ptab-find-pte}
	\item[ptab_free]	\ref{ptab-free}
\end{apidep}

\api{pdir_dump}{dump the contents of a page directory and all its page tables}
\label{pdir-dump}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void pdir_dump(oskit_addr_t pdir_pa);
\end{apisyn}
\begin{apidesc}
	This function is primarily intended for debugging purposes:
	it dumps the mappings described by the specified page directory
	and all associated page tables
	in a reasonably compact, human-readable form,
	using {\tt printf}.
	4MB superpage as well as 4KB page mappings are handled properly,
	and contiguous ranges of identical mappings
	referring to successive physical pages or superpages
	are collapsed into a single line for display purposes.
	The permissions and other page directory/page table entry flags
	are expanded out as human-readable flag names.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page directory
		describing the linear address space to dump.
\end{apiparm}
\begin{apidep}
	\item[ptab_dump]	\ref{ptab-dump}
	\item[printf]		\ref{printf}
	\item[phystokv]		\ref{base-vm}
\end{apidep}

\api{ptab_dump}{dump the contents of a page table}
\label{ptab-dump}
\begin{apisyn}
	\cinclude{oskit/x86/base_paging.h}

	\funcproto void ptab_dump(oskit_addr_t ptab_pa, oskit_addr_t base_la);
\end{apisyn}
\begin{apidesc}
	This is primarily a helper function for {\tt pdir_dump},
	but it can also be used independently,
	to dump the contents of an individual page table.
	For output purposes,
	the page table is assumed to reside at {\em base_la}
	in ``some'' linear address space:
	in other words, this parameter provides the topmost ten bits
	in the linear addresses dumped by this routine.
	Contiguous ranges of identical mappings
	referring to successive physical pages
	are collapsed into a single line for display purposes.
	The permissions and other page directory/page table entry flags
	are expanded out as human-readable flag names.
\end{apidesc}
\begin{apiparm}
	\item[pdir_pa]
		Physical address of the page table to dump.
	\item[base_la]
		Linear address at which this page table resides,
		for purposes of displaying linear source addresses.
		Must be 4MB aligned.
\end{apiparm}
\begin{apidep}
	\item[printf]		\ref{printf}
	\item[phystokv]		\ref{base-vm}
\end{apidep}


\apisec{\intel\ Base Environment: Protected-mode entry and exit}
\label{i16-raw}
\label{kern-x86-base-lastsection}

\emph{
The full mode switching code is written and functional
but not yet documented or integrated into the \oskit\ source tree.
%The source code implementing this functionality
%can currently be found in the \oskit\ ``source'' subdirectory
%containing unintegrated code,
%in source/x86/pc/i16 and related directories.}
% XX This directory does not exist!
% can currently be found in the Mach 4 distribution
% in the mach4-i386/kernel/pc/i16 directory and related directories.
}

\com{ XXX relevant to 16-bit startup support

If use multiboot, then can just use it.

This stuff is not integrated, in raw form in source directory.
If use anything in the source directory should only use it
as an example.  Better to look at in the Mach


\begin{verbatim}
raw_switch:

        Provides the code to switch between real and protected mode.
        Switches between the environments ``completely'':
        e.g. when switching to protected mode,
        all the normal protected-mode state for that environment is set up.

raw_pmode:

        i16_raw_enter_pmode()
                Enters protected mode from real mode.
                Does not initialize IDT or TSS or anything else;
                just gets the system into protected mode
                with a simple temporary GDT.
                Returns with interrupts turned off
                (and they'd better stay off until there's a valid pmode IDT!)

        i16_raw_leave_pmode()
                Assumes paging is turned off.
                Returns with interrupts turned off;
                they can probably be turned back on at any time.

        Depends on:
                i16_die()
                A20 enable/disable code (e.g. raw_a20).
                gdt.h: KERNEL_16_CS, KERNEL_16_DS



vm_param.h:

        Must export kvtolin(), lintokv()

i16_raw.c:
        Provides a default implementation
        of real/pmode switching code.
        Assumes that, as far as it's concerned,
        low linear address always map to physical addresses.
        (The low linear mappings can be changed,
        but must be changed back before switching back to real mode.)

        Provides:
                i16_raw_switch_to_pmode()
                i16_raw_switch_to_real_mode()

                i16_raw_start()
                        Called in real mode.
                        Initializes the pmode switching system,
                        switches to pmode for the first time,
                        and calls the 32-bit function raw_start().

        Depends on:

                paging.h:
                        raw_paging_enable()
                        raw_paging_disable()
                        raw_paging_init()

                a20.h:
                        i16_enable_a20()
                        i16_disable_a20()

                real.h:
                        real_cs

\end{verbatim}

}%com

\apisec{\intelpc\ Base Environment: Physical Memory Management}
\label{phys-lmm}
\label{kern-x86pc-base-phys}
\label{kern-x86pc-base-firstsection}

The physical memory address space on PCs is divided into distinct regions
which have certain attributes.
The lowest 1MB of physical memory is ``special''
in that only it can be accessed from real mode.
The lowest 16MB of physical memory is special
in that only it can be accessed by the built-in DMA controller.
On some PCs, there may be an additional boundary imposed by the motherboard.
Memory above this boundary (e.g., 64MB) may not be cacheable by the L2 cache.
The base environment uses the \oskit{} LMM library~\ref{lmm} to accommodate
these differences.
Physical memory is managed by a single LMM {\tt malloc_lmm} with separate
regions for each ``type'' of memory.
Hence, LMM allocation requests can be made with appropriate flag values to
obtain memory with the desired characteristics.

\api{phys_lmm.h}{Physical memory management for PCs}
\label{phys-lmm-h}
\begin{apisyn}
	\cinclude{oskit/x86/pc/phys_lmm.h}
\end{apisyn}
\begin{apidesc}
	There are three priority values assigned to regions of
	physical memory as they are made available at boot time
	(via {\tt lmm_add_region}).
	In increasing order of priority
	(i.e., increasing preference for allocation):
	\begin{csymlist}
	\item[LMM_PRI_1MB]		\ttindex{LMM_PRI_1MB}
		For physical memory below 1MB.
	\item[LMM_PRI_16MB]		\ttindex{LMM_PRI_16MB}
		For physical memory below 16MB.
	\item[LMM_PRI_HIGH]		\ttindex{LMM_PRI_HIGH}
		For physical memory above 16MB.
	\end{csymlist}
	These priorities prevent the simple memory allocation interfaces
	from handing out the more precious low-address memory.
	To enable savvy applications to explicitly allocate memory of a
	given type, the following flag values are assigned at boot time
	and can be passed to LMM allocation routines:
	\begin{csymlist}
	\item[LMMF_1MB]		\ttindex{LMMF_1MB}
		Set on memory below 1MB;
		i.e., the {\tt LMM_PRI_1MB} region.
	\item[LMMF_16MB]	\ttindex{LMMF_16MB}
		Set on memory below 16MB;
		i.e., the {\tt LMM_PRI_1MB} and {\tt LMM_PRI_16MB} regions.
	\end{csymlist}
	Thus, if neither flag is set, memory can be allocated from any of the
	three regions with preference given to {\tt LMM_PRI_HIGH}, followed
	by {\tt LMM_PRI_16MB} and {\tt LMM_PRI_1MB}.
	If just {LMMF_16MB} is set, memory can be allocated from either
	{\tt LMM_PRI_16MB} or {\tt LMM_PRI_1MB} in that order.
	If both flags are set, memory can only be allocated from the
	{\tt LMM_PRI_1MB} region.
\end{apidesc}

\api{phys_mem_max}{Highest physical memory address}
\label{phys-mem-max}
\begin{apisyn}
	\cinclude{oskit/x86/pc/phys_lmm.h}

	{\tt extern oskit_addr_t \csymbol{phys_mem_max};}
\end{apisyn}
\begin{apidesc}
	This variable records the highest physical memory address;
	i.e. the end address of the highest free block added to
	{\tt malloc_lmm}.
	This is the highest address that the kernel should ever have to
	deal with.

	Not all addresses between 0 and {\tt phys_mem_max} are necessarily
	available for allocation, there may be holes in the available physical
	memory space.
\end{apidesc}

\api{phys_lmm_init}{Initialize kernel physical memory LMM}
\label{phys-lmm-init}
\begin{apisyn}
	\cinclude{oskit/x86/pc/phys_lmm.h}

	\funcproto void phys_lmm_init(void);
\end{apisyn}
\begin{apidesc}
	This routine sets up {\tt malloc_lmm} with three physical
	memory regions, one for each of the memory types described in
	{\tt phys_lmm.h}.
	No actual memory is added to those regions.
	You can then call phys_lmm_add() to add memory to those regions.
	In the base environment, {\tt base_multiboot_init_mem} handles
	this chore.
\end{apidesc}
\begin{apidep}
	\item[malloc_lmm]	\ref{malloc-lmm}
	\item[lmm_add_region]	\ref{lmm-add-region}
	\item[phystokv]		\ref{phystokv}
\end{apidep}

\api{phys_lmm_add}{Add memory to the kernel physical memory LMM}
\label{phys-lmm-add}
\begin{apisyn}
	\cinclude{oskit/x86/pc/phys_lmm.h}

	\funcproto void phys_lmm_add(oskit_addr_t min_pa, oskit_size_t size);
\end{apisyn}
\begin{apidesc}
	Add a chunk of physical memory to the appropriate region(s)
	on the {\tt malloc_lmm}.
	The provided memory block may be arbitrarily aligned
	and may cross region boundaries (e.g. the 16MB boundary);
	it will be shrunken and split apart as necessary.
	If the address of the end of the block is greater than the current
	value in {\tt phys_max_mem}, this address is recorded.

	Note that {\tt phys_lmm_add} takes a {\em physical} address,
	not a virtual address as the underlying LMM routines do.
	This routine will perform the conversion as needed with {\tt phystokv}.
\end{apidesc}
\begin{apiparm}
	\item[min_pa]
		Physical address of the start of the chunk being added.
	\item[size]
		Size in bytes of the chunk being added.
\end{apiparm}
\begin{apidep}
	\item[malloc_lmm]	\ref{malloc-lmm}
	\item[lmm_add_free]	\ref{lmm-add-free}
	\item[phystokv]		\ref{phystokv}
	\item[phys_mem_max]	\ref{phys-mem-max}
\end{apidep}


\apisec{\intelpc\ Base Environment: Interrupt Support}
\label{kern-x86pc-base-irq}

In the base environment,
each hardware interrupt vector in the processor IDT
points to a small assembly language stub
that saves a standard trap frame (\ref{trap-state}),
disables and acknowledges the hardware interrupt,
and calls a designated high-level handler routine specified
in the {\tt base_irq_handlers} table (\ref{base-irq-handlers}).
Initially, all the entries in this table point to
{\tt base_irq_default_handler} (\ref{base-irq-default-handler}).
Custom interrupt handlers can be installed by changing
the appropriate entry in the table.
The default action for all interrupts can be changed by overriding
{\tt base_irq_default_handler}.

The base environment also includes support for a single
``software interrupt.''  A software interrupt is delivered
after all pending hardware interrupts have been processed but
before returning from the interrupt context.  A software
interrupt can be posted at any time with
{\tt base_irq_softint_request} (\ref{base-irq-softint-request})
but will only be triggered upon return from a hardware interrupt;
i.e., processing of a software interrupt requested from a
non-interrupt context is deferred until a hardware interrupt occurs.
The software interrupt handler is {\tt base_irq_softint_handler}
(\ref{base-irq-softint-handler}) which can be replaced by a custom
version provided by the kernel.

\api{base_irq.h}{Hardware interrupt definitions for standard PCs}
\label{base-irq-h}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}
\end{apisyn}
\begin{apidesc}
	\begin{csymlist}
	\item[BASE_IRQ_COUNT]		\ttindex{BASE_IRQ_COUNT}
		Number of interrupt request lines.
	\item[BASE_IRQ_MASTER_BASE]	\ttindex{BASE_IRQ_MASTER_BASE}
		Default location in the IDT for programming the PIC.
	\item[BASE_IRQ_SLAVE_BASE]	\ttindex{BASE_IRQ_SLAVE_BASE}
		Default location in the IDT for programming the PIC.
	\item[irq_master_base]		\ttindex{irq_master_base}
		Variable storing the current master PIC interrupt vector base.
	\item[irq_slave_base]		\ttindex{irq_slave_base}
		Variable storing the current slave PIC interrupt vector base.
	\item[fill_irq_gate(irq_num, entry, selector, access)]
		\ttindex{fill_irq_gate}
		Fill the {\tt base_idt} descriptor for the indicated IRQ
		with an interrupt gate containing the given entry,
		selector and access information.
	\end{csymlist}
\end{apidesc}

\api{base_irq_handlers}{Array of handler routines for hardware interrupts}
\label{base-irq-handlers}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	{\tt void (*\csymbol{base_irq_handlers}[BASE_IRQ_COUNT])
		(struct~trap_state *{\em ts});}
\end{apisyn}
\begin{apidesc}
	Contains a function pointer for every hardware interrupt vector.
	By default, all entries in this table point to
	{\tt base_irq_default_handler}.
	Custom interrupt handlers can be installed by changing the appropriate
	table entry.

	Interrupt handlers can freely examine and modify the processor state
	(\ref{trap-state})
	of the interrupted activity, e.g., to implement threads and preemption.
	On entry, the processor's IDT interrupt vector number is in
	{\tt ts->trapno} and the hardware IRQ number that caused the
	interrupt is in {\tt ts->err}.
\end{apidesc}
\begin{apidep}
	\item[base_irq_default_handler]	\ref{base-irq-default-handler}
\end{apidep}

\api{base_irq_init}{Initialize hardware interrupts}
\label{base-irq-init}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	\funcproto void base_irq_init(void);
\end{apisyn}
\begin{apidesc}
	Initializes the system to properly handle hardware interrupts.
	It loads the appropriate entries in the base IDT (\ref{base-idt})
	with the gate descriptor information from {\tt base_irq_inittab},
	programs the PICs to the standard vector base addresses
	(see Section~\ref{base-irq-h}), and disables all interrupt request
	lines.

	Processor interrupts must be disabled when this routine
	is called.

	NOTE: This routine no longer enables interrupts!
\end{apidesc}
\begin{apidep}
	\item[base_idt]		\ref{base-idt}
	\item[base_irq_inittab]	\ref{base-irq-inittab}
	\item[gate_init]	\ref{gate-init}
	\item[pic_init]		\ref{pic-init}
	\item[pic_disable_all]	\ref{pic-disable-all}
	\item[irq_master_base]	\ref{base-irq-h}
	\item[irq_slave_base]	\ref{base-irq-h}
\end{apidep}

\api{base_irq_inittab}{initialization table for default interrupt entrypoints}
\label{base-irq-inittab}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	{\tt extern struct gate_init_entry \csymbol{base_irq_inittab}[];}
\end{apisyn}
\begin{apidesc}
	This gate initialization table (\ref{gate-init-h})
	encapsulates the base environment's default interrupt entrypoint code.
	This module provides IDT entrypoints
	for all the standard PC hardware interrupt vectors;
	each entrypoint pushes a standard state frame on the stack
	(\ref{trap-state}),
	disables and acknowledges the hardware interrupt,
	and then calls the C handler function pointed to
	by the appropriate entry of the {\tt base_irq_handlers} array
	(\ref{base-irq-handlers}).
	Upon return from the handler, the interrupt code checks for a pending
	software interrupt and dispatches to {\tt base_irq_softint_handler}.
\end{apidesc}
\begin{apidep}
	\item[base_irq_handlers]	\ref{base-irq-handlers}
	\item[base_irq_nest]		\ref{base-irq-nest}
	\item[base_irq_softint_handler]	\ref{base-irq-softint-handler}
\end{apidep}

\api{base_irq_default_handler}{default IRQ handler for unexpected interrupts}
\label{base-irq-default-handler}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	\funcproto void base_irq_default_handler(struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	This routine is the default handler for all interrupts in the base
	environment.  It simply displays a warning message and returns.

	It is expected that the client OS will override this default
	behavior for all interrupts it cares about, leaving this routine
	to be called only for unexpected interrupts.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the processor state at the time of the interrupt.
\end{apiparm}
\begin{apidep}
	\item[struct trap_state]	\ref{trap-state}
	\item[printf]			\ref{printf}
\end{apidep}

%XXX software interrupt stuff.  Still valid?
\api{base_irq_nest}{interrupt nesting counter and software interrupt flag}
\label{base-irq-nest}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	{\tt extern unsigned char \csymbol{base_irq_nest};}
\end{apisyn}
\begin{apidesc}
	Hardware interrupt nesting counter,
	used to ensure that the software interrupt handler isn't called
	until all outstanding hardware interrupts have been processed.
	In addition, this variable also acts as the software interrupt
	pending flag:
	if the high bit is clear, a software interrupt is pending.
\end{apidesc}

\api{base_irq_softint_request}{request a software interrupt}
\label{base-irq-softint-request}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	\funcproto void base_irq_softint_request(void);
\end{apisyn}
\begin{apidesc}
	This routine requests a software interrupt and is typically
	called from a hardware interrupt handler to schedule
	lower priority processing.

	After requesting a software interrupt,
	{\tt base_irq_softint_handler} will be called when all hardware
	interrupt handlers have completed processing and
	{\tt base_irq_nest} is zero.
	If an interrupt is scheduled from a non-interrupt context,
	the handler will not be called until the next hardware interrupt
	occurs and has been processed.

	Only a single software interrupt may be pending at a time.
\end{apidesc}
\begin{apidep}
	\item[base_irq_nest]	\ref{base-irq-nest}
\end{apidep}

\api{base_irq_softint_handler}{handler for software interrupts}
\label{base-irq-softint-handler}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_irq.h}

	\funcproto void base_irq_softint_handler(struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	Software interrupt handler called by the interrupt entry/exit
	stub code when a software interrupt has been requested and
	needs to be run.
	The default implementation of this routine simply returns;
	to use software interrupts, the kernel must override it.

	The handler is free to examine and modify the processor state
	in {\tt state}.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the processor state at the time of the interrupt.
\end{apiparm}
\begin{apidep}
	\item[struct trap_state]	\ref{trap-state}
\end{apidep}


\apisec{\intelpc\ Base Environment: Console Support}
\label{kern-x86pc-base-console}
\label{kern-x86pc-base-lastsection}

The base console environment allows ``console'' input and output using either
the display and keyboard or a serial line.
Additionally it allows a remote kernel debugging with GDB over a serial line.
Selection of the display or serial port as console and which serial ports to
use for the console and GDB are controlled by
command line options or environment variables as described in this section.

The base console environment uses a simple polled interface for serial port
input and output as well as for keyboard input.
The video display output interface is a simple, dumb text terminal.
See the appropriate sections for details.

In the base interface, all input via \texttt{stdin}
(e.g., \texttt{getchar}, \texttt{scanf})
and all output via \texttt{stdout} or \texttt{stderr}
(e.g., \texttt{putchar}, \texttt{printf})
use the console.

For simplicity, a set of vanilla console functions is provided that direct
input and output to/from the appropriate device. For example, {\tt
console_putchar} will invoke {\tt com_cons_putchar} if the console device
is a serial port, or {\tt direct_cons_putchar} if the console device is a
display. Other vanilla console I/O routines include {\tt console_getchar},
{\tt console_puts}, and {\tt console_putbytes} (a raw block output function
that does not append a newline). All behave as expected. These routines are
provided to so that higher level I/O code does not need to be concerned
with which type of device is currenty the console. Both the minimal C
library (section \ref{libc}) and the \freebsd{} C library (section
\ref{freebsd-libc}) take advantage of this redirection.

\api{base_console.h}{definitions for base console support}
\label{base-console}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_console.h}
\end{apisyn}
\begin{apidesc}
The following variable are used in the base_console code:
\begin{csymlist}
	\item[serial_console]	\ttindex{serial_console}
		Set non-zero if a serial port is being used as the console.
		Default value is zero, but may be turned on by either a
		command line option or the \texttt{CONS_COM} environment
		variable.
	\item[cons_com_port]	\ttindex{cons_com_port}
		If \texttt{serial_console} is non-zero, this variable
		indicates the COM port to use for console input and output.
		Default value is 1, but may be changed by setting the
		\texttt{CONS_COM} environment variable.
		Possible values are 1, 2, 3 or 4.
	\item[enable_gdb]	\ttindex{enable_gdb}
		If non-zero, enables the GDB trap handler;
		i.e. makes remote debugging possible.
		The default value is zero.
	\item[gdb_com_port]	\ttindex{gdb_com_port}
		If \texttt{enable_gdb} is non-zero, this variable
		indicates the COM port to use for remote GDB interaction.
		The default value is 1
		(the console and remote GDB can share the same serial port,
		but do not have to).
		Possible values are 1, 2, 3 or 4.
\end{csymlist}
Refer to section ~\ref{base-console-init} for more information on command
line options and environment variables.
See section~\ref{gdb} for more on remote GDB.
\end{apidesc}

\api{base_console_init}{Initialize the base console}
\label{base-console-init}
\begin{apisyn}
	\cinclude{oskit/x86/base_console.h}

	\funcproto void base_console_init(int argc, char **argv);
\end{apisyn}
\begin{apidesc}
	This function parses the multiboot command line and
	optionally initializes the serial lines.

	Command line options recognized by the base_console code include:
	\begin{itemize}
	\item[-f]
		Enables ``fast'' serial ports.
		Sets the baud rate of the console and GDB serial ports
		to 115200.
	\item[-h]
		Enables a serial line console on \texttt{cons_com_port}.
	\item[-d]
		Enables remote GDB on \texttt{gdb_com_port}.
	\end{itemize}

	Environment variables recognized include:
	\begin{csymlist}
	\item[CONS_COM]
		Serial port number (1, 2, 3 or 4) to use as the console.
		Sets \texttt{cons_com_port} to this value and sets
		\texttt{serial_console} non-zero.
	\item[GDB_COM]
		Serial port number (1, 2, 3 or 4) to use as the
		remote GDB interface.
		Sets \texttt{gdb_com_port} to this value and sets
		\texttt{enable_gdb} non-zero.
	\item[BAUD]
		Baud rate to use for both the console and GDB serial ports.
		Any of the standard values in \texttt{termios.h}
		(section~\ref{termios-h}) are valid.
	\end{csymlist}
\end{apidesc}
\begin{apiparm}
	\item[argc]
		Count of command line arguments in \emph{argv}.
	\item[argv]
		Vector of command line arguments.
\end{apiparm}
\begin{apidep}
	\item[getenv]		\ref{getenv}
	\item[atoi]		\ref{atoi}
	\item[base_cooked_termios]	\ref{base-cooked-termios}
	\item[base_raw_termios]	\ref{base-raw-termios}
	\item[strcmp]		\ref{strcmp}
	\item[printf]		\ref{printf}
	\item[base_gdt_load]	\ref{base-gdt-load}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[com_cons_init]	\ref{com-cons-init}
	\item[com_cons_flush]	\ref{com-cons-flush}
	\item[com_cons_getchar]	\ref{com-cons-getchar}
	\item[com_cons_putchar]	\ref{com-cons-putchar}
	\item[gdb_pc_com_init]	\ref{gdb-pc-com-init}
	\item[gdb_serial_getchar]	\ref{gdb-serial-getchar}
	\item[gdb_serial_putchar]	\ref{gdb-serial-putchar}
	\item[gdb_serial_puts]	\ref{gdb-serial-puts}
	\item[gdb_serial_exit]	\ref{gdb-serial-exit}
	\item[direct_cons_getchar]	\ref{direct-cons-getchar}
	\item[direct_cons_putchar]	\ref{direct-cons-putchar}
\end{apidep}

\api{base_cooked_termios}{Default {\tt termios} setting for cooked-mode console}
\label{base-cooked-termios}
\begin{apisyn}
	\cinclude{termios.h}

	{\tt extern struct termios \csymbol{base_cooked_termios};}
\end{apisyn}
\begin{apidesc}
	A \posix{} {\tt termios} structures with values suitable for a
	basic cooked-mode console tty.
	Used in the base environment when initializing a serial-port
	console in {\tt com_cons_init}.
\end{apidesc}
\begin{apidep}
	\item[termios.h]	\ref{termios-h}
\end{apidep}

\api{base_raw_termios}{Default {\tt termios} setting for raw-mode console}
\label{base-raw-termios}
\begin{apisyn}
	\cinclude{termios.h}

	{\tt extern struct termios \csymbol{base_raw_termios};}
\end{apisyn}
\begin{apidesc}
	A \posix{} {\tt termios} structures with values suitable for a
	basic raw-mode console tty.
	Used in the base environment when initializing a serial-port
	for remote GDB debuging in {\tt com_cons_init}.
\end{apidesc}
\begin{apidep}
	\item[termios.h]	\ref{termios-h}
\end{apidep}

\api{direct_cons_getchar}{wait for and read a character from the keyboard}
\label{direct-cons-getchar}
\begin{apisyn}
	\cinclude{oskit/x86/pc/direct_console.h}

	\funcproto int direct_cons_getchar(void);
\end{apisyn}
\begin{apidesc}
	Read a character from the PC keyboard.
	If none is available, this routine loops polling the keyboard status
	register until a character is available.

	Supports only a subset of the available key presses.
	In particular, only the shifted and unshifted printable ASCII
	characters along with Escape, Backspace, Tab, and Carriage return.
	It does not support the remaining control characters or multi-character
	(function) keys.
\end{apidesc}
\begin{apiret}
	Returns the character read.
\end{apiret}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[inb]	\ref{inb}
\end{apidep}

\api{direct_cons_putchar}{write a character to the video console}
\label{direct-cons-putchar}
\begin{apisyn}
	\cinclude{oskit/x86/pc/direct_console.h}

	\funcproto void direct_cons_putchar(unsigned~char c);
\end{apisyn}
\begin{apidesc}
	Outputs the indicated character on the video console.
	Handles
	``\verb|\|n'' (newline),
	``\verb|\|r'' (carriage return),
	``\verb|\|b'' (backspace), and
	``\verb|\|t'' (tab)
	in addition to printable ASCII characters.
	Tabs are expanded to spaces (with stops are every 8 columns)
	and lines are automatically wrapped at 80 characters.
	Newline implies a carriage return.
\end{apidesc}
\begin{apiparm}
	\item[c]
		Character to be printed.
\end{apiparm}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[phystokv]			\ref{phystokv}
	\item[outb_p]			\ref{outb-p}
	\item[memcpy]			\ref{memcpy}
\end{apidep}

\api{direct_cons_trygetchar}{read an available character from the keyboard}
\label{direct-cons-trygetchar}
\begin{apisyn}
	\cinclude{oskit/x86/pc/direct_console.h}

	\funcproto int direct_cons_trygetchar(void);
\end{apisyn}
\begin{apidesc}
	Quick poll for an available input character.
	Returns a character or -1 if no character was available.

	Due to the large delay between when a character is typed
	and when the scan code arrives at the keyboard controller (4-5 ms),
	there are a variety of situations in which this routine may
	return -1 even though a character has been typed:
	\begin{itemize}
	\item	a valid scan code is in transit from the keyboard when called
	\item	a key release scan code is received
		(from a previous key press)
	\item	a SHIFT key press is received
		(shift state is updated however)
	\item	a key press for a multi-character sequence is received
		(e.g., CTRL or a function key)
	\end{itemize}
	In other words, this routine never delays in an attempt to wait
	for the next scan code to arrive when one is not currently available.
	Hence the utility of this routine is questionable.
\end{apidesc}
\begin{apiret}
	Returns a character if available, -1 otherwise.
\end{apiret}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[inb]	\ref{inb}
\end{apidep}

\api{com_cons_init}{initialize a serial port}
\label{com-cons-init}
\begin{apisyn}
	\cinclude{oskit/x86/pc/com_cons.h}

	\funcproto void com_cons_init(int port, struct~termios *com_params);
\end{apisyn}
\begin{apidesc}
	This routine must be called once to initialize a COM port for
	use by other {\tt com_cons} routines.
	The supplied {\tt termios} structure indicates
	the baud rate and other settings.
	If com_params is zero, a default of 9600 baud, 8 bit characters,
	no parity, and 1 stop bit is used.
\end{apidesc}
\begin{apiparm}
	\item[port]
		COM port to initialize.
		Must be 1, 2, 3 or 4.
	\item[com_params]
		Pointer to a {\tt termios} structures with the tty
		settings to use.
\end{apiparm}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[base_cooked_termios]	\ref{base-cooked-termios}
	\item[inb]			\ref{inb}
	\item[outb]			\ref{outb}
\end{apidep}

\api{com_cons_getchar}{wait for and read a character from a serial port}
\label{com-cons-getchar}
\begin{apisyn}
	\cinclude{oskit/x86/pc/com_cons.h}

	\funcproto int com_cons_getchar(int port);
\end{apisyn}
\begin{apidesc}
	Read a character from the indicated serial port.
	If none is available, this routine loops polling the status
	register until a character is available.
\end{apidesc}
\begin{apiparm}
	\item[port]
		COM port to read from.
		Must be 1, 2, 3 or 4.
\end{apiparm}
\begin{apiret}
	Returns the character read.
\end{apiret}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[inb]	\ref{inb}
\end{apidep}

\api{com_cons_putchar}{write a character to a serial port}
\label{com-cons-putchar}
\begin{apisyn}
	\cinclude{oskit/x86/pc/com_cons.h}

	\funcproto void com_cons_putchar(int port, int ch);
\end{apisyn}
\begin{apidesc}
	Outputs the indicated character on the specified serial port.
\end{apidesc}
\begin{apiparm}
	\item[port]
		COM port to write to.
		Must be 1, 2, 3 or 4.
	\item[ch]
		Character to be printed.
\end{apiparm}
\begin{apidep}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
	\item[inb]			\ref{inb}
	\item[outb]			\ref{outb}
\end{apidep}

\api{com_cons_flush}{delay until all output is flushed on a serial line}
\label{com-cons-flush}
\begin{apisyn}
	\cinclude{oskit/x86/pc/com_cons.h}

	\funcproto void com_cons_flush(int port);
\end{apisyn}
\begin{apidesc}
	Waits until the transmit FIFOs are empty on the serial port
	specified.
	This is useful as it allows the programmer to know that the
	message sent out has been received.
	This is necessary before resetting the UART or changing
	settings if it is desirable for any data already ``sent''
	to actually be transmitted.
\end{apidesc}
\begin{apiparm}
	\item[port]
		COM port to flush.
		Must be 1, 2, 3 or 4.
\end{apiparm}
\begin{apidep}
	\item[inb]	\ref{inb}
\end{apidep}

\api{com_cons_enable_receive_interrupt}{enable receive interrupts on a serial port}
\label{com-cons-enable-receive-interrupt}
\begin{apisyn}
	\cinclude{oskit/x86/pc/com_cons.h}

	\funcproto void com_cons_enable_receive_interrupt(int port);
\end{apisyn}
\begin{apidesc}
	Special function to enable receive character interrupts on a
	serial port.

	Since the base COM console operates by polling,
	there is no need to handle serial interrupts in order to do basic I/O.
	However, if you want to be notified up when a character is received,
	call this function immediately after {\tt com_cons_init},
	and make sure the appropriate IDT entry is initialized properly.

	For example, the serial debugging code for the PC COM port
	uses this so that the program can be woken up
	when the user presses the interrupt character (\^C)
	from the remote debugger.
\end{apidesc}
\begin{apiparm}
	\item[port]
		COM port to enable receive interrupts on.
		Must be 1, 2, 3 or 4.
\end{apiparm}
\begin{apidep}
	\item[inb]	\ref{inb}
\end{apidep}


\apisec{\intelpc\ MultiBoot Startup}
\label{kern-x86pc-multiboot}

MultiBoot is a standardized interface
between boot loaders and 32-bit operating systems
on x86 PC platforms,
which attempts to solve the traditional problem
that every single operating system
tends to come with its own boot loader or set of boot loaders
which are completely incompatible with boot loaders
written for any other operating system.
The MultiBoot standard allows any MultiBoot-compliant operating system
to be loaded from any MultiBoot-supporting boot loader.
MultiBoot is also designed to provide advanced features
needed by many modern operating systems,
such as direct 32-bit protected-mode startup,
and support for {\em boot modules},
which are arbitrary files loaded by the boot loader into physical memory
along with the kernel
and passed to the kernel on startup.
These boot modules may be dynamically loadable device drivers,
application program executables, files on an initial file system,
or anything else the OS may need before it has full device access.
The MultiBoot standard is already supported
by several boot loaders and operating systems,
and is gradually becoming more widespread.
For details on the MultiBoot standard
see Section~\ref{multiboot-spec}.

The MultiBoot standard
is separate from and largely independent of the \oskit{}.
However, if MultiBoot is used, the toolkit can leverage it
to provide a powerful, flexible, and extremely convenient method
of booting custom operating systems that use the \oskit{}.
The toolkit provides startup code
which allows MultiBoot-compliant OS kernels to be built easily,
and which handles the details of
finding and managing physical memory on startup,
interpreting the command line passed by the boot loader,
finding and using boot modules, etc.
If you use the \oskit{}'s MultiBoot startup support,
your kernel automatically inherits
a complete, full-featured 32-bit protected-mode startup environment
and the ability to use various existing boot loaders,
without being constrained by the limitations
of traditional OS-specific boot loaders.

\subsection{Startup code organization}

The MultiBoot startup code in the \oskit{} has two components.
The first component is contained in the object file {\tt multiboot.o},
% JJJ Used to be lib/fluxcrt0 dir; check is right.
installed by the toolkit in the {\tt {\em prefix}/lib/oskit/} directory.
This object file contains the actual MultiBoot header and entrypoint;
it must be linked into the kernel as the very first object file,
so that its contents will be at the very beginning of the resulting executable.
(This object file takes the place of the {\tt crt0.o} or {\tt crt1.o}
normally used when linking ordinary applications in a Unix-like system.)
The second component is contained in the {\tt libkern.a} library;
it contains the rest of the MultiBoot startup code
as well as various utility routines for the use of the client OS.

XXX diagram of MultiBoot kernel executable image

The toolkit's MultiBoot startup code will work
when using either ELF or {\tt a.out} format.
ELF is the format recommended for kernel images by the MultiBoot standard;
however, the {\tt a.out} format is also supported
through the use of some special header information
embedded in the {\tt multiboot.o} code
linked at the very beginning of the kernel's text segment.
This information allows the MultiBoot boot loader
to determine the location and sizes
of the kernel's text, data, and bss sections in the kernel executable
without knowing the details of the particular {\tt a.out} flavor in use
(e.g., Linux, NetBSD, FreeBSD, Mach, VSTa, etc.),
all of which are otherwise mutually incompatible.

\subsection{Startup sequence}

After the MultiBoot boot loader loads the kernel executable image,
it searches through the beginning of the image for the MultiBoot header
which provides important information about the OS being loaded.
% XX be a little more specific
The boot loader performs its activities,
then shuts itself down and jumps to the OS kernel entrypoint
defined in the kernel's MultiBoot header.
In one processor register the boot loader passes to the kernel
the address of a {\em MultiBoot information structure},
containing various information passed from the boot loader to the OS,
organized in a standardized format defined by the MultiBoot specification.

In the \oskit{}'s MultiBoot startup code,
the kernel entrypoint is a short code fragment in {\tt multiboot.o}
which sets up the initial stack and performs other minimal initialization
so that ordinary 32-bit C code can be run safely.\footnote{
        This file also turns all floppy drive motors off,
        since if we were booted from floppy the motor is
        most likely still on and can cause unnecessary wear on the
        floppy disk.}
This code fragment then calls the C function {\tt multiboot_main},
with a pointer to the MultiBoot information structure as its argument.
Normally, the {\tt multiboot_main} function comes from {\tt libkern.a};
it performs other high-level initialization
to create a convenient, stable 32-bit environment,
and then calls the familiar {\tt main} routine,
which the client OS must provide.

\subsection{Memory model}
\label{multiboot-memory-model}

Once the OS kernel receives control in its {\tt main} routine,
the processor has been set up in the base environment
defined earlier in Section~\ref{kern-x86-base}.
The {\tt base_gdt}, {\tt base_idt}, and {\tt base_tss}
have been set up and activated,
so that segmentation operations work and traps can be handled.
Paging is disabled,
and all kernel code and data segment descriptors
are set up with an offset of zero,
so that virtual addresses, linear addresses, and physical addresses
are all the same.
The client OS is free to change this memory layout later,
e.g., by enabling paging and reorganizing the linear address space
as described in Section~\ref{base-cpu-setup}.

As part of the initialization performed by {\tt multiboot_main},
the \oskit{}'s MultiBoot startup code
uses information passed to the OS by the boot loader,
describing the location and amount of physical memory available,
to set up the {\tt malloc_lmm} memory pool (see Section~\ref{malloc-lmm}).
This allows the OS kernel to allocate and manage physical memory
using the normal C-language memory allocation mechanisms,
as well as directly using the underlying LMM memory manager library functions.
The physical memory placed on the {\tt malloc_lmm} pool during initialization
is guaranteed {\em not} to contain any of the data structures
passed by the boot loader which the OS may need to use,
such as the command line or the boot modules;
this way, the kernel can freely allocate and use memory right from the start
without worrying about accidentally ``stepping on'' boot loader data
that it will need to access later on.
In addition, the physical memory placed on the {\tt malloc_lmm}
is divided into the three separate regions defined in {\tt phys_lmm.h}
(see Section~\ref{phys-lmm-h}):
one for low memory below 1MB, one for ``DMA'' memory below 16MB,
and one for all physical memory above this line.
This division allows the kernel to allocate ``special'' memory when needed
for device access or for calls to real-mode BIOS routines,
simply by specifying the appropriate flags in the LMM allocation calls.

\subsection{Command-line arguments}

The MultiBoot specification allows
an arbitrary ASCII string to be passed from the boot loader to the OS
as a ``command line'' for the OS to interpret as it sees fit.
As passed from the boot loader to the OS,
this is a single null-terminated ASCII string.
However, the default MultiBoot initialization code provided by the \oskit{}
performs some preprocessing of the command line
before the actual OS receives control in its {\tt main} routine.
In particular, it parses the single command line string
into an array of individual argument strings
so that the arguments can be passed to the OS
through the normal C-language {\tt argc}/{\tt argv} parameters to {\tt main}.
In addition, any command-line arguments containing an equals sign (`{\tt =}')
are added to the {\tt environ} array rather than the {\tt argv} array,
effectively providing the OS with a minimal initial environment
that can be specified by the user (through the boot loader)
and examined by the OS using the normal {\tt getenv} mechanism
(see Section~\ref{getenv}).

Note that this command-line preprocessing mechanism
matches the kernel command-line conventions established by Linux,
although it provides more convenience and flexibility to the OS
by providing this information to the OS
through standard C-language facilities,
and by not restricting the ``environment variables''
to be comma-separated lists of numeric constants, as Linux does.
This mechanism also provides {\em much} more flexibility
than traditional BSD/Mach command-line mechanisms,
in which the boot loader itself does most of the command-line parsing,
and basically only passes a single fixed ``flags'' word to the OS.

\subsection{Linking MultiBoot kernels}

Since MultiBoot kernels initially run in physical memory,
with paging disabled and segmentation effectively ``neutralized,''
the kernel must be linked at an address
within the range of physical memory present on typical PCs.
Normally the best place to link the kernel is at 0x100000, or 1MB,
which is the beginning of extended memory
just beyond the real-mode ROM BIOS.
Since the processor is already in 32-bit protected mode
when the MultiBoot boot loader starts the OS,
running above the 1MB ``boundary'' is not a problem.
By linking at 1MB,
the kernel has plenty of ``room to grow,''
having essentially all extended memory available to it
in one contiguous chunk.

In some cases, it may be preferable to link the kernel at a lower address,
below the 1MB boundary,
for example if the kernel needs to run on machines without any extended memory,
or if the kernel contains code that needs to run in real mode.
This is also allowed by the MultiBoot standard.
However, note that the kernel should generally leave
at least the first 0x500 bytes of physical memory untouched,
since this area contains important BIOS data structures
that will be needed if the kernel ever makes calls to the BIOS,
or if it wants to glean information about the machine from this area
such as hard disk configuration data.

\api{multiboot.h}{Definitions of MultiBoot structures and constants}
\label{multiboot-h}
\begin{apisyn}
	\cinclude{oskit/x86/multiboot.h}
\end{apisyn}
\begin{apidesc}
	This header file is not specific to the MultiBoot startup code
	provided by the \oskit{};
	it merely contains generic symbolic structure and constant definitions
	corresponding to the data structures specified in the MultiBoot specification.
	The following C structures are defined:
	\begin{csymlist}
	\item[struct multiboot_header]		\ttindex{multiboot_header}
		Defines the MultiBoot header structure
		which is located near the beginning
		of all MultiBoot-compliant kernel executables.
	\item[struct multiboot_info]		\ttindex{multiboot_info}
		Defines the general information structure
		passed from the boot loader to the OS
		when control is passed to the OS.
	\item[struct multiboot_module]		\ttindex{multiboot_module}
		One of the elements of the {\tt multiboot_info} structure
		is an optional array of boot modules
		which the boot loader may provide;
		each element of the boot module array
		is reflected by this structure.
	\item[struct multiboot_addr_range]	\ttindex{multiboot_addr_range}
		Another optional component of the {\tt multiboot_info} structure
		is a pointer to an array of address range descriptors,
		described by this structure,
		which define the layout of physical memory on the machine.
		(XXX name mismatch.)
	\end{csymlist}
	For more information on these structures and the associated constants,
	see the {\tt multiboot.h} header file and the MultiBoot specification.

	XXX should move this to x86/pc/multiboot.h?
\end{apidesc}

\api{boot_info}{MultiBoot information structure}
\label{boot-info}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_multiboot.h}

	{\tt extern struct multiboot_info \csymbol{boot_info};}
\end{apisyn}
\begin{apidesc}
	The first thing that {\tt multiboot_main} does on entry
	from the minimal startup code in {\tt multiboot.o}
	is copy the MultiBoot information structure passed by the boot loader
	into a global variable in the kernel's bss segment.
	Copying the information structure this way
	allows it to be accessed more conveniently by the kernel,
	and makes it unnecessary for the memory initialization code
	({\tt base_multiboot_init_mem};
	see Section~\ref{base-multiboot-init-mem})
	to carefully ``step over'' the information structure
	when determining what physical memory is available for general use.

	After the OS has received control in its {\tt main} routine,
	it is free to examine the {\tt boot_info} structure
	and use it to locate other data passed by the boot loader,
	such as the boot modules.
	The client OS must {\em not} attempt to access
	the original copy of the information structure
	passed by the boot loader,
	since that copy of the structure may be overwritten
	as memory is dynamically allocated and used.
	However, this should not be a problem,
	since a pointer to the original copy
	of the {\tt multiboot_info} structure
	is never even passed to the OS by the MultiBoot startup code;
	it is only accessible to the OS
	if it overrides the {\tt multiboot_main} function.
\end{apidesc}

\api{multiboot_main}{general MultiBoot initialization}
\label{multiboot-main}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_multiboot.h}

	\funcproto void multiboot_main(oskit_addr_t boot_info_pa);
\end{apisyn}
\begin{apidesc}
	This is the first C-language function to run,
	invoked by the minimal startup code fragment in {\tt multiboot.o}.
	The default implementation merely copies
	the MultiBoot information structure passed by the boot loader
	into the global variable {\tt boot_info}
	(see Section~\ref{boot-info}),
	and then calls the following routines
	to set up the base environment and start the OS:
	\begin{csymlist}
	\item[base_cpu_setup]
		Initializes the base GDT, IDT, and TSS,
		so that the processor's segmentation facilities can be used
		and processor traps can be handled.
	\item[base_multiboot_init_mem]
		Finds all physical memory available for general use
		and adds it to the {\tt malloc_lmm}
		so that OS code can allocate memory dynamically.
	\item[base_multiboot_init_cmdline]
		Performs basic preprocessing on the command line string
		passed by the boot loader,
		splitting it up into standard C argument
		and environment variable lists.
	\item[main]
		This call is what invokes the actual OS code,
		using standard C-language startup conventions.
	\item[exit]
		As per C language conventions,
		if the {\tt main} routine ever returns,
		{\tt exit} is called immediately,
		using the return value from {\tt main} as the exit code.
	\end{csymlist}
	If the client OS does not wish some or all of the above to be performed,
	it may override the {\tt multiboot_main} function
	with a version that does what it needs,
	or, alternatively, it may instead override
	the specific functions of interest called by {\tt multiboot_main}.
\end{apidesc}
\begin{apiparm}
	\item[boot_info_pa]
		The physical address of the MultiBoot information structure
		as created and passed by the boot loader.
\end{apiparm}
\begin{apiret}
	This function had better never return.
\end{apiret}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
	\item[boot_info]	\ref{boot-info}
	\item[base_cpu_setup]	\ref{base-cpu-setup}
	\item[base_multiboot_init_mem]
				\ref{base-multiboot-init-mem}
	\item[base_multiboot_init_cmdline]
				\ref{base-multiboot-init-cmdline}
	\item[exit]
				\ref{exit}
\end{apidep}

\api{base_multiboot_init_mem}{physical memory initialization}
\label{base-multiboot-init-mem}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_multiboot.h}

	\funcproto void base_multiboot_init_mem(void);
\end{apisyn}
\begin{apidesc}
	This function finds all physical memory available for general use
	and adds it to the {\tt malloc_lmm} pool,
	as described in Section~\ref{multiboot-memory-model}.
	It is normally called automatically during initialization
	by {\tt multiboot_main} (see Section~\ref{multiboot-main}).

	This function uses the lower and upper memory size fields
	in the MultiBoot information structure
	to determine the total amount of physical memory available;
	it then adds all of this memory to the {\tt malloc_lmm} pool
	except for the following ``special'' areas:
	\begin{itemize}
	\item	The first 0x500 bytes of physical memory are left untouched,
		since this area contains BIOS data structures
		which the OS might want to access
		(or the BIOS itself, if the OS makes any BIOS calls).
	\item	The area from 0xa0000 to 0x100000 is the I/O and ROM area,
		and therefore does not contain usable physical memory.
	\item	The memory occupied by the kernel itself is skipped,
		so that the kernel will not trash its own code, data, or bss.
	\item	All interesting boot loader data structures,
		which can be found through the MultiBoot information structure,
		are skipped, so that the OS can examine them later.
		This includes the kernel command line,
		the boot module information array,
		the boot modules themselves,
		and the strings associated with the boot modules.
	\end{itemize}

	This function uses {\tt phys_lmm_init}
	to initialize the {\tt malloc_lmm},
	and {\tt phys_lmm_add} to add available physical memory to it
	(see Section~\ref{phys-lmm-h});
	as a consequence, this causes the physical memory found
	to be split up automatically
	according to the three main functional ``classes'' of PC memory:
	low 1MB memory accessible to real-mode software,
	low 16MB memory accessible to the built-in DMA controller,
	and ``all other'' memory.
	This division allows the OS to allocate ``special'' memory when needed
	for device access or for calls to real-mode BIOS routines,
	simply by specifying the appropriate flags in the LMM allocation calls.

	XXX currently doesn't use the memory range array.
\end{apidesc}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
	\item[boot_info]	\ref{boot-info}
	\item[phys_lmm_init]	\ref{phys-lmm-init}
	\item[phys_lmm_add]	\ref{phys-lmm-add}
	\item[strlen]		\ref{strlen}
\end{apidep}

\api{base_multiboot_init_cmdline}{command-line preprocessing}
\label{base-multiboot-init-cmdline}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_multiboot.h}

	\funcproto void base_multiboot_init_cmdline(void);
\end{apisyn}
\begin{apidesc}
	This function breaks up the kernel command line string
	passed by the boot loader
	into independent C-language-compatible argument strings.
	Option strings are separated by any normal whitespace characters
	(spaces, tabs, newlines, etc.).
	In addition, strings containing an equals sign (`{\tt =}')
	are added to the {\tt environ} array rather than the {\tt argv} array,
	effectively providing the OS with a minimal initial environment
	that can be specified by the user (through the boot loader)
	and examined by the OS using the normal {\tt getenv} mechanism
	(see Section~\ref{getenv}).

	XXX example.

	XXX currently no quoting support.

	XXX currently just uses ``kernel'' as argv[0].
\end{apidesc}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
	\item[strlen]		\ref{strlen}
	\item[strtok]		\ref{strtok}
	\item[malloc]		\ref{malloc}
	\item[memcpy]		\ref{memcpy}
	\item[panic]		\ref{panic}
\end{apidep}


\api{base_multiboot_find}{find a MultiBoot boot module by name}
\label{base-multiboot-find}
\begin{apisyn}
	\cinclude{oskit/x86/pc/base_multiboot.h}

	\funcproto struct~multiboot_module *base_multiboot_find(const~char
								*string);
\end{apisyn}
\begin{apidesc}
	This is not an initialization function,
	but rather a utility function for the use of the client OS.
	Given a particular string,
	it searches the array of boot modules passed by the boot loader
	for a boot module with a matching string.
	This function can be easily used by the OS
	to locate specific boot modules by name.

	If multiple boot modules have matching strings,
	then the first one found is returned.
	If any boot modules have {\em no} strings attached
	(no pun intended),
	then those boot modules will never be ``found'' by this function,
	although they can still be found
	by hunting through the boot module array manually.
\end{apidesc}
\begin{apiparm}
	\item[string]
		The string to match against the strings
		attached to the boot modules.
\end{apiparm}
\begin{apiret}
	If successful,
	returns a pointer to the {\tt multiboot_module} entry matched;
	from this structure, the actual boot module data can be found
	using the {\tt mod_start} and {\tt mod_end} elements,
	which contain the start and ending physical addresses
	of the boot module data, respectively.

	If no matching boot module can be found,
	this function returns NULL.
\end{apiret}
\begin{apidep}
	\item[phystokv]		\ref{base-vm}
	\item[boot_info]	\ref{boot-info}
	\item[strcmp]		\ref{strcmp}
\end{apidep}

\subsection{Multiboot Specification}
\ttindex{Multiboot Specification}
\label{multiboot-spec}

\input{multiboot-spec.tex}


\apisec{\intelpc\ Raw BIOS Startup}
\label{kern-x86pc-biosboot}

\emph{
The BIOS startup code is written and functional
but not yet documented or integrated into the \oskit\ source tree.
%The source code implementing this functionality
%can currently be found in the \oskit\ ``source'' subdirectory
%containing unintegrated code,
%in source/x86/pc/i16 and related directories.}
% XX This directory does not exist!
% can currently be found in the Mach 4 distribution
% in the mach4-i386/kernel/pc/i16 directory and related directories.
}

\apisec{\intelpc\ DOS Startup}
\label{kern-x86pc-dosboot}

\emph{
The DOS startup code is written and functional
but not yet documented or integrated into the \oskit\ source tree.
%The source code implementing this functionality
%can currently be found in the \oskit\ ``source'' subdirectory
%containing unintegrated code,
%in source/x86/dos/i16 and related directories.}
% XX This directory does not exist!
% can currently be found in the Mach 4 distribution
% in the mach4-i386/kernel/dos/i16 directory and related directories.
}

\apisec{Remote Kernel Debugging with GDB}
\label{gdb}

In addition to the {\tt libkern} functionality described above
which is intended to facilitate implementing kernels,
the library also provides complete, easy-to-use functionality
to facilitate {\em debugging} kernels.
The \oskit{} does not itself contain a complete kernel debugger
(at least, not yet),
but it contains extensive support for remote debugging using GDB,
the GNU debugger.
This remote debugging support allows you to run the debugger on one machine,
and run the actual OS kernel being debugged on a different machine.
The two machines can be of different architectures.
A small ``debugging stub'' is linked into the OS kernel;
this piece of code handles debugging-related traps and interrupts
and communicates with the remote debugger,
acting as a ``slave'' that simply interprets and obeys the debugger's commands.

This section describes remote debugging in general,
applicable to any mechanism for communicating with the remote kernel
(e.g., serial line or ethernet).
The next section (\ref{gdb-serial}) describes kernel debugging support
specific to the serial line mechanism (currently the only one implemented).

XXX diagram

One of the main advantages of remote debugging is that
you can use a complete, full-featured source-level debugger,
since it can run on a stable, well-established operating system such as Unix;
a debugger running on the same machine as the kernel being debugged
would necessarily have to be much smaller and simpler
because of the lack of a stable underlying OS it can rely on.
Another advantage is that remote debugging is less invasive:
since most of the debugging code is on a different machine,
and the remote debugging stub linked into the OS
is much smaller than even a simple stand-alone debugger,
there is much less that can ``go wrong'' with the debugging code
when Strange Things start to happen due to subtle kernel bugs.
The main disadvantage of remote debugging, of course,
is that it requires at least two machines
with an appropriate connection between them.

The GNU debugger, GDB, supports a variety of remote debugging protocols.
The most common and well-supported is the serial-line protocol,
which operates over an arbitrary serial line (typically null-modem) connection
operating at any speed supported by the two machines involved.
The serial-line debugging protocol supports a multitude of features
such as multiple threads, signals, and data compression.
GDB also supports an Ethernet-based remote debugging protocol
and a variety of existing vendor- and OS-specific protocols.

Ths OS kit's GDB support has been tested with GDB versions 4.15 and 4.16;
probably a version $>=$ 4.15 is required.

\subsection{Organization of remote GDB support code}

The GDB remote debugging support provided by the \oskit{}
is broken into two components:
the protocol-independent component and the protocol-specific component.
The protocol-independent component
encapsulates all the processor architecture-specific code
to handle processor traps
and convert them into the ``signals'' understood by GDB,
to convert saved state frames to and from
GDB's standard representation for a given architecture,
and to perform ``safe'' memory reads and writes on behalf of the remote user
so that faulting accesses will terminate cleanly
without causing recursive traps.

The protocol-specific component of the toolkit's remote GDB support
encapsulates the code necessary to talk to the remote debugger
using the appropriate protocol.
Although this code is specific to a particular protocol,
it is architecture-neutral.
The \oskit{} currently supports only the standard serial-line protocol,
although support for other protocols is planned
(particularly the remote Ethernet debugging protocol)
and should be easy to add.

\subsection{Using the remote debugging code}
\label{gdb-using}

If you are using the base environment's default trap handler,
then activating the kernel debugger is extremely easy:
it is simply necessary to call an appropriate initialization routine
near the beginning of your kernel code;
all subsequent traps that occur will be dispatched to the remote debugger.
For example, on a PC,
to activate serial-line debugging over COM1 using default serial parameters,
simply make the call `{\tt gdb_pc_com_init(1, 0)}'.
Some example kernels are provided with the \oskit{}
that demonstrate how to initialize and use the remote debugging facilities;
see Section~\ref{example-kernels} for more information.

If you want a trap to occur {\em immediately}
after initialization of the debugging mechanism,
to transfer control to the remote debugger from the start
and give you the opportunity to set breakpoints and such,
simply invoke the {\tt gdb_breakpoint} macro
immediately after the call to initialize the remote debugger
(see Section~\ref{gdb-breakpoint}).

If your kernel uses its own trap entrypoint mechanisms
or its own serial line communication code
(e.g., ``real'' interrupt-driven serial device drivers
instead of the simple polling code used by default by the toolkit),
then you will have to write a small amount of ``glue'' code
to interface the generic remote debugging support code in the toolkit
with your specific OS mechanisms.
However, this glue code should generally be extremely small and simple,
and you can use the default implementations in the \oskit{}
as templates to work from or use as examples.

\subsection{Debugging address spaces other than the kernel's}

Although the \oskit{}'s remote debugging support code
is most directly and obviously useful for debugging the OS kernel itself,
most of the code does not assume that the kernel is the entity being debugged.
In fact, it is quite straightforward to adapt the mechanism
to allow remote debugging of other entities,
such as user-level programs running on top of the kernel.
To make the debugging stub operate
on a different address space than the kernel's,
it is simply necessary to override
the {\tt gdb_copyin} and {\tt gdb_copyout} routines
with alternate versions that transfer data
to or from the appropriate address space.
Operating systems that support a notion of user-level address spaces
generally have some kind of ``copyin'' and ``copyout'' routines anyway
to provide safe access to user address spaces;
the replacement {\tt gdb_copyin} and {\tt gdb_copyout} routines
can call those standard user space access routines.
In addition, the trap handling mechanism may need to be set up
so that only traps occurring in a particular context
(e.g., within a particular user process or thread)
will be dispatched to the remote debugger.

\api{gdb_state}{processor register state frame used by GDB}
\label{gdb-state}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\cstruct{gdb_state}{
		{} ...;	/* architecture-specific definitions */
	};
\end{apisyn}
\begin{apidesc}
	This structure represents the processor register state
	for the target architecture
	in the form in which GDB expects it.
	GDB uses a standard internal data structure
	for each processor architecture
	to represent the register state of a program being debugged,
	and most of GDB's architecture-neutral remote debugging protocols
	use this standard structure.
	The {\tt gdb_state} structure defined by the \oskit{}
	is defined to match GDB's corresponding register state structure
	for each supported architecture.
\end{apidesc}

\api{gdb_trap}{default trap handler for remote GDB debugging}
\label{gdb-trap}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto int gdb_trap(struct~trap_state *trap_state);
\end{apisyn}
\begin{apidesc}
	This function is intended to be installed
	as the kernel trap handler for all traps by setting each of the
	entries in the {\tt base_trap_handlers} array to point to it
	(see Section~\ref{base-trap-handlers}),
	when remote GDB debugging is desired.
	(Alternatively, the client OS can use its own trap handlers
	which chain to {\tt gdb_trap} when appropriate.)
	This function converts the contents of the {\tt trap_state} structure
	saved by the base trap entrypoint code
	into the {\tt gdb_state} structure used by GDB.
	It also converts the architecture-specific processor trap vector number
	into a suitable machine-independent signal number
	which can be interpreted by the remote debugger.

	After converting the register state and trap vector appropriately,
	this function calls the appropriate protocol-specific GDB stub
	through the {\tt gdb_signal} function pointer variable
	(see Section~\ref{gdb-signal}).
	Finally, it converts the final register state,
	possibly modified by the remote debugger,
	back into the original {\tt trap_state} format
	and returns an appropriate success or failure code
	as described below.

	On architectures that don't provide a way
	for the kernel to ``validate'' memory accesses before performing them,
	such as the x86,
	this function also provides support for ``recovering''
	from faulting memory accesses during calls
	to {\tt gdb_copyin} or {\tt gdb_copyout}
	(see Sections~\ref{gdb-copyin} and~\ref{gdb-copyout}).
	This is typically implemented using a ``recovery pointer''
	which is set before a ``safe'' memory access and cleared afterwards;
	{\tt gdb_trap} checks this recovery pointer, and if set,
	modifies the trap state appropriately and returns from the trap
	without invoking the protocol-specific GDB stub.

	If the client OS uses its own trap entrypoint code
	which saves register state in a different format
	when handling traps,
	then the client OS will also need
	to override the {\tt gdb_trap} function
	with a version that understands its custom saved state format.
\end{apidesc}
\begin{apiparm}
	\item[trap_state]
		A pointer to the saved register state
		representing the processor state at the time the trap occurred.
		The saved state must be in the default format
		defined by the \oskit{}'s base environment.
\end{apiparm}
\begin{apiret}
	The {\tt gdb_trap} function returns success (zero)
	when the remote debugger instructs the local stub
	to resume execution at the place it was stopped
	and ``consume'' the trap that caused the debugger to be invoked;
	this is the normal case.

	This function returns failure (nonzero)
	if the remote debugger passed the same or a different signal
	back to the local GDB stub,
	instructing the local kernel to handle the trap (signal) itself.
	If the default trap entrypoint mechanism
	provided by the base environment in use,
	then this simply causes the kernel to panic with a register dump,
	since the default trap code does not know
	how to ``handle'' signals by itself.
	However, if the client OS uses its own trap entrypoint mechanism
	or interposes its own trap handler over {\tt gdb_trap},
	then it may wish to interpret a nonzero return code from {\tt gdb_trap}
	as a request for the trap to be handled using the ``normal'' mechanism,
	(e.g., dispatched to the application being debugged).
\end{apiret}
\begin{apidep}
	\item[trap_state]		\ref{trap-state}
	\item[gdb_state]		\ref{gdb-state}
	\item[gdb_signal]		\ref{gdb-signal}
	\item[gdb_trap_recover]		\ref{gdb-trap-recover}
\end{apidep}

\api{gdb_copyin}{safely read data from the subject's address space}
\label{gdb-copyin}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto int gdb_copyin(oskit_addr_t src_va, void *dest_buf,
				  oskit_size_t size);
\end{apisyn}
\begin{apidesc}
	The protocol-specific local GDB stub
	calls this function in order to read data
	in the address space of the program being debugged.
	The default implementation of this function provided by {\tt libkern}
	assumes that the kernel itself is the program being debugged;
	thus, it acts basically like an ordinary {\tt memcpy}.
	However, the client can override this function
	with a version that accesses a different address space,
	such as a user process's address space,
	in order to support remote debugging of entities other than the kernel.

	If a fault occurs while trying to read the specified data,
	this function catches the fault cleanly and returns an error code
	rather than allowing a recursive trap to be dispatched to the debugger.
	This way, if the user of the debugger
	accidentally attempts to follow an invalid pointer
	or display unmapped or nonexistent memory,
	it will merely cause the debugger to report an error
	rather than making everything go haywire.
\end{apidesc}
\begin{apiparm}
	\item[src_va]
		The virtual address
		in the address space of the program being debugged
		(the kernel's address space, by default)
		from which to read data.
	\item[dest_buf]
		A pointer to the kernel buffer to copy data into.
		This buffer is provided by the caller,
		typically the local GDB stub,
	\item[size]
		The number of bytes of data to read into the destination buffer.
\end{apiparm}
\begin{apiret}
	Returns zero if the transfer completed successfully,
	or nonzero if some or all of the source region is not accessible.
\end{apiret}
\begin{apidep}
	\item[gdb_trap_recover]		\ref{gdb-trap-recover}
\end{apidep}

\api{gdb_copyout}{safely write data into the subject's address space}
\label{gdb-copyout}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto int gdb_copyout(const~void *src_buf, oskit_addr_t dest_va,
				   oskit_size_t size);
\end{apisyn}
\begin{apidesc}
	The protocol-specific local GDB stub
	calls this function in order to write data
	into the address space of the program being debugged.
	The default implementation of this function provided by {\tt libkern}
	assumes that the kernel itself is the program being debugged;
	thus, it acts basically like an ordinary {\tt memcpy}.
	However, the client can override this function
	with a version that accesses a different address space,
	such as a user process's address space,
	in order to support remote debugging of entities other than the kernel.

	If a fault occurs while trying to write the specified data,
	this function catches the fault cleanly and returns an error code
	rather than allowing a recursive trap to be dispatched to the debugger.
	This way, if the user of the debugger
	accidentally attempts to write to unmapped or nonexistent memory,
	it will merely cause the debugger to report an error
	rather than making everything go haywire.
\end{apidesc}
\begin{apiparm}
	\item[src_buf]
		A pointer to the kernel buffer
		containing the data to write.
	\item[dest_va]
		The virtual address
		in the address space of the program being debugged
		(the kernel's address space, by default)
		at which to write the data.
	\item[size]
		The number of bytes of data to transfer.
\end{apiparm}
\begin{apiret}
	Returns zero if the transfer completed successfully,
	or nonzero if some or all of the destination region is not writable.
\end{apiret}
\begin{apidep}
	\item[gdb_trap_recover]		\ref{gdb-trap-recover}
\end{apidep}

\api{gdb_trap_recover}{recovery pointer for safe memory transfer routines}
\label{gdb-trap-recover}

\api{gdb_signal}{vector to GDB trap/signal handler routine}
\label{gdb-signal}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	{\tt extern void (*\csymbol{gdb_signal})(int *{\em inout_signo},
				struct gdb_state *{\em inout_gdb_state});}
\end{apisyn}
\begin{apidesc}
	Before {\tt gdb_trap} is called for the first time,
	this function pointer must be initialized
	to point to an appropriate GDB debugging stub,
	such as {\tt gdb_serial_signal} (see Section~\ref{gdb-serial-signal}).
	This function is called to notify the remote debugger
	that a relevant processor trap or interrupt has occurred,
	and to wait for further instructions from the remote debugger.
	When the function returns, execution will be resumed
	as described in Section~\ref{gdb-trap}.
\end{apidesc}
\begin{apiparm}
	\item[inout_signo]
		On entry, the variable referenced by this pointer
		contains the signal number to transmit to the remote debugger.
		On return, this variable may have been modified
		to indicate what signal should be dispatched
		to the program being debugged.
		For example, if the variable is the same on return as on entry,
		then it means the remote debugger instructed the stub
		to ``pass through'' the signal to the application.
		If {\tt *\em signo} is 0 on return from this function,
		it means the remote debugger has ``consumed'' the signal
		and execution of the subject program
		should be resumed immediately.
	\item[inout_gdb_state]
		On entry, this structure contains
		a snapshot of the processor state
		at the time the relevant trap or interrupt occurred.
		On return, the remote debugger may have modified this state;
		the new state should be used when resuming execution.
\end{apiparm}

\api{gdb_set_trace_flag}{enable or disable single-stepping in a state frame}
\label{gdb-set-trace-flag}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto void gdb_set_trace_flag(int trace_enable,
					   \inoutparam struct~gdb_state *state);
\end{apisyn}
\begin{apidesc}
	This architecture-specific function
	merely modifies the specified processor state structure
	to enable or disable single-stepping
	according to the {\em trace_enable} parameter.
	On architectures that have some kind of trace flag,
	this function simply sets or clears that flag as appropriate.
	On other architectures,
	this behavior is achieved through other means.
	This function is called by machine-independent remote debugging stubs
	such as {\tt gdb_serial_signal}
	before resuming execution of the subject program,
	according to whether the remote debugger requested
	that the program ``continue'' or ``step'' one instruction.
\end{apidesc}
\begin{apiparm}
	\item[trace_enable]
		True if single-stepping should be enabled,
		or false otherwise.
	\item[state]
		The state frame to modify.
\end{apiparm}

\api{gdb_breakpoint}{macro to generate a manual instruction breakpoint}
\label{gdb-breakpoint}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto void gdb_breakpoint(void);
\end{apisyn}
\begin{apidesc}
	This is simply an architecture-specific macro
	which causes an instruction causing a breakpoint trap
	to be emitted at the corresponding location in the current function.
	This macro can be used to set ``manual breakpoints'' in program code,
	as well as to give control to the debugger
	at the very beginning of program execution
	as described in Section~\ref{gdb-using}.
\end{apidesc}

\apisec{Serial-line Remote Debugging with GDB}
\label{gdb-serial}

The GDB serial-line debugging protocol
is probably the most powerful and commonly-used remote debugging protocol
supported by GDB; this is the only protocol
for which the \oskit{} currently has direct support.
The GDB serial-line debugging stub supplied with the \oskit{}
is fully architecture-independent,
and supports most of the major features of the GDB serial-line protocol.

For technical information on the remote serial-line GDB debugging protocol,
or information on how to run and use the remote debugger itself,
consult the appropriate sections of the GDB manual.
This section merely describes how remote serial-line debugging
is supported by the \oskit{}.

Note that source code for several example serial-line debugging stubs
are supplied in the GDB distribution ({\tt gdb/*-stub.c});
in fact, this code was used as a template and example
for the \oskit{}'s serial-line debugging stub.
However, these stubs are highly machine-dependent
and make many more assumptions about how they are used.
For example, they assume that they have exclusive control
of the processor's trap vector table,
and are therefore only generally usable in an embedded environment
where traps are {\em never} supposed to occur during normal operation
and therefore all traps can be fielded directly by the debugger.
In contrast, the serial-line debugging stub provided in the \oskit{}
is much more generic and cleanly decomposed,
and therefore should be usable in a much wider range of environments.

\subsection{Redirecting console output to the remote debugger}
\label{gdb-serial-console}

If the machine on which the kernel is being debugged
is truly ``remote,'' e.g., in a different room
or a completely different building,
and you don't have easy access to the machine's ``real'' console,
it is possible to make the kernel use the remote debugger
as its ``console'' for printing status messages and such.
To do this, simply write your kernel's ``console'' output functions
(e.g., {\tt putchar} and {\tt puts},
if you're using the \oskit{}'s minimal C library
for console output routines such as {\tt printf})
so that they call {\tt gdb_serial_putchar} and {\tt gdb_serial_puts},
described in Sections~\ref{gdb-serial-putchar} and~\ref{gdb-serial-puts},
respectively.
The \oskit{} base console environment (section~\ref{kern-x86pc-base-console})
does this as necessary.

This mechanism only works for console {\em output}:
console input cannot be obtained from the remote debugger's console
because the GDB serial-line debugging protocol does not currently support it.
However, console input can be obtained ``outside the protocol'' as described
in section~\ref{gdb-serial-getchar}.

\api{gdb_serial_signal}{primary event handler in the GDB stub}
\label{gdb-serial-signal}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	\funcproto void gdb_serial_signal(\inoutparam int *signo,
					  \inoutparam struct~gdb_state *state);
\end{apisyn}
\begin{apidesc}
	This is the main trap/signal handler routine
	in the serial-line debugging stub;
	it should be called whenever a relevant processor trap occurs.
	This function notifies the remote debugger
	about the event that caused the processor to stop,
	and then waits for instructions from the remote debugger.
	The remote debugger may then cause the stub to perform various actions,
	such as examine memory, modify the register state,
	or kill the program being debugged.
	Eventually, the remote debugger
	will probably instruct the stub to resume execution,
	in which case this function returns
	with the signal number and trap state modified appropriately.

	If this function receives a ``kill'' (`{\tt k}') command
	from the remote debugger,
	then it breaks the remote debugging connection
	and then calls {\tt panic} to reboot the machine.
	XXX may not be appropriate when debugging a user task;
	should call an intermediate function.
\end{apidesc}
\begin{apiparm}
	\item[signo]
		On entry, the variable referenced by this pointer
		contains the signal number to transmit to the remote debugger.
		On return, this variable may have been modified
		to indicate what signal should be dispatched
		to the program being debugged.
		For example, if the variable is the same on return as on entry,
		then it means the remote debugger instructed the stub
		to ``pass through'' the signal to the application.
		If {\tt *\em signo} is 0 on return from this function,
		it means the remote debugger has ``consumed'' the signal
		and execution of the subject program
		should be resumed immediately.
	\item[state]
		On entry, this structure contains
		a snapshot of the processor state
		at the time the relevant trap or interrupt occurred.
		On return, the remote debugger may have modified this state;
		the new state should be used when resuming execution.
\end{apiparm}
\begin{apidep}
	\item[gdb_serial_send]		\ref{gdb-serial-send}
	\item[gdb_serial_recv]		\ref{gdb-serial-recv}
	\item[gdb_copyin]		\ref{gdb-copyin}
	\item[gdb_copyout]		\ref{gdb-copyout}
	\item[gdb_set_trace_flag]	\ref{gdb-set-trace-flag}
	\item[panic]			\ref{panic}
\end{apidep}

\api{gdb_serial_exit}{notify the remote debugger that the subject is dead}
\label{gdb-serial-exit}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	\funcproto void gdb_serial_exit(int exit_code);
\end{apisyn}
\begin{apidesc}
	This function sends a message to the remote debugger
	indicating that the program being debugged is terminating.
	This message causes the debugger to display an appropriate message
	on the debugger's console along with the {\em exit_code},
	and causes it to break the connection
	(i.e., stop listening for further messages on the serial port).
	If no remote debugging connection is currently active,
	this function does nothing.

	The client OS should typically call this function
	just before it reboots for any reason,
	so that the debugger does not hang indefinitely
	waiting for a response from a kernel that is no longer running.
	Alternatively,
	if the remote debugging facility is being used
	to debug a user-mode process running under the kernel,
	then this function should be called
	when {\em that process} terminates.

	Note that despite its name, this function {\em does} return.
	It does not by itself cause the machine
	to ``exit'' or reboot or hang or whatever;
	it merely notifies the debugger
	that the subject program is {\em about to} terminate.
\end{apidesc}
\begin{apiparm}
	\item[exit_code]
		Exit code to pass back to the remote debugger.
		Typically this value is simply printed
		on the remote debugger's console.
\end{apiparm}
\begin{apidep}
	\item[gdb_serial_send]		\ref{gdb-serial-send}
	\item[gdb_serial_recv]		\ref{gdb-serial-recv}
\end{apidep}

\api{gdb_serial_getchar}{input a character from the remote debugger's console}
\label{gdb-serial-getchar}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	\funcproto int gdb_serial_getchar(void);

	{\tt static char inbuf[256];}
\end{apisyn}
\begin{apidesc}
	Unfortunately, the GDB protocol doesn't support console input.
	However, we can simulate it with a rather horrible kludge:
	when the kernel first does a read from the console
	we take a breakpoint, allowing the user to fill an input buffer
	with a command such as:

	\begin{codefrag}
		call strcpy(inbuf, "hello\r")
	\end{codefrag}

	The supplied characters will be returned from successive calls
	to {\tt gdb_serial_getchar}, until {\tt inbuf} is emptied,
	at which point we hit a breakpoint again.
\end{apidesc}
\begin{apiret}
	Returns the next available character in the {\tt inbuf} array.
\end{apiret}
\begin{apidep}
	\item[gdb_breakpoint]		\ref{gdb-breakpoint}
	\item[base_critical_enter]	\ref{base-critical-enter}
	\item[base_critical_leave]	\ref{base-critical-leave}
\end{apidep}

\api{gdb_serial_putchar}{output a character to the remote debugger's console}
\label{gdb-serial-putchar}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	\funcproto void gdb_serial_putchar(int ch);
\end{apisyn}
\begin{apidesc}
	If a remote debugging connection is currently active,
	this function sends the specified character to the remote debugger
	in a special ``output'' (`{\tt O}') message
	which causes that character
	to be sent to the debugger's standard output.
	This allows the serial line used for remote debugging
	to double as a remote serial console,
	as described in Section~\ref{gdb-serial-console}.

	Note that using {\tt gdb_serial_putchar} by itself to print messages
	can be very inefficient,
	because a separate message is used for each character,
	and each of these messages must be acknowledged by the remote debugger
	before the next character can be sent.
	When possible, it is much faster to print strings of text
	using {\tt gdb_serial_puts} (see Section~\ref{gdb-serial-puts}).
	If you are using the implementation of {\tt printf}
	in the \oskit{}'s minimal C library (see Section~\ref{printf}),
	you can make this happen automatically by overriding {\tt puts}
	with a version that calls {\tt gdb_serial_puts} directly
	instead of calling {\tt putchar} successively on each character.

	If this function is called
	while no remote debugging connection is active,
	but the {\tt gdb_serial_send} and {\tt gdb_serial_receive} pointers
	are initialized to point to serial-line communication functions,
	then this function simply sends the specified character
	out the serial port using {\tt gdb_serial_send}.
	This way, if the kernel attempts to print any messages
	before a connection has been established
	or after the connection has been dropped
	(e.g., by calling {\tt gdb_serial_exit}),
	they won't confuse the debugger or cause the kernel to hang
	as they otherwise would,
	and they may be seen by the remote user
	if the serial port is being monitored at the time.

	If the {\tt gdb_serial_send} and {\tt gdb_serial_receive} pointers
	are uninitialized (still NULL) when this function is called,
	it does nothing.
\end{apidesc}
\begin{apiparm}
	\item[ch]
		The character to send to the remote debugger's console.
\end{apiparm}
\begin{apidep}
	\item[gdb_serial_send]		\ref{gdb-serial-send}
	\item[gdb_serial_recv]		\ref{gdb-serial-recv}
\end{apidep}

\api{gdb_serial_puts}{output a line to the remote debugger's console}
\label{gdb-serial-puts}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	\funcproto void gdb_serial_puts(const~char *s);
\end{apisyn}
\begin{apidesc}
	If a remote debugging connection is currently active,
	this function sends the specified string,
	followed by a newline character,
	to the remote debugger in a special ``output'' (`{\tt O}') message
	which causes the line to be sent to the debugger's standard output.
	This allows the serial line used for remote debugging
	to double as a remote serial console,
	as described in Section~\ref{gdb-serial-console}.

	If this function is called
	while no remote debugging connection is active,
	but the {\tt gdb_serial_send} and {\tt gdb_serial_receive} pointers
	are initialized to point to serial-line communication functions,
	then this function simply sends the specified line
	out the serial port using {\tt gdb_serial_send}.
	This way, if the kernel attempts to print any messages
	before a connection has been established
	or after the connection has been dropped
	(e.g., by calling {\tt gdb_serial_exit}),
	they won't confuse the debugger or cause the kernel to hang
	as they otherwise would,
	and they may be seen by the remote user
	if the serial port is being monitored at the time.

	If the {\tt gdb_serial_send} and {\tt gdb_serial_receive} pointers
	are uninitialized (still NULL) when this function is called,
	it does nothing.
\end{apidesc}
\begin{apiparm}
	\item[s]
		The string to send to the remote debugger's console.
		A newline is automatically appended to this string.
\end{apiparm}
\begin{apidep}
	\item[gdb_serial_send]		\ref{gdb-serial-send}
	\item[gdb_serial_recv]		\ref{gdb-serial-recv}
\end{apidep}

\api{gdb_serial_recv}{vector to GDB serial line receive function}
\label{gdb-serial-recv}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	{\tt int (*\csymbol{gdb_serial_recv})(void);}
\end{apisyn}
\begin{apidesc}
	Before the remote serial-line debugging stub can be used,
	this global variable must be initialized
	to point to a function to call
	to read a character from the serial port.
	The function should not return until a character has been received;
	the GDB stub has no notion of timeouts or interruptions.

	Calling functions in the GDB serial-line debugging stub
	before this variable is initialized
	(i.e., while it is still null)
	is guaranteed to be harmless.
\end{apidesc}
\begin{apiret}
	Returns the character received.
\end{apiret}

\api{gdb_serial_send}{vector to GDB serial line send function}
\label{gdb-serial-send}
\begin{apisyn}
	\cinclude{oskit/gdb_serial.h}

	{\tt void (*\csymbol{gdb_serial_send})(int {\em ch});}
\end{apisyn}
\begin{apidesc}
	Before the remote serial-line debugging stub can be used,
	this global variable must be initialized
	to point to a function to call
	to send out a character on the serial port.

	Calling functions in the GDB serial-line debugging stub
	before this variable is initialized
	(i.e., while it is still null)
	is guaranteed to be harmless.
\end{apidesc}
\begin{apiret}
	Returns the character received.
\end{apiret}

\api{gdb_pc_com_init}{\intelpc\ set up serial-line debugging over a COM port}
\label{gdb-pc-com-init}
\begin{apisyn}
	\cinclude{oskit/gdb.h}

	\funcproto void gdb_pc_com_init(int com_port,
					struct~termios *com_params);
\end{apisyn}
\begin{apidesc}
	This is a simple ``wrapper'' function
	which ties together all of the \oskit{}'s remote debugging facilities
	to automatically create a complete remote debugging environment
	for a specific, typical configuration:
	namely, remote serial-line debugging on a PC through a COM port.
	This function can be used as-is
	if this configuration happens to suit your purposes,
	or it can be used as an example
	for setting up the debugging facilities for other configurations.

	Specifically, this function does the following:
	\begin{itemize}
	\item	Sets all entries in the {\tt base_trap_handlers} array
		to point to {\tt gdb_trap}.
		This establishes the GDB debugging trap handler
		as the basic handler used to handle all processor traps.
	\item	Sets the {\tt gdb_signal} variable
		to point to {\tt gdb_serial_signal}.
		This ``connects'' the generic GDB debugging code
		to the serial-line debugging stub.
	\item	Sets {\tt gdb_serial_recv} to point to {\tt com_cons_getchar},
		and {\tt gdb_serial_send} to point to {\tt com_cons_putchar}.
		(Actually a wrapper that gives the port to those functions,
		as they now take a serial port as the first parameter).
		This connects the serial-line debugging stub
		to the simple polling PC COM-port console code.
	\item	Initializes the specified COM port
		using the specified parameters (baud rate, etc.).
	\item	Sets the hardware IRQ vector in the base IDT
		corresponding to the selected COM port
		to point to an interrupt handler
		that invokes the remote debugger with a ``fake'' SIGINT trap,
		and enables the serial port interrupt.
		This allows the remote user to interrupt the running kernel
		by pressing CTRL-C on the remote debugger's console,
		at least if the kernel is running with interrupts enabled.
	\end{itemize}
\end{apidesc}
\begin{apiparm}
	\item[com_port]
		The COM port number through which to communicate:
		must be 1, 2, 3, or 4.
	\item[com_params]
		A pointer to a {\tt termios} structure
		defining the required serial port communication parameters.
		If this parameter is NULL,
		the serial port is set up for 9600,8,N,1 by default.
\end{apiparm}
\begin{apidep}
	\item[gdb_trap]			\ref{gdb-trap}
	\item[gdb_signal]		\ref{gdb-signal}
	\item[gdb_serial_signal]	\ref{gdb-serial-signal}
	\item[gdb_serial_recv]		\ref{gdb-serial-recv}
	\item[gdb_serial_send]		\ref{gdb-serial-send}
	\item[com_cons_init]		\ref{com-cons-init}
	\item[com_cons_getchar]		\ref{com-cons-getchar}
	\item[com_cons_putchar]		\ref{com-cons-putchar}
	\item[com_cons_enable_receive_interrupt]
					\ref{com-cons-enable-receive-interrupt}
	\item[base_idt]			\ref{base-idt}
	\item[base_raw_termios]		\ref{base-raw-termios}
\end{apidep}

\com{
\subsection{Header files}

\begin{itemize}
\item[{\tt gdb_serial.h}]
	Public header file for the serial-line-based remote GDB debugging stub;
	see Section~\ref{gdb-serial}.
\item[{\tt lmm.h}]
	Public header file for the List-based Memory Manager (LMM);
	see Section~\ref{lmm}.
\end{itemize}
}


\apisec{Annotations}
\label{kern-anno}

Kernel annotations are ``markers'' that can be placed in code or static data.
Annotations are static and are collected into a special section
of the object/executable file.
How this section is created is object-file format specific and is
normally handled by the default startup files (e.g, {\tt crt0.o}).

Annotations are organized in tables which is sorted by a key value
(typically the address being marked) at boot time via {\tt anno_init}.

The basic annotation structures look like:

\cstruct{anno_table}{
	struct anno_entry	*start;	/* first entry */
	struct anno_entry	*end;	/* last entry */
};

\cstruct{anno_entry}{
	oskit_addr_t		val1;	/* lookup value */
	oskit_addr_t		val2;	/* context dependent value */
	oskit_addr_t		val3;	/* context dependent value */
	struct anno_table	*table;	/* associated anno_table */
};

Annotation tables contain a pointer to the first and last entries they contain.
All entries in a table are contiguous and sorted by the key value.

Annotation entries specify the table they belong to,
the key value used for lookups, and two uninterpreted values.

Though annotations can be structured arbitrarily,
the \oskit\ supports two common kernel annotation uses:
``trap tables'' and ``interrupt tables.''
These are described in the following {\tt anno_trap} and {\tt anno_intr}
sections.

Currently, annotation support only works with the ELF binary file format
(i.e., it does not work with {\tt a.out}).

\api{anno.h}{\intel\ generic macros to place annotations in kernel code.}
\begin{apisyn}
	\cinclude{oskit/machine/anno.h}

	{\tt \csymbol{ANNO_ENTRY}(table, val1, val2, val3)}

	{\tt \csymbol{ANNO_TEXT}(table, val2, val3)}
\end{apisyn}
\begin{apidesc}
	Contains architecture-dependent, assembly-code callable macros for
	placing annotations in kernel text and initialized data.
	No C-callable versions are included since most C compilers may reorder
	code making exact placement of annotations impossible.

	{\tt ANNO_ENTRY}
	creates a generic annotation entry associated with the indicated table
	and filled with the specified values.

	{\tt ANNO_TEXT}
	records an annotation in the given table for the current point in the
	text (code) segment.
	The current value of the program counter is placed in {\tt val1}.
	The specified values for {\tt val2} and {\tt val3} are recorded.
\end{apidesc}

\api{anno_dump}{dump all annotation tables}
\label{anno-dump}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	\funcproto void anno_dump(void);
\end{apisyn}
\begin{apidesc}
	Dumps, using {\tt printf}, all registered annotation tables and entries.
	Should not be called before {\tt anno_init}.
\end{apidesc}
\begin{apidep}
	\item[printf]			\ref{printf}
\end{apidep}

\api{anno_find_exact}{find annotation table exactly entry matching a value.}
\label{anno-find-exact}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	\funcproto struct~anno_entry *anno_find_exact(struct~anno_table *tab,
		oskit_addr_t val1);
\end{apisyn}
\begin{apidesc}
	Find an entry in the specified annotation table whose {\tt val1}
	field exactly matches the specified value.
\end{apidesc}
\begin{apiparm}
	\item[tab]
		annotation table to search
	\item[val1]
		value to search for
\end{apiparm}
\begin{apiret}
	Returns a pointer to the {\tt anno_entry} matching the value,
	or zero if no entry matches.
\end{apiret}

\api{anno_find_lower}{find greatest annotation table entry below a value.}
\label{anno-find-lower}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	\funcproto struct~anno_entry *anno_find_lower(struct~anno_table *tab,
		oskit_addr_t val1);
\end{apisyn}
\begin{apidesc}
	Find an entry in the specified annotation table with the largest
	{\tt val1} field less than or equal to the specified value.
	If no entry has a lower or equal value, returns zero.
\end{apidesc}
\begin{apiparm}
	\item[tab]
		annotation table to search
	\item[val1]
		value to search for
\end{apiparm}
\begin{apiret}
	Returns a pointer to the appropriate {\tt anno_entry},
	or zero if no lower entry is found.
\end{apiret}

\api{anno_init}{initialize annotation tables and sort the entries.}
\label{anno-init}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	\funcproto void anno_init(void);
\end{apisyn}
\begin{apidesc}
	This routine should be called once at program startup;
	it sorts all of the annotation entries appropriately
	and initializes the annotation tables they reside in.
\end{apidesc}

\api{anno_intr}{\intel\ interrupt annotations}
\label{anno-intr}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	{\tt struct anno_table \csymbol{anno_intr};}

	{\tt \csymbol{ANNO_INTR}(routine, val3)}

	\funcproto void anno_intr_handler(struct~anno_entry *anno,
		struct~trap_state *tstate);
\end{apisyn}
\begin{apidesc}
	The interrupt annotation table {\tt anno_intr} contains entries which
	associate a handler function with ranges of addresses in the kernel.
	Each entry defines an action to be performed if an asynchronous
	exception occurs between the address associated with this entry
	and that associated with the following entry.
	When an interrupt occurs,
	the default \oskit\ interrupt handler (in {\tt base_irq_inittab.S})
	uses {\tt anno_find_lower} to locate the correct annotation entry
	based on the instruction pointer at the time of the interrupt.
	This handler function is invoked {\em prior to} calling the standard
	interrupt handling function.

	{\tt ANNO_INTR}
	is a macro in {\tt oskit/x86/anno.h}.
	It records an annotation in {\tt anno_intr}
	for the current point in the code segment.
	The given {\em routine} and {\em val3} arguments are stored in
	the entry's {\tt val2} and {\tt val3} fields respectively.
	To disable interrupt redirection for a piece of code,
	place an {\tt ANNO_INTR(0,0)} call before it.

	The annotation interrupt handler function is called in the context
	of the interrupted thread with a pointer to the associated annotation
	entry and a pointer to the architecture-specific trap state
	for the thread.
	On return from the annotation handler,
	the actual interrupt handler is called.

	An example of interrupt annotation usage in a kernel is an
	efficient alternative to using ``spls''
	(i.e., raising processor priority)
	to protect critical sections from interrupts.
	By marking the critical section with an annotation entry,
	the kernel detects when an interrupt occurs within it and invokes an
	associated roll-back or roll-forward routine to back out of or complete
	the critical section before invoking the interrupt handler.
\end{apidesc}

\api{anno_trap}{\intel\ trap annotations}
\label{anno-trap}
\begin{apisyn}
	\cinclude{oskit/anno.h}

	{\tt struct anno_table \csymbol{anno_trap};}

	{\tt \csymbol{ANNO_TRAP}(routine, val3)}

	\funcproto int anno_trap_handler(struct~anno_entry *anno,
		struct~trap_state *tstate);
\end{apisyn}
\begin{apidesc}
	The trap annotation table {\tt anno_trap} contains entries which
	associate a handler function with specific addresses in the kernel.
	These addresses correspond to points where synchronous exceptions
	are expected to occur.
	When such an exception occurs,
	the default \oskit\ trap handler (in {\tt base_trap_inittab.S})
	uses {\tt anno_find_exact} to locate an annotation entry based
	on the instruction pointer at the time of the fault.
	This handler function is invoked {\em instead of}
	the standard kernel trap handler in those instances.

	{\tt ANNO_TRAP}
	is a macro in {\tt oskit/x86/anno.h}.
	It records an annotation in {\tt anno_trap}
	for the current point in the code segment.
	The given {\em routine} and {\em val3} arguments are stored in
	the entry's {\tt val2} and {\tt val3} fields respectively.

	The annotation trap handler function is called in the context
	of the faulting thread with a pointer to the matching annotation
	entry and a pointer to the architecture-specific trap state
	for the thread.
	If the handler returns zero, the \oskit\ trap handler will restore
	state from the trap state structure and resume execution.
	If it returns non-zero, it is considered a failed fault and the
	kernel will panic.

	An example of trap annotation usage is a kernel {\tt copyin} routine
	which must read data in the user's address space.
	Associating an annotation entry with the instruction which moves data
	from the user's address space enables the kernel to catch any access
	violation caused and reflect it to the user.
\end{apidesc}

\apisec{Boot Module Filesystem}
\label{bmod-fs}

The Boot Module (BMOD) filesystem is derived from the 
trivial memory-based filesystem, memfs (Chapter~\ref{memfs}),
exporting
the \oskit{} filesystem interface.
The initial contents of the BMOD filesystem are loaded from the Multiboot
boot image.
This allows an \oskit{} kernel to load a filesystem at boot time,
possibly not even requiring an actual disk-based filesystem.

XXX multiboot strings are parsed to create hierarchical filesystem.
XXX new BMODs may be added, multiboot BMODs may be modified or destroyed.
XXX no guarantee on alignment of multiboot created BMOD files.

\api{start_fs_bmod}{Create the BMOD filesystem}
\begin{apisyn}
	\cinclude{oskit/fs/memfs.h}
	\cinclude{oskit/startup.h}

	\funcproto oskit_dir_t *start_fs_bmod(void);
\end{apisyn}
\begin{apidesc}
	Initialize the BMOD filesystem.  Create the supporting memfs,
	and load it with the contents of the multiboot BMODs.
\end{apidesc}
\begin{apiret}
	Returns a handle to the root of the BMOD filesystem
\end{apiret}


\apisec{Signals}
\label{kern-signals}

The signal handling facilities allow the client OS to provide compatibility
with \posix{} style signal handling semantics. The support provided is
extremely basic and is intended to be used in conjunction with the
\oskit{}'s \freebsd{} C library (see Section \ref{freebsd-libc}) by arranging
for unexpected hardware traps to be converted into an appropriate signal
and delivered through the C library. By default, the \freebsd{} C library will
not arrange for signals to be delivered unless the {\tt oskit_init_libc}
initialization routine is called (see Section~\ref{oskit-init-libc}).
The exception are kernels linked with the \posix{} threads module, which
will {\em always} call the initialization routine.

\api{oskit_sendsig_init}{initialize kernel signal delivery}
\begin{apisyn}
	\cinclude{oskit/c/signal.h}

	\funcproto void oskit_sendsig_init(int
                    (*deliver_function)(int signo, int code,
                                        struct~trap_state *ts));
\end{apisyn}
\begin{apidesc}
	Initialize the kernel signal delivery mechanism, providing an upper
	level signal delivery routine. This delivery function will usually
	be an entrypoint in the C library that provides the appropriate
	signal semantics to the application. This entrypoint is responsible
	for converting the machine dependent trap state information into a
	suitable signal context structure, as defined by the API of the
	library in use. Since a pointer to the trap state structure is
	passed along, the callee is free to modify the machine state in way
	it wishes. 
\end{apidesc}
\begin{apidep}
	\item[oskit_init_libc]	\ref{oskit-init-libc}
	\item[oskit_init_libc]	\ref{oskit-init-freebsd-libc}
\end{apidep}

\api{oskit_sendsig}{deliver a signal}
\begin{apisyn}
	\cinclude{oskit/c/signal.h}\\
	\cinclude{oskit/x86/base_trap.h}

	\funcproto int oskit_sendsig(int signo, struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	Propagate a machine trap to the signal handling entrypoint provided
	to {\tt oskit_sendsig_init()} above. This routine is intended to be
	called by modules that have replaced a particular trap handler, and
	wish to propagate the trap to the application in the form of a
	signal. If the C library has not called {\tt oskit_sendsig_init()},
	the routine returns without doing anything.
\end{apidesc}
\begin{apiparm}
	\item[signo]
		The signal number.
	\item[state]
		A pointer to the trap state structure.
\end{apiparm}
\begin{apiret}
	Returns non-zero if a C library handler has not been installed, and
	thus the signal could not be propagated.
\end{apiret}

\api{sendsig_trap_handler}{convert trap into a signal}
\begin{apisyn}
	\cinclude{oskit/c/signal.h}\\
	\cinclude{oskit/x86/base_trap.h}

	\funcproto void oskit_sendsig(struct~trap_state *state);
\end{apisyn}
\begin{apidesc}
	Convert the machine dependent trap state structure {\tt state} (see
	Section \ref{trap-state}) into a signal code, and pass that, along
	with the trap state, to the C library via {\tt oskit_sendsig} above.

	This routine is provided as a default trap handler that can be
	plugged into the {\tt base_trap_handlers} array (see Section
	\ref{base-trap-handlers}). Unexpected hardware traps are thus
	converted into signals and delivered to the application through
	the C library.
\end{apidesc}
\begin{apiparm}
	\item[state]
		A pointer to the trap state structure.
\end{apiparm}