DragonFlyBSD Kernel Audit
sys/vfs/devfs/devfs_core.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
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
/*
 * Copyright (c) 2009-2019 The DragonFly Project.  All rights reserved.
 *
 * This code is derived from software contributed to The DragonFly Project
 * by Alex Hornung <ahornung@gmail.com>
 *
 * 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. Neither the name of The DragonFly Project 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 COPYRIGHT HOLDERS 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
 * COPYRIGHT HOLDERS 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.
 */
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/bus.h>
#include <sys/malloc.h>
#include <sys/mount.h>
#include <sys/vnode.h>
#include <sys/lock.h>
#include <sys/file.h>
#include <sys/msgport.h>
#include <sys/sysctl.h>
#include <sys/ucred.h>
#include <sys/devfs.h>
#include <sys/devfs_rules.h>
#include <sys/udev.h>

#include <sys/msgport2.h>
#include <sys/spinlock2.h>
#include <sys/sysref2.h>

MALLOC_DEFINE(M_DEVFS, "devfs", "Device File System (devfs) allocations");
DEVFS_DEFINE_CLONE_BITMAP(ops_id);
/*
 * SYSREF Integration - reference counting, allocation,
 * sysid and syslink integration.
 */
static void devfs_cdev_terminate(cdev_t dev);
static void devfs_cdev_lock(cdev_t dev);
static void devfs_cdev_unlock(cdev_t dev);
static struct sysref_class     cdev_sysref_class = {
	.name =         "cdev",
	.mtype =        M_DEVFS,
	.proto =        SYSREF_PROTO_DEV,
	.offset =       offsetof(struct cdev, si_sysref),
	.objsize =      sizeof(struct cdev),
	.nom_cache =	32,
	.flags =        0,
	.ops =  {
		.terminate = (sysref_terminate_func_t)devfs_cdev_terminate,
		.lock = (sysref_lock_func_t)devfs_cdev_lock,
		.unlock = (sysref_unlock_func_t)devfs_cdev_unlock
	}
};

static struct objcache	*devfs_node_cache;
static struct objcache 	*devfs_msg_cache;
static struct objcache	*devfs_dev_cache;

static struct objcache_malloc_args devfs_node_malloc_args = {
	sizeof(struct devfs_node), M_DEVFS };
struct objcache_malloc_args devfs_msg_malloc_args = {
	sizeof(struct devfs_msg), M_DEVFS };
struct objcache_malloc_args devfs_dev_malloc_args = {
	sizeof(struct cdev), M_DEVFS };

static struct devfs_dev_head devfs_dev_list =
		TAILQ_HEAD_INITIALIZER(devfs_dev_list);
static struct devfs_mnt_head devfs_mnt_list =
		TAILQ_HEAD_INITIALIZER(devfs_mnt_list);
static struct devfs_chandler_head devfs_chandler_list =
		TAILQ_HEAD_INITIALIZER(devfs_chandler_list);
static struct devfs_alias_head devfs_alias_list =
		TAILQ_HEAD_INITIALIZER(devfs_alias_list);
static struct devfs_dev_ops_head devfs_dev_ops_list =
		TAILQ_HEAD_INITIALIZER(devfs_dev_ops_list);

struct lock 		devfs_lock;
struct lwkt_token	devfs_token;
static struct lwkt_port devfs_dispose_port;
static struct lwkt_port devfs_msg_port;
static struct thread 	*td_core;

static struct spinlock  ino_lock;
static ino_t 	d_ino;
static int	devfs_debug_enable;
static int	devfs_run;

static ino_t devfs_fetch_ino(void);
static int devfs_reference_ops(struct dev_ops *ops);
static void devfs_release_ops(struct dev_ops *ops);
static int devfs_create_all_dev_worker(struct devfs_node *);
static int devfs_create_dev_worker(cdev_t, uid_t, gid_t, int);
static int devfs_destroy_dev_worker(cdev_t);
static int devfs_destroy_related_worker(cdev_t);
static int devfs_destroy_dev_by_ops_worker(struct dev_ops *, int);
static int devfs_propagate_dev(cdev_t, int);
static int devfs_unlink_dev(cdev_t dev);
static void devfs_msg_exec(devfs_msg_t msg);

static int devfs_chandler_add_worker(const char *, d_clone_t *);
static int devfs_chandler_del_worker(const char *);

static void devfs_msg_autofree_reply(lwkt_port_t, lwkt_msg_t);
static void devfs_msg_core(void *);

static int devfs_find_device_by_name_worker(devfs_msg_t);
static int devfs_find_device_by_devid_worker(devfs_msg_t);

static int devfs_apply_reset_rules_caller(char *, int);

static int devfs_scan_callback_worker(devfs_scan_t *, void *);

static struct devfs_node *devfs_resolve_or_create_dir(struct devfs_node *,
		char *, size_t, int);

static int devfs_make_alias_worker(struct devfs_alias *);
static int devfs_destroy_alias_worker(struct devfs_alias *);
static int devfs_alias_remove(cdev_t);
static int devfs_alias_reap(void);
static int devfs_alias_propagate(struct devfs_alias *, int);
static int devfs_alias_apply(struct devfs_node *, struct devfs_alias *);
static int devfs_alias_check_create(struct devfs_node *);

static int devfs_clr_related_flag_worker(cdev_t, uint32_t);
static int devfs_destroy_related_without_flag_worker(cdev_t, uint32_t);

static void *devfs_reaperp_callback(struct devfs_node *, void *);
static void devfs_iterate_orphans_unmount(struct mount *mp);
static void *devfs_gc_dirs_callback(struct devfs_node *, void *);
static void *devfs_gc_links_callback(struct devfs_node *, struct devfs_node *);
static void *
devfs_inode_to_vnode_worker_callback(struct devfs_node *, ino_t *);

/*
 * devfs_debug() is a SYSCTL and TUNABLE controlled debug output function
 * using kvprintf
 */
int
devfs_debug(int level, char *fmt, ...)
{
	__va_list ap;

	__va_start(ap, fmt);
	if (level <= devfs_debug_enable)
		kvprintf(fmt, ap);
	__va_end(ap);

	return 0;
}

/*
 * devfs_allocp() Allocates a new devfs node with the specified
 * parameters. The node is also automatically linked into the topology
 * if a parent is specified. It also calls the rule and alias stuff to
 * be applied on the new node
 */
struct devfs_node *
devfs_allocp(devfs_nodetype devfsnodetype, char *name,
	     struct devfs_node *parent, struct mount *mp, cdev_t dev)
{
	struct devfs_node *node = NULL;
	size_t namlen = strlen(name);

	node = objcache_get(devfs_node_cache, M_WAITOK);
	bzero(node, sizeof(*node));

	atomic_add_long(&DEVFS_MNTDATA(mp)->leak_count, 1);

	node->d_dev = NULL;
	node->nchildren = 1;
	node->mp = mp;
	node->d_dir.d_ino = devfs_fetch_ino();

	/*
	 * Cookie jar for children. Leave 0 and 1 for '.' and '..' entries
	 * respectively.
	 */
	node->cookie_jar = 2;

	/*
	 * Access Control members
	 */
	node->mode = DEVFS_DEFAULT_MODE;
	node->uid = DEVFS_DEFAULT_UID;
	node->gid = DEVFS_DEFAULT_GID;

	switch (devfsnodetype) {
	case Nroot:
		/*
		 * Ensure that we don't recycle the root vnode by marking it as
		 * linked into the topology.
		 */
		node->flags |= DEVFS_NODE_LINKED;
	case Ndir:
		TAILQ_INIT(DEVFS_DENODE_HEAD(node));
		node->d_dir.d_type = DT_DIR;
		node->nchildren = 2;
		break;

	case Nlink:
		node->d_dir.d_type = DT_LNK;
		break;

	case Nreg:
		node->d_dir.d_type = DT_REG;
		break;

	case Ndev:
		if (dev != NULL) {
			node->d_dir.d_type = DT_CHR;
			node->d_dev = dev;

			node->mode = dev->si_perms;
			node->uid = dev->si_uid;
			node->gid = dev->si_gid;

			devfs_alias_check_create(node);
		}
		break;

	default:
		panic("devfs_allocp: unknown node type");
	}

	node->v_node = NULL;
	node->node_type = devfsnodetype;

	/* Initialize the dirent structure of each devfs vnode */
	node->d_dir.d_namlen = namlen;
	node->d_dir.d_name = kmalloc(namlen+1, M_DEVFS, M_WAITOK);
	memcpy(node->d_dir.d_name, name, namlen);
	node->d_dir.d_name[namlen] = '\0';

	/* Initialize the parent node element */
	node->parent = parent;

	/* Initialize *time members */
	vfs_timestamp(&node->atime);
	node->mtime = node->ctime = node->atime;

	/*
	 * Associate with parent as last step, clean out namecache
	 * reference.
	 */
	if (parent) {
		if (parent->node_type == Nroot ||
		    parent->node_type == Ndir) {
			parent->nchildren++;
			node->cookie = parent->cookie_jar++;
			node->flags |= DEVFS_NODE_LINKED;
			TAILQ_INSERT_TAIL(DEVFS_DENODE_HEAD(parent), node, link);

			/* This forces negative namecache lookups to clear */
			++mp->mnt_namecache_gen;
		} else {
			kprintf("devfs: Cannot link node %p (%s) "
				"into %p (%s)\n",
				node, node->d_dir.d_name,
				parent, parent->d_dir.d_name);
			print_backtrace(-1);
		}
	}

	/*
	 * Apply rules (requires root node, skip if we are creating the root
	 * node)
	 */
	if (DEVFS_MNTDATA(mp)->root_node)
		devfs_rule_check_apply(node, NULL);

	atomic_add_long(&DEVFS_MNTDATA(mp)->file_count, 1);

	return node;
}

/*
 * devfs_allocv() allocates a new vnode based on a devfs node.
 */
int
devfs_allocv(struct vnode **vpp, struct devfs_node *node)
{
	struct vnode *vp;
	int error = 0;

	KKASSERT(node);

	/*
	 * devfs master lock must not be held across a vget() call, we have
	 * to hold our ad-hoc vp to avoid a free race from destroying the
	 * contents of the structure.  The vget() will interlock recycles
	 * for us.
	 */
try_again:
	while ((vp = node->v_node) != NULL) {
		vhold(vp);
		lockmgr(&devfs_lock, LK_RELEASE);
		error = vget(vp, LK_EXCLUSIVE);
		vdrop(vp);
		lockmgr(&devfs_lock, LK_EXCLUSIVE);
		if (error == 0) {
			*vpp = vp;
			goto out;
		}
		if (error != ENOENT) {
			*vpp = NULL;
			goto out;
		}
	}

	/*
	 * devfs master lock must not be held across a getnewvnode() call.
	 */
	lockmgr(&devfs_lock, LK_RELEASE);
	if ((error = getnewvnode(VT_DEVFS, node->mp, vpp, 0, 0)) != 0) {
		lockmgr(&devfs_lock, LK_EXCLUSIVE);
		goto out;
	}
	lockmgr(&devfs_lock, LK_EXCLUSIVE);

	vp = *vpp;

	if (node->v_node != NULL) {
		vp->v_type = VBAD;
		vx_put(vp);
		goto try_again;
	}

	vp->v_data = node;
	node->v_node = vp;

	switch (node->node_type) {
	case Nroot:
		vsetflags(vp, VROOT);
		/* fall through */
	case Ndir:
		vp->v_type = VDIR;
		break;

	case Nlink:
		vp->v_type = VLNK;
		break;

	case Nreg:
		vp->v_type = VREG;
		break;

	case Ndev:
		vp->v_type = VCHR;
		KKASSERT(node->d_dev);

		vp->v_uminor = node->d_dev->si_uminor;
		vp->v_umajor = node->d_dev->si_umajor;

		v_associate_rdev(vp, node->d_dev);
		vp->v_ops = &node->mp->mnt_vn_spec_ops;
		if (node->d_dev->si_ops->head.flags & D_KVABIO)
			vsetflags(vp, VKVABIO);
		break;

	default:
		panic("devfs_allocv: unknown node type");
	}
	vx_downgrade(vp);	/* downgrade VX lock to VN lock */

out:
	return error;
}

/*
 * devfs_allocvp allocates both a devfs node (with the given settings) and a vnode
 * based on the newly created devfs node.
 */
int
devfs_allocvp(struct mount *mp, struct vnode **vpp, devfs_nodetype devfsnodetype,
		char *name, struct devfs_node *parent, cdev_t dev)
{
	struct devfs_node *node;

	node = devfs_allocp(devfsnodetype, name, parent, mp, dev);

	if (node != NULL)
		devfs_allocv(vpp, node);
	else
		*vpp = NULL;

	return 0;
}

/*
 * Destroy the devfs_node.  The node must be unlinked from the topology.
 *
 * This function will also destroy any vnode association with the node
 * and device.
 *
 * The cdev_t itself remains intact.
 *
 * The core lock is not necessarily held on call and must be temporarily
 * released if it is to avoid a deadlock.
 */
void
devfs_freep(struct devfs_node *node)
{
	struct vnode *vp;
	int maxloops;

	KKASSERT(node);

	/*
	 * It is possible for devfs_freep() to race a destruction due
	 * to having to release the lock below.  We use DEVFS_DESTROYED
	 * to interlock the race (mediated by devfs_lock)
	 *
	 * We use NLINKSWAIT to indicate that the node couldn't be
	 * freed due to having pending nlinks.  We can free
	 * the node when nlinks drops to 0.  This should never print
	 * a "(null)" name, if it ever does there are still unresolved
	 * issues.
	 */
	if (node->flags & DEVFS_DESTROYED) {
		if ((node->flags & DEVFS_NLINKSWAIT) &&
		    node->nlinks == 0) {
			kprintf("devfs: final node '%s' on nlinks\n",
				node->d_dir.d_name);
			if (node->d_dir.d_name) {
				kfree(node->d_dir.d_name, M_DEVFS);
				node->d_dir.d_name = NULL;
			}
			objcache_put(devfs_node_cache, node);
		} else {
			kprintf("devfs: race avoided node '%s' (%p)\n",
				node->d_dir.d_name, node);
		}
		return;
	}
	node->flags |= DEVFS_DESTROYED;

	/*
	 * Items we have to dispose of before potentially releasing
	 * devfs_lock.
	 *
	 * Remove the node from the orphan list if it is still on it.
	 */
	atomic_subtract_long(&DEVFS_MNTDATA(node->mp)->leak_count, 1);
	atomic_subtract_long(&DEVFS_MNTDATA(node->mp)->file_count, 1);
	if (node->flags & DEVFS_ORPHANED)
		devfs_tracer_del_orphan(node);

	/*
	 * At this point only the vp points to node, and node cannot be
	 * physically freed because we own DEVFS_DESTROYED.
	 *
	 * We must dispose of the vnode without deadlocking or racing
	 * against e.g. a vnode reclaim.
	 *
	 * This also prevents the vnode reclaim code from double-freeing
	 * the node.  The vget() is required to safely modified the vp
	 * and cycle the refs to terminate an inactive vp.
	 */
	maxloops = 1000;
	while ((vp = node->v_node) != NULL) {
		int relock;

		vhold(vp);
		if (lockstatus(&devfs_lock, curthread) == LK_EXCLUSIVE) {
			lockmgr(&devfs_lock, LK_RELEASE);
			relock = 1;
		} else {
			relock = 0;
		}
		if (node->v_node == NULL) {
			/* reclaim race, mediated by devfs_lock */
			vdrop(vp);
		} else if (vget(vp, LK_EXCLUSIVE | LK_RETRY) == 0) {
			vdrop(vp);
			v_release_rdev(vp);
			vp->v_data = NULL;
			node->v_node = NULL;
			vput(vp);
		} else {
			/* reclaim race, mediated by devfs_lock */
			vdrop(vp);
		}
		if (relock)
			lockmgr(&devfs_lock, LK_EXCLUSIVE);
		if (--maxloops == 0) {
			kprintf("devfs_freep: livelock on node %p\n", node);
			break;
		}
	}

	/*
	 * Remaining cleanup
	 */
	if (node->symlink_name)	{
		kfree(node->symlink_name, M_DEVFS);
		node->symlink_name = NULL;
	}

	/*
	 * We cannot actually free the node if it still has
	 * nlinks.
	 */
	if (node->nlinks) {
		node->flags |= DEVFS_NLINKSWAIT;
	} else {
		if (node->d_dir.d_name) {
			kfree(node->d_dir.d_name, M_DEVFS);
			node->d_dir.d_name = NULL;
		}
		objcache_put(devfs_node_cache, node);
	}
}

/*
 * Returns a valid vp associated with the devfs alias node or NULL
 */
static void *devfs_alias_getvp(struct devfs_node *node)
{
	struct devfs_node *found = node;
	int depth = 0;

	while ((found->node_type == Nlink) && (found->link_target)) {
		if (depth >= 8) {
			devfs_debug(DEVFS_DEBUG_SHOW, "Recursive link or depth >= 8");
			break;
		}

		found = found->link_target;
		++depth;
	}

	return found->v_node;
}

/*
 * Unlink the devfs node from the topology and add it to the orphan list.
 * The node will later be destroyed by freep.
 *
 * Any vnode association, including the v_rdev and v_data, remains intact
 * until the freep.
 */
void
devfs_unlinkp(struct devfs_node *node)
{
	struct devfs_node *parent;
	struct devfs_node *target;
	struct vnode *vp;
	KKASSERT(node);

	/*
	 * Add the node to the orphan list, so it is referenced somewhere, to
	 * so we don't leak it.
	 */
	devfs_tracer_add_orphan(node);

	parent = node->parent;
	node->parent = NULL;

	/*
	 * If the parent is known we can unlink the node out of the topology
	 */
	if (node->flags & DEVFS_NODE_LINKED) {
		if (parent) {
			TAILQ_REMOVE(DEVFS_DENODE_HEAD(parent), node, link);
			parent->nchildren--;
		} else if (node == DEVFS_MNTDATA(node->mp)->root_node) {
			DEVFS_MNTDATA(node->mp)->root_node = NULL;
		}
		node->flags &= ~DEVFS_NODE_LINKED;
	}

	/*
	 * Namecache invalidation.
	 *
	 * devfs alias nodes are special: their v_node entry is always null
	 * and they use the one from their link target.  We thus use the
	 * target node's vp to invalidate both alias and target entries in
	 * the namecache.
	 *
	 * Doing so for the target is not necessary but it would be more
	 * expensive to resolve only the namecache entry of the alias node
	 * from the information available in this function.
	 *
	 * WARNING! We do not disassociate the vnode here.  That can only
	 *	    be safely done in devfs_freep().
	 */
	if (node->node_type == Nlink) {
		if ((target = node->link_target) != NULL) {
			vp = devfs_alias_getvp(node);
			node->link_target = NULL;
			target->nlinks--;
			if (target->nlinks == 0 &&
			    (target->flags & DEVFS_DESTROYED)) {
				devfs_freep(target);
			}
		} else {
			vp = NULL;
		}
	} else {
		vp = node->v_node;
	}

	if (vp != NULL)
		cache_inval_vp(vp, CINV_DESTROY);
}

void *
devfs_iterate_topology(struct devfs_node *node,
		devfs_iterate_callback_t *callback, void *arg1)
{
	struct devfs_node *node1, *node2;
	void *ret = NULL;

	if (((node->node_type == Nroot) || (node->node_type == Ndir)) &&
	    node->nchildren > 2) {
		TAILQ_FOREACH_MUTABLE(node1, DEVFS_DENODE_HEAD(node),
				      link, node2) {
			ret = devfs_iterate_topology(node1, callback, arg1);
			if (ret)
				return ret;
		}
	}
	ret = callback(node, arg1);

	return ret;
}

static void *
devfs_alias_reaper_callback(struct devfs_node *node, void *unused)
{
	if (node->node_type == Nlink) {
		devfs_unlinkp(node);
		devfs_freep(node);
	}

	return NULL;
}

/*
 * devfs_reaperp() is a recursive function that iterates through all the
 * topology, unlinking and freeing all devfs nodes.
 */
static void *
devfs_reaperp_callback(struct devfs_node *node, void *unused)
{
	devfs_unlinkp(node);
	devfs_freep(node);

	return NULL;
}

/*
 * Report any orphans that we couldn't delete.  The mp and mnt_data
 * are both disappearing, so we must also clean up the nodes a bit.
 */
static void
devfs_iterate_orphans_unmount(struct mount *mp)
{
	struct devfs_orphan *orphan;

	while ((orphan = TAILQ_FIRST(DEVFS_ORPHANLIST(mp))) != NULL) {
		devfs_freep(orphan->node);
		/* orphan stale */
	}
}

static void *
devfs_gc_dirs_callback(struct devfs_node *node, void *unused)
{
	if (node->node_type == Ndir) {
		if ((node->nchildren == 2) &&
		    !(node->flags & DEVFS_USER_CREATED)) {
			devfs_unlinkp(node);
			devfs_freep(node);
		}
	}

	return NULL;
}

static void *
devfs_gc_links_callback(struct devfs_node *node, struct devfs_node *target)
{
	if ((node->node_type == Nlink) && (node->link_target == target)) {
		devfs_unlinkp(node);
		devfs_freep(node);
	}

	return NULL;
}

/*
 * devfs_gc() is devfs garbage collector. It takes care of unlinking and
 * freeing a node, but also removes empty directories and links that link
 * via devfs auto-link mechanism to the node being deleted.
 */
int
devfs_gc(struct devfs_node *node)
{
	struct devfs_node *root_node = DEVFS_MNTDATA(node->mp)->root_node;

	if (node->nlinks > 0)
		devfs_iterate_topology(root_node,
				(devfs_iterate_callback_t *)devfs_gc_links_callback, node);

	devfs_unlinkp(node);
	devfs_iterate_topology(root_node,
			(devfs_iterate_callback_t *)devfs_gc_dirs_callback, NULL);

	devfs_freep(node);

	return 0;
}

/*
 * devfs_create_dev() is the asynchronous entry point for device creation.
 * It just sends a message with the relevant details to the devfs core.
 *
 * This function will reference the passed device.  The reference is owned
 * by devfs and represents all of the device's node associations.
 */
int
devfs_create_dev(cdev_t dev, uid_t uid, gid_t gid, int perms)
{
	reference_dev(dev);
	devfs_msg_send_dev(DEVFS_DEVICE_CREATE, dev, uid, gid, perms);

	return 0;
}

/*
 * devfs_destroy_dev() is the asynchronous entry point for device destruction.
 * It just sends a message with the relevant details to the devfs core.
 */
int
devfs_destroy_dev(cdev_t dev)
{
	devfs_msg_send_dev(DEVFS_DEVICE_DESTROY, dev, 0, 0, 0);
	return 0;
}

/*
 * devfs_mount_add() is the synchronous entry point for adding a new devfs
 * mount.  It sends a synchronous message with the relevant details to the
 * devfs core.
 */
int
devfs_mount_add(struct devfs_mnt_data *mnt)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_mnt = mnt;
	devfs_msg_send_sync(DEVFS_MOUNT_ADD, msg);
	devfs_msg_put(msg);

	return 0;
}

/*
 * devfs_mount_del() is the synchronous entry point for removing a devfs mount.
 * It sends a synchronous message with the relevant details to the devfs core.
 */
int
devfs_mount_del(struct devfs_mnt_data *mnt)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_mnt = mnt;
	devfs_msg_send_sync(DEVFS_MOUNT_DEL, msg);
	devfs_msg_put(msg);

	return 0;
}

/*
 * devfs_destroy_related() is the synchronous entry point for device
 * destruction by subname. It just sends a message with the relevant details to
 * the devfs core.
 */
int
devfs_destroy_related(cdev_t dev)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_load = dev;
	devfs_msg_send_sync(DEVFS_DESTROY_RELATED, msg);
	devfs_msg_put(msg);
	return 0;
}

int
devfs_clr_related_flag(cdev_t dev, uint32_t flag)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_flags.dev = dev;
	msg->mdv_flags.flag = flag;
	devfs_msg_send_sync(DEVFS_CLR_RELATED_FLAG, msg);
	devfs_msg_put(msg);

	return 0;
}

int
devfs_destroy_related_without_flag(cdev_t dev, uint32_t flag)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_flags.dev = dev;
	msg->mdv_flags.flag = flag;
	devfs_msg_send_sync(DEVFS_DESTROY_RELATED_WO_FLAG, msg);
	devfs_msg_put(msg);

	return 0;
}

/*
 * devfs_create_all_dev is the asynchronous entry point to trigger device
 * node creation.  It just sends a message with the relevant details to
 * the devfs core.
 */
int
devfs_create_all_dev(struct devfs_node *root)
{
	devfs_msg_send_generic(DEVFS_CREATE_ALL_DEV, root);
	return 0;
}

/*
 * devfs_destroy_dev_by_ops is the asynchronous entry point to destroy all
 * devices with a specific set of dev_ops and minor.  It just sends a
 * message with the relevant details to the devfs core.
 */
int
devfs_destroy_dev_by_ops(struct dev_ops *ops, int minor)
{
	devfs_msg_send_ops(DEVFS_DESTROY_DEV_BY_OPS, ops, minor);
	return 0;
}

/*
 * devfs_clone_handler_add is the synchronous entry point to add a new
 * clone handler.  It just sends a message with the relevant details to
 * the devfs core.
 */
int
devfs_clone_handler_add(const char *name, d_clone_t *nhandler)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_chandler.name = name;
	msg->mdv_chandler.nhandler = nhandler;
	devfs_msg_send_sync(DEVFS_CHANDLER_ADD, msg);
	devfs_msg_put(msg);
	return 0;
}

/*
 * devfs_clone_handler_del is the synchronous entry point to remove a
 * clone handler.  It just sends a message with the relevant details to
 * the devfs core.
 */
int
devfs_clone_handler_del(const char *name)
{
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_chandler.name = name;
	msg->mdv_chandler.nhandler = NULL;
	devfs_msg_send_sync(DEVFS_CHANDLER_DEL, msg);
	devfs_msg_put(msg);
	return 0;
}

/*
 * devfs_find_device_by_name is the synchronous entry point to find a
 * device given its name.  It sends a synchronous message with the
 * relevant details to the devfs core and returns the answer.
 */
cdev_t
devfs_find_device_by_name(const char *fmt, ...)
{
	cdev_t found = NULL;
	devfs_msg_t msg;
	char *target;
	__va_list ap;

	if (fmt == NULL)
		return NULL;

	__va_start(ap, fmt);
	kvasnprintf(&target, PATH_MAX, fmt, ap);
	__va_end(ap);

	msg = devfs_msg_get();
	msg->mdv_name = target;
	devfs_msg_send_sync(DEVFS_FIND_DEVICE_BY_NAME, msg);
	found = msg->mdv_cdev;
	devfs_msg_put(msg);
	kvasfree(&target);

	return found;
}

/*
 * devfs_find_device_by_devid is the synchronous entry point to find a
 * device given its udev number.  It sends a synchronous message with
 * the relevant details to the devfs core and returns the answer.
 */
cdev_t
devfs_find_device_by_devid(dev_t udev)
{
	cdev_t found = NULL;
	devfs_msg_t msg;

	msg = devfs_msg_get();
	msg->mdv_udev = udev;
	devfs_msg_send_sync(DEVFS_FIND_DEVICE_BY_DEVID, msg);
	found = msg->mdv_cdev;
	devfs_msg_put(msg);

	devfs_debug(DEVFS_DEBUG_DEBUG,
		    "devfs_find_device_by_devid found? %s  -end:3-\n",
		    ((found) ? found->si_name:"NO"));
	return found;
}

struct vnode *
devfs_inode_to_vnode(struct mount *mp, ino_t target)
{
	struct vnode *vp = NULL;
	devfs_msg_t msg;

	if (mp == NULL)
		return NULL;

	msg = devfs_msg_get();
	msg->mdv_ino.mp = mp;
	msg->mdv_ino.ino = target;
	devfs_msg_send_sync(DEVFS_INODE_TO_VNODE, msg);
	vp = msg->mdv_ino.vp;
	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
	devfs_msg_put(msg);

	return vp;
}

/*
 * devfs_make_alias is the asynchronous entry point to register an alias
 * for a device.  It just sends a message with the relevant details to the
 * devfs core.
 */
int
devfs_make_alias(const char *name, cdev_t dev_target)
{
	struct devfs_alias *alias;
	size_t len;

	len = strlen(name);

	alias = kmalloc(sizeof(struct devfs_alias), M_DEVFS, M_WAITOK);
	alias->name = kstrdup(name, M_DEVFS);
	alias->namlen = len;
	alias->dev_target = dev_target;

	devfs_msg_send_generic(DEVFS_MAKE_ALIAS, alias);
	return 0;
}

/*
 * devfs_destroy_alias is the asynchronous entry point to deregister an alias
 * for a device.  It just sends a message with the relevant details to the
 * devfs core.
 */
int
devfs_destroy_alias(const char *name, cdev_t dev_target)
{
	struct devfs_alias *alias;
	size_t len;

	len = strlen(name);

	alias = kmalloc(sizeof(struct devfs_alias), M_DEVFS, M_WAITOK);
	alias->name = kstrdup(name, M_DEVFS);
	alias->namlen = len;
	alias->dev_target = dev_target;

	devfs_msg_send_generic(DEVFS_DESTROY_ALIAS, alias);
	return 0;
}

/*
 * devfs_apply_rules is the asynchronous entry point to trigger application
 * of all rules.  It just sends a message with the relevant details to the
 * devfs core.
 */
int
devfs_apply_rules(char *mntto)
{
	char *new_name;

	new_name = kstrdup(mntto, M_DEVFS);
	devfs_msg_send_name(DEVFS_APPLY_RULES, new_name);

	return 0;
}

/*
 * devfs_reset_rules is the asynchronous entry point to trigger reset of all
 * rules. It just sends a message with the relevant details to the devfs core.
 */
int
devfs_reset_rules(char *mntto)
{
	char *new_name;

	new_name = kstrdup(mntto, M_DEVFS);
	devfs_msg_send_name(DEVFS_RESET_RULES, new_name);

	return 0;
}


/*
 * devfs_scan_callback is the asynchronous entry point to call a callback
 * on all cdevs.
 * It just sends a message with the relevant details to the devfs core.
 */
int
devfs_scan_callback(devfs_scan_t *callback, void *arg)
{
	devfs_msg_t msg;

	KKASSERT(callback);

	msg = devfs_msg_get();
	msg->mdv_load = callback;
	msg->mdv_load2 = arg;
	devfs_msg_send_sync(DEVFS_SCAN_CALLBACK, msg);
	devfs_msg_put(msg);

	return 0;
}


/*
 * Acts as a message drain. Any message that is replied to here gets destroyed
 * and the memory freed.
 */
static void
devfs_msg_autofree_reply(lwkt_port_t port, lwkt_msg_t msg)
{
	devfs_msg_put((devfs_msg_t)msg);
}

/*
 * devfs_msg_get allocates a new devfs msg and returns it.
 */
devfs_msg_t
devfs_msg_get(void)
{
	return objcache_get(devfs_msg_cache, M_WAITOK);
}

/*
 * devfs_msg_put deallocates a given devfs msg.
 */
int
devfs_msg_put(devfs_msg_t msg)
{
	objcache_put(devfs_msg_cache, msg);
	return 0;
}

/*
 * devfs_msg_send is the generic asynchronous message sending facility
 * for devfs. By default the reply port is the automatic disposal port.
 *
 * If the current thread is the devfs_msg_port thread we execute the
 * operation synchronously.
 */
void
devfs_msg_send(uint32_t cmd, devfs_msg_t devfs_msg)
{
	lwkt_port_t port = &devfs_msg_port;

	lwkt_initmsg(&devfs_msg->hdr, &devfs_dispose_port, 0);

	devfs_msg->hdr.u.ms_result = cmd;

	if (port->mpu_td == curthread) {
		devfs_msg_exec(devfs_msg);
		lwkt_replymsg(&devfs_msg->hdr, 0);
	} else {
		lwkt_sendmsg(port, (lwkt_msg_t)devfs_msg);
	}
}

/*
 * devfs_msg_send_sync is the generic synchronous message sending
 * facility for devfs. It initializes a local reply port and waits
 * for the core's answer. The core will write the answer on the same
 * message which is sent back as reply. The caller still has a reference
 * to the message, so we don't need to return it.
 */
int
devfs_msg_send_sync(uint32_t cmd, devfs_msg_t devfs_msg)
{
	struct lwkt_port rep_port;
	int	error;
	lwkt_port_t port = &devfs_msg_port;

	lwkt_initport_thread(&rep_port, curthread);
	lwkt_initmsg(&devfs_msg->hdr, &rep_port, 0);

	devfs_msg->hdr.u.ms_result = cmd;

	error = lwkt_domsg(port, (lwkt_msg_t)devfs_msg, 0);

	return error;
}

/*
 * sends a message with a generic argument.
 */
void
devfs_msg_send_generic(uint32_t cmd, void *load)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_load = load;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with a name argument.
 */
void
devfs_msg_send_name(uint32_t cmd, char *name)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_name = name;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with a mount argument.
 */
void
devfs_msg_send_mount(uint32_t cmd, struct devfs_mnt_data *mnt)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_mnt = mnt;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with an ops argument.
 */
void
devfs_msg_send_ops(uint32_t cmd, struct dev_ops *ops, int minor)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_ops.ops = ops;
	devfs_msg->mdv_ops.minor = minor;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with a clone handler argument.
 */
void
devfs_msg_send_chandler(uint32_t cmd, char *name, d_clone_t handler)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_chandler.name = name;
	devfs_msg->mdv_chandler.nhandler = handler;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with a device argument.
 */
void
devfs_msg_send_dev(uint32_t cmd, cdev_t dev, uid_t uid, gid_t gid, int perms)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_dev.dev = dev;
	devfs_msg->mdv_dev.uid = uid;
	devfs_msg->mdv_dev.gid = gid;
	devfs_msg->mdv_dev.perms = perms;

	devfs_msg_send(cmd, devfs_msg);
}

/*
 * sends a message with a link argument.
 */
void
devfs_msg_send_link(uint32_t cmd, char *name, char *target, struct mount *mp)
{
	devfs_msg_t devfs_msg = devfs_msg_get();

	devfs_msg->mdv_link.name = name;
	devfs_msg->mdv_link.target = target;
	devfs_msg->mdv_link.mp = mp;
	devfs_msg_send(cmd, devfs_msg);
}

/*
 * devfs_msg_core is the main devfs thread. It handles all incoming messages
 * and calls the relevant worker functions. By using messages it's assured
 * that events occur in the correct order.
 */
static void
devfs_msg_core(void *arg)
{
	devfs_msg_t msg;

	lwkt_initport_thread(&devfs_msg_port, curthread);

	lockmgr(&devfs_lock, LK_EXCLUSIVE);
	devfs_run = 1;
	wakeup(td_core);
	lockmgr(&devfs_lock, LK_RELEASE);

	lwkt_gettoken(&devfs_token);

	while (devfs_run) {
		msg = (devfs_msg_t)lwkt_waitport(&devfs_msg_port, 0);
		devfs_debug(DEVFS_DEBUG_DEBUG,
				"devfs_msg_core, new msg: %x\n",
				(unsigned int)msg->hdr.u.ms_result);
		devfs_msg_exec(msg);
		lwkt_replymsg(&msg->hdr, 0);
	}

	lwkt_reltoken(&devfs_token);
	wakeup(td_core);

	lwkt_exit();
}

static void
devfs_msg_exec(devfs_msg_t msg)
{
	struct devfs_mnt_data *mnt;
	struct devfs_node *node;
	cdev_t	dev;

	/*
	 * Acquire the devfs lock to ensure safety of all called functions
	 */
	lockmgr(&devfs_lock, LK_EXCLUSIVE);

	switch (msg->hdr.u.ms_result) {
	case DEVFS_DEVICE_CREATE:
		dev = msg->mdv_dev.dev;
		devfs_create_dev_worker(dev,
					msg->mdv_dev.uid,
					msg->mdv_dev.gid,
					msg->mdv_dev.perms);
		break;
	case DEVFS_DEVICE_DESTROY:
		dev = msg->mdv_dev.dev;
		devfs_destroy_dev_worker(dev);
		break;
	case DEVFS_DESTROY_RELATED:
		devfs_destroy_related_worker(msg->mdv_load);
		break;
	case DEVFS_DESTROY_DEV_BY_OPS:
		devfs_destroy_dev_by_ops_worker(msg->mdv_ops.ops,
						msg->mdv_ops.minor);
		break;
	case DEVFS_CREATE_ALL_DEV:
		node = (struct devfs_node *)msg->mdv_load;
		devfs_create_all_dev_worker(node);
		break;
	case DEVFS_MOUNT_ADD:
		mnt = msg->mdv_mnt;
		TAILQ_INSERT_TAIL(&devfs_mnt_list, mnt, link);
		devfs_create_all_dev_worker(mnt->root_node);
		break;
	case DEVFS_MOUNT_DEL:
		mnt = msg->mdv_mnt;
		TAILQ_REMOVE(&devfs_mnt_list, mnt, link);
		/* Be sure to remove all the aliases first */
		devfs_iterate_topology(mnt->root_node,
				       devfs_alias_reaper_callback,
				       NULL);
		devfs_iterate_topology(mnt->root_node,
				       devfs_reaperp_callback,
				       NULL);
		devfs_iterate_orphans_unmount(mnt->mp);
		if (mnt->leak_count) {
			devfs_debug(DEVFS_DEBUG_SHOW,
				    "Leaked %ld devfs_node elements!\n",
				    mnt->leak_count);
		}
		break;
	case DEVFS_CHANDLER_ADD:
		devfs_chandler_add_worker(msg->mdv_chandler.name,
				msg->mdv_chandler.nhandler);
		break;
	case DEVFS_CHANDLER_DEL:
		devfs_chandler_del_worker(msg->mdv_chandler.name);
		break;
	case DEVFS_FIND_DEVICE_BY_NAME:
		devfs_find_device_by_name_worker(msg);
		break;
	case DEVFS_FIND_DEVICE_BY_DEVID:
		devfs_find_device_by_devid_worker(msg);
		break;
	case DEVFS_MAKE_ALIAS:
		devfs_make_alias_worker((struct devfs_alias *)msg->mdv_load);
		break;
	case DEVFS_DESTROY_ALIAS:
		devfs_destroy_alias_worker((struct devfs_alias *)msg->mdv_load);
		break;
	case DEVFS_APPLY_RULES:
		devfs_apply_reset_rules_caller(msg->mdv_name, 1);
		break;
	case DEVFS_RESET_RULES:
		devfs_apply_reset_rules_caller(msg->mdv_name, 0);
		break;
	case DEVFS_SCAN_CALLBACK:
		devfs_scan_callback_worker((devfs_scan_t *)msg->mdv_load,
			msg->mdv_load2);
		break;
	case DEVFS_CLR_RELATED_FLAG:
		devfs_clr_related_flag_worker(msg->mdv_flags.dev,
				msg->mdv_flags.flag);
		break;
	case DEVFS_DESTROY_RELATED_WO_FLAG:
		devfs_destroy_related_without_flag_worker(msg->mdv_flags.dev,
				msg->mdv_flags.flag);
		break;
	case DEVFS_INODE_TO_VNODE:
		msg->mdv_ino.vp = devfs_iterate_topology(
			DEVFS_MNTDATA(msg->mdv_ino.mp)->root_node,
			(devfs_iterate_callback_t *)devfs_inode_to_vnode_worker_callback,
			&msg->mdv_ino.ino);
		break;
	case DEVFS_TERMINATE_CORE:
		devfs_run = 0;
		break;
	case DEVFS_SYNC:
		break;
	default:
		devfs_debug(DEVFS_DEBUG_WARNING,
			    "devfs_msg_core: unknown message "
			    "received at core\n");
		break;
	}
	lockmgr(&devfs_lock, LK_RELEASE);
}

static void
devfs_devctl_notify(cdev_t dev, const char *ev)
{
	static const char prefix[] = "cdev=";
	char *data;
	int namelen;

	namelen = strlen(dev->si_name);
	data = kmalloc(namelen + sizeof(prefix), M_TEMP, M_WAITOK);
	memcpy(data, prefix, sizeof(prefix) - 1);
	memcpy(data + sizeof(prefix) - 1, dev->si_name, namelen + 1);
	devctl_notify("DEVFS", "CDEV", ev, data);
	kfree(data, M_TEMP);
}

/*
 * Worker function to insert a new dev into the dev list and initialize its
 * permissions. It also calls devfs_propagate_dev which in turn propagates
 * the change to all mount points.
 *
 * The passed dev is already referenced.  This reference is eaten by this
 * function and represents the dev's linkage into devfs_dev_list.
 */
static int
devfs_create_dev_worker(cdev_t dev, uid_t uid, gid_t gid, int perms)
{
	KKASSERT(dev);

	dev->si_uid = uid;
	dev->si_gid = gid;
	dev->si_perms = perms;

	devfs_link_dev(dev);
	devfs_propagate_dev(dev, 1);

	udev_event_attach(dev, NULL, 0);
	devfs_devctl_notify(dev, "CREATE");

	return 0;
}

/*
 * Worker function to delete a dev from the dev list and free the cdev.
 * It also calls devfs_propagate_dev which in turn propagates the change
 * to all mount points.
 */
static int
devfs_destroy_dev_worker(cdev_t dev)
{
	int error;

	KKASSERT(dev);
	KKASSERT((lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE);

	error = devfs_unlink_dev(dev);
	devfs_propagate_dev(dev, 0);

	devfs_devctl_notify(dev, "DESTROY");
	udev_event_detach(dev, NULL, 0);

	if (error == 0)
		release_dev(dev);	/* link ref */
	release_dev(dev);
	release_dev(dev);

	return 0;
}

/*
 * Worker function to destroy all devices with a certain basename.
 * Calls devfs_destroy_dev_worker for the actual destruction.
 */
static int
devfs_destroy_related_worker(cdev_t needle)
{
	cdev_t dev;

restart:
	devfs_debug(DEVFS_DEBUG_DEBUG, "related worker: %s\n",
	    needle->si_name);
	TAILQ_FOREACH(dev, &devfs_dev_list, link) {
		if (dev->si_parent == needle) {
			devfs_destroy_related_worker(dev);
			devfs_destroy_dev_worker(dev);
			goto restart;
		}
	}
	return 0;
}

static int
devfs_clr_related_flag_worker(cdev_t needle, uint32_t flag)
{
	cdev_t dev, dev1;

	TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
		if (dev->si_parent == needle) {
			devfs_clr_related_flag_worker(dev, flag);
			dev->si_flags &= ~flag;
		}
	}

	return 0;
}

static int
devfs_destroy_related_without_flag_worker(cdev_t needle, uint32_t flag)
{
	cdev_t dev;

restart:
	devfs_debug(DEVFS_DEBUG_DEBUG, "related_wo_flag: %s\n",
	    needle->si_name);

	TAILQ_FOREACH(dev, &devfs_dev_list, link) {
		if (dev->si_parent == needle) {
			devfs_destroy_related_without_flag_worker(dev, flag);
			if (!(dev->si_flags & flag)) {
				devfs_destroy_dev_worker(dev);
				devfs_debug(DEVFS_DEBUG_DEBUG,
				    "related_wo_flag: %s restart\n", dev->si_name);
				goto restart;
			}
		}
	}

	return 0;
}

/*
 * Worker function that creates all device nodes on top of a devfs
 * root node.
 */
static int
devfs_create_all_dev_worker(struct devfs_node *root)
{
	cdev_t dev;

	KKASSERT(root);

	TAILQ_FOREACH(dev, &devfs_dev_list, link) {
		devfs_create_device_node(root, dev, NULL, NULL, NULL);
	}

	return 0;
}

/*
 * Worker function that destroys all devices that match a specific
 * dev_ops and/or minor. If minor is less than 0, it is not matched
 * against. It also propagates all changes.
 */
static int
devfs_destroy_dev_by_ops_worker(struct dev_ops *ops, int minor)
{
	cdev_t dev, dev1;

	KKASSERT(ops);

	TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
		if (dev->si_ops != ops)
			continue;
		if ((minor < 0) || (dev->si_uminor == minor)) {
			devfs_destroy_dev_worker(dev);
		}
	}

	return 0;
}

/*
 * Worker function that registers a new clone handler in devfs.
 */
static int
devfs_chandler_add_worker(const char *name, d_clone_t *nhandler)
{
	struct devfs_clone_handler *chandler = NULL;
	u_char len = strlen(name);

	if (len == 0)
		return 1;

	TAILQ_FOREACH(chandler, &devfs_chandler_list, link) {
		if (chandler->namlen != len)
			continue;

		if (!memcmp(chandler->name, name, len)) {
			/* Clonable basename already exists */
			return 1;
		}
	}

	chandler = kmalloc(sizeof(*chandler), M_DEVFS, M_WAITOK | M_ZERO);
	chandler->name = kstrdup(name, M_DEVFS);
	chandler->namlen = len;
	chandler->nhandler = nhandler;

	TAILQ_INSERT_TAIL(&devfs_chandler_list, chandler, link);
	return 0;
}

/*
 * Worker function that removes a given clone handler from the
 * clone handler list.
 */
static int
devfs_chandler_del_worker(const char *name)
{
	struct devfs_clone_handler *chandler, *chandler2;
	u_char len = strlen(name);

	if (len == 0)
		return 1;

	TAILQ_FOREACH_MUTABLE(chandler, &devfs_chandler_list, link, chandler2) {
		if (chandler->namlen != len)
			continue;
		if (memcmp(chandler->name, name, len))
			continue;

		TAILQ_REMOVE(&devfs_chandler_list, chandler, link);
		kfree(chandler->name, M_DEVFS);
		kfree(chandler, M_DEVFS);
		break;
	}

	return 0;
}

/*
 * Worker function that finds a given device name and changes
 * the message received accordingly so that when replied to,
 * the answer is returned to the caller.
 */
static int
devfs_find_device_by_name_worker(devfs_msg_t devfs_msg)
{
	struct devfs_alias *alias;
	cdev_t dev;
	cdev_t found = NULL;

	TAILQ_FOREACH(dev, &devfs_dev_list, link) {
		if (strcmp(devfs_msg->mdv_name, dev->si_name) == 0) {
			found = dev;
			break;
		}
	}
	if (found == NULL) {
		TAILQ_FOREACH(alias, &devfs_alias_list, link) {
			if (strcmp(devfs_msg->mdv_name, alias->name) == 0) {
				found = alias->dev_target;
				break;
			}
		}
	}
	devfs_msg->mdv_cdev = found;

	return 0;
}

/*
 * Worker function that finds a given device udev and changes
 * the message received accordingly so that when replied to,
 * the answer is returned to the caller.
 */
static int
devfs_find_device_by_devid_worker(devfs_msg_t devfs_msg)
{
	cdev_t dev, dev1;
	cdev_t found = NULL;

	TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
		if (((dev_t)dev->si_inode) == devfs_msg->mdv_udev) {
			found = dev;
			break;
		}
	}
	devfs_msg->mdv_cdev = found;

	return 0;
}

/*
 * Worker function that inserts a given alias into the
 * alias list, and propagates the alias to all mount
 * points.
 */
static int
devfs_make_alias_worker(struct devfs_alias *alias)
{
	struct devfs_alias *alias2;
	size_t len = strlen(alias->name);
	int found = 0;

	TAILQ_FOREACH(alias2, &devfs_alias_list, link) {
		if (len != alias2->namlen)
			continue;

		if (!memcmp(alias->name, alias2->name, len)) {
			found = 1;
			break;
		}
	}

	if (!found) {
		/*
		 * The alias doesn't exist yet, so we add it to the alias list
		 */
		TAILQ_INSERT_TAIL(&devfs_alias_list, alias, link);
		devfs_alias_propagate(alias, 0);
		udev_event_attach(alias->dev_target, alias->name, 1);
	} else {
		devfs_debug(DEVFS_DEBUG_WARNING,
			    "Warning: duplicate devfs_make_alias for %s\n",
			    alias->name);
		kfree(alias->name, M_DEVFS);
		kfree(alias, M_DEVFS);
	}

	return 0;
}

/*
 * Worker function that delete a given alias from the
 * alias list, and propagates the removal to all mount
 * points.
 */
static int
devfs_destroy_alias_worker(struct devfs_alias *alias)
{
	struct devfs_alias *alias2;
	int found = 0;

	TAILQ_FOREACH(alias2, &devfs_alias_list, link) {
		if (alias->dev_target != alias2->dev_target)
			continue;

		if (devfs_WildCmp(alias->name, alias2->name) == 0) {
			found = 1;
			break;
		}
	}

	if (!found) {
		devfs_debug(DEVFS_DEBUG_WARNING,
		    "Warning: devfs_destroy_alias for inexistant alias: %s\n",
		    alias->name);
		kfree(alias->name, M_DEVFS);
		kfree(alias, M_DEVFS);
	} else {
		/*
		 * The alias exists, so we delete it from the alias list
		 */
		TAILQ_REMOVE(&devfs_alias_list, alias2, link);
		devfs_alias_propagate(alias2, 1);
		udev_event_detach(alias2->dev_target, alias2->name, 1);
		kfree(alias->name, M_DEVFS);
		kfree(alias, M_DEVFS);
		kfree(alias2->name, M_DEVFS);
		kfree(alias2, M_DEVFS);
	}

	return 0;
}

/*
 * Function that removes and frees all aliases.
 */
static int
devfs_alias_reap(void)
{
	struct devfs_alias *alias, *alias2;

	TAILQ_FOREACH_MUTABLE(alias, &devfs_alias_list, link, alias2) {
		TAILQ_REMOVE(&devfs_alias_list, alias, link);
		kfree(alias->name, M_DEVFS);
		kfree(alias, M_DEVFS);
	}
	return 0;
}

/*
 * Function that removes an alias matching a specific cdev and frees
 * it accordingly.
 */
static int
devfs_alias_remove(cdev_t dev)
{
	struct devfs_alias *alias, *alias2;

	TAILQ_FOREACH_MUTABLE(alias, &devfs_alias_list, link, alias2) {
		if (alias->dev_target == dev) {
			TAILQ_REMOVE(&devfs_alias_list, alias, link);
			udev_event_detach(alias->dev_target, alias->name, 1);
			kfree(alias->name, M_DEVFS);
			kfree(alias, M_DEVFS);
		}
	}
	return 0;
}

/*
 * This function propagates an alias addition or removal to
 * all mount points.
 */
static int
devfs_alias_propagate(struct devfs_alias *alias, int remove)
{
	struct devfs_mnt_data *mnt;

	TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
		if (remove) {
			devfs_destroy_node(mnt->root_node, alias->name);
		} else {
			devfs_alias_apply(mnt->root_node, alias);
		}
	}
	return 0;
}

/*
 * This function is a recursive function iterating through
 * all device nodes in the topology and, if applicable,
 * creating the relevant alias for a device node.
 */
static int
devfs_alias_apply(struct devfs_node *node, struct devfs_alias *alias)
{
	struct devfs_node *node1, *node2;

	KKASSERT(alias != NULL);

	if ((node->node_type == Nroot) || (node->node_type == Ndir)) {
		if (node->nchildren > 2) {
			TAILQ_FOREACH_MUTABLE(node1, DEVFS_DENODE_HEAD(node), link, node2) {
				devfs_alias_apply(node1, alias);
			}
		}
	} else {
		if (node->d_dev == alias->dev_target)
			devfs_alias_create(alias->name, node, 0);
	}
	return 0;
}

/*
 * This function checks if any alias possibly is applicable
 * to the given node. If so, the alias is created.
 */
static int
devfs_alias_check_create(struct devfs_node *node)
{
	struct devfs_alias *alias;

	TAILQ_FOREACH(alias, &devfs_alias_list, link) {
		if (node->d_dev == alias->dev_target)
			devfs_alias_create(alias->name, node, 0);
	}
	return 0;
}

/*
 * This function creates an alias with a given name
 * linking to a given devfs node. It also increments
 * the link count on the target node.
 */
int
devfs_alias_create(char *name_orig, struct devfs_node *target, int rule_based)
{
	struct mount *mp = target->mp;
	struct devfs_node *parent = DEVFS_MNTDATA(mp)->root_node;
	struct devfs_node *linknode;
	char *create_path = NULL;
	char *name;
	char *name_buf;
	int result = 0;

	KKASSERT((lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE);

	name_buf = kmalloc(PATH_MAX, M_TEMP, M_WAITOK);
	devfs_resolve_name_path(name_orig, name_buf, &create_path, &name);

	if (create_path)
		parent = devfs_resolve_or_create_path(parent, create_path, 1);


	if (devfs_find_device_node_by_name(parent, name)) {
		devfs_debug(DEVFS_DEBUG_WARNING,
			    "Node already exists: %s "
			    "(devfs_make_alias_worker)!\n",
			    name);
		result = 1;
		goto done;
	}

	linknode = devfs_allocp(Nlink, name, parent, mp, NULL);
	if (linknode == NULL) {
		result = 1;
		goto done;
	}

	linknode->link_target = target;
	target->nlinks++;

	if (rule_based)
		linknode->flags |= DEVFS_RULE_CREATED;

done:
	kfree(name_buf, M_TEMP);
	return (result);
}

/*
 * This function is called by the core and handles mount point
 * strings. It either calls the relevant worker (devfs_apply_
 * reset_rules_worker) on all mountpoints or only a specific
 * one.
 */
static int
devfs_apply_reset_rules_caller(char *mountto, int apply)
{
	struct devfs_mnt_data *mnt;

	if (mountto[0] == '*') {
		TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
			devfs_iterate_topology(mnt->root_node,
					(apply)?(devfs_rule_check_apply):(devfs_rule_reset_node),
					NULL);
		}
	} else {
		TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
			if (!strcmp(mnt->mp->mnt_stat.f_mntonname, mountto)) {
				devfs_iterate_topology(mnt->root_node,
					(apply)?(devfs_rule_check_apply):(devfs_rule_reset_node),
					NULL);
				break;
			}
		}
	}

	kfree(mountto, M_DEVFS);
	return 0;
}

/*
 * This function calls a given callback function for
 * every dev node in the devfs dev list.
 */
static int
devfs_scan_callback_worker(devfs_scan_t *callback, void *arg)
{
	cdev_t dev, dev1;
	struct devfs_alias *alias, *alias1;

	TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
		callback(dev->si_name, dev, false, arg);
	}
	TAILQ_FOREACH_MUTABLE(alias, &devfs_alias_list, link, alias1) {
		callback(alias->name, alias->dev_target, true, arg);
	}

	return 0;
}

/*
 * This function tries to resolve a given directory, or if not
 * found and creation requested, creates the given directory.
 */
static struct devfs_node *
devfs_resolve_or_create_dir(struct devfs_node *parent, char *dir_name,
			    size_t name_len, int create)
{
	struct devfs_node *node, *found = NULL;

	TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(parent), link) {
		if (name_len != node->d_dir.d_namlen)
			continue;

		if (!memcmp(dir_name, node->d_dir.d_name, name_len)) {
			found = node;
			break;
		}
	}

	if ((found == NULL) && (create)) {
		found = devfs_allocp(Ndir, dir_name, parent, parent->mp, NULL);
	}

	return found;
}

/*
 * This function tries to resolve a complete path. If creation is requested,
 * if a given part of the path cannot be resolved (because it doesn't exist),
 * it is created.
 */
struct devfs_node *
devfs_resolve_or_create_path(struct devfs_node *parent, char *path, int create)
{
	struct devfs_node *node = parent;
	char *buf;
	size_t idx = 0;

	if (path == NULL)
		return parent;

	buf = kmalloc(PATH_MAX, M_TEMP, M_WAITOK);

	while (*path && idx < PATH_MAX - 1) {
		if (*path != '/') {
			buf[idx++] = *path;
		} else {
			buf[idx] = '\0';
			node = devfs_resolve_or_create_dir(node, buf, idx, create);
			if (node == NULL) {
				kfree(buf, M_TEMP);
				return NULL;
			}
			idx = 0;
		}
		++path;
	}
	buf[idx] = '\0';
	node = devfs_resolve_or_create_dir(node, buf, idx, create);
	kfree (buf, M_TEMP);
	return (node);
}

/*
 * Takes a full path and strips it into a directory path and a name.
 * For a/b/c/foo, it returns foo in namep and a/b/c in pathp. It
 * requires a working buffer with enough size to keep the whole
 * fullpath.
 */
int
devfs_resolve_name_path(char *fullpath, char *buf, char **pathp, char **namep)
{
	char *name = NULL;
	char *path = NULL;
	size_t len = strlen(fullpath) + 1;
	int i;

	KKASSERT((fullpath != NULL) && (buf != NULL));
	KKASSERT((pathp != NULL) && (namep != NULL));

	memcpy(buf, fullpath, len);

	for (i = len-1; i>= 0; i--) {
		if (buf[i] == '/') {
			buf[i] = '\0';
			name = &(buf[i+1]);
			path = buf;
			break;
		}
	}

	*pathp = path;

	if (name) {
		*namep = name;
	} else {
		*namep = buf;
	}

	return 0;
}

/*
 * This function creates a new devfs node for a given device.  It can
 * handle a complete path as device name, and accordingly creates
 * the path and the final device node.
 *
 * The reference count on the passed dev remains unchanged.
 */
struct devfs_node *
devfs_create_device_node(struct devfs_node *root, cdev_t dev,
			 int *existsp, char *dev_name, char *path_fmt, ...)
{
	struct devfs_node *parent, *node = NULL;
	char *path = NULL;
	char *name;
	char *name_buf;
	__va_list ap;
	int i, found;
	char *create_path = NULL;
	char *names = "pqrsPQRS";

	name_buf = kmalloc(PATH_MAX, M_TEMP, M_WAITOK);

	if (existsp)
		*existsp = 0;

	if (path_fmt != NULL) {
		__va_start(ap, path_fmt);
		kvasnprintf(&path, PATH_MAX, path_fmt, ap);
		__va_end(ap);
	}

	parent = devfs_resolve_or_create_path(root, path, 1);
	KKASSERT(parent);

	devfs_resolve_name_path(
			((dev_name == NULL) && (dev))?(dev->si_name):(dev_name),
			name_buf, &create_path, &name);

	if (create_path)
		parent = devfs_resolve_or_create_path(parent, create_path, 1);


	node = devfs_find_device_node_by_name(parent, name);
	if (node) {
		if (node->d_dev == dev) {
			/*
			 * Allow case where device caches dev after the
			 * close and might desire to reuse it.
			 */
			if (existsp)
				*existsp = 1;
		} else {
			devfs_debug(DEVFS_DEBUG_WARNING,
				    "devfs_create_device_node: "
				    "DEVICE %s ALREADY EXISTS!!! "
				    "Ignoring creation request.\n",
				    name);
			node = NULL;
		}
		goto out;
	}

	node = devfs_allocp(Ndev, name, parent, parent->mp, dev);
	vfs_timestamp(&parent->mtime);

	/*
	 * Ugly unix98 pty magic, to hide pty master (ptm) devices and their
	 * directory
	 */
	if ((dev) && (strlen(dev->si_name) >= 4) &&
			(!memcmp(dev->si_name, "ptm/", 4))) {
		node->parent->flags |= DEVFS_HIDDEN;
		node->flags |= DEVFS_HIDDEN;
	}

	/*
	 * Ugly pty magic, to tag pty devices as such and hide them if needed.
	 */
	if ((strlen(name) >= 3) && (!memcmp(name, "pty", 3)))
		node->flags |= (DEVFS_PTY | DEVFS_INVISIBLE);

	if ((strlen(name) >= 3) && (!memcmp(name, "tty", 3))) {
		found = 0;
		for (i = 0; i < strlen(names); i++) {
			if (name[3] == names[i]) {
				found = 1;
				break;
			}
		}
		if (found)
			node->flags |= (DEVFS_PTY | DEVFS_INVISIBLE);
	}

out:
	kfree(name_buf, M_TEMP);
	kvasfree(&path);
	return node;
}

/*
 * This function finds a given device node in the topology with a given
 * cdev.
 */
void *
devfs_find_device_node_callback(struct devfs_node *node, cdev_t target)
{
	if ((node->node_type == Ndev) && (node->d_dev == target)) {
		return node;
	}

	return NULL;
}

/*
 * This function finds a device node in the given parent directory by its
 * name and returns it.
 */
struct devfs_node *
devfs_find_device_node_by_name(struct devfs_node *parent, char *target)
{
	struct devfs_node *node, *found = NULL;
	size_t len = strlen(target);

	TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(parent), link) {
		if (len != node->d_dir.d_namlen)
			continue;

		if (!memcmp(node->d_dir.d_name, target, len)) {
			found = node;
			break;
		}
	}

	return found;
}

static void *
devfs_inode_to_vnode_worker_callback(struct devfs_node *node, ino_t *inop)
{
	struct vnode *vp = NULL;
	ino_t target = *inop;

	if (node->d_dir.d_ino == target) {
		if (node->v_node) {
			vp = node->v_node;
			vget(vp, LK_EXCLUSIVE | LK_RETRY);
			vn_unlock(vp);
		} else {
			devfs_allocv(&vp, node);
			vn_unlock(vp);
		}
	}

	return vp;
}

/*
 * This function takes a cdev and removes its devfs node in the
 * given topology.  The cdev remains intact.
 */
int
devfs_destroy_device_node(struct devfs_node *root, cdev_t target)
{
	KKASSERT(target != NULL);
	return devfs_destroy_node(root, target->si_name);
}

/*
 * This function takes a path to a devfs node, resolves it and
 * removes the devfs node from the given topology.
 */
int
devfs_destroy_node(struct devfs_node *root, char *target)
{
	struct devfs_node *node, *parent;
	char *name;
	char *name_buf;
	char *create_path = NULL;

	KKASSERT(target);

	name_buf = kmalloc(PATH_MAX, M_TEMP, M_WAITOK);
	ksnprintf(name_buf, PATH_MAX, "%s", target);

	devfs_resolve_name_path(target, name_buf, &create_path, &name);

	if (create_path)
		parent = devfs_resolve_or_create_path(root, create_path, 0);
	else
		parent = root;

	if (parent == NULL) {
		kfree(name_buf, M_TEMP);
		return 1;
	}

	node = devfs_find_device_node_by_name(parent, name);

	if (node) {
		vfs_timestamp(&node->parent->mtime);
		devfs_gc(node);
	}

	kfree(name_buf, M_TEMP);

	return 0;
}

/*
 * Just set perms and ownership for given node.
 */
int
devfs_set_perms(struct devfs_node *node, uid_t uid, gid_t gid,
		u_short mode, u_long flags)
{
	node->mode = mode;
	node->uid = uid;
	node->gid = gid;

	return 0;
}

/*
 * Propagates a device attach/detach to all mount
 * points. Also takes care of automatic alias removal
 * for a deleted cdev.
 */
static int
devfs_propagate_dev(cdev_t dev, int attach)
{
	struct devfs_mnt_data *mnt;

	TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
		if (attach) {
			/* Device is being attached */
			devfs_create_device_node(mnt->root_node, dev,
						 NULL, NULL, NULL);
		} else {
			/* Device is being detached */
			devfs_alias_remove(dev);
			devfs_destroy_device_node(mnt->root_node, dev);
		}
	}
	return 0;
}

/*
 * devfs_clone either returns a basename from a complete name by
 * returning the length of the name without trailing digits, or,
 * if clone != 0, calls the device's clone handler to get a new
 * device, which in turn is returned in devp.
 *
 * Caller must hold a shared devfs_lock
 */
cdev_t
devfs_clone(cdev_t dev, const char *name, size_t len, int mode,
		struct ucred *cred)
{
	int error;
	struct devfs_clone_handler *chandler;
	struct dev_clone_args ap;

	TAILQ_FOREACH(chandler, &devfs_chandler_list, link) {
		if (chandler->namlen != len)
			continue;
		if ((!memcmp(chandler->name, name, len)) &&
		    (chandler->nhandler)) {
			/*
			 * We have to unlock across the config and the
			 * callback to avoid deadlocking.  The device is
			 * likely to obtain its own lock in the callback
			 * and might then call into devfs.
			 */
			lockmgr(&devfs_lock, LK_RELEASE);
			devfs_config();
			ap.a_head.a_dev = dev;
			ap.a_dev = NULL;
			ap.a_name = name;
			ap.a_namelen = len;
			ap.a_mode = mode;
			ap.a_cred = cred;
			error = (chandler->nhandler)(&ap);
			lockmgr(&devfs_lock, LK_SHARED);
			if (error)
				continue;

			return ap.a_dev;
		}
	}

	return NULL;
}


/*
 * Registers a new orphan in the orphan list.
 */
void
devfs_tracer_add_orphan(struct devfs_node *node)
{
	struct devfs_orphan *orphan;

	KKASSERT(node);
	orphan = kmalloc(sizeof(struct devfs_orphan), M_DEVFS, M_WAITOK);
	orphan->node = node;

	KKASSERT((node->flags & DEVFS_ORPHANED) == 0);
	node->flags |= DEVFS_ORPHANED;
	TAILQ_INSERT_TAIL(DEVFS_ORPHANLIST(node->mp), orphan, link);
}

/*
 * Removes an orphan from the orphan list.
 */
void
devfs_tracer_del_orphan(struct devfs_node *node)
{
	struct devfs_orphan *orphan;

	KKASSERT(node);

	TAILQ_FOREACH(orphan, DEVFS_ORPHANLIST(node->mp), link)	{
		if (orphan->node == node) {
			node->flags &= ~DEVFS_ORPHANED;
			TAILQ_REMOVE(DEVFS_ORPHANLIST(node->mp), orphan, link);
			kfree(orphan, M_DEVFS);
			break;
		}
	}
}

/*
 * Counts the orphans in the orphan list, and if cleanup
 * is specified, also frees the orphan and removes it from
 * the list.
 */
size_t
devfs_tracer_orphan_count(struct mount *mp, int cleanup)
{
	struct devfs_orphan *orphan, *orphan2;
	size_t count = 0;

	TAILQ_FOREACH_MUTABLE(orphan, DEVFS_ORPHANLIST(mp), link, orphan2)	{
		count++;
		/*
		 * If we are instructed to clean up, we do so.
		 */
		if (cleanup) {
			TAILQ_REMOVE(DEVFS_ORPHANLIST(mp), orphan, link);
			orphan->node->flags &= ~DEVFS_ORPHANED;
			devfs_freep(orphan->node);
			kfree(orphan, M_DEVFS);
		}
	}

	return count;
}

/*
 * Fetch an ino_t from the global d_ino by increasing it
 * while spinlocked.
 */
static ino_t
devfs_fetch_ino(void)
{
	ino_t	ret;

	spin_lock(&ino_lock);
	ret = d_ino++;
	spin_unlock(&ino_lock);

	return ret;
}

/*
 * Allocates a new cdev and initializes it's most basic
 * fields.
 */
cdev_t
devfs_new_cdev(struct dev_ops *ops, int minor, struct dev_ops *bops)
{
	cdev_t dev = sysref_alloc(&cdev_sysref_class);

	sysref_activate(&dev->si_sysref);
	reference_dev(dev);
	bzero(dev, offsetof(struct cdev, si_sysref));

	lockmgr(&devfs_lock, LK_EXCLUSIVE);

	dev->si_uid = 0;
	dev->si_gid = 0;
	dev->si_perms = 0;
	dev->si_drv1 = NULL;
	dev->si_drv2 = NULL;
	dev->si_lastread = 0;		/* time_uptime */
	dev->si_lastwrite = 0;		/* time_uptime */

	dev->si_dict = NULL;
	dev->si_parent = NULL;
	dev->si_ops = ops;
	dev->si_flags = 0;
	dev->si_uminor = minor;
	dev->si_bops = bops;

	/*
	 * Since the disk subsystem is in the way, we need to
	 * propagate the D_CANFREE from bops (and ops) to
	 * si_flags.
	 */
	if (bops && (bops->head.flags & D_CANFREE)) {
		dev->si_flags |= SI_CANFREE;
	} else if (ops->head.flags & D_CANFREE) {
		dev->si_flags |= SI_CANFREE;
	}

	/* If there is a backing device, we reference its ops */
	if (bops == NULL)
		bops = ops;
	dev->si_inode = makeudev(devfs_reference_ops(bops), minor);
	dev->si_umajor = umajor(dev->si_inode);

	lockmgr(&devfs_lock, LK_RELEASE);

	return dev;
}

static void
devfs_cdev_terminate(cdev_t dev)
{
	/*
	 * Make sure the node isn't linked anymore. Otherwise we've screwed
	 * up somewhere, since normal devs are unlinked on the call to
	 * destroy_dev and only-cdevs that have not been used for cloning
	 * are not linked in the first place. only-cdevs used for cloning
	 * will be linked in, too, and should only be destroyed via
	 * destroy_dev, not destroy_only_dev, so we catch that problem, too.
	 */
	KKASSERT((dev->si_flags & SI_DEVFS_LINKED) == 0);

	/* If there is a backing device, we release the backing device's ops */
	devfs_release_ops((dev->si_bops)?(dev->si_bops):(dev->si_ops));

	/* devfs_cdev_unlock() is not called, unlock ourselves */
	lockmgr(&devfs_lock, LK_RELEASE);

	/* Finally destroy the device */
	sysref_put(&dev->si_sysref);
}

/*
 * Dummies for now (individual locks for MPSAFE)
 */
static void
devfs_cdev_lock(cdev_t dev)
{
	lockmgr(&devfs_lock, LK_EXCLUSIVE);
}

static void
devfs_cdev_unlock(cdev_t dev)
{
	lockmgr(&devfs_lock, LK_RELEASE);
}

static int
devfs_detached_filter_eof(struct knote *kn, long hint)
{
	kn->kn_flags |= (EV_EOF | EV_NODATA);
	return (1);
}

static void
devfs_detached_filter_detach(struct knote *kn)
{
	cdev_t dev = (cdev_t)kn->kn_hook;

	knote_remove(&dev->si_kqinfo.ki_note, kn);
}

static struct filterops devfs_detached_filterops =
	{ FILTEROP_ISFD, NULL,
	  devfs_detached_filter_detach,
	  devfs_detached_filter_eof };

/*
 * Delegates knote filter handling responsibility to devfs
 *
 * Any device that implements kqfilter event handling and could be detached
 * or shut down out from under the kevent subsystem must allow devfs to
 * assume responsibility for any knotes it may hold.
 */
void
devfs_assume_knotes(cdev_t dev, struct kqinfo *kqi)
{
	/*
	 * Let kern/kern_event.c do the heavy lifting.
	 */
	knote_assume_knotes(kqi, &dev->si_kqinfo,
			    &devfs_detached_filterops, (void *)dev);

	/*
	 * These should probably be activated individually, but doing so
	 * would require refactoring kq's public in-kernel interface.
	 */
	KNOTE(&dev->si_kqinfo.ki_note, 0);
}

/*
 * Links a given cdev into the dev list.
 */
int
devfs_link_dev(cdev_t dev)
{
	KKASSERT((dev->si_flags & SI_DEVFS_LINKED) == 0);
	dev->si_flags |= SI_DEVFS_LINKED;
	TAILQ_INSERT_TAIL(&devfs_dev_list, dev, link);

	return 0;
}

/*
 * Removes a given cdev from the dev list.  The caller is responsible for
 * releasing the reference on the device associated with the linkage.
 *
 * Returns EALREADY if the dev has already been unlinked.
 */
static int
devfs_unlink_dev(cdev_t dev)
{
	if ((dev->si_flags & SI_DEVFS_LINKED)) {
		TAILQ_REMOVE(&devfs_dev_list, dev, link);
		dev->si_flags &= ~SI_DEVFS_LINKED;
		return (0);
	}
	return (EALREADY);
}

int
devfs_node_is_accessible(struct devfs_node *node)
{
	if ((node) && (!(node->flags & DEVFS_HIDDEN)))
		return 1;
	else
		return 0;
}

/*
 * devfs must be locked
 */
static int
devfs_reference_ops(struct dev_ops *ops)
{
	int unit;
	struct devfs_dev_ops *found = NULL;
	struct devfs_dev_ops *devops;

	TAILQ_FOREACH(devops, &devfs_dev_ops_list, link) {
		if (devops->ops == ops) {
			found = devops;
			break;
		}
	}

	if (!found) {
		found = kmalloc(sizeof(struct devfs_dev_ops),
				M_DEVFS, M_WAITOK);
		found->ops = ops;
		found->ref_count = 0;
		TAILQ_INSERT_TAIL(&devfs_dev_ops_list, found, link);
	}

	KKASSERT(found);

	if (found->ref_count == 0) {
		found->id =
		    devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(ops_id), 255);
		if (found->id == -1) {
			/* Ran out of unique ids */
			devfs_debug(DEVFS_DEBUG_WARNING,
				    "devfs_reference_ops: WARNING: ran "
				    "out of unique ids\n");
		}
	}
	unit = found->id;
	++found->ref_count;

	return unit;
}

/*
 * devfs must be locked
 */
static void
devfs_release_ops(struct dev_ops *ops)
{
	struct devfs_dev_ops *found = NULL;
	struct devfs_dev_ops *devops;

	TAILQ_FOREACH(devops, &devfs_dev_ops_list, link) {
		if (devops->ops == ops) {
			found = devops;
			break;
		}
	}

	KKASSERT(found);

	--found->ref_count;

	if (found->ref_count == 0) {
		TAILQ_REMOVE(&devfs_dev_ops_list, found, link);
		lockmgr(&devfs_lock, LK_RELEASE);
		devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(ops_id), found->id);
		lockmgr(&devfs_lock, LK_EXCLUSIVE);
		kfree(found, M_DEVFS);
	}
}

/*
 * Wait for asynchronous messages to complete in the devfs helper
 * thread, then return.  Do nothing if the helper thread is dead
 * or we are being indirectly called from the helper thread itself.
 */
void
devfs_config(void)
{
	devfs_msg_t msg;

	if (devfs_run && curthread != td_core) {
		msg = devfs_msg_get();
		devfs_msg_send_sync(DEVFS_SYNC, msg);
		devfs_msg_put(msg);
	}
}

/*
 * Called on init of devfs; creates the objcaches and
 * spawns off the devfs core thread. Also initializes
 * locks.
 */
static void
devfs_init(void)
{
	devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_init() called\n");
	/* Create objcaches for nodes, msgs and devs */
	devfs_node_cache = objcache_create("devfs-node-cache", 0, 0,
					   NULL, NULL, NULL,
					   objcache_malloc_alloc,
					   objcache_malloc_free,
					   &devfs_node_malloc_args );

	devfs_msg_cache = objcache_create("devfs-msg-cache", 0, 0,
					  NULL, NULL, NULL,
					  objcache_malloc_alloc,
					  objcache_malloc_free,
					  &devfs_msg_malloc_args );

	devfs_dev_cache = objcache_create("devfs-dev-cache", 0, 0,
					  NULL, NULL, NULL,
					  objcache_malloc_alloc,
					  objcache_malloc_free,
					  &devfs_dev_malloc_args );

	devfs_clone_bitmap_init(&DEVFS_CLONE_BITMAP(ops_id));

	/* Initialize the reply-only port which acts as a message drain */
	lwkt_initport_replyonly(&devfs_dispose_port, devfs_msg_autofree_reply);

	/* Initialize *THE* devfs lock */
	lockinit(&devfs_lock, "devfs_core lock", 0, LK_CANRECURSE);
	lwkt_token_init(&devfs_token, "devfs_core");

	lockmgr(&devfs_lock, LK_EXCLUSIVE);
	lwkt_create(devfs_msg_core, /*args*/NULL, &td_core, NULL,
		    0, -1, "devfs_msg_core");
	while (devfs_run == 0)
		lksleep(td_core, &devfs_lock, 0, "devfsc", 0);
	lockmgr(&devfs_lock, LK_RELEASE);

	devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_init finished\n");
}

/*
 * Called on unload of devfs; takes care of destroying the core
 * and the objcaches. Also removes aliases that are no longer needed.
 */
static void
devfs_uninit(void)
{
	devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_uninit() called\n");

	devfs_msg_send(DEVFS_TERMINATE_CORE, NULL);
	while (devfs_run)
		tsleep(td_core, 0, "devfsc", hz*10);
	tsleep(td_core, 0, "devfsc", hz);

	devfs_clone_bitmap_uninit(&DEVFS_CLONE_BITMAP(ops_id));

	/* Destroy the objcaches */
	objcache_destroy(devfs_msg_cache);
	objcache_destroy(devfs_node_cache);
	objcache_destroy(devfs_dev_cache);

	devfs_alias_reap();
}

/*
 * This is a sysctl handler to assist userland devname(3) to
 * find the device name for a given udev.
 */
static int
devfs_sysctl_devname_helper(SYSCTL_HANDLER_ARGS)
{
	dev_t 	udev;
	cdev_t	found;
	int		error;

	if ((error = SYSCTL_IN(req, &udev, sizeof(dev_t))))
		return (error);

	devfs_debug(DEVFS_DEBUG_DEBUG,
		    "devfs sysctl, received udev: %d\n", udev);

	if (udev == NOUDEV)
		return(EINVAL);

	if ((found = devfs_find_device_by_devid(udev)) == NULL)
		return(ENOENT);

	return(SYSCTL_OUT(req, found->si_name, strlen(found->si_name) + 1));
}


SYSCTL_PROC(_kern, OID_AUTO, devname,
	    CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_NOLOCK,
	    NULL, 0, devfs_sysctl_devname_helper, "",
	    "helper for devname(3)");

SYSCTL_NODE(_vfs, OID_AUTO, devfs, CTLFLAG_RW, 0, "devfs");
TUNABLE_INT("vfs.devfs.debug", &devfs_debug_enable);
SYSCTL_INT(_vfs_devfs, OID_AUTO, debug, CTLFLAG_RW, &devfs_debug_enable,
		0, "Enable DevFS debugging");

SYSINIT(vfs_devfs_register, SI_SUB_DEVFS_CORE, SI_ORDER_FIRST,
		devfs_init, NULL);
SYSUNINIT(vfs_devfs_register, SI_SUB_DEVFS_CORE, SI_ORDER_ANY,
		devfs_uninit, NULL);

/*
 * WildCmp() - compare wild string to sane string
 *
 *	Returns 0 on success, -1 on failure.
 */
static int
wildCmp(const char **mary, int d, const char *w, const char *s)
{
    int i;

    /*
     * skip fixed portion
     */
    for (;;) {
	switch(*w) {
	case '*':
	    /*
	     * optimize terminator
	     */
	    if (w[1] == 0)
		return(0);
	    if (w[1] != '?' && w[1] != '*') {
		/*
		 * optimize * followed by non-wild
		 */
		for (i = 0; s + i < mary[d]; ++i) {
		    if (s[i] == w[1] && wildCmp(mary, d + 1, w + 1, s + i) == 0)
			return(0);
		}
	    } else {
		/*
		 * less-optimal
		 */
		for (i = 0; s + i < mary[d]; ++i) {
		    if (wildCmp(mary, d + 1, w + 1, s + i) == 0)
			return(0);
		}
	    }
	    mary[d] = s;
	    return(-1);
	case '?':
	    if (*s == 0)
		return(-1);
	    ++w;
	    ++s;
	    break;
	default:
	    if (*w != *s)
		return(-1);
	    if (*w == 0)	/* terminator */
		return(0);
	    ++w;
	    ++s;
	    break;
	}
    }
    /* not reached */
    return(-1);
}


/*
 * WildCaseCmp() - compare wild string to sane string, case insensitive
 *
 *	Returns 0 on success, -1 on failure.
 */
static int
wildCaseCmp(const char **mary, int d, const char *w, const char *s)
{
    int i;

    /*
     * skip fixed portion
     */
    for (;;) {
	switch(*w) {
	case '*':
	    /*
	     * optimize terminator
	     */
	    if (w[1] == 0)
		return(0);
	    if (w[1] != '?' && w[1] != '*') {
		/*
		 * optimize * followed by non-wild
		 */
		for (i = 0; s + i < mary[d]; ++i) {
		    if (s[i] == w[1] && wildCaseCmp(mary, d + 1, w + 1, s + i) == 0)
			return(0);
		}
	    } else {
		/*
		 * less-optimal
		 */
		for (i = 0; s + i < mary[d]; ++i) {
		    if (wildCaseCmp(mary, d + 1, w + 1, s + i) == 0)
			return(0);
		}
	    }
	    mary[d] = s;
	    return(-1);
	case '?':
	    if (*s == 0)
		return(-1);
	    ++w;
	    ++s;
	    break;
	default:
	    if (*w != *s) {
#define tolower(x)	((x >= 'A' && x <= 'Z')?(x+('a'-'A')):(x))
		if (tolower(*w) != tolower(*s))
		    return(-1);
	    }
	    if (*w == 0)	/* terminator */
		return(0);
	    ++w;
	    ++s;
	    break;
	}
    }
    /* not reached */
    return(-1);
}

struct cdev_privdata {
	void		*cdpd_data;
	d_priv_dtor_t	*cdpd_dtr;
};

int
devfs_get_cdevpriv(struct file *fp, void **datap)
{
	int error;

	if (fp == NULL)
		return(EBADF);

	spin_lock_shared(&fp->f_spin);
	if (fp->f_data1 == NULL) {
		*datap = NULL;
		error = ENOENT;
	} else {
		struct cdev_privdata *p = fp->f_data1;

		*datap = p->cdpd_data;
		error = 0;
	}
	spin_unlock_shared(&fp->f_spin);

	return (error);
}

int
devfs_set_cdevpriv(struct file *fp, void *priv, d_priv_dtor_t *dtr)
{
	struct cdev_privdata *p;
	int error;

	if (fp == NULL)
		return (ENOENT);

	p = kmalloc(sizeof(struct cdev_privdata), M_DEVFS, M_WAITOK);
	p->cdpd_data = priv;
	p->cdpd_dtr = dtr;

	spin_lock(&fp->f_spin);
	if (fp->f_data1 == NULL) {
		fp->f_data1 = p;
		error = 0;
	} else {
		error = EBUSY;
	}
	spin_unlock(&fp->f_spin);

	if (error)
		kfree(p, M_DEVFS);

	return error;
}

void
devfs_clear_cdevpriv(struct file *fp)
{
	struct cdev_privdata *p;

	if (fp == NULL)
		return;

	spin_lock(&fp->f_spin);
	p = fp->f_data1;
	fp->f_data1 = NULL;
	spin_unlock(&fp->f_spin);

	if (p != NULL) {
		p->cdpd_dtr(p->cdpd_data);
		kfree(p, M_DEVFS);
	}
}

int
devfs_WildCmp(const char *w, const char *s)
{
    int i;
    int c;
    int slen = strlen(s);
    const char **mary;

    for (i = c = 0; w[i]; ++i) {
	if (w[i] == '*')
	    ++c;
    }
    mary = kmalloc(sizeof(char *) * (c + 1), M_DEVFS, M_WAITOK);
    for (i = 0; i < c; ++i)
	mary[i] = s + slen;
    i = wildCmp(mary, 0, w, s);
    kfree(mary, M_DEVFS);
    return(i);
}

int
devfs_WildCaseCmp(const char *w, const char *s)
{
    int i;
    int c;
    int slen = strlen(s);
    const char **mary;

    for (i = c = 0; w[i]; ++i) {
	if (w[i] == '*')
	    ++c;
    }
    mary = kmalloc(sizeof(char *) * (c + 1), M_DEVFS, M_WAITOK);
    for (i = 0; i < c; ++i)
	mary[i] = s + slen;
    i = wildCaseCmp(mary, 0, w, s);
    kfree(mary, M_DEVFS);
    return(i);
}