summaryrefslogtreecommitdiffstats
path: root/sys/i386/i386/userconfig.c
blob: 150538530115a4f132bd3a060e59da46cece332e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
/**
 ** Copyright (c) 1995
 **      Michael Smith, msmith@atrad.adelaide.edu.au.  All rights reserved.
 **
 ** This code contains a module marked :

 * Copyright (c) 1991 Regents of the University of California.
 * All rights reserved.
 * Copyright (c) 1994 Jordan K. Hubbard
 * All rights reserved.
 * Copyright (c) 1994 David Greenman
 * All rights reserved.
 *
 * Many additional changes by Bruce Evans
 *
 * This code is derived from software contributed by the
 * University of California Berkeley, Jordan K. Hubbard,
 * David Greenman and Bruce Evans.

 ** As such, it contains code subject to the above copyrights.
 ** The module and its copyright can be found below.
 ** 
 ** Redistribution and use in source and binary forms, with or without
 ** modification, are permitted provided that the following conditions
 ** are met:
 ** 1. Redistributions of source code must retain the above copyright
 **    notice, this list of conditions and the following disclaimer as
 **    the first lines of this file unmodified.
 ** 2. Redistributions in binary form must reproduce the above copyright
 **    notice, this list of conditions and the following disclaimer in the
 **    documentation and/or other materials provided with the distribution.
 ** 3. All advertising materials mentioning features or use of this software
 **    must display the following acknowledgment:
 **      This product includes software developed by Michael Smith.
 ** 4. The name of the author may not be used to endorse or promote products
 **    derived from this software without specific prior written permission.
 **
 ** THIS SOFTWARE IS PROVIDED BY MICHAEL SMITH ``AS IS'' AND ANY EXPRESS OR
 ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 ** IN NO EVENT SHALL MICHAEL SMITH BE LIABLE FOR ANY DIRECT, INDIRECT,
 ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **      $Id: userconfig.c,v 1.79 1996/12/23 12:33:08 joerg Exp $
 **/

/**
 ** USERCONFIG
 **
 ** Kernel boot-time configuration manipulation tool for FreeBSD.
 **
 ** Two modes of operation are supported : the default is the line-editor mode,
 ** the command "visual" invokes the fullscreen mode.
 **
 ** The line-editor mode is the old favorite from FreeBSD 2.0/20.05 &c., the 
 ** fullscreen mode requires syscons or a minimal-ansi serial console.
 **/

/**
 ** USERCONFIG, visual mode.
 **
 **   msmith@atrad.adelaide.edu.au
 **
 ** Look for "EDIT THIS LIST" to add to the list of known devices
 ** 
 **
 ** There are a number of assumptions made in this code.
 ** 
 ** - That the console supports a minimal set of ANSI escape sequences
 **   (See the screen manipulation section for a summary)
 **   and has at least 24 rows.
 ** - That values less than or equal to zero for any of the device
 **   parameters indicate that the driver does not use the parameter.
 ** - That the only tunable parameter for PCI devices are their flags.
 ** - That flags are _always_ editable.
 **
 ** Devices marked as disabled are imported as such.  PCI devices are 
 ** listed under a seperate heading for informational purposes only.
 ** To date, there is no means for changing the behaviour of PCI drivers
 ** from UserConfig.
 **
 ** Note that some EISA devices probably fall into this category as well,
 ** and in fact the actual bus supported by some drivers is less than clear.
 ** A longer-term goal might be to list drivers by instance rather than
 ** per bus-presence.
 ** 
 ** For this tool to be useful, the list of devices below _MUST_ be updated 
 ** when a new driver is brought into the kernel.  It is not possible to 
 ** extract this information from the drivers in the kernel.
 **
 ** XXX - TODO:
 ** 
 ** - Display _what_ a device conflicts with.
 ** - Implement page up/down (as what?)
 ** - Wizard mode (no restrictions)
 ** - Find out how to put syscons back into low-intensity mode so that the
 **   !b escape is useful on the console.  (It seems to be that it actually
 **   gets low/high intensity backwards. That looks OK.)
 **
 ** - Only display headings with devices under them. (difficult)
 **/

#include "opt_userconfig.h"
#include "pci.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>

#include <machine/cons.h>
#include <machine/md_var.h>

#include <i386/isa/isa_device.h>

#include <pci/pcivar.h>

static struct isa_device *isa_devlist;	/* list read by dset to extract changes */

#ifdef USERCONFIG_BOOT
char userconfig_from_boot[512] = "";

static int
getchar(void)
{
    static char *next = userconfig_from_boot;

    if (next == userconfig_from_boot) {
	if (strncmp(next, "USERCONFIG\n", 11)) {
	    next++;
	    strcpy(next, "intro\n");
	} else {
	    next += 11;
	}
    } 
    if (*next) {
	return (*next++);
    } else {
	return cngetc();
    }
}
#else /* !USERCONFIG_BOOT */
#define getchar()	cngetc()
#endif /* USERCONFIG_BOOT */

#define putchar(x)	cnputc(x)

#ifndef FALSE
#define FALSE	(0)
#define TRUE	(!FALSE)
#endif

#ifdef VISUAL_USERCONFIG
static struct isa_device *devtabs[] = { isa_devtab_bio, isa_devtab_tty, isa_devtab_net,
				     isa_devtab_null, NULL };

typedef struct
{
    char	dev[16];		/* device basename */
    char	name[60];		/* long name */
    int		attrib;			/* things to do with the device */
    int		class;			/* device classification */
} DEV_INFO;

#define FLG_INVISIBLE	(1<<0)		/* device should not be shown */
#define FLG_MANDATORY	(1<<1)		/* device can be edited but not disabled */
#define FLG_FIXIRQ	(1<<2)		/* device IRQ cannot be changed */
#define FLG_FIXIOBASE	(1<<3)		/* device iobase cannot be changed */
#define FLG_FIXMADDR	(1<<4)		/* device maddr cannot be changed */
#define FLG_FIXMSIZE	(1<<5)		/* device msize cannot be changed */
#define FLG_FIXDRQ	(1<<6)		/* device DRQ cannot be changed */
#define FLG_FIXED	(FLG_FIXIRQ|FLG_FIXIOBASE|FLG_FIXMADDR|FLG_FIXMSIZE|FLG_FIXDRQ)
#define FLG_IMMUTABLE	(FLG_FIXED|FLG_MANDATORY)

#define CLS_STORAGE	1		/* storage devices */
#define CLS_NETWORK	2		/* network interfaces */
#define CLS_COMMS	3		/* serial, parallel ports */
#define CLS_INPUT	4		/* user input : mice, keyboards, joysticks etc */
#define CLS_MMEDIA	5		/* "multimedia" devices (sound, video, etc) */
#define CLS_PCI		254		/* PCI devices */
#define CLS_MISC	255		/* none of the above */


typedef struct 
{
    char	name[60];
    int		number;
} DEVCLASS_INFO;

static DEVCLASS_INFO devclass_names[] = {
{	"Storage :        ",	CLS_STORAGE},
{	"Network :        ",	CLS_NETWORK},
{	"Communications : ",	CLS_COMMS},
{	"Input :          ",	CLS_INPUT},
{	"Multimedia :     ",	CLS_MMEDIA},
{	"PCI :            ",	CLS_PCI},
{	"Miscellaneous :  ",	CLS_MISC},
{	"",0}};


/********************* EDIT THIS LIST **********************/

/** Notes :
 ** 
 ** - PCI devices should be marked FLG_IMMUTABLE.  They should not be movable
 **   or editable, and have no attributes.  This is handled in getdevs() and
 **   devinfo(), so drivers that have a presence on busses other than PCI
 **   should have appropriate flags set below.
 ** - Devices that shouldn't be seen or removed should be marked FLG_INVISIBLE.
 ** - XXX The list below should be reviewed by the driver authors to verify
 **   that the correct flags have been set for each driver, and that the
 **   descriptions are accurate.
 **/

static DEV_INFO device_info[] = {
/*---Name-----   ---Description---------------------------------------------- */
{"bt",          "Buslogic SCSI controller",		0,		CLS_STORAGE},
{"ahc",         "Adaptec 274x/284x/294x SCSI controller",	0,	CLS_STORAGE},
{"ahb",         "Adaptec 174x SCSI controller",		0,		CLS_STORAGE},
{"aha",         "Adaptec 154x SCSI controller",		0,		CLS_STORAGE},
{"uha",         "Ultrastor 14F/24F/34F SCSI controller",0,		CLS_STORAGE},
{"aic",         "Adaptec 152x SCSI and compatible sound cards",	0,      CLS_STORAGE},
{"nca",         "ProAudio Spectrum SCSI and compatibles",	0,	CLS_STORAGE},
{"sea",         "Seagate ST01/ST02 SCSI and compatibles",	0,	CLS_STORAGE},
{"wds",         "Western Digitial WD7000 SCSI controller",	0,	CLS_STORAGE},
{"ncr",         "NCR/Symbios 53C810/15/25/60/75 SCSI controller",FLG_FIXED,CLS_STORAGE},
{"wdc",         "IDE/ESDI/MFM disk controller",		0,		CLS_STORAGE},
{"fdc",         "Floppy disk controller",		FLG_FIXED,	CLS_STORAGE},
{"mcd",         "Mitsumi CD-ROM",			0,		CLS_STORAGE},
{"scd",         "Sony CD-ROM",				0,		CLS_STORAGE},
{"matcdc",       "Matsushita/Panasonic/Creative CDROM",	0,		CLS_STORAGE},
{"wt",          "Wangtek/Archive QIC-02 Tape drive",	0,		CLS_STORAGE},
{"amd",		"Tekram DC-390(T) / AMD 53c974 based PCI SCSI",	FLG_FIXED, CLS_STORAGE},

{"ed",          "NE1000,NE2000,3C503,WD/SMC80xx Ethernet adapters",0,	CLS_NETWORK},
{"el",          "3C501 Ethernet adapter",		0,		CLS_NETWORK},
{"ep",          "3C509 Ethernet adapter",		0,		CLS_NETWORK},
{"fe",          "Fujitsu MD86960A/MB869685A Ethernet adapters",	0,	CLS_NETWORK},
{"fea",         "DEC DEFEA EISA FDDI adapter",		0,		CLS_NETWORK},
{"fxp",         "Intel EtherExpress Pro/100B Ethernet adapter",	0,	CLS_NETWORK},
{"ie",          "AT&T Starlan 10 and EN100, 3C507, NI5210 Ethernet adapters",0,CLS_NETWORK},
{"ix",          "Intel EtherExpress Ethernet adapter",	0,		CLS_NETWORK},
{"le",          "DEC Etherworks 2 and 3 Ethernet adapters",	0,	CLS_NETWORK},
{"lnc",         "Isolan, Novell NE2100/NE32-VL Ethernet adapters",	0,CLS_NETWORK},
{"vx",          "3COM 3C590/3C595 Ethernet adapters",		0,	CLS_NETWORK},
{"ze",          "IBM/National Semiconductor PCMCIA Ethernet adapter",0,	CLS_NETWORK},
{"zp",          "3COM PCMCIA Etherlink III Ethernet adapter",	0,	CLS_NETWORK},
{"de",          "DEC DC21040 Ethernet adapter",		FLG_FIXED,	CLS_NETWORK},
{"fpa",         "DEC DEFPA PCI FDDI adapter",		FLG_FIXED,	CLS_NETWORK},

{"sio",         "8250/16450/16550 Serial port",		0,		CLS_COMMS},
{"cx",          "Cronyx/Sigma multiport sync/async adapter",0,		CLS_COMMS},
{"rc",          "RISCom/8 multiport async adapter",	0,		CLS_COMMS},
{"cy",          "Cyclades multiport async adapter",	0,		CLS_COMMS},
{"cyy",         "Cyclades Ye/PCI multiport async adapter",FLG_INVISIBLE,CLS_COMMS},
{"dgb",         "Digiboard PC/Xe, PC/Xi async adapter",	0,		CLS_COMMS},
{"si",          "Specialix SI/XIO async adapter",	0,		CLS_COMMS},
{"stl",         "Stallion EasyIO/Easy Connection 8/32 async adapter",0,	CLS_COMMS},
{"stli",        "Stallion intelligent async adapter"	,0,		CLS_COMMS},
{"lpt",         "Parallel printer port",		0,		CLS_COMMS},
{"gp",          "National Instruments AT-GPIB/TNT driver",	0,	CLS_COMMS},

{"mse",         "Microsoft Bus Mouse",			0,		CLS_INPUT},
{"psm",         "PS/2 Mouse",				0,		CLS_INPUT},
{"joy",         "Joystick",				FLG_FIXED,	CLS_INPUT},
{"vt",          "PCVT console driver",			FLG_FIXED,	CLS_INPUT},
{"sc",          "Syscons console driver",		FLG_FIXED,	CLS_INPUT},

{"sb",          "Soundblaster PCM (SB, SBPro, SB16, ProAudio Spectrum)",0,CLS_MMEDIA},
{"sbxvi",       "Soundblaster 16",			0,		CLS_MMEDIA},
{"sbmidi",      "Soundblaster MIDI interface",		0,		CLS_MMEDIA},
{"pas",         "ProAudio Spectrum PCM and MIDI",	0,		CLS_MMEDIA},
{"gus",         "Gravis Ultrasound, Ultrasound 16 and Ultrasound MAX",0,CLS_MMEDIA},
{"gusxvi",      "Gravis Ultrasound 16-bit PCM",		0,		CLS_MMEDIA},
{"gusmax",      "Gravis Ultrasound MAX",		0,		CLS_MMEDIA},
{"mss",         "Microsoft Sound System",		0,		CLS_MMEDIA},
{"opl",         "OPL-2/3 FM, Soundblaster, SBPro, SB16, ProAudio Spectrum",0,CLS_MMEDIA},
{"mpu",         "Roland MPU401 MIDI",			0,		CLS_MMEDIA},
{"uart",        "6850 MIDI UART",			0,		CLS_MMEDIA},
{"pca",         "PC speaker PCM audio driver",		FLG_FIXED,	CLS_MMEDIA},
{"ctx",         "Coretex-I frame grabber",		0,		CLS_MMEDIA},
{"spigot",      "Creative Labs Video Spigot video capture",	0,	CLS_MMEDIA},
{"scc",         "IBM Smart Capture Card",		0,		CLS_MMEDIA},
{"gsc",         "Genius GS-4500 hand scanner",		0,		CLS_MMEDIA},
{"asc",         "AmiScan scanner",			0,		CLS_MMEDIA},
{"qcam",	"QuickCam parallel port camera",	0,		CLS_MMEDIA},

{"apm",         "Advanced Power Management",		FLG_FIXED,	CLS_MISC},
{"labpc",       "National Instruments Lab-PC/Lab-PC+",	0,		CLS_MISC},
{"npx",	        "Math coprocessor",			FLG_INVISIBLE,	CLS_MISC},
{"lkm",		"Loadable PCI driver support",		FLG_INVISIBLE,	CLS_MISC},
{"vga",		"Catchall PCI VGA driver",		FLG_INVISIBLE,	CLS_MISC},
{"chip",	"PCI chipset support",			FLG_INVISIBLE,	CLS_MISC},
{"piix",        "Intel 82371 Bus-master IDE controller", FLG_INVISIBLE, CLS_MISC},
{"","",0,0}};


typedef struct _devlist_struct
{
    char	name[80];
    int		attrib;			/* flag values as per the FLG_* defines above */
    int		class;			/* disk, etc as per the CLS_* defines above */
    char	dev[16];
    int		iobase,irq,drq,maddr,msize,unit,flags,conflict_ok,id;
    int		comment;		/* 0 = device, 1 = comment, 2 = collapsed comment */
    int		conflicts;		/* set/reset by findconflict, count of conflicts */
    int		changed;		/* nonzero if the device has been edited */
    struct isa_device	*device;
    struct _devlist_struct *prev,*next;
} DEV_LIST;


#define DEV_DEVICE	0
#define DEV_COMMENT	1
#define DEV_ZOOMED	2

#define	LIST_CURRENT	(1<<0)
#define LIST_SELECTED	(1<<1)

#define KEY_EXIT	0	/* return codes from dolist() and friends */
#define KEY_DO		1
#define KEY_DEL		2
#define KEY_TAB		3
#define KEY_REDRAW	4

#define KEY_UP		5	/* these only returned from editval() */
#define KEY_DOWN	6
#define KEY_LEFT	7
#define KEY_RIGHT	8
#define KEY_NULL	9	/* this allows us to spin & redraw */

#define KEY_ZOOM	10	/* these for zoom all/collapse all */
#define KEY_UNZOOM	11

#define KEY_HELP	12	/* duh? */

static void redraw(void);
static void insdev(DEV_LIST *dev, DEV_LIST *list);
static int  devinfo(DEV_LIST *dev);
static int  visuserconfig(void);

static DEV_LIST	*active = NULL,*inactive = NULL;	/* driver lists */
static DEV_LIST	*alist,*ilist;				/* visible heads of the driver lists */
static DEV_LIST	scratch;				/* scratch record */
static int	conflicts;				/* total conflict count */


static char lines[] = "--------------------------------------------------------------------------------";
static char spaces[] = "                                                                                     ";


/**
 ** Device manipulation stuff : find, describe, configure.
 **/

/**
 ** setdev
 **
 ** Sets the device referenced by (*dev) to the parameters in the struct,
 ** and the enable flag according to (enabled)
 **/
static void 
setdev(DEV_LIST *dev, int enabled)
{
    if (dev->iobase == -2)						/* PCI device */
	return;
    dev->device->id_iobase = dev->iobase;				/* copy happy */
    dev->device->id_irq = (u_short)(dev->irq < 16 ? 1<<dev->irq : 0);	/* IRQ is bitfield */
    dev->device->id_drq = (short)dev->drq;
    dev->device->id_maddr = (caddr_t)dev->maddr;
    dev->device->id_msize = dev->msize;
    dev->device->id_flags = dev->flags;
    dev->device->id_enabled = enabled;
}


/**
 ** getdevs
 **
 ** Walk the kernel device tables and build the active and inactive lists
 **/
static void 
getdevs(void)
{
    int 		i,j;
    struct isa_device	*ap;

    for (j = 0; devtabs[j]; j++)			/* ISA devices */
    {
	ap = devtabs[j];				/* pointer to array of devices */
	for (i = 0; ap[i].id_id; i++)			/* for each device in this table */
	{
	    scratch.unit = ap[i].id_unit;		/* device parameters */
	    strcpy(scratch.dev,ap[i].id_driver->name);
	    scratch.iobase = ap[i].id_iobase;
	    scratch.irq = ffs(ap[i].id_irq)-1;
	    scratch.drq = ap[i].id_drq;
	    scratch.maddr = (int)ap[i].id_maddr;
	    scratch.msize = ap[i].id_msize;
	    scratch.flags = ap[i].id_flags;
	    scratch.conflict_ok = ap[i].id_conflicts;

	    scratch.comment = DEV_DEVICE;		/* admin stuff */
	    scratch.conflicts = 0;
	    scratch.device = &ap[i];			/* save pointer for later reference */
	    scratch.changed = 0;
	    if (!devinfo(&scratch))			/* get more info on the device */
		insdev(&scratch,ap[i].id_enabled?active:inactive);
	}
    }
#if NPCI > 0
    for (i = 0; i < pcidevice_set.ls_length; i++)
    {
	if (pcidevice_set.ls_items[i])
	{
	    if (((const struct pci_device *)pcidevice_set.ls_items[i])->pd_name)
	    {
		strcpy(scratch.dev,((const struct pci_device *)pcidevice_set.ls_items[i])->pd_name);
		scratch.iobase = -2;			/* mark as PCI for future reference */
		scratch.irq = -2;
		scratch.drq = -2;
		scratch.maddr = -2;
		scratch.msize = -2;
		scratch.flags = 0;
		scratch.conflict_ok = 0;		/* shouldn't conflict */
		scratch.comment = DEV_DEVICE;		/* is a device */
		scratch.unit = 0;			/* arbitrary number of them */
		scratch.conflicts = 0;
		scratch.device = NULL;	
		scratch.changed = 0;

		if (!devinfo(&scratch))			/* look up name, set class and flags */
		    insdev(&scratch,active);		/* always active */
	    }
	}
    }
#endif	/* NPCI > 0 */
}


/**
 ** Devinfo
 **
 ** Fill in (dev->name), (dev->attrib) and (dev->type) from the device_info array.
 ** If the device is unknown, put it in the CLS_MISC class, with no flags.
 **
 ** If the device is marked "invisible", return nonzero; the caller should
 ** not insert any such device into either list.
 **
 ** PCI devices are always inserted into CLS_PCI, regardless of the class associated
 ** with the driver type.
 **/
static int
devinfo(DEV_LIST *dev)
{
    int		i;

    for (i = 0; device_info[i].class; i++)
    {
	if (!strcmp(dev->dev,device_info[i].dev))
	{
	    if (device_info[i].attrib & FLG_INVISIBLE)	/* forget we ever saw this one */
		return(1);
	    strcpy(dev->name,device_info[i].name);	/* get the name */
	    if (dev->iobase == -2) {			/* is this a PCI device? */
		dev->attrib = FLG_IMMUTABLE;		/* dark green ones up the back... */
		dev->class = CLS_PCI;
	    } else {
		dev->attrib = device_info[i].attrib;	/* light green ones up the front */
		dev->class = device_info[i].class;
	    }
	    return(0);
	}
    }
    strcpy(dev->name,"Unknown device");
    dev->attrib = 0;
    dev->class = CLS_MISC;
    return(0);
}
    

/**
 ** List manipulation stuff : add, move, initialise, free, traverse
 **
 ** Note that there are assumptions throughout this code that
 ** the first entry in a list will never move. (assumed to be
 ** a comment).
 **/


/**
 ** Adddev
 ** 
 ** appends a copy of (dev) to the end of (*list)
 **/
static void 
addev(DEV_LIST *dev, DEV_LIST **list)
{

    DEV_LIST	*lp,*ap;

    lp = (DEV_LIST *)malloc(sizeof(DEV_LIST),M_DEVL,M_WAITOK);
    bcopy(dev,lp,sizeof(DEV_LIST));			/* create copied record */

    if (*list)						/* list exists */
    {
	ap = *list;
	while(ap->next)
	    ap = ap->next;				/* scoot to end of list */
	lp->prev = ap;
	lp->next = NULL;
	ap->next = lp;
    }else{						/* list does not yet exist */
	*list = lp;
	lp->prev = lp->next = NULL;			/* list now exists */
    }
}


/**
 ** Findspot
 **
 ** Finds the 'appropriate' place for (dev) in (list)
 **
 ** 'Appropriate' means in numeric order with other devices of the same type,
 ** or in alphabetic order following a comment of the appropriate type.
 ** or at the end of the list if an appropriate comment is not found. (this should
 ** never happen)
 ** (Note that the appropriate point is never the top, but may be the bottom)
 **/
static DEV_LIST	*
findspot(DEV_LIST *dev, DEV_LIST *list)
{
    DEV_LIST	*ap = NULL;

    /* search for a previous instance of the same device */
    if (dev->iobase != -2)	/* avoid PCI devices grouping with non-PCI devices */
    {
	for (ap = list; ap; ap = ap->next)
	{
	    if (ap->comment != DEV_DEVICE)			/* ignore comments */
		continue;
	    if (ap->iobase == -2)				/* don't group with a PCI device */
		continue;
	    if (!strcmp(dev->dev,ap->dev))			/* same base device */
	    {
		if ((dev->unit <= ap->unit)			/* belongs before (equal is bad) */
		    || !ap->next)				/* or end of list */
		{
		    ap = ap->prev;				/* back up one */
		    break;					/* done here */
		}
		if (ap->next)					/* if the next item exists */
		{
		    if (ap->next->comment != DEV_DEVICE)	/* next is a comment */
			break;
		    if (strcmp(dev->dev,ap->next->dev))		/* next is a different device */
			break;
		}
	    }
	}
    }

    if (!ap)						/* not sure yet */
    {
	/* search for a class that the device might belong to */
	for (ap = list; ap; ap = ap->next)
	{
	    if (ap->comment != DEV_DEVICE)		/* look for simlar devices */
		continue;
	    if (dev->class != ap->class)		/* of same class too 8) */
		continue;
	    if (strcmp(dev->dev,ap->dev) < 0)		/* belongs before the current entry */
	    {
		ap = ap->prev;				/* back up one */
		break;					/* done here */
	    }
	    if (ap->next)				/* if the next item exists */
		if (ap->next->comment != DEV_DEVICE)	/* next is a comment, go here */
		    break;
	}
    }

    if (!ap)						/* didn't find a match */
    {
	for (ap = list; ap->next; ap = ap->next)	/* try for a matching comment */
	    if ((ap->comment != DEV_DEVICE) 
		&& (ap->class == dev->class))		/* appropriate place? */
		break;
    }							/* or just put up with last */

    return(ap);
}


/**
 ** Insdev
 **
 ** Inserts a copy of (dev) at the appropriate point in (list)
 **/
static void 
insdev(DEV_LIST *dev, DEV_LIST *list)
{
    DEV_LIST	*lp,*ap;

    lp = (DEV_LIST *)malloc(sizeof(DEV_LIST),M_DEVL,M_WAITOK);
    bcopy(dev,lp,sizeof(DEV_LIST));			/* create copied record */

    ap = findspot(lp,list);				/* find appropriate spot */
    lp->next = ap->next;				/* point to next */
    if (ap->next)
	ap->next->prev = lp;				/* point next to new */
    lp->prev = ap;					/* point new to current */
    ap->next = lp;					/* and current to new */
}


/**
 ** Movedev
 **
 ** Moves (dev) from its current list to an appropriate place in (list)
 ** (dev) may not come from the top of a list, but it may from the bottom.
 **/
static void 
movedev(DEV_LIST *dev, DEV_LIST *list)
{
    DEV_LIST	*ap;

    ap = findspot(dev,list);
    dev->prev->next = dev->next;			/* remove from old list */
    if (dev->next)
	dev->next->prev = dev->prev;
    
    dev->next = ap->next;				/* insert in new list */
    if (ap->next)
	ap->next->prev = dev;				/* point next to new */
    dev->prev = ap;					/* point new to current */
    ap->next = dev;					/* and current to new */
}


/**
 ** Initlist
 **
 ** Initialises (*list) with the basic headings
 **/
static void 
initlist(DEV_LIST **list)
{
    int		i;

    for(i = 0; devclass_names[i].name[0]; i++)		/* for each devtype name */
    {
	strcpy(scratch.name,devclass_names[i].name);
	scratch.comment = DEV_ZOOMED;
	scratch.class = devclass_names[i].number;
	scratch.attrib = FLG_MANDATORY;			/* can't be moved */
	addev(&scratch,list);				/* add to the list */
    }
}


/**
 ** savelist
 **
 ** Walks (list) and saves the settings of any entry marked as changed.
 **
 ** The device's active field is set according to (active).
 **
 ** Builds the isa_devlist used by dset to extract the changed device information.
 ** The code for this was taken almost verbatim from the original module.
 **/
static void
savelist(DEV_LIST *list, int active)
{
    struct isa_device	*id_p,*id_pn;

    while (list)
    {
	if ((list->comment == DEV_DEVICE) &&		/* is a device */
	    (list->changed) &&				/* has been changed */
	    (list->iobase != -2) &&			/* is not a PCI device */
	    (list->device != NULL)) {			/* has an isa_device structure */

	    setdev(list,active);			/* set the device itself */

	    id_pn = NULL;
	    for (id_p=isa_devlist; id_p; id_p=id_p->id_next) 
	    {						/* look on the list for it */
		if (id_p->id_id == list->device->id_id) 
		{
		    id_pn = id_p->id_next;
		    bcopy(list->device,id_p,sizeof(struct isa_device));
		    id_p->id_next = id_pn;
		    break;
		}
	    }
	    if (!id_pn)					/* not already on the list */
	    {
		id_pn = malloc(sizeof(struct isa_device),M_DEVL,M_WAITOK);
		bcopy(list->device,id_pn,sizeof(struct isa_device));
		id_pn->id_next = isa_devlist;
		isa_devlist = id_pn;			/* park at top of list */
	    }
	}
	list = list->next;
    }
}


/**
 ** nukelist
 **
 ** Frees all storage in use by a (list).
 **/
static void 
nukelist(DEV_LIST *list)
{
    DEV_LIST	*dp;

    if (!list)
	return;
    while(list->prev)					/* walk to head of list */
	list = list->prev;

    while(list)
    {
	dp = list;
	list = list->next;
	free(dp,M_DEVL);
    }
}


/**
 ** prevent
 **
 ** Returns the previous entry in (list), skipping zoomed regions.  Returns NULL
 ** if there is no previous entry. (Only possible if list->prev == NULL given the
 ** premise that there is always a comment at the head of the list)
 **/
static DEV_LIST *
prevent(DEV_LIST *list)
{
    DEV_LIST	*dp;

    if (!list)
	return(NULL);
    dp = list->prev;			/* start back one */
    while(dp)
    {
	if (dp->comment == DEV_ZOOMED)	/* previous section is zoomed */
	    return(dp);			/* so skip to comment */
	if (dp->comment == DEV_COMMENT)	/* not zoomed */
	    return(list->prev);		/* one back as normal */
	dp = dp->prev;			/* backpedal */
    }
    return(dp);				/* NULL, we can assume */
}


/**
 ** nextent
 **
 ** Returns the next entry in (list), skipping zoomed regions.  Returns NULL
 ** if there is no next entry. (Possible if the current entry is last, or
 ** if the current entry is the last heading and it's collapsed)
 **/
static DEV_LIST	*
nextent(DEV_LIST *list)
{
    DEV_LIST	*dp;

    if (!list)
	return(NULL);
    if (list->comment != DEV_ZOOMED)	/* no reason to skip */
	return(list->next);
    dp = list->next;
    while(dp)
    {
	if (dp->comment != DEV_DEVICE)	/* found another heading */
	    break;
	dp = dp->next;
    }
    return(dp);				/* back we go */
}
    

/**
 ** ofsent
 **
 ** Returns the (ofs)th entry down from (list), or NULL if it doesn't exist 
 **/
static DEV_LIST *
ofsent(int ofs, DEV_LIST *list)
{
    while (ofs-- && list)
	list = nextent(list);
    return(list);
}


/**
 ** findconflict
 **
 ** Scans every element of (list) and sets the conflict tags appropriately
 ** Returns the number of conflicts found.
 **/
static int
findconflict(DEV_LIST *list)
{
    int		count = 0;			/* number of conflicts found */
    DEV_LIST	*dp,*sp;

    for (dp = list; dp; dp = dp->next)		/* over the whole list */
    {
	if (dp->comment != DEV_DEVICE)		/* comments don't usually conflict */
	    continue;
	if (dp->iobase == -2)			/* it's a PCI device, not interested */
	    continue;

	dp->conflicts = 0;			/* assume the best */
	for (sp = list; sp; sp = sp->next)	/* scan the entire list for conflicts */
	{
	    if (sp->comment != DEV_DEVICE)	/* likewise */
		continue;
	    if (dp->iobase == -2)		/* it's a PCI device, not interested */
		continue;

	    if (sp == dp)			/* always conflict with itself */
		continue;
	    if (sp->conflict_ok && dp->conflict_ok)
		continue;			/* both allowed to conflict */

	    if ((dp->iobase > 0) &&		/* iobase conflict? */
		(dp->iobase == sp->iobase))
		dp->conflicts = 1;
	    if ((dp->irq > 0) &&		/* irq conflict? */
		(dp->irq == sp->irq))
		dp->conflicts = 1;
	    if ((dp->drq > 0) &&		/* drq conflict? */
		(dp->drq == sp->drq))
		dp->conflicts = 1;
	    if ((dp->maddr > 0) &&		/* maddr conflict? */
		(dp->maddr == sp->maddr))
		dp->conflicts = 1;
	    if ((dp->msize > 0) &&		/* msize conflict? */
		(dp->msize == sp->msize))
		dp->conflicts = 1;
	}
	count += dp->conflicts;			/* count conflicts */
    }
    return(count);
}


/**
 ** expandlist
 **
 ** Unzooms all headings in (list)
 **/
static void
expandlist(DEV_LIST *list)
{
    while(list)
    {
	if (list->comment == DEV_COMMENT)
	    list->comment = DEV_ZOOMED;
	list = list->next;
    }
}


/**
 ** collapselist
 **
 ** Zooms all headings in (list)
 **/
static void
collapselist(DEV_LIST *list)
{
    while(list)
    {
	if (list->comment == DEV_ZOOMED)
	    list->comment = DEV_COMMENT;
	list = list->next;
    }
}


/**
 ** Screen-manipulation stuff
 **
 ** This is the basic screen layout :
 **
 **     0    5   10   15   20   25   30   35   40   45   50   55   60   67   70   75
 **     |....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....
 **    +--------------------------------------------------------------------------------+
 ** 0 -|---Active Drivers----------------------------xx Conflicts------Dev---IRQ--Port--|
 ** 1 -| ........................                                    .......  ..  0x....|
 ** 2 -| ........................                                    .......  ..  0x....|
 ** 3 -| ........................                                    .......  ..  0x....|
 ** 4 -| ........................                                    .......  ..  0x....|
 ** 5 -| ........................                                    .......  ..  0x....|
 ** 6 -| ........................                                    .......  ..  0x....|
 ** 7 -| ........................                                    .......  ..  0x....|
 ** 8 -| ........................                                    .......  ..  0x....|
 ** 9 -|---Inactive Drivers--------------------------------------------Dev--------------|
 ** 10-| ........................                                    .......            |
 ** 11-| ........................                                    .......            |
 ** 12-| ........................                                    .......            |
 ** 13-| ........................                                    .......            |
 ** 14-| ........................                                    .......            |
 ** 15-| ........................                                    .......            |
 ** 16-| ........................                                    .......            |
 ** 17-|------------------------------------------------------UP-DOWN-------------------|
 ** 18-| Relevant parameters for the current device                                     |
 ** 19-|                                                                                |
 ** 20-|                                                                                |
 ** 21-|--------------------------------------------------------------------------------|
 ** 22-| Help texts go here                                                             |
 ** 23-|                                                                                |
 **    +--------------------------------------------------------------------------------+
 **
 ** Help texts
 **
 ** On a collapsed comment :
 **
 ** [Enter] Expand device list      [z]   Expand all lists
 ** [TAB]   Change fields           [Q]   Save and Exit
 **
 ** On an expanded comment :
 ** 
 ** [Enter] Collapse device list    [Z]   Collapse all lists
 ** [TAB]   Change fields           [Q]   Save and Exit
 **
 ** On a comment with no followers
 **
 ** 
 ** [TAB]   Change fields           [Q]   Save and Exit
 **
 ** On a device in the active list
 **
 ** [Enter] Edit device parameters  [DEL] Disable device
 ** [TAB]   Change fields           [Q]   Save and Exit             [?] Help
 **
 ** On a device in the inactive list
 **
 ** [Enter] Enable device
 ** [TAB]   Change fields           [Q]   Save and Exit             [?] Help
 **
 ** While editing parameters
 **
 ** <parameter-specific help here>
 ** [TAB]   Change fields           [Q]   Save device parameters
 **/



/**
 **
 ** The base-level screen primitives :
 **
 ** bold()	- enter bold mode 		\E[1m     (md)
 ** inverse()   - enter inverse mode 		\E[7m     (so)
 ** normal()	- clear bold/inverse mode 	\E[m      (se)
 ** clear()	- clear the screen 		\E[H\E[J  (ce)
 ** move(x,y)	- move the cursor to x,y 	\E[y;xH:  (cm)
 **/

static void 
bold(void)
{
    printf("\033[1m");
}

static void 
inverse(void)
{
    printf("\033[7m");
}

static void 
normal(void)
{
    printf("\033[m");
}

static void 
clear(void)
{
    normal();
    printf("\033[H\033[J");
}

static void 
move(int x, int y)
{
    printf("\033[%d;%dH",y+1,x+1);
}


/**
 **
 ** High-level screen primitives :
 ** 
 ** putxyl(x,y,str,len)	- put (len) bytes of (str) at (x,y), supports embedded formatting
 ** putxy(x,y,str)	- put (str) at (x,y), supports embedded formatting
 ** erase(x,y,w,h)	- clear the box (x,y,w,h)
 ** txtbox(x,y,w,y,str) - put (str) in a region at (x,y,w,h)
 ** putmsg(str)		- put (str) in the message area
 ** puthelp(str)	- put (str) in the upper helpline
 ** pad(str,len)	- pad (str) to (len) with spaces
 ** drawline(row,detail,list,inverse,*dhelp)
 **			- draws a line for (*list) at (row) onscreen.  If (detail) is 
 **			  nonzero, include port, IRQ and maddr, if (inverse) is nonzero,
 **			  draw the line in inverse video, and display (*dhelp) on the
 **                       helpline.
 ** drawlist(row,num,detail,list)
 **			- draw (num) entries from (list) at (row) onscreen, passile (detail)
 **			  through to drawline().
 ** showparams(dev)	- displays the relevant parameters for (dev) below the lists onscreen.
 ** yesno(str)		- displays (str) in the message area, and returns nonzero on 'y' or 'Y'
 ** redraw();		- Redraws the entire screen layout, including the 
 **			- two list panels.
 **/

/** 
 ** putxy
 **   writes (str) at x,y onscreen
 ** putxyl
 **   writes up to (len) of (str) at x,y onscreen.
 **
 ** Supports embedded formatting :
 ** !i - inverse mode.
 ** !b - bold mode.
 ** !n - normal mode.
 **/
static void 
putxyl(int x, int y, char *str, int len)
{
    move(x,y);
    normal();

    while((*str) && (len--))
    {
	if (*str == '!')		/* format escape? */
	{
	    switch(*(str+1))		/* depending on the next character */
	    {
	    case 'i':
		inverse();
		str +=2;		/* skip formatting */
		len++;			/* doesn't count for length */
		break;
		
	    case 'b':
		bold();
		str  +=2;		/* skip formatting */
		len++;			/* doesn't count for length */
		break;

	    case 'n':
		normal();
		str +=2;		/* skip formatting */
		len++;			/* doesn't count for length */
		break;
		
	    default:
		putchar(*str++);	/* not an escape */
	    }
	}else{
	    putchar(*str++);		/* emit the character */
	}
    }
}

#define putxy(x,y,str)	putxyl(x,y,str,-1)


/**
 ** erase
 **
 ** Erases the region (x,y,w,h)
 **/
static void 
erase(int x, int y, int w, int h)
{
    int		i;

    normal();
    for (i = 0; i < h; i++)
	putxyl(x,y++,spaces,w);
}


/** 
 ** txtbox
 **
 ** Writes (str) into the region (x,y,w,h), supports embedded formatting using
 ** putxy.  Lines are not wrapped, newlines must be forced with \n.
 **/
static void 
txtbox(int x, int y, int w, int h, char *str)
{
    int		i = 0;

    h--;
    while((str[i]) && h)
    {
	if (str[i] == '\n')			/* newline */
	{
	    putxyl(x,y,str,(i<w)?i:w);		/* write lesser of i or w */
	    y++;				/* move down */
	    h--;				/* room for one less */
	    str += (i+1);			/* skip first newline */
	    i = 0;				/* zero offset */
	}else{
	    i++;				/* next character */
	}
    }
    if (h)					/* end of string, not region */
	putxyl(x,y,str,w);
}


/**
 ** putmsg
 **
 ** writes (msg) in the helptext area
 **/
static void 
putmsg(char *msg)
{
    erase(0,18,80,3);				/* clear area */
    txtbox(0,18,80,3,msg);
}


/**
 ** puthelp
 **
 ** Writes (msg) in the helpline area
 **/
static void 
puthelp(char *msg)
{
    erase(0,22,80,1);
    putxy(0,22,msg);
}


/**
 ** masterhelp
 **
 ** Draws the help message at the bottom of the screen
 **/
static void
masterhelp(char *msg)
{
    erase(0,23,80,1);
    putxy(0,23,msg);
}


/**
 ** pad 
 **
 ** space-pads a (str) to (len) characters
 **/
static void 
pad(char *str, int len)
{
    int		i;

    for (i = 0; str[i]; i++)			/* find the end of the string */
	;
    if (i >= len)				/* no padding needed */
	return;
    while(i < len)				/* pad */
	str[i++] = ' ';
    str[i] = '\0';
}
						   

/**
 ** drawline
 **
 ** Displays entry (ofs) of (list) in region at (row) onscreen, optionally displaying
 ** the port and IRQ fields if (detail) is nonzero.  If (inverse), in inverse video.
 **
 ** The text (dhelp) is displayed if the item is a normal device, otherwise
 ** help is shown for normal or zoomed comments
 **/
static void 
drawline(int row, int detail, DEV_LIST *list, int inverse, char *dhelp)
{
    char	lbuf[90],nb[70],db[20],ib[16],pb[16];
    
    if (list->comment == DEV_DEVICE)
    {
	nb[0] = ' ';
	strncpy(nb+1,list->name,57);
    }else{
	strncpy(nb,list->name,58);
	if ((list->comment == DEV_ZOOMED) && (list->next))
	    if (list->next->comment == DEV_DEVICE)	/* only mention if there's something hidden */
		strcat(nb,"  (Collapsed)");
    }
    nb[58] = '\0';
    pad(nb,60);
    if (list->conflicts)			/* device in conflict? */
	if (inverse)
	{
	    strcpy(nb+54," !nCONF!i ");		/* tag conflict, careful of length */
	}else{
	    strcpy(nb+54," !iCONF!n ");		/* tag conflict, careful of length */
	}

    if (list->comment == DEV_DEVICE)
    {
	sprintf(db,"%s%d",list->dev,list->unit);
	pad(db,8);
    }else{
	strcpy(db,"        ");
    }
    if ((list->irq > 0) && detail && (list->comment == DEV_DEVICE))
    {
	sprintf(ib," %d",list->irq);
	pad(ib,4);
    }else{
	strcpy(ib,"    ");
    }
    if ((list->iobase > 0) && detail && (list->comment == DEV_DEVICE))
    {
	sprintf(pb,"0x%x",list->iobase);
	pad(pb,7);
    }else{
	strcpy(pb,"       ");
    }

    sprintf(lbuf,"  %s%s%s%s%s",inverse?"!i":"",nb,db,ib,pb);

    putxyl(0,row,lbuf,80);
    if (dhelp)
    {
	switch(list->comment)
	{
	case DEV_DEVICE:	/* ordinary device */
	    puthelp(dhelp);
	    break;
	case DEV_COMMENT:
	    puthelp("");
	    if (list->next)
		if (list->next->comment == DEV_DEVICE)
		    puthelp("  [!bEnter!n] Collapse device list    [!bC!n]    Collapse all lists");
	    break;
	case DEV_ZOOMED:	
	    puthelp("");
	    if (list->next)
		if (list->next->comment == DEV_DEVICE)
		    puthelp("  [!bEnter!n] Expand device list      [!bX!n]    Expand all lists");
	    break;
	default:
	    puthelp("  WARNING: This list entry corrupted!");
	    break;
	}
    }
    move(0,row);				/* put the cursor somewhere relevant */
}


/**
 ** drawlist
 **
 ** Displays (num) lines of the contents of (list) at (row), optionally displaying the
 ** port and IRQ fields as well if (detail) is nonzero
 **
 ** printf in the kernel is essentially useless, so we do most of the hard work ourselves here.
 **/
static void 
drawlist(int row, int num, int detail, DEV_LIST *list)
{
    int		ofs;

    for(ofs = 0; ofs < num; ofs++)
    {
	if (list)
	{
	    drawline(row+ofs,detail,list,0,NULL);	/* NULL -> don't draw empty help string */
	    list = nextent(list);			/* move down visible list */
	}else{
	    erase(0,row+ofs,80,1);
	}
    }
}


/**
 ** redrawactive
 **
 ** Redraws the active list 
 **/
static void
redrawactive(void)
{
    char	cbuf[16];

    if (conflicts)
    {
	sprintf(cbuf,"!i%d conflict%s",conflicts,(conflicts>1)?"s":"");
	putxy(45,0,cbuf);
    }else{
	putxyl(45,0,lines,16);
    }
    drawlist(1,8,1,alist);			/* draw device lists */
}

/**
 ** redrawinactive
 **
 ** Redraws the inactive list 
 **/
static void
redrawinactive(void)
{
    drawlist(10,7,0,ilist);			/* draw device lists */
}


/**
 ** redraw
 **
 ** Clear the screen and redraw the entire layout
 **/
static void 
redraw(void)
{
    clear();
    putxy(0,0,lines);
    putxy(3,0,"!bActive!n-!bDrivers");
    putxy(63,0,"!bDev!n---!bIRQ!n--!bPort");
    putxy(0,9,lines);
    putxy(3,9,"!bInactive!n-!bDrivers");
    putxy(63,9,"!bDev");
    putxy(0,17,lines);
    putxy(0,21,lines);
    masterhelp("  [!bTAB!n]   Change fields           [!bQ!n]   Save and Exit             [!b?!n] Help");

    redrawactive();
    redrawinactive();
}


/**
 ** yesnocancel
 **
 ** Put (str) in the message area, and return 1 if the user hits 'y' or 'Y',
 ** 2 if they hit 'c' or 'C',  or 0 for 'n' or 'N'.
 **/
static int
yesnocancel(char *str)
{

    putmsg(str);
    for(;;)
	switch(getchar())
	{
	case -1:
	case 'n':
	case 'N':
	    return(0);
	    
	case 'y':
	case 'Y':
	    return(1);
	    
	case 'c':
	case 'C':
	    return(2);
	}
}


/**
 ** showparams
 **
 ** Show device parameters in the region below the lists
 **
 **     0    5   10   15   20   25   30   35   40   45   50   55   60   67   70   75
 **     |....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....
 **    +--------------------------------------------------------------------------------+
 ** 17-|--------------------------------------------------------------------------------|
 ** 18-| Port address : 0x0000     Memory address : 0x00000   Conflict allowed          |
 ** 19-| IRQ number   : 00         Memory size    : 0x0000                              |
 ** 20-| Flags        : 0x0000     DRQ number     : 00                                  |
 ** 21-|--------------------------------------------------------------------------------|
 **/
static void 
showparams(DEV_LIST *dev)
{
    char	buf[80];

    erase(0,18,80,3);				/* clear area */
    if (!dev)
	return;
    if (dev->comment != DEV_DEVICE)
	return;


    if (dev->iobase > 0)
    {
	sprintf(buf,"Port address : 0x%x",dev->iobase);
	putxy(1,18,buf);
    } else {
	if (dev->iobase == -2)			/* a PCI device */
	    putmsg(" PCI devices are displayed for informational purposes only, and\n"
		   " cannot be disabled or configured here.");
    }
	    
    if (dev->irq > 0)
    {
	sprintf(buf,"IRQ number   : %d",dev->irq);
	putxy(1,19,buf);
    }
    sprintf(buf,"Flags        : 0x%x",dev->flags);
    putxy(1,20,buf);
    if (dev->maddr > 0)
    {
	sprintf(buf,"Memory address : 0x%x",dev->maddr);
	putxy(26,18,buf);
    }
    if (dev->msize > 0)
    {
	sprintf(buf,"Memory size    : 0x%x",dev->msize);
	putxy(26,19,buf);
    }

    if (dev->drq > 0)
    {
	sprintf(buf,"DRQ number     : %d",dev->drq);
	putxy(26,20,buf);
    }
    if (dev->conflict_ok)
	putxy(54,18,"Conflict allowed");
}


/**
 ** Editing functions for device parameters
 **
 ** editval(x,y,width,hex,min,max,val)	- Edit (*val) in a field (width) wide at (x,y)
 **					  onscreen.  Refuse values outsise (min) and (max).
 ** editparams(dev)			- Edit the parameters for (dev)
 **/


#define VetRet(code)							\
{									\
    if ((i >= min) && (i <= max))	/* legit? */			\
    {									\
	*val = i;							\
	sprintf(buf,hex?"0x%x":"%d",i);					\
	putxy(hex?x-2:x,y,buf);						\
	return(code);			/* all done and exit */		\
    }									\
    i = *val;				/* restore original value */	\
    delta = 1;				/* restore other stuff */	\
}


/**
 ** editval
 **
 ** Edit (*val) at (x,y) in (hex)?hex:decimal mode, allowing values between (min) and (max)
 ** in a field (width) wide. (Allow one space)
 ** If (ro) is set, we're in "readonly" mode, so disallow edits.
 **
 ** Return KEY_TAB on \t, KEY_EXIT on 'q'
 **/
static int 
editval(int x, int y, int width, int hex, int min, int max, int *val, int ro)
{
    int		i = *val;			/* work with copy of the value */
    char	buf[2+11+1],tc[11+1];		/* display buffer, text copy */
    int		xp = 0;				/* cursor offset into text copy */
    int		delta = 1;			/* force redraw first time in */
    int		c;
    int		extended = 0;			/* stage counter for extended key sequences */

    if (hex)					/* we presume there's a leading 0x onscreen */
	putxy(x-2,y,"!i0x");			/* coz there sure is now */
    	
    for (;;)
    {
	if (delta)				/* only update if necessary */
	{
	    sprintf(tc,hex?"%x":"%d",i);	/* make a text copy of the value */
	    sprintf(buf,"!i%s",tc);		/* format for printing */
	    erase(x,y,width,1);			/* clear the area */
	    putxy(x,y,buf);			/* write */
	    xp = strlen(tc);			/* cursor always at end */
	    move(x+xp,y);			/* position the cursor */
	}

	c = getchar();

	switch(extended)			/* escape handling */
	{
	case 0:
	    if (c == 0x1b)			/* esc? */
	    {
		extended = 1;			/* flag and spin */
		continue;
	    }
	    extended = 0;
	    break;				/* nope, drop through */
	
	case 1:					/* there was an escape prefix */
	    if (c == '[' || c == 'O')		/* second character in sequence */
	    {
		extended = 2;
		continue;
	    }
	    if (c == 0x1b)
		return(KEY_EXIT);		/* double esc exits */
	    extended = 0;
	    break;				/* nup, not a sequence. */

	case 2:
	    extended = 0;
	    switch(c)				/* looks like the real McCoy */
	    {
	    case 'A':
		VetRet(KEY_UP);			/* leave if OK */
		continue;
	    case 'B':
		VetRet(KEY_DOWN);		/* leave if OK */
		continue;
	    case 'C':
		VetRet(KEY_RIGHT);		/* leave if OK */
		continue;
	    case 'D':
		VetRet(KEY_LEFT);		/* leave if OK */
		continue;
		
	    default:
		continue;
	    }
	}
    
	switch(c)
	{
	case '\t':				/* trying to tab off */
	    VetRet(KEY_TAB);			/* verify and maybe return */
	    break;

	case -1:
	case 'q':
	case 'Q':
	    VetRet(KEY_EXIT);
	    break;
	    
	case '\b':
	case '\177':				/* BS or DEL */
	    if (ro)				/* readonly? */
	    {
		puthelp(" !iThis value cannot be edited (Press ESC)");
		while(getchar() != 0x1b);	/* wait for key */
		return(KEY_NULL);		/* spin */
	    }
	    if (xp)				/* still something left to delete */
	    {
		i = (hex ? i/0x10u : i/10);	/* strip last digit */
		delta = 1;			/* force update */
	    }
	    break;

	case 588:
	    VetRet(KEY_UP);
	    break;

	case '\r':
	case '\n':
	case 596:
	    VetRet(KEY_DOWN);
	    break;

	case 591:
	    VetRet(KEY_LEFT);
	    break;

	case 593:
	    VetRet(KEY_RIGHT);
	    break;
		
	default:
	    if (ro)				/* readonly? */
	    {
		puthelp(" !iThis value cannot be edited (Press ESC)");
		while(getchar() != 0x1b);	/* wait for key */
		return(KEY_NULL);		/* spin */
	    }
	    if (xp >= width)			/* no room for more characters anyway */
		break;
	    if (hex)
	    {
		if ((c >= '0') && (c <= '9'))
		{
		    i = i*0x10 + (c-'0');	/* update value */
		    delta = 1;
		    break;
		}
		if ((c >= 'a') && (c <= 'f'))
		{
		    i = i*0x10 + (c-'a'+0xa);
		    delta = 1;
		    break;
		}
		if ((c >= 'A') && (c <= 'F'))
		{
		    i = i*0x10 + (c-'A'+0xa);
		    delta = 1;
		    break;
		}
	    }else{
		if ((c >= '0') && (c <= '9'))
		{
		    i = i*10 + (c-'0');		/* update value */
		    delta = 1;			/* force redraw */
		    break;
		}
	    }
	    break;
	}
    }
}


/**
 ** editparams
 **
 ** Edit the parameters for (dev)
 **
 ** Note that it's _always_ possible to edit the flags, otherwise it might be
 ** possible for this to spin in an endless loop...
 **     0    5   10   15   20   25   30   35   40   45   50   55   60   67   70   75
 **     |....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....
 **    +--------------------------------------------------------------------------------+
 ** 17-|--------------------------------------------------------------------------------|
 ** 18-| Port address : 0x0000     Memory address : 0x00000   Conflict allowed          |
 ** 19-| IRQ number   : 00         Memory size    : 0x0000                              |
 ** 20-| Flags        : 0x0000     DRQ number     : 00                                  |
 ** 21-|--------------------------------------------------------------------------------|
 **
 ** The "intelligence" in this function that hops around based on the directional
 ** returns from editval isn't very smart, and depends on the layout above.
 **/
static void 
editparams(DEV_LIST *dev)
{
    int		ret;
    char	buf[16];		/* needs to fit the device name */

    putxy(2,17,"!bParameters!n-!bfor!n-!bdevice!n-");
    sprintf(buf,"!b%s",dev->dev);
    putxy(24,17,buf);

    erase(1,22,80,1);
    for (;;)
    {
    ep_iobase:
	if (dev->iobase > 0)
	{
	    puthelp("  IO Port address (Hexadecimal, 0x1-0xffff)");
	    ret = editval(18,18,5,1,0x1,0xffff,&(dev->iobase),(dev->attrib & FLG_FIXIOBASE));
	    switch(ret)
	    {
	    case KEY_EXIT:
		goto ep_exit;

	    case KEY_RIGHT:
		if (dev->maddr > 0)
		    goto ep_maddr;
		break;

	    case KEY_TAB:
	    case KEY_DOWN:
		goto ep_irq;
	    }
	    goto ep_iobase;
	}
    ep_irq:
	if (dev->irq > 0)
	{
	    puthelp("  Interrupt number (Decimal, 1-15)");
	    ret = editval(16,19,3,0,1,15,&(dev->irq),(dev->attrib & FLG_FIXIRQ));
	    switch(ret)
	    {
	    case KEY_EXIT:
		goto ep_exit;

	    case KEY_RIGHT:
		if (dev->msize > 0)
		    goto ep_msize;
		break;

	    case KEY_UP:
		if (dev->iobase > 0)
		    goto ep_iobase;
		break;

	    case KEY_TAB:
	    case KEY_DOWN:
		goto ep_flags;
	    }
	    goto ep_irq;
	}
    ep_flags:
	puthelp("  Device-specific flag values.");
	ret = editval(18,20,8,1,INT_MIN,INT_MAX,&(dev->flags),0);
	switch(ret)
	{
	case KEY_EXIT:
	    goto ep_exit;

	case KEY_RIGHT:
	    if (dev->drq > 0) 
		goto ep_drq;
	    break;

	case KEY_UP:
	    if (dev->irq > 0)
		goto ep_irq;
	    if (dev->iobase > 0)
		goto ep_iobase;
	    break;

	case KEY_DOWN:
	    if (dev->maddr > 0)
		goto ep_maddr;
	    if (dev->msize > 0)
		goto ep_msize;
	    if (dev->drq > 0)
		goto ep_drq;
	    break;

	case KEY_TAB:
	    goto ep_maddr;
	}
	goto ep_flags;
    ep_maddr:
	if (dev->maddr > 0)
	{
	    puthelp("  Device memory start address (Hexadecimal, 0x1-0xfffff)");
	    ret = editval(45,18,6,1,0x1,0xfffff,&(dev->maddr),(dev->attrib & FLG_FIXMADDR));
	    switch(ret)
	    {
	    case KEY_EXIT:
		goto ep_exit;

	    case KEY_LEFT:
		if (dev->iobase > 0)
		    goto ep_iobase;
		break;

	    case KEY_UP:
		goto ep_flags;

	    case KEY_DOWN:
		if (dev->msize > 0)
		    goto ep_msize;
		if (dev->drq > 0)
		    goto ep_drq;
		break;

	    case KEY_TAB:
		goto ep_msize;
	    }
	    goto ep_maddr;
	}
    ep_msize:
	if (dev->msize > 0)
	{
	    puthelp("  Device memory size (Hexadecimal, 0x1-0x10000)");
	    ret = editval(45,19,5,1,0x1,0x10000,&(dev->msize),(dev->attrib & FLG_FIXMSIZE));
	    switch(ret)
	    {
	    case KEY_EXIT:
		goto ep_exit;

	    case KEY_LEFT:
		if (dev->irq > 0)
		    goto ep_irq;
		break;

	    case KEY_UP:
		if (dev->maddr > 0)
		    goto ep_maddr;
		goto ep_flags;

	    case KEY_DOWN:
		if (dev->drq > 0)
		    goto ep_drq;
		break;

	    case KEY_TAB:
		goto ep_drq;
	    }
	    goto ep_msize;
	}
    ep_drq:
	if (dev->drq > 0)
	{
	    puthelp("  Device DMA request number (Decimal, 1-7)");
	    ret = editval(43,20,2,0,1,7,&(dev->drq),(dev->attrib & FLG_FIXDRQ));
	    switch(ret)
	    {
	    case KEY_EXIT:
		goto ep_exit;

	    case KEY_LEFT:
		goto ep_flags;

	    case KEY_UP:
		if (dev->msize > 0)
		    goto ep_msize;
		if (dev->maddr > 0)
		    goto ep_maddr;
		goto ep_flags;

	    case KEY_TAB:
		goto ep_iobase;
	    }
	    goto ep_drq;
	}
    }
    ep_exit:
    dev->changed = 1;					/* mark as changed */
}

static char *helptext[] =
{
    "                Using the UserConfig kernel settings editor",
    "                -------------------------------------------",
    "",
    "VISUAL MODE:",
    "",
    "- - Layout -",
    "",
    "The screen displays a list of available drivers, divided into two",
    "scrolling lists: Active Drivers, and Inactive Drivers.  Each list is",
    "by default collapsed and can be expanded to show all the drivers",
    "available in each category.  The parameters for the currently selected",
    "driver are shown at the bottom of the screen.",
    "",
    "- - Moving around -",
    "",
    "To move in the current list, use the UP and DOWN cursor keys to select",
    "an item (the selected item will be highlighted).  If the item is a",
    "category name, you may alternatively expand or collapse the list of",
    "drivers for that category by pressing [!bRETURN!n].  Once the category is",
    "expanded, you can select each driver in the same manner and either:",
    "",
    "  - change its parameters using [!bRETURN!n]",
    "  - move it to the Inactive list using [!bDEL!n]",
    "",
    "Use the [!bTAB!n] key to toggle between the Active and Inactive list; if",
    "you need to move a driver from the Inactive list back to the Active",
    "one, select it in the Inactive list, using [!bTAB!n] to change lists if",
    "necessary, and press [!bRETURN!n] -- the device will me moved to its",
    "category in the Active list.",
    "",
    "- - Altering the list/parameters -",
    "",
    "Any drivers for devices not installed in your system should be moved",
    "to the Inactive list, until there are no remaining parameter conflicts",
    "between the drivers, as indicated at the top.",
    "",
    "Once the list of Active drivers only contains entries for the devices",
    "present in your system, you can set their parameters (Interrupt, DMA",
    "channel, I/O addresses).  To do this, select the driver and press",
    "[!bRETURN!n]: it is now possible to edit the settings the settings at the",
    "bottom of the screen.  Use [!bTAB!n] to change fields, and when you are",
    "finished, use [!bQ!n] to return to the list.",
    "",
    "- - Saving changes -",
    "",
    "When all settings seem correct, and you wish to proceed with the",
    "kernel device probing and boot, press [!bQ!n] -- you will be asked to",
    "confirm your choice.",
    "",
    NULL
};


/**
 ** helpscreen
 **
 ** Displays help text onscreen for people that are confused, using a simple
 ** pager.
 **/
static void
helpscreen(void) 
{
    int		topline = 0;			/* where we are in the text */
    int		line, c, delta = 1;
    char	prompt[80];

    for (;;)					/* loop until user quits */
    {
	/* display help text */
	if (delta) 
	{
	    clear();					/* remove everything else */
	    for (line = topline; 
		 (line < (topline + 24)) && (helptext[line]); 
		 line++)
		putxy(0,line-topline,helptext[line]);
	    delta = 0;
	}
	
	/* prompt */
	sprintf(prompt,"!i --%s-- [U]p [D]own [Q]uit !n",helptext[line] ? "MORE" : "END");
	putxy(0,24,prompt);
	
	c = getchar();				/* so what do they say? */
	
	switch (c)
	{
	case 'u':
	case 'U':
	case 'b':
	case 'B':				/* wired into 'more' users' fingers */
	    if (topline > 0)			/* room to go up? */
	    {
		topline -= 24;
		if (topline < 0)		/* don't go too far */
		    topline = 0;
		delta = 1;
	    }
	    break;

	case 'd':
	case 'D':
	case ' ':				/* expected by most people */
	    if (helptext[line]) 		/* maybe more below? */
	    {
		topline += 24;
		delta = 1;
	    }
	    break;
	    
	case 'q':
	case 'Q':
	    redraw();				/* restore the screen */
	    return;
	}
    }
}


/** 
 ** High-level control functions
 **/


/**
 ** dolist
 **
 ** Handle user movement within (*list) in the region starting at (row) onscreen with
 ** (num) lines, starting at (*ofs) offset from row onscreen.
 ** Pass (detail) on to drawing routines.
 **
 ** If the user hits a key other than a cursor key, maybe return a code.
 **
 ** (*list) points to the device at the top line in the region, (*ofs) is the 
 ** position of the highlight within the region.  All routines below
 ** this take only a device and an absolute row : use ofsent() to find the 
 ** device, and add (*ofs) to (row) to find the absolute row.
 **/
static int 
dolist(int row, int num, int detail, int *ofs, DEV_LIST **list, char *dhelp)
{
    int		extended = 0;
    int		c;
    DEV_LIST	*lp;
    int		delta = 1;
    
    for(;;)
    {
	if (delta)
	{
	    showparams(ofsent(*ofs,*list));				/* show device parameters */
	    drawline(row+*ofs,detail,ofsent(*ofs,*list),1,dhelp);	/* highlight current line */
	    delta = 0;
	}

	c = getchar();				/* get a character */
	if ((extended == 2) || (c==588) || (c==596))	/* console gives "alternative" codes */
	{
	    extended = 0;			/* no longer */
	    switch(c)
	    {
	    case 588:				/* syscons' idea of 'up' */
	    case 'A':				/* up */
		if (*ofs)			/* just a move onscreen */
		{
		    drawline(row+*ofs,detail,ofsent(*ofs,*list),0,dhelp);/* unhighlight current line */
		    (*ofs)--;			/* move up */
		}else{
		    lp = prevent(*list);	/* can we go up? */
		    if (!lp)			/* no */
			break;
		    *list = lp;			/* yes, move up list */
		    drawlist(row,num,detail,*list);
		}
		delta = 1;
		break;

	    case 596:				/* dooby-do */
	    case 'B':				/* down */
		lp = ofsent(*ofs,*list);	/* get current item */
		if (!nextent(lp))
		    break;			/* nothing more to move to */
		drawline(row+*ofs,detail,ofsent(*ofs,*list),0,dhelp);	/* unhighlight current line */
		if (*ofs < (num-1))		/* room to move onscreen? */
		{
		    (*ofs)++;		    
		}else{
		    *list = nextent(*list);	/* scroll region down */
		    drawlist(row,num,detail,*list);
		}		
		delta = 1;
		break;
	    }
	}else{
	    switch(c)
	    {
	    case '\033':
		extended=1;
		break;
		    
	    case '[':				/* cheat : always preceeds cursor move */
	    case 'O':				/* ANSI application key mode */
		if (extended==1)
		    extended=2;
		else
		    extended=0;
		break;
		
	    case 'Q':
	    case 'q':
		return(KEY_EXIT);		/* user requests exit */

	    case '\r':				
	    case '\n':
		return(KEY_DO);			/* "do" something */

	    case '\b':
	    case '\177':
	    case 599:
		return(KEY_DEL);		/* "delete" response */

	    case 'X':
	    case 'x':
		return(KEY_UNZOOM);		/* expand everything */
		
	    case 'C':
	    case 'c':
		return(KEY_ZOOM);		/* collapse everything */

	    case '\t':
		drawline(row+*ofs,detail,ofsent(*ofs,*list),0,dhelp);	/* unhighlight current line */
		return(KEY_TAB);				/* "move" response */
		
	    case '\014':			/* ^L, redraw */
		return(KEY_REDRAW);
		
	    case '?':				/* helptext */
		return(KEY_HELP);
		
	    }
	}
    }		
}


/**
 ** visuserconfig
 ** 
 ** Do the fullscreen config thang
 **/
static int
visuserconfig(void)
{
    int	actofs = 0, inactofs = 0, mode = 0, ret = -1, i;
    DEV_LIST	*dp;
    
    initlist(&active);
    initlist(&inactive);
    alist = active;
    ilist = inactive;

    getdevs();

    conflicts = findconflict(active);		/* find conflicts in the active list only */

    redraw();

    for(;;)
    {
	switch(mode)
	{
	case 0:					/* active devices */
	    ret = dolist(1,8,1,&actofs,&alist,
			 "  [!bEnter!n] Edit device parameters  [!bDEL!n] Disable device");
	    switch(ret)
	    {
	    case KEY_TAB:
		mode = 1;			/* swap lists */
		break;

	    case KEY_REDRAW:
		redraw();
		break;

	    case KEY_ZOOM:
		alist = active;
		actofs = 0;
		expandlist(active);
		redrawactive();
		break;

	    case KEY_UNZOOM:
		alist = active;
		actofs = 0;
		collapselist(active);
		redrawactive();
		break;

	    case KEY_DEL:
		dp = ofsent(actofs,alist);	/* get current device */
		if (dp)				/* paranoia... */
		{
		    if (dp->attrib & FLG_MANDATORY)	/* can't be deleted */
			break;
		    if (dp == alist)		/* moving top item on list? */
		    {
			if (dp->next)
			{
			    alist = dp->next;	/* point list to non-moving item */
			}else{
			    alist = dp->prev;	/* end of list, go back instead */
			}
		    }else{
			if (!dp->next)		/* moving last item on list? */
			    actofs--;
		    }
		    dp->conflicts = 0;		/* no conflicts on the inactive list */
		    movedev(dp,inactive);	/* shift to inactive list */
		    conflicts = findconflict(active);	/* update conflict tags */
		    dp->changed = 1;
		    redrawactive();			/* redraw */
		    redrawinactive();
		}
		break;
		
	    case KEY_DO:			/* edit device parameters */
		dp = ofsent(actofs,alist);	/* get current device */
		if (dp)				/* paranoia... */
		{
		    if (dp->comment == DEV_DEVICE)	/* can't edit comments, zoom? */
		    {
			if (dp->iobase != -2)		/* can't edit PCI devices */
			{
			    masterhelp("  [!bTAB!n]   Change fields           [!bQ!n]   Save device parameters");
			    editparams(dp);
			    masterhelp("  [!bTAB!n]   Change fields           [!bQ!n]   Save and Exit             [!b?!n] Help");
			    putxy(0,17,lines);
			    conflicts = findconflict(active);	/* update conflict tags */
			}
		    }else{				/* DO on comment = zoom */
			switch(dp->comment)		/* Depends on current state */
			{
			case DEV_COMMENT:		/* not currently zoomed */
			    dp->comment = DEV_ZOOMED;
			    break;

			case DEV_ZOOMED:
			    dp->comment = DEV_COMMENT;
			    break;
			}
		    }
		    redrawactive();
		}
		break;
	    }
	    break;

	case 1:					/* inactive devices */
	    ret = dolist(10,7,0,&inactofs,&ilist,
			 "  [!bEnter!n] Enable device                                   ");
	    switch(ret)
	    {
	    case KEY_TAB:
		mode = 0;
		break;

	    case KEY_REDRAW:
		redraw();
		break;

	    case KEY_ZOOM:
		ilist = inactive;
		inactofs = 0;
		expandlist(inactive);
		redrawinactive();
		break;

	    case KEY_UNZOOM:
		ilist = inactive;
		inactofs = 0;
		collapselist(inactive);
		redrawinactive();
		break;

	    case KEY_DO:
		dp = ofsent(inactofs,ilist);	/* get current device */
		if (dp)				/* paranoia... */
		{
		    if (dp->comment == DEV_DEVICE)	/* can't move comments, zoom? */
		    {
			if (dp == ilist)		/* moving top of list? */
			{
			    if (dp->next)
			    {
				ilist = dp->next;	/* point list to non-moving item */
			    }else{
				ilist = dp->prev;	/* can't go down, go up instead */
			    }
			}else{
			    if (!dp->next)		/* last entry on list? */
				inactofs--;		/* shift cursor up one */
			}

			movedev(dp,active);		/* shift to active list */
			conflicts = findconflict(active);	/* update conflict tags */
			dp->changed = 1;
			alist = dp;			/* put at top and current */
			actofs = 0;
			while(dp->comment == DEV_DEVICE)
			    dp = dp->prev;		/* forcibly unzoom section */
			dp ->comment = DEV_COMMENT;
			mode = 0;			/* and swap modes to follow it */

		    }else{				/* DO on comment = zoom */
			switch(dp->comment)		/* Depends on current state */
			{
			case DEV_COMMENT:		/* not currently zoomed */
			    dp->comment = DEV_ZOOMED;
			    break;

			case DEV_ZOOMED:
			    dp->comment = DEV_COMMENT;
			    break;
			}
		    }
		    redrawactive();			/* redraw */
		    redrawinactive();
		}
		break;

	    default:				/* nothing else relevant here */
		break;
	    }
	    break;
	default:
	    mode = 0;				/* shouldn't happen... */
	}

	/* handle returns that are the same for both modes */
	switch (ret) {
	case KEY_HELP:
	    helpscreen();
	    break;
	    
	case KEY_EXIT:
	    i = yesnocancel(" Save these parameters before exiting? ([!bY!n]es/[!bN!n]o/[!bC!n]ancel) ");
	    switch(i)
	    {
	    case 2:				/* cancel */
		redraw();
		break;
		
	    case 1:				/* save and exit */
		savelist(active,1);
		savelist(inactive,0);

	    case 0:				/* exit */
		nukelist(active);		/* clean up after ourselves */
		nukelist(inactive);
		normal();
		clear();
		return(1);
	    }
	    break;
	}
    }
}
#endif /* VISUAL_USERCONFIG */

/*
 * Copyright (c) 1991 Regents of the University of California.
 * All rights reserved.
 * Copyright (c) 1994 Jordan K. Hubbard
 * All rights reserved.
 * Copyright (c) 1994 David Greenman
 * All rights reserved.
 *
 * Many additional changes by Bruce Evans
 *
 * This code is derived from software contributed by the
 * University of California Berkeley, Jordan K. Hubbard,
 * David Greenman and Bruce Evans.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by the University of
 *      California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *      $Id: userconfig.c,v 1.79 1996/12/23 12:33:08 joerg Exp $
 */

#include "scbus.h"

#include <scsi/scsiconf.h>

#define PARM_DEVSPEC	0x1
#define PARM_INT	0x2
#define PARM_ADDR	0x3

typedef struct _cmdparm {
    int type;
    union {
	struct isa_device *dparm;
	int iparm;
	void *aparm;
    } parm;
} CmdParm;

typedef int (*CmdFunc)(CmdParm *);

typedef struct _cmd {
    char *name;
    CmdFunc handler;
    CmdParm *parms;
} Cmd;


#if NSCBUS > 0
static void lsscsi(void);
static int list_scsi(CmdParm *);
#endif

static int lsdevtab(struct isa_device *);
static struct isa_device *find_device(char *, int);
static struct isa_device *search_devtable(struct isa_device *, char *, int);
static void cngets(char *, int);
static Cmd *parse_cmd(char *);
static int parse_args(char *, CmdParm *);
static unsigned long strtoul(const char *, char **, int);
static int save_dev(struct isa_device *);

static int list_devices(CmdParm *);
static int set_device_ioaddr(CmdParm *);
static int set_device_irq(CmdParm *);
static int set_device_drq(CmdParm *);
static int set_device_iosize(CmdParm *);
static int set_device_mem(CmdParm *);
static int set_device_flags(CmdParm *);
static int set_device_enable(CmdParm *);
static int set_device_disable(CmdParm *);
static int quitfunc(CmdParm *);
static int helpfunc(CmdParm *);
#if defined(USERCONFIG_BOOT)
static int introfunc(CmdParm *);
#endif

static int lineno;

/* XXX hack */
#include "eisa.h"
#if NEISA > 0
extern int num_eisa_slots;
static int set_num_eisa_slots(CmdParm *);
#endif /* NEISA > 0 */

static CmdParm addr_parms[] = {
    { PARM_DEVSPEC, {} },
    { PARM_ADDR, {} },
    { -1, {} },
};

static CmdParm int_parms[] = {
    { PARM_DEVSPEC, {} },
    { PARM_INT, {} },
    { -1, {} },
};

static CmdParm dev_parms[] = {
    { PARM_DEVSPEC, {} },
    { -1, {} },
};

#if NEISA > 0
static CmdParm int_arg[] = {
    { PARM_INT, {} },
    { -1, {} },
};
#endif /* NEISA > 0 */

static Cmd CmdList[] = {
    { "?", 	helpfunc, 		NULL },		/* ? (help)	*/
    { "di",	set_device_disable,	dev_parms },	/* disable dev	*/
    { "dr",	set_device_drq,		int_parms },	/* drq dev #	*/
#if NEISA > 0
    { "ei",	set_num_eisa_slots,	int_arg },	/* # EISA slots */
#endif /* NEISA > 0 */
    { "en",	set_device_enable,	dev_parms },	/* enable dev	*/
    { "ex", 	quitfunc, 		NULL },		/* exit (quit)	*/
    { "f",	set_device_flags,	int_parms },	/* flags dev mask */
    { "h", 	helpfunc, 		NULL },		/* help		*/
#if defined(USERCONFIG_BOOT)
    { "intro", 	introfunc, 		NULL },		/* intro screen	*/
#endif
    { "iom",	set_device_mem,		addr_parms },	/* iomem dev addr */
    { "ios",	set_device_iosize,	int_parms },	/* iosize dev size */
    { "ir",	set_device_irq,		int_parms },	/* irq dev #	*/
    { "l",	list_devices,		NULL },		/* ls, list	*/
    { "po",	set_device_ioaddr,	int_parms },	/* port dev addr */
    { "res",	(CmdFunc)cpu_reset,	NULL },		/* reset CPU	*/
    { "q", 	quitfunc, 		NULL },		/* quit		*/
#if NSCBUS > 0
    { "s",	list_scsi,		NULL },		/* scsi */
#endif
#ifdef VISUAL_USERCONFIG
    { "v",	(CmdFunc)visuserconfig,	NULL },		/* visual mode */
#endif
    { NULL,	NULL,			NULL },
};

void
userconfig(void)
{
    char input[80];
    int rval;
    Cmd *cmd;

    printf("\nFreeBSD Kernel Configuration Utility - Version 1.1\n"
	   " Type \"help\" for help" 
#ifdef VISUAL_USERCONFIG
	   " or \"visual\" to go to the visual\n"
	   " configuration interface (requires MGA/VGA display or\n"
	   " serial terminal capable of displaying ANSI graphics)"
#endif
	   ".\n");


    while (1) {
	printf("config> ");
	cngets(input, 80);
	if (input[0] == '\0')
	    continue;
	cmd = parse_cmd(input);
	if (!cmd) {
	    printf("Invalid command or syntax.  Type `?' for help.\n");
	    continue;
	}
	rval = (*cmd->handler)(cmd->parms);
	if (rval)
	    return;
    }
}

static Cmd *
parse_cmd(char *cmd)
{
    Cmd *cp;

    for (cp = CmdList; cp->name; cp++) {
	int len = strlen(cp->name);

	if (!strncmp(cp->name, cmd, len)) {
	    while (*cmd && *cmd != ' ' && *cmd != '\t')
		++cmd;
	    if (parse_args(cmd, cp->parms))
		return NULL;
	    else
		return cp;
	}
    }
    return NULL;
}

static int
parse_args(char *cmd, CmdParm *parms)
{
    while (1) {
	char *ptr;

	if (*cmd == ' ' || *cmd == '\t') {
	    ++cmd;
	    continue;
	}
	if (parms == NULL || parms->type == -1) {
		if (*cmd == '\0')
			return 0;
		printf("Extra arg(s): %s\n", cmd);
		return 1;
	}
	if (parms->type == PARM_DEVSPEC) {
	    int i = 0;
	    char devname[64];
	    int unit = 0;

	    while (*cmd && !(*cmd == ' ' || *cmd == '\t' ||
	      (*cmd >= '0' && *cmd <= '9')))
		devname[i++] = *(cmd++);
	    devname[i] = '\0';
	    if (*cmd >= '0' && *cmd <= '9') {
		unit = strtoul(cmd, &ptr, 10);
		if (cmd == ptr) {
		    printf("Invalid device number\n");
		    /* XXX should print invalid token here and elsewhere. */
		    return 1;
		}
		/* XXX else should require end of token. */
		cmd = ptr;
	    }
	    if ((parms->parm.dparm = find_device(devname, unit)) == NULL) {
	        printf("No such device: %s%d\n", devname, unit);
		return 1;
	    }
	    ++parms;
	    continue;
	}
	if (parms->type == PARM_INT) {
	    parms->parm.iparm = strtoul(cmd, &ptr, 0);
	    if (cmd == ptr) {
	        printf("Invalid numeric argument\n");
		return 1;
	    }
	    cmd = ptr;
	    ++parms;
	    continue;
	}
	if (parms->type == PARM_ADDR) {
	    parms->parm.aparm = (void *)strtoul(cmd, &ptr, 0);
	    if (cmd == ptr) {
	        printf("Invalid address argument\n");
	        return 1;
	    }
	    cmd = ptr;
	    ++parms;
	    continue;
	}
    }
    return 0;
}

static int
list_devices(CmdParm *parms)
{
    lineno = 0;
    if (lsdevtab(&isa_devtab_bio[0])) return 0;
    if (lsdevtab(&isa_devtab_tty[0])) return 0;
    if (lsdevtab(&isa_devtab_net[0])) return 0;
    if (lsdevtab(&isa_devtab_null[0])) return 0;
#if NEISA > 0
    printf("\nNumber of EISA slots to probe: %d\n", num_eisa_slots);
#endif /* NEISA > 0 */
    return 0;
}

static int
set_device_ioaddr(CmdParm *parms)
{
    parms[0].parm.dparm->id_iobase = parms[1].parm.iparm;
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_irq(CmdParm *parms)
{
    unsigned irq;

    irq = parms[1].parm.iparm;
    if (irq == 2) {
	printf("Warning: Remapping IRQ 2 to IRQ 9 - see config(8)\n");
	irq = 9;
    }
    else if (irq != -1 && irq > 15) {
	printf("An IRQ > 15 would be invalid.\n");
	return 0;
    }
    parms[0].parm.dparm->id_irq = (irq < 16 ? 1 << irq : 0);
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_drq(CmdParm *parms)
{
    unsigned drq;

    /*
     * The bounds checking is just to ensure that the value can be printed
     * in 5 characters.  32768 gets converted to -32768 and doesn't fit.
     */
    drq = parms[1].parm.iparm;
    parms[0].parm.dparm->id_drq = (drq < 32768 ? drq : -1);
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_iosize(CmdParm *parms)
{
    parms[0].parm.dparm->id_msize = parms[1].parm.iparm;
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_mem(CmdParm *parms)
{
    parms[0].parm.dparm->id_maddr = parms[1].parm.aparm;
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_flags(CmdParm *parms)
{
    parms[0].parm.dparm->id_flags = parms[1].parm.iparm;
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_enable(CmdParm *parms)
{
    parms[0].parm.dparm->id_enabled = TRUE;
    save_dev(parms[0].parm.dparm);
    return 0;
}

static int
set_device_disable(CmdParm *parms)
{
    parms[0].parm.dparm->id_enabled = FALSE;
    save_dev(parms[0].parm.dparm);
    return 0;
}

#if NEISA > 0
static int
set_num_eisa_slots(CmdParm *parms)
{
    int num_slots;

    num_slots = parms[0].parm.iparm;
    num_eisa_slots = (num_slots <= 16 ? num_slots : 10);
    return 0;
}
#endif /* NEISA > 0 */

static int
quitfunc(CmdParm *parms)
{
    return 1;
}

static int
helpfunc(CmdParm *parms)
{
    printf("Command\t\t\tDescription\n");
    printf("-------\t\t\t-----------\n");
    printf("ls\t\t\tList currently configured devices\n");
    printf("port <devname> <addr>\tSet device port (i/o address)\n");
    printf("irq <devname> <number>\tSet device irq\n");
    printf("drq <devname> <number>\tSet device drq\n");
    printf("iomem <devname> <addr>\tSet device maddr (memory address)\n");
    printf("iosize <devname> <size>\tSet device memory size\n");
    printf("flags <devname> <mask>\tSet device flags\n");
    printf("enable <devname>\tEnable device\n");
    printf("disable <devname>\tDisable device (will not be probed)\n");
#if NEISA > 0
    printf("eisa <number>\t\tSet the number of EISA slots to probe\n");
#endif /* NEISA > 0 */
    printf("quit\t\t\tExit this configuration utility\n");
    printf("reset\t\t\tReset CPU\n");
#ifdef VISUAL_USERCONFIG
    printf("visual\t\t\tGo to fullscreen mode.\n");
#endif
    printf("help\t\t\tThis message\n\n");
    printf("Commands may be abbreviated to a unique prefix\n");
    return 0;
}

#if defined(USERCONFIG_BOOT) 

#if defined (VISUAL_USERCONFIG)
static void
center(int y, char *str)
{
    putxy((80 - strlen(str)) / 2, y, str);
}
#endif

static int
introfunc(CmdParm *parms)
{
#if defined (VISUAL_USERCONFIG)
    int curr_item, first_time, extended = 0;
    static char *choices[] = {
	" Skip kernel configuration and continue with installation ",
	" Start kernel configuration in Visual mode                ",
	" Start kernel configuration in CLI mode (experts only)    ",
    };

    clear();
    center(2, "!bKernel Configuration Menu!n");

    curr_item = 0;
    first_time = 1;
    while (1) {
	char tmp[80];
	int c, i;

	if (!extended) { 
	    for (i = 0; i < 3; i++) {
		tmp[0] = '\0';
		if (curr_item == i)
		    strcpy(tmp, "!i");
		strcat(tmp, choices[i]);
		if (curr_item == i)
		    strcat(tmp, "!n");
		putxy(10, 5 + i, tmp);
	    }

	    if (first_time) {
		putxy(2, 10, "Here you have the chance to go into kernel configuration mode, making");
		putxy(2, 11, "any changes which may be necessary to properly adjust the kernel to");
		putxy(2, 12, "match your hardware configuration.");
		putxy(2, 14, "If you are installing FreeBSD for the first time, select Visual Mode");
		putxy(2, 15, "(press Down-Arrow then ENTER).");
		putxy(2, 17, "If you need to do more specialized kernel configuration and are an");
		putxy(2, 18, "experienced FreeBSD user, select CLI mode.");
		putxy(2, 20, "If you are !icertain!n that you do not need to configure your kernel");
		putxy(2, 21, "then simply press ENTER or Q now.");
		first_time = 0;
	    }
	    
	    move(0, 0);	/* move the cursor out of the way */
	}
	c = getchar();
	if ((extended == 2) || (c == 588) || (c == 596)) {	/* console gives "alternative" codes */
	    extended = 0;		/* no longer */
	    switch (c) {
	    case 588:
	    case 'A':				/* up */
		if (curr_item > 0)
		    --curr_item;
		break;

	    case 596:
	    case 'B':				/* down */
		if (curr_item < 2)
		    ++curr_item;
		break;
	    }
	}
	else {
	    switch(c) {
	    case '\033':
		extended = 1;
		break;
		    
	    case '[':				/* cheat : always preceeds cursor move */
	    case 'O':				/* ANSI application key mode */
		if (extended == 1)
		    extended = 2;
		else
		    extended = 0;
		break;
		
	    case -1:
	    case 'Q':
	    case 'q':
		clear();
		return 1;	/* user requests exit */

	    case '\r':				
	    case '\n':
		clear();
		if (!curr_item)
		    return 1;
		else if (curr_item == 1)
		    return visuserconfig();
		else {
		    putxy(0, 1, "Type \"help\" for help or \"quit\" to exit.");
		    move (0, 3);
		    return 0;
		}
		break;
	    }
	}
    }
#endif
}
#endif

static int
lsdevtab(struct isa_device *dt)
{
    for (; dt->id_id != 0; dt++) {
	int i;
	char line[80];

	if (lineno >= 23) {
		printf("<More> ");
		if (getchar() == 'q') {
			printf("quit\n");
			return (1);
		}
		printf("\n");
		lineno = 0;
	}
	if (lineno == 0) {
		printf(
"Device   port       irq   drq   iomem   iosize   unit  flags      enabled\n");
		++lineno;
	}
	/*
	 * printf() doesn't support %#, %- or even field widths for strings,
	 * so formatting is not straightforward.
	 */
	bzero(line, sizeof line);
	sprintf(line, "%s%d", dt->id_driver->name, dt->id_unit);
	/* Missing: id_id (don't need it). */
	/* Missing: id_driver (useful if we could show it by name). */
	sprintf(line + 9, "0x%x", dt->id_iobase);
	sprintf(line + 20, "%d", ffs(dt->id_irq) - 1);
	sprintf(line + 26, "%d", dt->id_drq);
	sprintf(line + 32, "0x%x", dt->id_maddr);
	sprintf(line + 40, "%d", dt->id_msize);
	/* Missing: id_msize (0 at start, useful if we can get here later). */
	/* Missing: id_intr (useful if we could show it by name). */
	/* Display only: id_unit. */
	sprintf(line + 49, "%d", dt->id_unit);
	sprintf(line + 55, "0x%x", dt->id_flags);
	/* Missing: id_scsiid, id_alive, id_ri_flags, id_reconfig (0 now...) */
	sprintf(line + 66, "%s", dt->id_enabled ? "Yes" : "No");
	for (i = 0; i < 66; ++i)
		if (line[i] == '\0')
			line[i] = ' ';
	printf("%s\n", line);
	++lineno;
    }
    return(0);
}

static struct isa_device *
find_device(char *devname, int unit)
{
    struct isa_device *ret;

    if ((ret = search_devtable(&isa_devtab_bio[0], devname, unit)) != NULL)
        return ret;
    if ((ret = search_devtable(&isa_devtab_tty[0], devname, unit)) != NULL)
        return ret;
    if ((ret = search_devtable(&isa_devtab_net[0], devname, unit)) != NULL)
        return ret;
    if ((ret = search_devtable(&isa_devtab_null[0], devname, unit)) != NULL)
        return ret;
    return NULL;
}

static struct isa_device *
search_devtable(struct isa_device *dt, char *devname, int unit)
{
    int i;

    for (i = 0; dt->id_id != 0; dt++)
        if (!strcmp(dt->id_driver->name, devname) && dt->id_unit == unit)
	    return dt;
    return NULL;
}

static void
cngets(char *input, int maxin)
{
    int c, nchars = 0;

    while (1) {
	c = getchar();
	/* Treat ^H or ^? as backspace */
	if ((c == '\010' || c == '\177')) {
	    	if (nchars) {
			printf("\010 \010");
			*--input = '\0', --nchars;
		}
		continue;
	}
	/* Treat ^U or ^X as kill line */
	else if ((c == '\025' || c == '\030')) {
		while (nchars) {
			printf("\010 \010");
			*--input = '\0', --nchars;
		}
		continue;
	}
	printf("%c", c);
	if ((++nchars == maxin) || (c == '\n') || (c == '\r') || ( c == -1)) {
	    *input = '\0';
	    break;
	}
	*input++ = (u_char)c;
    }
}


/*
 * Kludges to get the library sources of strtoul.c to work in our
 * environment.  isdigit() and isspace() could be used above too.
 */
#define	isalpha(c)	(((c) >= 'A' && (c) <= 'Z') \
			 || ((c) >= 'a' && (c) <= 'z'))		/* unsafe */
#define	isdigit(c)	((unsigned)((c) - '0') <= '9' - '0')
#define	isspace(c)	((c) == ' ' || (c) == '\t')		/* unsafe */
#define	isupper(c)	((unsigned)((c) - 'A') <= 'Z' - 'A')

static int errno;

/*
 * The following should be identical with the library sources for strtoul.c.
 */

/*
 * Convert a string to an unsigned long integer.
 *
 * Ignores `locale' stuff.  Assumes that the upper and lower case
 * alphabets and digits are each contiguous.
 */
static unsigned long
strtoul(nptr, endptr, base)
	const char *nptr;
	char **endptr;
	register int base;
{
	register const char *s = nptr;
	register unsigned long acc;
	register int c;
	register unsigned long cutoff;
	register int neg = 0, any, cutlim;

	/*
	 * See strtol for comments as to the logic used.
	 */
	do {
		c = *s++;
	} while (isspace(c));
	if (c == '-') {
		neg = 1;
		c = *s++;
	} else if (c == '+')
		c = *s++;
	if ((base == 0 || base == 16) &&
	    c == '0' && (*s == 'x' || *s == 'X')) {
		c = s[1];
		s += 2;
		base = 16;
	}
	if (base == 0)
		base = c == '0' ? 8 : 10;
	cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
	cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
	for (acc = 0, any = 0;; c = *s++) {
		if (isdigit(c))
			c -= '0';
		else if (isalpha(c))
			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
		else
			break;
		if (c >= base)
			break;
		if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
			any = -1;
		else {
			any = 1;
			acc *= base;
			acc += c;
		}
	}
	if (any < 0) {
		acc = ULONG_MAX;
		errno = ERANGE;
	} else if (neg)
		acc = -acc;
	if (endptr != 0)
		*endptr = (char *)(any ? s - 1 : nptr);
	return (acc);
}

#if NSCBUS > 0
/* scsi: Support for displaying configured SCSI devices.
 * There is no way to edit them, and this is inconsistent
 * with the ISA method.  This is here as a basis for further work.
 */
static char *
type_text(char *name)	/* XXX: This is bogus */
{
	if (strcmp(name, "sd") == 0)
		return "disk";

	if (strcmp(name, "st") == 0)
		return "tape";

	return "device";
}

static void
id_put(char *desc, int id)
{
    if (id != SCCONF_UNSPEC)
    {
    	if (desc)
	    printf("%s", desc);

    	if (id == SCCONF_ANY)
	    printf("?");
        else
	    printf("%d", id);
    }
}

static void
lsscsi(void)
{
    int i;

    printf("scsi: (can't be edited):\n");

    for (i = 0; scsi_cinit[i].driver; i++)
    {
	id_put("controller scbus", scsi_cinit[i].bus);

	if (scsi_cinit[i].unit != -1)
	{
	    printf(" at ");
	    id_put(scsi_cinit[i].driver, scsi_cinit[i].unit);
	}

	printf("\n");
    }

    for (i = 0; scsi_dinit[i].name; i++)
    {
		printf("%s ", type_text(scsi_dinit[i].name));

		id_put(scsi_dinit[i].name, scsi_dinit[i].unit);
		id_put(" at scbus", scsi_dinit[i].cunit);
		id_put(" target ", scsi_dinit[i].target);
		id_put(" lun ", scsi_dinit[i].lun);

		if (scsi_dinit[i].flags)
	    	printf("flags 0x%x\n", scsi_dinit[i].flags);

		printf("\n");
    }
}

static int
list_scsi(CmdParm *parms)
{
    lineno = 0;
    lsscsi();
    return 0;
}
#endif

static int
save_dev(idev)
struct isa_device 	*idev;
{
	struct isa_device	*id_p,*id_pn;

	for (id_p=isa_devlist;
	id_p;
	id_p=id_p->id_next) {
		if (id_p->id_id == idev->id_id) {
			id_pn = id_p->id_next;
			bcopy(idev,id_p,sizeof(struct isa_device));
			id_p->id_next = id_pn;
			return 1;
		}
	}
	id_pn = malloc(sizeof(struct isa_device),M_DEVL,M_WAITOK);
	bcopy(idev,id_pn,sizeof(struct isa_device));
	id_pn->id_next = isa_devlist;
	isa_devlist = id_pn;
	return 0;
}


OpenPOWER on IntegriCloud