summaryrefslogtreecommitdiffstats
path: root/fs/bcachefs/btree_iter.c
blob: 1bd7c92d705ec7cf5f829fbe16ff72893e5d6111 (plain)
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
// SPDX-License-Identifier: GPL-2.0

#include "bcachefs.h"
#include "bkey_methods.h"
#include "bkey_buf.h"
#include "btree_cache.h"
#include "btree_iter.h"
#include "btree_key_cache.h"
#include "btree_locking.h"
#include "btree_update.h"
#include "debug.h"
#include "extents.h"
#include "journal.h"
#include "trace.h"

#include <linux/prefetch.h>

static inline bool is_btree_node(struct btree_iter *iter, unsigned l)
{
	return l < BTREE_MAX_DEPTH &&
		(unsigned long) iter->l[l].b >= 128;
}

static inline struct bpos btree_iter_search_key(struct btree_iter *iter)
{
	struct bpos pos = iter->pos;

	if ((iter->flags & BTREE_ITER_IS_EXTENTS) &&
	    bkey_cmp(pos, POS_MAX))
		pos = bkey_successor(pos);
	return pos;
}

static inline bool btree_iter_pos_before_node(struct btree_iter *iter,
					      struct btree *b)
{
	return bkey_cmp(iter->real_pos, b->data->min_key) < 0;
}

static inline bool btree_iter_pos_after_node(struct btree_iter *iter,
					     struct btree *b)
{
	return bkey_cmp(b->key.k.p, iter->real_pos) < 0;
}

static inline bool btree_iter_pos_in_node(struct btree_iter *iter,
					  struct btree *b)
{
	return iter->btree_id == b->c.btree_id &&
		!btree_iter_pos_before_node(iter, b) &&
		!btree_iter_pos_after_node(iter, b);
}

/* Btree node locking: */

void bch2_btree_node_unlock_write(struct btree *b, struct btree_iter *iter)
{
	bch2_btree_node_unlock_write_inlined(b, iter);
}

void __bch2_btree_node_lock_write(struct btree *b, struct btree_iter *iter)
{
	struct btree_iter *linked;
	unsigned readers = 0;

	EBUG_ON(!btree_node_intent_locked(iter, b->c.level));

	trans_for_each_iter(iter->trans, linked)
		if (linked->l[b->c.level].b == b &&
		    btree_node_read_locked(linked, b->c.level))
			readers++;

	/*
	 * Must drop our read locks before calling six_lock_write() -
	 * six_unlock() won't do wakeups until the reader count
	 * goes to 0, and it's safe because we have the node intent
	 * locked:
	 */
	atomic64_sub(__SIX_VAL(read_lock, readers),
		     &b->c.lock.state.counter);
	btree_node_lock_type(iter->trans->c, b, SIX_LOCK_write);
	atomic64_add(__SIX_VAL(read_lock, readers),
		     &b->c.lock.state.counter);
}

bool __bch2_btree_node_relock(struct btree_iter *iter, unsigned level)
{
	struct btree *b = btree_iter_node(iter, level);
	int want = __btree_lock_want(iter, level);

	if (!is_btree_node(iter, level))
		return false;

	if (race_fault())
		return false;

	if (six_relock_type(&b->c.lock, want, iter->l[level].lock_seq) ||
	    (btree_node_lock_seq_matches(iter, b, level) &&
	     btree_node_lock_increment(iter->trans, b, level, want))) {
		mark_btree_node_locked(iter, level, want);
		return true;
	} else {
		return false;
	}
}

static bool bch2_btree_node_upgrade(struct btree_iter *iter, unsigned level)
{
	struct btree *b = iter->l[level].b;

	EBUG_ON(btree_lock_want(iter, level) != BTREE_NODE_INTENT_LOCKED);

	if (!is_btree_node(iter, level))
		return false;

	if (btree_node_intent_locked(iter, level))
		return true;

	if (race_fault())
		return false;

	if (btree_node_locked(iter, level)
	    ? six_lock_tryupgrade(&b->c.lock)
	    : six_relock_type(&b->c.lock, SIX_LOCK_intent, iter->l[level].lock_seq))
		goto success;

	if (btree_node_lock_seq_matches(iter, b, level) &&
	    btree_node_lock_increment(iter->trans, b, level, BTREE_NODE_INTENT_LOCKED)) {
		btree_node_unlock(iter, level);
		goto success;
	}

	return false;
success:
	mark_btree_node_intent_locked(iter, level);
	return true;
}

static inline bool btree_iter_get_locks(struct btree_iter *iter,
					bool upgrade, bool trace)
{
	unsigned l = iter->level;
	int fail_idx = -1;

	do {
		if (!btree_iter_node(iter, l))
			break;

		if (!(upgrade
		      ? bch2_btree_node_upgrade(iter, l)
		      : bch2_btree_node_relock(iter, l))) {
			if (trace)
				(upgrade
				 ? trace_node_upgrade_fail
				 : trace_node_relock_fail)(l, iter->l[l].lock_seq,
						is_btree_node(iter, l)
						? 0
						: (unsigned long) iter->l[l].b,
						is_btree_node(iter, l)
						? iter->l[l].b->c.lock.state.seq
						: 0);

			fail_idx = l;
			btree_iter_set_dirty(iter, BTREE_ITER_NEED_TRAVERSE);
		}

		l++;
	} while (l < iter->locks_want);

	/*
	 * When we fail to get a lock, we have to ensure that any child nodes
	 * can't be relocked so bch2_btree_iter_traverse has to walk back up to
	 * the node that we failed to relock:
	 */
	while (fail_idx >= 0) {
		btree_node_unlock(iter, fail_idx);
		iter->l[fail_idx].b = BTREE_ITER_NO_NODE_GET_LOCKS;
		--fail_idx;
	}

	if (iter->uptodate == BTREE_ITER_NEED_RELOCK)
		iter->uptodate = BTREE_ITER_NEED_PEEK;

	bch2_btree_trans_verify_locks(iter->trans);

	return iter->uptodate < BTREE_ITER_NEED_RELOCK;
}

static struct bpos btree_node_pos(struct btree_bkey_cached_common *_b,
				  enum btree_iter_type type)
{
	return  type != BTREE_ITER_CACHED
		? container_of(_b, struct btree, c)->key.k.p
		: container_of(_b, struct bkey_cached, c)->key.pos;
}

/* Slowpath: */
bool __bch2_btree_node_lock(struct btree *b, struct bpos pos,
			    unsigned level, struct btree_iter *iter,
			    enum six_lock_type type,
			    six_lock_should_sleep_fn should_sleep_fn, void *p,
			    unsigned long ip)
{
	struct btree_trans *trans = iter->trans;
	struct btree_iter *linked, *deadlock_iter = NULL;
	u64 start_time = local_clock();
	unsigned reason = 9;

	/* Check if it's safe to block: */
	trans_for_each_iter(trans, linked) {
		if (!linked->nodes_locked)
			continue;

		/*
		 * Can't block taking an intent lock if we have _any_ nodes read
		 * locked:
		 *
		 * - Our read lock blocks another thread with an intent lock on
		 *   the same node from getting a write lock, and thus from
		 *   dropping its intent lock
		 *
		 * - And the other thread may have multiple nodes intent locked:
		 *   both the node we want to intent lock, and the node we
		 *   already have read locked - deadlock:
		 */
		if (type == SIX_LOCK_intent &&
		    linked->nodes_locked != linked->nodes_intent_locked) {
			if (!(trans->nounlock)) {
				linked->locks_want = max_t(unsigned,
						linked->locks_want,
						__fls(linked->nodes_locked) + 1);
				if (!btree_iter_get_locks(linked, true, false)) {
					deadlock_iter = linked;
					reason = 1;
				}
			} else {
				deadlock_iter = linked;
				reason = 2;
			}
		}

		if (linked->btree_id != iter->btree_id) {
			if (linked->btree_id > iter->btree_id) {
				deadlock_iter = linked;
				reason = 3;
			}
			continue;
		}

		/*
		 * Within the same btree, cached iterators come before non
		 * cached iterators:
		 */
		if (btree_iter_is_cached(linked) != btree_iter_is_cached(iter)) {
			if (btree_iter_is_cached(iter)) {
				deadlock_iter = linked;
				reason = 4;
			}
			continue;
		}

		/*
		 * Interior nodes must be locked before their descendants: if
		 * another iterator has possible descendants locked of the node
		 * we're about to lock, it must have the ancestors locked too:
		 */
		if (level > __fls(linked->nodes_locked)) {
			if (!(trans->nounlock)) {
				linked->locks_want =
					max(level + 1, max_t(unsigned,
					    linked->locks_want,
					    iter->locks_want));
				if (!btree_iter_get_locks(linked, true, false)) {
					deadlock_iter = linked;
					reason = 5;
				}
			} else {
				deadlock_iter = linked;
				reason = 6;
			}
		}

		/* Must lock btree nodes in key order: */
		if (btree_node_locked(linked, level) &&
		    bkey_cmp(pos, btree_node_pos((void *) linked->l[level].b,
						 btree_iter_type(linked))) <= 0) {
			deadlock_iter = linked;
			reason = 7;
		}

		/*
		 * Recheck if this is a node we already have locked - since one
		 * of the get_locks() calls might've successfully
		 * upgraded/relocked it:
		 */
		if (linked->l[level].b == b &&
		    btree_node_locked_type(linked, level) >= type) {
			six_lock_increment(&b->c.lock, type);
			return true;
		}
	}

	if (unlikely(deadlock_iter)) {
		trace_trans_restart_would_deadlock(iter->trans->ip, ip,
				reason,
				deadlock_iter->btree_id,
				btree_iter_type(deadlock_iter),
				iter->btree_id,
				btree_iter_type(iter));
		return false;
	}

	if (six_trylock_type(&b->c.lock, type))
		return true;

	if (six_lock_type(&b->c.lock, type, should_sleep_fn, p))
		return false;

	bch2_time_stats_update(&trans->c->times[lock_to_time_stat(type)],
			       start_time);
	return true;
}

/* Btree iterator locking: */

#ifdef CONFIG_BCACHEFS_DEBUG
static void bch2_btree_iter_verify_locks(struct btree_iter *iter)
{
	unsigned l;

	if (!(iter->trans->iters_linked & (1ULL << iter->idx))) {
		BUG_ON(iter->nodes_locked);
		return;
	}

	for (l = 0; is_btree_node(iter, l); l++) {
		if (iter->uptodate >= BTREE_ITER_NEED_RELOCK &&
		    !btree_node_locked(iter, l))
			continue;

		BUG_ON(btree_lock_want(iter, l) !=
		       btree_node_locked_type(iter, l));
	}
}

void bch2_btree_trans_verify_locks(struct btree_trans *trans)
{
	struct btree_iter *iter;

	trans_for_each_iter(trans, iter)
		bch2_btree_iter_verify_locks(iter);
}
#else
static inline void bch2_btree_iter_verify_locks(struct btree_iter *iter) {}
#endif

__flatten
bool bch2_btree_iter_relock(struct btree_iter *iter, bool trace)
{
	return btree_iter_get_locks(iter, false, trace);
}

bool __bch2_btree_iter_upgrade(struct btree_iter *iter,
			       unsigned new_locks_want)
{
	struct btree_iter *linked;

	EBUG_ON(iter->locks_want >= new_locks_want);

	iter->locks_want = new_locks_want;

	if (btree_iter_get_locks(iter, true, true))
		return true;

	/*
	 * Ancestor nodes must be locked before child nodes, so set locks_want
	 * on iterators that might lock ancestors before us to avoid getting
	 * -EINTR later:
	 */
	trans_for_each_iter(iter->trans, linked)
		if (linked != iter &&
		    linked->btree_id == iter->btree_id &&
		    linked->locks_want < new_locks_want) {
			linked->locks_want = new_locks_want;
			btree_iter_get_locks(linked, true, false);
		}

	return false;
}

bool __bch2_btree_iter_upgrade_nounlock(struct btree_iter *iter,
					unsigned new_locks_want)
{
	unsigned l = iter->level;

	EBUG_ON(iter->locks_want >= new_locks_want);

	iter->locks_want = new_locks_want;

	do {
		if (!btree_iter_node(iter, l))
			break;

		if (!bch2_btree_node_upgrade(iter, l)) {
			iter->locks_want = l;
			return false;
		}

		l++;
	} while (l < iter->locks_want);

	return true;
}

void __bch2_btree_iter_downgrade(struct btree_iter *iter,
				 unsigned downgrade_to)
{
	unsigned l, new_locks_want = downgrade_to ?:
		(iter->flags & BTREE_ITER_INTENT ? 1 : 0);

	if (iter->locks_want < downgrade_to) {
		iter->locks_want = new_locks_want;

		while (iter->nodes_locked &&
		       (l = __fls(iter->nodes_locked)) >= iter->locks_want) {
			if (l > iter->level) {
				btree_node_unlock(iter, l);
			} else {
				if (btree_node_intent_locked(iter, l)) {
					six_lock_downgrade(&iter->l[l].b->c.lock);
					iter->nodes_intent_locked ^= 1 << l;
				}
				break;
			}
		}
	}

	bch2_btree_trans_verify_locks(iter->trans);
}

void bch2_trans_downgrade(struct btree_trans *trans)
{
	struct btree_iter *iter;

	trans_for_each_iter(trans, iter)
		bch2_btree_iter_downgrade(iter);
}

/* Btree transaction locking: */

bool bch2_trans_relock(struct btree_trans *trans)
{
	struct btree_iter *iter;
	bool ret = true;

	trans_for_each_iter(trans, iter)
		if (iter->uptodate == BTREE_ITER_NEED_RELOCK)
			ret &= bch2_btree_iter_relock(iter, true);

	return ret;
}

void bch2_trans_unlock(struct btree_trans *trans)
{
	struct btree_iter *iter;

	trans_for_each_iter(trans, iter)
		__bch2_btree_iter_unlock(iter);
}

/* Btree iterator: */

#ifdef CONFIG_BCACHEFS_DEBUG

static void bch2_btree_iter_verify_cached(struct btree_iter *iter)
{
	struct bkey_cached *ck;
	bool locked = btree_node_locked(iter, 0);

	if (!bch2_btree_node_relock(iter, 0))
		return;

	ck = (void *) iter->l[0].b;
	BUG_ON(ck->key.btree_id != iter->btree_id ||
	       bkey_cmp(ck->key.pos, iter->pos));

	if (!locked)
		btree_node_unlock(iter, 0);
}

static void bch2_btree_iter_verify_level(struct btree_iter *iter,
					 unsigned level)
{
	struct btree_iter_level *l = &iter->l[level];
	struct btree_node_iter tmp = l->iter;
	bool locked = btree_node_locked(iter, level);
	struct bkey_packed *p, *k;
	char buf1[100], buf2[100];
	const char *msg;

	if (!bch2_debug_check_iterators)
		return;

	if (btree_iter_type(iter) == BTREE_ITER_CACHED) {
		if (!level)
			bch2_btree_iter_verify_cached(iter);
		return;
	}

	BUG_ON(iter->level < iter->min_depth);

	if (!btree_iter_node(iter, level))
		return;

	if (!bch2_btree_node_relock(iter, level))
		return;

	BUG_ON(!btree_iter_pos_in_node(iter, l->b));

	/*
	 * node iterators don't use leaf node iterator:
	 */
	if (btree_iter_type(iter) == BTREE_ITER_NODES &&
	    level <= iter->min_depth)
		goto unlock;

	bch2_btree_node_iter_verify(&l->iter, l->b);

	/*
	 * For interior nodes, the iterator will have skipped past
	 * deleted keys:
	 *
	 * For extents, the iterator may have skipped past deleted keys (but not
	 * whiteouts)
	 */
	p = level || btree_node_type_is_extents(iter->btree_id)
		? bch2_btree_node_iter_prev(&tmp, l->b)
		: bch2_btree_node_iter_prev_all(&tmp, l->b);
	k = bch2_btree_node_iter_peek_all(&l->iter, l->b);

	if (p && bkey_iter_pos_cmp(l->b, p, &iter->real_pos) >= 0) {
		msg = "before";
		goto err;
	}

	if (k && bkey_iter_pos_cmp(l->b, k, &iter->real_pos) < 0) {
		msg = "after";
		goto err;
	}
unlock:
	if (!locked)
		btree_node_unlock(iter, level);
	return;
err:
	strcpy(buf1, "(none)");
	strcpy(buf2, "(none)");

	if (p) {
		struct bkey uk = bkey_unpack_key(l->b, p);
		bch2_bkey_to_text(&PBUF(buf1), &uk);
	}

	if (k) {
		struct bkey uk = bkey_unpack_key(l->b, k);
		bch2_bkey_to_text(&PBUF(buf2), &uk);
	}

	panic("iterator should be %s key at level %u:\n"
	      "iter pos %llu:%llu\n"
	      "prev key %s\n"
	      "cur  key %s\n",
	      msg, level,
	      iter->real_pos.inode, iter->real_pos.offset,
	      buf1, buf2);
}

static void bch2_btree_iter_verify(struct btree_iter *iter)
{
	unsigned i;

	EBUG_ON(iter->btree_id >= BTREE_ID_NR);

	bch2_btree_iter_verify_locks(iter);

	for (i = 0; i < BTREE_MAX_DEPTH; i++)
		bch2_btree_iter_verify_level(iter, i);
}

static void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter)
{
	enum btree_iter_type type = btree_iter_type(iter);

	BUG_ON((type == BTREE_ITER_KEYS ||
		type == BTREE_ITER_CACHED) &&
	       (bkey_cmp(iter->pos, bkey_start_pos(&iter->k)) < 0 ||
		bkey_cmp(iter->pos, iter->k.p) > 0));
}

void bch2_btree_trans_verify_iters(struct btree_trans *trans, struct btree *b)
{
	struct btree_iter *iter;

	if (!bch2_debug_check_iterators)
		return;

	trans_for_each_iter_with_node(trans, b, iter)
		bch2_btree_iter_verify_level(iter, b->c.level);
}

#else

static inline void bch2_btree_iter_verify_level(struct btree_iter *iter, unsigned l) {}
static inline void bch2_btree_iter_verify(struct btree_iter *iter) {}
static inline void bch2_btree_iter_verify_entry_exit(struct btree_iter *iter) {}

#endif

static void btree_node_iter_set_set_pos(struct btree_node_iter *iter,
					struct btree *b,
					struct bset_tree *t,
					struct bkey_packed *k)
{
	struct btree_node_iter_set *set;

	btree_node_iter_for_each(iter, set)
		if (set->end == t->end_offset) {
			set->k = __btree_node_key_to_offset(b, k);
			bch2_btree_node_iter_sort(iter, b);
			return;
		}

	bch2_btree_node_iter_push(iter, b, k, btree_bkey_last(b, t));
}

static void __bch2_btree_iter_fix_key_modified(struct btree_iter *iter,
					       struct btree *b,
					       struct bkey_packed *where)
{
	struct btree_iter_level *l = &iter->l[b->c.level];

	if (where != bch2_btree_node_iter_peek_all(&l->iter, l->b))
		return;

	if (bkey_iter_pos_cmp(l->b, where, &iter->real_pos) < 0)
		bch2_btree_node_iter_advance(&l->iter, l->b);

	btree_iter_set_dirty(iter, BTREE_ITER_NEED_PEEK);
}

void bch2_btree_iter_fix_key_modified(struct btree_iter *iter,
				      struct btree *b,
				      struct bkey_packed *where)
{
	struct btree_iter *linked;

	trans_for_each_iter_with_node(iter->trans, b, linked) {
		__bch2_btree_iter_fix_key_modified(linked, b, where);
		bch2_btree_iter_verify_level(linked, b->c.level);
	}
}

static void __bch2_btree_node_iter_fix(struct btree_iter *iter,
				      struct btree *b,
				      struct btree_node_iter *node_iter,
				      struct bset_tree *t,
				      struct bkey_packed *where,
				      unsigned clobber_u64s,
				      unsigned new_u64s)
{
	const struct bkey_packed *end = btree_bkey_last(b, t);
	struct btree_node_iter_set *set;
	unsigned offset = __btree_node_key_to_offset(b, where);
	int shift = new_u64s - clobber_u64s;
	unsigned old_end = t->end_offset - shift;
	unsigned orig_iter_pos = node_iter->data[0].k;
	bool iter_current_key_modified =
		orig_iter_pos >= offset &&
		orig_iter_pos <= offset + clobber_u64s;

	btree_node_iter_for_each(node_iter, set)
		if (set->end == old_end)
			goto found;

	/* didn't find the bset in the iterator - might have to readd it: */
	if (new_u64s &&
	    bkey_iter_pos_cmp(b, where, &iter->real_pos) >= 0) {
		bch2_btree_node_iter_push(node_iter, b, where, end);
		goto fixup_done;
	} else {
		/* Iterator is after key that changed */
		return;
	}
found:
	set->end = t->end_offset;

	/* Iterator hasn't gotten to the key that changed yet: */
	if (set->k < offset)
		return;

	if (new_u64s &&
	    bkey_iter_pos_cmp(b, where, &iter->real_pos) >= 0) {
		set->k = offset;
	} else if (set->k < offset + clobber_u64s) {
		set->k = offset + new_u64s;
		if (set->k == set->end)
			bch2_btree_node_iter_set_drop(node_iter, set);
	} else {
		/* Iterator is after key that changed */
		set->k = (int) set->k + shift;
		return;
	}

	bch2_btree_node_iter_sort(node_iter, b);
fixup_done:
	if (node_iter->data[0].k != orig_iter_pos)
		iter_current_key_modified = true;

	/*
	 * When a new key is added, and the node iterator now points to that
	 * key, the iterator might have skipped past deleted keys that should
	 * come after the key the iterator now points to. We have to rewind to
	 * before those deleted keys - otherwise
	 * bch2_btree_node_iter_prev_all() breaks:
	 */
	if (!bch2_btree_node_iter_end(node_iter) &&
	    iter_current_key_modified &&
	    (b->c.level ||
	     btree_node_type_is_extents(iter->btree_id))) {
		struct bset_tree *t;
		struct bkey_packed *k, *k2, *p;

		k = bch2_btree_node_iter_peek_all(node_iter, b);

		for_each_bset(b, t) {
			bool set_pos = false;

			if (node_iter->data[0].end == t->end_offset)
				continue;

			k2 = bch2_btree_node_iter_bset_pos(node_iter, b, t);

			while ((p = bch2_bkey_prev_all(b, t, k2)) &&
			       bkey_iter_cmp(b, k, p) < 0) {
				k2 = p;
				set_pos = true;
			}

			if (set_pos)
				btree_node_iter_set_set_pos(node_iter,
							    b, t, k2);
		}
	}

	if (!b->c.level &&
	    node_iter == &iter->l[0].iter &&
	    iter_current_key_modified)
		btree_iter_set_dirty(iter, BTREE_ITER_NEED_PEEK);
}

void bch2_btree_node_iter_fix(struct btree_iter *iter,
			      struct btree *b,
			      struct btree_node_iter *node_iter,
			      struct bkey_packed *where,
			      unsigned clobber_u64s,
			      unsigned new_u64s)
{
	struct bset_tree *t = bch2_bkey_to_bset_inlined(b, where);
	struct btree_iter *linked;

	if (node_iter != &iter->l[b->c.level].iter) {
		__bch2_btree_node_iter_fix(iter, b, node_iter, t,
					   where, clobber_u64s, new_u64s);

		if (bch2_debug_check_iterators)
			bch2_btree_node_iter_verify(node_iter, b);
	}

	trans_for_each_iter_with_node(iter->trans, b, linked) {
		__bch2_btree_node_iter_fix(linked, b,
					   &linked->l[b->c.level].iter, t,
					   where, clobber_u64s, new_u64s);
		bch2_btree_iter_verify_level(linked, b->c.level);
	}
}

static inline struct bkey_s_c __btree_iter_unpack(struct btree_iter *iter,
						  struct btree_iter_level *l,
						  struct bkey *u,
						  struct bkey_packed *k)
{
	struct bkey_s_c ret;

	if (unlikely(!k)) {
		/*
		 * signal to bch2_btree_iter_peek_slot() that we're currently at
		 * a hole
		 */
		u->type = KEY_TYPE_deleted;
		return bkey_s_c_null;
	}

	ret = bkey_disassemble(l->b, k, u);

	if (bch2_debug_check_bkeys)
		bch2_bkey_debugcheck(iter->trans->c, l->b, ret);

	return ret;
}

/* peek_all() doesn't skip deleted keys */
static inline struct bkey_s_c __btree_iter_peek_all(struct btree_iter *iter,
						    struct btree_iter_level *l,
						    struct bkey *u)
{
	return __btree_iter_unpack(iter, l, u,
			bch2_btree_node_iter_peek_all(&l->iter, l->b));
}

static inline struct bkey_s_c __btree_iter_peek(struct btree_iter *iter,
						struct btree_iter_level *l)
{
	return __btree_iter_unpack(iter, l, &iter->k,
			bch2_btree_node_iter_peek(&l->iter, l->b));
}

static inline struct bkey_s_c __btree_iter_prev(struct btree_iter *iter,
						struct btree_iter_level *l)
{
	return __btree_iter_unpack(iter, l, &iter->k,
			bch2_btree_node_iter_prev(&l->iter, l->b));
}

static inline bool btree_iter_advance_to_pos(struct btree_iter *iter,
					     struct btree_iter_level *l,
					     int max_advance)
{
	struct bkey_packed *k;
	int nr_advanced = 0;

	while ((k = bch2_btree_node_iter_peek_all(&l->iter, l->b)) &&
	       bkey_iter_pos_cmp(l->b, k, &iter->real_pos) < 0) {
		if (max_advance > 0 && nr_advanced >= max_advance)
			return false;

		bch2_btree_node_iter_advance(&l->iter, l->b);
		nr_advanced++;
	}

	return true;
}

/*
 * Verify that iterator for parent node points to child node:
 */
static void btree_iter_verify_new_node(struct btree_iter *iter, struct btree *b)
{
	struct btree_iter_level *l;
	unsigned plevel;
	bool parent_locked;
	struct bkey_packed *k;

	if (!IS_ENABLED(CONFIG_BCACHEFS_DEBUG))
		return;

	plevel = b->c.level + 1;
	if (!btree_iter_node(iter, plevel))
		return;

	parent_locked = btree_node_locked(iter, plevel);

	if (!bch2_btree_node_relock(iter, plevel))
		return;

	l = &iter->l[plevel];
	k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
	if (!k ||
	    bkey_deleted(k) ||
	    bkey_cmp_left_packed(l->b, k, &b->key.k.p)) {
		char buf[100];
		struct bkey uk = bkey_unpack_key(b, k);

		bch2_dump_btree_node(iter->trans->c, l->b);
		bch2_bkey_to_text(&PBUF(buf), &uk);
		panic("parent iter doesn't point to new node:\n"
		      "iter pos %s %llu:%llu\n"
		      "iter key %s\n"
		      "new node %llu:%llu-%llu:%llu\n",
		      bch2_btree_ids[iter->btree_id],
		      iter->pos.inode,
		      iter->pos.offset,
		      buf,
		      b->data->min_key.inode,
		      b->data->min_key.offset,
		      b->key.k.p.inode, b->key.k.p.offset);
	}

	if (!parent_locked)
		btree_node_unlock(iter, b->c.level + 1);
}

static inline void __btree_iter_init(struct btree_iter *iter,
				     unsigned level)
{
	struct btree_iter_level *l = &iter->l[level];

	bch2_btree_node_iter_init(&l->iter, l->b, &iter->real_pos);

	/*
	 * Iterators to interior nodes should always be pointed at the first non
	 * whiteout:
	 */
	if (level)
		bch2_btree_node_iter_peek(&l->iter, l->b);

	btree_iter_set_dirty(iter, BTREE_ITER_NEED_PEEK);
}

static inline void btree_iter_node_set(struct btree_iter *iter,
				       struct btree *b)
{
	BUG_ON(btree_iter_type(iter) == BTREE_ITER_CACHED);

	btree_iter_verify_new_node(iter, b);

	EBUG_ON(!btree_iter_pos_in_node(iter, b));
	EBUG_ON(b->c.lock.state.seq & 1);

	iter->l[b->c.level].lock_seq = b->c.lock.state.seq;
	iter->l[b->c.level].b = b;
	__btree_iter_init(iter, b->c.level);
}

/*
 * A btree node is being replaced - update the iterator to point to the new
 * node:
 */
void bch2_btree_iter_node_replace(struct btree_iter *iter, struct btree *b)
{
	enum btree_node_locked_type t;
	struct btree_iter *linked;

	trans_for_each_iter(iter->trans, linked)
		if (btree_iter_type(linked) != BTREE_ITER_CACHED &&
		    btree_iter_pos_in_node(linked, b)) {
			/*
			 * bch2_btree_iter_node_drop() has already been called -
			 * the old node we're replacing has already been
			 * unlocked and the pointer invalidated
			 */
			BUG_ON(btree_node_locked(linked, b->c.level));

			t = btree_lock_want(linked, b->c.level);
			if (t != BTREE_NODE_UNLOCKED) {
				six_lock_increment(&b->c.lock, (enum six_lock_type) t);
				mark_btree_node_locked(linked, b->c.level, (enum six_lock_type) t);
			}

			btree_iter_node_set(linked, b);
		}
}

void bch2_btree_iter_node_drop(struct btree_iter *iter, struct btree *b)
{
	struct btree_iter *linked;
	unsigned level = b->c.level;

	trans_for_each_iter(iter->trans, linked)
		if (linked->l[level].b == b) {
			__btree_node_unlock(linked, level);
			linked->l[level].b = BTREE_ITER_NO_NODE_DROP;
		}
}

/*
 * A btree node has been modified in such a way as to invalidate iterators - fix
 * them:
 */
void bch2_btree_iter_reinit_node(struct btree_iter *iter, struct btree *b)
{
	struct btree_iter *linked;

	trans_for_each_iter_with_node(iter->trans, b, linked)
		__btree_iter_init(linked, b->c.level);
}

static int lock_root_check_fn(struct six_lock *lock, void *p)
{
	struct btree *b = container_of(lock, struct btree, c.lock);
	struct btree **rootp = p;

	return b == *rootp ? 0 : -1;
}

static inline int btree_iter_lock_root(struct btree_iter *iter,
				       unsigned depth_want,
				       unsigned long trace_ip)
{
	struct bch_fs *c = iter->trans->c;
	struct btree *b, **rootp = &c->btree_roots[iter->btree_id].b;
	enum six_lock_type lock_type;
	unsigned i;

	EBUG_ON(iter->nodes_locked);

	while (1) {
		b = READ_ONCE(*rootp);
		iter->level = READ_ONCE(b->c.level);

		if (unlikely(iter->level < depth_want)) {
			/*
			 * the root is at a lower depth than the depth we want:
			 * got to the end of the btree, or we're walking nodes
			 * greater than some depth and there are no nodes >=
			 * that depth
			 */
			iter->level = depth_want;
			for (i = iter->level; i < BTREE_MAX_DEPTH; i++)
				iter->l[i].b = NULL;
			return 1;
		}

		lock_type = __btree_lock_want(iter, iter->level);
		if (unlikely(!btree_node_lock(b, POS_MAX, iter->level,
					      iter, lock_type,
					      lock_root_check_fn, rootp,
					      trace_ip)))
			return -EINTR;

		if (likely(b == READ_ONCE(*rootp) &&
			   b->c.level == iter->level &&
			   !race_fault())) {
			for (i = 0; i < iter->level; i++)
				iter->l[i].b = BTREE_ITER_NO_NODE_LOCK_ROOT;
			iter->l[iter->level].b = b;
			for (i = iter->level + 1; i < BTREE_MAX_DEPTH; i++)
				iter->l[i].b = NULL;

			mark_btree_node_locked(iter, iter->level, lock_type);
			btree_iter_node_set(iter, b);
			return 0;
		}

		six_unlock_type(&b->c.lock, lock_type);
	}
}

noinline
static void btree_iter_prefetch(struct btree_iter *iter)
{
	struct bch_fs *c = iter->trans->c;
	struct btree_iter_level *l = &iter->l[iter->level];
	struct btree_node_iter node_iter = l->iter;
	struct bkey_packed *k;
	struct bkey_buf tmp;
	unsigned nr = test_bit(BCH_FS_STARTED, &c->flags)
		? (iter->level > 1 ? 0 :  2)
		: (iter->level > 1 ? 1 : 16);
	bool was_locked = btree_node_locked(iter, iter->level);

	bch2_bkey_buf_init(&tmp);

	while (nr) {
		if (!bch2_btree_node_relock(iter, iter->level))
			break;

		bch2_btree_node_iter_advance(&node_iter, l->b);
		k = bch2_btree_node_iter_peek(&node_iter, l->b);
		if (!k)
			break;

		bch2_bkey_buf_unpack(&tmp, c, l->b, k);
		bch2_btree_node_prefetch(c, iter, tmp.k, iter->btree_id,
					 iter->level - 1);
	}

	if (!was_locked)
		btree_node_unlock(iter, iter->level);

	bch2_bkey_buf_exit(&tmp, c);
}

static noinline void btree_node_mem_ptr_set(struct btree_iter *iter,
					    unsigned plevel, struct btree *b)
{
	struct btree_iter_level *l = &iter->l[plevel];
	bool locked = btree_node_locked(iter, plevel);
	struct bkey_packed *k;
	struct bch_btree_ptr_v2 *bp;

	if (!bch2_btree_node_relock(iter, plevel))
		return;

	k = bch2_btree_node_iter_peek_all(&l->iter, l->b);
	BUG_ON(k->type != KEY_TYPE_btree_ptr_v2);

	bp = (void *) bkeyp_val(&l->b->format, k);
	bp->mem_ptr = (unsigned long)b;

	if (!locked)
		btree_node_unlock(iter, plevel);
}

static __always_inline int btree_iter_down(struct btree_iter *iter,
					   unsigned long trace_ip)
{
	struct bch_fs *c = iter->trans->c;
	struct btree_iter_level *l = &iter->l[iter->level];
	struct btree *b;
	unsigned level = iter->level - 1;
	enum six_lock_type lock_type = __btree_lock_want(iter, level);
	struct bkey_buf tmp;
	int ret;

	EBUG_ON(!btree_node_locked(iter, iter->level));

	bch2_bkey_buf_init(&tmp);
	bch2_bkey_buf_unpack(&tmp, c, l->b,
			 bch2_btree_node_iter_peek(&l->iter, l->b));

	b = bch2_btree_node_get(c, iter, tmp.k, level, lock_type, trace_ip);
	ret = PTR_ERR_OR_ZERO(b);
	if (unlikely(ret))
		goto err;

	mark_btree_node_locked(iter, level, lock_type);
	btree_iter_node_set(iter, b);

	if (tmp.k->k.type == KEY_TYPE_btree_ptr_v2 &&
	    unlikely(b != btree_node_mem_ptr(tmp.k)))
		btree_node_mem_ptr_set(iter, level + 1, b);

	if (iter->flags & BTREE_ITER_PREFETCH)
		btree_iter_prefetch(iter);

	iter->level = level;
err:
	bch2_bkey_buf_exit(&tmp, c);
	return ret;
}

static void btree_iter_up(struct btree_iter *iter)
{
	btree_node_unlock(iter, iter->level++);
}

static int btree_iter_traverse_one(struct btree_iter *, unsigned long);

static int __btree_iter_traverse_all(struct btree_trans *trans, int ret)
{
	struct bch_fs *c = trans->c;
	struct btree_iter *iter;
	u8 sorted[BTREE_ITER_MAX];
	unsigned i, nr_sorted = 0;

	if (trans->in_traverse_all)
		return -EINTR;

	trans->in_traverse_all = true;
retry_all:
	nr_sorted = 0;

	trans_for_each_iter(trans, iter)
		sorted[nr_sorted++] = iter->idx;

#define btree_iter_cmp_by_idx(_l, _r)				\
		btree_iter_lock_cmp(&trans->iters[_l], &trans->iters[_r])

	bubble_sort(sorted, nr_sorted, btree_iter_cmp_by_idx);
#undef btree_iter_cmp_by_idx
	bch2_trans_unlock(trans);
	cond_resched();

	if (unlikely(ret == -ENOMEM)) {
		struct closure cl;

		closure_init_stack(&cl);

		do {
			ret = bch2_btree_cache_cannibalize_lock(c, &cl);
			closure_sync(&cl);
		} while (ret);
	}

	if (unlikely(ret == -EIO)) {
		trans->error = true;
		goto out;
	}

	BUG_ON(ret && ret != -EINTR);

	/* Now, redo traversals in correct order: */
	for (i = 0; i < nr_sorted; i++) {
		unsigned idx = sorted[i];

		/*
		 * sucessfully traversing one iterator can cause another to be
		 * unlinked, in btree_key_cache_fill()
		 */
		if (!(trans->iters_linked & (1ULL << idx)))
			continue;

		ret = btree_iter_traverse_one(&trans->iters[idx], _THIS_IP_);
		if (ret)
			goto retry_all;
	}

	if (hweight64(trans->iters_live) > 1)
		ret = -EINTR;
	else
		trans_for_each_iter(trans, iter)
			if (iter->flags & BTREE_ITER_KEEP_UNTIL_COMMIT) {
				ret = -EINTR;
				break;
			}
out:
	bch2_btree_cache_cannibalize_unlock(c);

	trans->in_traverse_all = false;
	return ret;
}

int bch2_btree_iter_traverse_all(struct btree_trans *trans)
{
	return __btree_iter_traverse_all(trans, 0);
}

static inline bool btree_iter_good_node(struct btree_iter *iter,
					unsigned l, int check_pos)
{
	if (!is_btree_node(iter, l) ||
	    !bch2_btree_node_relock(iter, l))
		return false;

	if (check_pos <= 0 && btree_iter_pos_before_node(iter, iter->l[l].b))
		return false;
	if (check_pos >= 0 && btree_iter_pos_after_node(iter, iter->l[l].b))
		return false;
	return true;
}

static inline unsigned btree_iter_up_until_good_node(struct btree_iter *iter,
						     int check_pos)
{
	unsigned l = iter->level;

	while (btree_iter_node(iter, l) &&
	       !btree_iter_good_node(iter, l, check_pos)) {
		btree_node_unlock(iter, l);
		iter->l[l].b = BTREE_ITER_NO_NODE_UP;
		l++;
	}

	return l;
}

/*
 * This is the main state machine for walking down the btree - walks down to a
 * specified depth
 *
 * Returns 0 on success, -EIO on error (error reading in a btree node).
 *
 * On error, caller (peek_node()/peek_key()) must return NULL; the error is
 * stashed in the iterator and returned from bch2_trans_exit().
 */
static int btree_iter_traverse_one(struct btree_iter *iter,
				   unsigned long trace_ip)
{
	unsigned depth_want = iter->level;

	/*
	 * if we need interior nodes locked, call btree_iter_relock() to make
	 * sure we walk back up enough that we lock them:
	 */
	if (iter->uptodate == BTREE_ITER_NEED_RELOCK ||
	    iter->locks_want > 1)
		bch2_btree_iter_relock(iter, false);

	if (btree_iter_type(iter) == BTREE_ITER_CACHED)
		return bch2_btree_iter_traverse_cached(iter);

	if (iter->uptodate < BTREE_ITER_NEED_RELOCK)
		return 0;

	if (unlikely(iter->level >= BTREE_MAX_DEPTH))
		return 0;

	/*
	 * XXX: correctly using BTREE_ITER_UPTODATE should make using check_pos
	 * here unnecessary
	 */
	iter->level = btree_iter_up_until_good_node(iter, 0);

	/*
	 * If we've got a btree node locked (i.e. we aren't about to relock the
	 * root) - advance its node iterator if necessary:
	 *
	 * XXX correctly using BTREE_ITER_UPTODATE should make this unnecessary
	 */
	if (is_btree_node(iter, iter->level)) {
		BUG_ON(!btree_iter_pos_in_node(iter, iter->l[iter->level].b));

		btree_iter_advance_to_pos(iter, &iter->l[iter->level], -1);
	}

	/*
	 * Note: iter->nodes[iter->level] may be temporarily NULL here - that
	 * would indicate to other code that we got to the end of the btree,
	 * here it indicates that relocking the root failed - it's critical that
	 * btree_iter_lock_root() comes next and that it can't fail
	 */
	while (iter->level > depth_want) {
		int ret = btree_iter_node(iter, iter->level)
			? btree_iter_down(iter, trace_ip)
			: btree_iter_lock_root(iter, depth_want, trace_ip);
		if (unlikely(ret)) {
			if (ret == 1)
				return 0;

			iter->level = depth_want;

			if (ret == -EIO) {
				iter->flags |= BTREE_ITER_ERROR;
				iter->l[iter->level].b =
					BTREE_ITER_NO_NODE_ERROR;
			} else {
				iter->l[iter->level].b =
					BTREE_ITER_NO_NODE_DOWN;
			}
			return ret;
		}
	}

	iter->uptodate = BTREE_ITER_NEED_PEEK;

	bch2_btree_iter_verify(iter);
	return 0;
}

int __must_check __bch2_btree_iter_traverse(struct btree_iter *iter)
{
	struct btree_trans *trans = iter->trans;
	int ret;

	ret =   bch2_trans_cond_resched(trans) ?:
		btree_iter_traverse_one(iter, _RET_IP_);
	if (unlikely(ret))
		ret = __btree_iter_traverse_all(trans, ret);

	return ret;
}

/* Iterate across nodes (leaf and interior nodes) */

struct btree *bch2_btree_iter_peek_node(struct btree_iter *iter)
{
	struct btree *b;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_NODES);
	bch2_btree_iter_verify(iter);

	if (iter->uptodate == BTREE_ITER_UPTODATE)
		return iter->l[iter->level].b;

	ret = bch2_btree_iter_traverse(iter);
	if (ret)
		return NULL;

	b = btree_iter_node(iter, iter->level);
	if (!b)
		return NULL;

	BUG_ON(bkey_cmp(b->key.k.p, iter->pos) < 0);

	iter->pos = iter->real_pos = b->key.k.p;
	iter->uptodate = BTREE_ITER_UPTODATE;

	bch2_btree_iter_verify(iter);

	return b;
}

struct btree *bch2_btree_iter_next_node(struct btree_iter *iter)
{
	struct btree *b;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_NODES);
	bch2_btree_iter_verify(iter);

	/* already got to end? */
	if (!btree_iter_node(iter, iter->level))
		return NULL;

	bch2_trans_cond_resched(iter->trans);

	btree_iter_up(iter);

	if (!bch2_btree_node_relock(iter, iter->level))
		btree_iter_set_dirty(iter, BTREE_ITER_NEED_RELOCK);

	ret = bch2_btree_iter_traverse(iter);
	if (ret)
		return NULL;

	/* got to end? */
	b = btree_iter_node(iter, iter->level);
	if (!b)
		return NULL;

	if (bkey_cmp(iter->pos, b->key.k.p) < 0) {
		/*
		 * Haven't gotten to the end of the parent node: go back down to
		 * the next child node
		 */

		/*
		 * We don't really want to be unlocking here except we can't
		 * directly tell btree_iter_traverse() "traverse to this level"
		 * except by setting iter->level, so we have to unlock so we
		 * don't screw up our lock invariants:
		 */
		if (btree_node_read_locked(iter, iter->level))
			btree_node_unlock(iter, iter->level);

		iter->pos = iter->real_pos = bkey_successor(iter->pos);
		iter->level	= iter->min_depth;

		btree_iter_set_dirty(iter, BTREE_ITER_NEED_TRAVERSE);
		ret = bch2_btree_iter_traverse(iter);
		if (ret)
			return NULL;

		b = iter->l[iter->level].b;
	}

	iter->pos = iter->real_pos = b->key.k.p;
	iter->uptodate = BTREE_ITER_UPTODATE;

	bch2_btree_iter_verify(iter);

	return b;
}

/* Iterate across keys (in leaf nodes only) */

static void btree_iter_pos_changed(struct btree_iter *iter, int cmp)
{
	unsigned l = iter->level;

	if (!cmp)
		goto out;

	if (unlikely(btree_iter_type(iter) == BTREE_ITER_CACHED)) {
		btree_node_unlock(iter, 0);
		iter->l[0].b = BTREE_ITER_NO_NODE_UP;
		btree_iter_set_dirty(iter, BTREE_ITER_NEED_TRAVERSE);
		return;
	}

	l = btree_iter_up_until_good_node(iter, cmp);

	if (btree_iter_node(iter, l)) {
		/*
		 * We might have to skip over many keys, or just a few: try
		 * advancing the node iterator, and if we have to skip over too
		 * many keys just reinit it (or if we're rewinding, since that
		 * is expensive).
		 */
		if (cmp < 0 ||
		    !btree_iter_advance_to_pos(iter, &iter->l[l], 8))
			__btree_iter_init(iter, l);

		/* Don't leave it locked if we're not supposed to: */
		if (btree_lock_want(iter, l) == BTREE_NODE_UNLOCKED)
			btree_node_unlock(iter, l);
	}
out:
	if (l != iter->level)
		btree_iter_set_dirty(iter, BTREE_ITER_NEED_TRAVERSE);
	else
		btree_iter_set_dirty(iter, BTREE_ITER_NEED_PEEK);
}

static void btree_iter_set_search_pos(struct btree_iter *iter, struct bpos new_pos)
{
	int cmp = bkey_cmp(new_pos, iter->real_pos);

	iter->real_pos = new_pos;

	btree_iter_pos_changed(iter, cmp);

	bch2_btree_iter_verify(iter);
}

void __bch2_btree_iter_set_pos(struct btree_iter *iter, struct bpos new_pos,
			       bool strictly_greater)
{
	bkey_init(&iter->k);
	iter->k.p = iter->pos = new_pos;

	iter->flags &= ~BTREE_ITER_IS_EXTENTS;
	iter->flags |= strictly_greater ? BTREE_ITER_IS_EXTENTS : 0;

	btree_iter_set_search_pos(iter, btree_iter_search_key(iter));
}

void bch2_btree_iter_set_pos(struct btree_iter *iter, struct bpos new_pos)
{
	__bch2_btree_iter_set_pos(iter, new_pos,
			(iter->flags & BTREE_ITER_IS_EXTENTS) != 0);
}

static inline bool bch2_btree_iter_advance_pos(struct btree_iter *iter)
{
	struct bpos pos = iter->k.p;
	bool ret = bkey_cmp(pos, POS_MAX) != 0;

	if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
		pos = bkey_successor(pos);
	bch2_btree_iter_set_pos(iter, pos);
	return ret;
}

static inline bool bch2_btree_iter_rewind_pos(struct btree_iter *iter)
{
	struct bpos pos = bkey_start_pos(&iter->k);
	bool ret = bkey_cmp(pos, POS_MIN) != 0;

	if (ret && !(iter->flags & BTREE_ITER_IS_EXTENTS))
		pos = bkey_predecessor(pos);
	bch2_btree_iter_set_pos(iter, pos);
	return ret;
}

static inline bool btree_iter_set_pos_to_next_leaf(struct btree_iter *iter)
{
	struct bpos next_pos = iter->l[0].b->key.k.p;
	bool ret = bkey_cmp(next_pos, POS_MAX) != 0;

	/*
	 * Typically, we don't want to modify iter->pos here, since that
	 * indicates where we searched from - unless we got to the end of the
	 * btree, in that case we want iter->pos to reflect that:
	 */
	if (ret)
		btree_iter_set_search_pos(iter, bkey_successor(next_pos));
	else
		bch2_btree_iter_set_pos(iter, POS_MAX);

	return ret;
}

static inline bool btree_iter_set_pos_to_prev_leaf(struct btree_iter *iter)
{
	struct bpos next_pos = iter->l[0].b->data->min_key;
	bool ret = bkey_cmp(next_pos, POS_MIN) != 0;

	if (ret)
		btree_iter_set_search_pos(iter, bkey_predecessor(next_pos));
	else
		bch2_btree_iter_set_pos(iter, POS_MIN);

	return ret;
}

/**
 * btree_iter_peek_uptodate - given an iterator that is uptodate, return the key
 * it currently points to
 */
static inline struct bkey_s_c btree_iter_peek_uptodate(struct btree_iter *iter)
{
	struct btree_iter_level *l = &iter->l[0];
	struct bkey_s_c ret = { .k = &iter->k };

	if (!bkey_deleted(&iter->k)) {
		struct bkey_packed *_k =
			__bch2_btree_node_iter_peek_all(&l->iter, l->b);

		ret.v = bkeyp_val(&l->b->format, _k);

		if (bch2_debug_check_iterators) {
			struct bkey k = bkey_unpack_key(l->b, _k);

			BUG_ON(memcmp(&k, &iter->k, sizeof(k)));
		}

		if (bch2_debug_check_bkeys)
			bch2_bkey_debugcheck(iter->trans->c, l->b, ret);
	}

	return ret;
}

/**
 * bch2_btree_iter_peek: returns first key greater than or equal to iterator's
 * current position
 */
struct bkey_s_c bch2_btree_iter_peek(struct btree_iter *iter)
{
	struct btree_iter_level *l = &iter->l[0];
	struct bkey_s_c k;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_KEYS);
	bch2_btree_iter_verify(iter);
	bch2_btree_iter_verify_entry_exit(iter);

	btree_iter_set_search_pos(iter, btree_iter_search_key(iter));

	if (iter->uptodate == BTREE_ITER_UPTODATE &&
	    !bkey_deleted(&iter->k))
		return btree_iter_peek_uptodate(iter);

	while (1) {
		ret = bch2_btree_iter_traverse(iter);
		if (unlikely(ret))
			return bkey_s_c_err(ret);

		k = __btree_iter_peek(iter, l);
		if (likely(k.k))
			break;

		if (!btree_iter_set_pos_to_next_leaf(iter))
			return bkey_s_c_null;
	}

	/*
	 * iter->pos should always be equal to the key we just
	 * returned - except extents can straddle iter->pos:
	 */
	if (bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0)
		iter->pos = bkey_start_pos(k.k);

	iter->real_pos = k.k->p;

	iter->uptodate = BTREE_ITER_UPTODATE;

	bch2_btree_iter_verify_entry_exit(iter);
	bch2_btree_iter_verify(iter);
	return k;
}

/**
 * bch2_btree_iter_next: returns first key greater than iterator's current
 * position
 */
struct bkey_s_c bch2_btree_iter_next(struct btree_iter *iter)
{
	if (!bch2_btree_iter_advance_pos(iter))
		return bkey_s_c_null;

	return bch2_btree_iter_peek(iter);
}

static struct bkey_s_c __btree_trans_updates_peek(struct btree_iter *iter)
{
	struct bpos pos = btree_iter_search_key(iter);
	struct btree_trans *trans = iter->trans;
	struct btree_insert_entry *i;

	trans_for_each_update2(trans, i)
		if ((cmp_int(iter->btree_id,	i->iter->btree_id) ?:
		     bkey_cmp(pos,		i->k->k.p)) <= 0)
			break;

	return i < trans->updates2 + trans->nr_updates2 &&
		iter->btree_id == i->iter->btree_id
		? bkey_i_to_s_c(i->k)
		: bkey_s_c_null;
}

static struct bkey_s_c __bch2_btree_iter_peek_with_updates(struct btree_iter *iter)
{
	struct btree_iter_level *l = &iter->l[0];
	struct bkey_s_c k = __btree_iter_peek(iter, l);
	struct bkey_s_c u = __btree_trans_updates_peek(iter);

	if (k.k && (!u.k || bkey_cmp(k.k->p, u.k->p) < 0))
		return k;
	if (u.k && bkey_cmp(u.k->p, l->b->key.k.p) <= 0) {
		iter->k = *u.k;
		return u;
	}
	return bkey_s_c_null;
}

struct bkey_s_c bch2_btree_iter_peek_with_updates(struct btree_iter *iter)
{
	struct bkey_s_c k;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_KEYS);
	bch2_btree_iter_verify(iter);

	while (1) {
		ret = bch2_btree_iter_traverse(iter);
		if (unlikely(ret))
			return bkey_s_c_err(ret);

		k = __bch2_btree_iter_peek_with_updates(iter);

		if (k.k && bkey_deleted(k.k)) {
			bch2_btree_iter_advance_pos(iter);
			continue;
		}

		if (likely(k.k))
			break;

		if (!btree_iter_set_pos_to_next_leaf(iter))
			return bkey_s_c_null;
	}

	/*
	 * iter->pos should be mononotically increasing, and always be equal to
	 * the key we just returned - except extents can straddle iter->pos:
	 */
	if (bkey_cmp(bkey_start_pos(k.k), iter->pos) > 0)
		iter->pos = bkey_start_pos(k.k);

	iter->uptodate = BTREE_ITER_UPTODATE;
	return k;
}

struct bkey_s_c bch2_btree_iter_next_with_updates(struct btree_iter *iter)
{
	if (!bch2_btree_iter_advance_pos(iter))
		return bkey_s_c_null;

	return bch2_btree_iter_peek_with_updates(iter);
}

/**
 * bch2_btree_iter_peek_prev: returns first key less than or equal to
 * iterator's current position
 */
struct bkey_s_c bch2_btree_iter_peek_prev(struct btree_iter *iter)
{
	struct bpos pos = iter->pos;
	struct btree_iter_level *l = &iter->l[0];
	struct bkey_s_c k;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_KEYS);
	bch2_btree_iter_verify(iter);
	bch2_btree_iter_verify_entry_exit(iter);

	btree_iter_set_search_pos(iter, iter->pos);

	if (iter->uptodate == BTREE_ITER_UPTODATE &&
	    !bkey_deleted(&iter->k))
		return btree_iter_peek_uptodate(iter);

	while (1) {
		ret = bch2_btree_iter_traverse(iter);
		if (unlikely(ret)) {
			k = bkey_s_c_err(ret);
			goto no_key;
		}

		k = __btree_iter_peek(iter, l);
		if (!k.k ||
		    ((iter->flags & BTREE_ITER_IS_EXTENTS)
		     ? bkey_cmp(bkey_start_pos(k.k), pos) >= 0
		     : bkey_cmp(bkey_start_pos(k.k), pos) > 0))
			k = __btree_iter_prev(iter, l);

		if (likely(k.k))
			break;

		if (!btree_iter_set_pos_to_prev_leaf(iter)) {
			k = bkey_s_c_null;
			goto no_key;
		}
	}

	EBUG_ON(bkey_cmp(bkey_start_pos(k.k), pos) > 0);

	/* Extents can straddle iter->pos: */
	if (bkey_cmp(k.k->p, pos) < 0)
		iter->pos = k.k->p;
	iter->real_pos = k.k->p;
	iter->uptodate = BTREE_ITER_UPTODATE;
out:
	bch2_btree_iter_verify_entry_exit(iter);
	bch2_btree_iter_verify(iter);
	return k;
no_key:
	/*
	 * __btree_iter_peek() may have set iter->k to a key we didn't want, and
	 * then we errored going to the previous leaf - make sure it's
	 * consistent with iter->pos:
	 */
	BUG_ON(bkey_cmp(pos, iter->pos) &&
	       bkey_cmp(iter->pos, POS_MIN));
	bkey_init(&iter->k);
	iter->k.p = iter->pos;
	goto out;
}

/**
 * bch2_btree_iter_prev: returns first key less than iterator's current
 * position
 */
struct bkey_s_c bch2_btree_iter_prev(struct btree_iter *iter)
{
	if (!bch2_btree_iter_rewind_pos(iter))
		return bkey_s_c_null;

	return bch2_btree_iter_peek_prev(iter);
}

static inline struct bkey_s_c
__bch2_btree_iter_peek_slot_extents(struct btree_iter *iter)
{
	struct bkey_s_c k;
	struct bpos pos, next_start;

	/* keys & holes can't span inode numbers: */
	if (iter->pos.offset == KEY_OFFSET_MAX) {
		if (iter->pos.inode == KEY_INODE_MAX)
			return bkey_s_c_null;

		bch2_btree_iter_set_pos(iter, bkey_successor(iter->pos));
	}

	pos = iter->pos;
	k = bch2_btree_iter_peek(iter);
	iter->pos = pos;

	if (bkey_err(k))
		return k;

	if (k.k && bkey_cmp(bkey_start_pos(k.k), iter->pos) <= 0)
		return k;

	next_start = k.k ? bkey_start_pos(k.k) : POS_MAX;

	bkey_init(&iter->k);
	iter->k.p = iter->pos;
	bch2_key_resize(&iter->k,
			min_t(u64, KEY_SIZE_MAX,
			      (next_start.inode == iter->pos.inode
			       ? next_start.offset
			       : KEY_OFFSET_MAX) -
			      iter->pos.offset));

	EBUG_ON(!iter->k.size);

	iter->uptodate = BTREE_ITER_UPTODATE;

	bch2_btree_iter_verify_entry_exit(iter);
	bch2_btree_iter_verify(iter);

	return (struct bkey_s_c) { &iter->k, NULL };
}

struct bkey_s_c bch2_btree_iter_peek_slot(struct btree_iter *iter)
{
	struct btree_iter_level *l = &iter->l[0];
	struct bkey_s_c k;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_KEYS);
	bch2_btree_iter_verify(iter);
	bch2_btree_iter_verify_entry_exit(iter);

	btree_iter_set_search_pos(iter, btree_iter_search_key(iter));

	if (iter->uptodate == BTREE_ITER_UPTODATE)
		return btree_iter_peek_uptodate(iter);

	if (iter->flags & BTREE_ITER_IS_EXTENTS)
		return __bch2_btree_iter_peek_slot_extents(iter);

	ret = bch2_btree_iter_traverse(iter);
	if (unlikely(ret))
		return bkey_s_c_err(ret);

	k = __btree_iter_peek_all(iter, l, &iter->k);

	EBUG_ON(k.k && bkey_deleted(k.k) && bkey_cmp(k.k->p, iter->pos) == 0);

	if (!k.k || bkey_cmp(iter->pos, k.k->p)) {
		/* hole */
		bkey_init(&iter->k);
		iter->k.p = iter->pos;
		k = (struct bkey_s_c) { &iter->k, NULL };
	}

	iter->uptodate = BTREE_ITER_UPTODATE;
	bch2_btree_iter_verify_entry_exit(iter);
	bch2_btree_iter_verify(iter);
	return k;
}

struct bkey_s_c bch2_btree_iter_next_slot(struct btree_iter *iter)
{
	if (!bch2_btree_iter_advance_pos(iter))
		return bkey_s_c_null;

	return bch2_btree_iter_peek_slot(iter);
}

struct bkey_s_c bch2_btree_iter_peek_cached(struct btree_iter *iter)
{
	struct bkey_cached *ck;
	int ret;

	EBUG_ON(btree_iter_type(iter) != BTREE_ITER_CACHED);
	bch2_btree_iter_verify(iter);

	ret = bch2_btree_iter_traverse(iter);
	if (unlikely(ret))
		return bkey_s_c_err(ret);

	ck = (void *) iter->l[0].b;

	EBUG_ON(iter->btree_id != ck->key.btree_id ||
		bkey_cmp(iter->pos, ck->key.pos));
	BUG_ON(!ck->valid);

	return bkey_i_to_s_c(ck->k);
}

static inline void bch2_btree_iter_init(struct btree_trans *trans,
			struct btree_iter *iter, enum btree_id btree_id,
			struct bpos pos, unsigned flags)
{
	struct bch_fs *c = trans->c;
	unsigned i;

	if (btree_node_type_is_extents(btree_id) &&
	    !(flags & BTREE_ITER_NODES))
		flags |= BTREE_ITER_IS_EXTENTS;

	iter->trans			= trans;
	iter->pos			= pos;
	bkey_init(&iter->k);
	iter->k.p			= pos;
	iter->flags			= flags;
	iter->real_pos			= btree_iter_search_key(iter);
	iter->uptodate			= BTREE_ITER_NEED_TRAVERSE;
	iter->btree_id			= btree_id;
	iter->level			= 0;
	iter->min_depth			= 0;
	iter->locks_want		= flags & BTREE_ITER_INTENT ? 1 : 0;
	iter->nodes_locked		= 0;
	iter->nodes_intent_locked	= 0;
	for (i = 0; i < ARRAY_SIZE(iter->l); i++)
		iter->l[i].b		= BTREE_ITER_NO_NODE_INIT;

	prefetch(c->btree_roots[btree_id].b);
}

/* new transactional stuff: */

static inline void __bch2_trans_iter_free(struct btree_trans *trans,
					  unsigned idx)
{
	__bch2_btree_iter_unlock(&trans->iters[idx]);
	trans->iters_linked		&= ~(1ULL << idx);
	trans->iters_live		&= ~(1ULL << idx);
	trans->iters_touched		&= ~(1ULL << idx);
}

int bch2_trans_iter_put(struct btree_trans *trans,
			struct btree_iter *iter)
{
	int ret;

	if (IS_ERR_OR_NULL(iter))
		return 0;

	BUG_ON(trans->iters + iter->idx != iter);

	ret = btree_iter_err(iter);

	if (!(trans->iters_touched & (1ULL << iter->idx)) &&
	    !(iter->flags & BTREE_ITER_KEEP_UNTIL_COMMIT))
		__bch2_trans_iter_free(trans, iter->idx);

	trans->iters_live	&= ~(1ULL << iter->idx);
	return ret;
}

int bch2_trans_iter_free(struct btree_trans *trans,
			 struct btree_iter *iter)
{
	if (IS_ERR_OR_NULL(iter))
		return 0;

	trans->iters_touched &= ~(1ULL << iter->idx);

	return bch2_trans_iter_put(trans, iter);
}

noinline __cold
static void btree_trans_iter_alloc_fail(struct btree_trans *trans)
{

	struct btree_iter *iter;
	struct btree_insert_entry *i;

	trans_for_each_iter(trans, iter)
		printk(KERN_ERR "iter: btree %s pos %llu:%llu%s%s%s %ps\n",
		       bch2_btree_ids[iter->btree_id],
		       iter->pos.inode,
		       iter->pos.offset,
		       (trans->iters_live & (1ULL << iter->idx)) ? " live" : "",
		       (trans->iters_touched & (1ULL << iter->idx)) ? " touched" : "",
		       iter->flags & BTREE_ITER_KEEP_UNTIL_COMMIT ? " keep" : "",
		       (void *) iter->ip_allocated);

	trans_for_each_update(trans, i) {
		char buf[300];

		bch2_bkey_val_to_text(&PBUF(buf), trans->c, bkey_i_to_s_c(i->k));
		printk(KERN_ERR "update: btree %s %s\n",
		       bch2_btree_ids[i->iter->btree_id], buf);
	}
	panic("trans iter oveflow\n");
}

static struct btree_iter *btree_trans_iter_alloc(struct btree_trans *trans)
{
	unsigned idx;

	if (unlikely(trans->iters_linked ==
		     ~((~0ULL << 1) << (BTREE_ITER_MAX - 1))))
		btree_trans_iter_alloc_fail(trans);

	idx = __ffs64(~trans->iters_linked);

	trans->iters_linked	|= 1ULL << idx;
	trans->iters[idx].idx	 = idx;
	trans->iters[idx].flags	 = 0;
	return &trans->iters[idx];
}

static inline void btree_iter_copy(struct btree_iter *dst,
				   struct btree_iter *src)
{
	unsigned i, idx = dst->idx;

	*dst = *src;
	dst->idx = idx;
	dst->flags &= ~BTREE_ITER_KEEP_UNTIL_COMMIT;

	for (i = 0; i < BTREE_MAX_DEPTH; i++)
		if (btree_node_locked(dst, i))
			six_lock_increment(&dst->l[i].b->c.lock,
					   __btree_lock_want(dst, i));

	dst->flags &= ~BTREE_ITER_KEEP_UNTIL_COMMIT;
	dst->flags &= ~BTREE_ITER_SET_POS_AFTER_COMMIT;
}

static inline struct bpos bpos_diff(struct bpos l, struct bpos r)
{
	if (bkey_cmp(l, r) > 0)
		swap(l, r);

	return POS(r.inode - l.inode, r.offset - l.offset);
}

static struct btree_iter *__btree_trans_get_iter(struct btree_trans *trans,
						 unsigned btree_id, struct bpos pos,
						 unsigned flags)
{
	struct btree_iter *iter, *best = NULL;

	trans_for_each_iter(trans, iter) {
		if (btree_iter_type(iter) != (flags & BTREE_ITER_TYPE))
			continue;

		if (iter->btree_id != btree_id)
			continue;

		if (best &&
		    bkey_cmp(bpos_diff(best->pos, pos),
			     bpos_diff(iter->real_pos, pos)) < 0)
			continue;

		best = iter;
	}

	if (!best) {
		iter = btree_trans_iter_alloc(trans);
		bch2_btree_iter_init(trans, iter, btree_id, pos, flags);
	} else if ((trans->iters_live & (1ULL << best->idx)) ||
		   (best->flags & BTREE_ITER_KEEP_UNTIL_COMMIT)) {
		iter = btree_trans_iter_alloc(trans);
		btree_iter_copy(iter, best);
	} else {
		iter = best;
	}

	iter->flags &= ~BTREE_ITER_KEEP_UNTIL_COMMIT;
	iter->flags &= ~BTREE_ITER_USER_FLAGS;
	iter->flags |= flags & BTREE_ITER_USER_FLAGS;

	if (iter->flags & BTREE_ITER_INTENT) {
		if (!iter->locks_want) {
			__bch2_btree_iter_unlock(iter);
			iter->locks_want = 1;
		}
	} else
		bch2_btree_iter_downgrade(iter);

	BUG_ON(iter->btree_id != btree_id);
	BUG_ON((iter->flags ^ flags) & BTREE_ITER_TYPE);
	BUG_ON(iter->flags & BTREE_ITER_KEEP_UNTIL_COMMIT);
	BUG_ON(iter->flags & BTREE_ITER_SET_POS_AFTER_COMMIT);
	BUG_ON(trans->iters_live & (1ULL << iter->idx));

	trans->iters_live	|= 1ULL << iter->idx;
	trans->iters_touched	|= 1ULL << iter->idx;

	return iter;
}

struct btree_iter *__bch2_trans_get_iter(struct btree_trans *trans,
					 enum btree_id btree_id,
					 struct bpos pos, unsigned flags)
{
	struct btree_iter *iter =
		__btree_trans_get_iter(trans, btree_id, pos, flags);

	__bch2_btree_iter_set_pos(iter, pos,
		btree_node_type_is_extents(btree_id));
	return iter;
}

struct btree_iter *bch2_trans_get_node_iter(struct btree_trans *trans,
					    enum btree_id btree_id,
					    struct bpos pos,
					    unsigned locks_want,
					    unsigned depth,
					    unsigned flags)
{
	struct btree_iter *iter =
		__btree_trans_get_iter(trans, btree_id, pos,
				       flags|BTREE_ITER_NODES);
	unsigned i;

	BUG_ON(bkey_cmp(iter->pos, pos));

	iter->locks_want = locks_want;
	iter->level	= depth;
	iter->min_depth	= depth;

	for (i = 0; i < ARRAY_SIZE(iter->l); i++)
		iter->l[i].b		= NULL;
	iter->l[iter->level].b		= BTREE_ITER_NO_NODE_INIT;

	return iter;
}

struct btree_iter *__bch2_trans_copy_iter(struct btree_trans *trans,
					struct btree_iter *src)
{
	struct btree_iter *iter;

	iter = btree_trans_iter_alloc(trans);
	btree_iter_copy(iter, src);

	trans->iters_live |= 1ULL << iter->idx;
	/*
	 * We don't need to preserve this iter since it's cheap to copy it
	 * again - this will cause trans_iter_put() to free it right away:
	 */
	trans->iters_touched &= ~(1ULL << iter->idx);

	return iter;
}

static int bch2_trans_preload_mem(struct btree_trans *trans, size_t size)
{
	if (size > trans->mem_bytes) {
		size_t old_bytes = trans->mem_bytes;
		size_t new_bytes = roundup_pow_of_two(size);
		void *new_mem;

		WARN_ON_ONCE(new_bytes > BTREE_TRANS_MEM_MAX);

		new_mem = krealloc(trans->mem, new_bytes, GFP_NOFS);
		if (!new_mem && new_bytes <= BTREE_TRANS_MEM_MAX) {
			new_mem = mempool_alloc(&trans->c->btree_trans_mem_pool, GFP_KERNEL);
			new_bytes = BTREE_TRANS_MEM_MAX;
			kfree(trans->mem);
		}

		if (!new_mem)
			return -ENOMEM;

		trans->mem = new_mem;
		trans->mem_bytes = new_bytes;

		if (old_bytes) {
			trace_trans_restart_mem_realloced(trans->ip, new_bytes);
			return -EINTR;
		}
	}

	return 0;
}

void *bch2_trans_kmalloc(struct btree_trans *trans, size_t size)
{
	void *p;
	int ret;

	ret = bch2_trans_preload_mem(trans, trans->mem_top + size);
	if (ret)
		return ERR_PTR(ret);

	p = trans->mem + trans->mem_top;
	trans->mem_top += size;
	return p;
}

inline void bch2_trans_unlink_iters(struct btree_trans *trans)
{
	u64 iters = trans->iters_linked &
		~trans->iters_touched &
		~trans->iters_live;

	while (iters) {
		unsigned idx = __ffs64(iters);

		iters &= ~(1ULL << idx);
		__bch2_trans_iter_free(trans, idx);
	}
}

void bch2_trans_reset(struct btree_trans *trans, unsigned flags)
{
	struct btree_iter *iter;

	trans_for_each_iter(trans, iter)
		iter->flags &= ~(BTREE_ITER_KEEP_UNTIL_COMMIT|
				 BTREE_ITER_SET_POS_AFTER_COMMIT);

	bch2_trans_unlink_iters(trans);

	trans->iters_touched &= trans->iters_live;

	trans->nr_updates		= 0;
	trans->nr_updates2		= 0;
	trans->mem_top			= 0;

	trans->extra_journal_entries	= NULL;
	trans->extra_journal_entry_u64s	= 0;

	if (trans->fs_usage_deltas) {
		trans->fs_usage_deltas->used = 0;
		memset((void *) trans->fs_usage_deltas +
		       offsetof(struct replicas_delta_list, memset_start), 0,
		       (void *) &trans->fs_usage_deltas->memset_end -
		       (void *) &trans->fs_usage_deltas->memset_start);
	}

	if (!(flags & TRANS_RESET_NOTRAVERSE))
		bch2_btree_iter_traverse_all(trans);
}

static void bch2_trans_alloc_iters(struct btree_trans *trans, struct bch_fs *c)
{
	size_t iters_bytes	= sizeof(struct btree_iter) * BTREE_ITER_MAX;
	size_t updates_bytes	= sizeof(struct btree_insert_entry) * BTREE_ITER_MAX;
	void *p = NULL;

	BUG_ON(trans->used_mempool);

#ifdef __KERNEL__
	p = this_cpu_xchg(c->btree_iters_bufs->iter, NULL);
#endif
	if (!p)
		p = mempool_alloc(&trans->c->btree_iters_pool, GFP_NOFS);

	trans->iters		= p; p += iters_bytes;
	trans->updates		= p; p += updates_bytes;
	trans->updates2		= p; p += updates_bytes;
}

void bch2_trans_init(struct btree_trans *trans, struct bch_fs *c,
		     unsigned expected_nr_iters,
		     size_t expected_mem_bytes)
{
	memset(trans, 0, sizeof(*trans));
	trans->c		= c;
	trans->ip		= _RET_IP_;

	/*
	 * reallocating iterators currently completely breaks
	 * bch2_trans_iter_put(), we always allocate the max:
	 */
	bch2_trans_alloc_iters(trans, c);

	if (expected_mem_bytes) {
		expected_mem_bytes = roundup_pow_of_two(expected_mem_bytes);
		trans->mem = kmalloc(expected_mem_bytes, GFP_KERNEL);

		if (!unlikely(trans->mem)) {
			trans->mem = mempool_alloc(&c->btree_trans_mem_pool, GFP_KERNEL);
			trans->mem_bytes = BTREE_TRANS_MEM_MAX;
		} else {
			trans->mem_bytes = expected_mem_bytes;
		}
	}

	trans->srcu_idx = srcu_read_lock(&c->btree_trans_barrier);

#ifdef CONFIG_BCACHEFS_DEBUG
	trans->pid = current->pid;
	mutex_lock(&c->btree_trans_lock);
	list_add(&trans->list, &c->btree_trans_list);
	mutex_unlock(&c->btree_trans_lock);
#endif
}

int bch2_trans_exit(struct btree_trans *trans)
{
	struct bch_fs *c = trans->c;

	bch2_trans_unlock(trans);

#ifdef CONFIG_BCACHEFS_DEBUG
	mutex_lock(&trans->c->btree_trans_lock);
	list_del(&trans->list);
	mutex_unlock(&trans->c->btree_trans_lock);
#endif

	srcu_read_unlock(&c->btree_trans_barrier, trans->srcu_idx);

	bch2_journal_preres_put(&trans->c->journal, &trans->journal_preres);

	if (trans->fs_usage_deltas) {
		if (trans->fs_usage_deltas->size + sizeof(trans->fs_usage_deltas) ==
		    REPLICAS_DELTA_LIST_MAX)
			mempool_free(trans->fs_usage_deltas,
				     &trans->c->replicas_delta_pool);
		else
			kfree(trans->fs_usage_deltas);
	}

	if (trans->mem_bytes == BTREE_TRANS_MEM_MAX)
		mempool_free(trans->mem, &trans->c->btree_trans_mem_pool);
	else
		kfree(trans->mem);

#ifdef __KERNEL__
	/*
	 * Userspace doesn't have a real percpu implementation:
	 */
	trans->iters = this_cpu_xchg(c->btree_iters_bufs->iter, trans->iters);
#endif

	if (trans->iters)
		mempool_free(trans->iters, &trans->c->btree_iters_pool);

	trans->mem	= (void *) 0x1;
	trans->iters	= (void *) 0x1;

	return trans->error ? -EIO : 0;
}

static void __maybe_unused
bch2_btree_iter_node_to_text(struct printbuf *out,
			     struct btree_bkey_cached_common *_b,
			     enum btree_iter_type type)
{
	pr_buf(out, "    %px l=%u %s:",
	       _b, _b->level, bch2_btree_ids[_b->btree_id]);
	bch2_bpos_to_text(out, btree_node_pos(_b, type));
}

void bch2_btree_trans_to_text(struct printbuf *out, struct bch_fs *c)
{
#ifdef CONFIG_BCACHEFS_DEBUG
	struct btree_trans *trans;
	struct btree_iter *iter;
	struct btree *b;
	unsigned l;

	mutex_lock(&c->btree_trans_lock);
	list_for_each_entry(trans, &c->btree_trans_list, list) {
		pr_buf(out, "%i %px %ps\n", trans->pid, trans, (void *) trans->ip);

		trans_for_each_iter(trans, iter) {
			if (!iter->nodes_locked)
				continue;

			pr_buf(out, "  iter %u %s:",
			       iter->idx,
			       bch2_btree_ids[iter->btree_id]);
			bch2_bpos_to_text(out, iter->pos);
			pr_buf(out, "\n");

			for (l = 0; l < BTREE_MAX_DEPTH; l++) {
				if (btree_node_locked(iter, l)) {
					pr_buf(out, "    %s l=%u ",
					       btree_node_intent_locked(iter, l) ? "i" : "r", l);
					bch2_btree_iter_node_to_text(out,
							(void *) iter->l[l].b,
							btree_iter_type(iter));
					pr_buf(out, "\n");
				}
			}
		}

		b = READ_ONCE(trans->locking);
		if (b) {
			pr_buf(out, "  locking iter %u l=%u %s:",
			       trans->locking_iter_idx,
			       trans->locking_level,
			       bch2_btree_ids[trans->locking_btree_id]);
			bch2_bpos_to_text(out, trans->locking_pos);


			pr_buf(out, " node ");
			bch2_btree_iter_node_to_text(out,
					(void *) b,
					btree_iter_type(&trans->iters[trans->locking_iter_idx]));
			pr_buf(out, "\n");
		}
	}
	mutex_unlock(&c->btree_trans_lock);
#endif
}

void bch2_fs_btree_iter_exit(struct bch_fs *c)
{
	mempool_exit(&c->btree_trans_mem_pool);
	mempool_exit(&c->btree_iters_pool);
	cleanup_srcu_struct(&c->btree_trans_barrier);
}

int bch2_fs_btree_iter_init(struct bch_fs *c)
{
	unsigned nr = BTREE_ITER_MAX;

	INIT_LIST_HEAD(&c->btree_trans_list);
	mutex_init(&c->btree_trans_lock);

	return  init_srcu_struct(&c->btree_trans_barrier) ?:
		mempool_init_kmalloc_pool(&c->btree_iters_pool, 1,
			sizeof(struct btree_iter) * nr +
			sizeof(struct btree_insert_entry) * nr +
			sizeof(struct btree_insert_entry) * nr) ?:
		mempool_init_kmalloc_pool(&c->btree_trans_mem_pool, 1,
					  BTREE_TRANS_MEM_MAX);
}