aboutsummaryrefslogtreecommitdiff
path: root/sys/kern/vfs_cache.c
blob: 50ec6face6ac20dee0765d9739ba5e96b7566801 (plain) (blame)
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
/*-
 * SPDX-License-Identifier: BSD-3-Clause
 *
 * Copyright (c) 1989, 1993, 1995
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Poul-Henning Kamp of the FreeBSD Project.
 *
 * 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 University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)vfs_cache.c	8.5 (Berkeley) 3/22/95
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_ddb.h"
#include "opt_ktrace.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/capsicum.h>
#include <sys/counter.h>
#include <sys/filedesc.h>
#include <sys/fnv_hash.h>
#include <sys/kernel.h>
#include <sys/ktr.h>
#include <sys/lock.h>
#include <sys/malloc.h>
#include <sys/fcntl.h>
#include <sys/jail.h>
#include <sys/mount.h>
#include <sys/namei.h>
#include <sys/proc.h>
#include <sys/seqc.h>
#include <sys/sdt.h>
#include <sys/smr.h>
#include <sys/smp.h>
#include <sys/syscallsubr.h>
#include <sys/sysctl.h>
#include <sys/sysproto.h>
#include <sys/vnode.h>
#include <ck_queue.h>
#ifdef KTRACE
#include <sys/ktrace.h>
#endif
#ifdef INVARIANTS
#include <machine/_inttypes.h>
#endif

#include <sys/capsicum.h>

#include <security/audit/audit.h>
#include <security/mac/mac_framework.h>

#ifdef DDB
#include <ddb/ddb.h>
#endif

#include <vm/uma.h>

static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Name cache");

SDT_PROVIDER_DECLARE(vfs);
SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
    "struct vnode *");
SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
    "struct vnode *");
SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
    "char *");
SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
    "const char *");
SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
    "struct namecache *", "int", "int");
SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
    "char *", "struct vnode *");
SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
    "struct vnode *", "char *");
SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
    "struct vnode *");
SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
    "struct vnode *", "char *");
SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
    "char *");
SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
    "struct componentname *");
SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
    "struct componentname *");
SDT_PROBE_DEFINE1(vfs, namecache, purge, done, "struct vnode *");
SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
    "struct vnode *");
SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
    "char *");
SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
    "char *");
SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");

SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
SDT_PROBE_DECLARE(vfs, namei, lookup, return);

/*
 * This structure describes the elements in the cache of recent
 * names looked up by namei.
 */
struct negstate {
	u_char neg_flag;
	u_char neg_hit;
};
_Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
    "the state must fit in a union with a pointer without growing it");

struct	namecache {
	LIST_ENTRY(namecache) nc_src;	/* source vnode list */
	TAILQ_ENTRY(namecache) nc_dst;	/* destination vnode list */
	CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
	struct	vnode *nc_dvp;		/* vnode of parent of name */
	union {
		struct	vnode *nu_vp;	/* vnode the name refers to */
		struct	negstate nu_neg;/* negative entry state */
	} n_un;
	u_char	nc_flag;		/* flag bits */
	u_char	nc_nlen;		/* length of name */
	char	nc_name[0];		/* segment name + nul */
};

/*
 * struct namecache_ts repeats struct namecache layout up to the
 * nc_nlen member.
 * struct namecache_ts is used in place of struct namecache when time(s) need
 * to be stored.  The nc_dotdottime field is used when a cache entry is mapping
 * both a non-dotdot directory name plus dotdot for the directory's
 * parent.
 *
 * See below for alignment requirement.
 */
struct	namecache_ts {
	struct	timespec nc_time;	/* timespec provided by fs */
	struct	timespec nc_dotdottime;	/* dotdot timespec provided by fs */
	int	nc_ticks;		/* ticks value when entry was added */
	int	nc_pad;
	struct namecache nc_nc;
};

TAILQ_HEAD(cache_freebatch, namecache);

/*
 * At least mips n32 performs 64-bit accesses to timespec as found
 * in namecache_ts and requires them to be aligned. Since others
 * may be in the same spot suffer a little bit and enforce the
 * alignment for everyone. Note this is a nop for 64-bit platforms.
 */
#define CACHE_ZONE_ALIGNMENT	UMA_ALIGNOF(time_t)

/*
 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
 * smaller and the value was bumped to retain the total size, but it
 * was never re-evaluated for suitability. A simple test counting
 * lengths during package building shows that the value of 45 covers
 * about 86% of all added entries, reaching 99% at 65.
 *
 * Regardless of the above, use of dedicated zones instead of malloc may be
 * inducing additional waste. This may be hard to address as said zones are
 * tied to VFS SMR. Even if retaining them, the current split should be
 * re-evaluated.
 */
#ifdef __LP64__
#define	CACHE_PATH_CUTOFF	45
#define	CACHE_LARGE_PAD		6
#else
#define	CACHE_PATH_CUTOFF	41
#define	CACHE_LARGE_PAD		2
#endif

#define CACHE_ZONE_SMALL_SIZE		(offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
#define CACHE_ZONE_SMALL_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
#define CACHE_ZONE_LARGE_SIZE		(offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
#define CACHE_ZONE_LARGE_TS_SIZE	(offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)

_Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
_Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
_Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
_Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");

#define	nc_vp		n_un.nu_vp
#define	nc_neg		n_un.nu_neg

/*
 * Flags in namecache.nc_flag
 */
#define NCF_WHITE	0x01
#define NCF_ISDOTDOT	0x02
#define	NCF_TS		0x04
#define	NCF_DTS		0x08
#define	NCF_DVDROP	0x10
#define	NCF_NEGATIVE	0x20
#define	NCF_INVALID	0x40
#define	NCF_WIP		0x80

/*
 * Flags in negstate.neg_flag
 */
#define NEG_HOT		0x01

static bool	cache_neg_evict_cond(u_long lnumcache);

/*
 * Mark an entry as invalid.
 *
 * This is called before it starts getting deconstructed.
 */
static void
cache_ncp_invalidate(struct namecache *ncp)
{

	KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
	    ("%s: entry %p already invalid", __func__, ncp));
	atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
	atomic_thread_fence_rel();
}

/*
 * Check whether the entry can be safely used.
 *
 * All places which elide locks are supposed to call this after they are
 * done with reading from an entry.
 */
#define cache_ncp_canuse(ncp)	({					\
	struct namecache *_ncp = (ncp);					\
	u_char _nc_flag;						\
									\
	atomic_thread_fence_acq();					\
	_nc_flag = atomic_load_char(&_ncp->nc_flag);			\
	__predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0);	\
})

/*
 * Like the above but also checks NCF_WHITE.
 */
#define cache_fpl_neg_ncp_canuse(ncp)	({				\
	struct namecache *_ncp = (ncp);					\
	u_char _nc_flag;						\
									\
	atomic_thread_fence_acq();					\
	_nc_flag = atomic_load_char(&_ncp->nc_flag);			\
	__predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0);	\
})

/*
 * Name caching works as follows:
 *
 * Names found by directory scans are retained in a cache
 * for future reference.  It is managed LRU, so frequently
 * used names will hang around.  Cache is indexed by hash value
 * obtained from (dvp, name) where dvp refers to the directory
 * containing name.
 *
 * If it is a "negative" entry, (i.e. for a name that is known NOT to
 * exist) the vnode pointer will be NULL.
 *
 * Upon reaching the last segment of a path, if the reference
 * is for DELETE, or NOCACHE is set (rewrite), and the
 * name is located in the cache, it will be dropped.
 *
 * These locks are used (in the order in which they can be taken):
 * NAME		TYPE	ROLE
 * vnodelock	mtx	vnode lists and v_cache_dd field protection
 * bucketlock	mtx	for access to given set of hash buckets
 * neglist	mtx	negative entry LRU management
 *
 * It is legal to take multiple vnodelock and bucketlock locks. The locking
 * order is lower address first. Both are recursive.
 *
 * "." lookups are lockless.
 *
 * ".." and vnode -> name lookups require vnodelock.
 *
 * name -> vnode lookup requires the relevant bucketlock to be held for reading.
 *
 * Insertions and removals of entries require involved vnodes and bucketlocks
 * to be locked to provide safe operation against other threads modifying the
 * cache.
 *
 * Some lookups result in removal of the found entry (e.g. getting rid of a
 * negative entry with the intent to create a positive one), which poses a
 * problem when multiple threads reach the state. Similarly, two different
 * threads can purge two different vnodes and try to remove the same name.
 *
 * If the already held vnode lock is lower than the second required lock, we
 * can just take the other lock. However, in the opposite case, this could
 * deadlock. As such, this is resolved by trylocking and if that fails unlocking
 * the first node, locking everything in order and revalidating the state.
 */

VFS_SMR_DECLARE;

static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Name cache parameters");

static u_int __read_mostly	ncsize; /* the size as computed on creation or resizing */
SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RW, &ncsize, 0,
    "Total namecache capacity");

u_int ncsizefactor = 2;
SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
    "Size factor for namecache");

static u_long __read_mostly	ncnegfactor = 5; /* ratio of negative entries */
SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
    "Ratio of negative namecache entries");

/*
 * Negative entry % of namecache capacity above which automatic eviction is allowed.
 *
 * Check cache_neg_evict_cond for details.
 */
static u_int ncnegminpct = 3;

static u_int __read_mostly     neg_min; /* the above recomputed against ncsize */
SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
    "Negative entry count above which automatic eviction is allowed");

/*
 * Structures associated with name caching.
 */
#define NCHHASH(hash) \
	(&nchashtbl[(hash) & nchash])
static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
static u_long __read_mostly	nchash;			/* size of hash table */
SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
    "Size of namecache hash table");
static u_long __exclusive_cache_line	numneg;	/* number of negative entries allocated */
static u_long __exclusive_cache_line	numcache;/* number of cache entries allocated */

struct nchstats	nchstats;		/* cache effectiveness statistics */

static bool __read_frequently cache_fast_revlookup = true;
SYSCTL_BOOL(_vfs, OID_AUTO, cache_fast_revlookup, CTLFLAG_RW,
    &cache_fast_revlookup, 0, "");

static bool __read_mostly cache_rename_add = true;
SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
    &cache_rename_add, 0, "");

static u_int __exclusive_cache_line neg_cycle;

#define ncneghash	3
#define	numneglists	(ncneghash + 1)

struct neglist {
	struct mtx		nl_evict_lock;
	struct mtx		nl_lock __aligned(CACHE_LINE_SIZE);
	TAILQ_HEAD(, namecache) nl_list;
	TAILQ_HEAD(, namecache) nl_hotlist;
	u_long			nl_hotnum;
} __aligned(CACHE_LINE_SIZE);

static struct neglist neglists[numneglists];

static inline struct neglist *
NCP2NEGLIST(struct namecache *ncp)
{

	return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
}

static inline struct negstate *
NCP2NEGSTATE(struct namecache *ncp)
{

	MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
	return (&ncp->nc_neg);
}

#define	numbucketlocks (ncbuckethash + 1)
static u_int __read_mostly  ncbuckethash;
static struct mtx_padalign __read_mostly  *bucketlocks;
#define	HASH2BUCKETLOCK(hash) \
	((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))

#define	numvnodelocks (ncvnodehash + 1)
static u_int __read_mostly  ncvnodehash;
static struct mtx __read_mostly *vnodelocks;
static inline struct mtx *
VP2VNODELOCK(struct vnode *vp)
{

	return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
}

static void
cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
{
	struct namecache_ts *ncp_ts;

	KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
	    (tsp == NULL && ticksp == NULL),
	    ("No NCF_TS"));

	if (tsp == NULL)
		return;

	ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
	*tsp = ncp_ts->nc_time;
	*ticksp = ncp_ts->nc_ticks;
}

#ifdef DEBUG_CACHE
static int __read_mostly	doingcache = 1;	/* 1 => enable the cache */
SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
    "VFS namecache enabled");
#endif

/* Export size information to userland */
SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
    sizeof(struct namecache), "sizeof(struct namecache)");

/*
 * The new name cache statistics
 */
static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Name cache statistics");

#define STATNODE_ULONG(name, varname, descr)					\
	SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
#define STATNODE_COUNTER(name, varname, descr)					\
	static COUNTER_U64_DEFINE_EARLY(varname);				\
	SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
	    descr);
STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
STATNODE_ULONG(count, numcache, "Number of cache entries");
STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
STATNODE_COUNTER(dothits, dothits, "Number of '.' hits");
STATNODE_COUNTER(dotdothis, dotdothits, "Number of '..' hits");
STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
STATNODE_COUNTER(posszaps, numposzaps,
    "Number of cache hits (positive) we do not want to cache");
STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
STATNODE_COUNTER(negzaps, numnegzaps,
    "Number of cache hits (negative) we do not want to cache");
STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
/* These count for vn_getcwd(), too. */
STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
STATNODE_COUNTER(fullpathfail1, numfullpathfail1, "Number of fullpath search errors (ENOTDIR)");
STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
    "Number of fullpath search errors (VOP_VPTOCNP failures)");
STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");

/*
 * Debug or developer statistics.
 */
static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Name cache debugging");
#define DEBUGNODE_ULONG(name, varname, descr)					\
	SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
#define DEBUGNODE_COUNTER(name, varname, descr)					\
	static COUNTER_U64_DEFINE_EARLY(varname);				\
	SYSCTL_COUNTER_U64(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, \
	    descr);
DEBUGNODE_COUNTER(zap_bucket_relock_success, zap_bucket_relock_success,
    "Number of successful removals after relocking");
static long zap_bucket_fail;
DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
static long zap_bucket_fail2;
DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
static long cache_lock_vnodes_cel_3_failures;
DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
    "Number of times 3-way vnode locking failed");

static void cache_zap_locked(struct namecache *ncp);
static int vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf,
    char **freebuf, size_t *buflen);
static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
    char **retbuf, size_t *buflen, size_t addend);
static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
    char **retbuf, size_t *buflen);
static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
    char **retbuf, size_t *len, size_t addend);

static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");

static inline void
cache_assert_vlp_locked(struct mtx *vlp)
{

	if (vlp != NULL)
		mtx_assert(vlp, MA_OWNED);
}

static inline void
cache_assert_vnode_locked(struct vnode *vp)
{
	struct mtx *vlp;

	vlp = VP2VNODELOCK(vp);
	cache_assert_vlp_locked(vlp);
}

/*
 * Directory vnodes with entries are held for two reasons:
 * 1. make them less of a target for reclamation in vnlru
 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
 *
 * It will be feasible to stop doing it altogether if all filesystems start
 * supporting lockless lookup.
 */
static void
cache_hold_vnode(struct vnode *vp)
{

	cache_assert_vnode_locked(vp);
	VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
	vhold(vp);
	counter_u64_add(numcachehv, 1);
}

static void
cache_drop_vnode(struct vnode *vp)
{

	/*
	 * Called after all locks are dropped, meaning we can't assert
	 * on the state of v_cache_src.
	 */
	vdrop(vp);
	counter_u64_add(numcachehv, -1);
}

/*
 * UMA zones.
 */
static uma_zone_t __read_mostly cache_zone_small;
static uma_zone_t __read_mostly cache_zone_small_ts;
static uma_zone_t __read_mostly cache_zone_large;
static uma_zone_t __read_mostly cache_zone_large_ts;

char *
cache_symlink_alloc(size_t size, int flags)
{

	if (size < CACHE_ZONE_SMALL_SIZE) {
		return (uma_zalloc_smr(cache_zone_small, flags));
	}
	if (size < CACHE_ZONE_LARGE_SIZE) {
		return (uma_zalloc_smr(cache_zone_large, flags));
	}
	counter_u64_add(symlinktoobig, 1);
	SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
	return (NULL);
}

void
cache_symlink_free(char *string, size_t size)
{

	MPASS(string != NULL);
	KASSERT(size < CACHE_ZONE_LARGE_SIZE,
	    ("%s: size %zu too big", __func__, size));

	if (size < CACHE_ZONE_SMALL_SIZE) {
		uma_zfree_smr(cache_zone_small, string);
		return;
	}
	if (size < CACHE_ZONE_LARGE_SIZE) {
		uma_zfree_smr(cache_zone_large, string);
		return;
	}
	__assert_unreachable();
}

static struct namecache *
cache_alloc_uma(int len, bool ts)
{
	struct namecache_ts *ncp_ts;
	struct namecache *ncp;

	if (__predict_false(ts)) {
		if (len <= CACHE_PATH_CUTOFF)
			ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
		else
			ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
		ncp = &ncp_ts->nc_nc;
	} else {
		if (len <= CACHE_PATH_CUTOFF)
			ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
		else
			ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
	}
	return (ncp);
}

static void
cache_free_uma(struct namecache *ncp)
{
	struct namecache_ts *ncp_ts;

	if (__predict_false(ncp->nc_flag & NCF_TS)) {
		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
			uma_zfree_smr(cache_zone_small_ts, ncp_ts);
		else
			uma_zfree_smr(cache_zone_large_ts, ncp_ts);
	} else {
		if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
			uma_zfree_smr(cache_zone_small, ncp);
		else
			uma_zfree_smr(cache_zone_large, ncp);
	}
}

static struct namecache *
cache_alloc(int len, bool ts)
{
	u_long lnumcache;

	/*
	 * Avoid blowout in namecache entries.
	 *
	 * Bugs:
	 * 1. filesystems may end up trying to add an already existing entry
	 * (for example this can happen after a cache miss during concurrent
	 * lookup), in which case we will call cache_neg_evict despite not
	 * adding anything.
	 * 2. the routine may fail to free anything and no provisions are made
	 * to make it try harder (see the inside for failure modes)
	 * 3. it only ever looks at negative entries.
	 */
	lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
	if (cache_neg_evict_cond(lnumcache)) {
		lnumcache = atomic_load_long(&numcache);
	}
	if (__predict_false(lnumcache >= ncsize)) {
		atomic_subtract_long(&numcache, 1);
		counter_u64_add(numdrops, 1);
		return (NULL);
	}
	return (cache_alloc_uma(len, ts));
}

static void
cache_free(struct namecache *ncp)
{

	MPASS(ncp != NULL);
	if ((ncp->nc_flag & NCF_DVDROP) != 0) {
		cache_drop_vnode(ncp->nc_dvp);
	}
	cache_free_uma(ncp);
	atomic_subtract_long(&numcache, 1);
}

static void
cache_free_batch(struct cache_freebatch *batch)
{
	struct namecache *ncp, *nnp;
	int i;

	i = 0;
	if (TAILQ_EMPTY(batch))
		goto out;
	TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
		if ((ncp->nc_flag & NCF_DVDROP) != 0) {
			cache_drop_vnode(ncp->nc_dvp);
		}
		cache_free_uma(ncp);
		i++;
	}
	atomic_subtract_long(&numcache, i);
out:
	SDT_PROBE1(vfs, namecache, purge, batch, i);
}

/*
 * Hashing.
 *
 * The code was made to use FNV in 2001 and this choice needs to be revisited.
 *
 * Short summary of the difficulty:
 * The longest name which can be inserted is NAME_MAX characters in length (or
 * 255 at the time of writing this comment), while majority of names used in
 * practice are significantly shorter (mostly below 10). More importantly
 * majority of lookups performed find names are even shorter than that.
 *
 * This poses a problem where hashes which do better than FNV past word size
 * (or so) tend to come with additional overhead when finalizing the result,
 * making them noticeably slower for the most commonly used range.
 *
 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
 *
 * When looking it up the most time consuming part by a large margin (at least
 * on amd64) is hashing.  Replacing FNV with something which pessimizes short
 * input would make the slowest part stand out even more.
 */

/*
 * TODO: With the value stored we can do better than computing the hash based
 * on the address.
 */
static void
cache_prehash(struct vnode *vp)
{

	vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
}

static uint32_t
cache_get_hash(char *name, u_char len, struct vnode *dvp)
{

	return (fnv_32_buf(name, len, dvp->v_nchash));
}

static uint32_t
cache_get_hash_iter_start(struct vnode *dvp)
{

	return (dvp->v_nchash);
}

static uint32_t
cache_get_hash_iter(char c, uint32_t hash)
{

	return (fnv_32_buf(&c, 1, hash));
}

static uint32_t
cache_get_hash_iter_finish(uint32_t hash)
{

	return (hash);
}

static inline struct nchashhead *
NCP2BUCKET(struct namecache *ncp)
{
	uint32_t hash;

	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
	return (NCHHASH(hash));
}

static inline struct mtx *
NCP2BUCKETLOCK(struct namecache *ncp)
{
	uint32_t hash;

	hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
	return (HASH2BUCKETLOCK(hash));
}

#ifdef INVARIANTS
static void
cache_assert_bucket_locked(struct namecache *ncp)
{
	struct mtx *blp;

	blp = NCP2BUCKETLOCK(ncp);
	mtx_assert(blp, MA_OWNED);
}

static void
cache_assert_bucket_unlocked(struct namecache *ncp)
{
	struct mtx *blp;

	blp = NCP2BUCKETLOCK(ncp);
	mtx_assert(blp, MA_NOTOWNED);
}
#else
#define cache_assert_bucket_locked(x) do { } while (0)
#define cache_assert_bucket_unlocked(x) do { } while (0)
#endif

#define cache_sort_vnodes(x, y)	_cache_sort_vnodes((void **)(x), (void **)(y))
static void
_cache_sort_vnodes(void **p1, void **p2)
{
	void *tmp;

	MPASS(*p1 != NULL || *p2 != NULL);

	if (*p1 > *p2) {
		tmp = *p2;
		*p2 = *p1;
		*p1 = tmp;
	}
}

static void
cache_lock_all_buckets(void)
{
	u_int i;

	for (i = 0; i < numbucketlocks; i++)
		mtx_lock(&bucketlocks[i]);
}

static void
cache_unlock_all_buckets(void)
{
	u_int i;

	for (i = 0; i < numbucketlocks; i++)
		mtx_unlock(&bucketlocks[i]);
}

static void
cache_lock_all_vnodes(void)
{
	u_int i;

	for (i = 0; i < numvnodelocks; i++)
		mtx_lock(&vnodelocks[i]);
}

static void
cache_unlock_all_vnodes(void)
{
	u_int i;

	for (i = 0; i < numvnodelocks; i++)
		mtx_unlock(&vnodelocks[i]);
}

static int
cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
{

	cache_sort_vnodes(&vlp1, &vlp2);

	if (vlp1 != NULL) {
		if (!mtx_trylock(vlp1))
			return (EAGAIN);
	}
	if (!mtx_trylock(vlp2)) {
		if (vlp1 != NULL)
			mtx_unlock(vlp1);
		return (EAGAIN);
	}

	return (0);
}

static void
cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
{

	MPASS(vlp1 != NULL || vlp2 != NULL);
	MPASS(vlp1 <= vlp2);

	if (vlp1 != NULL)
		mtx_lock(vlp1);
	if (vlp2 != NULL)
		mtx_lock(vlp2);
}

static void
cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
{

	MPASS(vlp1 != NULL || vlp2 != NULL);

	if (vlp1 != NULL)
		mtx_unlock(vlp1);
	if (vlp2 != NULL)
		mtx_unlock(vlp2);
}

static int
sysctl_nchstats(SYSCTL_HANDLER_ARGS)
{
	struct nchstats snap;

	if (req->oldptr == NULL)
		return (SYSCTL_OUT(req, 0, sizeof(snap)));

	snap = nchstats;
	snap.ncs_goodhits = counter_u64_fetch(numposhits);
	snap.ncs_neghits = counter_u64_fetch(numneghits);
	snap.ncs_badhits = counter_u64_fetch(numposzaps) +
	    counter_u64_fetch(numnegzaps);
	snap.ncs_miss = counter_u64_fetch(nummisszap) +
	    counter_u64_fetch(nummiss);

	return (SYSCTL_OUT(req, &snap, sizeof(snap)));
}
SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
    CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
    "VFS cache effectiveness statistics");

static void
cache_recalc_neg_min(u_int val)
{

	neg_min = (ncsize * val) / 100;
}

static int
sysctl_negminpct(SYSCTL_HANDLER_ARGS)
{
	u_int val;
	int error;

	val = ncnegminpct;
	error = sysctl_handle_int(oidp, &val, 0, req);
	if (error != 0 || req->newptr == NULL)
		return (error);

	if (val == ncnegminpct)
		return (0);
	if (val < 0 || val > 99)
		return (EINVAL);
	ncnegminpct = val;
	cache_recalc_neg_min(val);
	return (0);
}

SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
    CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
    "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");

#ifdef DIAGNOSTIC
/*
 * Grab an atomic snapshot of the name cache hash chain lengths
 */
static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
    CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
    "hash table stats");

static int
sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
{
	struct nchashhead *ncpp;
	struct namecache *ncp;
	int i, error, n_nchash, *cntbuf;

retry:
	n_nchash = nchash + 1;	/* nchash is max index, not count */
	if (req->oldptr == NULL)
		return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
	cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
	cache_lock_all_buckets();
	if (n_nchash != nchash + 1) {
		cache_unlock_all_buckets();
		free(cntbuf, M_TEMP);
		goto retry;
	}
	/* Scan hash tables counting entries */
	for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
		CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
			cntbuf[i]++;
	cache_unlock_all_buckets();
	for (error = 0, i = 0; i < n_nchash; i++)
		if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
			break;
	free(cntbuf, M_TEMP);
	return (error);
}
SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
    CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
    "nchash chain lengths");

static int
sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
{
	int error;
	struct nchashhead *ncpp;
	struct namecache *ncp;
	int n_nchash;
	int count, maxlength, used, pct;

	if (!req->oldptr)
		return SYSCTL_OUT(req, 0, 4 * sizeof(int));

	cache_lock_all_buckets();
	n_nchash = nchash + 1;	/* nchash is max index, not count */
	used = 0;
	maxlength = 0;

	/* Scan hash tables for applicable entries */
	for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
		count = 0;
		CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
			count++;
		}
		if (count)
			used++;
		if (maxlength < count)
			maxlength = count;
	}
	n_nchash = nchash + 1;
	cache_unlock_all_buckets();
	pct = (used * 100) / (n_nchash / 100);
	error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
	if (error)
		return (error);
	error = SYSCTL_OUT(req, &used, sizeof(used));
	if (error)
		return (error);
	error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
	if (error)
		return (error);
	error = SYSCTL_OUT(req, &pct, sizeof(pct));
	if (error)
		return (error);
	return (0);
}
SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
    CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
    "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
#endif

/*
 * Negative entries management
 *
 * Various workloads create plenty of negative entries and barely use them
 * afterwards. Moreover malicious users can keep performing bogus lookups
 * adding even more entries. For example "make tinderbox" as of writing this
 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
 * negative.
 *
 * As such, a rather aggressive eviction method is needed. The currently
 * employed method is a placeholder.
 *
 * Entries are split over numneglists separate lists, each of which is further
 * split into hot and cold entries. Entries get promoted after getting a hit.
 * Eviction happens on addition of new entry.
 */
static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
    "Name cache negative entry statistics");

SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
    "Number of negative cache entries");

static COUNTER_U64_DEFINE_EARLY(neg_created);
SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
    "Number of created negative entries");

static COUNTER_U64_DEFINE_EARLY(neg_evicted);
SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
    "Number of evicted negative entries");

static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
    &neg_evict_skipped_empty,
    "Number of times evicting failed due to lack of entries");

static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
    &neg_evict_skipped_missed,
    "Number of times evicting failed due to target entry disappearing");

static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
    &neg_evict_skipped_contended,
    "Number of times evicting failed due to contention");

SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
    "Number of cache hits (negative)");

static int
sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
{
	int i, out;

	out = 0;
	for (i = 0; i < numneglists; i++)
		out += neglists[i].nl_hotnum;

	return (SYSCTL_OUT(req, &out, sizeof(out)));
}
SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
    CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
    "Number of hot negative entries");

static void
cache_neg_init(struct namecache *ncp)
{
	struct negstate *ns;

	ncp->nc_flag |= NCF_NEGATIVE;
	ns = NCP2NEGSTATE(ncp);
	ns->neg_flag = 0;
	ns->neg_hit = 0;
	counter_u64_add(neg_created, 1);
}

#define CACHE_NEG_PROMOTION_THRESH 2

static bool
cache_neg_hit_prep(struct namecache *ncp)
{
	struct negstate *ns;
	u_char n;

	ns = NCP2NEGSTATE(ncp);
	n = atomic_load_char(&ns->neg_hit);
	for (;;) {
		if (n >= CACHE_NEG_PROMOTION_THRESH)
			return (false);
		if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
			break;
	}
	return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
}

/*
 * Nothing to do here but it is provided for completeness as some
 * cache_neg_hit_prep callers may end up returning without even
 * trying to promote.
 */
#define cache_neg_hit_abort(ncp)	do { } while (0)

static void
cache_neg_hit_finish(struct namecache *ncp)
{

	SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
	counter_u64_add(numneghits, 1);
}

/*
 * Move a negative entry to the hot list.
 */
static void
cache_neg_promote_locked(struct namecache *ncp)
{
	struct neglist *nl;
	struct negstate *ns;

	ns = NCP2NEGSTATE(ncp);
	nl = NCP2NEGLIST(ncp);
	mtx_assert(&nl->nl_lock, MA_OWNED);
	if ((ns->neg_flag & NEG_HOT) == 0) {
		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
		TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
		nl->nl_hotnum++;
		ns->neg_flag |= NEG_HOT;
	}
}

/*
 * Move a hot negative entry to the cold list.
 */
static void
cache_neg_demote_locked(struct namecache *ncp)
{
	struct neglist *nl;
	struct negstate *ns;

	ns = NCP2NEGSTATE(ncp);
	nl = NCP2NEGLIST(ncp);
	mtx_assert(&nl->nl_lock, MA_OWNED);
	MPASS(ns->neg_flag & NEG_HOT);
	TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
	nl->nl_hotnum--;
	ns->neg_flag &= ~NEG_HOT;
	atomic_store_char(&ns->neg_hit, 0);
}

/*
 * Move a negative entry to the hot list if it matches the lookup.
 *
 * We have to take locks, but they may be contended and in the worst
 * case we may need to go off CPU. We don't want to spin within the
 * smr section and we can't block with it. Exiting the section means
 * the found entry could have been evicted. We are going to look it
 * up again.
 */
static bool
cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
    struct namecache *oncp, uint32_t hash)
{
	struct namecache *ncp;
	struct neglist *nl;
	u_char nc_flag;

	nl = NCP2NEGLIST(oncp);

	mtx_lock(&nl->nl_lock);
	/*
	 * For hash iteration.
	 */
	vfs_smr_enter();

	/*
	 * Avoid all surprises by only succeeding if we got the same entry and
	 * bailing completely otherwise.
	 * XXX There are no provisions to keep the vnode around, meaning we may
	 * end up promoting a negative entry for a *new* vnode and returning
	 * ENOENT on its account. This is the error we want to return anyway
	 * and promotion is harmless.
	 *
	 * In particular at this point there can be a new ncp which matches the
	 * search but hashes to a different neglist.
	 */
	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp == oncp)
			break;
	}

	/*
	 * No match to begin with.
	 */
	if (__predict_false(ncp == NULL)) {
		goto out_abort;
	}

	/*
	 * The newly found entry may be something different...
	 */
	if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
	    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
		goto out_abort;
	}

	/*
	 * ... and not even negative.
	 */
	nc_flag = atomic_load_char(&ncp->nc_flag);
	if ((nc_flag & NCF_NEGATIVE) == 0) {
		goto out_abort;
	}

	if (!cache_ncp_canuse(ncp)) {
		goto out_abort;
	}

	cache_neg_promote_locked(ncp);
	cache_neg_hit_finish(ncp);
	vfs_smr_exit();
	mtx_unlock(&nl->nl_lock);
	return (true);
out_abort:
	vfs_smr_exit();
	mtx_unlock(&nl->nl_lock);
	return (false);
}

static void
cache_neg_promote(struct namecache *ncp)
{
	struct neglist *nl;

	nl = NCP2NEGLIST(ncp);
	mtx_lock(&nl->nl_lock);
	cache_neg_promote_locked(ncp);
	mtx_unlock(&nl->nl_lock);
}

static void
cache_neg_insert(struct namecache *ncp)
{
	struct neglist *nl;

	MPASS(ncp->nc_flag & NCF_NEGATIVE);
	cache_assert_bucket_locked(ncp);
	nl = NCP2NEGLIST(ncp);
	mtx_lock(&nl->nl_lock);
	TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
	mtx_unlock(&nl->nl_lock);
	atomic_add_long(&numneg, 1);
}

static void
cache_neg_remove(struct namecache *ncp)
{
	struct neglist *nl;
	struct negstate *ns;

	cache_assert_bucket_locked(ncp);
	nl = NCP2NEGLIST(ncp);
	ns = NCP2NEGSTATE(ncp);
	mtx_lock(&nl->nl_lock);
	if ((ns->neg_flag & NEG_HOT) != 0) {
		TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
		nl->nl_hotnum--;
	} else {
		TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
	}
	mtx_unlock(&nl->nl_lock);
	atomic_subtract_long(&numneg, 1);
}

static struct neglist *
cache_neg_evict_select_list(void)
{
	struct neglist *nl;
	u_int c;

	c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
	nl = &neglists[c % numneglists];
	if (!mtx_trylock(&nl->nl_evict_lock)) {
		counter_u64_add(neg_evict_skipped_contended, 1);
		return (NULL);
	}
	return (nl);
}

static struct namecache *
cache_neg_evict_select_entry(struct neglist *nl)
{
	struct namecache *ncp, *lncp;
	struct negstate *ns, *lns;
	int i;

	mtx_assert(&nl->nl_evict_lock, MA_OWNED);
	mtx_assert(&nl->nl_lock, MA_OWNED);
	ncp = TAILQ_FIRST(&nl->nl_list);
	if (ncp == NULL)
		return (NULL);
	lncp = ncp;
	lns = NCP2NEGSTATE(lncp);
	for (i = 1; i < 4; i++) {
		ncp = TAILQ_NEXT(ncp, nc_dst);
		if (ncp == NULL)
			break;
		ns = NCP2NEGSTATE(ncp);
		if (ns->neg_hit < lns->neg_hit) {
			lncp = ncp;
			lns = ns;
		}
	}
	return (lncp);
}

static bool
cache_neg_evict(void)
{
	struct namecache *ncp, *ncp2;
	struct neglist *nl;
	struct vnode *dvp;
	struct mtx *dvlp;
	struct mtx *blp;
	uint32_t hash;
	u_char nlen;
	bool evicted;

	nl = cache_neg_evict_select_list();
	if (nl == NULL) {
		return (false);
	}

	mtx_lock(&nl->nl_lock);
	ncp = TAILQ_FIRST(&nl->nl_hotlist);
	if (ncp != NULL) {
		cache_neg_demote_locked(ncp);
	}
	ncp = cache_neg_evict_select_entry(nl);
	if (ncp == NULL) {
		counter_u64_add(neg_evict_skipped_empty, 1);
		mtx_unlock(&nl->nl_lock);
		mtx_unlock(&nl->nl_evict_lock);
		return (false);
	}
	nlen = ncp->nc_nlen;
	dvp = ncp->nc_dvp;
	hash = cache_get_hash(ncp->nc_name, nlen, dvp);
	dvlp = VP2VNODELOCK(dvp);
	blp = HASH2BUCKETLOCK(hash);
	mtx_unlock(&nl->nl_lock);
	mtx_unlock(&nl->nl_evict_lock);
	mtx_lock(dvlp);
	mtx_lock(blp);
	/*
	 * Note that since all locks were dropped above, the entry may be
	 * gone or reallocated to be something else.
	 */
	CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
		if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
		    ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
			break;
	}
	if (ncp2 == NULL) {
		counter_u64_add(neg_evict_skipped_missed, 1);
		ncp = NULL;
		evicted = false;
	} else {
		MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
		MPASS(blp == NCP2BUCKETLOCK(ncp));
		SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
		    ncp->nc_name);
		cache_zap_locked(ncp);
		counter_u64_add(neg_evicted, 1);
		evicted = true;
	}
	mtx_unlock(blp);
	mtx_unlock(dvlp);
	if (ncp != NULL)
		cache_free(ncp);
	return (evicted);
}

/*
 * Maybe evict a negative entry to create more room.
 *
 * The ncnegfactor parameter limits what fraction of the total count
 * can comprise of negative entries. However, if the cache is just
 * warming up this leads to excessive evictions.  As such, ncnegminpct
 * (recomputed to neg_min) dictates whether the above should be
 * applied.
 *
 * Try evicting if the cache is close to full capacity regardless of
 * other considerations.
 */
static bool
cache_neg_evict_cond(u_long lnumcache)
{
	u_long lnumneg;

	if (ncsize - 1000 < lnumcache)
		goto out_evict;
	lnumneg = atomic_load_long(&numneg);
	if (lnumneg < neg_min)
		return (false);
	if (lnumneg * ncnegfactor < lnumcache)
		return (false);
out_evict:
	return (cache_neg_evict());
}

/*
 * cache_zap_locked():
 *
 *   Removes a namecache entry from cache, whether it contains an actual
 *   pointer to a vnode or if it is just a negative cache entry.
 */
static void
cache_zap_locked(struct namecache *ncp)
{
	struct nchashhead *ncpp;
	struct vnode *dvp, *vp;

	dvp = ncp->nc_dvp;
	vp = ncp->nc_vp;

	if (!(ncp->nc_flag & NCF_NEGATIVE))
		cache_assert_vnode_locked(vp);
	cache_assert_vnode_locked(dvp);
	cache_assert_bucket_locked(ncp);

	cache_ncp_invalidate(ncp);

	ncpp = NCP2BUCKET(ncp);
	CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
	if (!(ncp->nc_flag & NCF_NEGATIVE)) {
		SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
		TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
		if (ncp == vp->v_cache_dd) {
			atomic_store_ptr(&vp->v_cache_dd, NULL);
		}
	} else {
		SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
		cache_neg_remove(ncp);
	}
	if (ncp->nc_flag & NCF_ISDOTDOT) {
		if (ncp == dvp->v_cache_dd) {
			atomic_store_ptr(&dvp->v_cache_dd, NULL);
		}
	} else {
		LIST_REMOVE(ncp, nc_src);
		if (LIST_EMPTY(&dvp->v_cache_src)) {
			ncp->nc_flag |= NCF_DVDROP;
		}
	}
}

static void
cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
{
	struct mtx *blp;

	MPASS(ncp->nc_dvp == vp);
	MPASS(ncp->nc_flag & NCF_NEGATIVE);
	cache_assert_vnode_locked(vp);

	blp = NCP2BUCKETLOCK(ncp);
	mtx_lock(blp);
	cache_zap_locked(ncp);
	mtx_unlock(blp);
}

static bool
cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
    struct mtx **vlpp)
{
	struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
	struct mtx *blp;

	MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
	cache_assert_vnode_locked(vp);

	if (ncp->nc_flag & NCF_NEGATIVE) {
		if (*vlpp != NULL) {
			mtx_unlock(*vlpp);
			*vlpp = NULL;
		}
		cache_zap_negative_locked_vnode_kl(ncp, vp);
		return (true);
	}

	pvlp = VP2VNODELOCK(vp);
	blp = NCP2BUCKETLOCK(ncp);
	vlp1 = VP2VNODELOCK(ncp->nc_dvp);
	vlp2 = VP2VNODELOCK(ncp->nc_vp);

	if (*vlpp == vlp1 || *vlpp == vlp2) {
		to_unlock = *vlpp;
		*vlpp = NULL;
	} else {
		if (*vlpp != NULL) {
			mtx_unlock(*vlpp);
			*vlpp = NULL;
		}
		cache_sort_vnodes(&vlp1, &vlp2);
		if (vlp1 == pvlp) {
			mtx_lock(vlp2);
			to_unlock = vlp2;
		} else {
			if (!mtx_trylock(vlp1))
				goto out_relock;
			to_unlock = vlp1;
		}
	}
	mtx_lock(blp);
	cache_zap_locked(ncp);
	mtx_unlock(blp);
	if (to_unlock != NULL)
		mtx_unlock(to_unlock);
	return (true);

out_relock:
	mtx_unlock(vlp2);
	mtx_lock(vlp1);
	mtx_lock(vlp2);
	MPASS(*vlpp == NULL);
	*vlpp = vlp1;
	return (false);
}

/*
 * If trylocking failed we can get here. We know enough to take all needed locks
 * in the right order and re-lookup the entry.
 */
static int
cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
    struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
    struct mtx *blp)
{
	struct namecache *rncp;

	cache_assert_bucket_unlocked(ncp);

	cache_sort_vnodes(&dvlp, &vlp);
	cache_lock_vnodes(dvlp, vlp);
	mtx_lock(blp);
	CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
		if (rncp == ncp && rncp->nc_dvp == dvp &&
		    rncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
			break;
	}
	if (rncp != NULL) {
		cache_zap_locked(rncp);
		mtx_unlock(blp);
		cache_unlock_vnodes(dvlp, vlp);
		counter_u64_add(zap_bucket_relock_success, 1);
		return (0);
	}

	mtx_unlock(blp);
	cache_unlock_vnodes(dvlp, vlp);
	return (EAGAIN);
}

static int __noinline
cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
    uint32_t hash, struct mtx *blp)
{
	struct mtx *dvlp, *vlp;
	struct vnode *dvp;

	cache_assert_bucket_locked(ncp);

	dvlp = VP2VNODELOCK(ncp->nc_dvp);
	vlp = NULL;
	if (!(ncp->nc_flag & NCF_NEGATIVE))
		vlp = VP2VNODELOCK(ncp->nc_vp);
	if (cache_trylock_vnodes(dvlp, vlp) == 0) {
		cache_zap_locked(ncp);
		mtx_unlock(blp);
		cache_unlock_vnodes(dvlp, vlp);
		return (0);
	}

	dvp = ncp->nc_dvp;
	mtx_unlock(blp);
	return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
}

static __noinline int
cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
{
	struct namecache *ncp;
	struct mtx *blp;
	struct mtx *dvlp, *dvlp2;
	uint32_t hash;
	int error;

	if (cnp->cn_namelen == 2 &&
	    cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
		dvlp = VP2VNODELOCK(dvp);
		dvlp2 = NULL;
		mtx_lock(dvlp);
retry_dotdot:
		ncp = dvp->v_cache_dd;
		if (ncp == NULL) {
			mtx_unlock(dvlp);
			if (dvlp2 != NULL)
				mtx_unlock(dvlp2);
			SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
			return (0);
		}
		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
			if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
				goto retry_dotdot;
			MPASS(dvp->v_cache_dd == NULL);
			mtx_unlock(dvlp);
			if (dvlp2 != NULL)
				mtx_unlock(dvlp2);
			cache_free(ncp);
		} else {
			atomic_store_ptr(&dvp->v_cache_dd, NULL);
			mtx_unlock(dvlp);
			if (dvlp2 != NULL)
				mtx_unlock(dvlp2);
		}
		SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
		return (1);
	}

	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
	blp = HASH2BUCKETLOCK(hash);
retry:
	if (CK_SLIST_EMPTY(NCHHASH(hash)))
		goto out_no_entry;

	mtx_lock(blp);

	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
			break;
	}

	if (ncp == NULL) {
		mtx_unlock(blp);
		goto out_no_entry;
	}

	error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
	if (__predict_false(error != 0)) {
		zap_bucket_fail++;
		goto retry;
	}
	counter_u64_add(numposzaps, 1);
	SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
	cache_free(ncp);
	return (1);
out_no_entry:
	counter_u64_add(nummisszap, 1);
	SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
	return (0);
}

static int __noinline
cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
    struct timespec *tsp, int *ticksp)
{
	int ltype;

	*vpp = dvp;
	counter_u64_add(dothits, 1);
	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
	if (tsp != NULL)
		timespecclear(tsp);
	if (ticksp != NULL)
		*ticksp = ticks;
	vrefact(*vpp);
	/*
	 * When we lookup "." we still can be asked to lock it
	 * differently...
	 */
	ltype = cnp->cn_lkflags & LK_TYPE_MASK;
	if (ltype != VOP_ISLOCKED(*vpp)) {
		if (ltype == LK_EXCLUSIVE) {
			vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
			if (VN_IS_DOOMED((*vpp))) {
				/* forced unmount */
				vrele(*vpp);
				*vpp = NULL;
				return (ENOENT);
			}
		} else
			vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
	}
	return (-1);
}

static int __noinline
cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
    struct timespec *tsp, int *ticksp)
{
	struct namecache_ts *ncp_ts;
	struct namecache *ncp;
	struct mtx *dvlp;
	enum vgetstate vs;
	int error, ltype;
	bool whiteout;

	MPASS((cnp->cn_flags & ISDOTDOT) != 0);

	if ((cnp->cn_flags & MAKEENTRY) == 0) {
		cache_remove_cnp(dvp, cnp);
		return (0);
	}

	counter_u64_add(dotdothits, 1);
retry:
	dvlp = VP2VNODELOCK(dvp);
	mtx_lock(dvlp);
	ncp = dvp->v_cache_dd;
	if (ncp == NULL) {
		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
		mtx_unlock(dvlp);
		return (0);
	}
	if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
		if (ncp->nc_flag & NCF_NEGATIVE)
			*vpp = NULL;
		else
			*vpp = ncp->nc_vp;
	} else
		*vpp = ncp->nc_dvp;
	if (*vpp == NULL)
		goto negative_success;
	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
	cache_out_ts(ncp, tsp, ticksp);
	if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
	    NCF_DTS && tsp != NULL) {
		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
		*tsp = ncp_ts->nc_dotdottime;
	}

	MPASS(dvp != *vpp);
	ltype = VOP_ISLOCKED(dvp);
	VOP_UNLOCK(dvp);
	vs = vget_prep(*vpp);
	mtx_unlock(dvlp);
	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
	vn_lock(dvp, ltype | LK_RETRY);
	if (VN_IS_DOOMED(dvp)) {
		if (error == 0)
			vput(*vpp);
		*vpp = NULL;
		return (ENOENT);
	}
	if (error) {
		*vpp = NULL;
		goto retry;
	}
	return (-1);
negative_success:
	if (__predict_false(cnp->cn_nameiop == CREATE)) {
		if (cnp->cn_flags & ISLASTCN) {
			counter_u64_add(numnegzaps, 1);
			cache_zap_negative_locked_vnode_kl(ncp, dvp);
			mtx_unlock(dvlp);
			cache_free(ncp);
			return (0);
		}
	}

	whiteout = (ncp->nc_flag & NCF_WHITE);
	cache_out_ts(ncp, tsp, ticksp);
	if (cache_neg_hit_prep(ncp))
		cache_neg_promote(ncp);
	else
		cache_neg_hit_finish(ncp);
	mtx_unlock(dvlp);
	if (whiteout)
		cnp->cn_flags |= ISWHITEOUT;
	return (ENOENT);
}

/**
 * Lookup a name in the name cache
 *
 * # Arguments
 *
 * - dvp:	Parent directory in which to search.
 * - vpp:	Return argument.  Will contain desired vnode on cache hit.
 * - cnp:	Parameters of the name search.  The most interesting bits of
 *   		the cn_flags field have the following meanings:
 *   	- MAKEENTRY:	If clear, free an entry from the cache rather than look
 *   			it up.
 *   	- ISDOTDOT:	Must be set if and only if cn_nameptr == ".."
 * - tsp:	Return storage for cache timestamp.  On a successful (positive
 *   		or negative) lookup, tsp will be filled with any timespec that
 *   		was stored when this cache entry was created.  However, it will
 *   		be clear for "." entries.
 * - ticks:	Return storage for alternate cache timestamp.  On a successful
 *   		(positive or negative) lookup, it will contain the ticks value
 *   		that was current when the cache entry was created, unless cnp
 *   		was ".".
 *
 * Either both tsp and ticks have to be provided or neither of them.
 *
 * # Returns
 *
 * - -1:	A positive cache hit.  vpp will contain the desired vnode.
 * - ENOENT:	A negative cache hit, or dvp was recycled out from under us due
 *		to a forced unmount.  vpp will not be modified.  If the entry
 *		is a whiteout, then the ISWHITEOUT flag will be set in
 *		cnp->cn_flags.
 * - 0:		A cache miss.  vpp will not be modified.
 *
 * # Locking
 *
 * On a cache hit, vpp will be returned locked and ref'd.  If we're looking up
 * .., dvp is unlocked.  If we're looking up . an extra ref is taken, but the
 * lock is not recursively acquired.
 */
static int __noinline
cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
    struct timespec *tsp, int *ticksp)
{
	struct namecache *ncp;
	struct mtx *blp;
	uint32_t hash;
	enum vgetstate vs;
	int error;
	bool whiteout;

	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
	MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);

retry:
	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
	blp = HASH2BUCKETLOCK(hash);
	mtx_lock(blp);

	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
			break;
	}

	if (__predict_false(ncp == NULL)) {
		mtx_unlock(blp);
		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
		counter_u64_add(nummiss, 1);
		return (0);
	}

	if (ncp->nc_flag & NCF_NEGATIVE)
		goto negative_success;

	counter_u64_add(numposhits, 1);
	*vpp = ncp->nc_vp;
	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
	cache_out_ts(ncp, tsp, ticksp);
	MPASS(dvp != *vpp);
	vs = vget_prep(*vpp);
	mtx_unlock(blp);
	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
	if (error) {
		*vpp = NULL;
		goto retry;
	}
	return (-1);
negative_success:
	/*
	 * We don't get here with regular lookup apart from corner cases.
	 */
	if (__predict_true(cnp->cn_nameiop == CREATE)) {
		if (cnp->cn_flags & ISLASTCN) {
			counter_u64_add(numnegzaps, 1);
			error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
			if (__predict_false(error != 0)) {
				zap_bucket_fail2++;
				goto retry;
			}
			cache_free(ncp);
			return (0);
		}
	}

	whiteout = (ncp->nc_flag & NCF_WHITE);
	cache_out_ts(ncp, tsp, ticksp);
	if (cache_neg_hit_prep(ncp))
		cache_neg_promote(ncp);
	else
		cache_neg_hit_finish(ncp);
	mtx_unlock(blp);
	if (whiteout)
		cnp->cn_flags |= ISWHITEOUT;
	return (ENOENT);
}

int
cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
    struct timespec *tsp, int *ticksp)
{
	struct namecache *ncp;
	uint32_t hash;
	enum vgetstate vs;
	int error;
	bool whiteout, neg_promote;
	u_short nc_flag;

	MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));

#ifdef DEBUG_CACHE
	if (__predict_false(!doingcache)) {
		cnp->cn_flags &= ~MAKEENTRY;
		return (0);
	}
#endif

	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
		if (cnp->cn_namelen == 1)
			return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
			return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
	}

	MPASS((cnp->cn_flags & ISDOTDOT) == 0);

	if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
		cache_remove_cnp(dvp, cnp);
		return (0);
	}

	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
	vfs_smr_enter();

	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
			break;
	}

	if (__predict_false(ncp == NULL)) {
		vfs_smr_exit();
		SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
		counter_u64_add(nummiss, 1);
		return (0);
	}

	nc_flag = atomic_load_char(&ncp->nc_flag);
	if (nc_flag & NCF_NEGATIVE)
		goto negative_success;

	counter_u64_add(numposhits, 1);
	*vpp = ncp->nc_vp;
	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
	cache_out_ts(ncp, tsp, ticksp);
	MPASS(dvp != *vpp);
	if (!cache_ncp_canuse(ncp)) {
		vfs_smr_exit();
		*vpp = NULL;
		goto out_fallback;
	}
	vs = vget_prep_smr(*vpp);
	vfs_smr_exit();
	if (__predict_false(vs == VGET_NONE)) {
		*vpp = NULL;
		goto out_fallback;
	}
	error = vget_finish(*vpp, cnp->cn_lkflags, vs);
	if (error) {
		*vpp = NULL;
		goto out_fallback;
	}
	return (-1);
negative_success:
	if (cnp->cn_nameiop == CREATE) {
		if (cnp->cn_flags & ISLASTCN) {
			vfs_smr_exit();
			goto out_fallback;
		}
	}

	cache_out_ts(ncp, tsp, ticksp);
	whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
	neg_promote = cache_neg_hit_prep(ncp);
	if (!cache_ncp_canuse(ncp)) {
		cache_neg_hit_abort(ncp);
		vfs_smr_exit();
		goto out_fallback;
	}
	if (neg_promote) {
		vfs_smr_exit();
		if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
			goto out_fallback;
	} else {
		cache_neg_hit_finish(ncp);
		vfs_smr_exit();
	}
	if (whiteout)
		cnp->cn_flags |= ISWHITEOUT;
	return (ENOENT);
out_fallback:
	return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
}

struct celockstate {
	struct mtx *vlp[3];
	struct mtx *blp[2];
};
CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));

static inline void
cache_celockstate_init(struct celockstate *cel)
{

	bzero(cel, sizeof(*cel));
}

static void
cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
    struct vnode *dvp)
{
	struct mtx *vlp1, *vlp2;

	MPASS(cel->vlp[0] == NULL);
	MPASS(cel->vlp[1] == NULL);
	MPASS(cel->vlp[2] == NULL);

	MPASS(vp != NULL || dvp != NULL);

	vlp1 = VP2VNODELOCK(vp);
	vlp2 = VP2VNODELOCK(dvp);
	cache_sort_vnodes(&vlp1, &vlp2);

	if (vlp1 != NULL) {
		mtx_lock(vlp1);
		cel->vlp[0] = vlp1;
	}
	mtx_lock(vlp2);
	cel->vlp[1] = vlp2;
}

static void
cache_unlock_vnodes_cel(struct celockstate *cel)
{

	MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);

	if (cel->vlp[0] != NULL)
		mtx_unlock(cel->vlp[0]);
	if (cel->vlp[1] != NULL)
		mtx_unlock(cel->vlp[1]);
	if (cel->vlp[2] != NULL)
		mtx_unlock(cel->vlp[2]);
}

static bool
cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
{
	struct mtx *vlp;
	bool ret;

	cache_assert_vlp_locked(cel->vlp[0]);
	cache_assert_vlp_locked(cel->vlp[1]);
	MPASS(cel->vlp[2] == NULL);

	MPASS(vp != NULL);
	vlp = VP2VNODELOCK(vp);

	ret = true;
	if (vlp >= cel->vlp[1]) {
		mtx_lock(vlp);
	} else {
		if (mtx_trylock(vlp))
			goto out;
		cache_lock_vnodes_cel_3_failures++;
		cache_unlock_vnodes_cel(cel);
		if (vlp < cel->vlp[0]) {
			mtx_lock(vlp);
			mtx_lock(cel->vlp[0]);
			mtx_lock(cel->vlp[1]);
		} else {
			if (cel->vlp[0] != NULL)
				mtx_lock(cel->vlp[0]);
			mtx_lock(vlp);
			mtx_lock(cel->vlp[1]);
		}
		ret = false;
	}
out:
	cel->vlp[2] = vlp;
	return (ret);
}

static void
cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
    struct mtx *blp2)
{

	MPASS(cel->blp[0] == NULL);
	MPASS(cel->blp[1] == NULL);

	cache_sort_vnodes(&blp1, &blp2);

	if (blp1 != NULL) {
		mtx_lock(blp1);
		cel->blp[0] = blp1;
	}
	mtx_lock(blp2);
	cel->blp[1] = blp2;
}

static void
cache_unlock_buckets_cel(struct celockstate *cel)
{

	if (cel->blp[0] != NULL)
		mtx_unlock(cel->blp[0]);
	mtx_unlock(cel->blp[1]);
}

/*
 * Lock part of the cache affected by the insertion.
 *
 * This means vnodelocks for dvp, vp and the relevant bucketlock.
 * However, insertion can result in removal of an old entry. In this
 * case we have an additional vnode and bucketlock pair to lock.
 *
 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
 * preserving the locking order (smaller address first).
 */
static void
cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
    uint32_t hash)
{
	struct namecache *ncp;
	struct mtx *blps[2];
	u_char nc_flag;

	blps[0] = HASH2BUCKETLOCK(hash);
	for (;;) {
		blps[1] = NULL;
		cache_lock_vnodes_cel(cel, dvp, vp);
		if (vp == NULL || vp->v_type != VDIR)
			break;
		ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
		if (ncp == NULL)
			break;
		nc_flag = atomic_load_char(&ncp->nc_flag);
		if ((nc_flag & NCF_ISDOTDOT) == 0)
			break;
		MPASS(ncp->nc_dvp == vp);
		blps[1] = NCP2BUCKETLOCK(ncp);
		if ((nc_flag & NCF_NEGATIVE) != 0)
			break;
		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
			break;
		/*
		 * All vnodes got re-locked. Re-validate the state and if
		 * nothing changed we are done. Otherwise restart.
		 */
		if (ncp == vp->v_cache_dd &&
		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
		    blps[1] == NCP2BUCKETLOCK(ncp) &&
		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
			break;
		cache_unlock_vnodes_cel(cel);
		cel->vlp[0] = NULL;
		cel->vlp[1] = NULL;
		cel->vlp[2] = NULL;
	}
	cache_lock_buckets_cel(cel, blps[0], blps[1]);
}

static void
cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
    uint32_t hash)
{
	struct namecache *ncp;
	struct mtx *blps[2];
	u_char nc_flag;

	blps[0] = HASH2BUCKETLOCK(hash);
	for (;;) {
		blps[1] = NULL;
		cache_lock_vnodes_cel(cel, dvp, vp);
		ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
		if (ncp == NULL)
			break;
		nc_flag = atomic_load_char(&ncp->nc_flag);
		if ((nc_flag & NCF_ISDOTDOT) == 0)
			break;
		MPASS(ncp->nc_dvp == dvp);
		blps[1] = NCP2BUCKETLOCK(ncp);
		if ((nc_flag & NCF_NEGATIVE) != 0)
			break;
		if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
			break;
		if (ncp == dvp->v_cache_dd &&
		    (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
		    blps[1] == NCP2BUCKETLOCK(ncp) &&
		    VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
			break;
		cache_unlock_vnodes_cel(cel);
		cel->vlp[0] = NULL;
		cel->vlp[1] = NULL;
		cel->vlp[2] = NULL;
	}
	cache_lock_buckets_cel(cel, blps[0], blps[1]);
}

static void
cache_enter_unlock(struct celockstate *cel)
{

	cache_unlock_buckets_cel(cel);
	cache_unlock_vnodes_cel(cel);
}

static void __noinline
cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
    struct componentname *cnp)
{
	struct celockstate cel;
	struct namecache *ncp;
	uint32_t hash;
	int len;

	if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
		return;
	len = cnp->cn_namelen;
	cache_celockstate_init(&cel);
	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
	cache_enter_lock_dd(&cel, dvp, vp, hash);
	ncp = dvp->v_cache_dd;
	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
		KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
		cache_zap_locked(ncp);
	} else {
		ncp = NULL;
	}
	atomic_store_ptr(&dvp->v_cache_dd, NULL);
	cache_enter_unlock(&cel);
	if (ncp != NULL)
		cache_free(ncp);
}

/*
 * Add an entry to the cache.
 */
void
cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
    struct timespec *tsp, struct timespec *dtsp)
{
	struct celockstate cel;
	struct namecache *ncp, *n2, *ndd;
	struct namecache_ts *ncp_ts;
	struct nchashhead *ncpp;
	uint32_t hash;
	int flag;
	int len;

	KASSERT(cnp->cn_namelen <= NAME_MAX,
	    ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
	    NAME_MAX));
	VNPASS(dvp != vp, dvp);
	VNPASS(!VN_IS_DOOMED(dvp), dvp);
	VNPASS(dvp->v_type != VNON, dvp);
	if (vp != NULL) {
		VNPASS(!VN_IS_DOOMED(vp), vp);
		VNPASS(vp->v_type != VNON, vp);
	}

#ifdef DEBUG_CACHE
	if (__predict_false(!doingcache))
		return;
#endif

	flag = 0;
	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
		if (cnp->cn_namelen == 1)
			return;
		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
			cache_enter_dotdot_prep(dvp, vp, cnp);
			flag = NCF_ISDOTDOT;
		}
	}

	ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
	if (ncp == NULL)
		return;

	cache_celockstate_init(&cel);
	ndd = NULL;
	ncp_ts = NULL;

	/*
	 * Calculate the hash key and setup as much of the new
	 * namecache entry as possible before acquiring the lock.
	 */
	ncp->nc_flag = flag | NCF_WIP;
	ncp->nc_vp = vp;
	if (vp == NULL)
		cache_neg_init(ncp);
	ncp->nc_dvp = dvp;
	if (tsp != NULL) {
		ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
		ncp_ts->nc_time = *tsp;
		ncp_ts->nc_ticks = ticks;
		ncp_ts->nc_nc.nc_flag |= NCF_TS;
		if (dtsp != NULL) {
			ncp_ts->nc_dotdottime = *dtsp;
			ncp_ts->nc_nc.nc_flag |= NCF_DTS;
		}
	}
	len = ncp->nc_nlen = cnp->cn_namelen;
	hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
	memcpy(ncp->nc_name, cnp->cn_nameptr, len);
	ncp->nc_name[len] = '\0';
	cache_enter_lock(&cel, dvp, vp, hash);

	/*
	 * See if this vnode or negative entry is already in the cache
	 * with this name.  This can happen with concurrent lookups of
	 * the same path name.
	 */
	ncpp = NCHHASH(hash);
	CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
		if (n2->nc_dvp == dvp &&
		    n2->nc_nlen == cnp->cn_namelen &&
		    !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
			MPASS(cache_ncp_canuse(n2));
			if ((n2->nc_flag & NCF_NEGATIVE) != 0)
				KASSERT(vp == NULL,
				    ("%s: found entry pointing to a different vnode (%p != %p)",
				    __func__, NULL, vp));
			else
				KASSERT(n2->nc_vp == vp,
				    ("%s: found entry pointing to a different vnode (%p != %p)",
				    __func__, n2->nc_vp, vp));
			/*
			 * Entries are supposed to be immutable unless in the
			 * process of getting destroyed. Accommodating for
			 * changing timestamps is possible but not worth it.
			 * This should be harmless in terms of correctness, in
			 * the worst case resulting in an earlier expiration.
			 * Alternatively, the found entry can be replaced
			 * altogether.
			 */
			MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
#if 0
			if (tsp != NULL) {
				KASSERT((n2->nc_flag & NCF_TS) != 0,
				    ("no NCF_TS"));
				n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
				n2_ts->nc_time = ncp_ts->nc_time;
				n2_ts->nc_ticks = ncp_ts->nc_ticks;
				if (dtsp != NULL) {
					n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
					n2_ts->nc_nc.nc_flag |= NCF_DTS;
				}
			}
#endif
			SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
			    vp);
			goto out_unlock_free;
		}
	}

	if (flag == NCF_ISDOTDOT) {
		/*
		 * See if we are trying to add .. entry, but some other lookup
		 * has populated v_cache_dd pointer already.
		 */
		if (dvp->v_cache_dd != NULL)
			goto out_unlock_free;
		KASSERT(vp == NULL || vp->v_type == VDIR,
		    ("wrong vnode type %p", vp));
		atomic_thread_fence_rel();
		atomic_store_ptr(&dvp->v_cache_dd, ncp);
	}

	if (vp != NULL) {
		if (flag != NCF_ISDOTDOT) {
			/*
			 * For this case, the cache entry maps both the
			 * directory name in it and the name ".." for the
			 * directory's parent.
			 */
			if ((ndd = vp->v_cache_dd) != NULL) {
				if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
					cache_zap_locked(ndd);
				else
					ndd = NULL;
			}
			atomic_thread_fence_rel();
			atomic_store_ptr(&vp->v_cache_dd, ncp);
		} else if (vp->v_type != VDIR) {
			if (vp->v_cache_dd != NULL) {
				atomic_store_ptr(&vp->v_cache_dd, NULL);
			}
		}
	}

	if (flag != NCF_ISDOTDOT) {
		if (LIST_EMPTY(&dvp->v_cache_src)) {
			cache_hold_vnode(dvp);
		}
		LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
	}

	/*
	 * If the entry is "negative", we place it into the
	 * "negative" cache queue, otherwise, we place it into the
	 * destination vnode's cache entries queue.
	 */
	if (vp != NULL) {
		TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
		SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
		    vp);
	} else {
		if (cnp->cn_flags & ISWHITEOUT)
			atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
		cache_neg_insert(ncp);
		SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
		    ncp->nc_name);
	}

	/*
	 * Insert the new namecache entry into the appropriate chain
	 * within the cache entries table.
	 */
	CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);

	atomic_thread_fence_rel();
	/*
	 * Mark the entry as fully constructed.
	 * It is immutable past this point until its removal.
	 */
	atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);

	cache_enter_unlock(&cel);
	if (ndd != NULL)
		cache_free(ndd);
	return;
out_unlock_free:
	cache_enter_unlock(&cel);
	cache_free(ncp);
	return;
}

static u_int
cache_roundup_2(u_int val)
{
	u_int res;

	for (res = 1; res <= val; res <<= 1)
		continue;

	return (res);
}

static struct nchashhead *
nchinittbl(u_long elements, u_long *hashmask)
{
	struct nchashhead *hashtbl;
	u_long hashsize, i;

	hashsize = cache_roundup_2(elements) / 2;

	hashtbl = malloc((u_long)hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
	for (i = 0; i < hashsize; i++)
		CK_SLIST_INIT(&hashtbl[i]);
	*hashmask = hashsize - 1;
	return (hashtbl);
}

static void
ncfreetbl(struct nchashhead *hashtbl)
{

	free(hashtbl, M_VFSCACHE);
}

/*
 * Name cache initialization, from vfs_init() when we are booting
 */
static void
nchinit(void *dummy __unused)
{
	u_int i;

	cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
	cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
	cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
	cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
	    NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);

	VFS_SMR_ZONE_SET(cache_zone_small);
	VFS_SMR_ZONE_SET(cache_zone_small_ts);
	VFS_SMR_ZONE_SET(cache_zone_large);
	VFS_SMR_ZONE_SET(cache_zone_large_ts);

	ncsize = desiredvnodes * ncsizefactor;
	cache_recalc_neg_min(ncnegminpct);
	nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
	ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
	if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
		ncbuckethash = 7;
	if (ncbuckethash > nchash)
		ncbuckethash = nchash;
	bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
	    M_WAITOK | M_ZERO);
	for (i = 0; i < numbucketlocks; i++)
		mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
	ncvnodehash = ncbuckethash;
	vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
	    M_WAITOK | M_ZERO);
	for (i = 0; i < numvnodelocks; i++)
		mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);

	for (i = 0; i < numneglists; i++) {
		mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
		mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
		TAILQ_INIT(&neglists[i].nl_list);
		TAILQ_INIT(&neglists[i].nl_hotlist);
	}
}
SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);

void
cache_vnode_init(struct vnode *vp)
{

	LIST_INIT(&vp->v_cache_src);
	TAILQ_INIT(&vp->v_cache_dst);
	vp->v_cache_dd = NULL;
	cache_prehash(vp);
}

void
cache_changesize(u_long newmaxvnodes)
{
	struct nchashhead *new_nchashtbl, *old_nchashtbl;
	u_long new_nchash, old_nchash;
	struct namecache *ncp;
	uint32_t hash;
	u_long newncsize;
	int i;

	newncsize = newmaxvnodes * ncsizefactor;
	newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
	if (newmaxvnodes < numbucketlocks)
		newmaxvnodes = numbucketlocks;

	new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
	/* If same hash table size, nothing to do */
	if (nchash == new_nchash) {
		ncfreetbl(new_nchashtbl);
		return;
	}
	/*
	 * Move everything from the old hash table to the new table.
	 * None of the namecache entries in the table can be removed
	 * because to do so, they have to be removed from the hash table.
	 */
	cache_lock_all_vnodes();
	cache_lock_all_buckets();
	old_nchashtbl = nchashtbl;
	old_nchash = nchash;
	nchashtbl = new_nchashtbl;
	nchash = new_nchash;
	for (i = 0; i <= old_nchash; i++) {
		while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
			hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
			    ncp->nc_dvp);
			CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
			CK_SLIST_INSERT_HEAD(NCHHASH(hash), ncp, nc_hash);
		}
	}
	ncsize = newncsize;
	cache_recalc_neg_min(ncnegminpct);
	cache_unlock_all_buckets();
	cache_unlock_all_vnodes();
	ncfreetbl(old_nchashtbl);
}

/*
 * Remove all entries from and to a particular vnode.
 */
static void
cache_purge_impl(struct vnode *vp)
{
	struct cache_freebatch batch;
	struct namecache *ncp;
	struct mtx *vlp, *vlp2;

	TAILQ_INIT(&batch);
	vlp = VP2VNODELOCK(vp);
	vlp2 = NULL;
	mtx_lock(vlp);
retry:
	while (!LIST_EMPTY(&vp->v_cache_src)) {
		ncp = LIST_FIRST(&vp->v_cache_src);
		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
			goto retry;
		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
	}
	while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
		ncp = TAILQ_FIRST(&vp->v_cache_dst);
		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
			goto retry;
		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
	}
	ncp = vp->v_cache_dd;
	if (ncp != NULL) {
		KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
		   ("lost dotdot link"));
		if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
			goto retry;
		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
	}
	KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
	mtx_unlock(vlp);
	if (vlp2 != NULL)
		mtx_unlock(vlp2);
	cache_free_batch(&batch);
}

/*
 * Opportunistic check to see if there is anything to do.
 */
static bool
cache_has_entries(struct vnode *vp)
{

	if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
	    atomic_load_ptr(&vp->v_cache_dd) == NULL)
		return (false);
	return (true);
}

void
cache_purge(struct vnode *vp)
{

	SDT_PROBE1(vfs, namecache, purge, done, vp);
	if (!cache_has_entries(vp))
		return;
	cache_purge_impl(vp);
}

/*
 * Only to be used by vgone.
 */
void
cache_purge_vgone(struct vnode *vp)
{
	struct mtx *vlp;

	VNPASS(VN_IS_DOOMED(vp), vp);
	if (cache_has_entries(vp)) {
		cache_purge_impl(vp);
		return;
	}

	/*
	 * Serialize against a potential thread doing cache_purge.
	 */
	vlp = VP2VNODELOCK(vp);
	mtx_wait_unlocked(vlp);
	if (cache_has_entries(vp)) {
		cache_purge_impl(vp);
		return;
	}
	return;
}

/*
 * Remove all negative entries for a particular directory vnode.
 */
void
cache_purge_negative(struct vnode *vp)
{
	struct cache_freebatch batch;
	struct namecache *ncp, *nnp;
	struct mtx *vlp;

	SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
	if (LIST_EMPTY(&vp->v_cache_src))
		return;
	TAILQ_INIT(&batch);
	vlp = VP2VNODELOCK(vp);
	mtx_lock(vlp);
	LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
		if (!(ncp->nc_flag & NCF_NEGATIVE))
			continue;
		cache_zap_negative_locked_vnode_kl(ncp, vp);
		TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
	}
	mtx_unlock(vlp);
	cache_free_batch(&batch);
}

/*
 * Entry points for modifying VOP operations.
 */
void
cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
    struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
{

	ASSERT_VOP_IN_SEQC(fdvp);
	ASSERT_VOP_IN_SEQC(fvp);
	ASSERT_VOP_IN_SEQC(tdvp);
	if (tvp != NULL)
		ASSERT_VOP_IN_SEQC(tvp);

	cache_purge(fvp);
	if (tvp != NULL) {
		cache_purge(tvp);
		KASSERT(!cache_remove_cnp(tdvp, tcnp),
		    ("%s: lingering negative entry", __func__));
	} else {
		cache_remove_cnp(tdvp, tcnp);
	}

	/*
	 * TODO
	 *
	 * Historically renaming was always purging all revelang entries,
	 * but that's quite wasteful. In particular turns out that in many cases
	 * the target file is immediately accessed after rename, inducing a cache
	 * miss.
	 *
	 * Recode this to reduce relocking and reuse the existing entry (if any)
	 * instead of just removing it above and allocating a new one here.
	 */
	if (cache_rename_add) {
		cache_enter(tdvp, fvp, tcnp);
	}
}

void
cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
{

	ASSERT_VOP_IN_SEQC(dvp);
	ASSERT_VOP_IN_SEQC(vp);
	cache_purge(vp);
}

#ifdef INVARIANTS
/*
 * Validate that if an entry exists it matches.
 */
void
cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
{
	struct namecache *ncp;
	struct mtx *blp;
	uint32_t hash;

	hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
	if (CK_SLIST_EMPTY(NCHHASH(hash)))
		return;
	blp = HASH2BUCKETLOCK(hash);
	mtx_lock(blp);
	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
			if (ncp->nc_vp != vp)
				panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
				    __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
		}
	}
	mtx_unlock(blp);
}
#endif

/*
 * Flush all entries referencing a particular filesystem.
 */
void
cache_purgevfs(struct mount *mp)
{
	struct vnode *vp, *mvp;

	SDT_PROBE1(vfs, namecache, purgevfs, done, mp);
	/*
	 * Somewhat wasteful iteration over all vnodes. Would be better to
	 * support filtering and avoid the interlock to begin with.
	 */
	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
		if (!cache_has_entries(vp)) {
			VI_UNLOCK(vp);
			continue;
		}
		vholdl(vp);
		VI_UNLOCK(vp);
		cache_purge(vp);
		vdrop(vp);
	}
}

/*
 * Perform canonical checks and cache lookup and pass on to filesystem
 * through the vop_cachedlookup only if needed.
 */

int
vfs_cache_lookup(struct vop_lookup_args *ap)
{
	struct vnode *dvp;
	int error;
	struct vnode **vpp = ap->a_vpp;
	struct componentname *cnp = ap->a_cnp;
	int flags = cnp->cn_flags;

	*vpp = NULL;
	dvp = ap->a_dvp;

	if (dvp->v_type != VDIR)
		return (ENOTDIR);

	if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
		return (EROFS);

	error = vn_dir_check_exec(dvp, cnp);
	if (error != 0)
		return (error);

	error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
	if (error == 0)
		return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
	if (error == -1)
		return (0);
	return (error);
}

/* Implementation of the getcwd syscall. */
int
sys___getcwd(struct thread *td, struct __getcwd_args *uap)
{
	char *buf, *retbuf;
	size_t buflen;
	int error;

	buflen = uap->buflen;
	if (__predict_false(buflen < 2))
		return (EINVAL);
	if (buflen > MAXPATHLEN)
		buflen = MAXPATHLEN;

	buf = uma_zalloc(namei_zone, M_WAITOK);
	error = vn_getcwd(buf, &retbuf, &buflen);
	if (error == 0)
		error = copyout(retbuf, uap->buf, buflen);
	uma_zfree(namei_zone, buf);
	return (error);
}

int
vn_getcwd(char *buf, char **retbuf, size_t *buflen)
{
	struct pwd *pwd;
	int error;

	vfs_smr_enter();
	pwd = pwd_get_smr();
	error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
	    buflen, 0);
	VFS_SMR_ASSERT_NOT_ENTERED();
	if (error < 0) {
		pwd = pwd_hold(curthread);
		error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
		    retbuf, buflen);
		pwd_drop(pwd);
	}

#ifdef KTRACE
	if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
		ktrnamei(*retbuf);
#endif
	return (error);
}

static int
kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
    size_t size, int flags, enum uio_seg pathseg)
{
	struct nameidata nd;
	char *retbuf, *freebuf;
	int error;

	if (flags != 0)
		return (EINVAL);
	NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
	    pathseg, path, fd, &cap_fstat_rights, td);
	if ((error = namei(&nd)) != 0)
		return (error);
	error = vn_fullpath_hardlink(&nd, &retbuf, &freebuf, &size);
	if (error == 0) {
		error = copyout(retbuf, buf, size);
		free(freebuf, M_TEMP);
	}
	NDFREE(&nd, 0);
	return (error);
}

int
sys___realpathat(struct thread *td, struct __realpathat_args *uap)
{

	return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
	    uap->flags, UIO_USERSPACE));
}

/*
 * Retrieve the full filesystem path that correspond to a vnode from the name
 * cache (if available)
 */
int
vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
{
	struct pwd *pwd;
	char *buf;
	size_t buflen;
	int error;

	if (__predict_false(vp == NULL))
		return (EINVAL);

	buflen = MAXPATHLEN;
	buf = malloc(buflen, M_TEMP, M_WAITOK);
	vfs_smr_enter();
	pwd = pwd_get_smr();
	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
	VFS_SMR_ASSERT_NOT_ENTERED();
	if (error < 0) {
		pwd = pwd_hold(curthread);
		error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
		pwd_drop(pwd);
	}
	if (error == 0)
		*freebuf = buf;
	else
		free(buf, M_TEMP);
	return (error);
}

/*
 * This function is similar to vn_fullpath, but it attempts to lookup the
 * pathname relative to the global root mount point.  This is required for the
 * auditing sub-system, as audited pathnames must be absolute, relative to the
 * global root mount point.
 */
int
vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
{
	char *buf;
	size_t buflen;
	int error;

	if (__predict_false(vp == NULL))
		return (EINVAL);
	buflen = MAXPATHLEN;
	buf = malloc(buflen, M_TEMP, M_WAITOK);
	vfs_smr_enter();
	error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
	VFS_SMR_ASSERT_NOT_ENTERED();
	if (error < 0) {
		error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
	}
	if (error == 0)
		*freebuf = buf;
	else
		free(buf, M_TEMP);
	return (error);
}

static struct namecache *
vn_dd_from_dst(struct vnode *vp)
{
	struct namecache *ncp;

	cache_assert_vnode_locked(vp);
	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
			return (ncp);
	}
	return (NULL);
}

int
vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
{
	struct vnode *dvp;
	struct namecache *ncp;
	struct mtx *vlp;
	int error;

	vlp = VP2VNODELOCK(*vp);
	mtx_lock(vlp);
	ncp = (*vp)->v_cache_dd;
	if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
		KASSERT(ncp == vn_dd_from_dst(*vp),
		    ("%s: mismatch for dd entry (%p != %p)", __func__,
		    ncp, vn_dd_from_dst(*vp)));
	} else {
		ncp = vn_dd_from_dst(*vp);
	}
	if (ncp != NULL) {
		if (*buflen < ncp->nc_nlen) {
			mtx_unlock(vlp);
			vrele(*vp);
			counter_u64_add(numfullpathfail4, 1);
			error = ENOMEM;
			SDT_PROBE3(vfs, namecache, fullpath, return, error,
			    vp, NULL);
			return (error);
		}
		*buflen -= ncp->nc_nlen;
		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
		SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
		    ncp->nc_name, vp);
		dvp = *vp;
		*vp = ncp->nc_dvp;
		vref(*vp);
		mtx_unlock(vlp);
		vrele(dvp);
		return (0);
	}
	SDT_PROBE1(vfs, namecache, fullpath, miss, vp);

	mtx_unlock(vlp);
	vn_lock(*vp, LK_SHARED | LK_RETRY);
	error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
	vput(*vp);
	if (error) {
		counter_u64_add(numfullpathfail2, 1);
		SDT_PROBE3(vfs, namecache, fullpath, return,  error, vp, NULL);
		return (error);
	}

	*vp = dvp;
	if (VN_IS_DOOMED(dvp)) {
		/* forced unmount */
		vrele(dvp);
		error = ENOENT;
		SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
		return (error);
	}
	/*
	 * *vp has its use count incremented still.
	 */

	return (0);
}

/*
 * Resolve a directory to a pathname.
 *
 * The name of the directory can always be found in the namecache or fetched
 * from the filesystem. There is also guaranteed to be only one parent, meaning
 * we can just follow vnodes up until we find the root.
 *
 * The vnode must be referenced.
 */
static int
vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
    size_t *len, size_t addend)
{
#ifdef KDTRACE_HOOKS
	struct vnode *startvp = vp;
#endif
	struct vnode *vp1;
	size_t buflen;
	int error;
	bool slash_prefixed;

	VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
	VNPASS(vp->v_usecount > 0, vp);

	buflen = *len;

	slash_prefixed = true;
	if (addend == 0) {
		MPASS(*len >= 2);
		buflen--;
		buf[buflen] = '\0';
		slash_prefixed = false;
	}

	error = 0;

	SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
	counter_u64_add(numfullpathcalls, 1);
	while (vp != rdir && vp != rootvnode) {
		/*
		 * The vp vnode must be already fully constructed,
		 * since it is either found in namecache or obtained
		 * from VOP_VPTOCNP().  We may test for VV_ROOT safely
		 * without obtaining the vnode lock.
		 */
		if ((vp->v_vflag & VV_ROOT) != 0) {
			vn_lock(vp, LK_RETRY | LK_SHARED);

			/*
			 * With the vnode locked, check for races with
			 * unmount, forced or not.  Note that we
			 * already verified that vp is not equal to
			 * the root vnode, which means that
			 * mnt_vnodecovered can be NULL only for the
			 * case of unmount.
			 */
			if (VN_IS_DOOMED(vp) ||
			    (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
			    vp1->v_mountedhere != vp->v_mount) {
				vput(vp);
				error = ENOENT;
				SDT_PROBE3(vfs, namecache, fullpath, return,
				    error, vp, NULL);
				break;
			}

			vref(vp1);
			vput(vp);
			vp = vp1;
			continue;
		}
		if (vp->v_type != VDIR) {
			vrele(vp);
			counter_u64_add(numfullpathfail1, 1);
			error = ENOTDIR;
			SDT_PROBE3(vfs, namecache, fullpath, return,
			    error, vp, NULL);
			break;
		}
		error = vn_vptocnp(&vp, buf, &buflen);
		if (error)
			break;
		if (buflen == 0) {
			vrele(vp);
			error = ENOMEM;
			SDT_PROBE3(vfs, namecache, fullpath, return, error,
			    startvp, NULL);
			break;
		}
		buf[--buflen] = '/';
		slash_prefixed = true;
	}
	if (error)
		return (error);
	if (!slash_prefixed) {
		if (buflen == 0) {
			vrele(vp);
			counter_u64_add(numfullpathfail4, 1);
			SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
			    startvp, NULL);
			return (ENOMEM);
		}
		buf[--buflen] = '/';
	}
	counter_u64_add(numfullpathfound, 1);
	vrele(vp);

	*retbuf = buf + buflen;
	SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
	*len -= buflen;
	*len += addend;
	return (0);
}

/*
 * Resolve an arbitrary vnode to a pathname.
 *
 * Note 2 caveats:
 * - hardlinks are not tracked, thus if the vnode is not a directory this can
 *   resolve to a different path than the one used to find it
 * - namecache is not mandatory, meaning names are not guaranteed to be added
 *   (in which case resolving fails)
 */
static void __inline
cache_rev_failed_impl(int *reason, int line)
{

	*reason = line;
}
#define cache_rev_failed(var)	cache_rev_failed_impl((var), __LINE__)

static int
vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
    char **retbuf, size_t *buflen, size_t addend)
{
#ifdef KDTRACE_HOOKS
	struct vnode *startvp = vp;
#endif
	struct vnode *tvp;
	struct mount *mp;
	struct namecache *ncp;
	size_t orig_buflen;
	int reason;
	int error;
#ifdef KDTRACE_HOOKS
	int i;
#endif
	seqc_t vp_seqc, tvp_seqc;
	u_char nc_flag;

	VFS_SMR_ASSERT_ENTERED();

	if (!cache_fast_revlookup) {
		vfs_smr_exit();
		return (-1);
	}

	orig_buflen = *buflen;

	if (addend == 0) {
		MPASS(*buflen >= 2);
		*buflen -= 1;
		buf[*buflen] = '\0';
	}

	if (vp == rdir || vp == rootvnode) {
		if (addend == 0) {
			*buflen -= 1;
			buf[*buflen] = '/';
		}
		goto out_ok;
	}

#ifdef KDTRACE_HOOKS
	i = 0;
#endif
	error = -1;
	ncp = NULL; /* for sdt probe down below */
	vp_seqc = vn_seqc_read_any(vp);
	if (seqc_in_modify(vp_seqc)) {
		cache_rev_failed(&reason);
		goto out_abort;
	}

	for (;;) {
#ifdef KDTRACE_HOOKS
		i++;
#endif
		if ((vp->v_vflag & VV_ROOT) != 0) {
			mp = atomic_load_ptr(&vp->v_mount);
			if (mp == NULL) {
				cache_rev_failed(&reason);
				goto out_abort;
			}
			tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
			tvp_seqc = vn_seqc_read_any(tvp);
			if (seqc_in_modify(tvp_seqc)) {
				cache_rev_failed(&reason);
				goto out_abort;
			}
			if (!vn_seqc_consistent(vp, vp_seqc)) {
				cache_rev_failed(&reason);
				goto out_abort;
			}
			vp = tvp;
			vp_seqc = tvp_seqc;
			continue;
		}
		ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
		if (ncp == NULL) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		nc_flag = atomic_load_char(&ncp->nc_flag);
		if ((nc_flag & NCF_ISDOTDOT) != 0) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		if (ncp->nc_nlen >= *buflen) {
			cache_rev_failed(&reason);
			error = ENOMEM;
			goto out_abort;
		}
		*buflen -= ncp->nc_nlen;
		memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
		*buflen -= 1;
		buf[*buflen] = '/';
		tvp = ncp->nc_dvp;
		tvp_seqc = vn_seqc_read_any(tvp);
		if (seqc_in_modify(tvp_seqc)) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		if (!vn_seqc_consistent(vp, vp_seqc)) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		/*
		 * Acquire fence provided by vn_seqc_read_any above.
		 */
		if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		if (!cache_ncp_canuse(ncp)) {
			cache_rev_failed(&reason);
			goto out_abort;
		}
		vp = tvp;
		vp_seqc = tvp_seqc;
		if (vp == rdir || vp == rootvnode)
			break;
	}
out_ok:
	vfs_smr_exit();
	*retbuf = buf + *buflen;
	*buflen = orig_buflen - *buflen + addend;
	SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
	return (0);

out_abort:
	*buflen = orig_buflen;
	SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
	vfs_smr_exit();
	return (error);
}

static int
vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
    size_t *buflen)
{
	size_t orig_buflen, addend;
	int error;

	if (*buflen < 2)
		return (EINVAL);

	orig_buflen = *buflen;

	vref(vp);
	addend = 0;
	if (vp->v_type != VDIR) {
		*buflen -= 1;
		buf[*buflen] = '\0';
		error = vn_vptocnp(&vp, buf, buflen);
		if (error)
			return (error);
		if (*buflen == 0) {
			vrele(vp);
			return (ENOMEM);
		}
		*buflen -= 1;
		buf[*buflen] = '/';
		addend = orig_buflen - *buflen;
	}

	return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
}

/*
 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
 *
 * Since the namecache does not track hardlinks, the caller is expected to first
 * look up the target vnode with SAVENAME | WANTPARENT flags passed to namei.
 *
 * Then we have 2 cases:
 * - if the found vnode is a directory, the path can be constructed just by
 *   following names up the chain
 * - otherwise we populate the buffer with the saved name and start resolving
 *   from the parent
 */
static int
vn_fullpath_hardlink(struct nameidata *ndp, char **retbuf, char **freebuf,
    size_t *buflen)
{
	char *buf, *tmpbuf;
	struct pwd *pwd;
	struct componentname *cnp;
	struct vnode *vp;
	size_t addend;
	int error;
	enum vtype type;

	if (*buflen < 2)
		return (EINVAL);
	if (*buflen > MAXPATHLEN)
		*buflen = MAXPATHLEN;

	buf = malloc(*buflen, M_TEMP, M_WAITOK);

	addend = 0;
	vp = ndp->ni_vp;
	/*
	 * Check for VBAD to work around the vp_crossmp bug in lookup().
	 *
	 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
	 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
	 * If the type is VDIR (like in this very case) we can skip looking
	 * at ni_dvp in the first place. However, since vnodes get passed here
	 * unlocked the target may transition to doomed state (type == VBAD)
	 * before we get to evaluate the condition. If this happens, we will
	 * populate part of the buffer and descend to vn_fullpath_dir with
	 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
	 *
	 * This should be atomic_load(&vp->v_type) but it is illegal to take
	 * an address of a bit field, even if said field is sized to char.
	 * Work around the problem by reading the value into a full-sized enum
	 * and then re-reading it with atomic_load which will still prevent
	 * the compiler from re-reading down the road.
	 */
	type = vp->v_type;
	type = atomic_load_int(&type);
	if (type == VBAD) {
		error = ENOENT;
		goto out_bad;
	}
	if (type != VDIR) {
		cnp = &ndp->ni_cnd;
		addend = cnp->cn_namelen + 2;
		if (*buflen < addend) {
			error = ENOMEM;
			goto out_bad;
		}
		*buflen -= addend;
		tmpbuf = buf + *buflen;
		tmpbuf[0] = '/';
		memcpy(&tmpbuf[1], cnp->cn_nameptr, cnp->cn_namelen);
		tmpbuf[addend - 1] = '\0';
		vp = ndp->ni_dvp;
	}

	vfs_smr_enter();
	pwd = pwd_get_smr();
	error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
	    addend);
	VFS_SMR_ASSERT_NOT_ENTERED();
	if (error < 0) {
		pwd = pwd_hold(curthread);
		vref(vp);
		error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
		    addend);
		pwd_drop(pwd);
		if (error != 0)
			goto out_bad;
	}

	*freebuf = buf;

	return (0);
out_bad:
	free(buf, M_TEMP);
	return (error);
}

struct vnode *
vn_dir_dd_ino(struct vnode *vp)
{
	struct namecache *ncp;
	struct vnode *ddvp;
	struct mtx *vlp;
	enum vgetstate vs;

	ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
	vlp = VP2VNODELOCK(vp);
	mtx_lock(vlp);
	TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
		if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
			continue;
		ddvp = ncp->nc_dvp;
		vs = vget_prep(ddvp);
		mtx_unlock(vlp);
		if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
			return (NULL);
		return (ddvp);
	}
	mtx_unlock(vlp);
	return (NULL);
}

int
vn_commname(struct vnode *vp, char *buf, u_int buflen)
{
	struct namecache *ncp;
	struct mtx *vlp;
	int l;

	vlp = VP2VNODELOCK(vp);
	mtx_lock(vlp);
	TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
		if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
			break;
	if (ncp == NULL) {
		mtx_unlock(vlp);
		return (ENOENT);
	}
	l = min(ncp->nc_nlen, buflen - 1);
	memcpy(buf, ncp->nc_name, l);
	mtx_unlock(vlp);
	buf[l] = '\0';
	return (0);
}

/*
 * This function updates path string to vnode's full global path
 * and checks the size of the new path string against the pathlen argument.
 *
 * Requires a locked, referenced vnode.
 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
 *
 * If vp is a directory, the call to vn_fullpath_global() always succeeds
 * because it falls back to the ".." lookup if the namecache lookup fails.
 */
int
vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
    u_int pathlen)
{
	struct nameidata nd;
	struct vnode *vp1;
	char *rpath, *fbuf;
	int error;

	ASSERT_VOP_ELOCKED(vp, __func__);

	/* Construct global filesystem path from vp. */
	VOP_UNLOCK(vp);
	error = vn_fullpath_global(vp, &rpath, &fbuf);

	if (error != 0) {
		vrele(vp);
		return (error);
	}

	if (strlen(rpath) >= pathlen) {
		vrele(vp);
		error = ENAMETOOLONG;
		goto out;
	}

	/*
	 * Re-lookup the vnode by path to detect a possible rename.
	 * As a side effect, the vnode is relocked.
	 * If vnode was renamed, return ENOENT.
	 */
	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
	    UIO_SYSSPACE, path, td);
	error = namei(&nd);
	if (error != 0) {
		vrele(vp);
		goto out;
	}
	NDFREE(&nd, NDF_ONLY_PNBUF);
	vp1 = nd.ni_vp;
	vrele(vp);
	if (vp1 == vp)
		strcpy(path, rpath);
	else {
		vput(vp1);
		error = ENOENT;
	}

out:
	free(fbuf, M_TEMP);
	return (error);
}

#ifdef DDB
static void
db_print_vpath(struct vnode *vp)
{

	while (vp != NULL) {
		db_printf("%p: ", vp);
		if (vp == rootvnode) {
			db_printf("/");
			vp = NULL;
		} else {
			if (vp->v_vflag & VV_ROOT) {
				db_printf("<mount point>");
				vp = vp->v_mount->mnt_vnodecovered;
			} else {
				struct namecache *ncp;
				char *ncn;
				int i;

				ncp = TAILQ_FIRST(&vp->v_cache_dst);
				if (ncp != NULL) {
					ncn = ncp->nc_name;
					for (i = 0; i < ncp->nc_nlen; i++)
						db_printf("%c", *ncn++);
					vp = ncp->nc_dvp;
				} else {
					vp = NULL;
				}
			}
		}
		db_printf("\n");
	}

	return;
}

DB_SHOW_COMMAND(vpath, db_show_vpath)
{
	struct vnode *vp;

	if (!have_addr) {
		db_printf("usage: show vpath <struct vnode *>\n");
		return;
	}

	vp = (struct vnode *)addr;
	db_print_vpath(vp);
}

#endif

static int cache_fast_lookup = 1;
static char __read_frequently cache_fast_lookup_enabled = true;

#define CACHE_FPL_FAILED	-2020

void
cache_fast_lookup_enabled_recalc(void)
{
	int lookup_flag;
	int mac_on;

#ifdef MAC
	mac_on = mac_vnode_check_lookup_enabled();
	mac_on |= mac_vnode_check_readlink_enabled();
#else
	mac_on = 0;
#endif

	lookup_flag = atomic_load_int(&cache_fast_lookup);
	if (lookup_flag && !mac_on) {
		atomic_store_char(&cache_fast_lookup_enabled, true);
	} else {
		atomic_store_char(&cache_fast_lookup_enabled, false);
	}
}

static int
syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
{
	int error, old;

	old = atomic_load_int(&cache_fast_lookup);
	error = sysctl_handle_int(oidp, arg1, arg2, req);
	if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
		cache_fast_lookup_enabled_recalc();
	return (error);
}
SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
    &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");

/*
 * Components of nameidata (or objects it can point to) which may
 * need restoring in case fast path lookup fails.
 */
struct nameidata_outer {
	size_t ni_pathlen;
	int cn_flags;
};

struct nameidata_saved {
#ifdef INVARIANTS
	char *cn_nameptr;
	size_t ni_pathlen;
#endif
};

#ifdef INVARIANTS
struct cache_fpl_debug {
	size_t ni_pathlen;
};
#endif

struct cache_fpl {
	struct nameidata *ndp;
	struct componentname *cnp;
	char *nulchar;
	struct vnode *dvp;
	struct vnode *tvp;
	seqc_t dvp_seqc;
	seqc_t tvp_seqc;
	uint32_t hash;
	struct nameidata_saved snd;
	struct nameidata_outer snd_outer;
	int line;
	enum cache_fpl_status status:8;
	bool in_smr;
	bool fsearch;
	bool savename;
	struct pwd **pwd;
#ifdef INVARIANTS
	struct cache_fpl_debug debug;
#endif
};

static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);

static void
cache_fpl_cleanup_cnp(struct componentname *cnp)
{

	uma_zfree(namei_zone, cnp->cn_pnbuf);
#ifdef DIAGNOSTIC
	cnp->cn_pnbuf = NULL;
	cnp->cn_nameptr = NULL;
#endif
}

static struct vnode *
cache_fpl_handle_root(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	MPASS(*(cnp->cn_nameptr) == '/');
	cnp->cn_nameptr++;
	cache_fpl_pathlen_dec(fpl);

	if (__predict_false(*(cnp->cn_nameptr) == '/')) {
		do {
			cnp->cn_nameptr++;
			cache_fpl_pathlen_dec(fpl);
		} while (*(cnp->cn_nameptr) == '/');
	}

	return (ndp->ni_rootdir);
}

static void
cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
{

	fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
	fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
}

static void
cache_fpl_checkpoint(struct cache_fpl *fpl)
{

#ifdef INVARIANTS
	fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
	fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
#endif
}

static void
cache_fpl_restore_partial(struct cache_fpl *fpl)
{

	fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
#ifdef INVARIANTS
	fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
#endif
}

static void
cache_fpl_restore_abort(struct cache_fpl *fpl)
{

	cache_fpl_restore_partial(fpl);
	/*
	 * It is 0 on entry by API contract.
	 */
	fpl->ndp->ni_resflags = 0;
	fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
	fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
}

#ifdef INVARIANTS
#define cache_fpl_smr_assert_entered(fpl) ({			\
	struct cache_fpl *_fpl = (fpl);				\
	MPASS(_fpl->in_smr == true);				\
	VFS_SMR_ASSERT_ENTERED();				\
})
#define cache_fpl_smr_assert_not_entered(fpl) ({		\
	struct cache_fpl *_fpl = (fpl);				\
	MPASS(_fpl->in_smr == false);				\
	VFS_SMR_ASSERT_NOT_ENTERED();				\
})
static void
cache_fpl_assert_status(struct cache_fpl *fpl)
{

	switch (fpl->status) {
	case CACHE_FPL_STATUS_UNSET:
		__assert_unreachable();
		break;
	case CACHE_FPL_STATUS_DESTROYED:
	case CACHE_FPL_STATUS_ABORTED:
	case CACHE_FPL_STATUS_PARTIAL:
	case CACHE_FPL_STATUS_HANDLED:
		break;
	}
}
#else
#define cache_fpl_smr_assert_entered(fpl) do { } while (0)
#define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
#define cache_fpl_assert_status(fpl) do { } while (0)
#endif

#define cache_fpl_smr_enter_initial(fpl) ({			\
	struct cache_fpl *_fpl = (fpl);				\
	vfs_smr_enter();					\
	_fpl->in_smr = true;					\
})

#define cache_fpl_smr_enter(fpl) ({				\
	struct cache_fpl *_fpl = (fpl);				\
	MPASS(_fpl->in_smr == false);				\
	vfs_smr_enter();					\
	_fpl->in_smr = true;					\
})

#define cache_fpl_smr_exit(fpl) ({				\
	struct cache_fpl *_fpl = (fpl);				\
	MPASS(_fpl->in_smr == true);				\
	vfs_smr_exit();						\
	_fpl->in_smr = false;					\
})

static int
cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
{

	if (fpl->status != CACHE_FPL_STATUS_UNSET) {
		KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
		    ("%s: converting to abort from %d at %d, set at %d\n",
		    __func__, fpl->status, line, fpl->line));
	}
	cache_fpl_smr_assert_not_entered(fpl);
	fpl->status = CACHE_FPL_STATUS_ABORTED;
	fpl->line = line;
	return (CACHE_FPL_FAILED);
}

#define cache_fpl_aborted_early(x)	cache_fpl_aborted_early_impl((x), __LINE__)

static int __noinline
cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
{
	struct nameidata *ndp;
	struct componentname *cnp;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	if (fpl->status != CACHE_FPL_STATUS_UNSET) {
		KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
		    ("%s: converting to abort from %d at %d, set at %d\n",
		    __func__, fpl->status, line, fpl->line));
	}
	fpl->status = CACHE_FPL_STATUS_ABORTED;
	fpl->line = line;
	if (fpl->in_smr)
		cache_fpl_smr_exit(fpl);
	cache_fpl_restore_abort(fpl);
	/*
	 * Resolving symlinks overwrites data passed by the caller.
	 * Let namei know.
	 */
	if (ndp->ni_loopcnt > 0) {
		fpl->status = CACHE_FPL_STATUS_DESTROYED;
		cache_fpl_cleanup_cnp(cnp);
	}
	return (CACHE_FPL_FAILED);
}

#define cache_fpl_aborted(x)	cache_fpl_aborted_impl((x), __LINE__)

static int __noinline
cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
{

	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
	    ("%s: setting to partial at %d, but already set to %d at %d\n",
	    __func__, line, fpl->status, fpl->line));
	cache_fpl_smr_assert_entered(fpl);
	fpl->status = CACHE_FPL_STATUS_PARTIAL;
	fpl->line = line;
	return (cache_fplookup_partial_setup(fpl));
}

#define cache_fpl_partial(x)	cache_fpl_partial_impl((x), __LINE__)

static int
cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
{

	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
	    ("%s: setting to handled at %d, but already set to %d at %d\n",
	    __func__, line, fpl->status, fpl->line));
	cache_fpl_smr_assert_not_entered(fpl);
	fpl->status = CACHE_FPL_STATUS_HANDLED;
	fpl->line = line;
	return (0);
}

#define cache_fpl_handled(x)	cache_fpl_handled_impl((x), __LINE__)

static int
cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
{

	KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
	    ("%s: setting to handled at %d, but already set to %d at %d\n",
	    __func__, line, fpl->status, fpl->line));
	MPASS(error != 0);
	MPASS(error != CACHE_FPL_FAILED);
	cache_fpl_smr_assert_not_entered(fpl);
	fpl->status = CACHE_FPL_STATUS_HANDLED;
	fpl->line = line;
	fpl->dvp = NULL;
	fpl->tvp = NULL;
	fpl->savename = false;
	return (error);
}

#define cache_fpl_handled_error(x, e)	cache_fpl_handled_error_impl((x), (e), __LINE__)

static bool
cache_fpl_terminated(struct cache_fpl *fpl)
{

	return (fpl->status != CACHE_FPL_STATUS_UNSET);
}

#define CACHE_FPL_SUPPORTED_CN_FLAGS \
	(NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
	 FAILIFEXISTS | FOLLOW | LOCKSHARED | SAVENAME | SAVESTART | WILLBEDIR | \
	 ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK)

#define CACHE_FPL_INTERNAL_CN_FLAGS \
	(ISDOTDOT | MAKEENTRY | ISLASTCN)

_Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
    "supported and internal flags overlap");

static bool
cache_fpl_islastcn(struct nameidata *ndp)
{

	return (*ndp->ni_next == 0);
}

static bool
cache_fpl_istrailingslash(struct cache_fpl *fpl)
{

	return (*(fpl->nulchar - 1) == '/');
}

static bool
cache_fpl_isdotdot(struct componentname *cnp)
{

	if (cnp->cn_namelen == 2 &&
	    cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
		return (true);
	return (false);
}

static bool
cache_can_fplookup(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	struct thread *td;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	td = cnp->cn_thread;

	if (!atomic_load_char(&cache_fast_lookup_enabled)) {
		cache_fpl_aborted_early(fpl);
		return (false);
	}
	if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
		cache_fpl_aborted_early(fpl);
		return (false);
	}
	if (IN_CAPABILITY_MODE(td)) {
		cache_fpl_aborted_early(fpl);
		return (false);
	}
	if (AUDITING_TD(td)) {
		cache_fpl_aborted_early(fpl);
		return (false);
	}
	if (ndp->ni_startdir != NULL) {
		cache_fpl_aborted_early(fpl);
		return (false);
	}
	return (true);
}

static int
cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
{
	struct nameidata *ndp;
	int error;
	bool fsearch;

	ndp = fpl->ndp;
	error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
	if (__predict_false(error != 0)) {
		return (cache_fpl_aborted(fpl));
	}
	fpl->fsearch = fsearch;
	return (0);
}

static int __noinline
cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
    uint32_t hash)
{
	struct componentname *cnp;
	struct vnode *dvp;

	cnp = fpl->cnp;
	dvp = fpl->dvp;

	cache_fpl_smr_exit(fpl);
	if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
		return (cache_fpl_handled_error(fpl, ENOENT));
	else
		return (cache_fpl_aborted(fpl));
}

/*
 * The target vnode is not supported, prepare for the slow path to take over.
 */
static int __noinline
cache_fplookup_partial_setup(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	enum vgetstate dvs;
	struct vnode *dvp;
	struct pwd *pwd;
	seqc_t dvp_seqc;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	pwd = *(fpl->pwd);
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;

	if (!pwd_hold_smr(pwd)) {
		return (cache_fpl_aborted(fpl));
	}

	/*
	 * Note that seqc is checked before the vnode is locked, so by
	 * the time regular lookup gets to it it may have moved.
	 *
	 * Ultimately this does not affect correctness, any lookup errors
	 * are userspace racing with itself. It is guaranteed that any
	 * path which ultimately gets found could also have been found
	 * by regular lookup going all the way in absence of concurrent
	 * modifications.
	 */
	dvs = vget_prep_smr(dvp);
	cache_fpl_smr_exit(fpl);
	if (__predict_false(dvs == VGET_NONE)) {
		pwd_drop(pwd);
		return (cache_fpl_aborted(fpl));
	}

	vget_finish_ref(dvp, dvs);
	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
		vrele(dvp);
		pwd_drop(pwd);
		return (cache_fpl_aborted(fpl));
	}

	cache_fpl_restore_partial(fpl);
#ifdef INVARIANTS
	if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
		panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
		    cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
	}
#endif

	ndp->ni_startdir = dvp;
	cnp->cn_flags |= MAKEENTRY;
	if (cache_fpl_islastcn(ndp))
		cnp->cn_flags |= ISLASTCN;
	if (cache_fpl_isdotdot(cnp))
		cnp->cn_flags |= ISDOTDOT;

	/*
	 * Skip potential extra slashes parsing did not take care of.
	 * cache_fplookup_skip_slashes explains the mechanism.
	 */
	if (__predict_false(*(cnp->cn_nameptr) == '/')) {
		do {
			cnp->cn_nameptr++;
			cache_fpl_pathlen_dec(fpl);
		} while (*(cnp->cn_nameptr) == '/');
	}

	ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
#ifdef INVARIANTS
	if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
		    __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
	}
#endif
	return (0);
}

static int
cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
{
	struct componentname *cnp;
	struct vnode *tvp;
	seqc_t tvp_seqc;
	int error, lkflags;

	cnp = fpl->cnp;
	tvp = fpl->tvp;
	tvp_seqc = fpl->tvp_seqc;

	if ((cnp->cn_flags & LOCKLEAF) != 0) {
		lkflags = LK_SHARED;
		if ((cnp->cn_flags & LOCKSHARED) == 0)
			lkflags = LK_EXCLUSIVE;
		error = vget_finish(tvp, lkflags, tvs);
		if (__predict_false(error != 0)) {
			return (cache_fpl_aborted(fpl));
		}
	} else {
		vget_finish_ref(tvp, tvs);
	}

	if (!vn_seqc_consistent(tvp, tvp_seqc)) {
		if ((cnp->cn_flags & LOCKLEAF) != 0)
			vput(tvp);
		else
			vrele(tvp);
		return (cache_fpl_aborted(fpl));
	}

	return (cache_fpl_handled(fpl));
}

/*
 * They want to possibly modify the state of the namecache.
 */
static int __noinline
cache_fplookup_final_modifying(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	enum vgetstate dvs;
	struct vnode *dvp, *tvp;
	struct mount *mp;
	seqc_t dvp_seqc;
	int error;
	bool docache;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;

	MPASS(*(cnp->cn_nameptr) != '/');
	MPASS(cache_fpl_islastcn(ndp));
	if ((cnp->cn_flags & LOCKPARENT) == 0)
		MPASS((cnp->cn_flags & WANTPARENT) != 0);
	MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
	MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
	    cnp->cn_nameiop == RENAME);
	MPASS((cnp->cn_flags & MAKEENTRY) == 0);
	MPASS((cnp->cn_flags & ISDOTDOT) == 0);

	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
	if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
		docache = false;

	/*
	 * Regular lookup nulifies the slash, which we don't do here.
	 * Don't take chances with filesystem routines seeing it for
	 * the last entry.
	 */
	if (cache_fpl_istrailingslash(fpl)) {
		return (cache_fpl_partial(fpl));
	}

	mp = atomic_load_ptr(&dvp->v_mount);
	if (__predict_false(mp == NULL)) {
		return (cache_fpl_aborted(fpl));
	}

	if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
		cache_fpl_smr_exit(fpl);
		/*
		 * Original code keeps not checking for CREATE which
		 * might be a bug. For now let the old lookup decide.
		 */
		if (cnp->cn_nameiop == CREATE) {
			return (cache_fpl_aborted(fpl));
		}
		return (cache_fpl_handled_error(fpl, EROFS));
	}

	if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, EEXIST));
	}

	/*
	 * Secure access to dvp; check cache_fplookup_partial_setup for
	 * reasoning.
	 *
	 * XXX At least UFS requires its lookup routine to be called for
	 * the last path component, which leads to some level of complication
	 * and inefficiency:
	 * - the target routine always locks the target vnode, but our caller
	 *   may not need it locked
	 * - some of the VOP machinery asserts that the parent is locked, which
	 *   once more may be not required
	 *
	 * TODO: add a flag for filesystems which don't need this.
	 */
	dvs = vget_prep_smr(dvp);
	cache_fpl_smr_exit(fpl);
	if (__predict_false(dvs == VGET_NONE)) {
		return (cache_fpl_aborted(fpl));
	}

	vget_finish_ref(dvp, dvs);
	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
		vrele(dvp);
		return (cache_fpl_aborted(fpl));
	}

	error = vn_lock(dvp, LK_EXCLUSIVE);
	if (__predict_false(error != 0)) {
		vrele(dvp);
		return (cache_fpl_aborted(fpl));
	}

	tvp = NULL;
	cnp->cn_flags |= ISLASTCN;
	if (docache)
		cnp->cn_flags |= MAKEENTRY;
	if (cache_fpl_isdotdot(cnp))
		cnp->cn_flags |= ISDOTDOT;
	cnp->cn_lkflags = LK_EXCLUSIVE;
	error = VOP_LOOKUP(dvp, &tvp, cnp);
	switch (error) {
	case EJUSTRETURN:
	case 0:
		break;
	case ENOTDIR:
	case ENOENT:
		vput(dvp);
		return (cache_fpl_handled_error(fpl, error));
	default:
		vput(dvp);
		return (cache_fpl_aborted(fpl));
	}

	fpl->tvp = tvp;
	fpl->savename = (cnp->cn_flags & SAVENAME) != 0;

	if (tvp == NULL) {
		if ((cnp->cn_flags & SAVESTART) != 0) {
			ndp->ni_startdir = dvp;
			vrefact(ndp->ni_startdir);
			cnp->cn_flags |= SAVENAME;
			fpl->savename = true;
		}
		MPASS(error == EJUSTRETURN);
		if ((cnp->cn_flags & LOCKPARENT) == 0) {
			VOP_UNLOCK(dvp);
		}
		return (cache_fpl_handled(fpl));
	}

	/*
	 * There are very hairy corner cases concerning various flag combinations
	 * and locking state. In particular here we only hold one lock instead of
	 * two.
	 *
	 * Skip the complexity as it is of no significance for normal workloads.
	 */
	if (__predict_false(tvp == dvp)) {
		vput(dvp);
		vrele(tvp);
		return (cache_fpl_aborted(fpl));
	}

	/*
	 * If they want the symlink itself we are fine, but if they want to
	 * follow it regular lookup has to be engaged.
	 */
	if (tvp->v_type == VLNK) {
		if ((cnp->cn_flags & FOLLOW) != 0) {
			vput(dvp);
			vput(tvp);
			return (cache_fpl_aborted(fpl));
		}
	}

	/*
	 * Since we expect this to be the terminal vnode it should almost never
	 * be a mount point.
	 */
	if (__predict_false(cache_fplookup_is_mp(fpl))) {
		vput(dvp);
		vput(tvp);
		return (cache_fpl_aborted(fpl));
	}

	if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
		vput(dvp);
		vput(tvp);
		return (cache_fpl_handled_error(fpl, EEXIST));
	}

	if ((cnp->cn_flags & LOCKLEAF) == 0) {
		VOP_UNLOCK(tvp);
	}

	if ((cnp->cn_flags & LOCKPARENT) == 0) {
		VOP_UNLOCK(dvp);
	}

	if ((cnp->cn_flags & SAVESTART) != 0) {
		ndp->ni_startdir = dvp;
		vrefact(ndp->ni_startdir);
		cnp->cn_flags |= SAVENAME;
		fpl->savename = true;
	}

	return (cache_fpl_handled(fpl));
}

static int __noinline
cache_fplookup_modifying(struct cache_fpl *fpl)
{
	struct nameidata *ndp;

	ndp = fpl->ndp;

	if (!cache_fpl_islastcn(ndp)) {
		return (cache_fpl_partial(fpl));
	}
	return (cache_fplookup_final_modifying(fpl));
}

static int __noinline
cache_fplookup_final_withparent(struct cache_fpl *fpl)
{
	struct componentname *cnp;
	enum vgetstate dvs, tvs;
	struct vnode *dvp, *tvp;
	seqc_t dvp_seqc;
	int error;

	cnp = fpl->cnp;
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;
	tvp = fpl->tvp;

	MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);

	/*
	 * This is less efficient than it can be for simplicity.
	 */
	dvs = vget_prep_smr(dvp);
	if (__predict_false(dvs == VGET_NONE)) {
		return (cache_fpl_aborted(fpl));
	}
	tvs = vget_prep_smr(tvp);
	if (__predict_false(tvs == VGET_NONE)) {
		cache_fpl_smr_exit(fpl);
		vget_abort(dvp, dvs);
		return (cache_fpl_aborted(fpl));
	}

	cache_fpl_smr_exit(fpl);

	if ((cnp->cn_flags & LOCKPARENT) != 0) {
		error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
		if (__predict_false(error != 0)) {
			vget_abort(tvp, tvs);
			return (cache_fpl_aborted(fpl));
		}
	} else {
		vget_finish_ref(dvp, dvs);
	}

	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
		vget_abort(tvp, tvs);
		if ((cnp->cn_flags & LOCKPARENT) != 0)
			vput(dvp);
		else
			vrele(dvp);
		return (cache_fpl_aborted(fpl));
	}

	error = cache_fplookup_final_child(fpl, tvs);
	if (__predict_false(error != 0)) {
		MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED);
		if ((cnp->cn_flags & LOCKPARENT) != 0)
			vput(dvp);
		else
			vrele(dvp);
		return (error);
	}

	MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
	return (0);
}

static int
cache_fplookup_final(struct cache_fpl *fpl)
{
	struct componentname *cnp;
	enum vgetstate tvs;
	struct vnode *dvp, *tvp;
	seqc_t dvp_seqc;

	cnp = fpl->cnp;
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;
	tvp = fpl->tvp;

	MPASS(*(cnp->cn_nameptr) != '/');

	if (cnp->cn_nameiop != LOOKUP) {
		return (cache_fplookup_final_modifying(fpl));
	}

	if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
		return (cache_fplookup_final_withparent(fpl));

	tvs = vget_prep_smr(tvp);
	if (__predict_false(tvs == VGET_NONE)) {
		return (cache_fpl_partial(fpl));
	}

	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
		cache_fpl_smr_exit(fpl);
		vget_abort(tvp, tvs);
		return (cache_fpl_aborted(fpl));
	}

	cache_fpl_smr_exit(fpl);
	return (cache_fplookup_final_child(fpl, tvs));
}

/*
 * Comment from locked lookup:
 * Check for degenerate name (e.g. / or "") which is a way of talking about a
 * directory, e.g. like "/." or ".".
 */
static int __noinline
cache_fplookup_degenerate(struct cache_fpl *fpl)
{
	struct componentname *cnp;
	struct vnode *dvp;
	enum vgetstate dvs;
	int error, lkflags;
#ifdef INVARIANTS
	char *cp;
#endif

	fpl->tvp = fpl->dvp;
	fpl->tvp_seqc = fpl->dvp_seqc;

	cnp = fpl->cnp;
	dvp = fpl->dvp;

#ifdef INVARIANTS
	for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
		KASSERT(*cp == '/',
		    ("%s: encountered non-slash; string [%s]\n", __func__,
		    cnp->cn_pnbuf));
	}
#endif

	if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, EISDIR));
	}

	MPASS((cnp->cn_flags & SAVESTART) == 0);

	if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
		return (cache_fplookup_final_withparent(fpl));
	}

	dvs = vget_prep_smr(dvp);
	cache_fpl_smr_exit(fpl);
	if (__predict_false(dvs == VGET_NONE)) {
		return (cache_fpl_aborted(fpl));
	}

	if ((cnp->cn_flags & LOCKLEAF) != 0) {
		lkflags = LK_SHARED;
		if ((cnp->cn_flags & LOCKSHARED) == 0)
			lkflags = LK_EXCLUSIVE;
		error = vget_finish(dvp, lkflags, dvs);
		if (__predict_false(error != 0)) {
			return (cache_fpl_aborted(fpl));
		}
	} else {
		vget_finish_ref(dvp, dvs);
	}
	return (cache_fpl_handled(fpl));
}

static int __noinline
cache_fplookup_noentry(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	enum vgetstate dvs;
	struct vnode *dvp, *tvp;
	seqc_t dvp_seqc;
	int error;
	bool docache;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;

	MPASS((cnp->cn_flags & MAKEENTRY) == 0);
	MPASS((cnp->cn_flags & ISDOTDOT) == 0);
	MPASS(!cache_fpl_isdotdot(cnp));

	/*
	 * Hack: delayed name len checking.
	 */
	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
	}

	if (cnp->cn_nameptr[0] == '/') {
		return (cache_fplookup_skip_slashes(fpl));
	}

	if (cnp->cn_nameptr[0] == '\0') {
		if (fpl->tvp == NULL) {
			return (cache_fplookup_degenerate(fpl));
		}
		return (cache_fplookup_trailingslash(fpl));
	}

	if (cnp->cn_nameiop != LOOKUP) {
		fpl->tvp = NULL;
		return (cache_fplookup_modifying(fpl));
	}

	MPASS((cnp->cn_flags & SAVESTART) == 0);

	/*
	 * Only try to fill in the component if it is the last one,
	 * otherwise not only there may be several to handle but the
	 * walk may be complicated.
	 */
	if (!cache_fpl_islastcn(ndp)) {
		return (cache_fpl_partial(fpl));
	}

	/*
	 * Regular lookup nulifies the slash, which we don't do here.
	 * Don't take chances with filesystem routines seeing it for
	 * the last entry.
	 */
	if (cache_fpl_istrailingslash(fpl)) {
		return (cache_fpl_partial(fpl));
	}

	/*
	 * Secure access to dvp; check cache_fplookup_partial_setup for
	 * reasoning.
	 */
	dvs = vget_prep_smr(dvp);
	cache_fpl_smr_exit(fpl);
	if (__predict_false(dvs == VGET_NONE)) {
		return (cache_fpl_aborted(fpl));
	}

	vget_finish_ref(dvp, dvs);
	if (!vn_seqc_consistent(dvp, dvp_seqc)) {
		vrele(dvp);
		return (cache_fpl_aborted(fpl));
	}

	error = vn_lock(dvp, LK_SHARED);
	if (__predict_false(error != 0)) {
		vrele(dvp);
		return (cache_fpl_aborted(fpl));
	}

	tvp = NULL;
	/*
	 * TODO: provide variants which don't require locking either vnode.
	 */
	cnp->cn_flags |= ISLASTCN;
	docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
	if (docache)
		cnp->cn_flags |= MAKEENTRY;
	cnp->cn_lkflags = LK_SHARED;
	if ((cnp->cn_flags & LOCKSHARED) == 0) {
		cnp->cn_lkflags = LK_EXCLUSIVE;
	}
	error = VOP_LOOKUP(dvp, &tvp, cnp);
	switch (error) {
	case EJUSTRETURN:
	case 0:
		break;
	case ENOTDIR:
	case ENOENT:
		vput(dvp);
		return (cache_fpl_handled_error(fpl, error));
	default:
		vput(dvp);
		return (cache_fpl_aborted(fpl));
	}

	fpl->tvp = tvp;
	if (!fpl->savename) {
		MPASS((cnp->cn_flags & SAVENAME) == 0);
	}

	if (tvp == NULL) {
		MPASS(error == EJUSTRETURN);
		if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
			vput(dvp);
		} else if ((cnp->cn_flags & LOCKPARENT) == 0) {
			VOP_UNLOCK(dvp);
		}
		return (cache_fpl_handled(fpl));
	}

	if (tvp->v_type == VLNK) {
		if ((cnp->cn_flags & FOLLOW) != 0) {
			vput(dvp);
			vput(tvp);
			return (cache_fpl_aborted(fpl));
		}
	}

	if (__predict_false(cache_fplookup_is_mp(fpl))) {
		vput(dvp);
		vput(tvp);
		return (cache_fpl_aborted(fpl));
	}

	if ((cnp->cn_flags & LOCKLEAF) == 0) {
		VOP_UNLOCK(tvp);
	}

	if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
		vput(dvp);
	} else if ((cnp->cn_flags & LOCKPARENT) == 0) {
		VOP_UNLOCK(dvp);
	}
	return (cache_fpl_handled(fpl));
}

static int __noinline
cache_fplookup_dot(struct cache_fpl *fpl)
{
	int error;

	MPASS(!seqc_in_modify(fpl->dvp_seqc));
	/*
	 * Just re-assign the value. seqc will be checked later for the first
	 * non-dot path component in line and/or before deciding to return the
	 * vnode.
	 */
	fpl->tvp = fpl->dvp;
	fpl->tvp_seqc = fpl->dvp_seqc;

	counter_u64_add(dothits, 1);
	SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);

	error = 0;
	if (cache_fplookup_is_mp(fpl)) {
		error = cache_fplookup_cross_mount(fpl);
	}
	return (error);
}

static int __noinline
cache_fplookup_dotdot(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	struct namecache *ncp;
	struct vnode *dvp;
	struct prison *pr;
	u_char nc_flag;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	dvp = fpl->dvp;

	MPASS(cache_fpl_isdotdot(cnp));

	/*
	 * XXX this is racy the same way regular lookup is
	 */
	for (pr = cnp->cn_cred->cr_prison; pr != NULL;
	    pr = pr->pr_parent)
		if (dvp == pr->pr_root)
			break;

	if (dvp == ndp->ni_rootdir ||
	    dvp == ndp->ni_topdir ||
	    dvp == rootvnode ||
	    pr != NULL) {
		fpl->tvp = dvp;
		fpl->tvp_seqc = vn_seqc_read_any(dvp);
		if (seqc_in_modify(fpl->tvp_seqc)) {
			return (cache_fpl_aborted(fpl));
		}
		return (0);
	}

	if ((dvp->v_vflag & VV_ROOT) != 0) {
		/*
		 * TODO
		 * The opposite of climb mount is needed here.
		 */
		return (cache_fpl_partial(fpl));
	}

	ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
	if (ncp == NULL) {
		return (cache_fpl_aborted(fpl));
	}

	nc_flag = atomic_load_char(&ncp->nc_flag);
	if ((nc_flag & NCF_ISDOTDOT) != 0) {
		if ((nc_flag & NCF_NEGATIVE) != 0)
			return (cache_fpl_aborted(fpl));
		fpl->tvp = ncp->nc_vp;
	} else {
		fpl->tvp = ncp->nc_dvp;
	}

	fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
	if (seqc_in_modify(fpl->tvp_seqc)) {
		return (cache_fpl_partial(fpl));
	}

	/*
	 * Acquire fence provided by vn_seqc_read_any above.
	 */
	if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
		return (cache_fpl_aborted(fpl));
	}

	if (!cache_ncp_canuse(ncp)) {
		return (cache_fpl_aborted(fpl));
	}

	counter_u64_add(dotdothits, 1);
	return (0);
}

static int __noinline
cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
{
	u_char nc_flag;
	bool neg_promote;

	nc_flag = atomic_load_char(&ncp->nc_flag);
	MPASS((nc_flag & NCF_NEGATIVE) != 0);
	/*
	 * If they want to create an entry we need to replace this one.
	 */
	if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
		fpl->tvp = NULL;
		return (cache_fplookup_modifying(fpl));
	}
	neg_promote = cache_neg_hit_prep(ncp);
	if (!cache_fpl_neg_ncp_canuse(ncp)) {
		cache_neg_hit_abort(ncp);
		return (cache_fpl_partial(fpl));
	}
	if (neg_promote) {
		return (cache_fplookup_negative_promote(fpl, ncp, hash));
	}
	cache_neg_hit_finish(ncp);
	cache_fpl_smr_exit(fpl);
	return (cache_fpl_handled_error(fpl, ENOENT));
}

/*
 * Resolve a symlink. Called by filesystem-specific routines.
 *
 * Code flow is:
 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
 */
int
cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	size_t adjust;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	if (__predict_false(len == 0)) {
		return (ENOENT);
	}

	if (__predict_false(len > MAXPATHLEN - 2)) {
		if (cache_fpl_istrailingslash(fpl)) {
			return (EAGAIN);
		}
	}

	ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
#ifdef INVARIANTS
	if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
		    __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
	}
#endif

	if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
		return (ENAMETOOLONG);
	}

	if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
		return (ELOOP);
	}

	adjust = len;
	if (ndp->ni_pathlen > 1) {
		bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
	} else {
		if (cache_fpl_istrailingslash(fpl)) {
			adjust = len + 1;
			cnp->cn_pnbuf[len] = '/';
			cnp->cn_pnbuf[len + 1] = '\0';
		} else {
			cnp->cn_pnbuf[len] = '\0';
		}
	}
	bcopy(string, cnp->cn_pnbuf, len);

	ndp->ni_pathlen += adjust;
	cache_fpl_pathlen_add(fpl, adjust);
	cnp->cn_nameptr = cnp->cn_pnbuf;
	fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
	fpl->tvp = NULL;
	return (0);
}

static int __noinline
cache_fplookup_symlink(struct cache_fpl *fpl)
{
	struct mount *mp;
	struct nameidata *ndp;
	struct componentname *cnp;
	struct vnode *dvp, *tvp;
	int error;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	dvp = fpl->dvp;
	tvp = fpl->tvp;

	if (cache_fpl_islastcn(ndp)) {
		if ((cnp->cn_flags & FOLLOW) == 0) {
			return (cache_fplookup_final(fpl));
		}
	}

	mp = atomic_load_ptr(&dvp->v_mount);
	if (__predict_false(mp == NULL)) {
		return (cache_fpl_aborted(fpl));
	}

	/*
	 * Note this check races against setting the flag just like regular
	 * lookup.
	 */
	if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, EACCES));
	}

	error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
	if (__predict_false(error != 0)) {
		switch (error) {
		case EAGAIN:
			return (cache_fpl_partial(fpl));
		case ENOENT:
		case ENAMETOOLONG:
		case ELOOP:
			cache_fpl_smr_exit(fpl);
			return (cache_fpl_handled_error(fpl, error));
		default:
			return (cache_fpl_aborted(fpl));
		}
	}

	if (*(cnp->cn_nameptr) == '/') {
		fpl->dvp = cache_fpl_handle_root(fpl);
		fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
		if (seqc_in_modify(fpl->dvp_seqc)) {
			return (cache_fpl_aborted(fpl));
		}
	}
	return (0);
}

static int
cache_fplookup_next(struct cache_fpl *fpl)
{
	struct componentname *cnp;
	struct namecache *ncp;
	struct vnode *dvp, *tvp;
	u_char nc_flag;
	uint32_t hash;
	int error;

	cnp = fpl->cnp;
	dvp = fpl->dvp;
	hash = fpl->hash;

	if (__predict_false(cnp->cn_nameptr[0] == '.')) {
		if (cnp->cn_namelen == 1) {
			return (cache_fplookup_dot(fpl));
		}
		if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
			return (cache_fplookup_dotdot(fpl));
		}
	}

	MPASS(!cache_fpl_isdotdot(cnp));

	CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
		if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
		    !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
			break;
	}

	if (__predict_false(ncp == NULL)) {
		return (cache_fplookup_noentry(fpl));
	}

	tvp = atomic_load_ptr(&ncp->nc_vp);
	nc_flag = atomic_load_char(&ncp->nc_flag);
	if ((nc_flag & NCF_NEGATIVE) != 0) {
		return (cache_fplookup_neg(fpl, ncp, hash));
	}

	if (!cache_ncp_canuse(ncp)) {
		return (cache_fpl_partial(fpl));
	}

	fpl->tvp = tvp;
	fpl->tvp_seqc = vn_seqc_read_any(tvp);
	if (seqc_in_modify(fpl->tvp_seqc)) {
		return (cache_fpl_partial(fpl));
	}

	counter_u64_add(numposhits, 1);
	SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);

	error = 0;
	if (cache_fplookup_is_mp(fpl)) {
		error = cache_fplookup_cross_mount(fpl);
	}
	return (error);
}

static bool
cache_fplookup_mp_supported(struct mount *mp)
{

	MPASS(mp != NULL);
	if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
		return (false);
	return (true);
}

/*
 * Walk up the mount stack (if any).
 *
 * Correctness is provided in the following ways:
 * - all vnodes are protected from freeing with SMR
 * - struct mount objects are type stable making them always safe to access
 * - stability of the particular mount is provided by busying it
 * - relationship between the vnode which is mounted on and the mount is
 *   verified with the vnode sequence counter after busying
 * - association between root vnode of the mount and the mount is protected
 *   by busy
 *
 * From that point on we can read the sequence counter of the root vnode
 * and get the next mount on the stack (if any) using the same protection.
 *
 * By the end of successful walk we are guaranteed the reached state was
 * indeed present at least at some point which matches the regular lookup.
 */
static int __noinline
cache_fplookup_climb_mount(struct cache_fpl *fpl)
{
	struct mount *mp, *prev_mp;
	struct mount_pcpu *mpcpu, *prev_mpcpu;
	struct vnode *vp;
	seqc_t vp_seqc;

	vp = fpl->tvp;
	vp_seqc = fpl->tvp_seqc;

	VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
	mp = atomic_load_ptr(&vp->v_mountedhere);
	if (__predict_false(mp == NULL)) {
		return (0);
	}

	prev_mp = NULL;
	for (;;) {
		if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
			if (prev_mp != NULL)
				vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
			return (cache_fpl_partial(fpl));
		}
		if (prev_mp != NULL)
			vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
		if (!vn_seqc_consistent(vp, vp_seqc)) {
			vfs_op_thread_exit_crit(mp, mpcpu);
			return (cache_fpl_partial(fpl));
		}
		if (!cache_fplookup_mp_supported(mp)) {
			vfs_op_thread_exit_crit(mp, mpcpu);
			return (cache_fpl_partial(fpl));
		}
		vp = atomic_load_ptr(&mp->mnt_rootvnode);
		if (vp == NULL) {
			vfs_op_thread_exit_crit(mp, mpcpu);
			return (cache_fpl_partial(fpl));
		}
		vp_seqc = vn_seqc_read_any(vp);
		if (seqc_in_modify(vp_seqc)) {
			vfs_op_thread_exit_crit(mp, mpcpu);
			return (cache_fpl_partial(fpl));
		}
		prev_mp = mp;
		prev_mpcpu = mpcpu;
		mp = atomic_load_ptr(&vp->v_mountedhere);
		if (mp == NULL)
			break;
	}

	vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
	fpl->tvp = vp;
	fpl->tvp_seqc = vp_seqc;
	return (0);
}

static int __noinline
cache_fplookup_cross_mount(struct cache_fpl *fpl)
{
	struct mount *mp;
	struct mount_pcpu *mpcpu;
	struct vnode *vp;
	seqc_t vp_seqc;

	vp = fpl->tvp;
	vp_seqc = fpl->tvp_seqc;

	VNPASS(vp->v_type == VDIR || vp->v_type == VBAD, vp);
	mp = atomic_load_ptr(&vp->v_mountedhere);
	if (__predict_false(mp == NULL)) {
		return (0);
	}

	if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
		return (cache_fpl_partial(fpl));
	}
	if (!vn_seqc_consistent(vp, vp_seqc)) {
		vfs_op_thread_exit_crit(mp, mpcpu);
		return (cache_fpl_partial(fpl));
	}
	if (!cache_fplookup_mp_supported(mp)) {
		vfs_op_thread_exit_crit(mp, mpcpu);
		return (cache_fpl_partial(fpl));
	}
	vp = atomic_load_ptr(&mp->mnt_rootvnode);
	if (__predict_false(vp == NULL)) {
		vfs_op_thread_exit_crit(mp, mpcpu);
		return (cache_fpl_partial(fpl));
	}
	vp_seqc = vn_seqc_read_any(vp);
	vfs_op_thread_exit_crit(mp, mpcpu);
	if (seqc_in_modify(vp_seqc)) {
		return (cache_fpl_partial(fpl));
	}
	mp = atomic_load_ptr(&vp->v_mountedhere);
	if (__predict_false(mp != NULL)) {
		/*
		 * There are possibly more mount points on top.
		 * Normally this does not happen so for simplicity just start
		 * over.
		 */
		return (cache_fplookup_climb_mount(fpl));
	}

	fpl->tvp = vp;
	fpl->tvp_seqc = vp_seqc;
	return (0);
}

/*
 * Check if a vnode is mounted on.
 */
static bool
cache_fplookup_is_mp(struct cache_fpl *fpl)
{
	struct vnode *vp;

	vp = fpl->tvp;
	return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
}

/*
 * Parse the path.
 *
 * The code was originally copy-pasted from regular lookup and despite
 * clean ups leaves performance on the table. Any modifications here
 * must take into account that in case off fallback the resulting
 * nameidata state has to be compatible with the original.
 */

/*
 * Debug ni_pathlen tracking.
 */
#ifdef INVARIANTS
static void
cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
{

	fpl->debug.ni_pathlen += n;
	KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
	    ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
}

static void
cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
{

	fpl->debug.ni_pathlen -= n;
	KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
	    ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
}

static void
cache_fpl_pathlen_inc(struct cache_fpl *fpl)
{

	cache_fpl_pathlen_add(fpl, 1);
}

static void
cache_fpl_pathlen_dec(struct cache_fpl *fpl)
{

	cache_fpl_pathlen_sub(fpl, 1);
}
#else
static void
cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
{
}

static void
cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
{
}

static void
cache_fpl_pathlen_inc(struct cache_fpl *fpl)
{
}

static void
cache_fpl_pathlen_dec(struct cache_fpl *fpl)
{
}
#endif

static void
cache_fplookup_parse(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	struct vnode *dvp;
	char *cp;
	uint32_t hash;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	dvp = fpl->dvp;

	/*
	 * Find the end of this path component, it is either / or nul.
	 *
	 * Store / as a temporary sentinel so that we only have one character
	 * to test for. Pathnames tend to be short so this should not be
	 * resulting in cache misses.
	 *
	 * TODO: fix this to be word-sized.
	 */
	KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
	    ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
	    __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
	    fpl->nulchar, cnp->cn_pnbuf));
	KASSERT(*fpl->nulchar == '\0',
	    ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
	    cnp->cn_pnbuf));
	hash = cache_get_hash_iter_start(dvp);
	*fpl->nulchar = '/';
	for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
		KASSERT(*cp != '\0',
		    ("%s: encountered unexpected nul; string [%s]\n", __func__,
		    cnp->cn_nameptr));
		hash = cache_get_hash_iter(*cp, hash);
		continue;
	}
	*fpl->nulchar = '\0';
	fpl->hash = cache_get_hash_iter_finish(hash);

	cnp->cn_namelen = cp - cnp->cn_nameptr;
	cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);

#ifdef INVARIANTS
	if (cnp->cn_namelen <= NAME_MAX) {
		if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
			panic("%s: mismatched hash for [%s] len %ld", __func__,
			    cnp->cn_nameptr, cnp->cn_namelen);
		}
	}
#endif

	/*
	 * Hack: we have to check if the found path component's length exceeds
	 * NAME_MAX. However, the condition is very rarely true and check can
	 * be elided in the common case -- if an entry was found in the cache,
	 * then it could not have been too long to begin with.
	 */
	ndp->ni_next = cp;
}

static void
cache_fplookup_parse_advance(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	cnp->cn_nameptr = ndp->ni_next;
	KASSERT(*(cnp->cn_nameptr) == '/',
	    ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
	    cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
	cnp->cn_nameptr++;
	cache_fpl_pathlen_dec(fpl);
}

/*
 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
 *
 * Lockless lookup tries to elide checking for spurious slashes and should they
 * be present is guaranteed to fail to find an entry. In this case the caller
 * must check if the name starts with a slash and call this routine.  It is
 * going to fast forward across the spurious slashes and set the state up for
 * retry.
 */
static int __noinline
cache_fplookup_skip_slashes(struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	MPASS(*(cnp->cn_nameptr) == '/');
	do {
		cnp->cn_nameptr++;
		cache_fpl_pathlen_dec(fpl);
	} while (*(cnp->cn_nameptr) == '/');

	/*
	 * Go back to one slash so that cache_fplookup_parse_advance has
	 * something to skip.
	 */
	cnp->cn_nameptr--;
	cache_fpl_pathlen_inc(fpl);

	/*
	 * cache_fplookup_parse_advance starts from ndp->ni_next
	 */
	ndp->ni_next = cnp->cn_nameptr;

	/*
	 * See cache_fplookup_dot.
	 */
	fpl->tvp = fpl->dvp;
	fpl->tvp_seqc = fpl->dvp_seqc;

	return (0);
}

/*
 * Handle trailing slashes (e.g., "foo/").
 *
 * If a trailing slash is found the terminal vnode must be a directory.
 * Regular lookup shortens the path by nulifying the first trailing slash and
 * sets the TRAILINGSLASH flag to denote this took place. There are several
 * checks on it performed later.
 *
 * Similarly to spurious slashes, lockless lookup handles this in a speculative
 * manner relying on an invariant that a non-directory vnode will get a miss.
 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
 *
 * Thus for a path like "foo/bar/" the code unwinds the state back to 'bar/'
 * and denotes this is the last path component, which avoids looping back.
 *
 * Only plain lookups are supported for now to restrict corner cases to handle.
 */
static int __noinline
cache_fplookup_trailingslash(struct cache_fpl *fpl)
{
#ifdef INVARIANTS
	size_t ni_pathlen;
#endif
	struct nameidata *ndp;
	struct componentname *cnp;
	struct namecache *ncp;
	struct vnode *tvp;
	char *cn_nameptr_orig, *cn_nameptr_slash;
	seqc_t tvp_seqc;
	u_char nc_flag;

	ndp = fpl->ndp;
	cnp = fpl->cnp;
	tvp = fpl->tvp;
	tvp_seqc = fpl->tvp_seqc;

	MPASS(fpl->dvp == fpl->tvp);
	KASSERT(cache_fpl_istrailingslash(fpl),
	    ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
	    cnp->cn_pnbuf));
	KASSERT(cnp->cn_nameptr[0] == '\0',
	    ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
	    cnp->cn_pnbuf));
	KASSERT(cnp->cn_namelen == 0,
	    ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
	    cnp->cn_pnbuf));
	MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);

	if (cnp->cn_nameiop != LOOKUP) {
		return (cache_fpl_aborted(fpl));
	}

	if (__predict_false(tvp->v_type != VDIR)) {
		if (!vn_seqc_consistent(tvp, tvp_seqc)) {
			return (cache_fpl_aborted(fpl));
		}
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, ENOTDIR));
	}

	/*
	 * Denote the last component.
	 */
	ndp->ni_next = &cnp->cn_nameptr[0];
	MPASS(cache_fpl_islastcn(ndp));

	/*
	 * Unwind trailing slashes.
	 */
	cn_nameptr_orig = cnp->cn_nameptr;
	while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
		cnp->cn_nameptr--;
		if (cnp->cn_nameptr[0] != '/') {
			break;
		}
	}

	/*
	 * Unwind to the beginning of the path component.
	 *
	 * Note the path may or may not have started with a slash.
	 */
	cn_nameptr_slash = cnp->cn_nameptr;
	while (cnp->cn_nameptr > cnp->cn_pnbuf) {
		cnp->cn_nameptr--;
		if (cnp->cn_nameptr[0] == '/') {
			break;
		}
	}
	if (cnp->cn_nameptr[0] == '/') {
		cnp->cn_nameptr++;
	}

	cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
	cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
	cache_fpl_checkpoint(fpl);

#ifdef INVARIANTS
	ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
	if (ni_pathlen != fpl->debug.ni_pathlen) {
		panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
		    __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
		    cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
	}
#endif

	/*
	 * The previous directory is this one.
	 */
	if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
		return (0);
	}

	/*
	 * The previous directory is something else.
	 */
	tvp = fpl->tvp;
	ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
	if (__predict_false(ncp == NULL)) {
		return (cache_fpl_aborted(fpl));
	}
	nc_flag = atomic_load_char(&ncp->nc_flag);
	if ((nc_flag & NCF_ISDOTDOT) != 0) {
		return (cache_fpl_aborted(fpl));
	}
	fpl->dvp = ncp->nc_dvp;
	fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
	if (seqc_in_modify(fpl->dvp_seqc)) {
		return (cache_fpl_aborted(fpl));
	}
	return (0);
}

/*
 * See the API contract for VOP_FPLOOKUP_VEXEC.
 */
static int __noinline
cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
{
	struct componentname *cnp;
	struct vnode *dvp;
	seqc_t dvp_seqc;

	cnp = fpl->cnp;
	dvp = fpl->dvp;
	dvp_seqc = fpl->dvp_seqc;

	/*
	 * TODO: Due to ignoring slashes lookup will perform a permission check
	 * on the last dir when it should not have. If it fails, we get here.
	 * It is possible possible to fix it up fully without resorting to
	 * regular lookup, but for now just abort.
	 */
	if (cache_fpl_istrailingslash(fpl)) {
		return (cache_fpl_aborted(fpl));
	}

	/*
	 * Hack: delayed degenerate path checking.
	 */
	if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
		return (cache_fplookup_degenerate(fpl));
	}

	/*
	 * Hack: delayed name len checking.
	 */
	if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
		cache_fpl_smr_exit(fpl);
		return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
	}

	/*
	 * Hack: they may be looking up foo/bar, where foo is not a directory.
	 * In such a case we need to return ENOTDIR, but we may happen to get
	 * here with a different error.
	 */
	if (dvp->v_type != VDIR) {
		error = ENOTDIR;
	}

	/*
	 * Hack: handle O_SEARCH.
	 *
	 * Open Group Base Specifications Issue 7, 2018 edition states:
	 * <quote>
	 * If the access mode of the open file description associated with the
	 * file descriptor is not O_SEARCH, the function shall check whether
	 * directory searches are permitted using the current permissions of
	 * the directory underlying the file descriptor. If the access mode is
	 * O_SEARCH, the function shall not perform the check.
	 * </quote>
	 *
	 * Regular lookup tests for the NOEXECCHECK flag for every path
	 * component to decide whether to do the permission check. However,
	 * since most lookups never have the flag (and when they do it is only
	 * present for the first path component), lockless lookup only acts on
	 * it if there is a permission problem. Here the flag is represented
	 * with a boolean so that we don't have to clear it on the way out.
	 *
	 * For simplicity this always aborts.
	 * TODO: check if this is the first lookup and ignore the permission
	 * problem. Note the flag has to survive fallback (if it happens to be
	 * performed).
	 */
	if (fpl->fsearch) {
		return (cache_fpl_aborted(fpl));
	}

	switch (error) {
	case EAGAIN:
		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
			error = cache_fpl_aborted(fpl);
		} else {
			cache_fpl_partial(fpl);
		}
		break;
	default:
		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
			error = cache_fpl_aborted(fpl);
		} else {
			cache_fpl_smr_exit(fpl);
			cache_fpl_handled_error(fpl, error);
		}
		break;
	}
	return (error);
}

static int
cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
{
	struct nameidata *ndp;
	struct componentname *cnp;
	struct mount *mp;
	int error;

	ndp = fpl->ndp;
	cnp = fpl->cnp;

	cache_fpl_checkpoint(fpl);

	/*
	 * The vnode at hand is almost always stable, skip checking for it.
	 * Worst case this postpones the check towards the end of the iteration
	 * of the main loop.
	 */
	fpl->dvp = dvp;
	fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);

	mp = atomic_load_ptr(&dvp->v_mount);
	if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
		return (cache_fpl_aborted(fpl));
	}

	MPASS(fpl->tvp == NULL);

	for (;;) {
		cache_fplookup_parse(fpl);

		error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
		if (__predict_false(error != 0)) {
			error = cache_fplookup_failed_vexec(fpl, error);
			break;
		}

		error = cache_fplookup_next(fpl);
		if (__predict_false(cache_fpl_terminated(fpl))) {
			break;
		}

		VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);

		if (fpl->tvp->v_type == VLNK) {
			error = cache_fplookup_symlink(fpl);
			if (cache_fpl_terminated(fpl)) {
				break;
			}
		} else {
			if (cache_fpl_islastcn(ndp)) {
				error = cache_fplookup_final(fpl);
				break;
			}

			if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
				error = cache_fpl_aborted(fpl);
				break;
			}

			fpl->dvp = fpl->tvp;
			fpl->dvp_seqc = fpl->tvp_seqc;
			cache_fplookup_parse_advance(fpl);
		}

		cache_fpl_checkpoint(fpl);
	}

	return (error);
}

/*
 * Fast path lookup protected with SMR and sequence counters.
 *
 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
 *
 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
 * outlined below.
 *
 * Traditional vnode lookup conceptually looks like this:
 *
 * vn_lock(current);
 * for (;;) {
 *	next = find();
 *	vn_lock(next);
 *	vn_unlock(current);
 *	current = next;
 *	if (last)
 *	    break;
 * }
 * return (current);
 *
 * Each jump to the next vnode is safe memory-wise and atomic with respect to
 * any modifications thanks to holding respective locks.
 *
 * The same guarantee can be provided with a combination of safe memory
 * reclamation and sequence counters instead. If all operations which affect
 * the relationship between the current vnode and the one we are looking for
 * also modify the counter, we can verify whether all the conditions held as
 * we made the jump. This includes things like permissions, mount points etc.
 * Counter modification is provided by enclosing relevant places in
 * vn_seqc_write_begin()/end() calls.
 *
 * Thus this translates to:
 *
 * vfs_smr_enter();
 * dvp_seqc = seqc_read_any(dvp);
 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
 *     abort();
 * for (;;) {
 * 	tvp = find();
 * 	tvp_seqc = seqc_read_any(tvp);
 * 	if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
 * 	    abort();
 * 	if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
 * 	    abort();
 * 	dvp = tvp; // we know nothing of importance has changed
 * 	dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
 * 	if (last)
 * 	    break;
 * }
 * vget(); // secure the vnode
 * if (!seqc_consistent(tvp, tvp_seqc) // final check
 * 	    abort();
 * // at this point we know nothing has changed for any parent<->child pair
 * // as they were crossed during the lookup, meaning we matched the guarantee
 * // of the locked variant
 * return (tvp);
 *
 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
 * - they are called while within vfs_smr protection which they must never exit
 * - EAGAIN can be returned to denote checking could not be performed, it is
 *   always valid to return it
 * - if the sequence counter has not changed the result must be valid
 * - if the sequence counter has changed both false positives and false negatives
 *   are permitted (since the result will be rejected later)
 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
 *
 * Caveats to watch out for:
 * - vnodes are passed unlocked and unreferenced with nothing stopping
 *   VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
 *   to use atomic_load_ptr to fetch it.
 * - the aforementioned object can also get freed, meaning absent other means it
 *   should be protected with vfs_smr
 * - either safely checking permissions as they are modified or guaranteeing
 *   their stability is left to the routine
 */
int
cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
    struct pwd **pwdp)
{
	struct cache_fpl fpl;
	struct pwd *pwd;
	struct vnode *dvp;
	struct componentname *cnp;
	int error;

	fpl.status = CACHE_FPL_STATUS_UNSET;
	fpl.in_smr = false;
	fpl.ndp = ndp;
	fpl.cnp = cnp = &ndp->ni_cnd;
	MPASS(ndp->ni_lcf == 0);
	MPASS(curthread == cnp->cn_thread);
	KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
	    ("%s: internal flags found in cn_flags %" PRIx64, __func__,
	    cnp->cn_flags));
	if ((cnp->cn_flags & SAVESTART) != 0) {
		MPASS(cnp->cn_nameiop != LOOKUP);
	}
	MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);

	if (__predict_false(!cache_can_fplookup(&fpl))) {
		*status = fpl.status;
		SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
		return (EOPNOTSUPP);
	}

	cache_fpl_checkpoint_outer(&fpl);

	cache_fpl_smr_enter_initial(&fpl);
#ifdef INVARIANTS
	fpl.debug.ni_pathlen = ndp->ni_pathlen;
#endif
	fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
	fpl.fsearch = false;
	fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
	fpl.tvp = NULL; /* for degenerate path handling */
	fpl.pwd = pwdp;
	pwd = pwd_get_smr();
	*(fpl.pwd) = pwd;
	ndp->ni_rootdir = pwd->pwd_rdir;
	ndp->ni_topdir = pwd->pwd_jdir;

	if (cnp->cn_pnbuf[0] == '/') {
		dvp = cache_fpl_handle_root(&fpl);
		MPASS(ndp->ni_resflags == 0);
		ndp->ni_resflags = NIRES_ABS;
	} else {
		if (ndp->ni_dirfd == AT_FDCWD) {
			dvp = pwd->pwd_cdir;
		} else {
			error = cache_fplookup_dirfd(&fpl, &dvp);
			if (__predict_false(error != 0)) {
				goto out;
			}
		}
	}

	SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
	error = cache_fplookup_impl(dvp, &fpl);
out:
	cache_fpl_smr_assert_not_entered(&fpl);
	cache_fpl_assert_status(&fpl);
	*status = fpl.status;
	if (SDT_PROBES_ENABLED()) {
		SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
		if (fpl.status == CACHE_FPL_STATUS_HANDLED)
			SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
			    ndp);
	}

	if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
		MPASS(error != CACHE_FPL_FAILED);
		if (error != 0) {
			MPASS(fpl.dvp == NULL);
			MPASS(fpl.tvp == NULL);
			MPASS(fpl.savename == false);
		}
		ndp->ni_dvp = fpl.dvp;
		ndp->ni_vp = fpl.tvp;
		if (fpl.savename) {
			cnp->cn_flags |= HASBUF;
		} else {
			cache_fpl_cleanup_cnp(cnp);
		}
	}
	return (error);
}