DragonFlyBSD Kernel Audit
sys/kern/vfs_nlookup.c
← back
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
/*
 * Copyright (c) 2004-2022 The DragonFly Project.  All rights reserved.
 * 
 * This code is derived from software contributed to The DragonFly Project
 * by Matthew Dillon <dillon@backplane.com>
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name of The DragonFly Project nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific, prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
/*
 * nlookup() is the 'new' namei interface.  Rather then return directory and
 * leaf vnodes (in various lock states) the new interface instead deals in
 * namecache records.  Namecache records may represent both a positive or
 * a negative hit.  The namespace is locked via the namecache record instead
 * of via the vnode, and only the leaf namecache record (representing the
 * filename) needs to be locked.
 *
 * This greatly improves filesystem parallelism and is a huge simplification
 * of the API verses the old vnode locking / namei scheme.
 *
 * Filesystems must actively control the caching aspects of the namecache,
 * and since namecache pointers are used as handles they are non-optional
 * even for filesystems which do not generally wish to cache things.  It is
 * intended that a separate cache coherency API will be constructed to handle
 * these issues.
 */

#include "opt_ktrace.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/uio.h>
#include <sys/kernel.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/filedesc.h>
#include <sys/proc.h>
#include <sys/namei.h>
#include <sys/nlookup.h>
#include <sys/malloc.h>
#include <sys/stat.h>
#include <sys/objcache.h>
#include <sys/file.h>
#include <sys/kcollect.h>
#include <sys/sysctl.h>

#ifdef KTRACE
#include <sys/ktrace.h>
#endif

__read_mostly static int nlookup_max_retries = 4;
SYSCTL_INT(_debug, OID_AUTO, nlookup_max_retries, CTLFLAG_RW,
	&nlookup_max_retries, 0,
	"retries on generation mismatch");
__read_mostly static int nlookup_debug;
SYSCTL_INT(_debug, OID_AUTO, nlookup_debug, CTLFLAG_RW,
	&nlookup_debug, 0,
	"Force retry test");

static int naccess(struct nlookupdata *nd, struct nchandle *nch,
			u_int *genp, int vmode,
			struct ucred *cred, int *stickyp, int nchislocked);

/*
 * unmount operations flag NLC_IGNBADDIR in order to allow the
 * umount to successfully issue a nlookup() on the path in order
 * to extract the mount point.  Allow certain errors through.
 */
static __inline
int
keeperror(struct nlookupdata *nd, int error)
{
	if (error) {
		if ((nd->nl_flags & NLC_IGNBADDIR) == 0 ||
		   (error != EIO && error != EBADRPC && error != ESTALE)) {
			return 1;
		}
	}
	return 0;
}

/*
 * Initialize a nlookup() structure, early error return for copyin faults
 * or a degenerate empty string (which is not allowed).
 *
 * The first process proc0's credentials are used if the calling thread
 * is not associated with a process context.
 *
 * MPSAFE
 */
int
nlookup_init(struct nlookupdata *nd, 
	     const char *path, enum uio_seg seg, int flags)
{
    size_t pathlen;
    struct proc *p;
    thread_t td;
    int error;

    td = curthread;
    p = td->td_proc;

    /*
     * note: the pathlen set by copy*str() includes the terminating \0.
     */
    bzero(nd, sizeof(struct nlookupdata));
    nd->nl_path = objcache_get(namei_oc, M_WAITOK);
    nd->nl_flags |= NLC_HASBUF;
    if (seg == UIO_SYSSPACE) 
	error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
    else
	error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);

    /*
     * Don't allow empty pathnames.
     * POSIX.1 requirement: "" is not a vaild file name.
     */
    if (error == 0 && pathlen <= 1)
	error = ENOENT;

    if (error == 0) {
	if (p && p->p_fd) {
	    if (nd->nl_path[0] == '/') {
		    if ((flags & NLC_NLNCH_NOINIT) == 0) {
			    nd->nl_basench = &p->p_fd->fd_nrdir;
			    cache_copy(nd->nl_basench, &nd->nl_nch);
		    }
		    cache_copy(&p->p_fd->fd_nrdir, &nd->nl_rootnch);
		    if (p->p_fd->fd_njdir.ncp)
			cache_copy(&p->p_fd->fd_njdir, &nd->nl_jailnch);
		    nd->nl_cred = td->td_ucred;
		    nd->nl_flags |= NLC_BORROWCRED;
	    } else {
		    if ((flags & NLC_NLNCH_NOINIT) == 0) {
			    nd->nl_basench = &p->p_fd->fd_ncdir;
			    cache_copy(nd->nl_basench, &nd->nl_nch);
		    }
		    cache_copy(&p->p_fd->fd_nrdir, &nd->nl_rootnch);
		    if (p->p_fd->fd_njdir.ncp)
			cache_copy(&p->p_fd->fd_njdir, &nd->nl_jailnch);
		    nd->nl_cred = td->td_ucred;
		    nd->nl_flags |= NLC_BORROWCRED;
	    }
	} else {
	    if ((flags & NLC_NLNCH_NOINIT) == 0) {
		    nd->nl_basench = &rootnch;
		    cache_copy(nd->nl_basench, &nd->nl_nch);
	    }
	    cache_copy(&rootnch, &nd->nl_rootnch);
	    cache_copy(&rootnch, &nd->nl_jailnch);
	    nd->nl_cred = proc0.p_ucred;
	    nd->nl_flags |= NLC_BORROWCRED;
	}
	nd->nl_td = td;
	nd->nl_flags |= flags & ~NLC_NLNCH_NOINIT;
    } else {
	nlookup_done(nd);
    }
    return(error);
}


/*
 * nlookup_init() for "at" family of syscalls.
 *
 * Similar to nlookup_init() but if the path is relative and fd is not
 * AT_FDCWD, the path will be interpreted relative to the directory pointed
*  to by fd.  In this case, the file entry pointed to by fd is ref'ed and
*  returned in *fpp.
 *
 * If the call succeeds, nlookup_done_at() must be called to clean-up the nd
 * and release the ref to the file entry.
 */
int
nlookup_init_at(struct nlookupdata *nd, struct file **fpp, int fd, 
		const char *path, enum uio_seg seg, int flags)
{
	struct thread *td = curthread;
	struct file* fp;
	struct vnode *vp;
	int error;

	*fpp = NULL;

	/*
	 * Resolve the path, we might have to copy it in from userland,
	 * but don't initialize nl_basench, or nl_nch.
	 */
	error = nlookup_init(nd, path, seg, flags | NLC_NLNCH_NOINIT);
	if (__predict_false(error))
		return (error);

	/*
	 * Setup nl_basench (a pointer only not refd), and copy+ref
	 * to initialize nl_nch.  Only applicable to relative paths.
	 * For absolute paths, or if (fd) is degenerate, just use the
	 * normal path.
	 */
	if (nd->nl_path[0] == '/') {
		struct proc *p = curproc;
		nd->nl_basench = &p->p_fd->fd_nrdir;
	} else if (fd == AT_FDCWD) {
		struct proc *p = curproc;
		nd->nl_basench = &p->p_fd->fd_ncdir;
	} else {
		if ((error = holdvnode(td, fd, &fp)) != 0)
			goto done;
		vp = (struct vnode*)fp->f_data;
		if (vp->v_type != VDIR || fp->f_nchandle.ncp == NULL) {
			fdrop(fp);
			fp = NULL;
			error = ENOTDIR;
			goto done;
		}
		nd->nl_basench = &fp->f_nchandle;
		*fpp = fp;
	}
	cache_copy(nd->nl_basench, &nd->nl_nch);
done:
	if (error)
		nlookup_done(nd);
	return (error);
}

/*
 * This works similarly to nlookup_init() but does not assume a process
 * context.  rootnch is always chosen for the root directory and the cred
 * and starting directory are supplied in arguments.
 */
int
nlookup_init_raw(struct nlookupdata *nd, 
	     const char *path, enum uio_seg seg, int flags,
	     struct ucred *cred, struct nchandle *ncstart)
{
    size_t pathlen;
    thread_t td;
    int error;

    td = curthread;

    bzero(nd, sizeof(struct nlookupdata));
    nd->nl_path = objcache_get(namei_oc, M_WAITOK);
    nd->nl_flags |= NLC_HASBUF;
    if (seg == UIO_SYSSPACE) 
	error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
    else
	error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);

    /*
     * Don't allow empty pathnames.
     * POSIX.1 requirement: "" is not a vaild file name.
     */
    if (error == 0 && pathlen <= 1)
	error = ENOENT;

    if (error == 0) {
	cache_copy(ncstart, &nd->nl_nch);
	cache_copy(&rootnch, &nd->nl_rootnch);
	cache_copy(&rootnch, &nd->nl_jailnch);
	nd->nl_cred = crhold(cred);
	nd->nl_td = td;
	nd->nl_flags |= flags;
    } else {
	nlookup_done(nd);
    }
    return(error);
}

/*
 * This works similarly to nlookup_init_raw() but does not rely
 * on rootnch being initialized yet.
 */
int
nlookup_init_root(struct nlookupdata *nd, 
	     const char *path, enum uio_seg seg, int flags,
	     struct ucred *cred, struct nchandle *ncstart,
	     struct nchandle *ncroot)
{
    size_t pathlen;
    thread_t td;
    int error;

    td = curthread;

    bzero(nd, sizeof(struct nlookupdata));
    nd->nl_path = objcache_get(namei_oc, M_WAITOK);
    nd->nl_flags |= NLC_HASBUF;
    if (seg == UIO_SYSSPACE) 
	error = copystr(path, nd->nl_path, MAXPATHLEN, &pathlen);
    else
	error = copyinstr(path, nd->nl_path, MAXPATHLEN, &pathlen);

    /*
     * Don't allow empty pathnames.
     * POSIX.1 requirement: "" is not a vaild file name.
     */
    if (error == 0 && pathlen <= 1)
	error = ENOENT;

    if (error == 0) {
	cache_copy(ncstart, &nd->nl_nch);
	cache_copy(ncroot, &nd->nl_rootnch);
	cache_copy(ncroot, &nd->nl_jailnch);
	nd->nl_cred = crhold(cred);
	nd->nl_td = td;
	nd->nl_flags |= flags;
    } else {
	nlookup_done(nd);
    }
    return(error);
}

#if 0
/*
 * Set a different credential; this credential will be used by future
 * operations performed on nd.nl_open_vp and nlookupdata structure.
 */
void
nlookup_set_cred(struct nlookupdata *nd, struct ucred *cred)
{
	KKASSERT(nd->nl_cred != NULL);

	if (nd->nl_cred != cred) {
		cred = crhold(cred);
		if ((nd->nl_flags & NLC_BORROWCRED) == 0)
			crfree(nd->nl_cred);
		nd->nl_flags &= ~NLC_BORROWCRED;
		nd->nl_cred = cred;
	}
}
#endif

/*
 * Cleanup a nlookupdata structure after we are through with it.  This may
 * be called on any nlookupdata structure initialized with nlookup_init().
 * Calling nlookup_done() is mandatory in all cases except where nlookup_init()
 * returns an error, even if as a consumer you believe you have taken all
 * dynamic elements out of the nlookupdata structure.
 */
void
nlookup_done(struct nlookupdata *nd)
{
    if (nd->nl_nch.ncp) {
	if (nd->nl_flags & NLC_NCPISLOCKED)
	    cache_unlock(&nd->nl_nch);
	cache_drop_and_cache(&nd->nl_nch, nd->nl_elmno);
    }
    nd->nl_flags &= ~NLC_NCPISLOCKED;
    if (nd->nl_rootnch.ncp)
	cache_drop_and_cache(&nd->nl_rootnch, 0);
    if (nd->nl_jailnch.ncp)
	cache_drop_and_cache(&nd->nl_jailnch, 0);
    if ((nd->nl_flags & NLC_HASBUF) && nd->nl_path) {
	objcache_put(namei_oc, nd->nl_path);
	nd->nl_path = NULL;
    }
    if (nd->nl_cred) {
	if ((nd->nl_flags & NLC_BORROWCRED) == 0)
	    crfree(nd->nl_cred);
	nd->nl_cred = NULL;
	nd->nl_flags &= ~NLC_BORROWCRED;
    }
    if (nd->nl_open_vp) {
	if (nd->nl_flags & NLC_LOCKVP) {
		vn_unlock(nd->nl_open_vp);
		nd->nl_flags &= ~NLC_LOCKVP;
	}
	vn_close(nd->nl_open_vp, nd->nl_vp_fmode, NULL);
	nd->nl_open_vp = NULL;
    }
    if (nd->nl_dvp) {
	vrele(nd->nl_dvp);
	nd->nl_dvp = NULL;
    }
    nd->nl_flags = 0;	/* clear remaining flags (just clear everything) */
    nd->nl_basench = NULL;
}

/*
 * Works similarly to nlookup_done() when nd initialized with
 * nlookup_init_at().
 */
void
nlookup_done_at(struct nlookupdata *nd, struct file *fp)
{
	nlookup_done(nd);
	if (fp != NULL)
		fdrop(fp);
}

void
nlookup_zero(struct nlookupdata *nd)
{
	bzero(nd, sizeof(struct nlookupdata));
}

/*
 * Simple all-in-one nlookup.  Returns a locked namecache structure or NULL
 * if an error occured. 
 *
 * Note that the returned ncp is not checked for permissions, though VEXEC
 * is checked on the directory path leading up to the result.  The caller
 * must call naccess() to check the permissions of the returned leaf.
 */
struct nchandle
nlookup_simple(const char *str, enum uio_seg seg,
	       int niflags, int *error)
{
    struct nlookupdata nd;
    struct nchandle nch;

    *error = nlookup_init(&nd, str, seg, niflags);
    if (*error == 0) {
	    if ((*error = nlookup(&nd)) == 0) {
		    nch = nd.nl_nch;	/* keep hold ref from structure */
		    cache_zero(&nd.nl_nch); /* and NULL out */
	    } else {
		    cache_zero(&nch);
	    }
	    nlookup_done(&nd);
    } else {
	    cache_zero(&nch);
    }
    return(nch);
}

/*
 * Returns non-zero if the path element is the last element
 */
static
int
islastelement(const char *ptr)
{
	while (*ptr == '/')
		++ptr;
	return (*ptr == 0);
}

/*
 * Returns non-zero if we need to lock the namecache element
 * exclusively.  Unless otherwise requested by NLC_SHAREDLOCK,
 * the last element of the namecache lookup will be locked
 * exclusively.
 *
 * O_CREAT or O_TRUNC need the last element to be locked exlcusively.
 * Intermediate elements are always locked shared.
 *
 * NOTE: Even if we return on-zero, an unresolved namecache record
 *	 will always be locked exclusively.
 */
static __inline
int
wantsexcllock(struct nlookupdata *nd, int last_element)
{
	if ((nd->nl_flags & NLC_SHAREDLOCK) == 0)
		return(last_element);
	return 0;
}


/*
 * Do a generic nlookup.  Note that the passed nd is not nlookup_done()'d
 * on return, even if an error occurs.  If no error occurs or NLC_CREATE
 * is flagged and ENOENT is returned, then the returned nl_nch is always
 * referenced and locked exclusively.
 *
 * WARNING: For any general error other than ENOENT w/NLC_CREATE, the
 *	    the resulting nl_nch may or may not be locked and if locked
 *	    might be locked either shared or exclusive.
 *
 * Intermediate directory elements, including the current directory, require
 * execute (search) permission.  nlookup does not examine the access 
 * permissions on the returned element.
 *
 * If NLC_CREATE is set the last directory must allow node creation,
 * and an error code of 0 will be returned for a non-existant
 * target (not ENOENT).
 *
 * If NLC_RENAME_DST is set the last directory mut allow node deletion,
 * plus the sticky check is made, and an error code of 0 will be returned
 * for a non-existant target (not ENOENT).
 *
 * If NLC_DELETE is set the last directory mut allow node deletion,
 * plus the sticky check is made.
 *
 * If NLC_REFDVP is set nd->nl_dvp will be set to the directory vnode
 * of the returned entry.  The vnode will be referenced but not locked.
 *
 * IF THE PATH REPRESENTS A MOUNT POINT CROSSING THEN NLC_REFDVP WILL SET
 * NL_DVP TO NULL AND RETURN NO ERROR (ERROR == 0), allowing the operation
 * to return up the stack.  The nch will only be referenced and not locked.
 * High level code must check this case and do the right thing since,
 * typically, it means things like 'mkdir' should fail with EEXIST.  For
 * example 'mkdir /var/cache' where /var/cache is a null-mount from
 * /build/var.cache, needs to return EEXIST rather than a mount-crossing
 * failure.
 *
 * NOTE: As an optimization we attempt to obtain a shared namecache lock
 *	 on any intermediate elements.  On success, the returned element
 *	 is ALWAYS locked exclusively.
 *
 * NOTE: If for any reason the nc_generation number of the ncp's being
 *	 evaluated changes, the lookup is retried.
 */
int
nlookup(struct nlookupdata *nd)
{
    globaldata_t gd = mycpu;
    struct nlcomponent nlc;
    struct nchandle nch;
    struct nchandle nctmp;
    struct mount *mp;
    int wasdotordotdot;
    char *path_reset;
    char *ptr;
    char *nptr;
    int error;
    int len;
    int dflags;
    int hit = 1;
    int saveflag = nd->nl_flags;
    int max_retries = nlookup_max_retries;
    u_int nl_gen;
    u_int nch_gen;
    int gen_changed;
    boolean_t doretry = FALSE;
    boolean_t inretry = FALSE;

    path_reset = NULL;

nlookup_start:

#ifdef KTRACE
    if (KTRPOINT(nd->nl_td, KTR_NAMEI))
	ktrnamei(nd->nl_td->td_lwp, nd->nl_path);
#endif
    bzero(&nlc, sizeof(nlc));

    /*
     * Setup for the loop.  The current working namecache element is
     * always at least referenced.  We lock it as required, but always
     * return a locked, resolved namecache entry.
     */
    nd->nl_loopcnt = 0;
    nd->nl_dir_error = 0;
    if (nd->nl_dvp) {
	vrele(nd->nl_dvp);
	nd->nl_dvp = NULL;
    }
    ptr = nd->nl_path;

    nl_gen = nd->nl_nch.ncp ? nd->nl_nch.ncp->nc_generation : 0;
    nl_gen &= ~3;
    gen_changed = 0;

    /*
     * Loop on the path components.  At the top of the loop nd->nl_nch
     * is ref'd and unlocked and represents our current position.
     */
    for (;;) {
	int last_element;

	++nd->nl_elmno;
	KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);

	/*
	 * Check if the root directory should replace the current
	 * directory.  This is done at the start of a translation
	 * or after a symbolic link has been found.  In other cases
	 * ptr will never be pointing at a '/'.
	 */
	if (*ptr == '/') {
	    do {
		++ptr;
	    } while (*ptr == '/');

	    /*
	     * We might already be at the root as a pre-optimization
	     */
	    if (nd->nl_nch.mount != nd->nl_rootnch.mount ||
		nd->nl_nch.ncp != nd->nl_rootnch.ncp) {
		cache_drop_and_cache(&nd->nl_nch, 0);
		cache_copy(&nd->nl_rootnch, &nd->nl_nch);
		nl_gen = nd->nl_nch.ncp->nc_generation & ~3;
	    }

	    /*
	     * Fast-track termination.  There is no parent directory of
	     * the root in the same mount from the point of view of
	     * the caller so return EACCES if NLC_REFDVP is specified,
	     * and EEXIST if NLC_CREATE is also specified.
	     * e.g. 'rmdir /' or 'mkdir /' are not allowed.
	     */
	    if (*ptr == 0) {
		if (nd->nl_flags & NLC_REFDVP)
			error = (nd->nl_flags & NLC_CREATE) ? EEXIST : EACCES;
		else
			error = 0;
		nd->nl_flags |= NLC_NCPISLOCKED;
		cache_lock_maybe_shared(&nd->nl_nch,
					wantsexcllock(nd, islastelement(ptr)));
		break;
	    }
	    continue;
	}

	/*
	 * Pre-calculate next path component so we can check whether the
	 * current component directory is the last directory in the path
	 * or not.
	 */
	for (nptr = ptr; *nptr && *nptr != '/'; ++nptr)
		;

	/*
	 * nd->nl_nch is referenced and not locked here.
	 *
	 * Check directory search permissions.  This will load dflags to
	 * obtain directory-special permissions to be checked along with the
	 * last component.
	 *
	 * We only need to pass-in &dflags for the second-to-last component.
	 * Optimize by passing-in NULL for any prior components, which may
	 * allow the code to bypass the naccess() call.
	 *
	 * naccess() is optimized to avoid having to lock the nch or get
	 * the related vnode if cached perms are sufficient.
	 */
	dflags = 0;
	if (*nptr == '/' || (saveflag & NLC_MODIFYING_MASK) == 0) {
	    error = naccess(nd, &nd->nl_nch, &nl_gen, NLC_EXEC,
			    nd->nl_cred, NULL, 0);
	} else {
	    error = naccess(nd, &nd->nl_nch, &nl_gen, NLC_EXEC,
			    nd->nl_cred, &dflags, 0);
	}
	if (error) {
	    if (keeperror(nd, error))
		break;
	    error = 0;
	}

	/*
	 * Extract the next (or last) path component.  Path components are
	 * limited to 255 characters.
	 */
	nlc.nlc_nameptr = ptr;
	nlc.nlc_namelen = nptr - ptr;
	ptr = nptr;
	if (nlc.nlc_namelen >= 256) {
	    error = ENAMETOOLONG;
	    break;
	}
	last_element = islastelement(nptr);

	/*
	 * Lookup the path component in the cache, creating an unresolved
	 * entry if necessary.  We have to handle "." and ".." as special
	 * cases.
	 *
	 * When handling ".." we have to detect a traversal back through a
	 * mount point.   If we are at the root, ".." just returns the root.
	 *
	 * When handling "." or ".." we also have to recalculate dflags
	 * since our dflags will be for some sub-directory instead of the
	 * parent dir.
	 *
	 * This subsection returns a referenced and possibly locked 'nch'.
	 * The locking status is based on the last_element flag.
	 *
	 * The namecache topology is not allowed to be disconnected, so 
	 * encountering a NULL parent will generate EINVAL.  This typically
	 * occurs when a directory is removed out from under a process.
	 *
	 * WARNING! The unlocking of nd->nl_nch is sensitive code.
	 */
	KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);

	if (nlc.nlc_namelen == 1 && nlc.nlc_nameptr[0] == '.') {
	    if (last_element) {
		cache_get_maybe_shared(&nd->nl_nch, &nch,
				       wantsexcllock(nd, 1));
	    } else {
		cache_copy(&nd->nl_nch, &nch);
	    }
	    nch_gen = nch.ncp->nc_generation & ~3;
	    wasdotordotdot = 1;
	} else if (nlc.nlc_namelen == 2 && 
		   nlc.nlc_nameptr[0] == '.' && nlc.nlc_nameptr[1] == '.') {
	    if (nd->nl_nch.mount == nd->nl_rootnch.mount &&
		nd->nl_nch.ncp == nd->nl_rootnch.ncp
	    ) {
		/*
		 * ".." at the root returns the root
		 */
		if (last_element) {
		    cache_get_maybe_shared(&nd->nl_nch, &nch,
					   wantsexcllock(nd, 1));
		} else {
		    cache_copy(&nd->nl_nch, &nch);
		}
	    } else {
		/*
		 * Locate the parent ncp.  If we are at the root of a
		 * filesystem mount we have to skip to the mounted-on
		 * point in the underlying filesystem.
		 *
		 * Expect the parent to always be good since the
		 * mountpoint doesn't go away.  XXX hack.  cache_get()
		 * requires the ncp to already have a ref as a safety.
		 *
		 * However, a process which has been broken out of a chroot
		 * will wind up with a NULL parent if it tries to '..' above
		 * the real root, deal with the case.  Note that this does
		 * not protect us from a jail breakout, it just stops a panic
		 * if the jail-broken process tries to '..' past the real
		 * root.
		 */
		nctmp = nd->nl_nch;
		while (nctmp.ncp == nctmp.mount->mnt_ncmountpt.ncp) {
			nctmp = nctmp.mount->mnt_ncmounton;
			if (nctmp.ncp == NULL)
				break;
		}
		if (nctmp.ncp == NULL) {
			if (curthread->td_proc) {
				kprintf("vfs_nlookup: '..' traverse broke "
					"jail: pid %d (%s)\n",
					curthread->td_proc->p_pid,
					curthread->td_comm);
			}
			nctmp = nd->nl_rootnch;
		} else {
			nctmp.ncp = nctmp.ncp->nc_parent;
		}
		if (last_element) {
		    cache_get_maybe_shared(&nctmp, &nch,
					   wantsexcllock(nd, 1));
		} else {
		    cache_copy(&nctmp, &nch);
		}
	    }
	    nch_gen = nch.ncp->nc_generation & ~3;
	    wasdotordotdot = 2;
	} else {
	    /*
	     * Quickly lookup the component.  If we can't find it, then
	     * slowly lookup and resolve the component.
	     */
	    if (last_element) {
		    error = cache_nlookup_maybe_shared(&nd->nl_nch, &nlc,
						       wantsexcllock(nd, 1),
						       &nch);
	    } else {
		    nch = cache_nlookup_nonlocked(&nd->nl_nch, &nlc);
		    if (nch.ncp == NULL)
			error = EWOULDBLOCK;
	    }

	    /*
	     * At this point the only possible error is EWOULDBLOCK.
	     *
	     * If no error nch is set and referenced, and then also locked
	     * according to last_element.  For EWOULDBLOCK nch is not set.
	     * For any other error nch is set and referenced, but not locked.
	     *
	     * On EWOULDBLOCK the ncp may be unresolved (if not locked it can
	     * become unresolved at any time, but we don't care at this time).
	     */
	    if (error == EWOULDBLOCK) {
		nch = cache_nlookup(&nd->nl_nch, &nlc);
		if (nch.ncp->nc_flag & NCF_UNRESOLVED)
		    hit = 0;
		for (;;) {
		    error = cache_resolve(&nch, &nch_gen, nd->nl_cred);
		    if (error != EAGAIN &&
			(nch.ncp->nc_flag & NCF_DESTROYED) == 0) {
			    if (error == ESTALE) {
				if (!inretry)
				    error = ENOENT;
				doretry = TRUE;
			    }
			    if (last_element == 0)
				    cache_unlock(&nch);
			    break;
		    }
		    kprintf("[diagnostic] nlookup: relookup %*.*s\n",
			    nch.ncp->nc_nlen, nch.ncp->nc_nlen,
			    nch.ncp->nc_name);
		    cache_put(&nch);
		    nch = cache_nlookup(&nd->nl_nch, &nlc);
		}
	    }
	    nch_gen = nch.ncp->nc_generation & ~3;
	    wasdotordotdot = 0;
	}

	/*
	 * If the component is "." or ".." our dflags no longer represents
	 * the parent directory and we have to explicitly look it up.
	 *
	 * Expect the parent to be good since nch is locked.
	 *
	 * nch will continue to be valid even if an error occurs after this
	 * point.
	 */
	if (wasdotordotdot && error == 0) {
	    struct nchandle par;

	    dflags = 0;
	    if (last_element == 0)
		cache_lock_maybe_shared(&nch, wantsexcllock(nd, 0));

	    if ((par.ncp = nch.ncp->nc_parent) != NULL) {
		u_int dummy_gen = 0;

		par.mount = nch.mount;
		cache_hold(&par);
		error = naccess(nd, &par, &dummy_gen, 0, nd->nl_cred, &dflags, 0);
		cache_drop_and_cache(&par, nd->nl_elmno - 1);
		if (error) {
		    if (!keeperror(nd, error))
			error = 0;
		    if (error == EINVAL) {
			kprintf("nlookup (%s): trailing . or .. retry on %s\n",
				curthread->td_comm, nd->nl_path);
			doretry = TRUE;
		    }
		}
	    }

	    if (last_element == 0)
		cache_unlock(&nch);
	}

	/*
	 * [end of subsection]
	 *
	 * nch is referenced and locked according to (last_element).
	 * nd->nl_nch is unlocked and referenced.
	 * nl_gen and nch_gen are both set.
	 */
	KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);

	/*
	 * Resolve the namespace if necessary.  The ncp returned by
	 * cache_nlookup() is referenced, and also locked according
	 * to last_element.
	 *
	 * XXX neither '.' nor '..' should return EAGAIN since they were
	 * previously resolved and thus cannot be newly created ncp's.
	 */
	if (nch.ncp->nc_flag & NCF_UNRESOLVED) {
	    if (last_element == 0)
		cache_lock(&nch);
	    hit = 0;
	    error = cache_resolve(&nch, &nch_gen, nd->nl_cred);
	    if (error == ESTALE) {
		if (!inretry)
		    error = ENOENT;
		doretry = TRUE;
	    }
	    if (last_element == 0)
		cache_unlock(&nch);
	    KKASSERT(error != EAGAIN);
	} else {
	    error = nch.ncp->nc_error;
	}

	/*
	 * Early completion.  ENOENT is not an error if this is the last
	 * component and NLC_CREATE or NLC_RENAME (rename target) was
	 * requested.  Note that ncp->nc_error is left as ENOENT in that
	 * case, which we check later on.
	 *
	 * Also handle invalid '.' or '..' components terminating a path
	 * for a create/rename/delete.  The standard requires this and pax
	 * pretty stupidly depends on it.
	 */
	if (last_element) {
	    if (error == ENOENT &&
		(nd->nl_flags & (NLC_CREATE | NLC_RENAME_DST)))
	    {
		if (nd->nl_flags & NLC_NFS_RDONLY) {
			error = EROFS;
		} else {
			error = naccess(nd, &nch, &nch_gen,
					nd->nl_flags | dflags,
					nd->nl_cred, NULL, last_element);
		}
	    }
	    if (error == 0 && wasdotordotdot &&
		(nd->nl_flags & (NLC_CREATE | NLC_DELETE |
				 NLC_RENAME_SRC | NLC_RENAME_DST)))
	    {
		/*
		 * POSIX junk
		 */
		if (nd->nl_flags & NLC_CREATE)
			error = EEXIST;
		else if (nd->nl_flags & NLC_DELETE)
			error = (wasdotordotdot == 1) ? EINVAL : ENOTEMPTY;
		else
			error = EINVAL;
	    }
	}

	/*
	 * Early completion on error.
	 */
	if (error) {
	    if (last_element)
		    cache_unlock(&nch);
	    cache_drop_and_cache(&nch, nd->nl_elmno);
	    break;
	}

	/*
	 * If the element is a symlink and it is either not the last
	 * element or it is the last element and we are allowed to
	 * follow symlinks, resolve the symlink.
	 */
	if ((nch.ncp->nc_flag & NCF_ISSYMLINK) &&
	    (*ptr || (nd->nl_flags & NLC_FOLLOW))
	) {
	    if (nd->nl_loopcnt++ >= MAXSYMLINKS) {
		error = ELOOP;
		if (last_element)
			cache_unlock(&nch);
		cache_drop_and_cache(&nch, nd->nl_elmno);
		break;
	    }

	    /*
	     * Check for a generation change.
	     *
	     * NOTE: On generation changes we must at a minimum cycle
	     *	     the lock.  Here we get or have the lock so we are
	     *	     ok.
	     */
	    if (last_element == 0)
		cache_lock_maybe_shared(&nch, 1);

	    if ((nch.ncp->nc_generation - nch_gen) & ~1) {
		if (nlookup_debug & 1) {
		    kprintf("nlookup: symlink: GEN CHANGE %d\n",
			    (nch.ncp->nc_generation - nch_gen));
		}
		gen_changed = 1;
	    }

	    error = nreadsymlink(nd, &nch, &nlc);
	    cache_put(&nch);
	    if (error)
		break;

	    /*
	     * Concatenate trailing path elements onto the returned symlink.
	     * Note that if the path component (ptr) is not exhausted, it
	     * will being with a '/', so we do not have to add another one.
	     *
	     * The symlink may not be empty.
	     */
	    len = strlen(ptr);
	    if (nlc.nlc_namelen == 0 || nlc.nlc_namelen + len >= MAXPATHLEN) {
		error = nlc.nlc_namelen ? ENAMETOOLONG : ENOENT;
		objcache_put(namei_oc, nlc.nlc_nameptr);
		break;
	    }
	    bcopy(ptr, nlc.nlc_nameptr + nlc.nlc_namelen, len + 1);

	    if (path_reset) {
		if (nd->nl_flags & NLC_HASBUF)
		    objcache_put(namei_oc, nd->nl_path);
	    } else {
		path_reset = nd->nl_path;
	    }
	    nd->nl_path = nlc.nlc_nameptr;
	    nd->nl_flags |= NLC_HASBUF;
	    ptr = nd->nl_path;
	    /* nl_gen has not changed */

	    /*
	     * Go back up to the top to resolve any initial '/'s in the
	     * symlink.
	     */
	    continue;
	}
	
	/*
	 * If the element is a directory and we are crossing a mount point,
	 * Locate the mount.
	 */
	while ((nch.ncp->nc_flag & NCF_ISMOUNTPT) && 
	    (nd->nl_flags & NLC_NOCROSSMOUNT) == 0 &&
	    (mp = cache_findmount(&nch)) != NULL
	) {
	    struct vnode *tdp;
	    int vfs_do_busy = 0;

	    /*
	     * VFS must be busied before the namecache entry is locked,
	     * but we don't want to waste time calling vfs_busy() if the
	     * mount point is already resolved.
	     */
again:
	    /*
	     * Check for a generation change.
	     *
	     * NOTE: On generation changes we must at a minimum cycle
	     *	     the lock.  So get and release the lock if we
	     *	     do not have it.
	     */
	    if ((nch.ncp->nc_generation - nch_gen) & ~1) {
		if (last_element == 0) {
		    cache_lock_maybe_shared(&nch, 1);
		    cache_unlock(&nch);
		}
		if (nlookup_debug & 1) {
		    kprintf("nlookup: mountpt: GEN CHANGE %d\n",
			    (nch.ncp->nc_generation - nch_gen));
		}
		gen_changed = 1;
	    }
	    if (last_element)
		    cache_unlock(&nch);
	    cache_drop_and_cache(&nch, nd->nl_elmno);

	    if (vfs_do_busy) {
		while (vfs_busy(mp, 0)) {
		    if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
			kprintf("nlookup: warning umount race avoided\n");
			cache_dropmount(mp);
			error = EBUSY;
			vfs_do_busy = 0;
			goto double_break;
		    }
		}
	    }

	    /*
	     * We don't need to lock the nch unless the entry is unresolved
	     * or this is the last element.
	     */
	    if (last_element)
		cache_get_maybe_shared(&mp->mnt_ncmountpt, &nch,
				       wantsexcllock(nd, 1));
	    else
		cache_copy(&mp->mnt_ncmountpt, &nch);
	    nch_gen = nch.ncp->nc_generation & ~3;

	    if (nch.ncp->nc_flag & NCF_UNRESOLVED) {
		if (last_element == 0)
		    cache_lock(&nch);
		if (nch.ncp->nc_flag & NCF_UNRESOLVED) {
		    if (vfs_do_busy == 0) {
			vfs_do_busy = 1;
			if (last_element == 0)
			    cache_unlock(&nch);
			goto again;
		    }
		    error = VFS_ROOT(mp, &tdp);
		    vfs_unbusy(mp);
		    vfs_do_busy = 0;
		    if (keeperror(nd, error)) {
			cache_dropmount(mp);
			if (last_element == 0)
			    cache_unlock(&nch);
			break;
		    }
		    if (error == 0) {
			cache_setvp(&nch, tdp);
			nch_gen = nch.ncp->nc_generation & ~3;
			vput(tdp);
		    }
		}
		if (last_element == 0)
		    cache_unlock(&nch);
	    }
	    if (vfs_do_busy)
		vfs_unbusy(mp);
	    cache_dropmount(mp);
	}

	/*
	 * Break out on error
	 */
	if (keeperror(nd, error)) {
	    if (last_element)
		    cache_unlock(&nch);
	    cache_drop_and_cache(&nch, nd->nl_elmno);
double_break:
	    break;
	}
	    
	/*
	 * Skip any slashes to get to the next element.  If there 
	 * are any slashes at all the current element must be a
	 * directory or, in the create case, intended to become a directory.
	 * If it isn't we break without incrementing ptr and fall through
	 * to the failure case below.
	 */
	while (*ptr == '/') {
	    if ((nch.ncp->nc_flag & NCF_ISDIR) == 0 && 
		!(nd->nl_flags & NLC_WILLBEDIR)
	    ) {
		break;
	    }
	    ++ptr;
	}

	/*
	 * Continuation case: additional elements and the current
	 * element is a directory.
	 */
	if (*ptr && (nch.ncp->nc_flag & NCF_ISDIR)) {
	    /*
	     * Check for a generation change.
	     *
	     * NOTE: On generation changes we must at a minimum cycle
	     *	     the lock.  So get and release the lock if we
	     *	     do not have it.
	     */
	    if ((nch.ncp->nc_generation - nch_gen) & ~1) {
		if (last_element == 0) {
		    cache_lock_maybe_shared(&nch, 1);
		    cache_unlock(&nch);
		}
		if (nlookup_debug & 1) {
		    kprintf("nlookup: next: GEN CHANGE %d\n",
			    (nch.ncp->nc_generation - nch_gen));
		}
		gen_changed = 1;
	    }
	    cache_drop_and_cache(&nd->nl_nch, nd->nl_elmno);
	    if (last_element)
		    cache_unlock(&nch);
	    /*nchislocked = 0; not needed */
	    KKASSERT((nd->nl_flags & NLC_NCPISLOCKED) == 0);
	    nd->nl_nch = nch;
	    nl_gen = nch_gen;
	    continue;
	}

	/*
	 * Check for a generation change.
	 *
	 * NOTE: On generation changes we must at a minimum cycle
	 *	     the lock.  So get and release the lock if we
	 *	     do not have it.
	 */
	if ((nch.ncp->nc_generation - nch_gen) & ~1) {
	    if (nlookup_debug & 1) {
		if (last_element == 0) {
		    cache_lock_maybe_shared(&nch, 1);
		    cache_unlock(&nch);
		}
		kprintf("nlookup: final: GEN CHANGE %d\n",
			(nch.ncp->nc_generation - nch_gen));
		gen_changed = 1;
	    }
	}

	/*
	 * Failure case: additional elements and the current element
	 * is not a directory
	 */
	if (*ptr) {
	    if (last_element)
		    cache_unlock(&nch);
	    cache_drop_and_cache(&nch, nd->nl_elmno);
	    error = ENOTDIR;
	    break;
	}

	/*
	 * Successful lookup of last element.
	 *
	 * Check permissions if the target exists.  If the target does not
	 * exist directory permissions were already tested in the early
	 * completion code above.
	 *
	 * nd->nl_flags will be adjusted on return with NLC_APPENDONLY
	 * if the file is marked append-only, and NLC_STICKY if the directory
	 * containing the file is sticky.
	 */
	KKASSERT(last_element);

	if (nch.ncp->nc_vp && (nd->nl_flags & NLC_ALLCHKS)) {
	    error = naccess(nd, &nch, &nch_gen, nd->nl_flags | dflags,
			    nd->nl_cred, NULL, 1);
	    if (keeperror(nd, error)) {
		cache_put(&nch);
		break;
	    }
	}

	/*
	 * Termination: no more elements.
	 *
	 * Check to see if the immediate parent has been destroyed.  This race
	 * can occur because the element lookup must temporarily unlock
	 * the parent.  If so, do a retry.
	 */
	if (nch.ncp->nc_parent &&
	    (nch.ncp->nc_parent->nc_flag & NCF_DESTROYED)) {
		doretry = TRUE;
	}

	/*
	 * Termination: no more elements.
	 *
	 * If NLC_REFDVP is set acquire a referenced parent dvp.  Typically
	 * used for mkdir/mknod/ncreate/nremove/unlink/rename.
	 *
	 * If a mount-point transition occurs due to ncp being a mount point,
	 * or a null-mount, nl_dvp will be set to NULL and an error code of
	 * 0 will be returned.  A NULL nc_parent is not necessarily the only
	 * indication of a mount-point as null-mounts will also tend to have
	 * a non-null nc_parent.
	 *
	 * nch is locked, standard lock order for the namecache is
	 * child-to-parent so we can safely lock its parent.  We can
	 * just use cache_dvpref().
	 */
	if ((nd->nl_flags & NLC_REFDVP) &&
	    (doretry == FALSE || inretry == TRUE)) {
		if (nch.ncp->nc_parent) {
			error = cache_resolve_dvp(&nch, nd->nl_cred,
						  &nd->nl_dvp);
			if (error) {
				if (nlookup_debug & 1) {
				    kprintf("Parent directory lost during "
					    "nlookup: %s/%s (%08x/%08x)\n",
					    nch.ncp->nc_parent->nc_name,
					    nch.ncp->nc_name,
					    nch.ncp->nc_parent->nc_flag,
					    nch.ncp->nc_flag);
				}
				cache_put(&nch);
				error = EINVAL;
				break;
			}

			/*
			 * Mount-point, nl_dvp should remain NULL, error 0,
			 * caller won't be able to use the results so leave
			 * the ncp referenced but unlocked.
			 */
			if (nd->nl_dvp == NULL) {
				cache_put(&nch);
				break;
			}

			/*
			 * Good directory, fall through to drop-and-cache
			 * below
			 */
			/* */
		} else {
			/*
			 * Mount-point, nl_dvp should remain NULL, error 0,
			 * caller won't be able to use the results so leave
			 * the ncp referenced but unlocked.
			 */
			error = 0;
			cache_put(&nch);
			break;
		}
	}

	/*
	 * ncp left with lock+ref on break, set NLC_NCPISLOCKED flag
	 */
	cache_drop_and_cache(&nd->nl_nch, nd->nl_elmno);
	nd->nl_nch = nch;
	nd->nl_flags |= NLC_NCPISLOCKED;
	nl_gen = nch_gen;
	error = 0;
	break;
    }

    /*
     * Force a retry (up to max_retries) if nl_gen is incorrect
     *
     * NOTE: On generation changes we must at a minimum cycle
     *	     the lock.   In this case we have one so we are ok.
     */
    if (nd->nl_nch.ncp && (nd->nl_nch.ncp->nc_generation - nl_gen) & ~1) {
	if (nlookup_debug & 1) {
	    kprintf("nlookup: DONE error %d: GEN CHANGE ON \"%s\" "
		    "%d (retries %d)\n",
		    error,
		    nd->nl_nch.ncp->nc_name,
		    (nd->nl_nch.ncp->nc_generation - nl_gen),
		    max_retries);
	}
	gen_changed = 1;
    }
    if (gen_changed) {
	if (max_retries) {
	    --max_retries;
	    doretry = TRUE;
	    inretry = FALSE;
	} else {
	    error = EINVAL;
	}
    }

    /*
     * We are done / or possibly retry
     */
    if (hit)
	++gd->gd_nchstats->ncs_longhits;
    else
	++gd->gd_nchstats->ncs_longmiss;

    if (nd->nl_flags & NLC_NCPISLOCKED)
	KKASSERT(cache_lockstatus(&nd->nl_nch) > 0);

    /*
     * Reset nd->nl_path if necessary (due to softlinks).  We want to return
     * nl_path to its original state before retrying or returning.
     */
    if (path_reset) {
	if (nd->nl_flags & NLC_HASBUF) {
	    objcache_put(namei_oc, nd->nl_path);
	    nd->nl_flags &= ~NLC_HASBUF;
	}
	nd->nl_path = path_reset;
	nd->nl_flags |= saveflag & NLC_HASBUF;
	path_reset = NULL;
    }

    /*
     * Retry the whole thing if doretry flag is set, but only once.
     *
     * autofs(5) may mount another filesystem under its root directory
     * while resolving a path.
     *
     * NFS might return ESTALE
     */
    if (doretry && !inretry) {
	if (nlookup_debug & 2)
	    kprintf("nlookup: errno %d retry %s\n", error, nd->nl_path);
	inretry = TRUE;

	/*
	 * Clean up nd->nl_nch and reset to base directory
	 */
	if (nd->nl_flags & NLC_NCPISLOCKED) {
		cache_unlock(&nd->nl_nch);
		nd->nl_flags &= ~NLC_NCPISLOCKED;
	}
	cache_drop(&nd->nl_nch);
	cache_copy(nd->nl_basench, &nd->nl_nch);

	nd->nl_elmno = 0;
	nd->nl_flags |= saveflag;

	goto nlookup_start;
    }

    /*
     * NOTE: If NLC_CREATE was set the ncp may represent a negative hit
     * (ncp->nc_error will be ENOENT), but we will still return an error
     * code of 0.
     */
    return(error);
}

/*
 * Resolve a mount point's glue ncp.  This ncp connects creates the illusion
 * of continuity in the namecache tree by connecting the ncp related to the
 * vnode under the mount to the ncp related to the mount's root vnode.
 *
 * If no error occured a locked, ref'd ncp is stored in *ncpp.
 */
int
nlookup_mp(struct mount *mp, struct nchandle *nch)
{
    struct vnode *vp;
    int error;

    error = 0;
    cache_get(&mp->mnt_ncmountpt, nch);
    if (nch->ncp->nc_flag & NCF_UNRESOLVED) {
	while (vfs_busy(mp, 0))
	    ;
	error = VFS_ROOT(mp, &vp);
	vfs_unbusy(mp);
	if (error) {
	    cache_put(nch);
	} else {
	    cache_setvp(nch, vp);
	    vput(vp);
	}
    }
    return(error);
}

/*
 * Read the contents of a symlink, allocate a path buffer out of the
 * namei_oc and initialize the supplied nlcomponent with the result.
 *
 * If an error occurs no buffer will be allocated or returned in the nlc.
 */
int
nreadsymlink(struct nlookupdata *nd, struct nchandle *nch, 
		struct nlcomponent *nlc)
{
    struct vnode *vp;
    struct iovec aiov;
    struct uio auio;
    int linklen;
    int error;
    char *cp;

    nlc->nlc_nameptr = NULL;
    nlc->nlc_namelen = 0;
    if (nch->ncp->nc_vp == NULL)
	return(ENOENT);
    if ((error = cache_vget(nch, nd->nl_cred, LK_SHARED, &vp)) != 0)
	return(error);
    cp = objcache_get(namei_oc, M_WAITOK);
    aiov.iov_base = cp;
    aiov.iov_len = MAXPATHLEN;
    auio.uio_iov = &aiov;
    auio.uio_iovcnt = 1;
    auio.uio_offset = 0;
    auio.uio_rw = UIO_READ;
    auio.uio_segflg = UIO_SYSSPACE;
    auio.uio_td = nd->nl_td;
    auio.uio_resid = MAXPATHLEN - 1;
    error = VOP_READLINK(vp, &auio, nd->nl_cred);
    if (error)
	goto fail;
    linklen = MAXPATHLEN - 1 - auio.uio_resid;
    if (varsym_enable) {
	linklen = varsymreplace(cp, linklen, MAXPATHLEN - 1);
	if (linklen < 0) {
	    error = ENAMETOOLONG;
	    goto fail;
	}
    }
    cp[linklen] = 0;
    nlc->nlc_nameptr = cp;
    nlc->nlc_namelen = linklen;
    vput(vp);
    return(0);
fail:
    objcache_put(namei_oc, cp);
    vput(vp);
    return(error);
}

/*
 * Check access [XXX cache vattr!] [XXX quota]
 *
 * Generally check the NLC_* access bits.   All specified bits must pass
 * for this function to return 0.
 *
 * The file does not have to exist when checking NLC_CREATE or NLC_RENAME_DST
 * access, otherwise it must exist.  No error is returned in this case.
 *
 * The file must not exist if NLC_EXCL is specified.
 *
 * Directory permissions in general are tested for NLC_CREATE if the file
 * does not exist, NLC_DELETE if the file does exist, and NLC_RENAME_DST
 * whether the file exists or not.
 *
 * The directory sticky bit is tested for NLC_DELETE and NLC_RENAME_DST,
 * the latter is only tested if the target exists.
 *
 * The passed ncp must be referenced and locked.  If it is already resolved
 * it may be locked shared but otherwise should be locked exclusively.
 */

#define S_WXOK_MASK	(S_IRUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)
#define S_XOK_MASK	(S_IXUSR|S_IXGRP|S_IXOTH)

static int
naccess(struct nlookupdata *nd, struct nchandle *nch, u_int *genp, int nflags,
	struct ucred *cred, int *nflagsp, int nchislocked)
{
    struct vnode *vp;
    struct vattr_lite lva;
    struct namecache *ncp;
    int error;
    int cflags;

    ncp = nch->ncp;

again:
    /*
     * We need a resolved entry.  If the entry is not resolved we need
     * to lock and resolve it.  If it is already resolved, our ref should
     * prevent normal evictions (as long as we tested the lock race above).
     *
     * If the ncp was locked by the caller and left unresolved, it must
     * have been locked exclusively.
     */
    if (ncp->nc_flag & NCF_UNRESOLVED) {
	if (nchislocked == 0) {
	    cache_lock(nch);
	    nchislocked = 2;
	}
	cache_resolve(nch, genp, cred);
	ncp = nch->ncp;
    }
    error = ncp->nc_error;

    /*
     * Only unresolved entries should return this error (though maybe
     * in-filesystem sockets can too).   XXX check filetype for VSOCK.
     */
    if (error == ENOTCONN) {
	if (nchislocked == 0) {
	    if (nlookup_debug & 4) {
		kprintf("ncp %p %08x %d %s: Warning, unexpected state, "
			"forcing lock\n",
			ncp, ncp->nc_flag, ncp->nc_error, ncp->nc_name);
		print_backtrace(-1);
	    }
	    cache_lock(nch);
	    nchislocked = 2;
	    goto again;
	}
	if (nlookup_debug & 4) {
	    kprintf("ncp %p %08x %d %s: Warning, unexpected state\n",
		    ncp, ncp->nc_flag, ncp->nc_error, ncp->nc_name);
	    print_backtrace(-1);
	}
    }

    /*
     * Directory permissions checks.  Silently ignore ENOENT if these
     * tests pass.  It isn't an error.
     *
     * We can safely resolve ncp->nc_parent because ncp is currently
     * locked.
     *
     * We set nl_dir_error if an error occurs checking directory perms
     * for an intermediate directory.
     */
    if (nflags & (NLC_CREATE | NLC_DELETE | NLC_RENAME_SRC | NLC_RENAME_DST)) {
	if (((nflags & NLC_CREATE) && ncp->nc_vp == NULL) ||
	    ((nflags & NLC_DELETE) && ncp->nc_vp != NULL) ||
	    ((nflags & NLC_RENAME_SRC) && ncp->nc_vp != NULL) ||
	    (nflags & NLC_RENAME_DST)
	) {
	    struct nchandle par;

	    if (nchislocked == 0) {
		cache_lock_maybe_shared(nch, 0);
		nchislocked = 2;
		goto again;
	    }
	    if ((par.ncp = ncp->nc_parent) == NULL) {
		if (error != EAGAIN) {
		    error = EINVAL;
		    ++nd->nl_dir_error;
		}
	    } else if (error == 0 || error == ENOENT) {
		u_int dummy_gen = 0;

		par.mount = nch->mount;
		cache_hold(&par);
		cache_lock_maybe_shared(&par, 0);
		error = naccess(nd, &par, &dummy_gen, NLC_WRITE, cred, NULL, 1);
		cache_put(&par);
		if (error)
			++nd->nl_dir_error;
	    }
	}
    }

    /*
     * NLC_EXCL check.  Target file must not exist.
     */
    if (error == 0 && (nflags & NLC_EXCL) && ncp->nc_vp != NULL)
	error = EEXIST;

    /*
     * Try to short-cut the vnode operation for intermediate directory
     * components.  This is a major SMP win because it avoids having
     * to execute a lot of code for intermediate directory components,
     * including shared refs and locks on intermediate directory vnodes.
     *
     * We can only do this if the caller does not need nflagsp.
     */
    if (error == 0 && nflagsp == NULL &&
	nflags == NLC_EXEC && (ncp->nc_flag & NCF_WXOK)) {
	if (nchislocked == 2)
		cache_unlock(nch);
	return 0;
    }

    /*
     * Get the vnode attributes so we can do the rest of our checks.
     *
     * NOTE: We only call naccess_lva() if the target exists.
     */
    if (error == 0) {
	if (nchislocked == 0) {
	    cache_lock_maybe_shared(nch, 0);
	    nchislocked = 2;
	}
#if 0
	error = cache_vget(nch, cred, LK_SHARED, &vp);
#else
	error = cache_vref(nch, cred, &vp);
#endif
	if (error == ENOENT) {
	    /*
	     * Silently zero-out ENOENT if creating or renaming
	     * (rename target).  It isn't an error.
	     */
	    if (nflags & (NLC_CREATE | NLC_RENAME_DST))
		error = 0;
	} else if (error == 0) {
	    /*
	     * Get the vnode attributes and check for illegal O_TRUNC
	     * requests and read-only mounts.
	     *
	     * NOTE: You can still open devices on read-only mounts for
	     * 	     writing.
	     *
	     * NOTE: creates/deletes/renames are handled by the NLC_WRITE
	     *	     check on the parent directory above.
	     *
	     * XXX cache the va in the namecache or in the vnode
	     */
	    error = VOP_GETATTR_LITE(vp, &lva);
	    if (error == 0 && (nflags & NLC_TRUNCATE)) {
		switch(lva.va_type) {
		case VREG:
		case VDATABASE:
		case VCHR:
		case VBLK:
		case VFIFO:
		    break;
		case VDIR:
		    error = EISDIR;
		    break;
		default:
		    error = EINVAL;
		    break;
		}
	    }
	    if (error == 0 && (nflags & NLC_WRITE) && vp->v_mount &&
		(vp->v_mount->mnt_flag & MNT_RDONLY)
	    ) {
		switch(lva.va_type) {
		case VDIR:
		case VLNK:
		case VREG:
		case VDATABASE:
		    error = EROFS;
		    break;
		default:
		    break;
		}
	    }
#if 0
	    vput(vp);
#else
	    vrele(vp);
#endif

	    /*
	     * Check permissions based on file attributes.  The passed
	     * flags (*nflagsp) are modified with feedback based on
	     * special attributes and requirements.
	     */
	    if (error == 0) {
		/*
		 * Adjust the returned (*nflagsp) if non-NULL.
		 */
		if (nflagsp) {
		    if ((lva.va_mode & VSVTX) && lva.va_uid != cred->cr_uid)
			*nflagsp |= NLC_STICKY;
		    if (lva.va_flags & APPEND)
			*nflagsp |= NLC_APPENDONLY;
		    if (lva.va_flags & IMMUTABLE)
			*nflagsp |= NLC_IMMUTABLE;
		}

		/*
		 * NCF_WXOK can be set for world-searchable directories.
		 *
		 * XXX When we implement capabilities this code would also
		 * need a cap check, or only set the flag if there are no
		 * capabilities.
		 */
		cflags = 0;
		if (lva.va_type == VDIR &&
		    (lva.va_mode & S_WXOK_MASK) == S_WXOK_MASK) {
			cflags |= NCF_WXOK;
		}
		if ((lva.va_mode & S_XOK_MASK) == 0)
			cflags |= NCF_NOTX;

		/*
		 * Track swapcache management flags in the namecache.
		 *
		 * Calculate the flags based on the current vattr_lite info
		 * and recalculate the inherited flags from the parent
		 * (the original cache linkage may have occurred without
		 * getattrs and thus have stale flags).
		 */
		if (lva.va_flags & SF_NOCACHE)
			cflags |= NCF_SF_NOCACHE;
		if (lva.va_flags & UF_CACHE)
			cflags |= NCF_UF_CACHE;
		if (ncp->nc_parent) {
			if (ncp->nc_parent->nc_flag &
			    (NCF_SF_NOCACHE | NCF_SF_PNOCACHE)) {
				cflags |= NCF_SF_PNOCACHE;
			}
			if (ncp->nc_parent->nc_flag &
			    (NCF_UF_CACHE | NCF_UF_PCACHE)) {
				cflags |= NCF_UF_PCACHE;
			}
		}

		/*
		 * We're not supposed to update nc_flag when holding a shared
		 * lock, but we allow the case for certain flags.  Note that
		 * holding an exclusive lock allows updating nc_flag without
		 * atomics.  nc_flag is not allowe to be updated at all unless
		 * a shared or exclusive lock is held.
		 */
		atomic_clear_short(&ncp->nc_flag,
				   (NCF_SF_NOCACHE | NCF_UF_CACHE |
				   NCF_SF_PNOCACHE | NCF_UF_PCACHE |
				   NCF_WXOK | NCF_NOTX) & ~cflags);
		atomic_set_short(&ncp->nc_flag, cflags);

		/*
		 * Process general access.
		 */
		error = naccess_lva(&lva, nflags, cred);
	    }
	}
    }
    if (nchislocked == 2)
	cache_unlock(nch);
    return(error);
}

/*
 * Check the requested access against the given vattr using cred.
 */
int
naccess_lva(struct vattr_lite *lvap, int nflags, struct ucred *cred)
{
    int i;
    int vmode;

    /*
     * Test the immutable bit.  Creations, deletions, renames (source
     * or destination) are not allowed.  chown/chmod/other is also not
     * allowed but is handled by SETATTR.  Hardlinks to the immutable
     * file are allowed.
     *
     * If the directory is set to immutable then creations, deletions,
     * renames (source or dest) and hardlinks to files within the directory
     * are not allowed, and regular files opened through the directory may
     * not be written to or truncated (unless a special device).
     *
     * NOTE!  New hardlinks to immutable files work but new hardlinks to
     * files, immutable or not, sitting inside an immutable directory are
     * not allowed.  As always if the file is hardlinked via some other
     * path additional hardlinks may be possible even if the file is marked
     * immutable.  The sysop needs to create a closure by checking the hard
     * link count.  Once closure is achieved you are good, and security
     * scripts should check link counts anyway.
     *
     * Writes and truncations are only allowed on special devices.
     */
    if ((lvap->va_flags & IMMUTABLE) || (nflags & NLC_IMMUTABLE)) {
	if ((nflags & NLC_IMMUTABLE) && (nflags & NLC_HLINK))
	    return (EPERM);
	if (nflags & (NLC_CREATE | NLC_DELETE |
		      NLC_RENAME_SRC | NLC_RENAME_DST)) {
	    return (EPERM);
	}
	if (nflags & (NLC_WRITE | NLC_TRUNCATE)) {
	    switch(lvap->va_type) {
	    case VDIR:
		return (EISDIR);
	    case VLNK:
	    case VREG:
	    case VDATABASE:
		return (EPERM);
	    default:
		break;
	    }
	}
    }

    /*
     * Test the no-unlink and append-only bits for opens, rename targets,
     * and deletions.  These bits are not tested for creations or
     * rename sources.
     *
     * Unlike FreeBSD we allow a file with APPEND set to be renamed.
     * If you do not wish this you must also set NOUNLINK.
     *
     * If the governing directory is marked APPEND-only it implies
     * NOUNLINK for all entries in the directory.
     */
    if (((lvap->va_flags & NOUNLINK) || (nflags & NLC_APPENDONLY)) &&
	(nflags & (NLC_DELETE | NLC_RENAME_SRC | NLC_RENAME_DST))
    ) {
	return (EPERM);
    }

    /*
     * A file marked append-only may not be deleted but can be renamed.
     */
    if ((lvap->va_flags & APPEND) &&
	(nflags & (NLC_DELETE | NLC_RENAME_DST))
    ) {
	return (EPERM);
    }

    /*
     * A file marked append-only which is opened for writing must also
     * be opened O_APPEND.
     */
    if ((lvap->va_flags & APPEND) && (nflags & (NLC_OPEN | NLC_TRUNCATE))) {
	if (nflags & NLC_TRUNCATE)
	    return (EPERM);
	if ((nflags & (NLC_OPEN | NLC_WRITE)) == (NLC_OPEN | NLC_WRITE)) {
	    if ((nflags & NLC_APPEND) == 0)
		return (EPERM);
	}
    }

    /*
     * root gets universal access
     */
    if (cred->cr_uid == 0)
	return(0);

    /*
     * Check owner perms.
     *
     * If NLC_OWN is set the owner of the file is allowed no matter when
     * the owner-mode bits say (utimes).
     */
    vmode = 0;
    if (nflags & NLC_READ)
	vmode |= S_IRUSR;
    if (nflags & NLC_WRITE)
	vmode |= S_IWUSR;
    if (nflags & NLC_EXEC)
	vmode |= S_IXUSR;

    if (cred->cr_uid == lvap->va_uid) {
	if ((nflags & NLC_OWN) == 0) {
	    if ((vmode & lvap->va_mode) != vmode)
		return(EACCES);
	}
	return(0);
    }

    /*
     * If NLC_STICKY is set only the owner may delete or rename a file.
     * This bit is typically set on /tmp.
     *
     * Note that the NLC_READ/WRITE/EXEC bits are not typically set in
     * the specific delete or rename case.  For deletions and renames we
     * usually just care about directory permissions, not file permissions.
     */
    if ((nflags & NLC_STICKY) &&
	(nflags & (NLC_RENAME_SRC | NLC_RENAME_DST | NLC_DELETE))) {
	return(EACCES);
    }

    /*
     * Check group perms
     */
    vmode >>= 3;
    for (i = 0; i < cred->cr_ngroups; ++i) {
	if (lvap->va_gid == cred->cr_groups[i]) {
	    if ((vmode & lvap->va_mode) != vmode)
		return(EACCES);
	    return(0);
	}
    }

    /*
     * Check world perms
     */
    vmode >>= 3;
    if ((vmode & lvap->va_mode) != vmode)
	return(EACCES);
    return(0);
}

/*
 * Long-term (10-second interval) statistics collection
 */
static
uint64_t
collect_nlookup_callback(int n)
{
	static uint64_t last_total;
	uint64_t save;
	uint64_t total;

	total = 0;
	for (n = 0; n < ncpus; ++n) {
		globaldata_t gd = globaldata_find(n);
		struct nchstats *sp;

		if ((sp = gd->gd_nchstats) != NULL)
			total += sp->ncs_longhits + sp->ncs_longmiss;
	}
	save = total;
	total = total - last_total;
	last_total = save;

	return total;
}

static
void
nlookup_collect_init(void *dummy __unused)
{
	kcollect_register(KCOLLECT_NLOOKUP, "nlookup", collect_nlookup_callback,
			  KCOLLECT_SCALE(KCOLLECT_NLOOKUP_FORMAT, 0));
}
SYSINIT(collect_nlookup, SI_SUB_PROP, SI_ORDER_ANY, nlookup_collect_init, 0);