DragonFlyBSD Kernel Audit
sys/dev/raid/vinum/vinumconfig.c
← back
   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
/*
 * To do:
 *
 * Don't store drive configuration on the config DB: read each drive's header
 * to decide where it is.
 *
 * Accept any old crap in the config_<foo> functions, and complain when
 * we try to bring it up.
 *
 * When trying to bring volumes up, check that the complete address range
 * is covered.
 */
/*-
 * Copyright (c) 1997, 1998
 *	Nan Yang Computer Services Limited.  All rights reserved.
 *
 *  This software is distributed under the so-called ``Berkeley
 *  License'':
 *
 * 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 Nan Yang Computer
 *      Services Limited.
 * 4. Neither the name of the Company 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 ``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 company 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: vinumconfig.c,v 1.30 2000/05/01 09:45:50 grog Exp grog $
 * $FreeBSD: src/sys/dev/vinum/vinumconfig.c,v 1.32.2.6 2002/02/03 00:43:35 grog Exp $
 */

#define STATIC static

#include <sys/udev.h>
#include "vinumhdr.h"
#include "request.h"

#define MAXTOKEN 64					    /* maximum number of tokens in a line */

/*
 * We can afford the luxury of global variables here,
 * since start_config ensures that these functions
 * are single-threaded.
 */

/* These are indices in vinum_conf of the last-mentioned of each kind of object */
static int current_drive;				    /* note the last drive we mention, for
							    * some defaults */
static int current_plex;				    /* and the same for the last plex */
static int current_volume;				    /* and the last volme */
static struct _ioctl_reply *ioctl_reply;		    /* struct to return via ioctl */

static void made_sd(struct sd *sd);
static void made_vol(struct volume *vol);
static void made_plex(struct plex *plex);

/* These values are used by most of these routines, so set them as globals */
static char *token[MAXTOKEN];				    /* pointers to individual tokens */
static int tokens;					    /* number of tokens */

#define TOCONS	0x01
#define TOTTY	0x02
#define TOLOG	0x04

struct putchar_arg {
    int flags;
    struct tty *tty;
};

#define MSG_MAX 1024					    /* maximum length of a formatted message */
/*
 * Format an error message and return to the user in the reply.
 * CARE: This routine is designed to be called only from the
 * configuration routines, so it assumes it's the owner of
 * the configuration lock, and unlocks it on exit
 */
void
throw_rude_remark(int error, char *msg,...)
{
    __va_list ap;
    char *text;
    static int finishing;				    /* don't recurse */
    int was_finishing;

    if ((vinum_conf.flags & VF_LOCKED) == 0)		    /* bug catcher */
    	panic ("throw_rude_remark: called without config lock");
    __va_start(ap, msg);
    if ((ioctl_reply != NULL)				    /* we're called from the user */
    &&(!(vinum_conf.flags & VF_READING_CONFIG))) {	    /* and not reading from disk: return msg */
	/*
	 * We can't just format to ioctl_reply, since it
	 * may contain our input parameters
	 */
	    kvasnprintf(&text, MSG_MAX, msg, ap);
	    strcpy(ioctl_reply->msg, text);
	    ioctl_reply->error = error;			    /* first byte is the error number */
	    kvasfree(&text);
    } else {
	kprintf("vinum: ");
	kvprintf(msg, ap);				    /* print to the console */
	kprintf("\n");
    }
    __va_end(ap);

    if (vinum_conf.flags & VF_READING_CONFIG) {		    /* go through to the bitter end, */
	if ((vinum_conf.flags & VF_READING_CONFIG)	    /* we're reading from disk, */
	&&((daemon_options & daemon_noupdate) == 0)) {
	    log(LOG_NOTICE, "Disabling configuration updates\n");
	    daemon_options |= daemon_noupdate;
	}
	return;
    }
    /*
     * We have a problem here: we want to unlock the
     * configuration, which implies tidying up, but
     * if we find an error while tidying up, we could
     * recurse for ever.  Use this kludge to only try
     * once
     */
    was_finishing = finishing;
    finishing = 1;
    finish_config(was_finishing);			    /* unlock anything we may be holding */
    finishing = was_finishing;
    longjmp(command_fail, error);
}

/*
 * Check a volume to see if the plex is already assigned to it.
 * Return index in volume->plex, or -1 if not assigned
 */
int
my_plex(int volno, int plexno)
{
    int i;
    struct volume *vol;

    vol = &VOL[volno];					    /* point to volno */
    for (i = 0; i < vol->plexes; i++)
	if (vol->plex[i] == plexno)
	    return i;
    return -1;						    /* not found */
}

/*
 * Check a plex to see if the subdisk is already assigned to it.
 * Return index in plex->sd, or -1 if not assigned
 */
int
my_sd(int plexno, int sdno)
{
    int i;
    struct plex *plex;

    plex = &PLEX[plexno];
    for (i = 0; i < plex->subdisks; i++)
	if (plex->sdnos[i] == sdno)
	    return i;
    return -1;						    /* not found */
}

/* Add plex to the volume if possible */
int
give_plex_to_volume(int volno, int plexno)
{
    struct volume *vol;
    int i;

    /*
     * It's not an error for the plex to already
     * belong to the volume, but we need to check a
     * number of things to make sure it's done right.
     * Some day.
     */
    if (my_plex(volno, plexno) >= 0)
	return plexno;					    /* that's it */

    vol = &VOL[volno];					    /* point to volume */
    if (vol->plexes == MAXPLEX)				    /* all plexes allocated */
	throw_rude_remark(ENOSPC,
	    "Too many plexes for volume %s",
	    vol->name);
    else if ((vol->plexes > 0)				    /* we have other plexes */
    &&((vol->flags & VF_CONFIG_SETUPSTATE) == 0))	    /* and we're not setting up state */
	invalidate_subdisks(&PLEX[plexno], sd_stale);	    /* make the subdisks invalid */
    vol->plex[vol->plexes] = plexno;			    /* this one */
    vol->plexes++;					    /* add another plex */
    PLEX[plexno].volno = volno;				    /* note the number of our volume */

    /* Find out how big our volume is */
    for (i = 0; i < vol->plexes; i++)
	vol->size = u64max(vol->size, PLEX[vol->plex[i]].length);
    return vol->plexes - 1;				    /* and return its index */
}

/*
 * Add subdisk to a plex if possible
 */
int
give_sd_to_plex(int plexno, int sdno)
{
    int i;
    struct plex *plex;
    struct sd *sd;

    /*
     * It's not an error for the sd to already
     * belong to the plex, but we need to check a
     * number of things to make sure it's done right.
     * Some day.
     */
    i = my_sd(plexno, sdno);
    if (i >= 0)						    /* does it already belong to us? */
	return i;					    /* that's it */

    plex = &PLEX[plexno];				    /* point to the plex */
    sd = &SD[sdno];					    /* and the subdisk */

    /* Do we have an offset?  Otherwise put it after the last one */
    if (sd->plexoffset < 0) {				    /* no offset specified */
	if (plex->subdisks > 0) {
	    struct sd *lastsd = &SD[plex->sdnos[plex->subdisks - 1]]; /* last subdisk */

	    if (plex->organization == plex_concat)	    /* concat, */
		sd->plexoffset = lastsd->sectors + lastsd->plexoffset; /* starts here */
	    else					    /* striped, RAID-4 or RAID-5 */
		sd->plexoffset = plex->stripesize * plex->subdisks; /* starts here */
	} else						    /* first subdisk */
	    sd->plexoffset = 0;				    /* start at the beginning */
    }
    if (plex->subdisks == MAXSD)			    /* we already have our maximum */
	throw_rude_remark(ENOSPC,			    /* crap out */
	    "Can't add %s to %s: plex full",
	    sd->name,
	    plex->name);

    plex->subdisks++;					    /* another entry */
    if (plex->subdisks >= plex->subdisks_allocated)	    /* need more space */
	EXPAND(plex->sdnos, int, plex->subdisks_allocated, INITIAL_SUBDISKS_IN_PLEX);

    /* Adjust size of plex and volume. */
    if (isparity(plex))					    /* RAID-4 or RAID-5 */
	plex->length = (plex->subdisks - 1) * sd->sectors;  /* size is one disk short */
    else
	plex->length += sd->sectors;			    /* plex gets this much bigger */
    if (plex->volno >= 0)				    /* we have a volume */
	VOL[plex->volno].size = u64max(VOL[plex->volno].size, plex->length); /* adjust its size */

    /*
     * We need to check that the subdisks don't overlap,
     * but we can't do that until a point where we *must*
     * know the size of all the subdisks.  That's not
     * here.  But we need to sort them by offset
     */
    for (i = 0; i < plex->subdisks - 1; i++) {
	if (sd->plexoffset < SD[plex->sdnos[i]].plexoffset) { /* it fits before this one */
	    /* First move any remaining subdisks by one */
	    int j;

	    for (j = plex->subdisks - 1; j > i; j--)	    /* move up one at a time */
		plex->sdnos[j] = plex->sdnos[j - 1];
	    plex->sdnos[i] = sdno;
	    sd->plexsdno = i;				    /* note where we are in the subdisk */
	    return i;
	}
    }

    /*
     * The plex doesn't have any subdisk with a
     * larger offset.  Insert it here.
     */
    plex->sdnos[i] = sdno;
    sd->plexsdno = i;					    /* note where we are in the subdisk */
    sd->plexno = plex->plexno;				    /* and who we belong to */
    return i;
}

/*
 * Add a subdisk to drive if possible.  The
 * pointer to the drive must already be stored in
 * the sd structure, but the drive doesn't know
 * about the subdisk yet.
 */
void
give_sd_to_drive(int sdno)
{
    struct sd *sd;					    /* pointer to subdisk */
    struct drive *drive;				    /* and drive */
    int fe;						    /* index in free list */
    int sfe;						    /* and index of subdisk when assigning max */

    sd = &SD[sdno];					    /* point to sd */
    drive = &DRIVE[sd->driveno];			    /* and drive */

    if (drive->state != drive_up) {
	update_sd_state(sdno);				    /* that crashes the subdisk */
	return;
    }
    if (drive->flags & VF_HOTSPARE)			    /* the drive is a hot spare, */
	throw_rude_remark(ENOSPC,
	    "Can't place %s on hot spare drive %s",
	    sd->name,
	    drive->label.name);
    if ((drive->sectors_available == 0)			    /* no space left */
    ||(sd->sectors > drive->sectors_available)) {	    /* or too big, */
	sd->driveoffset = -1;				    /* don't be confusing */
	free_sd(sd->sdno);
	throw_rude_remark(ENOSPC, "No space for %s on %s", sd->name, drive->label.name);
	return;						    /* in case we come back here */
    }
    drive->subdisks_used++;				    /* one more subdisk */

    if (sd->sectors == 0) {				    /* take the largest chunk */
	sfe = 0;					    /* to keep the compiler happy */
	for (fe = 0; fe < drive->freelist_entries; fe++) {
	    if (drive->freelist[fe].sectors >= sd->sectors) { /* more space here */
		sd->sectors = drive->freelist[fe].sectors;  /* take it */
		sd->driveoffset = drive->freelist[fe].offset;
		sfe = fe;				    /* and note the index for later */
	    }
	}
	if (sd->sectors == 0) {				    /* no luck, */
	    sd->driveoffset = -1;			    /* don't be confusing */
	    free_sd(sd->sdno);
	    throw_rude_remark(ENOSPC,			    /* give up */
		"No space for %s on %s",
		sd->name,
		drive->label.name);
	}
	if (sfe < (drive->freelist_entries - 1))	    /* not the last one, */
	    bcopy(&drive->freelist[sfe + 1],
		&drive->freelist[sfe],
		(drive->freelist_entries - sfe) * sizeof(struct drive_freelist));
	drive->freelist_entries--;			    /* one less entry */
	drive->sectors_available -= sd->sectors;	    /* and note how much less space we have */
    } else if (sd->driveoffset < 0) {			    /* no offset specified, find one */
	for (fe = 0; fe < drive->freelist_entries; fe++) {
	    if (drive->freelist[fe].sectors >= sd->sectors) { /* it'll fit here */
		sd->driveoffset = drive->freelist[fe].offset;
		if (sd->sectors == drive->freelist[fe].sectors) { /* used up the entire entry */
		    if (fe < (drive->freelist_entries - 1)) /* not the last one, */
			bcopy(&drive->freelist[fe + 1],
			    &drive->freelist[fe],
			    (drive->freelist_entries - fe) * sizeof(struct drive_freelist));
		    drive->freelist_entries--;		    /* one less entry */
		} else {
		    drive->freelist[fe].sectors -= sd->sectors;	/* this much less space */
		    drive->freelist[fe].offset += sd->sectors; /* this much further on */
		}
		drive->sectors_available -= sd->sectors;    /* and note how much less space we have */
		break;
	    }
	}
	if (sd->driveoffset < 0)
	    /*
	     * Didn't find anything.  Although the drive has
	     * enough space, it's too fragmented
	     */
	{
	    free_sd(sd->sdno);
	    throw_rude_remark(ENOSPC, "No space for %s on %s", sd->name, drive->label.name);
	}
    } else {						    /* specific offset */
	/*
	 * For a specific offset to work, the space must be
	 * entirely in a single freelist entry.  Look for it.
	 */
	u_int64_t sdend = sd->driveoffset + sd->sectors;    /* end of our subdisk */
	for (fe = 0; fe < drive->freelist_entries; fe++) {
	    u_int64_t dend = drive->freelist[fe].offset + drive->freelist[fe].sectors; /* end of entry */
	    if (dend >= sdend) {			    /* fits before here */
		if (drive->freelist[fe].offset > sd->driveoffset) { /* starts after the beginning of sd area */
		    sd->driveoffset = -1;		    /* don't be confusing */
		    set_sd_state(sd->sdno, sd_down, setstate_force);
		    throw_rude_remark(ENOSPC,
			"No space for %s on drive %s at offset %jd",
			sd->name,
			drive->label.name,
			(intmax_t)sd->driveoffset);
		    return;
		}
		/*
		 * We've found the space, and we can allocate it.
		 * We don't need to say that to the subdisk, which
		 * already knows about it.  We need to tell it to
		 * the free list, though.  We have four possibilities:
		 *
		 * 1.  The subdisk exactly eats up the entry.  That's the
		 *     same as above.
		 * 2.  The subdisk starts at the beginning and leaves space
		 *     at the end.
		 * 3.  The subdisk starts after the beginning and leaves
		 *     space at the end as well: we end up with another
		 *     fragment.
		 * 4.  The subdisk leaves space at the beginning and finishes
		 *     at the end.
		 */
		drive->sectors_available -= sd->sectors;    /* note how much less space we have */
		if (sd->driveoffset == drive->freelist[fe].offset) { /* 1 or 2 */
		    if (sd->sectors == drive->freelist[fe].sectors) { /* 1: used up the entire entry */
			if (fe < (drive->freelist_entries - 1))	/* not the last one, */
			    bcopy(&drive->freelist[fe + 1],
				&drive->freelist[fe],
				(drive->freelist_entries - fe) * sizeof(struct drive_freelist));
			drive->freelist_entries--;	    /* one less entry */
		    } else {				    /* 2: space at the end */
			drive->freelist[fe].sectors -= sd->sectors; /* this much less space */
			drive->freelist[fe].offset += sd->sectors; /* this much further on */
		    }
		} else {				    /* 3 or 4 */
		    drive->freelist[fe].sectors = sd->driveoffset - drive->freelist[fe].offset;
		    if (dend > sdend) {			    /* 3: space at the end as well */
			if (fe < (drive->freelist_entries - 1))	/* not the last one */
			    bcopy(&drive->freelist[fe],	    /* move the rest down */
				&drive->freelist[fe + 1],
				(drive->freelist_entries - fe) * sizeof(struct drive_freelist));
			drive->freelist_entries++;	    /* one less entry */
			drive->freelist[fe + 1].offset = sdend;	/* second entry starts after sd */
			drive->freelist[fe + 1].sectors = dend - sdend;	/* and is this long */
		    }
		}
		break;
	    }
	}
    }
    drive->opencount++;					    /* one more subdisk attached */
}

/* Get an empty drive entry from the drive table */
int
get_empty_drive(void)
{
    int driveno;
    struct drive *drive;

    /* first see if we have one which has been deallocated */
    for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
	if (DRIVE[driveno].state == drive_unallocated)	    /* bingo */
	    break;
    }

    if (driveno >= vinum_conf.drives_allocated)		    /* we've used all our allocation */
	EXPAND(DRIVE, struct drive, vinum_conf.drives_allocated, INITIAL_DRIVES);

    /* got a drive entry.  Make it pretty */
    drive = &DRIVE[driveno];
    bzero(drive, sizeof(struct drive));
    drive->driveno = driveno;				    /* put number in structure */
    drive->flags |= VF_NEWBORN;				    /* newly born drive */
    strcpy(drive->devicename, "unknown");		    /* and make the name ``unknown'' */
    return driveno;					    /* return the index */
}

/*
 * Find the named drive in vinum_conf.drive, return a pointer
 * return the index in vinum_conf.drive.
 * Don't mark the drive as allocated (XXX SMP)
 * If create != 0, create an entry if it doesn't exist
 */
/* XXX check if we have it open from attach */
int
find_drive(const char *name, int create)
{
    int driveno;
    struct drive *drive;

    if (name != NULL) {
	for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
	    drive = &DRIVE[driveno];			    /* point to drive */
	    if ((drive->label.name[0] != '\0')		    /* it has a name */
	    &&(strcmp(drive->label.name, name) == 0)	    /* and it's this one */
	    &&(drive->state > drive_unallocated))	    /* and it's a real one: found */
		return driveno;
	}
    }
    /* the drive isn't in the list.  Add it if he wants */
    if (create == 0)					    /* don't want to create */
	return -1;					    /* give up */

    driveno = get_empty_drive();
    drive = &DRIVE[driveno];
    if (name != NULL)
	ksnprintf(drive->label.name, sizeof(drive->label.name), "%s", name);
    drive->state = drive_referenced;			    /* in use, nothing worthwhile there */
    return driveno;					    /* return the index */
}

/*
 * Find a drive given its device name.
 * devname must be valid.
 * Otherwise the same as find_drive above
 */
int
find_drive_by_dev(const char *devname, int create)
{
    int driveno;
    struct drive *drive;

    for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
	drive = &DRIVE[driveno];
	if (strcmp(drive->devicename, devname) == 0 &&
	    drive->state > drive_unallocated
	) {
	    return driveno;
	}
    }

    if (create == 0)
	return -1;

    driveno = get_empty_drive();
    drive = &DRIVE[driveno];
    ksnprintf(drive->devicename, sizeof(drive->devicename), "%s", devname);
    /* in use, nothing worthwhile there */
    drive->state = drive_referenced;
    return driveno;
}

/* Find an empty subdisk in the subdisk table */
int
get_empty_sd(void)
{
    int sdno;
    struct sd *sd;

    /* first see if we have one which has been deallocated */
    for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
	if (SD[sdno].state == sd_unallocated)		    /* bingo */
	    break;
    }
    if (sdno >= vinum_conf.subdisks_allocated)
	/*
	 * We've run out of space.  sdno is pointing
	 * where we want it, but at the moment we
	 * don't have the space.  Get it.
	 */
	EXPAND(SD, struct sd, vinum_conf.subdisks_allocated, INITIAL_SUBDISKS);

    /* initialize some things */
    sd = &SD[sdno];					    /* point to it */
    bzero(sd, sizeof(struct sd));			    /* initialize */
    sd->flags |= VF_NEWBORN;				    /* newly born subdisk */
    sd->plexno = -1;					    /* no plex */
    sd->sectors = -1;					    /* no space */
    sd->driveno = -1;					    /* no drive */
    sd->plexoffset = -1;				    /* and no offsets */
    sd->driveoffset = -1;
    return sdno;					    /* return the index */
}

/* return a drive to the free pool */
void
free_drive(struct drive *drive)
{
    if ((drive->state > drive_referenced)		    /* real drive */
    ||(drive->flags & VF_OPEN)) {			    /* how can it be open without a state? */
	LOCKDRIVE(drive);
	if (drive->flags & VF_OPEN) {			    /* it's open, */
	    close_locked_drive(drive);			    /* close it */
	    drive->state = drive_down;			    /* and note the fact */
	}
	if (drive->freelist)
	    Free(drive->freelist);
	bzero(drive, sizeof(struct drive));		    /* this also sets drive_unallocated */
	unlockdrive(drive);
    }
}

/*
 * Find the named subdisk in vinum_conf.sd.
 *
 * If create != 0, create an entry if it doesn't exist
 *
 * Return index in vinum_conf.sd
 */
int
find_subdisk(const char *name, int create)
{
    int sdno;
    struct sd *sd;

    for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
	if (strcmp(SD[sdno].name, name) == 0)		    /* found it */
	    return sdno;
    }

    /* the subdisk isn't in the list.  Add it if he wants */
    if (create == 0)					    /* don't want to create */
	return -1;					    /* give up */

    /* Allocate one and insert the name */
    sdno = get_empty_sd();
    sd = &SD[sdno];
    ksnprintf(sd->name, sizeof(sd->name), "%s", name);
    return sdno;					    /* return the pointer */
}

/* Return space to a drive */
void
return_drive_space(int driveno, int64_t offset, int length)
{
    struct drive *drive;
    int fe;						    /* free list entry */
    u_int64_t sdend;					    /* end of our subdisk */
    u_int64_t dend;					    /* end of our freelist entry */

    drive = &DRIVE[driveno];
    if (drive->state == drive_up) {
	sdend = offset + length;			    /* end of our subdisk */

	/* Look for where to return the sd address space */
	for (fe = 0;
	    (fe < drive->freelist_entries) && (drive->freelist[fe].offset < offset);
	    fe++);
	/*
	 * Now we are pointing to the last entry, the first
	 * with a higher offset than the subdisk, or both.
	 */
	if ((fe > 1)					    /* not the first entry */
	&&((fe == drive->freelist_entries)		    /* gone past the end */
	||(drive->freelist[fe].offset > offset)))	    /* or past the block were looking for */
	    fe--;					    /* point to the block before */
	dend = drive->freelist[fe].offset + drive->freelist[fe].sectors; /* end of the entry */

	/*
	 * At this point, we are pointing to the correct
	 * place in the free list.  A number of possibilities
	 * exist:
	 *
	 * 1.  The block to be freed starts at the end of the
	 *     block to which we are pointing.  This has two
	 *     subcases:
	 *
	 * a.  The block to be freed ends at the beginning
	 *     of the following block.  Merge the three
	 *     areas into a single block.
	 *
	 * b.  The block is shorter than the space between
	 *     the current block and the next one.  Enlarge
	 *     the current block.
	 *
	 * 2.  The block to be freed starts after the end
	 *     of the block.  Again, we have two cases:
	 *
	 * a.  It ends before the start of the following block.
	 *     Create a new free block.
	 *
	 * b.  It ends at the start of the following block.
	 *     Enlarge the following block downwards.
	 *
	 * When there is only one free space block, and the
	 * space to be returned is before it, the pointer is
	 * to a non-existent zeroth block. XXX check this
	 */
	if (offset == dend) {				    /* Case 1: it starts at the end of this block */
	    if ((fe < drive->freelist_entries - 1)	    /* we're not the last block in the free list */
	    /* and the subdisk ends at the start of the next block */
	    &&(sdend == drive->freelist[fe + 1].offset)) {
		drive->freelist[fe].sectors		    /* 1a: merge all three blocks */
		    = drive->freelist[fe + 1].sectors;
		if (fe < drive->freelist_entries - 2)	    /* still more blocks after next */
		    bcopy(&drive->freelist[fe + 2],	    /* move down one */
			&drive->freelist[fe + 1],
			(drive->freelist_entries - 2 - fe)
			* sizeof(struct drive_freelist));
		drive->freelist_entries--;		    /* one less entry in the free list */
	    } else					    /* 1b: just enlarge this block */
		drive->freelist[fe].sectors += length;
	} else {					    /* Case 2 */
	    if (offset > dend)				    /* it starts after this block */
		fe++;					    /* so look at the next block */
	    if ((fe < drive->freelist_entries)		    /* we're not the last block in the free list */
	    /* and the subdisk ends at the start of this block: case 4 */
	    &&(sdend == drive->freelist[fe].offset)) {
		drive->freelist[fe].offset = offset;	    /* it starts where the sd was */
		drive->freelist[fe].sectors += length;	    /* and it's this much bigger */
	    } else {					    /* case 3: non-contiguous */
		if (fe < drive->freelist_entries)	    /* not after the last block, */
		    bcopy(&drive->freelist[fe],		    /* move the rest up one entry */
			&drive->freelist[fe + 1],
			(drive->freelist_entries - fe)
			* sizeof(struct drive_freelist));
		drive->freelist_entries++;		    /* one less entry */
		drive->freelist[fe].offset = offset;	    /* this entry represents the sd */
		drive->freelist[fe].sectors = length;
	    }
	}
	drive->sectors_available += length;		    /* the sectors are now available */
    }
}

/*
 * Free an allocated sd entry.
 * This performs memory management only.  remove()
 * is responsible for checking relationships.
 */
void
free_sd(int sdno)
{
    struct sd *sd;

    sd = &SD[sdno];
    if ((sd->driveno >= 0)				    /* we have a drive, */
    &&(sd->sectors > 0))				    /* and some space on it */
	return_drive_space(sd->driveno,			    /* return the space */
	    sd->driveoffset,
	    sd->sectors);
    if (sd->plexno >= 0)
	PLEX[sd->plexno].subdisks--;			    /* one less subdisk */
    sd->state = sd_unallocated;
    made_sd(sd);
    bzero(sd, sizeof(struct sd));			    /* and clear it out */
    sd->state = sd_unallocated;
    vinum_conf.subdisks_used--;				    /* one less sd */
}

static void
made_sd(struct sd *sd)
{
    if (sd->sd_dev == NULL && sd->state != sd_unallocated) {
	sd->sd_dev = make_dev(&vinum_ops, VINUM_SD(sd->sdno),
			      UID_ROOT, GID_OPERATOR, 0640,
			      VINUM_BASE "sd/%s", sd->name);
	udev_dict_set_cstr(sd->sd_dev, "subsystem", "raid");
	udev_dict_set_cstr(sd->sd_dev, "disk-type", "raid");
#if 0
	if (sd->plexno >= 0 && PLEX[sd->plexno].volno >= 0) {
		make_dev_alias(sd->sd_dev, "vol/%s.plex/%s",
				VOL[PLEX[sd->plexno].volno].name,
				plex->name, VOL[plex->volno].name);
	}
#endif
    }
    if (sd->sd_dev && sd->state == sd_unallocated) {
	destroy_dev(sd->sd_dev);
	sd->sd_dev = NULL;
    }
}

static void
made_vol(struct volume *vol)
{
    if (vol->vol_dev == NULL && vol->state != volume_unallocated) {
	vol->vol_dev = make_dev(&vinum_ops,
				VINUMDEV(vol->volno, 0, 0, VINUM_VOLUME_TYPE),
				UID_ROOT, GID_OPERATOR, 0640,
				VINUM_BASE "vol/%s", vol->name);
	udev_dict_set_cstr(vol->vol_dev, "subsystem", "raid");
	udev_dict_set_cstr(vol->vol_dev, "disk-type", "raid");
    }
    if (vol->vol_dev && vol->state == volume_unallocated) {
	destroy_dev(vol->vol_dev);
	vol->vol_dev = NULL;
    }
}

static void
made_plex(struct plex *plex)
{
    if (plex->plex_dev == NULL && plex->state != plex_unallocated) {
	plex->plex_dev = make_dev(&vinum_ops, VINUM_PLEX(plex->plexno),
				UID_ROOT, GID_OPERATOR, 0640,
				VINUM_BASE "plex/%s", plex->name);
	udev_dict_set_cstr(plex->plex_dev, "subsystem", "raid");
	udev_dict_set_cstr(plex->plex_dev, "disk-type", "raid");
	if (plex->volno >= 0) {
		make_dev_alias(plex->plex_dev, "vol/%s.plex/%s",
				plex->name, VOL[plex->volno].name);
	}
    }
    if (plex->plex_dev && plex->state == plex_unallocated) {
	destroy_dev(plex->plex_dev);
	plex->plex_dev = NULL;
    }
}

/* Find an empty plex in the plex table */
int
get_empty_plex(void)
{
    int plexno;
    struct plex *plex;					    /* if we allocate one */

    /* first see if we have one which has been deallocated */
    for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++) {
	if (PLEX[plexno].state == plex_unallocated)	    /* bingo */
	    break;					    /* and get out of here */
    }

    if (plexno >= vinum_conf.plexes_allocated)
	EXPAND(PLEX, struct plex, vinum_conf.plexes_allocated, INITIAL_PLEXES);

    /* Found a plex.  Give it an sd structure */
    plex = &PLEX[plexno];				    /* this one is ours */
    bzero(plex, sizeof(struct plex));			    /* polish it up */
    plex->sdnos = (int *) Malloc(sizeof(int) * INITIAL_SUBDISKS_IN_PLEX); /* allocate sd table */
    CHECKALLOC(plex->sdnos, "vinum: Can't allocate plex subdisk table");
    bzero(plex->sdnos, (sizeof(int) * INITIAL_SUBDISKS_IN_PLEX)); /* do we need this? */
    plex->flags |= VF_NEWBORN;				    /* newly born plex */
    plex->subdisks = 0;					    /* no subdisks in use */
    plex->subdisks_allocated = INITIAL_SUBDISKS_IN_PLEX;    /* and we have space for this many */
    plex->organization = plex_disorg;			    /* and it's not organized */
    plex->volno = -1;					    /* no volume yet */
    return plexno;					    /* return the index */
}

/*
 * Find the named plex in vinum_conf.plex
 *
 * If create != 0, create an entry if it doesn't exist
 * return index in vinum_conf.plex
 */
int
find_plex(const char *name, int create)
{
    int plexno;
    struct plex *plex;

    for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++) {
	if (strcmp(PLEX[plexno].name, name) == 0)	    /* found it */
	    return plexno;
    }

    /* the plex isn't in the list.  Add it if he wants */
    if (create == 0)					    /* don't want to create */
	return -1;					    /* give up */

    /* Allocate one and insert the name */
    plexno = get_empty_plex();
    plex = &PLEX[plexno];				    /* point to it */
    ksnprintf(plex->name, sizeof(plex->name), "%s", name);
    return plexno;					    /* return the pointer */
}

/*
 * Free an allocated plex entry
 * and its associated memory areas
 */
void
free_plex(int plexno)
{
    struct plex *plex;

    plex = &PLEX[plexno];
    if (plex->sdnos)
	Free(plex->sdnos);
    if (plex->lock)
	Free(plex->lock);
    plex->state = plex_unallocated;
    made_plex(plex);
    bzero(plex, sizeof(struct plex));			    /* and clear it out */
    plex->state = plex_unallocated;
}

/* Find an empty volume in the volume table */
int
get_empty_volume(void)
{
    int volno;
    struct volume *vol;
    int i;

    /* first see if we have one which has been deallocated */
    for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
	if (VOL[volno].state == volume_unallocated)	    /* bingo */
	    break;
    }

    if (volno >= vinum_conf.volumes_allocated)
	EXPAND(VOL, struct volume, vinum_conf.volumes_allocated, INITIAL_VOLUMES);

    /* Now initialize fields */
    vol = &VOL[volno];
    bzero(vol, sizeof(struct volume));
    vol->flags |= VF_NEWBORN | VF_CREATED;		    /* newly born volume */
    vol->preferred_plex = ROUND_ROBIN_READPOL;		    /* round robin */
    for (i = 0; i < MAXPLEX; i++)			    /* mark the plexes missing */
	vol->plex[i] = -1;
    return volno;					    /* return the index */
}

/*
 * Find the named volume in vinum_conf.volume.
 *
 * If create != 0, create an entry if it doesn't exist
 * return the index in vinum_conf
 */
int
find_volume(const char *name, int create)
{
    int volno;
    struct volume *vol;

    for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
	if (strcmp(VOL[volno].name, name) == 0)		    /* found it */
	    return volno;
    }

    /* the volume isn't in the list.  Add it if he wants */
    if (create == 0)					    /* don't want to create */
	return -1;					    /* give up */

    /* Allocate one and insert the name */
    volno = get_empty_volume();
    vol = &VOL[volno];
    ksnprintf(vol->name, sizeof(vol->name), "%s", name);
    vol->blocksize = DEV_BSIZE;				    /* block size of this volume */
    return volno;					    /* return the pointer */
}

/*
 * Free an allocated volume entry
 * and its associated memory areas
 */
void
free_volume(int volno)
{
    struct volume *vol;

    vol = &VOL[volno];
    vol->state = volume_unallocated;
    made_vol(vol);
    bzero(vol, sizeof(struct volume));			    /* and clear it out */
    vol->state = volume_unallocated;
}

/*
 * Handle a drive definition.  We store the information in the global variable
 * drive, so we don't need to allocate.
 *
 * If we find an error, print a message and return
 */
void
config_drive(int update)
{
    enum drive_label_info partition_status;		    /* info about the partition */
    int parameter;
    int driveno;					    /* index of drive in vinum_conf */
    struct drive *drive;				    /* and pointer to it */
    int otherdriveno;					    /* index of possible second drive */
    int sdno;

    if (tokens < 2)					    /* not enough tokens */
	throw_rude_remark(EINVAL, "Drive has no name\n");
    driveno = find_drive(token[1], 1);			    /* allocate a drive to initialize */
    drive = &DRIVE[driveno];				    /* and get a pointer */
    if (update && ((drive->flags & VF_NEWBORN) == 0))	    /* this drive exists already */
	return;						    /* don't do anything */
    drive->flags &= ~VF_NEWBORN;			    /* no longer newly born */

    if (drive->state != drive_referenced) {		    /* we already know this drive */
	/*
	 * XXX Check which definition is more up-to-date.  Give
	 * preference for the definition on its own drive.
	 */
	return;						    /* XXX */
    }
    for (parameter = 2; parameter < tokens; parameter++) {  /* look at the other tokens */
	switch (get_keyword(token[parameter], &keyword_set)) {
	case kw_device:
	    parameter++;
	    otherdriveno = find_drive_by_dev(token[parameter], 0); /* see if it exists already */
	    if (otherdriveno >= 0) {			    /* yup, */
		drive->state = drive_unallocated;	    /* deallocate the drive */
		throw_rude_remark(EEXIST,		    /* and complain */
		    "Drive %s would have same device as drive %s",
		    token[1],
		    DRIVE[otherdriveno].label.name);
	    }
	    if (drive->devicename[0] == '/') {		    /* we know this drive... */
		if (strcmp(drive->devicename, token[parameter])) /* different name */
		    close_drive(drive);			    /* close it if it's open */
		else					    /* no change */
		    break;
	    }

	    /*
	     * open the device and get the configuration
	     */
	    ksnprintf(drive->devicename, sizeof(drive->devicename),
		      "%s", token[parameter]);
	    partition_status = read_drive_label(drive, 1);

	    switch (partition_status) {
	    case DL_CANT_OPEN:				    /* not our kind */
		close_drive(drive);
		if (drive->lasterror == EFTYPE)		    /* wrong kind of partition */
		    throw_rude_remark(drive->lasterror,
			"Drive %s has invalid partition type",
			drive->label.name);
		else					    /* I/O error of some kind */
		    throw_rude_remark(drive->lasterror,
			"Can't initialize drive %s",
			drive->label.name);
		break;

	    case DL_WRONG_DRIVE:			    /* valid drive, not the name we expected */
		if (vinum_conf.flags & VF_FORCECONFIG) {    /* but we'll accept that */
		    bcopy(token[1], drive->label.name, sizeof(drive->label.name));
		    break;
		}
		close_drive(drive);
		/*
		 * There's a potential race condition here:
		 * the rude remark refers to a field in an
		 * unallocated drive, which potentially could
		 * be reused.  This works because we're the only
		 * thread accessing the config at the moment.
		 */
		drive->state = drive_unallocated;	    /* throw it away completely */
		throw_rude_remark(drive->lasterror,
		    "Incorrect drive name %s specified for drive %s",
		    token[1],
		    drive->label.name);
		break;

	    case DL_DELETED_LABEL:			    /* it was a drive, but we deleted it */
	    case DL_NOT_OURS:				    /* nothing to do with the rest */
	    case DL_OURS:
		break;
	    }
	    /*
	     * read_drive_label overwrites the device name.
	     * If we get here, we can have the drive,
	     * so put it back again
	     */
	    ksnprintf(drive->devicename, sizeof(drive->devicename),
		      "%s", token[parameter]);
	    break;

	case kw_state:
	    parameter++;				    /* skip the keyword */
	    if (vinum_conf.flags & VF_READING_CONFIG)
		drive->state = DriveState(token[parameter]); /* set the state */
	    break;

	case kw_hotspare:				    /* this drive is a hot spare */
	    drive->flags |= VF_HOTSPARE;
	    break;

	default:
	    close_drive(drive);
	    throw_rude_remark(EINVAL,
		"Drive %s, invalid keyword: %s",
		token[1],
		token[parameter]);
	}
    }

    if (drive->devicename[0] != '/') {
	drive->state = drive_unallocated;		    /* deallocate the drive */
	throw_rude_remark(EINVAL, "No device name for %s", drive->label.name);
    }
    vinum_conf.drives_used++;				    /* passed all hurdles: one more in use */
    /*
     * If we're replacing a drive, it could be that
     * we already have subdisks referencing this
     * drive.  Note where they should be and change
     * their state to obsolete.
     */
    for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
	if ((SD[sdno].state > sd_referenced)
	    && (SD[sdno].driveno == driveno)) {
	    give_sd_to_drive(sdno);
	    if (SD[sdno].state > sd_stale)
		SD[sdno].state = sd_stale;
	}
    }
}

/*
 * Handle a subdisk definition.  We store the information in the global variable
 * sd, so we don't need to allocate.
 *
 * If we find an error, print a message and return
 */
void
config_subdisk(int update)
{
    int parameter;
    int sdno;						    /* index of sd in vinum_conf */
    struct sd *sd;					    /* and pointer to it */
    u_int64_t size;
    int detached = 0;					    /* set to 1 if this is a detached subdisk */
    int sdindex = -1;					    /* index in plexes subdisk table */
    enum sdstate state = sd_unallocated;		    /* state to set, if specified */
    int autosize = 0;					    /* set if we autosize in give_sd_to_drive */
    int namedsdno;					    /* index of another with this name */

    sdno = get_empty_sd();				    /* allocate an SD to initialize */
    sd = &SD[sdno];					    /* and get a pointer */

    for (parameter = 1; parameter < tokens; parameter++) {  /* look at the other tokens */
	switch (get_keyword(token[parameter], &keyword_set)) {
	    /*
	     * If we have a 'name' parameter, it must
	     * come first, because we're too lazy to tidy
	     * up dangling refs if it comes later.
	     */
	case kw_name:
	    namedsdno = find_subdisk(token[++parameter], 0); /* find an existing sd with this name */
	    if (namedsdno >= 0) {			    /* got one */
		if (SD[namedsdno].state == sd_referenced) { /* we've been told about this one */
		    if (parameter > 2)
			throw_rude_remark(EINVAL,
			    "sd %s: name parameter must come first\n", /* no go */
			    token[parameter]);
		    else {
			int i;
			struct plex *plex;		    /* for tidying up dangling references */

			*sd = SD[namedsdno];		    /* copy from the referenced one */
			sd->sd_dev = NULL;
			made_sd(sd);
			SD[namedsdno].state = sd_unallocated; /* and deallocate the referenced one */
			made_sd(&SD[namedsdno]);
			plex = &PLEX[sd->plexno];	    /* now take a look at our plex */
			for (i = 0; i < plex->subdisks; i++) { /* look for the pointer */
			    if (plex->sdnos[i] == namedsdno) /* pointing to the old subdisk */
				plex->sdnos[i] = sdno;	    /* bend it to point here */
			}
		    }
		}
		if (update)				    /* are we updating? */
		    return;				    /* that's OK, nothing more to do */
		else
		    throw_rude_remark(EINVAL, "Duplicate subdisk %s", token[parameter]);
	    } else {
		    ksnprintf(sd->name, sizeof(sd->name),
			      "%s", token[parameter]);
	    }
	    break;

	case kw_detached:
	    detached = 1;
	    break;

	case kw_plexoffset:
	    size = sizespec(token[++parameter]);
	    if ((size == -1)				    /* unallocated */
	    &&(vinum_conf.flags & VF_READING_CONFIG))	    /* reading from disk */
		break;					    /* invalid sd; just ignore it */
	    if ((size % DEV_BSIZE) != 0)
		throw_rude_remark(EINVAL,
		    "sd %s, bad plex offset alignment: %lld",
		    sd->name,
		    (long long) size);
	    else
		sd->plexoffset = size / DEV_BSIZE;
	    break;

	case kw_driveoffset:
	    size = sizespec(token[++parameter]);
	    if ((size == -1)				    /* unallocated */
	    &&(vinum_conf.flags & VF_READING_CONFIG))	    /* reading from disk */
		break;					    /* invalid sd; just ignore it */
	    if ((size % DEV_BSIZE) != 0)
		throw_rude_remark(EINVAL,
		    "sd %s, bad drive offset alignment: %lld",
		    sd->name,
		    (long long) size);
	    else
		sd->driveoffset = size / DEV_BSIZE;
	    break;

	case kw_len:
	    if (get_keyword(token[++parameter], &keyword_set) == kw_max) /* select maximum size from drive */
		size = 0;				    /* this is how we say it :-) */
	    else
		size = sizespec(token[parameter]);
	    if ((size % DEV_BSIZE) != 0)
		throw_rude_remark(EINVAL, "sd %s, length %jd not multiple of sector size", sd->name, (intmax_t)size);
	    else
		sd->sectors = size / DEV_BSIZE;
	    /*
	     * We have a problem with autosizing: we need to
	     * give the drive to the plex before we give it
	     * to the drive, in order to be clean if we give
	     * up in the middle, but at this time the size hasn't
	     * been set.  Note that we have to fix up after
	     * giving the subdisk to the drive.
	     */
	    if (size == 0)
		autosize = 1;				    /* note that we're autosizing */
	    break;

	case kw_drive:
	    sd->driveno = find_drive(token[++parameter], 1); /* insert drive information */
	    break;

	case kw_plex:
	    sd->plexno = find_plex(token[++parameter], 1);  /* insert plex information */
	    break;

	    /*
	     * Set the state.  We can't do this directly,
	     * because give_sd_to_plex may change it
	     */
	case kw_state:
	    parameter++;				    /* skip the keyword */
	    if (vinum_conf.flags & VF_READING_CONFIG)
		state = SdState(token[parameter]);	    /* set the state */
	    break;

	case kw_partition:
	    parameter++;				    /* skip the keyword */
	    if ((strlen(token[parameter]) != 1)
		|| (token[parameter][0] < 'a')
		|| (token[parameter][0] > 'p'))
		throw_rude_remark(EINVAL,
		    "%s: invalid partition %c",
		    sd->name,
		    token[parameter][0]);
	    break;

	case kw_retryerrors:
	    sd->flags |= VF_RETRYERRORS;
	    break;

	default:
	    throw_rude_remark(EINVAL, "%s: invalid keyword: %s", sd->name, token[parameter]);
	}
    }

    /* Check we have a drive name */
    if (sd->driveno < 0) {				    /* didn't specify a drive */
	sd->driveno = current_drive;			    /* set to the current drive */
	if (sd->driveno < 0)				    /* no current drive? */
	    throw_rude_remark(EINVAL, "Subdisk %s is not associated with a drive", sd->name);
    }
    /*
     * This is tacky.  If something goes wrong
     * with the checks, we may end up losing drive
     * space.  FIXME.
     */
    if (autosize != 0)					    /* need to find a size, */
	give_sd_to_drive(sdno);				    /* do it before the plex */

    /*  Check for a plex name */
    if ((sd->plexno < 0)				    /* didn't specify a plex */
    &&(!detached))					    /* and didn't say not to, */
	sd->plexno = current_plex;			    /* set to the current plex */

    if (sd->plexno >= 0)
	sdindex = give_sd_to_plex(sd->plexno, sdno);	    /* now tell the plex that it has this sd */

    sd->sdno = sdno;					    /* point to our entry in the table */

    /* Does the subdisk have a name?  If not, give it one */
    if (sd->name[0] == '\0') {				    /* no name */
	char sdsuffix[8];				    /* form sd name suffix here */

	/* Do we have a plex name? */
	if (sdindex >= 0)				    /* we have a plex */
	    strcpy(sd->name, PLEX[sd->plexno].name);	    /* take it from there */
	else						    /* no way */
	    throw_rude_remark(EINVAL, "Unnamed sd is not associated with a plex");
	ksprintf(sdsuffix, ".s%d", sdindex);		    /* form the suffix */
	strcat(sd->name, sdsuffix);			    /* and add it to the name */
    }
    /* do we have complete info for this subdisk? */
    if (sd->sectors < 0)
	throw_rude_remark(EINVAL, "sd %s has no length spec", sd->name);

    if (state != sd_unallocated) {			    /* we had a specific state to set */
	sd->state = state;				    /* do it now */
	made_sd(sd);
    } else if (sd->state == sd_unallocated) {		    /* no, nothing set yet, */
	sd->state = sd_empty;				    /* must be empty */
	made_sd(sd);
    }
    if (autosize == 0)					    /* no autoconfig, do the drive now */
	give_sd_to_drive(sdno);
    vinum_conf.subdisks_used++;				    /* one more in use */
}

/*
 * Handle a plex definition.
 */
void
config_plex(int update)
{
    int parameter;
    int plexno;						    /* index of plex in vinum_conf */
    struct plex *plex;					    /* and pointer to it */
    int pindex = MAXPLEX;				    /* index in volume's plex list */
    int detached = 0;					    /* don't give it to a volume */
    int namedplexno;
    enum plexstate state = plex_init;			    /* state to set at end */

    current_plex = -1;					    /* forget the previous plex */
    plexno = get_empty_plex();				    /* allocate a plex */
    plex = &PLEX[plexno];				    /* and point to it */
    plex->plexno = plexno;				    /* and back to the config */

    for (parameter = 1; parameter < tokens; parameter++) {  /* look at the other tokens */
	switch (get_keyword(token[parameter], &keyword_set)) {
	    /*
	     * If we have a 'name' parameter, it must
	     * come first, because we're too lazy to tidy
	     * up dangling refs if it comes later.
	     */
	case kw_name:
	    namedplexno = find_plex(token[++parameter], 0); /* find an existing plex with this name */
	    if (namedplexno >= 0) {			    /* plex exists already, */
		if (PLEX[namedplexno].state == plex_referenced) { /* we've been told about this one */
		    if (parameter > 2)			    /* we've done other things first, */
			throw_rude_remark(EINVAL,
			    "plex %s: name parameter must come first\n", /* no go */
			    token[parameter]);
		    else {
			int i;
			struct volume *vol;		    /* for tidying up dangling references */

			*plex = PLEX[namedplexno];	    /* get the info */
			plex->plex_dev = NULL;
			made_plex(plex);
			PLEX[namedplexno].state = plex_unallocated; /* and deallocate the other one */
			made_plex(&PLEX[namedplexno]);
			vol = &VOL[plex->volno];	    /* point to the volume */
			for (i = 0; i < MAXPLEX; i++) {	    /* for each plex */
			    if (vol->plex[i] == namedplexno)
				vol->plex[i] = plexno;	    /* bend the pointer */
			}
		    }
		    break;				    /* use this one */
		}
		if (update)				    /* are we updating? */
		    return;				    /* yes: that's OK, just return */
		else
		    throw_rude_remark(EINVAL, "Duplicate plex %s", token[parameter]);
	    } else {
		    ksnprintf(plex->name, sizeof(plex->name),
			      "%s", token[parameter]);
	    }
	    break;

	case kw_detached:
	    detached = 1;
	    break;

	case kw_org:					    /* plex organization */
	    switch (get_keyword(token[++parameter], &keyword_set)) {
	    case kw_concat:
		plex->organization = plex_concat;
		break;

	    case kw_striped:
		{
		    int stripesize = sizespec(token[++parameter]);

		    plex->organization = plex_striped;
		    if (stripesize % DEV_BSIZE != 0)	    /* not a multiple of block size, */
			throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
			    plex->name,
			    stripesize);
		    else
			plex->stripesize = stripesize / DEV_BSIZE;
		    break;
		}

	    case kw_raid4:
		{
		    int stripesize = sizespec(token[++parameter]);

		    plex->organization = plex_raid4;
		    if (stripesize % DEV_BSIZE != 0)	    /* not a multiple of block size, */
			throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
			    plex->name,
			    stripesize);
		    else
			plex->stripesize = stripesize / DEV_BSIZE;
		    break;
		}

	    case kw_raid5:
		{
		    int stripesize = sizespec(token[++parameter]);

		    plex->organization = plex_raid5;
		    if (stripesize % DEV_BSIZE != 0)	    /* not a multiple of block size, */
			throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
			    plex->name,
			    stripesize);
		    else
			plex->stripesize = stripesize / DEV_BSIZE;
		    break;
		}

	    default:
		throw_rude_remark(EINVAL, "Invalid plex organization");
	    }
	    if (isstriped(plex)
		&& (plex->stripesize == 0))		    /* didn't specify a valid stripe size */
		throw_rude_remark(EINVAL, "Need a stripe size parameter");
	    break;

	case kw_volume:
	    plex->volno = find_volume(token[++parameter], 1); /* insert a pointer to the volume */
	    break;

	case kw_sd:					    /* add a subdisk */
	    {
		int sdno;

		sdno = find_subdisk(token[++parameter], 1); /* find a subdisk */
		SD[sdno].plexoffset = sizespec(token[++parameter]); /* get the offset */
		give_sd_to_plex(plexno, sdno);		    /* and insert it there */
		break;
	    }

	case kw_state:
	    parameter++;				    /* skip the keyword */
	    if (vinum_conf.flags & VF_READING_CONFIG)
		state = PlexState(token[parameter]);	    /* set the state */
	    break;

	default:
	    throw_rude_remark(EINVAL, "plex %s, invalid keyword: %s",
		plex->name,
		token[parameter]);
	}
    }

    if (plex->organization == plex_disorg)
	throw_rude_remark(EINVAL, "No plex organization specified");

    if ((plex->volno < 0)				    /* we don't have a volume */
    &&(!detached))					    /* and we wouldn't object */
	plex->volno = current_volume;

    if (plex->volno >= 0)
	pindex = give_plex_to_volume(plex->volno, plexno);  /* Now tell the volume that it has this plex */

    /* Does the plex have a name?  If not, give it one */
    if (plex->name[0] == '\0') {			    /* no name */
	char plexsuffix[8];				    /* form plex name suffix here */
	/* Do we have a volume name? */
	if (plex->volno >= 0)				    /* we have a volume */
	    strcpy(plex->name,				    /* take it from there */
		VOL[plex->volno].name);
	else						    /* no way */
	    throw_rude_remark(EINVAL, "Unnamed plex is not associated with a volume");
	ksprintf(plexsuffix, ".p%d", pindex);		    /* form the suffix */
	strcat(plex->name, plexsuffix);			    /* and add it to the name */
    }
    if (isstriped(plex)) {
	plex->lock = (struct rangelock *)
	    Malloc(PLEX_LOCKS * sizeof(struct rangelock));
	CHECKALLOC(plex->lock, "vinum: Can't allocate lock table\n");
	bzero((char *) plex->lock, PLEX_LOCKS * sizeof(struct rangelock));
    }
    /* Note the last plex we configured */
    current_plex = plexno;
    plex->state = state;				    /* set whatever state we chose */
    made_plex(plex);
    vinum_conf.plexes_used++;				    /* one more in use */
}

/*
 * Handle a volume definition.
 * If we find an error, print a message, deallocate the nascent volume, and return
 */
void
config_volume(int update)
{
    int parameter;
    int volno;
    struct volume *vol;					    /* collect volume info here */
    int i;

    if (tokens < 2)					    /* not enough tokens */
	throw_rude_remark(EINVAL, "Volume has no name");
    current_volume = -1;				    /* forget the previous volume */
    volno = find_volume(token[1], 1);			    /* allocate a volume to initialize */
    vol = &VOL[volno];					    /* and get a pointer */
    if (update && ((vol->flags & VF_CREATED) == 0))	    /* this volume exists already */
	return;						    /* don't do anything */
    vol->flags &= ~VF_CREATED;				    /* it exists now */

    for (parameter = 2; parameter < tokens; parameter++) {  /* look at all tokens */
	switch (get_keyword(token[parameter], &keyword_set)) {
	case kw_plex:
	    {
		int plexno;				    /* index of this plex */
		int myplexno;				    /* and index if it's already ours */

		plexno = find_plex(token[++parameter], 1);  /* find a plex */
		if (plexno < 0)				    /* couldn't */
		    break;				    /* we've already had an error message */
		myplexno = my_plex(volno, plexno);	    /* does it already belong to us? */
		if (myplexno > 0)			    /* yes, shouldn't get it again */
		    throw_rude_remark(EINVAL,
			"Plex %s already belongs to volume %s",
			token[parameter],
			vol->name);
		else if (vol->plexes + 1 > 8)		    /* another entry */
		    throw_rude_remark(EINVAL,
			"Too many plexes for volume %s",
			vol->name);
		vol->plex[vol->plexes] = plexno;
		vol->plexes++;
		PLEX[plexno].state = plex_referenced;	    /* we know something about it */
		PLEX[plexno].volno = volno;		    /* and this volume references it */
	    }
	    break;

	case kw_readpol:
	    switch (get_keyword(token[++parameter], &keyword_set)) { /* decide what to do */
	    case kw_round:
		vol->preferred_plex = ROUND_ROBIN_READPOL;  /* default */
		break;

	    case kw_prefer:
		{
		    int myplexno;			    /* index of this plex */

		    myplexno = find_plex(token[++parameter], 1); /* find a plex */
		    if (myplexno < 0)			    /* couldn't */
			break;				    /* we've already had an error message */
		    myplexno = my_plex(volno, myplexno);    /* does it already belong to us? */
		    if (myplexno > 0)			    /* yes */
			vol->preferred_plex = myplexno;	    /* just note the index */
		    else if (++vol->plexes > 8)		    /* another entry */
			throw_rude_remark(EINVAL, "Too many plexes");
		    else {				    /* space for the new plex */
			vol->plex[vol->plexes - 1] = myplexno; /* add it to our list */
			vol->preferred_plex = vol->plexes - 1; /* and note the index */
		    }
		}
		break;

	    default:
		throw_rude_remark(EINVAL, "Invalid read policy");
	    }

	case kw_setupstate:
	    vol->flags |= VF_CONFIG_SETUPSTATE;		    /* set the volume up later on */
	    break;

	case kw_state:
	    parameter++;				    /* skip the keyword */
	    if (vinum_conf.flags & VF_READING_CONFIG) {
		vol->state = VolState(token[parameter]);    /* set the state */
		vol->volno = volno;	/* needs correct volno to make devs */
		made_vol(vol);
	    }
	    break;

	    /*
	     * XXX experimental ideas.  These are not
	     * documented, and will not be until I
	     * decide they're worth keeping
	     */
	case kw_writethrough:				    /* set writethrough mode */
	    vol->flags |= VF_WRITETHROUGH;
	    break;

	case kw_writeback:				    /* set writeback mode */
	    vol->flags &= ~VF_WRITETHROUGH;
	    break;

	case kw_raw:
	    vol->flags |= VF_RAW;			    /* raw volume (no label) */
	    break;

	default:
	    throw_rude_remark(EINVAL, "volume %s, invalid keyword: %s",
		vol->name,
		token[parameter]);
	}
    }
    current_volume = volno;				    /* note last referred volume */
    vol->volno = volno;					    /* also note in volume */

    /*
     * Before we can actually use the volume, we need
     * a volume label.  We could start to fake one here,
     * but it will be a lot easier when we have some
     * to copy from the drives, so defer it until we
     * set up the configuration. XXX
     */
    if (vol->state == volume_unallocated) {
	vol->state = volume_down;			    /* now ready to bring up at the end */
	made_vol(vol);
    }

    /* Find out how big our volume is */
    for (i = 0; i < vol->plexes; i++)
	vol->size = u64max(vol->size, PLEX[vol->plex[i]].length);
    vinum_conf.volumes_used++;				    /* one more in use */
}

/*
 * Parse a config entry.  CARE!  This destroys the original contents of the
 * config entry, which we don't really need after this.  More specifically, it
 * places \0 characters at the end of each token.
 *
 * Return 0 if all is well, otherwise EINVAL for invalid keyword,
 * or ENOENT if 'read' command doesn't find any drives.
 */
int
parse_config(char *cptr, struct keywordset *keyset, int update)
{
    int status;

    status = 0;						    /* until proven otherwise */
    tokens = tokenize(cptr, token);			    /* chop up into tokens */

    if (tokens <= 0)					    /* screwed up or empty line */
	return tokens;					    /* give up */

    if (token[0][0] == '#')				    /* comment line */
	return 0;

    switch (get_keyword(token[0], keyset)) {		    /* decide what to do */
    case kw_read:					    /* read config from a specified drive */
	status = vinum_scandisk(&token[1], tokens - 1);	    /* read the config from disk */
	break;

    case kw_drive:
	config_drive(update);
	break;

    case kw_subdisk:
	config_subdisk(update);
	break;

    case kw_plex:
	config_plex(update);
	break;

    case kw_volume:
	config_volume(update);
	break;

	/* Anything else is invalid in this context */
    default:
	throw_rude_remark(EINVAL,			    /* should we die? */
	    "Invalid configuration information: %s",
	    token[0]);
    }
    return status;
}

/*
 * parse a line handed in from userland via ioctl.
 * This differs only by the error reporting mechanism:
 * we return the error indication in the reply to the
 * ioctl, so we need to set a global static pointer in
 * this file.  This technique works because we have
 * ensured that configuration is performed in a single-
 * threaded manner
 */
int
parse_user_config(char *cptr, struct keywordset *keyset)
{
    int status;

    ioctl_reply = (struct _ioctl_reply *) cptr;
    status = parse_config(cptr, keyset, 0);
    if (status == ENOENT)				    /* from scandisk, but it can't tell us */
	strcpy(ioctl_reply->msg, "no drives found");
    ioctl_reply = NULL;					    /* don't do this again */
    return status;
}

/* Remove an object */
void
remove(struct vinum_ioctl_msg *msg)
{
    struct vinum_ioctl_msg message = *msg;		    /* make a copy to hand on */

    ioctl_reply = (struct _ioctl_reply *) msg;		    /* reinstate the address to reply to */
    ioctl_reply->error = 0;				    /* no error, */
    ioctl_reply->msg[0] = '\0';				    /* no message */

    switch (message.type) {
    case drive_object:
	remove_drive_entry(message.index, message.force);
	updateconfig(0);
	return;

    case sd_object:
	remove_sd_entry(message.index, message.force, message.recurse);
	updateconfig(0);
	return;

    case plex_object:
	remove_plex_entry(message.index, message.force, message.recurse);
	updateconfig(0);
	return;

    case volume_object:
	remove_volume_entry(message.index, message.force, message.recurse);
	updateconfig(0);
	return;

    default:
	ioctl_reply->error = EINVAL;
	strcpy(ioctl_reply->msg, "Invalid object type");
    }
}

/* Remove a drive.  */
void
remove_drive_entry(int driveno, int force)
{
    struct drive *drive = &DRIVE[driveno];
    int sdno;

    if ((driveno > vinum_conf.drives_allocated)		    /* not a valid drive */
    ||(drive->state == drive_unallocated)) {		    /* or nothing there */
	ioctl_reply->error = EINVAL;
	strcpy(ioctl_reply->msg, "No such drive");
    } else if (drive->opencount > 0) {			    /* we have subdisks */
	if (force) {					    /* do it at any cost */
	    for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
		if ((SD[sdno].state != sd_unallocated)	    /* subdisk is allocated */
		&&(SD[sdno].driveno == driveno))	    /* and it belongs to this drive */
		    remove_sd_entry(sdno, force, 0);
	    }
	    remove_drive(driveno);			    /* now remove it */
	    vinum_conf.drives_used--;			    /* one less drive */
	} else
	    ioctl_reply->error = EBUSY;			    /* can't do that */
    } else {
	remove_drive(driveno);				    /* just remove it */
	vinum_conf.drives_used--;			    /* one less drive */
    }
}

/* remove a subdisk */
void
remove_sd_entry(int sdno, int force, int recurse)
{
    struct sd *sd = &SD[sdno];

    if ((sdno > vinum_conf.subdisks_allocated)		    /* not a valid sd */
    ||(sd->state == sd_unallocated)) {			    /* or nothing there */
	ioctl_reply->error = EINVAL;
	strcpy(ioctl_reply->msg, "No such subdisk");
    } else if (sd->flags & VF_OPEN) {			    /* we're open */
	ioctl_reply->error = EBUSY;			    /* no getting around that */
	return;
    } else if (sd->plexno >= 0) {			    /* we have a plex */
	if (force) {					    /* do it at any cost */
	    struct plex *plex = &PLEX[sd->plexno];	    /* point to our plex */
	    int mysdno;

	    for (mysdno = 0;				    /* look for ourselves */
		mysdno < plex->subdisks && &SD[plex->sdnos[mysdno]] != sd;
		mysdno++);
	    if (mysdno == plex->subdisks)		    /* didn't find it */
		log(LOG_ERR,
		    "Error removing subdisk %s: not found in plex %s\n",
		    SD[mysdno].name,
		    plex->name);
	    else {					    /* remove the subdisk from plex */
		if (mysdno < (plex->subdisks - 1))	    /* not the last subdisk */
		    bcopy(&plex->sdnos[mysdno + 1],
			&plex->sdnos[mysdno],
			(plex->subdisks - 1 - mysdno) * sizeof(int));
		plex->subdisks--;
		sd->plexno = -1;			    /* disown the subdisk */
	    }

	    /*
	     * Removing a subdisk from a striped or
	     * RAID-4 or RAID-5 plex really tears the
	     * hell out of the structure, and it needs
	     * to be reinitialized.
	     */
	    if (plex->organization != plex_concat)	    /* not concatenated, */
		set_plex_state(plex->plexno, plex_faulty, setstate_force); /* need to reinitialize */
	    log(LOG_INFO, "vinum: removing %s\n", sd->name);
	    free_sd(sdno);
	} else
	    ioctl_reply->error = EBUSY;			    /* can't do that */
    } else {
	log(LOG_INFO, "vinum: removing %s\n", sd->name);
	free_sd(sdno);
    }
}

/* remove a plex */
void
remove_plex_entry(int plexno, int force, int recurse)
{
    struct plex *plex = &PLEX[plexno];
    int sdno;

    if ((plexno > vinum_conf.plexes_allocated)		    /* not a valid plex */
    ||(plex->state == plex_unallocated)) {		    /* or nothing there */
	ioctl_reply->error = EINVAL;
	strcpy(ioctl_reply->msg, "No such plex");
    } else if (plex->flags & VF_OPEN) {			    /* we're open */
	ioctl_reply->error = EBUSY;			    /* no getting around that */
	return;
    }
    if (plex->subdisks) {
	if (force) {					    /* do it anyway */
	    if (recurse) {				    /* remove all below */
		int sds = plex->subdisks;
		for (sdno = 0; sdno < sds; sdno++)
		    free_sd(plex->sdnos[sdno]);		    /* free all subdisks */
	    } else {					    /* just tear them out */
		int sds = plex->subdisks;
		for (sdno = 0; sdno < sds; sdno++)
		    SD[plex->sdnos[sdno]].plexno = -1;	    /* no plex any more */
	    }
	} else {					    /* can't do it without force */
	    ioctl_reply->error = EBUSY;			    /* can't do that */
	    return;
	}
    }
    if (plex->volno >= 0) {				    /* we are part of a volume */
	if (force) {					    /* do it at any cost */
	    struct volume *vol = &VOL[plex->volno];
	    int myplexno;

	    for (myplexno = 0; myplexno < vol->plexes; myplexno++)
		if (vol->plex[myplexno] == plexno)	    /* found it */
		    break;
	    if (myplexno == vol->plexes)		    /* didn't find it.  Huh? */
		log(LOG_ERR,
		    "Error removing plex %s: not found in volume %s\n",
		    plex->name,
		    vol->name);
	    if (myplexno < (vol->plexes - 1))		    /* not the last plex in the list */
		bcopy(&vol->plex[myplexno + 1],
		    &vol->plex[myplexno],
		    vol->plexes - 1 - myplexno);
	    vol->plexes--;
	} else {
	    ioctl_reply->error = EBUSY;			    /* can't do that */
	    return;
	}
    }
    log(LOG_INFO, "vinum: removing %s\n", plex->name);
    free_plex(plexno);
    vinum_conf.plexes_used--;				    /* one less plex */
}

/* remove a volume */
void
remove_volume_entry(int volno, int force, int recurse)
{
    struct volume *vol = &VOL[volno];
    int plexno;

    if ((volno > vinum_conf.volumes_allocated)		    /* not a valid volume */
    ||(vol->state == volume_unallocated)) {		    /* or nothing there */
	ioctl_reply->error = EINVAL;
	strcpy(ioctl_reply->msg, "No such volume");
    } else if (vol->flags & VF_OPEN)			    /* we're open */
	ioctl_reply->error = EBUSY;			    /* no getting around that */
    else if (vol->plexes) {
	if (recurse && force) {				    /* remove all below */
	    int plexes = vol->plexes;

/*       for (plexno = plexes - 1; plexno >= 0; plexno--) */
	    for (plexno = 0; plexno < plexes; plexno++)
		remove_plex_entry(vol->plex[plexno], force, recurse);
	    log(LOG_INFO, "vinum: removing %s\n", vol->name);
	    free_volume(volno);
	    vinum_conf.volumes_used--;			    /* one less volume */
	} else
	    ioctl_reply->error = EBUSY;			    /* can't do that */
    } else {
	log(LOG_INFO, "vinum: removing %s\n", vol->name);
	free_volume(volno);
	vinum_conf.volumes_used--;			    /* one less volume */
    }
}

/* Currently called only from ioctl */
void
update_sd_config(int sdno, int diskconfig)
{
    if (!diskconfig)
	set_sd_state(sdno, sd_up, setstate_configuring);
    SD[sdno].flags &= ~VF_NEWBORN;
}

void
update_plex_config(int plexno, int diskconfig)
{
    u_int64_t size;
    int sdno;
    struct plex *plex = &PLEX[plexno];
    int remainder;					    /* size of fractional stripe at end */
    int added_plex;					    /* set if we add a plex to a volume */
    int required_sds;					    /* number of subdisks we need */
    struct sd *sd;
    struct volume *vol;
    int data_sds = 0;					    /* number of sds carrying data */

    if (plex->state < plex_init)			    /* not a real plex, */
	return;
    added_plex = 0;
    if (plex->volno >= 0) {				    /* we have a volume */
	vol = &VOL[plex->volno];

	/*
	 * If we're newly born,
	 * and the volume isn't,
	 * and it has other plexes,
	 * and we didn't read this mess from disk,
	 * we were added later.
	 */
	if ((plex->flags & VF_NEWBORN)
	    && ((vol->flags & VF_NEWBORN) == 0)
	    && (vol->plexes > 0)
	    && (diskconfig == 0)) {
	    added_plex = 1;
	}
    }
    /*
     * Check that our subdisks make sense.  For
     * striped, RAID-4 and RAID-5 plexes, we need at
     * least two subdisks, and they must all be the
     * same size.
     */
    if (plex->organization == plex_striped) {
	data_sds = plex->subdisks;
	required_sds = 2;
    } else if (isparity(plex)) {			    /* RAID 4 or 5 */
	data_sds = plex->subdisks - 1;
	required_sds = 3;
    } else
	required_sds = 0;
    if (required_sds > 0) {				    /* striped, RAID-4 or RAID-5 */
	if (plex->subdisks < required_sds) {
	    log(LOG_ERR,
		"vinum: plex %s does not have at least %d subdisks\n",
		plex->name,
		required_sds);
	}
	/*
	 * Now see if the plex size is a multiple of
	 * the stripe size.  If not, trim off the end
	 * of each subdisk and return it to the drive.
	 */
	if (plex->length > 0) {
	    if (data_sds > 0) {
		if (plex->stripesize > 0) {
		    remainder = (int) (plex->length	    /* are we exact? */
			% ((u_int64_t) plex->stripesize * data_sds));
		    if (remainder) {			    /* no */
			log(LOG_INFO, "vinum: removing %d blocks of partial stripe at the end of %s\n",
			    remainder,
			    plex->name);
			plex->length -= remainder;	    /* shorten the plex */
			remainder /= data_sds;		    /* spread the remainder amongst the sds */
			for (sdno = 0; sdno < plex->subdisks; sdno++) {
			    sd = &SD[plex->sdnos[sdno]];    /* point to the subdisk */
			    return_drive_space(sd->driveno, /* return the space */
				sd->driveoffset + sd->sectors - remainder,
				remainder);
			    sd->sectors -= remainder;	    /* and shorten it */
			}
		    }
		} else					    /* no data sds, */
		    plex->length = 0;			    /* reset length */
	    }
	}
    }
    size = 0;
    for (sdno = 0; sdno < plex->subdisks; sdno++) {
	sd = &SD[plex->sdnos[sdno]];
	if (isstriped(plex)
	    && (sdno > 0)
	    && (sd->sectors != SD[plex->sdnos[sdno - 1]].sectors)) {
	    log(LOG_ERR, "vinum: %s must have equal sized subdisks\n", plex->name);
	}
	size += sd->sectors;
	if (added_plex) {				    /* we were added later */
	    sd->state = sd_stale;			    /* stale until proven otherwise */
	    made_sd(sd);
	}
    }

    if (plex->subdisks) {				    /* plex has subdisks, calculate size */
	/*
	 * XXX We shouldn't need to calculate the size any
	 * more.  Check this some time
	 */
	if (isparity(plex))
	    size = size / plex->subdisks * (plex->subdisks - 1); /* less space for RAID-4 and RAID-5 */
	if (plex->length != size)
	    log(LOG_INFO,
		"Correcting length of %s: was %lld, is %lld\n",
		plex->name,
		(long long) plex->length,
		(long long) size);
	plex->length = size;
    } else {						    /* no subdisks, */
	plex->length = 0;				    /* no size */
    }
    update_plex_state(plexno);				    /* set the state */
    plex->flags &= ~VF_NEWBORN;
}

void
update_volume_config(int volno, int diskconfig)
{
    struct volume *vol = &VOL[volno];
    struct plex *plex;
    int plexno;

    if (vol->state != volume_unallocated)
	/*
	 * Recalculate the size of the volume,
	 * which might change if the original
	 * plexes were not a multiple of the
	 * stripe size.
	 */
    {
	vol->size = 0;
	for (plexno = 0; plexno < vol->plexes; plexno++) {
	    plex = &PLEX[vol->plex[plexno]];
	    vol->size = u64max(plex->length, vol->size);
	    plex->volplexno = plexno;	    /* note it in the plex */
	}
    }
    vol->flags &= ~VF_NEWBORN;		    /* no longer newly born */
}

/*
 * Update the global configuration.
 * diskconfig is != 0 if we're reading in a config
 * from disk.  In this case, we don't try to
 * bring the devices up, though we will bring
 * them down if there's some error which got
 * missed when writing to disk.
 */
void
updateconfig(int diskconfig)
{
    int plexno;
    int volno;

    for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++)
	update_plex_config(plexno, diskconfig);

    for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
	if (VOL[volno].state > volume_uninit) {
	    VOL[volno].flags &= ~VF_CONFIG_SETUPSTATE;	    /* no more setupstate */
	    update_volume_state(volno);
	    update_volume_config(volno, diskconfig);
	}
    }
    save_config();
}

/*
 * Start manual changes to the configuration and lock out
 * others who may wish to do so.
 * XXX why do we need this and lock_config too?
 */
int
start_config(int force)
{
    int error;

    current_drive = -1;					    /* note the last drive we mention, for
							    * some defaults */
    current_plex = -1;					    /* and the same for the last plex */
    current_volume = -1;				    /* and the last volume */
    while ((vinum_conf.flags & VF_CONFIGURING) != 0) {
	vinum_conf.flags |= VF_WILL_CONFIGURE;
	if ((error = tsleep(&vinum_conf, PCATCH, "vincfg", 0)) != 0)
	    return error;
    }
    /*
     * We need two flags here: VF_CONFIGURING
     * tells other processes to hold off (this
     * function), and VF_CONFIG_INCOMPLETE
     * tells the state change routines not to
     * propagate incrememntal state changes
     */
    vinum_conf.flags |= VF_CONFIGURING | VF_CONFIG_INCOMPLETE;
    if (force)
	vinum_conf.flags |= VF_FORCECONFIG;		    /* overwrite differently named drives */
    current_drive = -1;					    /* reset the defaults */
    current_plex = -1;					    /* and the same for the last plex */
    current_volume = -1;				    /* and the last volme */
    return 0;
}

/*
 * Update the config if update is 1, and unlock
 * it.  We won't update the configuration if we
 * are called in a recursive loop via throw_rude_remark.
 */
void
finish_config(int update)
{
    /* we've finished our config */
    vinum_conf.flags &= ~(VF_CONFIG_INCOMPLETE | VF_READING_CONFIG | VF_FORCECONFIG);
    if (update)
	updateconfig(0);				    /* so update things */
    else
	updateconfig(1);				    /* do some updates only */
    vinum_conf.flags &= ~VF_CONFIGURING;		    /* and now other people can take a turn */
    if ((vinum_conf.flags & VF_WILL_CONFIGURE) != 0) {
	vinum_conf.flags &= ~VF_WILL_CONFIGURE;
	wakeup_one(&vinum_conf);
    }
}