Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

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

#ifndef APPLEKEXT
#include <fs/nfs/common/nfsport.h>

struct nfsrv_stablefirst nfsrv_stablefirst;
int nfsrv_issuedelegs = 0;
int nfsrv_dolocallocks = 0;
struct nfsv4lock nfsv4rootfs_lock;

extern int newnfs_numnfsd;
extern struct nfsstatsv1 nfsstatsv1;
extern int nfsrv_lease;
extern struct timeval nfsboottime;
extern u_int32_t newnfs_true, newnfs_false;
NFSV4ROOTLOCKMUTEX;
NFSSTATESPINLOCK;

SYSCTL_DECL(_vfs_nfsd);
int	nfsrv_statehashsize = NFSSTATEHASHSIZE;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, statehashsize, CTLFLAG_RDTUN,
    &nfsrv_statehashsize, 0,
    "Size of state hash table set via loader.conf");

int	nfsrv_clienthashsize = NFSCLIENTHASHSIZE;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, clienthashsize, CTLFLAG_RDTUN,
    &nfsrv_clienthashsize, 0,
    "Size of client hash table set via loader.conf");

int	nfsrv_lockhashsize = NFSLOCKHASHSIZE;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, fhhashsize, CTLFLAG_RDTUN,
    &nfsrv_lockhashsize, 0,
    "Size of file handle hash table set via loader.conf");

int	nfsrv_sessionhashsize = NFSSESSIONHASHSIZE;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, sessionhashsize, CTLFLAG_RDTUN,
    &nfsrv_sessionhashsize, 0,
    "Size of session hash table set via loader.conf");

static int	nfsrv_v4statelimit = NFSRV_V4STATELIMIT;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, v4statelimit, CTLFLAG_RWTUN,
    &nfsrv_v4statelimit, 0,
    "High water limit for NFSv4 opens+locks+delegations");

static int	nfsrv_writedelegifpos = 0;
SYSCTL_INT(_vfs_nfsd, OID_AUTO, writedelegifpos, CTLFLAG_RW,
    &nfsrv_writedelegifpos, 0,
    "Issue a write delegation for read opens if possible");

/*
 * Hash lists for nfs V4.
 */
struct nfsclienthashhead	*nfsclienthash;
struct nfslockhashhead		*nfslockhash;
struct nfssessionhash		*nfssessionhash;
#endif	/* !APPLEKEXT */

static u_int32_t nfsrv_openpluslock = 0, nfsrv_delegatecnt = 0;
static time_t nfsrvboottime;
static int nfsrv_returnoldstateid = 0, nfsrv_clients = 0;
static int nfsrv_clienthighwater = NFSRV_CLIENTHIGHWATER;
static int nfsrv_nogsscallback = 0;

/* local functions */
static void nfsrv_dumpaclient(struct nfsclient *clp,
    struct nfsd_dumpclients *dumpp);
static void nfsrv_freeopenowner(struct nfsstate *stp, int cansleep,
    NFSPROC_T *p);
static int nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep,
    NFSPROC_T *p);
static void nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
    NFSPROC_T *p);
static void nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp,
    int cansleep, NFSPROC_T *p);
static void nfsrv_freenfslock(struct nfslock *lop);
static void nfsrv_freenfslockfile(struct nfslockfile *lfp);
static void nfsrv_freedeleg(struct nfsstate *);
static int nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, 
    u_int32_t flags, struct nfsstate **stpp);
static void nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
    struct nfsstate **stpp);
static int nfsrv_getlockfh(vnode_t vp, u_short flags,
    struct nfslockfile *new_lfp, fhandle_t *nfhp, NFSPROC_T *p);
static int nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
    struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit);
static void nfsrv_insertlock(struct nfslock *new_lop,
    struct nfslock *insert_lop, struct nfsstate *stp, struct nfslockfile *lfp);
static void nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
    struct nfslock **other_lopp, struct nfslockfile *lfp);
static int nfsrv_getipnumber(u_char *cp);
static int nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
    nfsv4stateid_t *stateidp, int specialid);
static int nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
    u_int32_t flags);
static int nfsrv_docallback(struct nfsclient *clp, int procnum,
    nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
    struct nfsvattr *nap, nfsattrbit_t *attrbitp, NFSPROC_T *p);
static int nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
    uint32_t callback, int op, const char *optag, struct nfsdsession **sepp);
static u_int32_t nfsrv_nextclientindex(void);
static u_int32_t nfsrv_nextstateindex(struct nfsclient *clp);
static void nfsrv_markstable(struct nfsclient *clp);
static int nfsrv_checkstable(struct nfsclient *clp);
static int nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, struct 
    vnode *vp, NFSPROC_T *p);
static int nfsrv_delegconflict(struct nfsstate *stp, int *haslockp,
    NFSPROC_T *p, vnode_t vp);
static int nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
    struct nfsclient *clp, int *haslockp, NFSPROC_T *p);
static int nfsrv_notsamecredname(struct nfsrv_descript *nd,
    struct nfsclient *clp);
static time_t nfsrv_leaseexpiry(void);
static void nfsrv_delaydelegtimeout(struct nfsstate *stp);
static int nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
    struct nfsstate *stp, struct nfsrvcache *op);
static int nfsrv_nootherstate(struct nfsstate *stp);
static int nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
    uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p);
static void nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp,
    uint64_t init_first, uint64_t init_end, NFSPROC_T *p);
static int nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags,
    int oldflags, uint64_t first, uint64_t end, struct nfslockconflict *cfp,
    NFSPROC_T *p);
static void nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp,
    NFSPROC_T *p);
static void nfsrv_locallock_commit(struct nfslockfile *lfp, int flags,
    uint64_t first, uint64_t end);
static void nfsrv_locklf(struct nfslockfile *lfp);
static void nfsrv_unlocklf(struct nfslockfile *lfp);
static struct nfsdsession *nfsrv_findsession(uint8_t *sessionid);
static int nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid);
static int nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
    int dont_replycache, struct nfsdsession **sepp);
static int nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp);

/*
 * Scan the client list for a match and either return the current one,
 * create a new entry or return an error.
 * If returning a non-error, the clp structure must either be linked into
 * the client list or free'd.
 */
APPLESTATIC int
nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
    nfsquad_t *clientidp, nfsquad_t *confirmp, NFSPROC_T *p)
{
	struct nfsclient *clp = NULL, *new_clp = *new_clpp;
	int i, error = 0;
	struct nfsstate *stp, *tstp;
	struct sockaddr_in *sad, *rad;
	int zapit = 0, gotit, hasstate = 0, igotlock;
	static u_int64_t confirm_index = 0;

	/*
	 * Check for state resource limit exceeded.
	 */
	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
		error = NFSERR_RESOURCE;
		goto out;
	}

	if (nfsrv_issuedelegs == 0 ||
	    ((nd->nd_flag & ND_GSS) != 0 && nfsrv_nogsscallback != 0))
		/*
		 * Don't do callbacks when delegations are disabled or
		 * for AUTH_GSS unless enabled via nfsrv_nogsscallback.
		 * If establishing a callback connection is attempted
		 * when a firewall is blocking the callback path, the
		 * server may wait too long for the connect attempt to
		 * succeed during the Open. Some clients, such as Linux,
		 * may timeout and give up on the Open before the server
		 * replies. Also, since AUTH_GSS callbacks are not
		 * yet interoperability tested, they might cause the
		 * server to crap out, if they get past the Init call to
		 * the client.
		 */
		new_clp->lc_program = 0;

	/* Lock out other nfsd threads */
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	do {
		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
		    NFSV4ROOTLOCKMUTEXPTR, NULL);
	} while (!igotlock);
	NFSUNLOCKV4ROOTMUTEX();

	/*
	 * Search for a match in the client list.
	 */
	gotit = i = 0;
	while (i < nfsrv_clienthashsize && !gotit) {
	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
		if (new_clp->lc_idlen == clp->lc_idlen &&
		    !NFSBCMP(new_clp->lc_id, clp->lc_id, clp->lc_idlen)) {
			gotit = 1;
			break;
		}
	    }
	    if (gotit == 0)
		i++;
	}
	if (!gotit ||
	    (clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_ADMINREVOKED))) {
		if ((nd->nd_flag & ND_NFSV41) != 0 && confirmp->lval[1] != 0) {
			/*
			 * For NFSv4.1, if confirmp->lval[1] is non-zero, the
			 * client is trying to update a confirmed clientid.
			 */
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
			confirmp->lval[1] = 0;
			error = NFSERR_NOENT;
			goto out;
		}
		/*
		 * Get rid of the old one.
		 */
		if (i != nfsrv_clienthashsize) {
			LIST_REMOVE(clp, lc_hash);
			nfsrv_cleanclient(clp, p);
			nfsrv_freedeleglist(&clp->lc_deleg);
			nfsrv_freedeleglist(&clp->lc_olddeleg);
			zapit = 1;
		}
		/*
		 * Add it after assigning a client id to it.
		 */
		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
		if ((nd->nd_flag & ND_NFSV41) != 0)
			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
			    ++confirm_index;
		else
			confirmp->qval = new_clp->lc_confirm.qval =
			    ++confirm_index;
		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
		    (u_int32_t)nfsrvboottime;
		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
		    nfsrv_nextclientindex();
		new_clp->lc_stateindex = 0;
		new_clp->lc_statemaxindex = 0;
		new_clp->lc_cbref = 0;
		new_clp->lc_expiry = nfsrv_leaseexpiry();
		LIST_INIT(&new_clp->lc_open);
		LIST_INIT(&new_clp->lc_deleg);
		LIST_INIT(&new_clp->lc_olddeleg);
		LIST_INIT(&new_clp->lc_session);
		for (i = 0; i < nfsrv_statehashsize; i++)
			LIST_INIT(&new_clp->lc_stateid[i]);
		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
		    lc_hash);
		nfsstatsv1.srvclients++;
		nfsrv_openpluslock++;
		nfsrv_clients++;
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
		if (zapit)
			nfsrv_zapclient(clp, p);
		*new_clpp = NULL;
		goto out;
	}

	/*
	 * Now, handle the cases where the id is already issued.
	 */
	if (nfsrv_notsamecredname(nd, clp)) {
	    /*
	     * Check to see if there is expired state that should go away.
	     */
	    if (clp->lc_expiry < NFSD_MONOSEC &&
	        (!LIST_EMPTY(&clp->lc_open) || !LIST_EMPTY(&clp->lc_deleg))) {
		nfsrv_cleanclient(clp, p);
		nfsrv_freedeleglist(&clp->lc_deleg);
	    }

	    /*
	     * If there is outstanding state, then reply NFSERR_CLIDINUSE per
	     * RFC3530 Sec. 8.1.2 last para.
	     */
	    if (!LIST_EMPTY(&clp->lc_deleg)) {
		hasstate = 1;
	    } else if (LIST_EMPTY(&clp->lc_open)) {
		hasstate = 0;
	    } else {
		hasstate = 0;
		/* Look for an Open on the OpenOwner */
		LIST_FOREACH(stp, &clp->lc_open, ls_list) {
		    if (!LIST_EMPTY(&stp->ls_open)) {
			hasstate = 1;
			break;
		    }
		}
	    }
	    if (hasstate) {
		/*
		 * If the uid doesn't match, return NFSERR_CLIDINUSE after
		 * filling out the correct ipaddr and portnum.
		 */
		sad = NFSSOCKADDR(new_clp->lc_req.nr_nam, struct sockaddr_in *);
		rad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr_in *);
		sad->sin_addr.s_addr = rad->sin_addr.s_addr;
		sad->sin_port = rad->sin_port;
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
		error = NFSERR_CLIDINUSE;
		goto out;
	    }
	}

	if (NFSBCMP(new_clp->lc_verf, clp->lc_verf, NFSX_VERF)) {
		/*
		 * If the verifier has changed, the client has rebooted
		 * and a new client id is issued. The old state info
		 * can be thrown away once the SETCLIENTID_CONFIRM occurs.
		 */
		LIST_REMOVE(clp, lc_hash);
		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
		if ((nd->nd_flag & ND_NFSV41) != 0)
			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
			    ++confirm_index;
		else
			confirmp->qval = new_clp->lc_confirm.qval =
			    ++confirm_index;
		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
		    nfsrvboottime;
		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
		    nfsrv_nextclientindex();
		new_clp->lc_stateindex = 0;
		new_clp->lc_statemaxindex = 0;
		new_clp->lc_cbref = 0;
		new_clp->lc_expiry = nfsrv_leaseexpiry();

		/*
		 * Save the state until confirmed.
		 */
		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
			tstp->ls_clp = new_clp;
		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
			tstp->ls_clp = new_clp;
		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg,
		    ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
			tstp->ls_clp = new_clp;
		for (i = 0; i < nfsrv_statehashsize; i++) {
			LIST_NEWHEAD(&new_clp->lc_stateid[i],
			    &clp->lc_stateid[i], ls_hash);
			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
				tstp->ls_clp = new_clp;
		}
		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
		    lc_hash);
		nfsstatsv1.srvclients++;
		nfsrv_openpluslock++;
		nfsrv_clients++;
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();

		/*
		 * Must wait until any outstanding callback on the old clp
		 * completes.
		 */
		NFSLOCKSTATE();
		while (clp->lc_cbref) {
			clp->lc_flags |= LCL_WAKEUPWANTED;
			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
			    "nfsd clp", 10 * hz);
		}
		NFSUNLOCKSTATE();
		nfsrv_zapclient(clp, p);
		*new_clpp = NULL;
		goto out;
	}

	/* For NFSv4.1, mark that we found a confirmed clientid. */
	if ((nd->nd_flag & ND_NFSV41) != 0) {
		clientidp->lval[0] = clp->lc_clientid.lval[0];
		clientidp->lval[1] = clp->lc_clientid.lval[1];
		confirmp->lval[0] = 0;	/* Ignored by client */
		confirmp->lval[1] = 1;
	} else {
		/*
		 * id and verifier match, so update the net address info
		 * and get rid of any existing callback authentication
		 * handle, so a new one will be acquired.
		 */
		LIST_REMOVE(clp, lc_hash);
		new_clp->lc_flags |= (LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
		new_clp->lc_expiry = nfsrv_leaseexpiry();
		confirmp->qval = new_clp->lc_confirm.qval = ++confirm_index;
		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
		    clp->lc_clientid.lval[0];
		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
		    clp->lc_clientid.lval[1];
		new_clp->lc_delegtime = clp->lc_delegtime;
		new_clp->lc_stateindex = clp->lc_stateindex;
		new_clp->lc_statemaxindex = clp->lc_statemaxindex;
		new_clp->lc_cbref = 0;
		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
			tstp->ls_clp = new_clp;
		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
			tstp->ls_clp = new_clp;
		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg, ls_list);
		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
			tstp->ls_clp = new_clp;
		for (i = 0; i < nfsrv_statehashsize; i++) {
			LIST_NEWHEAD(&new_clp->lc_stateid[i],
			    &clp->lc_stateid[i], ls_hash);
			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
				tstp->ls_clp = new_clp;
		}
		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
		    lc_hash);
		nfsstatsv1.srvclients++;
		nfsrv_openpluslock++;
		nfsrv_clients++;
	}
	NFSLOCKV4ROOTMUTEX();
	nfsv4_unlock(&nfsv4rootfs_lock, 1);
	NFSUNLOCKV4ROOTMUTEX();

	if ((nd->nd_flag & ND_NFSV41) == 0) {
		/*
		 * Must wait until any outstanding callback on the old clp
		 * completes.
		 */
		NFSLOCKSTATE();
		while (clp->lc_cbref) {
			clp->lc_flags |= LCL_WAKEUPWANTED;
			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
			    "nfsdclp", 10 * hz);
		}
		NFSUNLOCKSTATE();
		nfsrv_zapclient(clp, p);
		*new_clpp = NULL;
	}

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Check to see if the client id exists and optionally confirm it.
 */
APPLESTATIC int
nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
    struct nfsdsession *nsep, nfsquad_t confirm, uint32_t cbprogram,
    struct nfsrv_descript *nd, NFSPROC_T *p)
{
	struct nfsclient *clp;
	struct nfsstate *stp;
	int i;
	struct nfsclienthashhead *hp;
	int error = 0, igotlock, doneok;
	struct nfssessionhash *shp;
	struct nfsdsession *sep;
	uint64_t sessid[2];
	static uint64_t next_sess = 0;

	if (clpp)
		*clpp = NULL;
	if ((nd == NULL || (nd->nd_flag & ND_NFSV41) == 0 ||
	    opflags != CLOPS_RENEW) && nfsrvboottime != clientid.lval[0]) {
		error = NFSERR_STALECLIENTID;
		goto out;
	}

	/*
	 * If called with opflags == CLOPS_RENEW, the State Lock is
	 * already held. Otherwise, we need to get either that or,
	 * for the case of Confirm, lock out the nfsd threads.
	 */
	if (opflags & CLOPS_CONFIRM) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_relref(&nfsv4rootfs_lock);
		do {
			igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
			    NFSV4ROOTLOCKMUTEXPTR, NULL);
		} while (!igotlock);
		/*
		 * Create a new sessionid here, since we need to do it where
		 * there is a mutex held to serialize update of next_sess.
		 */
		if ((nd->nd_flag & ND_NFSV41) != 0) {
			sessid[0] = ++next_sess;
			sessid[1] = clientid.qval;
		}
		NFSUNLOCKV4ROOTMUTEX();
	} else if (opflags != CLOPS_RENEW) {
		NFSLOCKSTATE();
	}

	/* For NFSv4.1, the clp is acquired from the associated session. */
	if (nd != NULL && (nd->nd_flag & ND_NFSV41) != 0 &&
	    opflags == CLOPS_RENEW) {
		clp = NULL;
		if ((nd->nd_flag & ND_HASSEQUENCE) != 0) {
			shp = NFSSESSIONHASH(nd->nd_sessionid);
			NFSLOCKSESSION(shp);
			sep = nfsrv_findsession(nd->nd_sessionid);
			if (sep != NULL)
				clp = sep->sess_clp;
			NFSUNLOCKSESSION(shp);
		}
	} else {
		hp = NFSCLIENTHASH(clientid);
		LIST_FOREACH(clp, hp, lc_hash) {
			if (clp->lc_clientid.lval[1] == clientid.lval[1])
				break;
		}
	}
	if (clp == NULL) {
		if (opflags & CLOPS_CONFIRM)
			error = NFSERR_STALECLIENTID;
		else
			error = NFSERR_EXPIRED;
	} else if (clp->lc_flags & LCL_ADMINREVOKED) {
		/*
		 * If marked admin revoked, just return the error.
		 */
		error = NFSERR_ADMINREVOKED;
	}
	if (error) {
		if (opflags & CLOPS_CONFIRM) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		} else if (opflags != CLOPS_RENEW) {
			NFSUNLOCKSTATE();
		}
		goto out;
	}

	/*
	 * Perform any operations specified by the opflags.
	 */
	if (opflags & CLOPS_CONFIRM) {
		if (((nd->nd_flag & ND_NFSV41) != 0 &&
		     clp->lc_confirm.lval[0] != confirm.lval[0]) ||
		    ((nd->nd_flag & ND_NFSV41) == 0 &&
		     clp->lc_confirm.qval != confirm.qval))
			error = NFSERR_STALECLIENTID;
		else if (nfsrv_notsamecredname(nd, clp))
			error = NFSERR_CLIDINUSE;

		if (!error) {
		    if ((clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_DONTCLEAN)) ==
			LCL_NEEDSCONFIRM) {
			/*
			 * Hang onto the delegations (as old delegations)
			 * for an Open with CLAIM_DELEGATE_PREV unless in
			 * grace, but get rid of the rest of the state.
			 */
			nfsrv_cleanclient(clp, p);
			nfsrv_freedeleglist(&clp->lc_olddeleg);
			if (nfsrv_checkgrace(nd, clp, 0)) {
			    /* In grace, so just delete delegations */
			    nfsrv_freedeleglist(&clp->lc_deleg);
			} else {
			    LIST_FOREACH(stp, &clp->lc_deleg, ls_list)
				stp->ls_flags |= NFSLCK_OLDDELEG;
			    clp->lc_delegtime = NFSD_MONOSEC +
				nfsrv_lease + NFSRV_LEASEDELTA;
			    LIST_NEWHEAD(&clp->lc_olddeleg, &clp->lc_deleg,
				ls_list);
			}
			if ((nd->nd_flag & ND_NFSV41) != 0)
			    clp->lc_program = cbprogram;
		    }
		    clp->lc_flags &= ~(LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
		    if (clp->lc_program)
			clp->lc_flags |= LCL_NEEDSCBNULL;
		    /* For NFSv4.1, link the session onto the client. */
		    if (nsep != NULL) {
			/* Hold a reference on the xprt for a backchannel. */
			if ((nsep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN)
			    != 0 && clp->lc_req.nr_client == NULL) {
			    clp->lc_req.nr_client = (struct __rpc_client *)
				clnt_bck_create(nd->nd_xprt->xp_socket,
				cbprogram, NFSV4_CBVERS);
			    if (clp->lc_req.nr_client != NULL) {
				SVC_ACQUIRE(nd->nd_xprt);
				nd->nd_xprt->xp_p2 =
				    clp->lc_req.nr_client->cl_private;
				/* Disable idle timeout. */
				nd->nd_xprt->xp_idletimeout = 0;
				nsep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
			    } else
				nsep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
			}
			NFSBCOPY(sessid, nsep->sess_sessionid,
			    NFSX_V4SESSIONID);
			NFSBCOPY(sessid, nsep->sess_cbsess.nfsess_sessionid,
			    NFSX_V4SESSIONID);
			shp = NFSSESSIONHASH(nsep->sess_sessionid);
			NFSLOCKSTATE();
			NFSLOCKSESSION(shp);
			LIST_INSERT_HEAD(&shp->list, nsep, sess_hash);
			LIST_INSERT_HEAD(&clp->lc_session, nsep, sess_list);
			nsep->sess_clp = clp;
			NFSUNLOCKSESSION(shp);
			NFSUNLOCKSTATE();
		    }
		}
	} else if (clp->lc_flags & LCL_NEEDSCONFIRM) {
		error = NFSERR_EXPIRED;
	}

	/*
	 * If called by the Renew Op, we must check the principal.
	 */
	if (!error && (opflags & CLOPS_RENEWOP)) {
	    if (nfsrv_notsamecredname(nd, clp)) {
		doneok = 0;
		for (i = 0; i < nfsrv_statehashsize && doneok == 0; i++) {
		    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
			if ((stp->ls_flags & NFSLCK_OPEN) &&
			    stp->ls_uid == nd->nd_cred->cr_uid) {
				doneok = 1;
				break;
			}
		    }
		}
		if (!doneok)
			error = NFSERR_ACCES;
	    }
	    if (!error && (clp->lc_flags & LCL_CBDOWN))
		error = NFSERR_CBPATHDOWN;
	}
	if ((!error || error == NFSERR_CBPATHDOWN) &&
	     (opflags & CLOPS_RENEW)) {
		clp->lc_expiry = nfsrv_leaseexpiry();
	}
	if (opflags & CLOPS_CONFIRM) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
	} else if (opflags != CLOPS_RENEW) {
		NFSUNLOCKSTATE();
	}
	if (clpp)
		*clpp = clp;

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Perform the NFSv4.1 destroy clientid.
 */
int
nfsrv_destroyclient(nfsquad_t clientid, NFSPROC_T *p)
{
	struct nfsclient *clp;
	struct nfsclienthashhead *hp;
	int error = 0, i, igotlock;

	if (nfsrvboottime != clientid.lval[0]) {
		error = NFSERR_STALECLIENTID;
		goto out;
	}

	/* Lock out other nfsd threads */
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	do {
		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
		    NFSV4ROOTLOCKMUTEXPTR, NULL);
	} while (igotlock == 0);
	NFSUNLOCKV4ROOTMUTEX();

	hp = NFSCLIENTHASH(clientid);
	LIST_FOREACH(clp, hp, lc_hash) {
		if (clp->lc_clientid.lval[1] == clientid.lval[1])
			break;
	}
	if (clp == NULL) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
		/* Just return ok, since it is gone. */
		goto out;
	}

	/* Scan for state on the clientid. */
	for (i = 0; i < nfsrv_statehashsize; i++)
		if (!LIST_EMPTY(&clp->lc_stateid[i])) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
			error = NFSERR_CLIENTIDBUSY;
			goto out;
		}
	if (!LIST_EMPTY(&clp->lc_session) || !LIST_EMPTY(&clp->lc_deleg)) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
		error = NFSERR_CLIENTIDBUSY;
		goto out;
	}

	/* Destroy the clientid and return ok. */
	nfsrv_cleanclient(clp, p);
	nfsrv_freedeleglist(&clp->lc_deleg);
	nfsrv_freedeleglist(&clp->lc_olddeleg);
	LIST_REMOVE(clp, lc_hash);
	NFSLOCKV4ROOTMUTEX();
	nfsv4_unlock(&nfsv4rootfs_lock, 1);
	NFSUNLOCKV4ROOTMUTEX();
	nfsrv_zapclient(clp, p);
out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Called from the new nfssvc syscall to admin revoke a clientid.
 * Returns 0 for success, error otherwise.
 */
APPLESTATIC int
nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
{
	struct nfsclient *clp = NULL;
	int i, error = 0;
	int gotit, igotlock;

	/*
	 * First, lock out the nfsd so that state won't change while the
	 * revocation record is being written to the stable storage restart
	 * file.
	 */
	NFSLOCKV4ROOTMUTEX();
	do {
		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
		    NFSV4ROOTLOCKMUTEXPTR, NULL);
	} while (!igotlock);
	NFSUNLOCKV4ROOTMUTEX();

	/*
	 * Search for a match in the client list.
	 */
	gotit = i = 0;
	while (i < nfsrv_clienthashsize && !gotit) {
	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
		if (revokep->nclid_idlen == clp->lc_idlen &&
		    !NFSBCMP(revokep->nclid_id, clp->lc_id, clp->lc_idlen)) {
			gotit = 1;
			break;
		}
	    }
	    i++;
	}
	if (!gotit) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 0);
		NFSUNLOCKV4ROOTMUTEX();
		error = EPERM;
		goto out;
	}

	/*
	 * Now, write out the revocation record
	 */
	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
	nfsrv_backupstable();

	/*
	 * and clear out the state, marking the clientid revoked.
	 */
	clp->lc_flags &= ~LCL_CALLBACKSON;
	clp->lc_flags |= LCL_ADMINREVOKED;
	nfsrv_cleanclient(clp, p);
	nfsrv_freedeleglist(&clp->lc_deleg);
	nfsrv_freedeleglist(&clp->lc_olddeleg);
	NFSLOCKV4ROOTMUTEX();
	nfsv4_unlock(&nfsv4rootfs_lock, 0);
	NFSUNLOCKV4ROOTMUTEX();

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Dump out stats for all clients. Called from nfssvc(2), that is used
 * nfsstatsv1.
 */
APPLESTATIC void
nfsrv_dumpclients(struct nfsd_dumpclients *dumpp, int maxcnt)
{
	struct nfsclient *clp;
	int i = 0, cnt = 0;

	/*
	 * First, get a reference on the nfsv4rootfs_lock so that an
	 * exclusive lock cannot be acquired while dumping the clients.
	 */
	NFSLOCKV4ROOTMUTEX();
	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
	NFSUNLOCKV4ROOTMUTEX();
	NFSLOCKSTATE();
	/*
	 * Rattle through the client lists until done.
	 */
	while (i < nfsrv_clienthashsize && cnt < maxcnt) {
	    clp = LIST_FIRST(&nfsclienthash[i]);
	    while (clp != NULL && cnt < maxcnt) {
		nfsrv_dumpaclient(clp, &dumpp[cnt]);
		cnt++;
		clp = LIST_NEXT(clp, lc_hash);
	    }
	    i++;
	}
	if (cnt < maxcnt)
	    dumpp[cnt].ndcl_clid.nclid_idlen = 0;
	NFSUNLOCKSTATE();
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	NFSUNLOCKV4ROOTMUTEX();
}

/*
 * Dump stats for a client. Must be called with the NFSSTATELOCK and spl'd.
 */
static void
nfsrv_dumpaclient(struct nfsclient *clp, struct nfsd_dumpclients *dumpp)
{
	struct nfsstate *stp, *openstp, *lckownstp;
	struct nfslock *lop;
	struct sockaddr *sad;
	struct sockaddr_in *rad;
	struct sockaddr_in6 *rad6;

	dumpp->ndcl_nopenowners = dumpp->ndcl_nlockowners = 0;
	dumpp->ndcl_nopens = dumpp->ndcl_nlocks = 0;
	dumpp->ndcl_ndelegs = dumpp->ndcl_nolddelegs = 0;
	dumpp->ndcl_flags = clp->lc_flags;
	dumpp->ndcl_clid.nclid_idlen = clp->lc_idlen;
	NFSBCOPY(clp->lc_id, dumpp->ndcl_clid.nclid_id, clp->lc_idlen);
	sad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr *);
	dumpp->ndcl_addrfam = sad->sa_family;
	if (sad->sa_family == AF_INET) {
		rad = (struct sockaddr_in *)sad;
		dumpp->ndcl_cbaddr.sin_addr = rad->sin_addr;
	} else {
		rad6 = (struct sockaddr_in6 *)sad;
		dumpp->ndcl_cbaddr.sin6_addr = rad6->sin6_addr;
	}

	/*
	 * Now, scan the state lists and total up the opens and locks.
	 */
	LIST_FOREACH(stp, &clp->lc_open, ls_list) {
	    dumpp->ndcl_nopenowners++;
	    LIST_FOREACH(openstp, &stp->ls_open, ls_list) {
		dumpp->ndcl_nopens++;
		LIST_FOREACH(lckownstp, &openstp->ls_open, ls_list) {
		    dumpp->ndcl_nlockowners++;
		    LIST_FOREACH(lop, &lckownstp->ls_lock, lo_lckowner) {
			dumpp->ndcl_nlocks++;
		    }
		}
	    }
	}

	/*
	 * and the delegation lists.
	 */
	LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
	    dumpp->ndcl_ndelegs++;
	}
	LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
	    dumpp->ndcl_nolddelegs++;
	}
}

/*
 * Dump out lock stats for a file.
 */
APPLESTATIC void
nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
    NFSPROC_T *p)
{
	struct nfsstate *stp;
	struct nfslock *lop;
	int cnt = 0;
	struct nfslockfile *lfp;
	struct sockaddr *sad;
	struct sockaddr_in *rad;
	struct sockaddr_in6 *rad6;
	int ret;
	fhandle_t nfh;

	ret = nfsrv_getlockfh(vp, 0, NULL, &nfh, p);
	/*
	 * First, get a reference on the nfsv4rootfs_lock so that an
	 * exclusive lock on it cannot be acquired while dumping the locks.
	 */
	NFSLOCKV4ROOTMUTEX();
	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
	NFSUNLOCKV4ROOTMUTEX();
	NFSLOCKSTATE();
	if (!ret)
		ret = nfsrv_getlockfile(0, NULL, &lfp, &nfh, 0);
	if (ret) {
		ldumpp[0].ndlck_clid.nclid_idlen = 0;
		NFSUNLOCKSTATE();
		NFSLOCKV4ROOTMUTEX();
		nfsv4_relref(&nfsv4rootfs_lock);
		NFSUNLOCKV4ROOTMUTEX();
		return;
	}

	/*
	 * For each open share on file, dump it out.
	 */
	stp = LIST_FIRST(&lfp->lf_open);
	while (stp != NULL && cnt < maxcnt) {
		ldumpp[cnt].ndlck_flags = stp->ls_flags;
		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
		ldumpp[cnt].ndlck_owner.nclid_idlen =
		    stp->ls_openowner->ls_ownerlen;
		NFSBCOPY(stp->ls_openowner->ls_owner,
		    ldumpp[cnt].ndlck_owner.nclid_id,
		    stp->ls_openowner->ls_ownerlen);
		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
		    stp->ls_clp->lc_idlen);
		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
		if (sad->sa_family == AF_INET) {
			rad = (struct sockaddr_in *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
		} else {
			rad6 = (struct sockaddr_in6 *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
		}
		stp = LIST_NEXT(stp, ls_file);
		cnt++;
	}

	/*
	 * and all locks.
	 */
	lop = LIST_FIRST(&lfp->lf_lock);
	while (lop != NULL && cnt < maxcnt) {
		stp = lop->lo_stp;
		ldumpp[cnt].ndlck_flags = lop->lo_flags;
		ldumpp[cnt].ndlck_first = lop->lo_first;
		ldumpp[cnt].ndlck_end = lop->lo_end;
		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
		ldumpp[cnt].ndlck_owner.nclid_idlen = stp->ls_ownerlen;
		NFSBCOPY(stp->ls_owner, ldumpp[cnt].ndlck_owner.nclid_id,
		    stp->ls_ownerlen);
		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
		    stp->ls_clp->lc_idlen);
		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
		if (sad->sa_family == AF_INET) {
			rad = (struct sockaddr_in *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
		} else {
			rad6 = (struct sockaddr_in6 *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
		}
		lop = LIST_NEXT(lop, lo_lckfile);
		cnt++;
	}

	/*
	 * and the delegations.
	 */
	stp = LIST_FIRST(&lfp->lf_deleg);
	while (stp != NULL && cnt < maxcnt) {
		ldumpp[cnt].ndlck_flags = stp->ls_flags;
		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
		ldumpp[cnt].ndlck_owner.nclid_idlen = 0;
		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
		    stp->ls_clp->lc_idlen);
		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
		if (sad->sa_family == AF_INET) {
			rad = (struct sockaddr_in *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
		} else {
			rad6 = (struct sockaddr_in6 *)sad;
			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
		}
		stp = LIST_NEXT(stp, ls_file);
		cnt++;
	}

	/*
	 * If list isn't full, mark end of list by setting the client name
	 * to zero length.
	 */
	if (cnt < maxcnt)
		ldumpp[cnt].ndlck_clid.nclid_idlen = 0;
	NFSUNLOCKSTATE();
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	NFSUNLOCKV4ROOTMUTEX();
}

/*
 * Server timer routine. It can scan any linked list, so long
 * as it holds the spin/mutex lock and there is no exclusive lock on
 * nfsv4rootfs_lock.
 * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
 *  to do this from a callout, since the spin locks work. For
 *  Darwin, I'm not sure what will work correctly yet.)
 * Should be called once per second.
 */
APPLESTATIC void
nfsrv_servertimer(void)
{
	struct nfsclient *clp, *nclp;
	struct nfsstate *stp, *nstp;
	int got_ref, i;

	/*
	 * Make sure nfsboottime is set. This is used by V3 as well
	 * as V4. Note that nfsboottime is not nfsrvboottime, which is
	 * only used by the V4 server for leases.
	 */
	if (nfsboottime.tv_sec == 0)
		NFSSETBOOTTIME(nfsboottime);

	/*
	 * If server hasn't started yet, just return.
	 */
	NFSLOCKSTATE();
	if (nfsrv_stablefirst.nsf_eograce == 0) {
		NFSUNLOCKSTATE();
		return;
	}
	if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE)) {
		if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) &&
		    NFSD_MONOSEC > nfsrv_stablefirst.nsf_eograce)
			nfsrv_stablefirst.nsf_flags |=
			    (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
		NFSUNLOCKSTATE();
		return;
	}

	/*
	 * Try and get a reference count on the nfsv4rootfs_lock so that
	 * no nfsd thread can acquire an exclusive lock on it before this
	 * call is done. If it is already exclusively locked, just return.
	 */
	NFSLOCKV4ROOTMUTEX();
	got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
	NFSUNLOCKV4ROOTMUTEX();
	if (got_ref == 0) {
		NFSUNLOCKSTATE();
		return;
	}

	/*
	 * For each client...
	 */
	for (i = 0; i < nfsrv_clienthashsize; i++) {
	    clp = LIST_FIRST(&nfsclienthash[i]);
	    while (clp != NULL) {
		nclp = LIST_NEXT(clp, lc_hash);
		if (!(clp->lc_flags & LCL_EXPIREIT)) {
		    if (((clp->lc_expiry + NFSRV_STALELEASE) < NFSD_MONOSEC
			 && ((LIST_EMPTY(&clp->lc_deleg)
			      && LIST_EMPTY(&clp->lc_open)) ||
			     nfsrv_clients > nfsrv_clienthighwater)) ||
			(clp->lc_expiry + NFSRV_MOULDYLEASE) < NFSD_MONOSEC ||
			(clp->lc_expiry < NFSD_MONOSEC &&
			 (nfsrv_openpluslock * 10 / 9) > nfsrv_v4statelimit)) {
			/*
			 * Lease has expired several nfsrv_lease times ago:
			 * PLUS
			 *    - no state is associated with it
			 *    OR
			 *    - above high water mark for number of clients
			 *      (nfsrv_clienthighwater should be large enough
			 *       that this only occurs when clients fail to
			 *       use the same nfs_client_id4.id. Maybe somewhat
			 *       higher that the maximum number of clients that
			 *       will mount this server?)
			 * OR
			 * Lease has expired a very long time ago
			 * OR
			 * Lease has expired PLUS the number of opens + locks
			 * has exceeded 90% of capacity
			 *
			 * --> Mark for expiry. The actual expiry will be done
			 *     by an nfsd sometime soon.
			 */
			clp->lc_flags |= LCL_EXPIREIT;
			nfsrv_stablefirst.nsf_flags |=
			    (NFSNSF_NEEDLOCK | NFSNSF_EXPIREDCLIENT);
		    } else {
			/*
			 * If there are no opens, increment no open tick cnt
			 * If time exceeds NFSNOOPEN, mark it to be thrown away
			 * otherwise, if there is an open, reset no open time
			 * Hopefully, this will avoid excessive re-creation
			 * of open owners and subsequent open confirms.
			 */
			stp = LIST_FIRST(&clp->lc_open);
			while (stp != NULL) {
				nstp = LIST_NEXT(stp, ls_list);
				if (LIST_EMPTY(&stp->ls_open)) {
					stp->ls_noopens++;
					if (stp->ls_noopens > NFSNOOPEN ||
					    (nfsrv_openpluslock * 2) >
					    nfsrv_v4statelimit)
						nfsrv_stablefirst.nsf_flags |=
							NFSNSF_NOOPENS;
				} else {
					stp->ls_noopens = 0;
				}
				stp = nstp;
			}
		    }
		}
		clp = nclp;
	    }
	}
	NFSUNLOCKSTATE();
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	NFSUNLOCKV4ROOTMUTEX();
}

/*
 * The following set of functions free up the various data structures.
 */
/*
 * Clear out all open/lock state related to this nfsclient.
 * Caller must hold an exclusive lock on nfsv4rootfs_lock, so that
 * there are no other active nfsd threads.
 */
APPLESTATIC void
nfsrv_cleanclient(struct nfsclient *clp, NFSPROC_T *p)
{
	struct nfsstate *stp, *nstp;
	struct nfsdsession *sep, *nsep;

	LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp)
		nfsrv_freeopenowner(stp, 1, p);
	if ((clp->lc_flags & LCL_ADMINREVOKED) == 0)
		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep)
			(void)nfsrv_freesession(sep, NULL);
}

/*
 * Free a client that has been cleaned. It should also already have been
 * removed from the lists.
 * (Just to be safe w.r.t. newnfs_disconnect(), call this function when
 *  softclock interrupts are enabled.)
 */
APPLESTATIC void
nfsrv_zapclient(struct nfsclient *clp, NFSPROC_T *p)
{

#ifdef notyet
	if ((clp->lc_flags & (LCL_GSS | LCL_CALLBACKSON)) ==
	     (LCL_GSS | LCL_CALLBACKSON) &&
	    (clp->lc_hand.nfsh_flag & NFSG_COMPLETE) &&
	    clp->lc_handlelen > 0) {
		clp->lc_hand.nfsh_flag &= ~NFSG_COMPLETE;
		clp->lc_hand.nfsh_flag |= NFSG_DESTROYED;
		(void) nfsrv_docallback(clp, NFSV4PROC_CBNULL,
			NULL, 0, NULL, NULL, NULL, p);
	}
#endif
	newnfs_disconnect(&clp->lc_req);
	NFSSOCKADDRFREE(clp->lc_req.nr_nam);
	NFSFREEMUTEX(&clp->lc_req.nr_mtx);
	free(clp->lc_stateid, M_NFSDCLIENT);
	free(clp, M_NFSDCLIENT);
	NFSLOCKSTATE();
	nfsstatsv1.srvclients--;
	nfsrv_openpluslock--;
	nfsrv_clients--;
	NFSUNLOCKSTATE();
}

/*
 * Free a list of delegation state structures.
 * (This function will also free all nfslockfile structures that no
 *  longer have associated state.)
 */
APPLESTATIC void
nfsrv_freedeleglist(struct nfsstatehead *sthp)
{
	struct nfsstate *stp, *nstp;

	LIST_FOREACH_SAFE(stp, sthp, ls_list, nstp) {
		nfsrv_freedeleg(stp);
	}
	LIST_INIT(sthp);
}

/*
 * Free up a delegation.
 */
static void
nfsrv_freedeleg(struct nfsstate *stp)
{
	struct nfslockfile *lfp;

	LIST_REMOVE(stp, ls_hash);
	LIST_REMOVE(stp, ls_list);
	LIST_REMOVE(stp, ls_file);
	lfp = stp->ls_lfp;
	if (LIST_EMPTY(&lfp->lf_open) &&
	    LIST_EMPTY(&lfp->lf_lock) && LIST_EMPTY(&lfp->lf_deleg) &&
	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
	    lfp->lf_usecount == 0 &&
	    nfsv4_testlock(&lfp->lf_locallock_lck) == 0)
		nfsrv_freenfslockfile(lfp);
	FREE((caddr_t)stp, M_NFSDSTATE);
	nfsstatsv1.srvdelegates--;
	nfsrv_openpluslock--;
	nfsrv_delegatecnt--;
}

/*
 * This function frees an open owner and all associated opens.
 */
static void
nfsrv_freeopenowner(struct nfsstate *stp, int cansleep, NFSPROC_T *p)
{
	struct nfsstate *nstp, *tstp;

	LIST_REMOVE(stp, ls_list);
	/*
	 * Now, free all associated opens.
	 */
	nstp = LIST_FIRST(&stp->ls_open);
	while (nstp != NULL) {
		tstp = nstp;
		nstp = LIST_NEXT(nstp, ls_list);
		(void) nfsrv_freeopen(tstp, NULL, cansleep, p);
	}
	if (stp->ls_op)
		nfsrvd_derefcache(stp->ls_op);
	FREE((caddr_t)stp, M_NFSDSTATE);
	nfsstatsv1.srvopenowners--;
	nfsrv_openpluslock--;
}

/*
 * This function frees an open (nfsstate open structure) with all associated
 * lock_owners and locks. It also frees the nfslockfile structure iff there
 * are no other opens on the file.
 * Returns 1 if it free'd the nfslockfile, 0 otherwise.
 */
static int
nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
{
	struct nfsstate *nstp, *tstp;
	struct nfslockfile *lfp;
	int ret;

	LIST_REMOVE(stp, ls_hash);
	LIST_REMOVE(stp, ls_list);
	LIST_REMOVE(stp, ls_file);

	lfp = stp->ls_lfp;
	/*
	 * Now, free all lockowners associated with this open.
	 */
	LIST_FOREACH_SAFE(tstp, &stp->ls_open, ls_list, nstp)
		nfsrv_freelockowner(tstp, vp, cansleep, p);

	/*
	 * The nfslockfile is freed here if there are no locks
	 * associated with the open.
	 * If there are locks associated with the open, the
	 * nfslockfile structure can be freed via nfsrv_freelockowner().
	 * Acquire the state mutex to avoid races with calls to
	 * nfsrv_getlockfile().
	 */
	if (cansleep != 0)
		NFSLOCKSTATE();
	if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
	    LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
	    lfp->lf_usecount == 0 &&
	    (cansleep != 0 || nfsv4_testlock(&lfp->lf_locallock_lck) == 0)) {
		nfsrv_freenfslockfile(lfp);
		ret = 1;
	} else
		ret = 0;
	if (cansleep != 0)
		NFSUNLOCKSTATE();
	FREE((caddr_t)stp, M_NFSDSTATE);
	nfsstatsv1.srvopens--;
	nfsrv_openpluslock--;
	return (ret);
}

/*
 * Frees a lockowner and all associated locks.
 */
static void
nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
    NFSPROC_T *p)
{

	LIST_REMOVE(stp, ls_hash);
	LIST_REMOVE(stp, ls_list);
	nfsrv_freeallnfslocks(stp, vp, cansleep, p);
	if (stp->ls_op)
		nfsrvd_derefcache(stp->ls_op);
	FREE((caddr_t)stp, M_NFSDSTATE);
	nfsstatsv1.srvlockowners--;
	nfsrv_openpluslock--;
}

/*
 * Free all the nfs locks on a lockowner.
 */
static void
nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp, int cansleep,
    NFSPROC_T *p)
{
	struct nfslock *lop, *nlop;
	struct nfsrollback *rlp, *nrlp;
	struct nfslockfile *lfp = NULL;
	int gottvp = 0;
	vnode_t tvp = NULL;
	uint64_t first, end;

	if (vp != NULL)
		ASSERT_VOP_UNLOCKED(vp, "nfsrv_freeallnfslocks: vnode locked");
	lop = LIST_FIRST(&stp->ls_lock);
	while (lop != NULL) {
		nlop = LIST_NEXT(lop, lo_lckowner);
		/*
		 * Since all locks should be for the same file, lfp should
		 * not change.
		 */
		if (lfp == NULL)
			lfp = lop->lo_lfp;
		else if (lfp != lop->lo_lfp)
			panic("allnfslocks");
		/*
		 * If vp is NULL and cansleep != 0, a vnode must be acquired
		 * from the file handle. This only occurs when called from
		 * nfsrv_cleanclient().
		 */
		if (gottvp == 0) {
			if (nfsrv_dolocallocks == 0)
				tvp = NULL;
			else if (vp == NULL && cansleep != 0) {
				tvp = nfsvno_getvp(&lfp->lf_fh);
				NFSVOPUNLOCK(tvp, 0);
			} else
				tvp = vp;
			gottvp = 1;
		}

		if (tvp != NULL) {
			if (cansleep == 0)
				panic("allnfs2");
			first = lop->lo_first;
			end = lop->lo_end;
			nfsrv_freenfslock(lop);
			nfsrv_localunlock(tvp, lfp, first, end, p);
			LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list,
			    nrlp)
				free(rlp, M_NFSDROLLBACK);
			LIST_INIT(&lfp->lf_rollback);
		} else
			nfsrv_freenfslock(lop);
		lop = nlop;
	}
	if (vp == NULL && tvp != NULL)
		vrele(tvp);
}

/*
 * Free an nfslock structure.
 */
static void
nfsrv_freenfslock(struct nfslock *lop)
{

	if (lop->lo_lckfile.le_prev != NULL) {
		LIST_REMOVE(lop, lo_lckfile);
		nfsstatsv1.srvlocks--;
		nfsrv_openpluslock--;
	}
	LIST_REMOVE(lop, lo_lckowner);
	FREE((caddr_t)lop, M_NFSDLOCK);
}

/*
 * This function frees an nfslockfile structure.
 */
static void
nfsrv_freenfslockfile(struct nfslockfile *lfp)
{

	LIST_REMOVE(lfp, lf_hash);
	FREE((caddr_t)lfp, M_NFSDLOCKFILE);
}

/*
 * This function looks up an nfsstate structure via stateid.
 */
static int
nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, __unused u_int32_t flags,
    struct nfsstate **stpp)
{
	struct nfsstate *stp;
	struct nfsstatehead *hp;
	int error = 0;

	*stpp = NULL;
	hp = NFSSTATEHASH(clp, *stateidp);
	LIST_FOREACH(stp, hp, ls_hash) {
		if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
			NFSX_STATEIDOTHER))
			break;
	}

	/*
	 * If no state id in list, return NFSERR_BADSTATEID.
	 */
	if (stp == NULL) {
		error = NFSERR_BADSTATEID;
		goto out;
	}
	*stpp = stp;

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * This function gets an nfsstate structure via owner string.
 */
static void
nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
    struct nfsstate **stpp)
{
	struct nfsstate *stp;

	*stpp = NULL;
	LIST_FOREACH(stp, hp, ls_list) {
		if (new_stp->ls_ownerlen == stp->ls_ownerlen &&
		  !NFSBCMP(new_stp->ls_owner,stp->ls_owner,stp->ls_ownerlen)) {
			*stpp = stp;
			return;
		}
	}
}

/*
 * Lock control function called to update lock status.
 * Returns 0 upon success, -1 if there is no lock and the flags indicate
 * that one isn't to be created and an NFSERR_xxx for other errors.
 * The structures new_stp and new_lop are passed in as pointers that should
 * be set to NULL if the structure is used and shouldn't be free'd.
 * For the NFSLCK_TEST and NFSLCK_CHECK cases, the structures are
 * never used and can safely be allocated on the stack. For all other
 * cases, *new_stpp and *new_lopp should be malloc'd before the call,
 * in case they are used.
 */
APPLESTATIC int
nfsrv_lockctrl(vnode_t vp, struct nfsstate **new_stpp,
    struct nfslock **new_lopp, struct nfslockconflict *cfp,
    nfsquad_t clientid, nfsv4stateid_t *stateidp,
    __unused struct nfsexstuff *exp,
    struct nfsrv_descript *nd, NFSPROC_T *p)
{
	struct nfslock *lop;
	struct nfsstate *new_stp = *new_stpp;
	struct nfslock *new_lop = *new_lopp;
	struct nfsstate *tstp, *mystp, *nstp;
	int specialid = 0;
	struct nfslockfile *lfp;
	struct nfslock *other_lop = NULL;
	struct nfsstate *stp, *lckstp = NULL;
	struct nfsclient *clp = NULL;
	u_int32_t bits;
	int error = 0, haslock = 0, ret, reterr;
	int getlckret, delegation = 0, filestruct_locked, vnode_unlocked = 0;
	fhandle_t nfh;
	uint64_t first, end;
	uint32_t lock_flags;

	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_SETATTR)) {
		/*
		 * Note the special cases of "all 1s" or "all 0s" stateids and
		 * let reads with all 1s go ahead.
		 */
		if (new_stp->ls_stateid.seqid == 0x0 &&
		    new_stp->ls_stateid.other[0] == 0x0 &&
		    new_stp->ls_stateid.other[1] == 0x0 &&
		    new_stp->ls_stateid.other[2] == 0x0)
			specialid = 1;
		else if (new_stp->ls_stateid.seqid == 0xffffffff &&
		    new_stp->ls_stateid.other[0] == 0xffffffff &&
		    new_stp->ls_stateid.other[1] == 0xffffffff &&
		    new_stp->ls_stateid.other[2] == 0xffffffff)
			specialid = 2;
	}

	/*
	 * Check for restart conditions (client and server).
	 */
	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
	    &new_stp->ls_stateid, specialid);
	if (error)
		goto out;

	/*
	 * Check for state resource limit exceeded.
	 */
	if ((new_stp->ls_flags & NFSLCK_LOCK) &&
	    nfsrv_openpluslock > nfsrv_v4statelimit) {
		error = NFSERR_RESOURCE;
		goto out;
	}

	/*
	 * For the lock case, get another nfslock structure,
	 * just in case we need it.
	 * Malloc now, before we start sifting through the linked lists,
	 * in case we have to wait for memory.
	 */
tryagain:
	if (new_stp->ls_flags & NFSLCK_LOCK)
		MALLOC(other_lop, struct nfslock *, sizeof (struct nfslock),
		    M_NFSDLOCK, M_WAITOK);
	filestruct_locked = 0;
	reterr = 0;
	lfp = NULL;

	/*
	 * Get the lockfile structure for CFH now, so we can do a sanity
	 * check against the stateid, before incrementing the seqid#, since
	 * we want to return NFSERR_BADSTATEID on failure and the seqid#
	 * shouldn't be incremented for this case.
	 * If nfsrv_getlockfile() returns -1, it means "not found", which
	 * will be handled later.
	 * If we are doing Lock/LockU and local locking is enabled, sleep
	 * lock the nfslockfile structure.
	 */
	getlckret = nfsrv_getlockfh(vp, new_stp->ls_flags, NULL, &nfh, p);
	NFSLOCKSTATE();
	if (getlckret == 0) {
		if ((new_stp->ls_flags & (NFSLCK_LOCK | NFSLCK_UNLOCK)) != 0 &&
		    nfsrv_dolocallocks != 0 && nd->nd_repstat == 0) {
			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
			    &lfp, &nfh, 1);
			if (getlckret == 0)
				filestruct_locked = 1;
		} else
			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
			    &lfp, &nfh, 0);
	}
	if (getlckret != 0 && getlckret != -1)
		reterr = getlckret;

	if (filestruct_locked != 0) {
		LIST_INIT(&lfp->lf_rollback);
		if ((new_stp->ls_flags & NFSLCK_LOCK)) {
			/*
			 * For local locking, do the advisory locking now, so
			 * that any conflict can be detected. A failure later
			 * can be rolled back locally. If an error is returned,
			 * struct nfslockfile has been unlocked and any local
			 * locking rolled back.
			 */
			NFSUNLOCKSTATE();
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl1");
				vnode_unlocked = 1;
				NFSVOPUNLOCK(vp, 0);
			}
			reterr = nfsrv_locallock(vp, lfp,
			    (new_lop->lo_flags & (NFSLCK_READ | NFSLCK_WRITE)),
			    new_lop->lo_first, new_lop->lo_end, cfp, p);
			NFSLOCKSTATE();
		}
	}

	if (specialid == 0) {
	    if (new_stp->ls_flags & NFSLCK_TEST) {
		/*
		 * RFC 3530 does not list LockT as an op that renews a
		 * lease, but the consensus seems to be that it is ok
		 * for a server to do so.
		 */
		error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
		    (nfsquad_t)((u_quad_t)0), 0, nd, p);

		/*
		 * Since NFSERR_EXPIRED, NFSERR_ADMINREVOKED are not valid
		 * error returns for LockT, just go ahead and test for a lock,
		 * since there are no locks for this client, but other locks
		 * can conflict. (ie. same client will always be false)
		 */
		if (error == NFSERR_EXPIRED || error == NFSERR_ADMINREVOKED)
		    error = 0;
		lckstp = new_stp;
	    } else {
	      error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
		(nfsquad_t)((u_quad_t)0), 0, nd, p);
	      if (error == 0)
		/*
		 * Look up the stateid
		 */
		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
		  new_stp->ls_flags, &stp);
	      /*
	       * do some sanity checks for an unconfirmed open or a
	       * stateid that refers to the wrong file, for an open stateid
	       */
	      if (error == 0 && (stp->ls_flags & NFSLCK_OPEN) &&
		  ((stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM) ||
		   (getlckret == 0 && stp->ls_lfp != lfp))){
		      /*
		       * NFSLCK_SETATTR should return OK rather than NFSERR_BADSTATEID
		       * The only exception is using SETATTR with SIZE.
		       * */
                    if ((new_stp->ls_flags &
                         (NFSLCK_SETATTR | NFSLCK_CHECK)) != NFSLCK_SETATTR)
			     error = NFSERR_BADSTATEID;
	      }
	      
		if (error == 0 &&
		  (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) &&
		  getlckret == 0 && stp->ls_lfp != lfp)
			error = NFSERR_BADSTATEID;

	      /*
	       * If the lockowner stateid doesn't refer to the same file,
	       * I believe that is considered ok, since some clients will
	       * only create a single lockowner and use that for all locks
	       * on all files.
	       * For now, log it as a diagnostic, instead of considering it
	       * a BadStateid.
	       */
	      if (error == 0 && (stp->ls_flags &
		  (NFSLCK_OPEN | NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) == 0 &&
		  getlckret == 0 && stp->ls_lfp != lfp) {
#ifdef DIAGNOSTIC
		  printf("Got a lock statid for different file open\n");
#endif
		  /*
		  error = NFSERR_BADSTATEID;
		  */
	      }

	      if (error == 0) {
		    if (new_stp->ls_flags & NFSLCK_OPENTOLOCK) {
			/*
			 * If haslock set, we've already checked the seqid.
			 */
			if (!haslock) {
			    if (stp->ls_flags & NFSLCK_OPEN)
				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
				    stp->ls_openowner, new_stp->ls_op);
			    else
				error = NFSERR_BADSTATEID;
			}
			if (!error)
			    nfsrv_getowner(&stp->ls_open, new_stp, &lckstp);
			if (lckstp)
			    /*
			     * I believe this should be an error, but it
			     * isn't obvious what NFSERR_xxx would be
			     * appropriate, so I'll use NFSERR_INVAL for now.
			     */
			    error = NFSERR_INVAL;
			else
			    lckstp = new_stp;
		    } else if (new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK)) {
			/*
			 * If haslock set, ditto above.
			 */
			if (!haslock) {
			    if (stp->ls_flags & NFSLCK_OPEN)
				error = NFSERR_BADSTATEID;
			    else
				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
				    stp, new_stp->ls_op);
			}
			lckstp = stp;
		    } else {
			lckstp = stp;
		    }
	      }
	      /*
	       * If the seqid part of the stateid isn't the same, return
	       * NFSERR_OLDSTATEID for cases other than I/O Ops.
	       * For I/O Ops, only return NFSERR_OLDSTATEID if
	       * nfsrv_returnoldstateid is set. (The consensus on the email
	       * list was that most clients would prefer to not receive
	       * NFSERR_OLDSTATEID for I/O Ops, but the RFC suggests that that
	       * is what will happen, so I use the nfsrv_returnoldstateid to
	       * allow for either server configuration.)
	       */
	      if (!error && stp->ls_stateid.seqid!=new_stp->ls_stateid.seqid &&
		  (((nd->nd_flag & ND_NFSV41) == 0 &&
		   (!(new_stp->ls_flags & NFSLCK_CHECK) ||
		    nfsrv_returnoldstateid)) ||
		   ((nd->nd_flag & ND_NFSV41) != 0 &&
		    new_stp->ls_stateid.seqid != 0)))
		    error = NFSERR_OLDSTATEID;
	    }
	}

	/*
	 * Now we can check for grace.
	 */
	if (!error)
		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
		nfsrv_checkstable(clp))
		error = NFSERR_NOGRACE;
	/*
	 * If we successfully Reclaimed state, note that.
	 */
	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error)
		nfsrv_markstable(clp);

	/*
	 * At this point, either error == NFSERR_BADSTATEID or the
	 * seqid# has been updated, so we can return any error.
	 * If error == 0, there may be an error in:
	 *    nd_repstat - Set by the calling function.
	 *    reterr - Set above, if getting the nfslockfile structure
	 *       or acquiring the local lock failed.
	 *    (If both of these are set, nd_repstat should probably be
	 *     returned, since that error was detected before this
	 *     function call.)
	 */
	if (error != 0 || nd->nd_repstat != 0 || reterr != 0) {
		if (error == 0) {
			if (nd->nd_repstat != 0)
				error = nd->nd_repstat;
			else
				error = reterr;
		}
		if (filestruct_locked != 0) {
			/* Roll back local locks. */
			NFSUNLOCKSTATE();
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl2");
				vnode_unlocked = 1;
				NFSVOPUNLOCK(vp, 0);
			}
			nfsrv_locallock_rollback(vp, lfp, p);
			NFSLOCKSTATE();
			nfsrv_unlocklf(lfp);
		}
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * Check the nfsrv_getlockfile return.
	 * Returned -1 if no structure found.
	 */
	if (getlckret == -1) {
		error = NFSERR_EXPIRED;
		/*
		 * Called from lockt, so no lock is OK.
		 */
		if (new_stp->ls_flags & NFSLCK_TEST) {
			error = 0;
		} else if (new_stp->ls_flags &
		    (NFSLCK_CHECK | NFSLCK_SETATTR)) {
			/*
			 * Called to check for a lock, OK if the stateid is all
			 * 1s or all 0s, but there should be an nfsstate
			 * otherwise.
			 * (ie. If there is no open, I'll assume no share
			 *  deny bits.)
			 */
			if (specialid)
				error = 0;
			else
				error = NFSERR_BADSTATEID;
		}
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * For NFSLCK_CHECK and NFSLCK_LOCK, test for a share conflict.
	 * For NFSLCK_CHECK, allow a read if write access is granted,
	 * but check for a deny. For NFSLCK_LOCK, require correct access,
	 * which implies a conflicting deny can't exist.
	 */
	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_LOCK)) {
	    /*
	     * Four kinds of state id:
	     * - specialid (all 0s or all 1s), only for NFSLCK_CHECK
	     * - stateid for an open
	     * - stateid for a delegation
	     * - stateid for a lock owner
	     */
	    if (!specialid) {
		if (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
		    delegation = 1;
		    mystp = stp;
		    nfsrv_delaydelegtimeout(stp);
	        } else if (stp->ls_flags & NFSLCK_OPEN) {
		    mystp = stp;
		} else {
		    mystp = stp->ls_openstp;
		}
		/*
		 * If locking or checking, require correct access
		 * bit set.
		 */
		if (((new_stp->ls_flags & NFSLCK_LOCK) &&
		     !((new_lop->lo_flags >> NFSLCK_LOCKSHIFT) &
		       mystp->ls_flags & NFSLCK_ACCESSBITS)) ||
		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_READACCESS)) ==
		      (NFSLCK_CHECK | NFSLCK_READACCESS) &&
		     !(mystp->ls_flags & NFSLCK_READACCESS)) ||
		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_WRITEACCESS)) ==
		      (NFSLCK_CHECK | NFSLCK_WRITEACCESS) &&
		     !(mystp->ls_flags & NFSLCK_WRITEACCESS))) {
			if (filestruct_locked != 0) {
				/* Roll back local locks. */
				NFSUNLOCKSTATE();
				if (vnode_unlocked == 0) {
					ASSERT_VOP_ELOCKED(vp,
					    "nfsrv_lockctrl3");
					vnode_unlocked = 1;
					NFSVOPUNLOCK(vp, 0);
				}
				nfsrv_locallock_rollback(vp, lfp, p);
				NFSLOCKSTATE();
				nfsrv_unlocklf(lfp);
			}
			NFSUNLOCKSTATE();
			error = NFSERR_OPENMODE;
			goto out;
		}
	    } else
		mystp = NULL;
	    if ((new_stp->ls_flags & NFSLCK_CHECK) && !delegation) {
		/*
		 * Check for a conflicting deny bit.
		 */
		LIST_FOREACH(tstp, &lfp->lf_open, ls_file) {
		    if (tstp != mystp) {
			bits = tstp->ls_flags;
			bits >>= NFSLCK_SHIFT;
			if (new_stp->ls_flags & bits & NFSLCK_ACCESSBITS) {
			    KASSERT(vnode_unlocked == 0,
				("nfsrv_lockctrl: vnode unlocked1"));
			    ret = nfsrv_clientconflict(tstp->ls_clp, &haslock,
				vp, p);
			    if (ret == 1) {
				/*
				* nfsrv_clientconflict unlocks state
				 * when it returns non-zero.
				 */
				lckstp = NULL;
				goto tryagain;
			    }
			    if (ret == 0)
				NFSUNLOCKSTATE();
			    if (ret == 2)
				error = NFSERR_PERM;
			    else
				error = NFSERR_OPENMODE;
			    goto out;
			}
		    }
		}

		/* We're outta here */
		NFSUNLOCKSTATE();
		goto out;
	    }
	}

	/*
	 * For setattr, just get rid of all the Delegations for other clients.
	 */
	if (new_stp->ls_flags & NFSLCK_SETATTR) {
		KASSERT(vnode_unlocked == 0,
		    ("nfsrv_lockctrl: vnode unlocked2"));
		ret = nfsrv_cleandeleg(vp, lfp, clp, &haslock, p);
		if (ret) {
			/*
			 * nfsrv_cleandeleg() unlocks state when it
			 * returns non-zero.
			 */
			if (ret == -1) {
				lckstp = NULL;
				goto tryagain;
			}
			error = ret;
			goto out;
		}
		if (!(new_stp->ls_flags & NFSLCK_CHECK) ||
		    (LIST_EMPTY(&lfp->lf_open) && LIST_EMPTY(&lfp->lf_lock) &&
		     LIST_EMPTY(&lfp->lf_deleg))) {
			NFSUNLOCKSTATE();
			goto out;
		}
	}

	/*
	 * Check for a conflicting delegation. If one is found, call
	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
	 * been set yet, it will get the lock. Otherwise, it will recall
	 * the delegation. Then, we try try again...
	 * I currently believe the conflict algorithm to be:
	 * For Lock Ops (Lock/LockT/LockU)
	 * - there is a conflict iff a different client has a write delegation
	 * For Reading (Read Op)
	 * - there is a conflict iff a different client has a write delegation
	 *   (the specialids are always a different client)
	 * For Writing (Write/Setattr of size)
	 * - there is a conflict if a different client has any delegation
	 * - there is a conflict if the same client has a read delegation
	 *   (I don't understand why this isn't allowed, but that seems to be
	 *    the current consensus?)
	 */
	tstp = LIST_FIRST(&lfp->lf_deleg);
	while (tstp != NULL) {
	    nstp = LIST_NEXT(tstp, ls_file);
	    if ((((new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK|NFSLCK_TEST))||
		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
		  (new_lop->lo_flags & NFSLCK_READ))) &&
		  clp != tstp->ls_clp &&
		 (tstp->ls_flags & NFSLCK_DELEGWRITE)) ||
		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
		   (new_lop->lo_flags & NFSLCK_WRITE) &&
		  (clp != tstp->ls_clp ||
		   (tstp->ls_flags & NFSLCK_DELEGREAD)))) {
		ret = 0;
		if (filestruct_locked != 0) {
			/* Roll back local locks. */
			NFSUNLOCKSTATE();
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl4");
				NFSVOPUNLOCK(vp, 0);
			}
			nfsrv_locallock_rollback(vp, lfp, p);
			NFSLOCKSTATE();
			nfsrv_unlocklf(lfp);
			NFSUNLOCKSTATE();
			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
			vnode_unlocked = 0;
			if ((vp->v_iflag & VI_DOOMED) != 0)
				ret = NFSERR_SERVERFAULT;
			NFSLOCKSTATE();
		}
		if (ret == 0)
			ret = nfsrv_delegconflict(tstp, &haslock, p, vp);
		if (ret) {
		    /*
		     * nfsrv_delegconflict unlocks state when it
		     * returns non-zero, which it always does.
		     */
		    if (other_lop) {
			FREE((caddr_t)other_lop, M_NFSDLOCK);
			other_lop = NULL;
		    }
		    if (ret == -1) {
			lckstp = NULL;
			goto tryagain;
		    }
		    error = ret;
		    goto out;
		}
		/* Never gets here. */
	    }
	    tstp = nstp;
	}

	/*
	 * Handle the unlock case by calling nfsrv_updatelock().
	 * (Should I have done some access checking above for unlock? For now,
	 *  just let it happen.)
	 */
	if (new_stp->ls_flags & NFSLCK_UNLOCK) {
		first = new_lop->lo_first;
		end = new_lop->lo_end;
		nfsrv_updatelock(stp, new_lopp, &other_lop, lfp);
		stateidp->seqid = ++(stp->ls_stateid.seqid);
		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
			stateidp->seqid = stp->ls_stateid.seqid = 1;
		stateidp->other[0] = stp->ls_stateid.other[0];
		stateidp->other[1] = stp->ls_stateid.other[1];
		stateidp->other[2] = stp->ls_stateid.other[2];
		if (filestruct_locked != 0) {
			NFSUNLOCKSTATE();
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl5");
				vnode_unlocked = 1;
				NFSVOPUNLOCK(vp, 0);
			}
			/* Update the local locks. */
			nfsrv_localunlock(vp, lfp, first, end, p);
			NFSLOCKSTATE();
			nfsrv_unlocklf(lfp);
		}
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * Search for a conflicting lock. A lock conflicts if:
	 * - the lock range overlaps and
	 * - at least one lock is a write lock and
	 * - it is not owned by the same lock owner
	 */
	if (!delegation) {
	  LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
	    if (new_lop->lo_end > lop->lo_first &&
		new_lop->lo_first < lop->lo_end &&
		(new_lop->lo_flags == NFSLCK_WRITE ||
		 lop->lo_flags == NFSLCK_WRITE) &&
		lckstp != lop->lo_stp &&
		(clp != lop->lo_stp->ls_clp ||
		 lckstp->ls_ownerlen != lop->lo_stp->ls_ownerlen ||
		 NFSBCMP(lckstp->ls_owner, lop->lo_stp->ls_owner,
		    lckstp->ls_ownerlen))) {
		if (other_lop) {
		    FREE((caddr_t)other_lop, M_NFSDLOCK);
		    other_lop = NULL;
		}
		if (vnode_unlocked != 0)
		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
			NULL, p);
		else
		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
			vp, p);
		if (ret == 1) {
		    if (filestruct_locked != 0) {
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl6");
				NFSVOPUNLOCK(vp, 0);
			}
			/* Roll back local locks. */
			nfsrv_locallock_rollback(vp, lfp, p);
			NFSLOCKSTATE();
			nfsrv_unlocklf(lfp);
			NFSUNLOCKSTATE();
			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
			vnode_unlocked = 0;
			if ((vp->v_iflag & VI_DOOMED) != 0) {
				error = NFSERR_SERVERFAULT;
				goto out;
			}
		    }
		    /*
		     * nfsrv_clientconflict() unlocks state when it
		     * returns non-zero.
		     */
		    lckstp = NULL;
		    goto tryagain;
		}
		/*
		 * Found a conflicting lock, so record the conflict and
		 * return the error.
		 */
		if (cfp != NULL && ret == 0) {
		    cfp->cl_clientid.lval[0]=lop->lo_stp->ls_stateid.other[0];
		    cfp->cl_clientid.lval[1]=lop->lo_stp->ls_stateid.other[1];
		    cfp->cl_first = lop->lo_first;
		    cfp->cl_end = lop->lo_end;
		    cfp->cl_flags = lop->lo_flags;
		    cfp->cl_ownerlen = lop->lo_stp->ls_ownerlen;
		    NFSBCOPY(lop->lo_stp->ls_owner, cfp->cl_owner,
			cfp->cl_ownerlen);
		}
		if (ret == 2)
		    error = NFSERR_PERM;
		else if (new_stp->ls_flags & NFSLCK_RECLAIM)
		    error = NFSERR_RECLAIMCONFLICT;
		else if (new_stp->ls_flags & NFSLCK_CHECK)
		    error = NFSERR_LOCKED;
		else
		    error = NFSERR_DENIED;
		if (filestruct_locked != 0 && ret == 0) {
			/* Roll back local locks. */
			NFSUNLOCKSTATE();
			if (vnode_unlocked == 0) {
				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl7");
				vnode_unlocked = 1;
				NFSVOPUNLOCK(vp, 0);
			}
			nfsrv_locallock_rollback(vp, lfp, p);
			NFSLOCKSTATE();
			nfsrv_unlocklf(lfp);
		}
		if (ret == 0)
			NFSUNLOCKSTATE();
		goto out;
	    }
	  }
	}

	/*
	 * We only get here if there was no lock that conflicted.
	 */
	if (new_stp->ls_flags & (NFSLCK_TEST | NFSLCK_CHECK)) {
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * We only get here when we are creating or modifying a lock.
	 * There are two variants:
	 * - exist_lock_owner where lock_owner exists
	 * - open_to_lock_owner with new lock_owner
	 */
	first = new_lop->lo_first;
	end = new_lop->lo_end;
	lock_flags = new_lop->lo_flags;
	if (!(new_stp->ls_flags & NFSLCK_OPENTOLOCK)) {
		nfsrv_updatelock(lckstp, new_lopp, &other_lop, lfp);
		stateidp->seqid = ++(lckstp->ls_stateid.seqid);
		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
			stateidp->seqid = lckstp->ls_stateid.seqid = 1;
		stateidp->other[0] = lckstp->ls_stateid.other[0];
		stateidp->other[1] = lckstp->ls_stateid.other[1];
		stateidp->other[2] = lckstp->ls_stateid.other[2];
	} else {
		/*
		 * The new open_to_lock_owner case.
		 * Link the new nfsstate into the lists.
		 */
		new_stp->ls_seq = new_stp->ls_opentolockseq;
		nfsrvd_refcache(new_stp->ls_op);
		stateidp->seqid = new_stp->ls_stateid.seqid = 1;
		stateidp->other[0] = new_stp->ls_stateid.other[0] =
		    clp->lc_clientid.lval[0];
		stateidp->other[1] = new_stp->ls_stateid.other[1] =
		    clp->lc_clientid.lval[1];
		stateidp->other[2] = new_stp->ls_stateid.other[2] =
		    nfsrv_nextstateindex(clp);
		new_stp->ls_clp = clp;
		LIST_INIT(&new_stp->ls_lock);
		new_stp->ls_openstp = stp;
		new_stp->ls_lfp = lfp;
		nfsrv_insertlock(new_lop, (struct nfslock *)new_stp, new_stp,
		    lfp);
		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_stp->ls_stateid),
		    new_stp, ls_hash);
		LIST_INSERT_HEAD(&stp->ls_open, new_stp, ls_list);
		*new_lopp = NULL;
		*new_stpp = NULL;
		nfsstatsv1.srvlockowners++;
		nfsrv_openpluslock++;
	}
	if (filestruct_locked != 0) {
		NFSUNLOCKSTATE();
		nfsrv_locallock_commit(lfp, lock_flags, first, end);
		NFSLOCKSTATE();
		nfsrv_unlocklf(lfp);
	}
	NFSUNLOCKSTATE();

out:
	if (haslock) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
	}
	if (vnode_unlocked != 0) {
		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
		if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
			error = NFSERR_SERVERFAULT;
	}
	if (other_lop)
		FREE((caddr_t)other_lop, M_NFSDLOCK);
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Check for state errors for Open.
 * repstat is passed back out as an error if more critical errors
 * are not detected.
 */
APPLESTATIC int
nfsrv_opencheck(nfsquad_t clientid, nfsv4stateid_t *stateidp,
    struct nfsstate *new_stp, vnode_t vp, struct nfsrv_descript *nd,
    NFSPROC_T *p, int repstat)
{
	struct nfsstate *stp, *nstp;
	struct nfsclient *clp;
	struct nfsstate *ownerstp;
	struct nfslockfile *lfp, *new_lfp;
	int error = 0, haslock = 0, ret, readonly = 0, getfhret = 0;

	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
		readonly = 1;
	/*
	 * Check for restart conditions (client and server).
	 */
	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
		&new_stp->ls_stateid, 0);
	if (error)
		goto out;

	/*
	 * Check for state resource limit exceeded.
	 * Technically this should be SMP protected, but the worst
	 * case error is "out by one or two" on the count when it
	 * returns NFSERR_RESOURCE and the limit is just a rather
	 * arbitrary high water mark, so no harm is done.
	 */
	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
		error = NFSERR_RESOURCE;
		goto out;
	}

tryagain:
	MALLOC(new_lfp, struct nfslockfile *, sizeof (struct nfslockfile),
	    M_NFSDLOCKFILE, M_WAITOK);
	if (vp)
		getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
		    NULL, p);
	NFSLOCKSTATE();
	/*
	 * Get the nfsclient structure.
	 */
	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
	    (nfsquad_t)((u_quad_t)0), 0, nd, p);

	/*
	 * Look up the open owner. See if it needs confirmation and
	 * check the seq#, as required.
	 */
	if (!error)
		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);

	if (!error && ownerstp) {
		error = nfsrv_checkseqid(nd, new_stp->ls_seq, ownerstp,
		    new_stp->ls_op);
		/*
		 * If the OpenOwner hasn't been confirmed, assume the
		 * old one was a replay and this one is ok.
		 * See: RFC3530 Sec. 14.2.18.
		 */
		if (error == NFSERR_BADSEQID &&
		    (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM))
			error = 0;
	}

	/*
	 * Check for grace.
	 */
	if (!error)
		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
		nfsrv_checkstable(clp))
		error = NFSERR_NOGRACE;

	/*
	 * If none of the above errors occurred, let repstat be
	 * returned.
	 */
	if (repstat && !error)
		error = repstat;
	if (error) {
		NFSUNLOCKSTATE();
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		free((caddr_t)new_lfp, M_NFSDLOCKFILE);
		goto out;
	}

	/*
	 * If vp == NULL, the file doesn't exist yet, so return ok.
	 * (This always happens on the first pass, so haslock must be 0.)
	 */
	if (vp == NULL) {
		NFSUNLOCKSTATE();
		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
		goto out;
	}

	/*
	 * Get the structure for the underlying file.
	 */
	if (getfhret)
		error = getfhret;
	else
		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
		    NULL, 0);
	if (new_lfp)
		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
	if (error) {
		NFSUNLOCKSTATE();
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		goto out;
	}

	/*
	 * Search for a conflicting open/share.
	 */
	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
	    /*
	     * For Delegate_Cur, search for the matching Delegation,
	     * which indicates no conflict.
	     * An old delegation should have been recovered by the
	     * client doing a Claim_DELEGATE_Prev, so I won't let
	     * it match and return NFSERR_EXPIRED. Should I let it
	     * match?
	     */
	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
		    (((nd->nd_flag & ND_NFSV41) != 0 &&
		    stateidp->seqid == 0) ||
		    stateidp->seqid == stp->ls_stateid.seqid) &&
		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
			  NFSX_STATEIDOTHER))
			break;
	    }
	    if (stp == NULL ||
		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
		NFSUNLOCKSTATE();
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		error = NFSERR_EXPIRED;
		goto out;
	    }
	}

	/*
	 * Check for access/deny bit conflicts. I check for the same
	 * owner as well, in case the client didn't bother.
	 */
	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR) &&
		    (((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
		      ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
		     ((stp->ls_flags & NFSLCK_ACCESSBITS) &
		      ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS)))){
			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
			if (ret == 1) {
				/*
				 * nfsrv_clientconflict() unlocks
				 * state when it returns non-zero.
				 */
				goto tryagain;
			}
			if (ret == 2)
				error = NFSERR_PERM;
			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
				error = NFSERR_RECLAIMCONFLICT;
			else
				error = NFSERR_SHAREDENIED;
			if (ret == 0)
				NFSUNLOCKSTATE();
			if (haslock) {
				NFSLOCKV4ROOTMUTEX();
				nfsv4_unlock(&nfsv4rootfs_lock, 1);
				NFSUNLOCKV4ROOTMUTEX();
			}
			goto out;
		}
	}

	/*
	 * Check for a conflicting delegation. If one is found, call
	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
	 * been set yet, it will get the lock. Otherwise, it will recall
	 * the delegation. Then, we try try again...
	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
	 *  isn't a conflict.)
	 * I currently believe the conflict algorithm to be:
	 * For Open with Read Access and Deny None
	 * - there is a conflict iff a different client has a write delegation
	 * For Open with other Write Access or any Deny except None
	 * - there is a conflict if a different client has any delegation
	 * - there is a conflict if the same client has a read delegation
	 *   (The current consensus is that this last case should be
	 *    considered a conflict since the client with a read delegation
	 *    could have done an Open with ReadAccess and WriteDeny
	 *    locally and then not have checked for the WriteDeny.)
	 * Don't check for a Reclaim, since that will be dealt with
	 * by nfsrv_openctrl().
	 */
	if (!(new_stp->ls_flags &
		(NFSLCK_DELEGPREV | NFSLCK_DELEGCUR | NFSLCK_RECLAIM))) {
	    stp = LIST_FIRST(&lfp->lf_deleg);
	    while (stp != NULL) {
		nstp = LIST_NEXT(stp, ls_file);
		if ((readonly && stp->ls_clp != clp &&
		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
		    (!readonly && (stp->ls_clp != clp ||
		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
			if (ret) {
			    /*
			     * nfsrv_delegconflict() unlocks state
			     * when it returns non-zero.
			     */
			    if (ret == -1)
				goto tryagain;
			    error = ret;
			    goto out;
			}
		}
		stp = nstp;
	    }
	}
	NFSUNLOCKSTATE();
	if (haslock) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
	}

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Open control function to create/update open state for an open.
 */
APPLESTATIC int
nfsrv_openctrl(struct nfsrv_descript *nd, vnode_t vp,
    struct nfsstate **new_stpp, nfsquad_t clientid, nfsv4stateid_t *stateidp,
    nfsv4stateid_t *delegstateidp, u_int32_t *rflagsp, struct nfsexstuff *exp,
    NFSPROC_T *p, u_quad_t filerev)
{
	struct nfsstate *new_stp = *new_stpp;
	struct nfsstate *stp, *nstp;
	struct nfsstate *openstp = NULL, *new_open, *ownerstp, *new_deleg;
	struct nfslockfile *lfp, *new_lfp;
	struct nfsclient *clp;
	int error = 0, haslock = 0, ret, delegate = 1, writedeleg = 1;
	int readonly = 0, cbret = 1, getfhret = 0;

	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
		readonly = 1;
	/*
	 * Check for restart conditions (client and server).
	 * (Paranoia, should have been detected by nfsrv_opencheck().)
	 * If an error does show up, return NFSERR_EXPIRED, since the
	 * the seqid# has already been incremented.
	 */
	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
	    &new_stp->ls_stateid, 0);
	if (error) {
		printf("Nfsd: openctrl unexpected restart err=%d\n",
		    error);
		error = NFSERR_EXPIRED;
		goto out;
	}

tryagain:
	MALLOC(new_lfp, struct nfslockfile *, sizeof (struct nfslockfile),
	    M_NFSDLOCKFILE, M_WAITOK);
	MALLOC(new_open, struct nfsstate *, sizeof (struct nfsstate),
	    M_NFSDSTATE, M_WAITOK);
	MALLOC(new_deleg, struct nfsstate *, sizeof (struct nfsstate),
	    M_NFSDSTATE, M_WAITOK);
	getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
	    NULL, p);
	NFSLOCKSTATE();
	/*
	 * Get the client structure. Since the linked lists could be changed
	 * by other nfsd processes if this process does a tsleep(), one of
	 * two things must be done.
	 * 1 - don't tsleep()
	 * or
	 * 2 - get the nfsv4_lock() { indicated by haslock == 1 }
	 *     before using the lists, since this lock stops the other
	 *     nfsd. This should only be used for rare cases, since it
	 *     essentially single threads the nfsd.
	 *     At this time, it is only done for cases where the stable
	 *     storage file must be written prior to completion of state
	 *     expiration.
	 */
	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
	if (!error && (clp->lc_flags & LCL_NEEDSCBNULL) &&
	    clp->lc_program) {
		/*
		 * This happens on the first open for a client
		 * that supports callbacks.
		 */
		NFSUNLOCKSTATE();
		/*
		 * Although nfsrv_docallback() will sleep, clp won't
		 * go away, since they are only removed when the
		 * nfsv4_lock() has blocked the nfsd threads. The
		 * fields in clp can change, but having multiple
		 * threads do this Null callback RPC should be
		 * harmless.
		 */
		cbret = nfsrv_docallback(clp, NFSV4PROC_CBNULL,
		    NULL, 0, NULL, NULL, NULL, p);
		NFSLOCKSTATE();
		clp->lc_flags &= ~LCL_NEEDSCBNULL;
		if (!cbret)
			clp->lc_flags |= LCL_CALLBACKSON;
	}

	/*
	 * Look up the open owner. See if it needs confirmation and
	 * check the seq#, as required.
	 */
	if (!error)
		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);

	if (error) {
		NFSUNLOCKSTATE();
		printf("Nfsd: openctrl unexpected state err=%d\n",
			error);
		free((caddr_t)new_lfp, M_NFSDLOCKFILE);
		free((caddr_t)new_open, M_NFSDSTATE);
		free((caddr_t)new_deleg, M_NFSDSTATE);
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		error = NFSERR_EXPIRED;
		goto out;
	}

	if (new_stp->ls_flags & NFSLCK_RECLAIM)
		nfsrv_markstable(clp);

	/*
	 * Get the structure for the underlying file.
	 */
	if (getfhret)
		error = getfhret;
	else
		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
		    NULL, 0);
	if (new_lfp)
		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
	if (error) {
		NFSUNLOCKSTATE();
		printf("Nfsd openctrl unexpected getlockfile err=%d\n",
		    error);
		free((caddr_t)new_open, M_NFSDSTATE);
		free((caddr_t)new_deleg, M_NFSDSTATE);
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		goto out;
	}

	/*
	 * Search for a conflicting open/share.
	 */
	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
	    /*
	     * For Delegate_Cur, search for the matching Delegation,
	     * which indicates no conflict.
	     * An old delegation should have been recovered by the
	     * client doing a Claim_DELEGATE_Prev, so I won't let
	     * it match and return NFSERR_EXPIRED. Should I let it
	     * match?
	     */
	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
		    (((nd->nd_flag & ND_NFSV41) != 0 &&
		    stateidp->seqid == 0) ||
		    stateidp->seqid == stp->ls_stateid.seqid) &&
		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
			NFSX_STATEIDOTHER))
			break;
	    }
	    if (stp == NULL ||
		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
		NFSUNLOCKSTATE();
		printf("Nfsd openctrl unexpected expiry\n");
		free((caddr_t)new_open, M_NFSDSTATE);
		free((caddr_t)new_deleg, M_NFSDSTATE);
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		error = NFSERR_EXPIRED;
		goto out;
	    }

	    /*
	     * Don't issue a Delegation, since one already exists and
	     * delay delegation timeout, as required.
	     */
	    delegate = 0;
	    nfsrv_delaydelegtimeout(stp);
	}

	/*
	 * Check for access/deny bit conflicts. I also check for the
	 * same owner, since the client might not have bothered to check.
	 * Also, note an open for the same file and owner, if found,
	 * which is all we do here for Delegate_Cur, since conflict
	 * checking is already done.
	 */
	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
		if (ownerstp && stp->ls_openowner == ownerstp)
			openstp = stp;
		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR)) {
		    /*
		     * If another client has the file open, the only
		     * delegation that can be issued is a Read delegation
		     * and only if it is a Read open with Deny none.
		     */
		    if (clp != stp->ls_clp) {
			if ((stp->ls_flags & NFSLCK_SHAREBITS) ==
			    NFSLCK_READACCESS)
			    writedeleg = 0;
			else
			    delegate = 0;
		    }
		    if(((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
		        ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
		       ((stp->ls_flags & NFSLCK_ACCESSBITS) &
		        ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS))){
			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
			if (ret == 1) {
				/*
				 * nfsrv_clientconflict() unlocks state
				 * when it returns non-zero.
				 */
				free((caddr_t)new_open, M_NFSDSTATE);
				free((caddr_t)new_deleg, M_NFSDSTATE);
				openstp = NULL;
				goto tryagain;
			}
			if (ret == 2)
				error = NFSERR_PERM;
			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
				error = NFSERR_RECLAIMCONFLICT;
			else
				error = NFSERR_SHAREDENIED;
			if (ret == 0)
				NFSUNLOCKSTATE();
			if (haslock) {
				NFSLOCKV4ROOTMUTEX();
				nfsv4_unlock(&nfsv4rootfs_lock, 1);
				NFSUNLOCKV4ROOTMUTEX();
			}
			free((caddr_t)new_open, M_NFSDSTATE);
			free((caddr_t)new_deleg, M_NFSDSTATE);
			printf("nfsd openctrl unexpected client cnfl\n");
			goto out;
		    }
		}
	}

	/*
	 * Check for a conflicting delegation. If one is found, call
	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
	 * been set yet, it will get the lock. Otherwise, it will recall
	 * the delegation. Then, we try try again...
	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
	 *  isn't a conflict.)
	 * I currently believe the conflict algorithm to be:
	 * For Open with Read Access and Deny None
	 * - there is a conflict iff a different client has a write delegation
	 * For Open with other Write Access or any Deny except None
	 * - there is a conflict if a different client has any delegation
	 * - there is a conflict if the same client has a read delegation
	 *   (The current consensus is that this last case should be
	 *    considered a conflict since the client with a read delegation
	 *    could have done an Open with ReadAccess and WriteDeny
	 *    locally and then not have checked for the WriteDeny.)
	 */
	if (!(new_stp->ls_flags & (NFSLCK_DELEGPREV | NFSLCK_DELEGCUR))) {
	    stp = LIST_FIRST(&lfp->lf_deleg);
	    while (stp != NULL) {
		nstp = LIST_NEXT(stp, ls_file);
		if (stp->ls_clp != clp && (stp->ls_flags & NFSLCK_DELEGREAD))
			writedeleg = 0;
		else
			delegate = 0;
		if ((readonly && stp->ls_clp != clp &&
		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
		    (!readonly && (stp->ls_clp != clp ||
		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
		    if (new_stp->ls_flags & NFSLCK_RECLAIM) {
			delegate = 2;
		    } else {
			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
			if (ret) {
			    /*
			     * nfsrv_delegconflict() unlocks state
			     * when it returns non-zero.
			     */
			    printf("Nfsd openctrl unexpected deleg cnfl\n");
			    free((caddr_t)new_open, M_NFSDSTATE);
			    free((caddr_t)new_deleg, M_NFSDSTATE);
			    if (ret == -1) {
				openstp = NULL;
				goto tryagain;
			    }
			    error = ret;
			    goto out;
			}
		    }
		}
		stp = nstp;
	    }
	}

	/*
	 * We only get here if there was no open that conflicted.
	 * If an open for the owner exists, or in the access/deny bits.
	 * Otherwise it is a new open. If the open_owner hasn't been
	 * confirmed, replace the open with the new one needing confirmation,
	 * otherwise add the open.
	 */
	if (new_stp->ls_flags & NFSLCK_DELEGPREV) {
	    /*
	     * Handle NFSLCK_DELEGPREV by searching the old delegations for
	     * a match. If found, just move the old delegation to the current
	     * delegation list and issue open. If not found, return
	     * NFSERR_EXPIRED.
	     */
	    LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
		if (stp->ls_lfp == lfp) {
		    /* Found it */
		    if (stp->ls_clp != clp)
			panic("olddeleg clp");
		    LIST_REMOVE(stp, ls_list);
		    LIST_REMOVE(stp, ls_hash);
		    stp->ls_flags &= ~NFSLCK_OLDDELEG;
		    stp->ls_stateid.seqid = delegstateidp->seqid = 1;
		    stp->ls_stateid.other[0] = delegstateidp->other[0] =
			clp->lc_clientid.lval[0];
		    stp->ls_stateid.other[1] = delegstateidp->other[1] =
			clp->lc_clientid.lval[1];
		    stp->ls_stateid.other[2] = delegstateidp->other[2] =
			nfsrv_nextstateindex(clp);
		    stp->ls_compref = nd->nd_compref;
		    LIST_INSERT_HEAD(&clp->lc_deleg, stp, ls_list);
		    LIST_INSERT_HEAD(NFSSTATEHASH(clp,
			stp->ls_stateid), stp, ls_hash);
		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
		    else
			*rflagsp |= NFSV4OPEN_READDELEGATE;
		    clp->lc_delegtime = NFSD_MONOSEC +
			nfsrv_lease + NFSRV_LEASEDELTA;

		    /*
		     * Now, do the associated open.
		     */
		    new_open->ls_stateid.seqid = 1;
		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
		    new_open->ls_flags = (new_stp->ls_flags&NFSLCK_DENYBITS)|
			NFSLCK_OPEN;
		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
			new_open->ls_flags |= (NFSLCK_READACCESS |
			    NFSLCK_WRITEACCESS);
		    else
			new_open->ls_flags |= NFSLCK_READACCESS;
		    new_open->ls_uid = new_stp->ls_uid;
		    new_open->ls_lfp = lfp;
		    new_open->ls_clp = clp;
		    LIST_INIT(&new_open->ls_open);
		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
			new_open, ls_hash);
		    /*
		     * and handle the open owner
		     */
		    if (ownerstp) {
			new_open->ls_openowner = ownerstp;
			LIST_INSERT_HEAD(&ownerstp->ls_open,new_open,ls_list);
		    } else {
			new_open->ls_openowner = new_stp;
			new_stp->ls_flags = 0;
			nfsrvd_refcache(new_stp->ls_op);
			new_stp->ls_noopens = 0;
			LIST_INIT(&new_stp->ls_open);
			LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
			LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
			*new_stpp = NULL;
			nfsstatsv1.srvopenowners++;
			nfsrv_openpluslock++;
		    }
		    openstp = new_open;
		    new_open = NULL;
		    nfsstatsv1.srvopens++;
		    nfsrv_openpluslock++;
		    break;
		}
	    }
	    if (stp == NULL)
		error = NFSERR_EXPIRED;
	} else if (new_stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
	    /*
	     * Scan to see that no delegation for this client and file
	     * doesn't already exist.
	     * There also shouldn't yet be an Open for this file and
	     * openowner.
	     */
	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
		if (stp->ls_clp == clp)
		    break;
	    }
	    if (stp == NULL && openstp == NULL) {
		/*
		 * This is the Claim_Previous case with a delegation
		 * type != Delegate_None.
		 */
		/*
		 * First, add the delegation. (Although we must issue the
		 * delegation, we can also ask for an immediate return.)
		 */
		new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
		new_deleg->ls_stateid.other[0] = delegstateidp->other[0] =
		    clp->lc_clientid.lval[0];
		new_deleg->ls_stateid.other[1] = delegstateidp->other[1] =
		    clp->lc_clientid.lval[1];
		new_deleg->ls_stateid.other[2] = delegstateidp->other[2] =
		    nfsrv_nextstateindex(clp);
		if (new_stp->ls_flags & NFSLCK_DELEGWRITE) {
		    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
			NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
		    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
		} else {
		    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
			NFSLCK_READACCESS);
		    *rflagsp |= NFSV4OPEN_READDELEGATE;
		}
		new_deleg->ls_uid = new_stp->ls_uid;
		new_deleg->ls_lfp = lfp;
		new_deleg->ls_clp = clp;
		new_deleg->ls_filerev = filerev;
		new_deleg->ls_compref = nd->nd_compref;
		LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
		LIST_INSERT_HEAD(NFSSTATEHASH(clp,
		    new_deleg->ls_stateid), new_deleg, ls_hash);
		LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
		new_deleg = NULL;
		if (delegate == 2 || nfsrv_issuedelegs == 0 ||
		    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
		     LCL_CALLBACKSON ||
		    NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) ||
		    !NFSVNO_DELEGOK(vp))
		    *rflagsp |= NFSV4OPEN_RECALL;
		nfsstatsv1.srvdelegates++;
		nfsrv_openpluslock++;
		nfsrv_delegatecnt++;

		/*
		 * Now, do the associated open.
		 */
		new_open->ls_stateid.seqid = 1;
		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_DENYBITS) |
		    NFSLCK_OPEN;
		if (new_stp->ls_flags & NFSLCK_DELEGWRITE)
			new_open->ls_flags |= (NFSLCK_READACCESS |
			    NFSLCK_WRITEACCESS);
		else
			new_open->ls_flags |= NFSLCK_READACCESS;
		new_open->ls_uid = new_stp->ls_uid;
		new_open->ls_lfp = lfp;
		new_open->ls_clp = clp;
		LIST_INIT(&new_open->ls_open);
		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
		   new_open, ls_hash);
		/*
		 * and handle the open owner
		 */
		if (ownerstp) {
		    new_open->ls_openowner = ownerstp;
		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
		} else {
		    new_open->ls_openowner = new_stp;
		    new_stp->ls_flags = 0;
		    nfsrvd_refcache(new_stp->ls_op);
		    new_stp->ls_noopens = 0;
		    LIST_INIT(&new_stp->ls_open);
		    LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
		    LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
		    *new_stpp = NULL;
		    nfsstatsv1.srvopenowners++;
		    nfsrv_openpluslock++;
		}
		openstp = new_open;
		new_open = NULL;
		nfsstatsv1.srvopens++;
		nfsrv_openpluslock++;
	    } else {
		error = NFSERR_RECLAIMCONFLICT;
	    }
	} else if (ownerstp) {
		if (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM) {
		    /* Replace the open */
		    if (ownerstp->ls_op)
			nfsrvd_derefcache(ownerstp->ls_op);
		    ownerstp->ls_op = new_stp->ls_op;
		    nfsrvd_refcache(ownerstp->ls_op);
		    ownerstp->ls_seq = new_stp->ls_seq;
		    *rflagsp |= NFSV4OPEN_RESULTCONFIRM;
		    stp = LIST_FIRST(&ownerstp->ls_open);
		    stp->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
			NFSLCK_OPEN;
		    stp->ls_stateid.seqid = 1;
		    stp->ls_uid = new_stp->ls_uid;
		    if (lfp != stp->ls_lfp) {
			LIST_REMOVE(stp, ls_file);
			LIST_INSERT_HEAD(&lfp->lf_open, stp, ls_file);
			stp->ls_lfp = lfp;
		    }
		    openstp = stp;
		} else if (openstp) {
		    openstp->ls_flags |= (new_stp->ls_flags & NFSLCK_SHAREBITS);
		    openstp->ls_stateid.seqid++;
		    if ((nd->nd_flag & ND_NFSV41) != 0 &&
			openstp->ls_stateid.seqid == 0)
			openstp->ls_stateid.seqid = 1;

		    /*
		     * This is where we can choose to issue a delegation.
		     */
		    if (delegate == 0 || writedeleg == 0 ||
			NFSVNO_EXRDONLY(exp) || (readonly != 0 &&
			nfsrv_writedelegifpos == 0) ||
			!NFSVNO_DELEGOK(vp) ||
			(new_stp->ls_flags & NFSLCK_WANTRDELEG) != 0 ||
			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
			 LCL_CALLBACKSON)
			*rflagsp |= NFSV4OPEN_WDCONTENTION;
		    else if (nfsrv_issuedelegs == 0 ||
			NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
			*rflagsp |= NFSV4OPEN_WDRESOURCE;
		    else if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
		    else {
			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
			    = clp->lc_clientid.lval[0];
			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
			    = clp->lc_clientid.lval[1];
			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
			    = nfsrv_nextstateindex(clp);
			new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
			    NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
			new_deleg->ls_uid = new_stp->ls_uid;
			new_deleg->ls_lfp = lfp;
			new_deleg->ls_clp = clp;
			new_deleg->ls_filerev = filerev;
			new_deleg->ls_compref = nd->nd_compref;
			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
			    new_deleg->ls_stateid), new_deleg, ls_hash);
			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
			new_deleg = NULL;
			nfsstatsv1.srvdelegates++;
			nfsrv_openpluslock++;
			nfsrv_delegatecnt++;
		    }
		} else {
		    new_open->ls_stateid.seqid = 1;
		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
		    new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS)|
			NFSLCK_OPEN;
		    new_open->ls_uid = new_stp->ls_uid;
		    new_open->ls_openowner = ownerstp;
		    new_open->ls_lfp = lfp;
		    new_open->ls_clp = clp;
		    LIST_INIT(&new_open->ls_open);
		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
			new_open, ls_hash);
		    openstp = new_open;
		    new_open = NULL;
		    nfsstatsv1.srvopens++;
		    nfsrv_openpluslock++;

		    /*
		     * This is where we can choose to issue a delegation.
		     */
		    if (delegate == 0 || (writedeleg == 0 && readonly == 0) ||
			!NFSVNO_DELEGOK(vp) ||
			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
			 LCL_CALLBACKSON)
			*rflagsp |= NFSV4OPEN_WDCONTENTION;
		    else if (nfsrv_issuedelegs == 0 ||
			NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
			*rflagsp |= NFSV4OPEN_WDRESOURCE;
		    else if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
		    else {
			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
			    = clp->lc_clientid.lval[0];
			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
			    = clp->lc_clientid.lval[1];
			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
			    = nfsrv_nextstateindex(clp);
			if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
			    (nfsrv_writedelegifpos || !readonly) &&
			    (new_stp->ls_flags & NFSLCK_WANTRDELEG) == 0) {
			    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
				NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
			    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
			} else {
			    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
				NFSLCK_READACCESS);
			    *rflagsp |= NFSV4OPEN_READDELEGATE;
			}
			new_deleg->ls_uid = new_stp->ls_uid;
			new_deleg->ls_lfp = lfp;
			new_deleg->ls_clp = clp;
			new_deleg->ls_filerev = filerev;
			new_deleg->ls_compref = nd->nd_compref;
			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
			    new_deleg->ls_stateid), new_deleg, ls_hash);
			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
			new_deleg = NULL;
			nfsstatsv1.srvdelegates++;
			nfsrv_openpluslock++;
			nfsrv_delegatecnt++;
		    }
		}
	} else {
		/*
		 * New owner case. Start the open_owner sequence with a
		 * Needs confirmation (unless a reclaim) and hang the
		 * new open off it.
		 */
		new_open->ls_stateid.seqid = 1;
		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
		    NFSLCK_OPEN;
		new_open->ls_uid = new_stp->ls_uid;
		LIST_INIT(&new_open->ls_open);
		new_open->ls_openowner = new_stp;
		new_open->ls_lfp = lfp;
		new_open->ls_clp = clp;
		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
		if (new_stp->ls_flags & NFSLCK_RECLAIM) {
			new_stp->ls_flags = 0;
		} else if ((nd->nd_flag & ND_NFSV41) != 0) {
			/* NFSv4.1 never needs confirmation. */
			new_stp->ls_flags = 0;

			/*
			 * This is where we can choose to issue a delegation.
			 */
			if (delegate && nfsrv_issuedelegs &&
			    (writedeleg || readonly) &&
			    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) ==
			     LCL_CALLBACKSON &&
			    !NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) &&
			    NFSVNO_DELEGOK(vp) &&
			    ((nd->nd_flag & ND_NFSV41) == 0 ||
			     (new_stp->ls_flags & NFSLCK_WANTNODELEG) == 0)) {
				new_deleg->ls_stateid.seqid =
				    delegstateidp->seqid = 1;
				new_deleg->ls_stateid.other[0] =
				    delegstateidp->other[0]
				    = clp->lc_clientid.lval[0];
				new_deleg->ls_stateid.other[1] =
				    delegstateidp->other[1]
				    = clp->lc_clientid.lval[1];
				new_deleg->ls_stateid.other[2] =
				    delegstateidp->other[2]
				    = nfsrv_nextstateindex(clp);
				if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
				    (nfsrv_writedelegifpos || !readonly) &&
				    ((nd->nd_flag & ND_NFSV41) == 0 ||
				     (new_stp->ls_flags & NFSLCK_WANTRDELEG) ==
				     0)) {
					new_deleg->ls_flags =
					    (NFSLCK_DELEGWRITE |
					     NFSLCK_READACCESS |
					     NFSLCK_WRITEACCESS);
					*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
				} else {
					new_deleg->ls_flags =
					    (NFSLCK_DELEGREAD |
					     NFSLCK_READACCESS);
					*rflagsp |= NFSV4OPEN_READDELEGATE;
				}
				new_deleg->ls_uid = new_stp->ls_uid;
				new_deleg->ls_lfp = lfp;
				new_deleg->ls_clp = clp;
				new_deleg->ls_filerev = filerev;
				new_deleg->ls_compref = nd->nd_compref;
				LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg,
				    ls_file);
				LIST_INSERT_HEAD(NFSSTATEHASH(clp,
				    new_deleg->ls_stateid), new_deleg, ls_hash);
				LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg,
				    ls_list);
				new_deleg = NULL;
				nfsstatsv1.srvdelegates++;
				nfsrv_openpluslock++;
				nfsrv_delegatecnt++;
			}
		} else {
			*rflagsp |= NFSV4OPEN_RESULTCONFIRM;
			new_stp->ls_flags = NFSLCK_NEEDSCONFIRM;
		}
		nfsrvd_refcache(new_stp->ls_op);
		new_stp->ls_noopens = 0;
		LIST_INIT(&new_stp->ls_open);
		LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
		LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
		    new_open, ls_hash);
		openstp = new_open;
		new_open = NULL;
		*new_stpp = NULL;
		nfsstatsv1.srvopens++;
		nfsrv_openpluslock++;
		nfsstatsv1.srvopenowners++;
		nfsrv_openpluslock++;
	}
	if (!error) {
		stateidp->seqid = openstp->ls_stateid.seqid;
		stateidp->other[0] = openstp->ls_stateid.other[0];
		stateidp->other[1] = openstp->ls_stateid.other[1];
		stateidp->other[2] = openstp->ls_stateid.other[2];
	}
	NFSUNLOCKSTATE();
	if (haslock) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
	}
	if (new_open)
		FREE((caddr_t)new_open, M_NFSDSTATE);
	if (new_deleg)
		FREE((caddr_t)new_deleg, M_NFSDSTATE);

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Open update. Does the confirm, downgrade and close.
 */
APPLESTATIC int
nfsrv_openupdate(vnode_t vp, struct nfsstate *new_stp, nfsquad_t clientid,
    nfsv4stateid_t *stateidp, struct nfsrv_descript *nd, NFSPROC_T *p)
{
	struct nfsstate *stp, *ownerstp;
	struct nfsclient *clp;
	struct nfslockfile *lfp;
	u_int32_t bits;
	int error = 0, gotstate = 0, len = 0;
	u_char client[NFSV4_OPAQUELIMIT];

	/*
	 * Check for restart conditions (client and server).
	 */
	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
	    &new_stp->ls_stateid, 0);
	if (error)
		goto out;

	NFSLOCKSTATE();
	/*
	 * Get the open structure via clientid and stateid.
	 */
	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
	if (!error)
		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
		    new_stp->ls_flags, &stp);

	/*
	 * Sanity check the open.
	 */
	if (!error && (!(stp->ls_flags & NFSLCK_OPEN) ||
		(!(new_stp->ls_flags & NFSLCK_CONFIRM) &&
		 (stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)) ||
		((new_stp->ls_flags & NFSLCK_CONFIRM) &&
		 (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)))))
		error = NFSERR_BADSTATEID;

	if (!error)
		error = nfsrv_checkseqid(nd, new_stp->ls_seq,
		    stp->ls_openowner, new_stp->ls_op);
	if (!error && stp->ls_stateid.seqid != new_stp->ls_stateid.seqid &&
	    (((nd->nd_flag & ND_NFSV41) == 0 &&
	      !(new_stp->ls_flags & NFSLCK_CONFIRM)) ||
	     ((nd->nd_flag & ND_NFSV41) != 0 &&
	      new_stp->ls_stateid.seqid != 0)))
		error = NFSERR_OLDSTATEID;
	if (!error && vnode_vtype(vp) != VREG) {
		if (vnode_vtype(vp) == VDIR)
			error = NFSERR_ISDIR;
		else
			error = NFSERR_INVAL;
	}

	if (error) {
		/*
		 * If a client tries to confirm an Open with a bad
		 * seqid# and there are no byte range locks or other Opens
		 * on the openowner, just throw it away, so the next use of the
		 * openowner will start a fresh seq#.
		 */
		if (error == NFSERR_BADSEQID &&
		    (new_stp->ls_flags & NFSLCK_CONFIRM) &&
		    nfsrv_nootherstate(stp))
			nfsrv_freeopenowner(stp->ls_openowner, 0, p);
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * Set the return stateid.
	 */
	stateidp->seqid = stp->ls_stateid.seqid + 1;
	if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
		stateidp->seqid = 1;
	stateidp->other[0] = stp->ls_stateid.other[0];
	stateidp->other[1] = stp->ls_stateid.other[1];
	stateidp->other[2] = stp->ls_stateid.other[2];
	/*
	 * Now, handle the three cases.
	 */
	if (new_stp->ls_flags & NFSLCK_CONFIRM) {
		/*
		 * If the open doesn't need confirmation, it seems to me that
		 * there is a client error, but I'll just log it and keep going?
		 */
		if (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM))
			printf("Nfsv4d: stray open confirm\n");
		stp->ls_openowner->ls_flags = 0;
		stp->ls_stateid.seqid++;
		if ((nd->nd_flag & ND_NFSV41) != 0 &&
		    stp->ls_stateid.seqid == 0)
			stp->ls_stateid.seqid = 1;
		if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
			clp->lc_flags |= LCL_STAMPEDSTABLE;
			len = clp->lc_idlen;
			NFSBCOPY(clp->lc_id, client, len);
			gotstate = 1;
		}
		NFSUNLOCKSTATE();
	} else if (new_stp->ls_flags & NFSLCK_CLOSE) {
		ownerstp = stp->ls_openowner;
		lfp = stp->ls_lfp;
		if (nfsrv_dolocallocks != 0 && !LIST_EMPTY(&stp->ls_open)) {
			/* Get the lf lock */
			nfsrv_locklf(lfp);
			NFSUNLOCKSTATE();
			ASSERT_VOP_ELOCKED(vp, "nfsrv_openupdate");
			NFSVOPUNLOCK(vp, 0);
			if (nfsrv_freeopen(stp, vp, 1, p) == 0) {
				NFSLOCKSTATE();
				nfsrv_unlocklf(lfp);
				NFSUNLOCKSTATE();
			}
			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
		} else {
			(void) nfsrv_freeopen(stp, NULL, 0, p);
			NFSUNLOCKSTATE();
		}
	} else {
		/*
		 * Update the share bits, making sure that the new set are a
		 * subset of the old ones.
		 */
		bits = (new_stp->ls_flags & NFSLCK_SHAREBITS);
		if (~(stp->ls_flags) & bits) {
			NFSUNLOCKSTATE();
			error = NFSERR_INVAL;
			goto out;
		}
		stp->ls_flags = (bits | NFSLCK_OPEN);
		stp->ls_stateid.seqid++;
		if ((nd->nd_flag & ND_NFSV41) != 0 &&
		    stp->ls_stateid.seqid == 0)
			stp->ls_stateid.seqid = 1;
		NFSUNLOCKSTATE();
	}

	/*
	 * If the client just confirmed its first open, write a timestamp
	 * to the stable storage file.
	 */
	if (gotstate != 0) {
		nfsrv_writestable(client, len, NFSNST_NEWSTATE, p);
		nfsrv_backupstable();
	}

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Delegation update. Does the purge and return.
 */
APPLESTATIC int
nfsrv_delegupdate(struct nfsrv_descript *nd, nfsquad_t clientid,
    nfsv4stateid_t *stateidp, vnode_t vp, int op, struct ucred *cred,
    NFSPROC_T *p)
{
	struct nfsstate *stp;
	struct nfsclient *clp;
	int error = 0;
	fhandle_t fh;

	/*
	 * Do a sanity check against the file handle for DelegReturn.
	 */
	if (vp) {
		error = nfsvno_getfh(vp, &fh, p);
		if (error)
			goto out;
	}
	/*
	 * Check for restart conditions (client and server).
	 */
	if (op == NFSV4OP_DELEGRETURN)
		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGRETURN,
			stateidp, 0);
	else
		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGPURGE,
			stateidp, 0);

	NFSLOCKSTATE();
	/*
	 * Get the open structure via clientid and stateid.
	 */
	if (!error)
	    error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
		(nfsquad_t)((u_quad_t)0), 0, nd, p);
	if (error) {
		if (error == NFSERR_CBPATHDOWN)
			error = 0;
		if (error == NFSERR_STALECLIENTID && op == NFSV4OP_DELEGRETURN)
			error = NFSERR_STALESTATEID;
	}
	if (!error && op == NFSV4OP_DELEGRETURN) {
	    error = nfsrv_getstate(clp, stateidp, NFSLCK_DELEGRETURN, &stp);
	    if (!error && stp->ls_stateid.seqid != stateidp->seqid &&
		((nd->nd_flag & ND_NFSV41) == 0 || stateidp->seqid != 0))
		error = NFSERR_OLDSTATEID;
	}
	/*
	 * NFSERR_EXPIRED means that the state has gone away,
	 * so Delegations have been purged. Just return ok.
	 */
	if (error == NFSERR_EXPIRED && op == NFSV4OP_DELEGPURGE) {
		NFSUNLOCKSTATE();
		error = 0;
		goto out;
	}
	if (error) {
		NFSUNLOCKSTATE();
		goto out;
	}

	if (op == NFSV4OP_DELEGRETURN) {
		if (NFSBCMP((caddr_t)&fh, (caddr_t)&stp->ls_lfp->lf_fh,
		    sizeof (fhandle_t))) {
			NFSUNLOCKSTATE();
			error = NFSERR_BADSTATEID;
			goto out;
		}
		nfsrv_freedeleg(stp);
	} else {
		nfsrv_freedeleglist(&clp->lc_olddeleg);
	}
	NFSUNLOCKSTATE();
	error = 0;

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Release lock owner.
 */
APPLESTATIC int
nfsrv_releaselckown(struct nfsstate *new_stp, nfsquad_t clientid,
    NFSPROC_T *p)
{
	struct nfsstate *stp, *nstp, *openstp, *ownstp;
	struct nfsclient *clp;
	int error = 0;

	/*
	 * Check for restart conditions (client and server).
	 */
	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
	    &new_stp->ls_stateid, 0);
	if (error)
		goto out;

	NFSLOCKSTATE();
	/*
	 * Get the lock owner by name.
	 */
	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
	    (nfsquad_t)((u_quad_t)0), 0, NULL, p);
	if (error) {
		NFSUNLOCKSTATE();
		goto out;
	}
	LIST_FOREACH(ownstp, &clp->lc_open, ls_list) {
	    LIST_FOREACH(openstp, &ownstp->ls_open, ls_list) {
		stp = LIST_FIRST(&openstp->ls_open);
		while (stp != NULL) {
		    nstp = LIST_NEXT(stp, ls_list);
		    /*
		     * If the owner matches, check for locks and
		     * then free or return an error.
		     */
		    if (stp->ls_ownerlen == new_stp->ls_ownerlen &&
			!NFSBCMP(stp->ls_owner, new_stp->ls_owner,
			 stp->ls_ownerlen)){
			if (LIST_EMPTY(&stp->ls_lock)) {
			    nfsrv_freelockowner(stp, NULL, 0, p);
			} else {
			    NFSUNLOCKSTATE();
			    error = NFSERR_LOCKSHELD;
			    goto out;
			}
		    }
		    stp = nstp;
		}
	    }
	}
	NFSUNLOCKSTATE();

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Get the file handle for a lock structure.
 */
static int
nfsrv_getlockfh(vnode_t vp, u_short flags, struct nfslockfile *new_lfp,
    fhandle_t *nfhp, NFSPROC_T *p)
{
	fhandle_t *fhp = NULL;
	int error;

	/*
	 * For lock, use the new nfslock structure, otherwise just
	 * a fhandle_t on the stack.
	 */
	if (flags & NFSLCK_OPEN) {
		KASSERT(new_lfp != NULL, ("nfsrv_getlockfh: new_lfp NULL"));
		fhp = &new_lfp->lf_fh;
	} else if (nfhp) {
		fhp = nfhp;
	} else {
		panic("nfsrv_getlockfh");
	}
	error = nfsvno_getfh(vp, fhp, p);
	NFSEXITCODE(error);
	return (error);
}

/*
 * Get an nfs lock structure. Allocate one, as required, and return a
 * pointer to it.
 * Returns an NFSERR_xxx upon failure or -1 to indicate no current lock.
 */
static int
nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
    struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit)
{
	struct nfslockfile *lfp;
	fhandle_t *fhp = NULL, *tfhp;
	struct nfslockhashhead *hp;
	struct nfslockfile *new_lfp = NULL;

	/*
	 * For lock, use the new nfslock structure, otherwise just
	 * a fhandle_t on the stack.
	 */
	if (flags & NFSLCK_OPEN) {
		new_lfp = *new_lfpp;
		fhp = &new_lfp->lf_fh;
	} else if (nfhp) {
		fhp = nfhp;
	} else {
		panic("nfsrv_getlockfile");
	}

	hp = NFSLOCKHASH(fhp);
	LIST_FOREACH(lfp, hp, lf_hash) {
		tfhp = &lfp->lf_fh;
		if (NFSVNO_CMPFH(fhp, tfhp)) {
			if (lockit)
				nfsrv_locklf(lfp);
			*lfpp = lfp;
			return (0);
		}
	}
	if (!(flags & NFSLCK_OPEN))
		return (-1);

	/*
	 * No match, so chain the new one into the list.
	 */
	LIST_INIT(&new_lfp->lf_open);
	LIST_INIT(&new_lfp->lf_lock);
	LIST_INIT(&new_lfp->lf_deleg);
	LIST_INIT(&new_lfp->lf_locallock);
	LIST_INIT(&new_lfp->lf_rollback);
	new_lfp->lf_locallock_lck.nfslock_usecnt = 0;
	new_lfp->lf_locallock_lck.nfslock_lock = 0;
	new_lfp->lf_usecount = 0;
	LIST_INSERT_HEAD(hp, new_lfp, lf_hash);
	*lfpp = new_lfp;
	*new_lfpp = NULL;
	return (0);
}

/*
 * This function adds a nfslock lock structure to the list for the associated
 * nfsstate and nfslockfile structures. It will be inserted after the
 * entry pointed at by insert_lop.
 */
static void
nfsrv_insertlock(struct nfslock *new_lop, struct nfslock *insert_lop,
    struct nfsstate *stp, struct nfslockfile *lfp)
{
	struct nfslock *lop, *nlop;

	new_lop->lo_stp = stp;
	new_lop->lo_lfp = lfp;

	if (stp != NULL) {
		/* Insert in increasing lo_first order */
		lop = LIST_FIRST(&lfp->lf_lock);
		if (lop == NULL ||
		    new_lop->lo_first <= lop->lo_first) {
			LIST_INSERT_HEAD(&lfp->lf_lock, new_lop, lo_lckfile);
		} else {
			nlop = LIST_NEXT(lop, lo_lckfile);
			while (nlop != NULL &&
			       nlop->lo_first < new_lop->lo_first) {
				lop = nlop;
				nlop = LIST_NEXT(lop, lo_lckfile);
			}
			LIST_INSERT_AFTER(lop, new_lop, lo_lckfile);
		}
	} else {
		new_lop->lo_lckfile.le_prev = NULL;	/* list not used */
	}

	/*
	 * Insert after insert_lop, which is overloaded as stp or lfp for
	 * an empty list.
	 */
	if (stp == NULL && (struct nfslockfile *)insert_lop == lfp)
		LIST_INSERT_HEAD(&lfp->lf_locallock, new_lop, lo_lckowner);
	else if ((struct nfsstate *)insert_lop == stp)
		LIST_INSERT_HEAD(&stp->ls_lock, new_lop, lo_lckowner);
	else
		LIST_INSERT_AFTER(insert_lop, new_lop, lo_lckowner);
	if (stp != NULL) {
		nfsstatsv1.srvlocks++;
		nfsrv_openpluslock++;
	}
}

/*
 * This function updates the locking for a lock owner and given file. It
 * maintains a list of lock ranges ordered on increasing file offset that
 * are NFSLCK_READ or NFSLCK_WRITE and non-overlapping (aka POSIX style).
 * It always adds new_lop to the list and sometimes uses the one pointed
 * at by other_lopp.
 */
static void
nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
    struct nfslock **other_lopp, struct nfslockfile *lfp)
{
	struct nfslock *new_lop = *new_lopp;
	struct nfslock *lop, *tlop, *ilop;
	struct nfslock *other_lop = *other_lopp;
	int unlock = 0, myfile = 0;
	u_int64_t tmp;

	/*
	 * Work down the list until the lock is merged.
	 */
	if (new_lop->lo_flags & NFSLCK_UNLOCK)
		unlock = 1;
	if (stp != NULL) {
		ilop = (struct nfslock *)stp;
		lop = LIST_FIRST(&stp->ls_lock);
	} else {
		ilop = (struct nfslock *)lfp;
		lop = LIST_FIRST(&lfp->lf_locallock);
	}
	while (lop != NULL) {
	    /*
	     * Only check locks for this file that aren't before the start of
	     * new lock's range.
	     */
	    if (lop->lo_lfp == lfp) {
	      myfile = 1;
	      if (lop->lo_end >= new_lop->lo_first) {
		if (new_lop->lo_end < lop->lo_first) {
			/*
			 * If the new lock ends before the start of the
			 * current lock's range, no merge, just insert
			 * the new lock.
			 */
			break;
		}
		if (new_lop->lo_flags == lop->lo_flags ||
		    (new_lop->lo_first <= lop->lo_first &&
		     new_lop->lo_end >= lop->lo_end)) {
			/*
			 * This lock can be absorbed by the new lock/unlock.
			 * This happens when it covers the entire range
			 * of the old lock or is contiguous
			 * with the old lock and is of the same type or an
			 * unlock.
			 */
			if (lop->lo_first < new_lop->lo_first)
				new_lop->lo_first = lop->lo_first;
			if (lop->lo_end > new_lop->lo_end)
				new_lop->lo_end = lop->lo_end;
			tlop = lop;
			lop = LIST_NEXT(lop, lo_lckowner);
			nfsrv_freenfslock(tlop);
			continue;
		}

		/*
		 * All these cases are for contiguous locks that are not the
		 * same type, so they can't be merged.
		 */
		if (new_lop->lo_first <= lop->lo_first) {
			/*
			 * This case is where the new lock overlaps with the
			 * first part of the old lock. Move the start of the
			 * old lock to just past the end of the new lock. The
			 * new lock will be inserted in front of the old, since
			 * ilop hasn't been updated. (We are done now.)
			 */
			lop->lo_first = new_lop->lo_end;
			break;
		}
		if (new_lop->lo_end >= lop->lo_end) {
			/*
			 * This case is where the new lock overlaps with the
			 * end of the old lock's range. Move the old lock's
			 * end to just before the new lock's first and insert
			 * the new lock after the old lock.
			 * Might not be done yet, since the new lock could
			 * overlap further locks with higher ranges.
			 */
			lop->lo_end = new_lop->lo_first;
			ilop = lop;
			lop = LIST_NEXT(lop, lo_lckowner);
			continue;
		}
		/*
		 * The final case is where the new lock's range is in the
		 * middle of the current lock's and splits the current lock
		 * up. Use *other_lopp to handle the second part of the
		 * split old lock range. (We are done now.)
		 * For unlock, we use new_lop as other_lop and tmp, since
		 * other_lop and new_lop are the same for this case.
		 * We noted the unlock case above, so we don't need
		 * new_lop->lo_flags any longer.
		 */
		tmp = new_lop->lo_first;
		if (other_lop == NULL) {
			if (!unlock)
				panic("nfsd srv update unlock");
			other_lop = new_lop;
			*new_lopp = NULL;
		}
		other_lop->lo_first = new_lop->lo_end;
		other_lop->lo_end = lop->lo_end;
		other_lop->lo_flags = lop->lo_flags;
		other_lop->lo_stp = stp;
		other_lop->lo_lfp = lfp;
		lop->lo_end = tmp;
		nfsrv_insertlock(other_lop, lop, stp, lfp);
		*other_lopp = NULL;
		ilop = lop;
		break;
	      }
	    }
	    ilop = lop;
	    lop = LIST_NEXT(lop, lo_lckowner);
	    if (myfile && (lop == NULL || lop->lo_lfp != lfp))
		break;
	}

	/*
	 * Insert the new lock in the list at the appropriate place.
	 */
	if (!unlock) {
		nfsrv_insertlock(new_lop, ilop, stp, lfp);
		*new_lopp = NULL;
	}
}

/*
 * This function handles sequencing of locks, etc.
 * It returns an error that indicates what the caller should do.
 */
static int
nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
    struct nfsstate *stp, struct nfsrvcache *op)
{
	int error = 0;

	if ((nd->nd_flag & ND_NFSV41) != 0)
		/* NFSv4.1 ignores the open_seqid and lock_seqid. */
		goto out;
	if (op != nd->nd_rp)
		panic("nfsrvstate checkseqid");
	if (!(op->rc_flag & RC_INPROG))
		panic("nfsrvstate not inprog");
	if (stp->ls_op && stp->ls_op->rc_refcnt <= 0) {
		printf("refcnt=%d\n", stp->ls_op->rc_refcnt);
		panic("nfsrvstate op refcnt");
	}
	if ((stp->ls_seq + 1) == seqid) {
		if (stp->ls_op)
			nfsrvd_derefcache(stp->ls_op);
		stp->ls_op = op;
		nfsrvd_refcache(op);
		stp->ls_seq = seqid;
		goto out;
	} else if (stp->ls_seq == seqid && stp->ls_op &&
		op->rc_xid == stp->ls_op->rc_xid &&
		op->rc_refcnt == 0 &&
		op->rc_reqlen == stp->ls_op->rc_reqlen &&
		op->rc_cksum == stp->ls_op->rc_cksum) {
		if (stp->ls_op->rc_flag & RC_INPROG) {
			error = NFSERR_DONTREPLY;
			goto out;
		}
		nd->nd_rp = stp->ls_op;
		nd->nd_rp->rc_flag |= RC_INPROG;
		nfsrvd_delcache(op);
		error = NFSERR_REPLYFROMCACHE;
		goto out;
	}
	error = NFSERR_BADSEQID;

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Get the client ip address for callbacks. If the strings can't be parsed,
 * just set lc_program to 0 to indicate no callbacks are possible.
 * (For cases where the address can't be parsed or is 0.0.0.0.0.0, set
 *  the address to the client's transport address. This won't be used
 *  for callbacks, but can be printed out by nfsstats for info.)
 * Return error if the xdr can't be parsed, 0 otherwise.
 */
APPLESTATIC int
nfsrv_getclientipaddr(struct nfsrv_descript *nd, struct nfsclient *clp)
{
	u_int32_t *tl;
	u_char *cp, *cp2;
	int i, j;
	struct sockaddr_in *rad, *sad;
	u_char protocol[5], addr[24];
	int error = 0, cantparse = 0;
	union {
		u_long ival;
		u_char cval[4];
	} ip;
	union {
		u_short sval;
		u_char cval[2];
	} port;

	rad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr_in *);
	rad->sin_family = AF_INET;
	rad->sin_len = sizeof (struct sockaddr_in);
	rad->sin_addr.s_addr = 0;
	rad->sin_port = 0;
	clp->lc_req.nr_client = NULL;
	clp->lc_req.nr_lock = 0;
	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
	i = fxdr_unsigned(int, *tl);
	if (i >= 3 && i <= 4) {
		error = nfsrv_mtostr(nd, protocol, i);
		if (error)
			goto nfsmout;
		if (!strcmp(protocol, "tcp")) {
			clp->lc_flags |= LCL_TCPCALLBACK;
			clp->lc_req.nr_sotype = SOCK_STREAM;
			clp->lc_req.nr_soproto = IPPROTO_TCP;
		} else if (!strcmp(protocol, "udp")) {
			clp->lc_req.nr_sotype = SOCK_DGRAM;
			clp->lc_req.nr_soproto = IPPROTO_UDP;
		} else {
			cantparse = 1;
		}
	} else {
		cantparse = 1;
		if (i > 0) {
			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
			if (error)
				goto nfsmout;
		}
	}
	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
	i = fxdr_unsigned(int, *tl);
	if (i < 0) {
		error = NFSERR_BADXDR;
		goto nfsmout;
	} else if (i == 0) {
		cantparse = 1;
	} else if (!cantparse && i <= 23 && i >= 11) {
		error = nfsrv_mtostr(nd, addr, i);
		if (error)
			goto nfsmout;

		/*
		 * Parse out the address fields. We expect 6 decimal numbers
		 * separated by '.'s.
		 */
		cp = addr;
		i = 0;
		while (*cp && i < 6) {
			cp2 = cp;
			while (*cp2 && *cp2 != '.')
				cp2++;
			if (*cp2)
				*cp2++ = '\0';
			else if (i != 5) {
				cantparse = 1;
				break;
			}
			j = nfsrv_getipnumber(cp);
			if (j >= 0) {
				if (i < 4)
					ip.cval[3 - i] = j;
				else
					port.cval[5 - i] = j;
			} else {
				cantparse = 1;
				break;
			}
			cp = cp2;
			i++;
		}
		if (!cantparse) {
			if (ip.ival != 0x0) {
				rad->sin_addr.s_addr = htonl(ip.ival);
				rad->sin_port = htons(port.sval);
			} else {
				cantparse = 1;
			}
		}
	} else {
		cantparse = 1;
		if (i > 0) {
			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
			if (error)
				goto nfsmout;
		}
	}
	if (cantparse) {
		sad = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
		rad->sin_addr.s_addr = sad->sin_addr.s_addr;
		rad->sin_port = 0x0;
		clp->lc_program = 0;
	}
nfsmout:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Turn a string of up to three decimal digits into a number. Return -1 upon
 * error.
 */
static int
nfsrv_getipnumber(u_char *cp)
{
	int i = 0, j = 0;

	while (*cp) {
		if (j > 2 || *cp < '0' || *cp > '9')
			return (-1);
		i *= 10;
		i += (*cp - '0');
		cp++;
		j++;
	}
	if (i < 256)
		return (i);
	return (-1);
}

/*
 * This function checks for restart conditions.
 */
static int
nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
    nfsv4stateid_t *stateidp, int specialid)
{
	int ret = 0;

	/*
	 * First check for a server restart. Open, LockT, ReleaseLockOwner
	 * and DelegPurge have a clientid, the rest a stateid.
	 */
	if (flags &
	    (NFSLCK_OPEN | NFSLCK_TEST | NFSLCK_RELEASE | NFSLCK_DELEGPURGE)) {
		if (clientid.lval[0] != nfsrvboottime) {
			ret = NFSERR_STALECLIENTID;
			goto out;
		}
	} else if (stateidp->other[0] != nfsrvboottime &&
		specialid == 0) {
		ret = NFSERR_STALESTATEID;
		goto out;
	}

	/*
	 * Read, Write, Setattr and LockT can return NFSERR_GRACE and do
	 * not use a lock/open owner seqid#, so the check can be done now.
	 * (The others will be checked, as required, later.)
	 */
	if (!(flags & (NFSLCK_CHECK | NFSLCK_TEST)))
		goto out;

	NFSLOCKSTATE();
	ret = nfsrv_checkgrace(NULL, NULL, flags);
	NFSUNLOCKSTATE();

out:
	NFSEXITCODE(ret);
	return (ret);
}

/*
 * Check for grace.
 */
static int
nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
    u_int32_t flags)
{
	int error = 0;

	if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
		if (flags & NFSLCK_RECLAIM) {
			error = NFSERR_NOGRACE;
			goto out;
		}
	} else {
		if (!(flags & NFSLCK_RECLAIM)) {
			error = NFSERR_GRACE;
			goto out;
		}
		if (nd != NULL && clp != NULL &&
		    (nd->nd_flag & ND_NFSV41) != 0 &&
		    (clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0) {
			error = NFSERR_NOGRACE;
			goto out;
		}

		/*
		 * If grace is almost over and we are still getting Reclaims,
		 * extend grace a bit.
		 */
		if ((NFSD_MONOSEC + NFSRV_LEASEDELTA) >
		    nfsrv_stablefirst.nsf_eograce)
			nfsrv_stablefirst.nsf_eograce = NFSD_MONOSEC +
				NFSRV_LEASEDELTA;
	}

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Do a server callback.
 */
static int
nfsrv_docallback(struct nfsclient *clp, int procnum,
    nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
    struct nfsvattr *nap, nfsattrbit_t *attrbitp, NFSPROC_T *p)
{
	mbuf_t m;
	u_int32_t *tl;
	struct nfsrv_descript nfsd, *nd = &nfsd;
	struct ucred *cred;
	int error = 0;
	u_int32_t callback;
	struct nfsdsession *sep = NULL;

	cred = newnfs_getcred();
	NFSLOCKSTATE();	/* mostly for lc_cbref++ */
	if (clp->lc_flags & LCL_NEEDSCONFIRM) {
		NFSUNLOCKSTATE();
		panic("docallb");
	}
	clp->lc_cbref++;

	/*
	 * Fill the callback program# and version into the request
	 * structure for newnfs_connect() to use.
	 */
	clp->lc_req.nr_prog = clp->lc_program;
#ifdef notnow
	if ((clp->lc_flags & LCL_NFSV41) != 0)
		clp->lc_req.nr_vers = NFSV41_CBVERS;
	else
#endif
		clp->lc_req.nr_vers = NFSV4_CBVERS;

	/*
	 * First, fill in some of the fields of nd and cr.
	 */
	nd->nd_flag = ND_NFSV4;
	if (clp->lc_flags & LCL_GSS)
		nd->nd_flag |= ND_KERBV;
	if ((clp->lc_flags & LCL_NFSV41) != 0)
		nd->nd_flag |= ND_NFSV41;
	nd->nd_repstat = 0;
	cred->cr_uid = clp->lc_uid;
	cred->cr_gid = clp->lc_gid;
	callback = clp->lc_callback;
	NFSUNLOCKSTATE();
	cred->cr_ngroups = 1;

	/*
	 * Get the first mbuf for the request.
	 */
	MGET(m, M_WAITOK, MT_DATA);
	mbuf_setlen(m, 0);
	nd->nd_mreq = nd->nd_mb = m;
	nd->nd_bpos = NFSMTOD(m, caddr_t);
	
	/*
	 * and build the callback request.
	 */
	if (procnum == NFSV4OP_CBGETATTR) {
		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBGETATTR,
		    "CB Getattr", &sep);
		if (error != 0) {
			mbuf_freem(nd->nd_mreq);
			goto errout;
		}
		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
		(void)nfsrv_putattrbit(nd, attrbitp);
	} else if (procnum == NFSV4OP_CBRECALL) {
		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBRECALL,
		    "CB Recall", &sep);
		if (error != 0) {
			mbuf_freem(nd->nd_mreq);
			goto errout;
		}
		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED + NFSX_STATEID);
		*tl++ = txdr_unsigned(stateidp->seqid);
		NFSBCOPY((caddr_t)stateidp->other, (caddr_t)tl,
		    NFSX_STATEIDOTHER);
		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
		if (trunc)
			*tl = newnfs_true;
		else
			*tl = newnfs_false;
		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
	} else if (procnum == NFSV4PROC_CBNULL) {
		nd->nd_procnum = NFSV4PROC_CBNULL;
		if ((clp->lc_flags & LCL_NFSV41) != 0) {
			error = nfsv4_getcbsession(clp, &sep);
			if (error != 0) {
				mbuf_freem(nd->nd_mreq);
				goto errout;
			}
		}
	} else {
		error = NFSERR_SERVERFAULT;
		mbuf_freem(nd->nd_mreq);
		goto errout;
	}

	/*
	 * Call newnfs_connect(), as required, and then newnfs_request().
	 */
	(void) newnfs_sndlock(&clp->lc_req.nr_lock);
	if (clp->lc_req.nr_client == NULL) {
		if ((clp->lc_flags & LCL_NFSV41) != 0)
			error = ECONNREFUSED;
		else if (nd->nd_procnum == NFSV4PROC_CBNULL)
			error = newnfs_connect(NULL, &clp->lc_req, cred,
			    NULL, 1);
		else
			error = newnfs_connect(NULL, &clp->lc_req, cred,
			    NULL, 3);
	}
	newnfs_sndunlock(&clp->lc_req.nr_lock);
	if (!error) {
		if ((nd->nd_flag & ND_NFSV41) != 0) {
			KASSERT(sep != NULL, ("sep NULL"));
			if (sep->sess_cbsess.nfsess_xprt != NULL)
				error = newnfs_request(nd, NULL, clp,
				    &clp->lc_req, NULL, NULL, cred,
				    clp->lc_program, clp->lc_req.nr_vers, NULL,
				    1, NULL, &sep->sess_cbsess);
			else {
				/*
				 * This should probably never occur, but if a
				 * client somehow does an RPC without a
				 * SequenceID Op that causes a callback just
				 * after the nfsd threads have been terminated
				 * and restared we could conceivably get here
				 * without a backchannel xprt.
				 */
				printf("nfsrv_docallback: no xprt\n");
				error = ECONNREFUSED;
			}
			nfsrv_freesession(sep, NULL);
		} else
			error = newnfs_request(nd, NULL, clp, &clp->lc_req,
			    NULL, NULL, cred, clp->lc_program,
			    clp->lc_req.nr_vers, NULL, 1, NULL, NULL);
	}
errout:
	NFSFREECRED(cred);

	/*
	 * If error is set here, the Callback path isn't working
	 * properly, so twiddle the appropriate LCL_ flags.
	 * (nd_repstat != 0 indicates the Callback path is working,
	 *  but the callback failed on the client.)
	 */
	if (error) {
		/*
		 * Mark the callback pathway down, which disabled issuing
		 * of delegations and gets Renew to return NFSERR_CBPATHDOWN.
		 */
		NFSLOCKSTATE();
		clp->lc_flags |= LCL_CBDOWN;
		NFSUNLOCKSTATE();
	} else {
		/*
		 * Callback worked. If the callback path was down, disable
		 * callbacks, so no more delegations will be issued. (This
		 * is done on the assumption that the callback pathway is
		 * flakey.)
		 */
		NFSLOCKSTATE();
		if (clp->lc_flags & LCL_CBDOWN)
			clp->lc_flags &= ~(LCL_CBDOWN | LCL_CALLBACKSON);
		NFSUNLOCKSTATE();
		if (nd->nd_repstat)
			error = nd->nd_repstat;
		else if (error == 0 && procnum == NFSV4OP_CBGETATTR)
			error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
			    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
			    p, NULL);
		mbuf_freem(nd->nd_mrep);
	}
	NFSLOCKSTATE();
	clp->lc_cbref--;
	if ((clp->lc_flags & LCL_WAKEUPWANTED) && clp->lc_cbref == 0) {
		clp->lc_flags &= ~LCL_WAKEUPWANTED;
		wakeup(clp);
	}
	NFSUNLOCKSTATE();

	NFSEXITCODE(error);
	return (error);
}

/*
 * Set up the compound RPC for the callback.
 */
static int
nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
    uint32_t callback, int op, const char *optag, struct nfsdsession **sepp)
{
	uint32_t *tl;
	int error, len;

	len = strlen(optag);
	(void)nfsm_strtom(nd, optag, len);
	NFSM_BUILD(tl, uint32_t *, 4 * NFSX_UNSIGNED);
	if ((nd->nd_flag & ND_NFSV41) != 0) {
		*tl++ = txdr_unsigned(NFSV41_MINORVERSION);
		*tl++ = txdr_unsigned(callback);
		*tl++ = txdr_unsigned(2);
		*tl = txdr_unsigned(NFSV4OP_CBSEQUENCE);
		error = nfsv4_setcbsequence(nd, clp, 1, sepp);
		if (error != 0)
			return (error);
		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
		*tl = txdr_unsigned(op);
	} else {
		*tl++ = txdr_unsigned(NFSV4_MINORVERSION);
		*tl++ = txdr_unsigned(callback);
		*tl++ = txdr_unsigned(1);
		*tl = txdr_unsigned(op);
	}
	return (0);
}

/*
 * Return the next index# for a clientid. Mostly just increment and return
 * the next one, but... if the 32bit unsigned does actually wrap around,
 * it should be rebooted.
 * At an average rate of one new client per second, it will wrap around in
 * approximately 136 years. (I think the server will have been shut
 * down or rebooted before then.)
 */
static u_int32_t
nfsrv_nextclientindex(void)
{
	static u_int32_t client_index = 0;

	client_index++;
	if (client_index != 0)
		return (client_index);

	printf("%s: out of clientids\n", __func__);
	return (client_index);
}

/*
 * Return the next index# for a stateid. Mostly just increment and return
 * the next one, but... if the 32bit unsigned does actually wrap around
 * (will a BSD server stay up that long?), find
 * new start and end values.
 */
static u_int32_t
nfsrv_nextstateindex(struct nfsclient *clp)
{
	struct nfsstate *stp;
	int i;
	u_int32_t canuse, min_index, max_index;

	if (!(clp->lc_flags & LCL_INDEXNOTOK)) {
		clp->lc_stateindex++;
		if (clp->lc_stateindex != clp->lc_statemaxindex)
			return (clp->lc_stateindex);
	}

	/*
	 * Yuck, we've hit the end.
	 * Look for a new min and max.
	 */
	min_index = 0;
	max_index = 0xffffffff;
	for (i = 0; i < nfsrv_statehashsize; i++) {
	    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
		if (stp->ls_stateid.other[2] > 0x80000000) {
		    if (stp->ls_stateid.other[2] < max_index)
			max_index = stp->ls_stateid.other[2];
		} else {
		    if (stp->ls_stateid.other[2] > min_index)
			min_index = stp->ls_stateid.other[2];
		}
	    }
	}

	/*
	 * Yikes, highly unlikely, but I'll handle it anyhow.
	 */
	if (min_index == 0x80000000 && max_index == 0x80000001) {
	    canuse = 0;
	    /*
	     * Loop around until we find an unused entry. Return that
	     * and set LCL_INDEXNOTOK, so the search will continue next time.
	     * (This is one of those rare cases where a goto is the
	     *  cleanest way to code the loop.)
	     */
tryagain:
	    for (i = 0; i < nfsrv_statehashsize; i++) {
		LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
		    if (stp->ls_stateid.other[2] == canuse) {
			canuse++;
			goto tryagain;
		    }
		}
	    }
	    clp->lc_flags |= LCL_INDEXNOTOK;
	    return (canuse);
	}

	/*
	 * Ok to start again from min + 1.
	 */
	clp->lc_stateindex = min_index + 1;
	clp->lc_statemaxindex = max_index;
	clp->lc_flags &= ~LCL_INDEXNOTOK;
	return (clp->lc_stateindex);
}

/*
 * The following functions handle the stable storage file that deals with
 * the edge conditions described in RFC3530 Sec. 8.6.3.
 * The file is as follows:
 * - a single record at the beginning that has the lease time of the
 *   previous server instance (before the last reboot) and the nfsrvboottime
 *   values for the previous server boots.
 *   These previous boot times are used to ensure that the current
 *   nfsrvboottime does not, somehow, get set to a previous one.
 *   (This is important so that Stale ClientIDs and StateIDs can
 *    be recognized.)
 *   The number of previous nfsvrboottime values precedes the list.
 * - followed by some number of appended records with:
 *   - client id string
 *   - flag that indicates it is a record revoking state via lease
 *     expiration or similar
 *     OR has successfully acquired state.
 * These structures vary in length, with the client string at the end, up
 * to NFSV4_OPAQUELIMIT in size.
 *
 * At the end of the grace period, the file is truncated, the first
 * record is rewritten with updated information and any acquired state
 * records for successful reclaims of state are written.
 *
 * Subsequent records are appended when the first state is issued to
 * a client and when state is revoked for a client.
 *
 * When reading the file in, state issued records that come later in
 * the file override older ones, since the append log is in cronological order.
 * If, for some reason, the file can't be read, the grace period is
 * immediately terminated and all reclaims get NFSERR_NOGRACE.
 */

/*
 * Read in the stable storage file. Called by nfssvc() before the nfsd
 * processes start servicing requests.
 */
APPLESTATIC void
nfsrv_setupstable(NFSPROC_T *p)
{
	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
	struct nfsrv_stable *sp, *nsp;
	struct nfst_rec *tsp;
	int error, i, tryagain;
	off_t off = 0;
	ssize_t aresid, len;

	/*
	 * If NFSNSF_UPDATEDONE is set, this is a restart of the nfsds without
	 * a reboot, so state has not been lost.
	 */
	if (sf->nsf_flags & NFSNSF_UPDATEDONE)
		return;
	/*
	 * Set Grace over just until the file reads successfully.
	 */
	nfsrvboottime = time_second;
	LIST_INIT(&sf->nsf_head);
	sf->nsf_flags = (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
	sf->nsf_eograce = NFSD_MONOSEC + NFSRV_LEASEDELTA;
	if (sf->nsf_fp == NULL)
		return;
	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
	    (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), off, UIO_SYSSPACE,
	    0, NFSFPCRED(sf->nsf_fp), &aresid, p);
	if (error || aresid || sf->nsf_numboots == 0 ||
		sf->nsf_numboots > NFSNSF_MAXNUMBOOTS)
		return;

	/*
	 * Now, read in the boottimes.
	 */
	sf->nsf_bootvals = (time_t *)malloc((sf->nsf_numboots + 1) *
		sizeof (time_t), M_TEMP, M_WAITOK);
	off = sizeof (struct nfsf_rec);
	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
	    (caddr_t)sf->nsf_bootvals, sf->nsf_numboots * sizeof (time_t), off,
	    UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
	if (error || aresid) {
		free((caddr_t)sf->nsf_bootvals, M_TEMP);
		sf->nsf_bootvals = NULL;
		return;
	}

	/*
	 * Make sure this nfsrvboottime is different from all recorded
	 * previous ones.
	 */
	do {
		tryagain = 0;
		for (i = 0; i < sf->nsf_numboots; i++) {
			if (nfsrvboottime == sf->nsf_bootvals[i]) {
				nfsrvboottime++;
				tryagain = 1;
				break;
			}
		}
	} while (tryagain);

	sf->nsf_flags |= NFSNSF_OK;
	off += (sf->nsf_numboots * sizeof (time_t));

	/*
	 * Read through the file, building a list of records for grace
	 * checking.
	 * Each record is between sizeof (struct nfst_rec) and
	 * sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1
	 * and is actually sizeof (struct nfst_rec) + nst_len - 1.
	 */
	tsp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
		NFSV4_OPAQUELIMIT - 1, M_TEMP, M_WAITOK);
	do {
	    error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
	        (caddr_t)tsp, sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1,
	        off, UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
	    len = (sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1) - aresid;
	    if (error || (len > 0 && (len < sizeof (struct nfst_rec) ||
		len < (sizeof (struct nfst_rec) + tsp->len - 1)))) {
		/*
		 * Yuck, the file has been corrupted, so just return
		 * after clearing out any restart state, so the grace period
		 * is over.
		 */
		LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
			LIST_REMOVE(sp, nst_list);
			free((caddr_t)sp, M_TEMP);
		}
		free((caddr_t)tsp, M_TEMP);
		sf->nsf_flags &= ~NFSNSF_OK;
		free((caddr_t)sf->nsf_bootvals, M_TEMP);
		sf->nsf_bootvals = NULL;
		return;
	    }
	    if (len > 0) {
		off += sizeof (struct nfst_rec) + tsp->len - 1;
		/*
		 * Search the list for a matching client.
		 */
		LIST_FOREACH(sp, &sf->nsf_head, nst_list) {
			if (tsp->len == sp->nst_len &&
			    !NFSBCMP(tsp->client, sp->nst_client, tsp->len))
				break;
		}
		if (sp == NULL) {
			sp = (struct nfsrv_stable *)malloc(tsp->len +
				sizeof (struct nfsrv_stable) - 1, M_TEMP,
				M_WAITOK);
			NFSBCOPY((caddr_t)tsp, (caddr_t)&sp->nst_rec,
				sizeof (struct nfst_rec) + tsp->len - 1);
			LIST_INSERT_HEAD(&sf->nsf_head, sp, nst_list);
		} else {
			if (tsp->flag == NFSNST_REVOKE)
				sp->nst_flag |= NFSNST_REVOKE;
			else
				/*
				 * A subsequent timestamp indicates the client
				 * did a setclientid/confirm and any previous
				 * revoke is no longer relevant.
				 */
				sp->nst_flag &= ~NFSNST_REVOKE;
		}
	    }
	} while (len > 0);
	free((caddr_t)tsp, M_TEMP);
	sf->nsf_flags = NFSNSF_OK;
	sf->nsf_eograce = NFSD_MONOSEC + sf->nsf_lease +
		NFSRV_LEASEDELTA;
}

/*
 * Update the stable storage file, now that the grace period is over.
 */
APPLESTATIC void
nfsrv_updatestable(NFSPROC_T *p)
{
	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
	struct nfsrv_stable *sp, *nsp;
	int i;
	struct nfsvattr nva;
	vnode_t vp;
#if defined(__FreeBSD_version) && (__FreeBSD_version >= 500000)
	mount_t mp = NULL;
#endif
	int error;

	if (sf->nsf_fp == NULL || (sf->nsf_flags & NFSNSF_UPDATEDONE))
		return;
	sf->nsf_flags |= NFSNSF_UPDATEDONE;
	/*
	 * Ok, we need to rewrite the stable storage file.
	 * - truncate to 0 length
	 * - write the new first structure
	 * - loop through the data structures, writing out any that
	 *   have timestamps older than the old boot
	 */
	if (sf->nsf_bootvals) {
		sf->nsf_numboots++;
		for (i = sf->nsf_numboots - 2; i >= 0; i--)
			sf->nsf_bootvals[i + 1] = sf->nsf_bootvals[i];
	} else {
		sf->nsf_numboots = 1;
		sf->nsf_bootvals = (time_t *)malloc(sizeof (time_t),
			M_TEMP, M_WAITOK);
	}
	sf->nsf_bootvals[0] = nfsrvboottime;
	sf->nsf_lease = nfsrv_lease;
	NFSVNO_ATTRINIT(&nva);
	NFSVNO_SETATTRVAL(&nva, size, 0);
	vp = NFSFPVNODE(sf->nsf_fp);
	vn_start_write(vp, &mp, V_WAIT);
	if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
		error = nfsvno_setattr(vp, &nva, NFSFPCRED(sf->nsf_fp), p,
		    NULL);
		NFSVOPUNLOCK(vp, 0);
	} else
		error = EPERM;
	vn_finished_write(mp);
	if (!error)
	    error = NFSD_RDWR(UIO_WRITE, vp,
		(caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), (off_t)0,
		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
	if (!error)
	    error = NFSD_RDWR(UIO_WRITE, vp,
		(caddr_t)sf->nsf_bootvals,
		sf->nsf_numboots * sizeof (time_t),
		(off_t)(sizeof (struct nfsf_rec)),
		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
	free((caddr_t)sf->nsf_bootvals, M_TEMP);
	sf->nsf_bootvals = NULL;
	if (error) {
		sf->nsf_flags &= ~NFSNSF_OK;
		printf("EEK! Can't write NfsV4 stable storage file\n");
		return;
	}
	sf->nsf_flags |= NFSNSF_OK;

	/*
	 * Loop through the list and write out timestamp records for
	 * any clients that successfully reclaimed state.
	 */
	LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
		if (sp->nst_flag & NFSNST_GOTSTATE) {
			nfsrv_writestable(sp->nst_client, sp->nst_len,
				NFSNST_NEWSTATE, p);
			sp->nst_clp->lc_flags |= LCL_STAMPEDSTABLE;
		}
		LIST_REMOVE(sp, nst_list);
		free((caddr_t)sp, M_TEMP);
	}
	nfsrv_backupstable();
}

/*
 * Append a record to the stable storage file.
 */
APPLESTATIC void
nfsrv_writestable(u_char *client, int len, int flag, NFSPROC_T *p)
{
	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
	struct nfst_rec *sp;
	int error;

	if (!(sf->nsf_flags & NFSNSF_OK) || sf->nsf_fp == NULL)
		return;
	sp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
		len - 1, M_TEMP, M_WAITOK);
	sp->len = len;
	NFSBCOPY(client, sp->client, len);
	sp->flag = flag;
	error = NFSD_RDWR(UIO_WRITE, NFSFPVNODE(sf->nsf_fp),
	    (caddr_t)sp, sizeof (struct nfst_rec) + len - 1, (off_t)0,
	    UIO_SYSSPACE, (IO_SYNC | IO_APPEND), NFSFPCRED(sf->nsf_fp), NULL, p);
	free((caddr_t)sp, M_TEMP);
	if (error) {
		sf->nsf_flags &= ~NFSNSF_OK;
		printf("EEK! Can't write NfsV4 stable storage file\n");
	}
}

/*
 * This function is called during the grace period to mark a client
 * that successfully reclaimed state.
 */
static void
nfsrv_markstable(struct nfsclient *clp)
{
	struct nfsrv_stable *sp;

	/*
	 * First find the client structure.
	 */
	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
		if (sp->nst_len == clp->lc_idlen &&
		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
			break;
	}
	if (sp == NULL)
		return;

	/*
	 * Now, just mark it and set the nfsclient back pointer.
	 */
	sp->nst_flag |= NFSNST_GOTSTATE;
	sp->nst_clp = clp;
}

/*
 * This function is called for a reclaim, to see if it gets grace.
 * It returns 0 if a reclaim is allowed, 1 otherwise.
 */
static int
nfsrv_checkstable(struct nfsclient *clp)
{
	struct nfsrv_stable *sp;

	/*
	 * First, find the entry for the client.
	 */
	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
		if (sp->nst_len == clp->lc_idlen &&
		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
			break;
	}

	/*
	 * If not in the list, state was revoked or no state was issued
	 * since the previous reboot, a reclaim is denied.
	 */
	if (sp == NULL ||
	    (sp->nst_flag & NFSNST_REVOKE) ||
	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_OK))
		return (1);
	return (0);
}

/*
 * Test for and try to clear out a conflicting client. This is called by
 * nfsrv_lockctrl() and nfsrv_openctrl() when conflicts with other clients
 * a found.
 * The trick here is that it can't revoke a conflicting client with an
 * expired lease unless it holds the v4root lock, so...
 * If no v4root lock, get the lock and return 1 to indicate "try again".
 * Return 0 to indicate the conflict can't be revoked and 1 to indicate
 * the revocation worked and the conflicting client is "bye, bye", so it
 * can be tried again.
 * Return 2 to indicate that the vnode is VI_DOOMED after NFSVOPLOCK().
 * Unlocks State before a non-zero value is returned.
 */
static int
nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, vnode_t vp,
    NFSPROC_T *p)
{
	int gotlock, lktype = 0;

	/*
	 * If lease hasn't expired, we can't fix it.
	 */
	if (clp->lc_expiry >= NFSD_MONOSEC ||
	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE))
		return (0);
	if (*haslockp == 0) {
		NFSUNLOCKSTATE();
		if (vp != NULL) {
			lktype = NFSVOPISLOCKED(vp);
			NFSVOPUNLOCK(vp, 0);
		}
		NFSLOCKV4ROOTMUTEX();
		nfsv4_relref(&nfsv4rootfs_lock);
		do {
			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
			    NFSV4ROOTLOCKMUTEXPTR, NULL);
		} while (!gotlock);
		NFSUNLOCKV4ROOTMUTEX();
		*haslockp = 1;
		if (vp != NULL) {
			NFSVOPLOCK(vp, lktype | LK_RETRY);
			if ((vp->v_iflag & VI_DOOMED) != 0)
				return (2);
		}
		return (1);
	}
	NFSUNLOCKSTATE();

	/*
	 * Ok, we can expire the conflicting client.
	 */
	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
	nfsrv_backupstable();
	nfsrv_cleanclient(clp, p);
	nfsrv_freedeleglist(&clp->lc_deleg);
	nfsrv_freedeleglist(&clp->lc_olddeleg);
	LIST_REMOVE(clp, lc_hash);
	nfsrv_zapclient(clp, p);
	return (1);
}

/*
 * Resolve a delegation conflict.
 * Returns 0 to indicate the conflict was resolved without sleeping.
 * Return -1 to indicate that the caller should check for conflicts again.
 * Return > 0 for an error that should be returned, normally NFSERR_DELAY.
 *
 * Also, manipulate the nfsv4root_lock, as required. It isn't changed
 * for a return of 0, since there was no sleep and it could be required
 * later. It is released for a return of NFSERR_DELAY, since the caller
 * will return that error. It is released when a sleep was done waiting
 * for the delegation to be returned or expire (so that other nfsds can
 * handle ops). Then, it must be acquired for the write to stable storage.
 * (This function is somewhat similar to nfsrv_clientconflict(), but
 *  the semantics differ in a couple of subtle ways. The return of 0
 *  indicates the conflict was resolved without sleeping here, not
 *  that the conflict can't be resolved and the handling of nfsv4root_lock
 *  differs, as noted above.)
 * Unlocks State before returning a non-zero value.
 */
static int
nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
    vnode_t vp)
{
	struct nfsclient *clp = stp->ls_clp;
	int gotlock, error, lktype = 0, retrycnt, zapped_clp;
	nfsv4stateid_t tstateid;
	fhandle_t tfh;

	/*
	 * If the conflict is with an old delegation...
	 */
	if (stp->ls_flags & NFSLCK_OLDDELEG) {
		/*
		 * You can delete it, if it has expired.
		 */
		if (clp->lc_delegtime < NFSD_MONOSEC) {
			nfsrv_freedeleg(stp);
			NFSUNLOCKSTATE();
			error = -1;
			goto out;
		}
		NFSUNLOCKSTATE();
		/*
		 * During this delay, the old delegation could expire or it
		 * could be recovered by the client via an Open with
		 * CLAIM_DELEGATE_PREV.
		 * Release the nfsv4root_lock, if held.
		 */
		if (*haslockp) {
			*haslockp = 0;
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		error = NFSERR_DELAY;
		goto out;
	}

	/*
	 * It's a current delegation, so:
	 * - check to see if the delegation has expired
	 *   - if so, get the v4root lock and then expire it
	 */
	if (!(stp->ls_flags & NFSLCK_DELEGRECALL)) {
		/*
		 * - do a recall callback, since not yet done
		 * For now, never allow truncate to be set. To use
		 * truncate safely, it must be guaranteed that the
		 * Remove, Rename or Setattr with size of 0 will
		 * succeed and that would require major changes to
		 * the VFS/Vnode OPs.
		 * Set the expiry time large enough so that it won't expire
		 * until after the callback, then set it correctly, once
		 * the callback is done. (The delegation will now time
		 * out whether or not the Recall worked ok. The timeout
		 * will be extended when ops are done on the delegation
		 * stateid, up to the timelimit.)
		 */
		stp->ls_delegtime = NFSD_MONOSEC + (2 * nfsrv_lease) +
		    NFSRV_LEASEDELTA;
		stp->ls_delegtimelimit = NFSD_MONOSEC + (6 * nfsrv_lease) +
		    NFSRV_LEASEDELTA;
		stp->ls_flags |= NFSLCK_DELEGRECALL;

		/*
		 * Loop NFSRV_CBRETRYCNT times while the CBRecall replies
		 * NFSERR_BADSTATEID or NFSERR_BADHANDLE. This is done
		 * in order to try and avoid a race that could happen
		 * when a CBRecall request passed the Open reply with
		 * the delegation in it when transitting the network.
		 * Since nfsrv_docallback will sleep, don't use stp after
		 * the call.
		 */
		NFSBCOPY((caddr_t)&stp->ls_stateid, (caddr_t)&tstateid,
		    sizeof (tstateid));
		NFSBCOPY((caddr_t)&stp->ls_lfp->lf_fh, (caddr_t)&tfh,
		    sizeof (tfh));
		NFSUNLOCKSTATE();
		if (*haslockp) {
			*haslockp = 0;
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		retrycnt = 0;
		do {
		    error = nfsrv_docallback(clp, NFSV4OP_CBRECALL,
			&tstateid, 0, &tfh, NULL, NULL, p);
		    retrycnt++;
		} while ((error == NFSERR_BADSTATEID ||
		    error == NFSERR_BADHANDLE) && retrycnt < NFSV4_CBRETRYCNT);
		error = NFSERR_DELAY;
		goto out;
	}

	if (clp->lc_expiry >= NFSD_MONOSEC &&
	    stp->ls_delegtime >= NFSD_MONOSEC) {
		NFSUNLOCKSTATE();
		/*
		 * A recall has been done, but it has not yet expired.
		 * So, RETURN_DELAY.
		 */
		if (*haslockp) {
			*haslockp = 0;
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		error = NFSERR_DELAY;
		goto out;
	}

	/*
	 * If we don't yet have the lock, just get it and then return,
	 * since we need that before deleting expired state, such as
	 * this delegation.
	 * When getting the lock, unlock the vnode, so other nfsds that
	 * are in progress, won't get stuck waiting for the vnode lock.
	 */
	if (*haslockp == 0) {
		NFSUNLOCKSTATE();
		if (vp != NULL) {
			lktype = NFSVOPISLOCKED(vp);
			NFSVOPUNLOCK(vp, 0);
		}
		NFSLOCKV4ROOTMUTEX();
		nfsv4_relref(&nfsv4rootfs_lock);
		do {
			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
			    NFSV4ROOTLOCKMUTEXPTR, NULL);
		} while (!gotlock);
		NFSUNLOCKV4ROOTMUTEX();
		*haslockp = 1;
		if (vp != NULL) {
			NFSVOPLOCK(vp, lktype | LK_RETRY);
			if ((vp->v_iflag & VI_DOOMED) != 0) {
				*haslockp = 0;
				NFSLOCKV4ROOTMUTEX();
				nfsv4_unlock(&nfsv4rootfs_lock, 1);
				NFSUNLOCKV4ROOTMUTEX();
				error = NFSERR_PERM;
				goto out;
			}
		}
		error = -1;
		goto out;
	}

	NFSUNLOCKSTATE();
	/*
	 * Ok, we can delete the expired delegation.
	 * First, write the Revoke record to stable storage and then
	 * clear out the conflict.
	 * Since all other nfsd threads are now blocked, we can safely
	 * sleep without the state changing.
	 */
	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
	nfsrv_backupstable();
	if (clp->lc_expiry < NFSD_MONOSEC) {
		nfsrv_cleanclient(clp, p);
		nfsrv_freedeleglist(&clp->lc_deleg);
		nfsrv_freedeleglist(&clp->lc_olddeleg);
		LIST_REMOVE(clp, lc_hash);
		zapped_clp = 1;
	} else {
		nfsrv_freedeleg(stp);
		zapped_clp = 0;
	}
	if (zapped_clp)
		nfsrv_zapclient(clp, p);
	error = -1;

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Check for a remove allowed, if remove is set to 1 and get rid of
 * delegations.
 */
APPLESTATIC int
nfsrv_checkremove(vnode_t vp, int remove, NFSPROC_T *p)
{
	struct nfsstate *stp;
	struct nfslockfile *lfp;
	int error, haslock = 0;
	fhandle_t nfh;

	/*
	 * First, get the lock file structure.
	 * (A return of -1 means no associated state, so remove ok.)
	 */
	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
tryagain:
	NFSLOCKSTATE();
	if (!error)
		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
	if (error) {
		NFSUNLOCKSTATE();
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		if (error == -1)
			error = 0;
		goto out;
	}

	/*
	 * Now, we must Recall any delegations.
	 */
	error = nfsrv_cleandeleg(vp, lfp, NULL, &haslock, p);
	if (error) {
		/*
		 * nfsrv_cleandeleg() unlocks state for non-zero
		 * return.
		 */
		if (error == -1)
			goto tryagain;
		if (haslock) {
			NFSLOCKV4ROOTMUTEX();
			nfsv4_unlock(&nfsv4rootfs_lock, 1);
			NFSUNLOCKV4ROOTMUTEX();
		}
		goto out;
	}

	/*
	 * Now, look for a conflicting open share.
	 */
	if (remove) {
		/*
		 * If the entry in the directory was the last reference to the
		 * corresponding filesystem object, the object can be destroyed
		 * */
		if(lfp->lf_usecount>1)
			LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
				if (stp->ls_flags & NFSLCK_WRITEDENY) {
					error = NFSERR_FILEOPEN;
					break;
				}
			}
	}

	NFSUNLOCKSTATE();
	if (haslock) {
		NFSLOCKV4ROOTMUTEX();
		nfsv4_unlock(&nfsv4rootfs_lock, 1);
		NFSUNLOCKV4ROOTMUTEX();
	}

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Clear out all delegations for the file referred to by lfp.
 * May return NFSERR_DELAY, if there will be a delay waiting for
 * delegations to expire.
 * Returns -1 to indicate it slept while recalling a delegation.
 * This function has the side effect of deleting the nfslockfile structure,
 * if it no longer has associated state and didn't have to sleep.
 * Unlocks State before a non-zero value is returned.
 */
static int
nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
    struct nfsclient *clp, int *haslockp, NFSPROC_T *p)
{
	struct nfsstate *stp, *nstp;
	int ret = 0;

	stp = LIST_FIRST(&lfp->lf_deleg);
	while (stp != NULL) {
		nstp = LIST_NEXT(stp, ls_file);
		if (stp->ls_clp != clp) {
			ret = nfsrv_delegconflict(stp, haslockp, p, vp);
			if (ret) {
				/*
				 * nfsrv_delegconflict() unlocks state
				 * when it returns non-zero.
				 */
				goto out;
			}
		}
		stp = nstp;
	}
out:
	NFSEXITCODE(ret);
	return (ret);
}

/*
 * There are certain operations that, when being done outside of NFSv4,
 * require that any NFSv4 delegation for the file be recalled.
 * This function is to be called for those cases:
 * VOP_RENAME() - When a delegation is being recalled for any reason,
 *	the client may have to do Opens against the server, using the file's
 *	final component name. If the file has been renamed on the server,
 *	that component name will be incorrect and the Open will fail.
 * VOP_REMOVE() - Theoretically, a client could Open a file after it has
 *	been removed on the server, if there is a delegation issued to
 *	that client for the file. I say "theoretically" since clients
 *	normally do an Access Op before the Open and that Access Op will
 *	fail with ESTALE. Note that NFSv2 and 3 don't even do Opens, so
 *	they will detect the file's removal in the same manner. (There is
 *	one case where RFC3530 allows a client to do an Open without first
 *	doing an Access Op, which is passage of a check against the ACE
 *	returned with a Write delegation, but current practice is to ignore
 *	the ACE and always do an Access Op.)
 *	Since the functions can only be called with an unlocked vnode, this
 *	can't be done at this time.
 * VOP_ADVLOCK() - When a client holds a delegation, it can issue byte range
 *	locks locally in the client, which are not visible to the server. To
 *	deal with this, issuing of delegations for a vnode must be disabled
 *	and all delegations for the vnode recalled. This is done via the
 *	second function, using the VV_DISABLEDELEG vflag on the vnode.
 */
APPLESTATIC void
nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
{
	time_t starttime;
	int error;

	/*
	 * First, check to see if the server is currently running and it has
	 * been called for a regular file when issuing delegations.
	 */
	if (newnfs_numnfsd == 0 || vp->v_type != VREG ||
	    nfsrv_issuedelegs == 0)
		return;

	KASSERT((NFSVOPISLOCKED(vp) != LK_EXCLUSIVE), ("vp %p is locked", vp));
	/*
	 * First, get a reference on the nfsv4rootfs_lock so that an
	 * exclusive lock cannot be acquired by another thread.
	 */
	NFSLOCKV4ROOTMUTEX();
	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
	NFSUNLOCKV4ROOTMUTEX();

	/*
	 * Now, call nfsrv_checkremove() in a loop while it returns
	 * NFSERR_DELAY. Return upon any other error or when timed out.
	 */
	starttime = NFSD_MONOSEC;
	do {
		if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
			error = nfsrv_checkremove(vp, 0, p);
			NFSVOPUNLOCK(vp, 0);
		} else
			error = EPERM;
		if (error == NFSERR_DELAY) {
			if (NFSD_MONOSEC - starttime > NFS_REMOVETIMEO)
				break;
			/* Sleep for a short period of time */
			(void) nfs_catnap(PZERO, 0, "nfsremove");
		}
	} while (error == NFSERR_DELAY);
	NFSLOCKV4ROOTMUTEX();
	nfsv4_relref(&nfsv4rootfs_lock);
	NFSUNLOCKV4ROOTMUTEX();
}

APPLESTATIC void
nfsd_disabledelegation(vnode_t vp, NFSPROC_T *p)
{

#ifdef VV_DISABLEDELEG
	/*
	 * First, flag issuance of delegations disabled.
	 */
	atomic_set_long(&vp->v_vflag, VV_DISABLEDELEG);
#endif

	/*
	 * Then call nfsd_recalldelegation() to get rid of all extant
	 * delegations.
	 */
	nfsd_recalldelegation(vp, p);
}

/*
 * Check for conflicting locks, etc. and then get rid of delegations.
 * (At one point I thought that I should get rid of delegations for any
 *  Setattr, since it could potentially disallow the I/O op (read or write)
 *  allowed by the delegation. However, Setattr Ops that aren't changing
 *  the size get a stateid of all 0s, so you can't tell if it is a delegation
 *  for the same client or a different one, so I decided to only get rid
 *  of delegations for other clients when the size is being changed.)
 * In general, a Setattr can disable NFS I/O Ops that are outstanding, such
 * as Write backs, even if there is no delegation, so it really isn't any
 * different?)
 */
APPLESTATIC int
nfsrv_checksetattr(vnode_t vp, struct nfsrv_descript *nd,
    nfsv4stateid_t *stateidp, struct nfsvattr *nvap, nfsattrbit_t *attrbitp,
    struct nfsexstuff *exp, NFSPROC_T *p)
{
	struct nfsstate st, *stp = &st;
	struct nfslock lo, *lop = &lo;
	int error = 0;
	nfsquad_t clientid;

	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE)) {
		stp->ls_flags = (NFSLCK_CHECK | NFSLCK_WRITEACCESS);
		lop->lo_first = nvap->na_size;
	} else {
		stp->ls_flags = 0;
		lop->lo_first = 0;
	}
	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNER) ||
	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNERGROUP) ||
	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_MODE) ||
	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL))
		stp->ls_flags |= NFSLCK_SETATTR;
	if (stp->ls_flags == 0)
		goto out;
	lop->lo_end = NFS64BITSSET;
	lop->lo_flags = NFSLCK_WRITE;
	stp->ls_ownerlen = 0;
	stp->ls_op = NULL;
	stp->ls_uid = nd->nd_cred->cr_uid;
	stp->ls_stateid.seqid = stateidp->seqid;
	clientid.lval[0] = stp->ls_stateid.other[0] = stateidp->other[0];
	clientid.lval[1] = stp->ls_stateid.other[1] = stateidp->other[1];
	stp->ls_stateid.other[2] = stateidp->other[2];
	error = nfsrv_lockctrl(vp, &stp, &lop, NULL, clientid,
	    stateidp, exp, nd, p);

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * Check for a write delegation and do a CBGETATTR if there is one, updating
 * the attributes, as required.
 * Should I return an error if I can't get the attributes? (For now, I'll
 * just return ok.
 */
APPLESTATIC int
nfsrv_checkgetattr(struct nfsrv_descript *nd, vnode_t vp,
    struct nfsvattr *nvap, nfsattrbit_t *attrbitp, struct ucred *cred,
    NFSPROC_T *p)
{
	struct nfsstate *stp;
	struct nfslockfile *lfp;
	struct nfsclient *clp;
	struct nfsvattr nva;
	fhandle_t nfh;
	int error = 0;
	nfsattrbit_t cbbits;
	u_quad_t delegfilerev;

	NFSCBGETATTR_ATTRBIT(attrbitp, &cbbits);
	if (!NFSNONZERO_ATTRBIT(&cbbits))
		goto out;

	/*
	 * Get the lock file structure.
	 * (A return of -1 means no associated state, so return ok.)
	 */
	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
	NFSLOCKSTATE();
	if (!error)
		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
	if (error) {
		NFSUNLOCKSTATE();
		if (error == -1)
			error = 0;
		goto out;
	}

	/*
	 * Now, look for a write delegation.
	 */
	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
		if (stp->ls_flags & NFSLCK_DELEGWRITE)
			break;
	}
	if (stp == NULL) {
		NFSUNLOCKSTATE();
		goto out;
	}
	clp = stp->ls_clp;
	delegfilerev = stp->ls_filerev;

	/*
	 * If the Write delegation was issued as a part of this Compound RPC
	 * or if we have an Implied Clientid (used in a previous Op in this
	 * compound) and it is the client the delegation was issued to,
	 * just return ok.
	 * I also assume that it is from the same client iff the network
	 * host IP address is the same as the callback address. (Not
	 * exactly correct by the RFC, but avoids a lot of Getattr
	 * callbacks.)
	 */
	if (nd->nd_compref == stp->ls_compref ||
	    ((nd->nd_flag & ND_IMPLIEDCLID) &&
	     clp->lc_clientid.qval == nd->nd_clientid.qval) ||
	     nfsaddr2_match(clp->lc_req.nr_nam, nd->nd_nam)) {
		NFSUNLOCKSTATE();
		goto out;
	}

	/*
	 * We are now done with the delegation state structure,
	 * so the statelock can be released and we can now tsleep().
	 */

	/*
	 * Now, we must do the CB Getattr callback, to see if Change or Size
	 * has changed.
	 */
	if (clp->lc_expiry >= NFSD_MONOSEC) {
		NFSUNLOCKSTATE();
		NFSVNO_ATTRINIT(&nva);
		nva.na_filerev = NFS64BITSSET;
		error = nfsrv_docallback(clp, NFSV4OP_CBGETATTR, NULL,
		    0, &nfh, &nva, &cbbits, p);
		if (!error) {
			if ((nva.na_filerev != NFS64BITSSET &&
			    nva.na_filerev > delegfilerev) ||
			    (NFSVNO_ISSETSIZE(&nva) &&
			     nva.na_size != nvap->na_size)) {
				error = nfsvno_updfilerev(vp, nvap, cred, p);
				if (NFSVNO_ISSETSIZE(&nva))
					nvap->na_size = nva.na_size;
			}
		} else
			error = 0;	/* Ignore callback errors for now. */
	} else {
		NFSUNLOCKSTATE();
	}

out:
	NFSEXITCODE2(error, nd);
	return (error);
}

/*
 * This function looks for openowners that haven't had any opens for
 * a while and throws them away. Called by an nfsd when NFSNSF_NOOPENS
 * is set.
 */
APPLESTATIC void
nfsrv_throwawayopens(NFSPROC_T *p)
{
	struct nfsclient *clp, *nclp;
	struct nfsstate *stp, *nstp;
	int i;

	NFSLOCKSTATE();
	nfsrv_stablefirst.nsf_flags &= ~NFSNSF_NOOPENS;
	/*
	 * For each client...
	 */
	for (i = 0; i < nfsrv_clienthashsize; i++) {
	    LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
		LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp) {
			if (LIST_EMPTY(&stp->ls_open) &&
			    (stp->ls_noopens > NFSNOOPEN ||
			     (nfsrv_openpluslock * 2) >
			     nfsrv_v4statelimit))
				nfsrv_freeopenowner(stp, 0, p);
		}
	    }
	}
	NFSUNLOCKSTATE();
}

/*
 * This function checks to see if the credentials are the same.
 * Returns 1 for not same, 0 otherwise.
 */
static int
nfsrv_notsamecredname(struct nfsrv_descript *nd, struct nfsclient *clp)
{

	if (nd->nd_flag & ND_GSS) {
		if (!(clp->lc_flags & LCL_GSS))
			return (1);
		if (clp->lc_flags & LCL_NAME) {
			if (nd->nd_princlen != clp->lc_namelen ||
			    NFSBCMP(nd->nd_principal, clp->lc_name,
				clp->lc_namelen))
				return (1);
			else
				return (0);
		}
		if (nd->nd_cred->cr_uid == clp->lc_uid)
			return (0);
		else
			return (1);
	} else if (clp->lc_flags & LCL_GSS)
		return (1);
	/*
	 * For AUTH_SYS, allow the same uid or root. (This is underspecified
	 * in RFC3530, which talks about principals, but doesn't say anything
	 * about uids for AUTH_SYS.)
	 */
	if (nd->nd_cred->cr_uid == clp->lc_uid || nd->nd_cred->cr_uid == 0)
		return (0);
	else
		return (1);
}

/*
 * Calculate the lease expiry time.
 */
static time_t
nfsrv_leaseexpiry(void)
{

	if (nfsrv_stablefirst.nsf_eograce > NFSD_MONOSEC)
		return (NFSD_MONOSEC + 2 * (nfsrv_lease + NFSRV_LEASEDELTA));
	return (NFSD_MONOSEC + nfsrv_lease + NFSRV_LEASEDELTA);
}

/*
 * Delay the delegation timeout as far as ls_delegtimelimit, as required.
 */
static void
nfsrv_delaydelegtimeout(struct nfsstate *stp)
{

	if ((stp->ls_flags & NFSLCK_DELEGRECALL) == 0)
		return;

	if ((stp->ls_delegtime + 15) > NFSD_MONOSEC &&
	    stp->ls_delegtime < stp->ls_delegtimelimit) {
		stp->ls_delegtime += nfsrv_lease;
		if (stp->ls_delegtime > stp->ls_delegtimelimit)
			stp->ls_delegtime = stp->ls_delegtimelimit;
	}
}

/*
 * This function checks to see if there is any other state associated
 * with the openowner for this Open.
 * It returns 1 if there is no other state, 0 otherwise.
 */
static int
nfsrv_nootherstate(struct nfsstate *stp)
{
	struct nfsstate *tstp;

	LIST_FOREACH(tstp, &stp->ls_openowner->ls_open, ls_list) {
		if (tstp != stp || !LIST_EMPTY(&tstp->ls_lock))
			return (0);
	}
	return (1);
}

/*
 * Create a list of lock deltas (changes to local byte range locking
 * that can be rolled back using the list) and apply the changes via
 * nfsvno_advlock(). Optionally, lock the list. It is expected that either
 * the rollback or update function will be called after this.
 * It returns an error (and rolls back, as required), if any nfsvno_advlock()
 * call fails. If it returns an error, it will unlock the list.
 */
static int
nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
    uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
{
	struct nfslock *lop, *nlop;
	int error = 0;

	/* Loop through the list of locks. */
	lop = LIST_FIRST(&lfp->lf_locallock);
	while (first < end && lop != NULL) {
		nlop = LIST_NEXT(lop, lo_lckowner);
		if (first >= lop->lo_end) {
			/* not there yet */
			lop = nlop;
		} else if (first < lop->lo_first) {
			/* new one starts before entry in list */
			if (end <= lop->lo_first) {
				/* no overlap between old and new */
				error = nfsrv_dolocal(vp, lfp, flags,
				    NFSLCK_UNLOCK, first, end, cfp, p);
				if (error != 0)
					break;
				first = end;
			} else {
				/* handle fragment overlapped with new one */
				error = nfsrv_dolocal(vp, lfp, flags,
				    NFSLCK_UNLOCK, first, lop->lo_first, cfp,
				    p);
				if (error != 0)
					break;
				first = lop->lo_first;
			}
		} else {
			/* new one overlaps this entry in list */
			if (end <= lop->lo_end) {
				/* overlaps all of new one */
				error = nfsrv_dolocal(vp, lfp, flags,
				    lop->lo_flags, first, end, cfp, p);
				if (error != 0)
					break;
				first = end;
			} else {
				/* handle fragment overlapped with new one */
				error = nfsrv_dolocal(vp, lfp, flags,
				    lop->lo_flags, first, lop->lo_end, cfp, p);
				if (error != 0)
					break;
				first = lop->lo_end;
				lop = nlop;
			}
		}
	}
	if (first < end && error == 0)
		/* handle fragment past end of list */
		error = nfsrv_dolocal(vp, lfp, flags, NFSLCK_UNLOCK, first,
		    end, cfp, p);

	NFSEXITCODE(error);
	return (error);
}

/*
 * Local lock unlock. Unlock all byte ranges that are no longer locked
 * by NFSv4. To do this, unlock any subranges of first-->end that
 * do not overlap with the byte ranges of any lock in the lfp->lf_lock
 * list. This list has all locks for the file held by other
 * <clientid, lockowner> tuples. The list is ordered by increasing
 * lo_first value, but may have entries that overlap each other, for
 * the case of read locks.
 */
static void
nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp, uint64_t init_first,
    uint64_t init_end, NFSPROC_T *p)
{
	struct nfslock *lop;
	uint64_t first, end, prevfirst;

	first = init_first;
	end = init_end;
	while (first < init_end) {
		/* Loop through all nfs locks, adjusting first and end */
		prevfirst = 0;
		LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
			KASSERT(prevfirst <= lop->lo_first,
			    ("nfsv4 locks out of order"));
			KASSERT(lop->lo_first < lop->lo_end,
			    ("nfsv4 bogus lock"));
			prevfirst = lop->lo_first;
			if (first >= lop->lo_first &&
			    first < lop->lo_end)
				/*
				 * Overlaps with initial part, so trim
				 * off that initial part by moving first past
				 * it.
				 */
				first = lop->lo_end;
			else if (end > lop->lo_first &&
			    lop->lo_first > first) {
				/*
				 * This lock defines the end of the
				 * segment to unlock, so set end to the
				 * start of it and break out of the loop.
				 */
				end = lop->lo_first;
				break;
			}
			if (first >= end)
				/*
				 * There is no segment left to do, so
				 * break out of this loop and then exit
				 * the outer while() since first will be set
				 * to end, which must equal init_end here.
				 */
				break;
		}
		if (first < end) {
			/* Unlock this segment */
			(void) nfsrv_dolocal(vp, lfp, NFSLCK_UNLOCK,
			    NFSLCK_READ, first, end, NULL, p);
			nfsrv_locallock_commit(lfp, NFSLCK_UNLOCK,
			    first, end);
		}
		/*
		 * Now move past this segment and look for any further
		 * segment in the range, if there is one.
		 */
		first = end;
		end = init_end;
	}
}

/*
 * Do the local lock operation and update the rollback list, as required.
 * Perform the rollback and return the error if nfsvno_advlock() fails.
 */
static int
nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags, int oldflags,
    uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
{
	struct nfsrollback *rlp;
	int error = 0, ltype, oldltype;

	if (flags & NFSLCK_WRITE)
		ltype = F_WRLCK;
	else if (flags & NFSLCK_READ)
		ltype = F_RDLCK;
	else
		ltype = F_UNLCK;
	if (oldflags & NFSLCK_WRITE)
		oldltype = F_WRLCK;
	else if (oldflags & NFSLCK_READ)
		oldltype = F_RDLCK;
	else
		oldltype = F_UNLCK;
	if (ltype == oldltype || (oldltype == F_WRLCK && ltype == F_RDLCK))
		/* nothing to do */
		goto out;
	error = nfsvno_advlock(vp, ltype, first, end, p);
	if (error != 0) {
		if (cfp != NULL) {
			cfp->cl_clientid.lval[0] = 0;
			cfp->cl_clientid.lval[1] = 0;
			cfp->cl_first = 0;
			cfp->cl_end = NFS64BITSSET;
			cfp->cl_flags = NFSLCK_WRITE;
			cfp->cl_ownerlen = 5;
			NFSBCOPY("LOCAL", cfp->cl_owner, 5);
		}
		nfsrv_locallock_rollback(vp, lfp, p);
	} else if (ltype != F_UNLCK) {
		rlp = malloc(sizeof (struct nfsrollback), M_NFSDROLLBACK,
		    M_WAITOK);
		rlp->rlck_first = first;
		rlp->rlck_end = end;
		rlp->rlck_type = oldltype;
		LIST_INSERT_HEAD(&lfp->lf_rollback, rlp, rlck_list);
	}

out:
	NFSEXITCODE(error);
	return (error);
}

/*
 * Roll back local lock changes and free up the rollback list.
 */
static void
nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp, NFSPROC_T *p)
{
	struct nfsrollback *rlp, *nrlp;

	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp) {
		(void) nfsvno_advlock(vp, rlp->rlck_type, rlp->rlck_first,
		    rlp->rlck_end, p);
		free(rlp, M_NFSDROLLBACK);
	}
	LIST_INIT(&lfp->lf_rollback);
}

/*
 * Update local lock list and delete rollback list (ie now committed to the
 * local locks). Most of the work is done by the internal function.
 */
static void
nfsrv_locallock_commit(struct nfslockfile *lfp, int flags, uint64_t first,
    uint64_t end)
{
	struct nfsrollback *rlp, *nrlp;
	struct nfslock *new_lop, *other_lop;

	new_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK, M_WAITOK);
	if (flags & (NFSLCK_READ | NFSLCK_WRITE))
		other_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK,
		    M_WAITOK);
	else
		other_lop = NULL;
	new_lop->lo_flags = flags;
	new_lop->lo_first = first;
	new_lop->lo_end = end;
	nfsrv_updatelock(NULL, &new_lop, &other_lop, lfp);
	if (new_lop != NULL)
		free(new_lop, M_NFSDLOCK);
	if (other_lop != NULL)
		free(other_lop, M_NFSDLOCK);

	/* and get rid of the rollback list */
	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp)
		free(rlp, M_NFSDROLLBACK);
	LIST_INIT(&lfp->lf_rollback);
}

/*
 * Lock the struct nfslockfile for local lock updating.
 */
static void
nfsrv_locklf(struct nfslockfile *lfp)
{
	int gotlock;

	/* lf_usecount ensures *lfp won't be free'd */
	lfp->lf_usecount++;
	do {
		gotlock = nfsv4_lock(&lfp->lf_locallock_lck, 1, NULL,
		    NFSSTATEMUTEXPTR, NULL);
	} while (gotlock == 0);
	lfp->lf_usecount--;
}

/*
 * Unlock the struct nfslockfile after local lock updating.
 */
static void
nfsrv_unlocklf(struct nfslockfile *lfp)
{

	nfsv4_unlock(&lfp->lf_locallock_lck, 0);
}

/*
 * Clear out all state for the NFSv4 server.
 * Must be called by a thread that can sleep when no nfsds are running.
 */
void
nfsrv_throwawayallstate(NFSPROC_T *p)
{
	struct nfsclient *clp, *nclp;
	struct nfslockfile *lfp, *nlfp;
	int i;

	/*
	 * For each client, clean out the state and then free the structure.
	 */
	for (i = 0; i < nfsrv_clienthashsize; i++) {
		LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
			nfsrv_cleanclient(clp, p);
			nfsrv_freedeleglist(&clp->lc_deleg);
			nfsrv_freedeleglist(&clp->lc_olddeleg);
			free(clp->lc_stateid, M_NFSDCLIENT);
			free(clp, M_NFSDCLIENT);
		}
	}

	/*
	 * Also, free up any remaining lock file structures.
	 */
	for (i = 0; i < nfsrv_lockhashsize; i++) {
		LIST_FOREACH_SAFE(lfp, &nfslockhash[i], lf_hash, nlfp) {
			printf("nfsd unload: fnd a lock file struct\n");
			nfsrv_freenfslockfile(lfp);
		}
	}
}

/*
 * Check the sequence# for the session and slot provided as an argument.
 * Also, renew the lease if the session will return NFS_OK.
 */
int
nfsrv_checksequence(struct nfsrv_descript *nd, uint32_t sequenceid,
    uint32_t *highest_slotidp, uint32_t *target_highest_slotidp, int cache_this,
    uint32_t *sflagsp, NFSPROC_T *p)
{
	struct nfsdsession *sep;
	struct nfssessionhash *shp;
	int error;
	SVCXPRT *savxprt;

	shp = NFSSESSIONHASH(nd->nd_sessionid);
	NFSLOCKSESSION(shp);
	sep = nfsrv_findsession(nd->nd_sessionid);
	if (sep == NULL) {
		NFSUNLOCKSESSION(shp);
		return (NFSERR_BADSESSION);
	}
	error = nfsv4_seqsession(sequenceid, nd->nd_slotid, *highest_slotidp,
	    sep->sess_slots, NULL, NFSV4_SLOTS - 1);
	if (error != 0) {
		NFSUNLOCKSESSION(shp);
		return (error);
	}
	if (cache_this != 0)
		nd->nd_flag |= ND_SAVEREPLY;
	/* Renew the lease. */
	sep->sess_clp->lc_expiry = nfsrv_leaseexpiry();
	nd->nd_clientid.qval = sep->sess_clp->lc_clientid.qval;
	nd->nd_flag |= ND_IMPLIEDCLID;

	/*
	 * If this session handles the backchannel, save the nd_xprt for this
	 * RPC, since this is the one being used.
	 */
	if (sep->sess_clp->lc_req.nr_client != NULL &&
	    (sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0) {
		savxprt = sep->sess_cbsess.nfsess_xprt;
		SVC_ACQUIRE(nd->nd_xprt);
		nd->nd_xprt->xp_p2 =
		    sep->sess_clp->lc_req.nr_client->cl_private;
		nd->nd_xprt->xp_idletimeout = 0;	/* Disable timeout. */
		sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
		if (savxprt != NULL)
			SVC_RELEASE(savxprt);
	}

	*sflagsp = 0;
	if (sep->sess_clp->lc_req.nr_client == NULL)
		*sflagsp |= NFSV4SEQ_CBPATHDOWN;
	NFSUNLOCKSESSION(shp);
	if (error == NFSERR_EXPIRED) {
		*sflagsp |= NFSV4SEQ_EXPIREDALLSTATEREVOKED;
		error = 0;
	} else if (error == NFSERR_ADMINREVOKED) {
		*sflagsp |= NFSV4SEQ_ADMINSTATEREVOKED;
		error = 0;
	}
	*highest_slotidp = *target_highest_slotidp = NFSV4_SLOTS - 1;
	return (0);
}

/*
 * Check/set reclaim complete for this session/clientid.
 */
int
nfsrv_checkreclaimcomplete(struct nfsrv_descript *nd)
{
	struct nfsdsession *sep;
	struct nfssessionhash *shp;
	int error = 0;

	shp = NFSSESSIONHASH(nd->nd_sessionid);
	NFSLOCKSTATE();
	NFSLOCKSESSION(shp);
	sep = nfsrv_findsession(nd->nd_sessionid);
	if (sep == NULL) {
		NFSUNLOCKSESSION(shp);
		NFSUNLOCKSTATE();
		return (NFSERR_BADSESSION);
	}

	/* Check to see if reclaim complete has already happened. */
	if ((sep->sess_clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0)
		error = NFSERR_COMPLETEALREADY;
	else
		sep->sess_clp->lc_flags |= LCL_RECLAIMCOMPLETE;
	NFSUNLOCKSESSION(shp);
	NFSUNLOCKSTATE();
	return (error);
}

/*
 * Cache the reply in a session slot.
 */
void
nfsrv_cache_session(uint8_t *sessionid, uint32_t slotid, int repstat,
   struct mbuf **m)
{
	struct nfsdsession *sep;
	struct nfssessionhash *shp;

	shp = NFSSESSIONHASH(sessionid);
	NFSLOCKSESSION(shp);
	sep = nfsrv_findsession(sessionid);
	if (sep == NULL) {
		NFSUNLOCKSESSION(shp);
		printf("nfsrv_cache_session: no session\n");
		m_freem(*m);
		return;
	}
	nfsv4_seqsess_cacherep(slotid, sep->sess_slots, repstat, m);
	NFSUNLOCKSESSION(shp);
}

/*
 * Search for a session that matches the sessionid.
 */
static struct nfsdsession *
nfsrv_findsession(uint8_t *sessionid)
{
	struct nfsdsession *sep;
	struct nfssessionhash *shp;

	shp = NFSSESSIONHASH(sessionid);
	LIST_FOREACH(sep, &shp->list, sess_hash) {
		if (!NFSBCMP(sessionid, sep->sess_sessionid, NFSX_V4SESSIONID))
			break;
	}
	return (sep);
}

/*
 * Destroy a session.
 */
int
nfsrv_destroysession(struct nfsrv_descript *nd, uint8_t *sessionid)
{
	int error, samesess;

	samesess = 0;
	if (!NFSBCMP(sessionid, nd->nd_sessionid, NFSX_V4SESSIONID)) {
		samesess = 1;
		if ((nd->nd_flag & ND_LASTOP) == 0)
			return (NFSERR_BADSESSION);
	}
	error = nfsrv_freesession(NULL, sessionid);
	if (error == 0 && samesess != 0)
		nd->nd_flag &= ~ND_HASSEQUENCE;
	return (error);
}

/*
 * Free up a session structure.
 */
static int
nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid)
{
	struct nfssessionhash *shp;
	int i;

	NFSLOCKSTATE();
	if (sep == NULL) {
		shp = NFSSESSIONHASH(sessionid);
		NFSLOCKSESSION(shp);
		sep = nfsrv_findsession(sessionid);
	} else {
		shp = NFSSESSIONHASH(sep->sess_sessionid);
		NFSLOCKSESSION(shp);
	}
	if (sep != NULL) {
		sep->sess_refcnt--;
		if (sep->sess_refcnt > 0) {
			NFSUNLOCKSESSION(shp);
			NFSUNLOCKSTATE();
			return (0);
		}
		LIST_REMOVE(sep, sess_hash);
		LIST_REMOVE(sep, sess_list);
	}
	NFSUNLOCKSESSION(shp);
	NFSUNLOCKSTATE();
	if (sep == NULL)
		return (NFSERR_BADSESSION);
	for (i = 0; i < NFSV4_SLOTS; i++)
		if (sep->sess_slots[i].nfssl_reply != NULL)
			m_freem(sep->sess_slots[i].nfssl_reply);
	if (sep->sess_cbsess.nfsess_xprt != NULL)
		SVC_RELEASE(sep->sess_cbsess.nfsess_xprt);
	free(sep, M_NFSDSESSION);
	return (0);
}

/*
 * Free a stateid.
 * RFC5661 says that it should fail when there are associated opens, locks
 * or delegations. Since stateids represent opens, I don't see how you can
 * free an open stateid (it will be free'd when closed), so this function
 * only works for lock stateids (freeing the lock_owner) or delegations.
 */
int
nfsrv_freestateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
    NFSPROC_T *p)
{
	struct nfsclient *clp;
	struct nfsstate *stp;
	int error;

	NFSLOCKSTATE();
	/*
	 * Look up the stateid
	 */
	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
	if (error == 0) {
		/* First, check for a delegation. */
		LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
			if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
			    NFSX_STATEIDOTHER))
				break;
		}
		if (stp != NULL) {
			nfsrv_freedeleg(stp);
			NFSUNLOCKSTATE();
			return (error);
		}
	}
	/* Not a delegation, try for a lock_owner. */
	if (error == 0)
		error = nfsrv_getstate(clp, stateidp, 0, &stp);
	if (error == 0 && ((stp->ls_flags & (NFSLCK_OPEN | NFSLCK_DELEGREAD |
	    NFSLCK_DELEGWRITE)) != 0 || (stp->ls_flags & NFSLCK_LOCK) == 0))
		/* Not a lock_owner stateid. */
		error = NFSERR_LOCKSHELD;
	if (error == 0 && !LIST_EMPTY(&stp->ls_lock))
		error = NFSERR_LOCKSHELD;
	if (error == 0)
		nfsrv_freelockowner(stp, NULL, 0, p);
	NFSUNLOCKSTATE();
	return (error);
}

/*
 * Generate the xdr for an NFSv4.1 CBSequence Operation.
 */
static int
nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
    int dont_replycache, struct nfsdsession **sepp)
{
	struct nfsdsession *sep;
	uint32_t *tl, slotseq = 0;
	int maxslot, slotpos;
	uint8_t sessionid[NFSX_V4SESSIONID];
	int error;

	error = nfsv4_getcbsession(clp, sepp);
	if (error != 0)
		return (error);
	sep = *sepp;
	(void)nfsv4_sequencelookup(NULL, &sep->sess_cbsess, &slotpos, &maxslot,
	    &slotseq, sessionid);
	KASSERT(maxslot >= 0, ("nfsv4_setcbsequence neg maxslot"));

	/* Build the Sequence arguments. */
	NFSM_BUILD(tl, uint32_t *, NFSX_V4SESSIONID + 5 * NFSX_UNSIGNED);
	bcopy(sessionid, tl, NFSX_V4SESSIONID);
	tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
	nd->nd_slotseq = tl;
	*tl++ = txdr_unsigned(slotseq);
	*tl++ = txdr_unsigned(slotpos);
	*tl++ = txdr_unsigned(maxslot);
	if (dont_replycache == 0)
		*tl++ = newnfs_true;
	else
		*tl++ = newnfs_false;
	*tl = 0;			/* No referring call list, for now. */
	nd->nd_flag |= ND_HASSEQUENCE;
	return (0);
}

/*
 * Get a session for the callback.
 */
static int
nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp)
{
	struct nfsdsession *sep;

	NFSLOCKSTATE();
	LIST_FOREACH(sep, &clp->lc_session, sess_list) {
		if ((sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0)
			break;
	}
	if (sep == NULL) {
		NFSUNLOCKSTATE();
		return (NFSERR_BADSESSION);
	}
	sep->sess_refcnt++;
	*sepp = sep;
	NFSUNLOCKSTATE();
	return (0);
}

/*
 * Free up all backchannel xprts.  This needs to be done when the nfsd threads
 * exit, since those transports will all be going away.
 * This is only called after all the nfsd threads are done performing RPCs,
 * so locking shouldn't be an issue.
 */
APPLESTATIC void
nfsrv_freeallbackchannel_xprts(void)
{
	struct nfsdsession *sep;
	struct nfsclient *clp;
	SVCXPRT *xprt;
	int i;

	for (i = 0; i < nfsrv_clienthashsize; i++) {
		LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
			LIST_FOREACH(sep, &clp->lc_session, sess_list) {
				xprt = sep->sess_cbsess.nfsess_xprt;
				sep->sess_cbsess.nfsess_xprt = NULL;
				if (xprt != NULL)
					SVC_RELEASE(xprt);
			}
		}
	}
}