summaryrefslogtreecommitdiff
path: root/drivers/md/bcache/btree_update.c
blob: a54cc5aa4ed14d65b9c9e3c2c7e77208eaee12f7 (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

#include "bcache.h"
#include "alloc.h"
#include "bkey_methods.h"
#include "btree_cache.h"
#include "btree_gc.h"
#include "btree_update.h"
#include "btree_io.h"
#include "btree_iter.h"
#include "btree_locking.h"
#include "buckets.h"
#include "extents.h"
#include "journal.h"
#include "keylist.h"
#include "super.h"

#include <linux/random.h>
#include <linux/sort.h>
#include <trace/events/bcache.h>

static void async_split_updated_root(struct async_split *,
				     struct btree *);

/* Calculate ideal packed bkey format for new btree nodes: */

void __bch_btree_calc_format(struct bkey_format_state *s, struct btree *b)
{
	struct btree_node_iter iter;
	struct bkey unpacked;
	struct bkey_s_c k;

	for_each_btree_node_key_unpack(&b->keys, k, &iter, &unpacked)
		bch_bkey_format_add_key(s, k.k);
}

static struct bkey_format bch_btree_calc_format(struct btree *b)
{
	struct bkey_format_state s;

	bch_bkey_format_init(&s);
	__bch_btree_calc_format(&s, b);

	return bch_bkey_format_done(&s);
}

/**
 * btree_node_format_fits - check if we could rewrite node with a new format
 *
 * This assumes all keys can pack with the new format -- it just checks if
 * the re-packed keys would fit inside the node itself.
 */
bool bch_btree_node_format_fits(struct btree *b, struct bkey_format *new_f)
{
	struct bkey_format *old_f = &b->keys.format;

	/* stupid integer promotion rules */
	ssize_t new_u64s =
	    (((int) new_f->key_u64s - old_f->key_u64s) *
	     (int) b->keys.nr.packed_keys) +
	    (((int) new_f->key_u64s - BKEY_U64s) *
	     (int) b->keys.nr.unpacked_keys);

	bch_verify_btree_nr_keys(&b->keys);

	BUG_ON(new_u64s + b->keys.nr.live_u64s < 0);

	return __set_bytes(b->data, b->keys.nr.live_u64s + new_u64s) <
		PAGE_SIZE << b->keys.page_order;
}

/* Btree node freeing/allocation: */

/*
 * @b is going to be freed, allocate a pending_btree_node_free in @as:
 */
void bch_btree_node_free_start(struct cache_set *c,
			       struct async_split *as,
			       struct btree *b)
{
	struct pending_btree_node_free *d;

	BUG_ON(as->nr_pending >= ARRAY_SIZE(as->pending));
	d = &as->pending[as->nr_pending++];

	d->index_update_done = false;
	bkey_copy(&d->key, &b->key);

	mutex_lock(&c->btree_node_pending_free_lock);
	list_add(&d->list, &c->btree_node_pending_free);
	mutex_unlock(&c->btree_node_pending_free_lock);
}

/*
 * We're doing the index update that makes @b unreachable, update stuff to
 * reflect that:
 *
 * Must be called _before_ async_split_updated_root() or
 * async_split_updated_btree:
 */
static void bch_btree_node_free_index(struct cache_set *c, struct btree *b,
				      enum btree_id id, struct bkey_s_c k,
				      struct bucket_stats_cache_set *stats)
{
	struct pending_btree_node_free *d;

	mutex_lock(&c->btree_node_pending_free_lock);

	list_for_each_entry(d, &c->btree_node_pending_free, list)
		if (!bkey_cmp(k.k->p, d->key.k.p) &&
		    bkey_val_bytes(k.k) == bkey_val_bytes(&d->key.k) &&
		    !memcmp(k.v, &d->key.v, bkey_val_bytes(k.k)))
			goto found;

	BUG();
found:
	d->index_update_done = true;

	/*
	 * Btree nodes are accounted as freed in cache_set_stats when they're
	 * freed from the index:
	 */
	stats->sectors_meta -= c->sb.btree_node_size;

	/*
	 * We're dropping @k from the btree, but it's still live until the
	 * index update is persistent so we need to keep a reference around for
	 * mark and sweep to find - that's primarily what the
	 * btree_node_pending_free list is for.
	 *
	 * So here (when we set index_update_done = true), we're moving an
	 * existing reference to a different part of the larger "gc keyspace" -
	 * and the new position comes after the old position, since GC marks
	 * the pending free list after it walks the btree.
	 *
	 * If we move the reference while mark and sweep is _between_ the old
	 * and the new position, mark and sweep will see the reference twice
	 * and it'll get double accounted - so check for that here and subtract
	 * to cancel out one of mark and sweep's markings if necessary:
	 */

	/*
	 * bch_mark_key() compares the current gc pos to the pos we're
	 * moving this reference from, hence one comparison here:
	 */
	if (gc_pos_cmp(c->gc_pos, gc_phase(GC_PHASE_PENDING_DELETE)) < 0) {
		struct bucket_stats_cache_set tmp = { 0 };

		bch_mark_key(c, bkey_i_to_s_c(&d->key),
			     -c->sb.btree_node_size, true, b
			     ? gc_pos_btree_node(b)
			     : gc_pos_btree_root(id),
			     &tmp);
		/*
		 * Don't apply tmp - pending deletes aren't tracked in
		 * cache_set_stats:
		 */
	}

	mutex_unlock(&c->btree_node_pending_free_lock);
}

static void __btree_node_free(struct cache_set *c, struct btree *b,
			      struct btree_iter *iter)
{
	trace_bcache_btree_node_free(b);

	BUG_ON(b == btree_node_root(b));
	BUG_ON(b->ob);
	BUG_ON(!list_empty(&b->write_blocked));

	six_lock_write(&b->lock);

	if (btree_node_dirty(b))
		bch_btree_complete_write(c, b, btree_current_write(b));
	clear_btree_node_dirty(b);
	cancel_delayed_work(&b->work);

	if (!list_empty_careful(&b->journal_seq_blacklisted)) {
		mutex_lock(&c->journal.blacklist_lock);
		list_del_init(&b->journal_seq_blacklisted);
		mutex_unlock(&c->journal.blacklist_lock);
	}

	mca_hash_remove(c, b);

	mutex_lock(&c->btree_cache_lock);
	list_move(&b->list, &c->btree_cache_freeable);
	mutex_unlock(&c->btree_cache_lock);

	/*
	 * By using six_unlock_write() directly instead of
	 * btree_node_unlock_write(), we don't update the iterator's sequence
	 * numbers and cause future btree_node_relock() calls to fail:
	 */
	six_unlock_write(&b->lock);
}

void bch_btree_node_free_never_inserted(struct cache_set *c, struct btree *b)
{
	struct open_bucket *ob = b->ob;

	b->ob = NULL;

	__btree_node_free(c, b, NULL);

	bch_open_bucket_put(c, ob);
}

void bch_btree_node_free_inmem(struct btree_iter *iter, struct btree *b)
{
	bch_btree_iter_node_drop_linked(iter, b);

	__btree_node_free(iter->c, b, iter);

	bch_btree_iter_node_drop(iter, b);
}

static void bch_btree_node_free_ondisk(struct cache_set *c,
				       struct pending_btree_node_free *pending)
{
	struct bucket_stats_cache_set stats = { 0 };

	BUG_ON(!pending->index_update_done);

	mutex_lock(&c->btree_node_pending_free_lock);
	list_del(&pending->list);

	bch_mark_key(c, bkey_i_to_s_c(&pending->key),
		     -c->sb.btree_node_size, true,
		     gc_phase(GC_PHASE_PENDING_DELETE),
		     &stats);
	/*
	 * Don't apply stats - pending deletes aren't tracked in
	 * cache_set_stats:
	 */

	mutex_unlock(&c->btree_node_pending_free_lock);
}

void btree_open_bucket_put(struct cache_set *c, struct btree *b)
{
	bch_open_bucket_put(c, b->ob);
	b->ob = NULL;
}

static struct btree *__bch_btree_node_alloc(struct cache_set *c,
					    struct closure *cl)
{
	BKEY_PADDED(k) tmp;
	struct open_bucket *ob;
	struct btree *b;

	mutex_lock(&c->btree_reserve_cache_lock);
	if (c->btree_reserve_cache_nr) {
		struct btree_alloc *a =
			&c->btree_reserve_cache[--c->btree_reserve_cache_nr];

		ob = a->ob;
		bkey_copy(&tmp.k, &a->k);
		mutex_unlock(&c->btree_reserve_cache_lock);
		goto mem_alloc;
	}
	mutex_unlock(&c->btree_reserve_cache_lock);

retry:
	/* alloc_sectors is weird, I suppose */
	bkey_extent_init(&tmp.k);
	tmp.k.k.size = c->sb.btree_node_size,

	ob = bch_alloc_sectors(c, &c->btree_write_point,
			       bkey_i_to_extent(&tmp.k),
			       c->opts.metadata_replicas, cl);
	if (IS_ERR(ob))
		return ERR_CAST(ob);

	if (tmp.k.k.size < c->sb.btree_node_size) {
		bch_open_bucket_put(c, ob);
		goto retry;
	}
mem_alloc:
	b = mca_alloc(c, NULL);

	/* we hold cannibalize_lock: */
	BUG_ON(IS_ERR(b));
	BUG_ON(b->ob);

	bkey_copy(&b->key, &tmp.k);
	b->key.k.size = 0;
	b->ob = ob;

	return b;
}

static struct btree *bch_btree_node_alloc(struct cache_set *c,
					  unsigned level, enum btree_id id,
					  struct btree_reserve *reserve)
{
	struct btree *b;

	BUG_ON(!reserve->nr);

	b = reserve->b[--reserve->nr];

	BUG_ON(mca_hash_insert(c, b, level, id));

	b->accessed = 1;
	set_btree_node_dirty(b);

	bch_bset_init_first(&b->keys, &b->data->keys);
	b->data->magic = cpu_to_le64(bset_magic(&c->disk_sb));
	SET_BSET_BTREE_LEVEL(&b->data->keys, level);

	bch_check_mark_super(c, &b->key, true);

	trace_bcache_btree_node_alloc(b);
	return b;
}

struct btree *__btree_node_alloc_replacement(struct cache_set *c,
					     struct btree *b,
					     struct bkey_format format,
					     struct btree_reserve *reserve)
{
	struct btree *n;

	n = bch_btree_node_alloc(c, b->level, b->btree_id, reserve);

	n->data->min_key	= b->data->min_key;
	n->data->max_key	= b->data->max_key;
	n->data->format		= format;
	n->keys.format		= format;

	bch_btree_sort_into(&n->keys, &b->keys,
			    b->keys.ops->key_normalize,
			    &c->sort);

	n->key.k.p = b->key.k.p;
	trace_bcache_btree_node_alloc_replacement(b, n);

	return n;
}

struct btree *btree_node_alloc_replacement(struct cache_set *c,
					   struct btree *b,
					   struct btree_reserve *reserve)
{
	struct bkey_format new_f = bch_btree_calc_format(b);

	/*
	 * The keys might expand with the new format - if they wouldn't fit in
	 * the btree node anymore, use the old format for now:
	 */
	if (!bch_btree_node_format_fits(b, &new_f))
		new_f = b->keys.format;

	return __btree_node_alloc_replacement(c, b, new_f, reserve);
}

static void bch_btree_set_root_inmem(struct cache_set *c, struct btree *b,
				     struct btree_reserve *btree_reserve)
{
	struct btree *old = btree_node_root(b);

	/* Root nodes cannot be reaped */
	mutex_lock(&c->btree_cache_lock);
	list_del_init(&b->list);
	mutex_unlock(&c->btree_cache_lock);

	mutex_lock(&c->btree_root_lock);
	btree_node_root(b) = b;

	if (btree_reserve) {
		/*
		 * New allocation (we're not being called because we're in
		 * bch_btree_root_read()) - do marking while holding
		 * btree_root_lock:
		 */
		struct bucket_stats_cache_set stats = { 0 };

		bch_mark_key(c, bkey_i_to_s_c(&b->key),
			     c->sb.btree_node_size, true,
			     gc_pos_btree_root(b->btree_id),
			     &stats);

		if (old)
			bch_btree_node_free_index(c, NULL, old->btree_id,
						  bkey_i_to_s_c(&old->key),
						  &stats);
		bch_cache_set_stats_apply(c, &stats, &btree_reserve->disk_res,
					  gc_pos_btree_root(b->btree_id));
	}
	mutex_unlock(&c->btree_root_lock);

	bch_recalc_btree_reserve(c);
}

static void bch_btree_set_root_ondisk(struct cache_set *c, struct btree *b)
{
	struct btree_root *r = &c->btree_roots[b->btree_id];

	mutex_lock(&c->btree_root_lock);

	BUG_ON(b != r->b);
	bkey_copy(&r->key, &b->key);
	r->level = b->level;
	r->alive = true;

	mutex_unlock(&c->btree_root_lock);
}

/*
 * Only for cache set bringup, when first reading the btree roots or allocating
 * btree roots when initializing a new cache set:
 */
void bch_btree_set_root_initial(struct cache_set *c, struct btree *b,
				struct btree_reserve *btree_reserve)
{
	BUG_ON(btree_node_root(b));

	bch_btree_set_root_inmem(c, b, btree_reserve);
	bch_btree_set_root_ondisk(c, b);
}

/**
 * bch_btree_set_root - update the root in memory and on disk
 *
 * To ensure forward progress, the current task must not be holding any
 * btree node write locks. However, you must hold an intent lock on the
 * old root.
 *
 * Note: This allocates a journal entry but doesn't add any keys to
 * it.  All the btree roots are part of every journal write, so there
 * is nothing new to be done.  This just guarantees that there is a
 * journal write.
 */
static void bch_btree_set_root(struct btree_iter *iter, struct btree *b,
			       struct async_split *as,
			       struct btree_reserve *btree_reserve)
{
	struct cache_set *c = iter->c;
	struct btree *old;

	trace_bcache_btree_set_root(b);
	BUG_ON(!b->written);

	old = btree_node_root(b);

	/*
	 * Ensure no one is using the old root while we switch to the
	 * new root:
	 */
	btree_node_lock_write(old, iter);

	bch_btree_set_root_inmem(c, b, btree_reserve);

	async_split_updated_root(as, b);

	/*
	 * Unlock old root after new root is visible:
	 *
	 * The new root isn't persistent, but that's ok: we still have
	 * an intent lock on the new root, and any updates that would
	 * depend on the new root would have to update the new root.
	 */
	btree_node_unlock_write(old, iter);
}

static struct btree *__btree_root_alloc(struct cache_set *c, unsigned level,
					enum btree_id id,
					struct btree_reserve *reserve)
{
	struct btree *b = bch_btree_node_alloc(c, level, id, reserve);

	b->data->min_key = POS_MIN;
	b->data->max_key = POS_MAX;
	b->data->format = bch_btree_calc_format(b);
	b->key.k.p = POS_MAX;

	six_unlock_write(&b->lock);

	return b;
}

void bch_btree_reserve_put(struct cache_set *c, struct btree_reserve *reserve)
{
	bch_disk_reservation_put(c, &reserve->disk_res);

	mutex_lock(&c->btree_reserve_cache_lock);

	while (reserve->nr) {
		struct btree *b = reserve->b[--reserve->nr];

		six_unlock_write(&b->lock);

		if (c->btree_reserve_cache_nr <
		    ARRAY_SIZE(c->btree_reserve_cache)) {
			struct btree_alloc *a =
				&c->btree_reserve_cache[c->btree_reserve_cache_nr++];

			a->ob = b->ob;
			b->ob = NULL;
			bkey_copy(&a->k, &b->key);
		} else {
			bch_open_bucket_put(c, b->ob);
			b->ob = NULL;
		}

		__btree_node_free(c, b, NULL);

		six_unlock_intent(&b->lock);
	}

	mutex_unlock(&c->btree_reserve_cache_lock);

	mempool_free(reserve, &c->btree_reserve_pool);
}

static struct btree_reserve *__bch_btree_reserve_get(struct cache_set *c,
					bool check_enospc,
					unsigned nr_nodes,
					struct closure *cl)
{
	struct btree_reserve *reserve;
	struct btree *b;
	struct disk_reservation disk_res = { 0, 0 };
		unsigned sectors = nr_nodes * c->sb.btree_node_size;
	int ret;

	if (__bch_disk_reservation_get(c, &disk_res, sectors,
				       check_enospc, true))
		return ERR_PTR(-ENOSPC);

	BUG_ON(nr_nodes > BTREE_RESERVE_MAX);

	/*
	 * Protects reaping from the btree node cache and using the btree node
	 * open bucket reserve:
	 */
	ret = mca_cannibalize_lock(c, cl);
	if (ret) {
		bch_disk_reservation_put(c, &disk_res);
		return ERR_PTR(ret);
	}

	reserve = mempool_alloc(&c->btree_reserve_pool, GFP_NOIO);

	reserve->disk_res = disk_res;
	reserve->nr = 0;

	while (reserve->nr < nr_nodes) {
		b = __bch_btree_node_alloc(c, cl);
		if (IS_ERR(b)) {
			ret = PTR_ERR(b);
			goto err_free;
		}

		reserve->b[reserve->nr++] = b;
	}

	mca_cannibalize_unlock(c);
	return reserve;
err_free:
	bch_btree_reserve_put(c, reserve);
	mca_cannibalize_unlock(c);
	trace_bcache_btree_reserve_get_fail(c, nr_nodes, cl);
	return ERR_PTR(ret);
}

struct btree_reserve *bch_btree_reserve_get(struct cache_set *c,
					    struct btree *b,
					    unsigned extra_nodes,
					    bool check_enospc,
					    struct closure *cl)
{
	unsigned depth = btree_node_root(b)->level - b->level;
	unsigned nr_nodes = btree_reserve_required_nodes(depth) + extra_nodes;

	return __bch_btree_reserve_get(c, check_enospc,
				       nr_nodes, cl);

}

int bch_btree_root_alloc(struct cache_set *c, enum btree_id id,
			 struct closure *writes)
{
	struct closure cl;
	struct btree_reserve *reserve;
	struct btree *b;

	closure_init_stack(&cl);

	while (1) {
		/* XXX haven't calculated capacity yet :/ */
		reserve = __bch_btree_reserve_get(c, false, 1, &cl);
		if (!IS_ERR(reserve))
			break;

		if (PTR_ERR(reserve) == -ENOSPC)
			return PTR_ERR(reserve);

		closure_sync(&cl);
	}

	b = __btree_root_alloc(c, 0, id, reserve);

	bch_btree_node_write(b, writes, NULL);

	bch_btree_set_root_initial(c, b, reserve);
	btree_open_bucket_put(c, b);
	six_unlock_intent(&b->lock);

	bch_btree_reserve_put(c, reserve);

	return 0;
}

static bool bch_insert_fixup_btree_ptr(struct btree_iter *iter,
				       struct btree *b,
				       struct bkey_i *insert,
				       struct btree_node_iter *node_iter,
				       struct disk_reservation *disk_res)
{
	struct cache_set *c = iter->c;
	const struct bkey_format *f = &b->keys.format;
	struct bucket_stats_cache_set stats = { 0 };
	struct bkey_packed *k;
	int cmp;

	bch_btree_node_iter_verify(node_iter, &b->keys);
	EBUG_ON((k = bch_btree_node_iter_prev_all(node_iter, &b->keys)) &&
		(bkey_deleted(k)
		 ? bkey_cmp_packed(f, k, &insert->k) > 0
		 : bkey_cmp_packed(f, k, &insert->k) >= 0));

	if (bkey_extent_is_data(&insert->k))
		bch_mark_key(c, bkey_i_to_s_c(insert),
			     c->sb.btree_node_size, true,
			     gc_pos_btree_node(b), &stats);

	while ((k = bch_btree_node_iter_peek_all(node_iter, &b->keys))) {
		struct bkey tmp;
		struct bkey_s_c u = bkey_disassemble(f, k, &tmp);

		cmp = bkey_cmp(u.k->p, insert->k.p);
		if (cmp > 0)
			break;

		if (!cmp && !bkey_deleted(k)) {
			bch_btree_node_free_index(c, b, iter->btree_id,
						  u, &stats);
			/*
			 * Look up pending delete, mark so that gc marks it on
			 * the pending delete list
			 */
			k->type = KEY_TYPE_DELETED;
			btree_keys_account_key_drop(&b->keys.nr, k);
		}

		bch_btree_node_iter_advance(node_iter, &b->keys);
	}

	bch_btree_bset_insert(iter, b, node_iter, insert);
	set_btree_node_dirty(b);

	bch_cache_set_stats_apply(c, &stats, disk_res, gc_pos_btree_node(b));
	return true;
}

/* Inserting into a given leaf node (last stage of insert): */

/* Wrapper around bch_bset_insert() that fixes linked iterators: */
void bch_btree_bset_insert(struct btree_iter *iter,
			   struct btree *b,
			   struct btree_node_iter *node_iter,
			   struct bkey_i *insert)
{
	struct btree_iter *linked;
	struct bkey_packed *where;
	bool overwrote;

	EBUG_ON(bkey_deleted(&insert->k) && bkey_val_u64s(&insert->k));
	EBUG_ON(insert->k.u64s > bch_btree_keys_u64s_remaining(iter->c, b));
	EBUG_ON(bkey_cmp(bkey_start_pos(&insert->k), b->data->min_key) < 0 ||
		bkey_cmp(insert->k.p, b->data->max_key) > 0);

	/*
	 * Note: when we're called from btree_split(), @b is not in @iter - and
	 * thus we can't use the node iter in @iter either, that's why it's
	 * passed in separately. This isn't an issue for the linked iterators,
	 * though.
	 */

	where = bch_bset_insert(&b->keys, node_iter, insert, &overwrote);

	bch_btree_node_iter_fix(iter, &b->keys, node_iter, where, overwrote);

	for_each_linked_btree_node(iter, b, linked)
		bch_btree_node_iter_fix(linked, &b->keys,
					&linked->node_iters[b->level],
					where, overwrote);

	bch_btree_node_iter_verify(node_iter, &b->keys);

	for_each_linked_btree_node(iter, b, linked)
		bch_btree_node_iter_verify(&linked->node_iters[b->level],
					   &b->keys);
}

static void btree_node_flush(struct journal_entry_pin *pin)
{
	struct btree_write *w = container_of(pin, struct btree_write, journal);
	struct btree *b = container_of(w, struct btree, writes[w->index]);

	six_lock_read(&b->lock);
	__bch_btree_node_write(b, NULL, w->index);
	six_unlock_read(&b->lock);
}

/**
 * bch_btree_insert_and_journal - insert a non-overlapping key into a btree node
 *
 * This is called from bch_insert_fixup_extent() and bch_insert_fixup_key()
 *
 * The insert is journalled.
 */
void bch_btree_insert_and_journal(struct btree_iter *iter,
				  struct bkey_i *insert,
				  struct journal_res *res)
{
	struct cache_set *c = iter->c;
	struct btree *b = iter->nodes[0];
	struct btree_node_iter *node_iter = &iter->node_iters[0];

	EBUG_ON(iter->level || b->level);

	if (!btree_node_dirty(b)) {
		set_btree_node_dirty(b);

		if (c->btree_flush_delay)
			queue_delayed_work(system_freezable_wq, &b->work,
					   c->btree_flush_delay * HZ);
	}

	if (res->ref ||
	    !test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)) {
		struct btree_write *w = btree_current_write(b);

		if (!w->have_pin) {
			journal_pin_add(&c->journal,
					c->journal.cur_pin_list,
					&w->journal,
					btree_node_flush);
			w->have_pin = true;
		}
	}

	if (res->ref) {
		bch_journal_add_keys(&c->journal, res, b->btree_id,
				     insert, b->level);
		btree_bset_last(b)->journal_seq = cpu_to_le64(c->journal.seq);
	}

	bch_btree_bset_insert(iter, b, node_iter, insert);
}

static void verify_keys_sorted(struct keylist *l)
{
#ifdef CONFIG_BCACHE_DEBUG
	struct bkey_i *k;

	for (k = l->bot;
	     k < l->top && bkey_next(k) < l->top;
	     k = bkey_next(k))
		BUG_ON(bkey_cmp(k->k.p, bkey_next(k)->k.p) >= 0);
#endif
}

static void btree_node_lock_for_insert(struct btree *b, struct btree_iter *iter)
{
	struct cache_set *c = iter->c;
relock:
	btree_node_lock_write(b, iter);

	BUG_ON(&write_block(c, b)->keys < btree_bset_last(b));

	/*
	 * If the last bset has been written, initialize a new one - check after
	 * taking the write lock because it can be written with only a read
	 * lock:
	 */
	if (b->written != btree_blocks(c) &&
	    &write_block(c, b)->keys > btree_bset_last(b)) {
		btree_node_unlock_write(b, iter);
		bch_btree_init_next(c, b, iter);
		goto relock;
	}
}

/* Asynchronous interior node update machinery */

struct async_split *__bch_async_split_alloc(struct btree *nodes[],
					    unsigned nr_nodes,
					    struct btree_iter *iter)
{
	struct cache_set *c = iter->c;
	struct async_split *as;
	struct journal_entry_pin_list *pin_list = NULL;
	unsigned i, pin_idx = UINT_MAX;

	as = mempool_alloc(&c->btree_async_split_pool, GFP_NOIO);
	closure_init(&as->cl, &c->cl);
	as->c		= c;
	as->mode	= ASYNC_SPLIT_NO_UPDATE;
	as->b		= NULL;
	as->parent_as	= NULL;
	as->nr_pending	= 0;
	init_llist_head(&as->wait.list);

	bch_keylist_init(&as->parent_keys, as->inline_keys,
			 ARRAY_SIZE(as->inline_keys));

	/* block btree node from being written and write_idx changing: */
	for (i = 0; i < nr_nodes; i++) {
		/*
		 * It's not legal to call btree_node_lock_write() when @iter
		 * does not point to nodes[i] - which happens in
		 * bch_coalesce_nodes(), unfortunately.
		 *
		 * So far this is the only place where we have this issue:
		 */
		if (iter->nodes[nodes[i]->level] == nodes[i])
			btree_node_lock_write(nodes[i], iter);
		else
			six_lock_write(&nodes[i]->lock);
	}

	for (i = 0; i < nr_nodes; i++) {
		struct btree_write *w = btree_current_write(nodes[i]);

		if (w->have_pin) {
			unsigned idx = fifo_entry_idx(&c->journal.pin,
						      w->journal.pin_list);

			if (idx < pin_idx) {
				pin_list = w->journal.pin_list;
				pin_idx = idx;
			}
		}
	}

	if (!pin_list) {
		/*
		 * We don't have a journal reservation to block cur_pin_list
		 * from changing, need to use a barrier to make sure it points
		 * to an initialised pin_list:
		 */
		pin_list = c->journal.cur_pin_list;
		smp_rmb();
	}

	journal_pin_add(&c->journal, pin_list, &as->journal, NULL);

	for (i = 0; i < nr_nodes; i++) {
		if (iter->nodes[nodes[i]->level] == nodes[i])
			btree_node_unlock_write(nodes[i], iter);
		else
			six_unlock_write(&nodes[i]->lock);
	}

	return as;
}

struct async_split *bch_async_split_alloc(struct btree *b, struct btree_iter *iter)
{
	return __bch_async_split_alloc(&b, 1, iter);
}

static void async_split_free(struct closure *cl)
{
	struct async_split *as = container_of(cl, struct async_split, cl);

	mempool_free(as, &as->c->btree_async_split_pool);
}

static void async_split_pointers_written(struct closure *cl)
{
	struct async_split *as = container_of(cl, struct async_split, cl);
	struct cache_set *c = as->c;
	unsigned i;

	closure_wake_up(&as->wait);

	journal_pin_drop(&c->journal, &as->journal);

	for (i = 0; i < as->nr_pending; i++)
		bch_btree_node_free_ondisk(c, &as->pending[i]);

	closure_return_with_destructor(cl, async_split_free);
}

static void async_split_nodes_written(struct closure *cl)
{
	struct async_split *as = container_of(cl, struct async_split, cl);
	struct cache_set *c = as->c;
	struct btree *b;

	/*
	 * We did an update to a parent node where the pointers we added pointed
	 * to child nodes that weren't written yet: now, the child nodes have
	 * been written so we can write out the update to the interior node.
	 */

retry:
	mutex_lock(&c->async_split_lock);
	switch (as->mode) {
	case ASYNC_SPLIT_NO_UPDATE:
		BUG();
	case ASYNC_SPLIT_UPDATING_BTREE:
		/* The usual case: */
		b = READ_ONCE(as->b);

		if (!six_trylock_read(&b->lock)) {
			mutex_unlock(&c->async_split_lock);
			six_lock_read(&b->lock);
			six_unlock_read(&b->lock);
			goto retry;
		}

		BUG_ON(!btree_node_dirty(b));
		closure_wait(&btree_current_write(b)->wait, cl);

		list_del(&as->list);

		if (list_empty(&b->write_blocked))
			__bch_btree_node_write(b, NULL, -1);
		six_unlock_read(&b->lock);
		break;

	case ASYNC_SPLIT_UPDATING_AS:
		/*
		 * The btree node we originally updated has been freed and is
		 * being rewritten - so we need to write anything here, we just
		 * need to signal to that async_split that it's ok to make the
		 * new replacement node visible:
		 */
		closure_put(&as->parent_as->cl);

		/*
		 * and then we have to wait on that async_split to finish:
		 */
		closure_wait(&as->parent_as->wait, cl);
		break;

	case ASYNC_SPLIT_UPDATING_ROOT:
		/* b is the new btree root: */
		b = READ_ONCE(as->b);

		if (!six_trylock_read(&b->lock)) {
			mutex_unlock(&c->async_split_lock);
			six_lock_read(&b->lock);
			six_unlock_read(&b->lock);
			goto retry;
		}

		BUG_ON(c->btree_roots[b->btree_id].as != as);
		c->btree_roots[b->btree_id].as = NULL;

		bch_btree_set_root_ondisk(c, b);

		/*
		 * We don't have to wait anything anything here (before
		 * async_split_pointers_written frees the old nodes ondisk) -
		 * we've ensured that the very next journal write will have the
		 * pointer to the new root, and before the allocator can reuse
		 * the old nodes it'll have to do a journal commit:
		 */
		six_unlock_read(&b->lock);
	}
	mutex_unlock(&c->async_split_lock);

	continue_at(cl, async_split_pointers_written, system_wq);
}

/*
 * We're updating @b with pointers to nodes that haven't finished writing yet:
 * block @b from being written until @as completes
 */
static void async_split_updated_btree(struct async_split *as,
				      struct btree *b)
{
	mutex_lock(&as->c->async_split_lock);

	BUG_ON(as->mode != ASYNC_SPLIT_NO_UPDATE);
	BUG_ON(!btree_node_dirty(b));

	as->mode = ASYNC_SPLIT_UPDATING_BTREE;
	as->b = b;
	list_add(&as->list, &b->write_blocked);

	mutex_unlock(&as->c->async_split_lock);

	continue_at(&as->cl, async_split_nodes_written, system_freezable_wq);
}

static void async_split_updated_root(struct async_split *as,
				     struct btree *b)
{
	struct btree_root *r = &as->c->btree_roots[b->btree_id];

	/*
	 * XXX: if there's an outstanding async_split updating the root, we
	 * have to do the dance with the old one
	 */

	mutex_lock(&as->c->async_split_lock);

	if (r->as) {
		BUG_ON(r->as->mode != ASYNC_SPLIT_UPDATING_ROOT);

		r->as->b = NULL;
		r->as->mode = ASYNC_SPLIT_UPDATING_AS;
		r->as->parent_as = as;
		closure_get(&as->cl);
	}

	BUG_ON(as->mode != ASYNC_SPLIT_NO_UPDATE);
	as->mode = ASYNC_SPLIT_UPDATING_ROOT;
	as->b = b;
	r->as = as;

	mutex_unlock(&as->c->async_split_lock);

	continue_at(&as->cl, async_split_nodes_written, system_freezable_wq);
}

/*
 * @b is being split/rewritten: it may have pointers to not-yet-written btree
 * nodes and thus outstanding async_splits - redirect @b's async_splits to point
 * to this async_split:
 */
void bch_async_split_will_free_node(struct async_split *as, struct btree *b)
{
	mutex_lock(&as->c->async_split_lock);

	while (!list_empty(&b->write_blocked)) {
		struct async_split *p =
			list_first_entry(&b->write_blocked,
					 struct async_split, list);

		BUG_ON(p->mode != ASYNC_SPLIT_UPDATING_BTREE);

		p->mode = ASYNC_SPLIT_UPDATING_AS;
		list_del(&p->list);
		p->b = NULL;
		p->parent_as = as;
		closure_get(&as->cl);
	}

	mutex_unlock(&as->c->async_split_lock);
}

static void btree_node_interior_verify(struct btree *b)
{
	const struct bkey_format *f = &b->keys.format;
	struct btree_node_iter iter;
	struct bkey_packed *k;

	BUG_ON(!b->level);

	bch_btree_node_iter_init(&iter, &b->keys, b->key.k.p, false);
#if 1
	BUG_ON(!(k = bch_btree_node_iter_peek(&iter, &b->keys)) ||
	       bkey_cmp_left_packed(f, k, b->key.k.p));

	BUG_ON((bch_btree_node_iter_advance(&iter, &b->keys),
		!bch_btree_node_iter_end(&iter)));
#else
	const char *msg;

	msg = "not found";
	k = bch_btree_node_iter_peek(&iter, &b->keys);
	if (!k)
		goto err;

	msg = "isn't what it should be";
	if (bkey_cmp_left_packed(f, k, b->key.k.p))
		goto err;

	bch_btree_node_iter_advance(&iter, &b->keys);

	msg = "isn't last key";
	if (!bch_btree_node_iter_end(&iter))
		goto err;
	return;
err:
	bch_dump_bucket(&b->keys);
	printk(KERN_ERR "last key %llu:%llu %s\n", b->key.k.p.inode,
	       b->key.k.p.offset, msg);
	BUG();
#endif
}

static enum btree_insert_ret
bch_btree_insert_keys_interior(struct btree *b,
			       struct btree_iter *iter,
			       struct keylist *insert_keys,
			       struct async_split *as,
			       struct btree_reserve *res)
{
	struct btree_node_iter *node_iter = &iter->node_iters[b->level];
	const struct bkey_format *f = &b->keys.format;
	struct bkey_packed *k;
	bool inserted = false;

	BUG_ON(!btree_node_intent_locked(iter, btree_node_root(b)->level));
	BUG_ON(!b->level);
	BUG_ON(!as || as->b);
	verify_keys_sorted(insert_keys);

	btree_node_lock_for_insert(b, iter);

	if (bch_keylist_nkeys(insert_keys) >
	    bch_btree_keys_u64s_remaining(iter->c, b)) {
		btree_node_unlock_write(b, iter);
		return BTREE_INSERT_BTREE_NODE_FULL;
	}

	while (!bch_keylist_empty(insert_keys)) {
		struct bkey_i *insert = bch_keylist_front(insert_keys);

		/*
		 * btree_split(), btree_gc_coalesce() will insert keys before
		 * the iterator's current position - they know the keys go in
		 * the node the iterator points to:
		 */
		while ((k = bch_btree_node_iter_prev_all(node_iter, &b->keys)) &&
		       (bkey_cmp_packed(f, k, &insert->k) >= 0))
			;

		bch_insert_fixup_btree_ptr(iter, b, insert,
					   node_iter, &res->disk_res);
		inserted = true;
		bch_keylist_dequeue(insert_keys);
	}

	BUG_ON(!inserted);
	async_split_updated_btree(as, b);

	btree_node_unlock_write(b, iter);

	/*
	 * insert_fixup_btree_ptr() will advance the node iterator to _after_
	 * the last key it inserted, which is not what we want
	 */

	while ((k = bch_btree_node_iter_prev_all(node_iter, &b->keys)) &&
	       (bkey_cmp_left_packed(f, k, iter->pos) >= 0))
		;

	btree_node_interior_verify(b);
	return BTREE_INSERT_OK;
}

/*
 * Move keys from n1 (original replacement node, now lower node) to n2 (higher
 * node)
 */
static struct btree *__btree_split_node(struct btree_iter *iter, struct btree *n1,
					struct btree_reserve *reserve)
{
	size_t nr_packed = 0, nr_unpacked = 0;
	struct btree *n2;
	struct bset *set1, *set2;
	struct bkey_packed *k;

	n2 = bch_btree_node_alloc(iter->c, n1->level, iter->btree_id, reserve);
	n2->data->max_key	= n1->data->max_key;
	n2->keys.format		= n1->keys.format;
	n2->key.k.p = n1->key.k.p;

	set1 = btree_bset_first(n1);
	set2 = btree_bset_first(n2);

	/*
	 * Has to be a linear search because we don't have an auxiliary
	 * search tree yet
	 */
	k = set1->start;
	while (1) {
		if (bkey_packed(k))
			nr_packed++;
		else
			nr_unpacked++;
		if (k->_data - set1->_data >= (le16_to_cpu(set1->u64s) * 3) / 5)
			break;
		k = bkey_next(k);
	}

	n1->key.k.p = bkey_unpack_key(&n1->keys.format, k).p;
	k = bkey_next(k);

	n1->data->max_key = n1->key.k.p;
	n2->data->min_key =
		btree_type_successor(n1->btree_id, n1->key.k.p);

	set2->u64s = cpu_to_le16((u64 *) bset_bkey_last(set1) - (u64 *) k);
	set1->u64s = cpu_to_le16(le16_to_cpu(set1->u64s) - le16_to_cpu(set2->u64s));

	n2->keys.nr.live_u64s = le16_to_cpu(set2->u64s);
	n2->keys.nr.packed_keys
		= n1->keys.nr.packed_keys - nr_packed;
	n2->keys.nr.unpacked_keys
		= n1->keys.nr.unpacked_keys - nr_unpacked;

	n1->keys.nr.live_u64s = le16_to_cpu(set1->u64s);
	n1->keys.nr.packed_keys = nr_packed;
	n1->keys.nr.unpacked_keys = nr_unpacked;

	BUG_ON(!set1->u64s);
	BUG_ON(!set2->u64s);

	memcpy(set2->start,
	       bset_bkey_last(set1),
	       le16_to_cpu(set2->u64s) * sizeof(u64));

	n1->keys.set->size = 0;
	n1->keys.set->extra = BSET_TREE_NONE_VAL;
	n2->keys.set->size = 0;
	n2->keys.set->extra = BSET_TREE_NONE_VAL;

	six_unlock_write(&n2->lock);

	bch_verify_btree_nr_keys(&n1->keys);
	bch_verify_btree_nr_keys(&n2->keys);

	if (n1->level) {
		btree_node_interior_verify(n1);
		btree_node_interior_verify(n2);
	}

	return n2;
}

static void btree_split_insert_keys(struct btree_iter *iter, struct btree *b,
				    struct keylist *keys,
				    struct btree_reserve *res,
				    bool is_last)
{
	struct btree_node_iter node_iter;
	struct bkey_i *k = bch_keylist_front(keys);

	BUG_ON(!b->level);
	BUG_ON(b->keys.ops->is_extents);

	bch_btree_node_iter_init(&node_iter, &b->keys, k->k.p, false);

	six_lock_write(&b->lock);

	while (!bch_keylist_empty(keys)) {
		k = bch_keylist_front(keys);

		BUG_ON(bch_keylist_nkeys(keys) >
		       bch_btree_keys_u64s_remaining(iter->c, b));
		BUG_ON(bkey_cmp(k->k.p, b->data->min_key) < 0);

		if (bkey_cmp(k->k.p, b->key.k.p) > 0) {
			BUG_ON(is_last);
			break;
		}

		bch_insert_fixup_btree_ptr(iter, b, k, &node_iter, &res->disk_res);
		bch_keylist_dequeue(keys);
	}

	six_unlock_write(&b->lock);

	btree_node_interior_verify(b);
}

static void btree_split(struct btree *b, struct btree_iter *iter,
			struct keylist *insert_keys,
			struct btree_reserve *reserve,
			struct async_split *as)
{
	struct cache_set *c = iter->c;
	struct btree *parent = iter->nodes[b->level + 1];
	struct btree *n1, *n2 = NULL, *n3 = NULL;
	uint64_t start_time = local_clock();
	unsigned u64s_to_insert = b->level
		? bch_keylist_nkeys(insert_keys) : 0;

	BUG_ON(!parent && (b != btree_node_root(b)));
	BUG_ON(!btree_node_intent_locked(iter, btree_node_root(b)->level));

	bch_async_split_will_free_node(as, b);

	n1 = btree_node_alloc_replacement(c, b, reserve);

	/*
	 * For updates to interior nodes, we've got to do the insert
	 * before we split because the stuff we're inserting has to be
	 * inserted atomically. Post split, the keys might have to go in
	 * different nodes and the split would no longer be atomic.
	 *
	 * Worse, if the insert is from btree node coalescing, if we do the
	 * insert after we do the split (and pick the pivot) - the pivot we pick
	 * might be between nodes that were coalesced, and thus in the middle of
	 * a child node post coalescing:
	 */
	if (b->level) {
		struct bkey_packed *k;
		struct bset *i;

		six_unlock_write(&n1->lock);
		btree_split_insert_keys(iter, n1, insert_keys, reserve, true);
		six_lock_write(&n1->lock);

		/*
		 * There might be duplicate (deleted) keys after the
		 * bch_btree_insert_keys() call - we need to remove them before
		 * we split, as it would be rather bad if we picked a duplicate
		 * for the pivot.
		 *
		 * Additionally, inserting might overwrite a bunch of existing
		 * keys (i.e. a big discard when there were a bunch of small
		 * extents previously) - we might not want to split after the
		 * insert. Splitting a node that's too small to be split would
		 * be bad (if the node had only one key, we wouldn't be able to
		 * assign the new node a key different from the original node)
		 */
		i = btree_bset_first(n1);
		k = i->start;
		while (k != bset_bkey_last(i))
			if (bkey_deleted(k)) {
				i->u64s = cpu_to_le16(le16_to_cpu(i->u64s) - k->u64s);
				memmove(k, bkey_next(k),
					(void *) bset_bkey_last(i) -
					(void *) k);
			} else
				k = bkey_next(k);

		btree_node_interior_verify(n1);
	}

	if (__set_blocks(n1->data,
			 le16_to_cpu(n1->data->keys.u64s) + u64s_to_insert,
			 block_bytes(n1->c)) > btree_blocks(c) * 3 / 4) {
		trace_bcache_btree_node_split(b, le16_to_cpu(btree_bset_first(n1)->u64s));

		n2 = __btree_split_node(iter, n1, reserve);
		six_unlock_write(&n1->lock);

		bch_btree_node_write(n2, &as->cl, NULL);

		/*
		 * Note that on recursive parent_keys == insert_keys, so we
		 * can't start adding new keys to parent_keys before emptying it
		 * out (which we did with btree_split_insert_keys() above)
		 */
		bch_keylist_add(&as->parent_keys, &n1->key);
		bch_keylist_add(&as->parent_keys, &n2->key);

		if (!parent) {
			/* Depth increases, make a new root */
			n3 = __btree_root_alloc(c, b->level + 1,
						iter->btree_id,
						reserve);

			btree_split_insert_keys(iter, n3, &as->parent_keys,
						reserve, true);
			bch_btree_node_write(n3, &as->cl, NULL);
		}
	} else {
		trace_bcache_btree_node_compact(b, le16_to_cpu(btree_bset_first(n1)->u64s));
		six_unlock_write(&n1->lock);

		bch_keylist_add(&as->parent_keys, &n1->key);
	}

	bch_btree_node_write(n1, &as->cl, NULL);

	bch_btree_node_free_start(c, as, b);

	/* New nodes all written, now make them visible: */

	if (parent) {
		/* Split a non root node */
		bch_btree_insert_node(parent, iter, &as->parent_keys,
				      reserve, as);
	} else if (n3) {
		bch_btree_set_root(iter, n3, as, reserve);
	} else {
		/* Root filled up but didn't need to be split */
		bch_btree_set_root(iter, n1, as, reserve);
	}

	btree_open_bucket_put(c, n1);
	if (n2)
		btree_open_bucket_put(c, n2);
	if (n3)
		btree_open_bucket_put(c, n3);

	/*
	 * Note - at this point other linked iterators could still have @b read
	 * locked; we're depending on the bch_btree_iter_node_replace() calls
	 * below removing all references to @b so we don't return with other
	 * iterators pointing to a node they have locked that's been freed.
	 *
	 * We have to free the node first because the bch_iter_node_replace()
	 * calls will drop _our_ iterator's reference - and intent lock - to @b.
	 */
	bch_btree_node_free_inmem(iter, b);

	/* Successful split, update the iterator to point to the new nodes: */

	if (n3)
		bch_btree_iter_node_replace(iter, n3);
	if (n2)
		bch_btree_iter_node_replace(iter, n2);
	bch_btree_iter_node_replace(iter, n1);

	bch_time_stats_update(&c->btree_split_time, start_time);
}

/**
 * bch_btree_insert_node - insert bkeys into a given btree node
 *
 * @iter:		btree iterator
 * @insert_keys:	list of keys to insert
 * @hook:		insert callback
 * @persistent:		if not null, @persistent will wait on journal write
 * @flags:		BTREE_INSERT_NO_MARK_KEY
 *
 * Inserts as many keys as it can into a given btree node, splitting it if full.
 * If a split occurred, this function will return early. This can only happen
 * for leaf nodes -- inserts into interior nodes have to be atomic.
 */
void bch_btree_insert_node(struct btree *b,
			   struct btree_iter *iter,
			   struct keylist *insert_keys,
			   struct btree_reserve *reserve,
			   struct async_split *as)
{
	BUG_ON(!b->level);
	BUG_ON(!reserve || !as);

	switch (bch_btree_insert_keys_interior(b, iter, insert_keys,
					       as, reserve)) {
	case BTREE_INSERT_OK:
		break;
	case BTREE_INSERT_BTREE_NODE_FULL:
		btree_split(b, iter, insert_keys, reserve, as);
		break;
	default:
		BUG();
	}
}

static int bch_btree_split_leaf(struct btree_iter *iter, unsigned flags,
				struct closure *cl)
{
	struct btree_iter *linked;
	struct cache_set *c = iter->c;
	struct btree *b = iter->nodes[0];
	struct btree_reserve *reserve;
	struct async_split *as;
	int ret = 0;

	/* Hack, because gc and splitting nodes doesn't mix yet: */
	if (!down_read_trylock(&c->gc_lock)) {
		bch_btree_iter_unlock(iter);
		down_read(&c->gc_lock);
	}

	/*
	 * XXX: figure out how far we might need to split,
	 * instead of locking/reserving all the way to the root:
	 */
	iter->locks_want = BTREE_MAX_DEPTH;

	if (!bch_btree_iter_upgrade(iter)) {
		ret = -EINTR;
		goto out_get_locks;
	}

	reserve = bch_btree_reserve_get(c, b, 0,
					!(flags & BTREE_INSERT_NOFAIL),
					cl);
	if (IS_ERR(reserve)) {
		ret = PTR_ERR(reserve);
		goto out_get_locks;
	}

	as = bch_async_split_alloc(b, iter);

	btree_split(b, iter, NULL, reserve, as);
	bch_btree_reserve_put(c, reserve);
	iter->locks_want = 0;
out:
	up_read(&c->gc_lock);
	return ret;
out_get_locks:
	/* Lock ordering... */
	for_each_linked_btree_iter(iter, linked)
		if (btree_iter_cmp(linked, iter) <= 0)
			linked->locks_want = BTREE_MAX_DEPTH;
	goto out;
}

/**
 * btree_insert_key - insert a key one key into a leaf node
 */
static enum btree_insert_ret
btree_insert_key(struct btree_insert_trans *trans,
		 struct btree_trans_entry *insert,
		 struct disk_reservation *disk_res,
		 struct extent_insert_hook *hook,
		 struct journal_res *res,
		 unsigned flags)
{
	struct btree *b = insert->iter->nodes[0];
	s64 oldsize = bch_count_data(&b->keys);
	enum btree_insert_ret ret;

	bch_btree_node_iter_verify(&insert->iter->node_iters[0], &b->keys);

	ret = !b->keys.ops->is_extents
		? bch_insert_fixup_key(trans, insert, res)
		: bch_insert_fixup_extent(trans, insert, disk_res,
					  hook, res, flags);

	bch_count_data_verify(&b->keys, oldsize);

	trace_bcache_btree_insert_key(b, insert->k);
	return ret;
}

static bool same_leaf_as_prev(struct btree_insert_trans *trans,
			      struct btree_trans_entry *i)
{
	/*
	 * Because we sorted the transaction entries, if multiple iterators
	 * point to the same leaf node they'll always be adjacent now:
	 */
	return i != trans->entries &&
		i[0].iter->nodes[0] == i[-1].iter->nodes[0];
}

#define trans_for_each_entry(trans, i)					\
	for ((i) = (trans)->entries; (i) < (trans)->entries + (trans)->nr; (i)++)

static void multi_lock_write(struct btree_insert_trans *trans)
{
	struct btree_trans_entry *i;

	trans_for_each_entry(trans, i)
		if (!same_leaf_as_prev(trans, i))
			btree_node_lock_for_insert(i->iter->nodes[0], i->iter);
}

static void multi_unlock_write(struct btree_insert_trans *trans)
{
	struct btree_trans_entry *i;

	trans_for_each_entry(trans, i)
		if (!same_leaf_as_prev(trans, i))
			btree_node_unlock_write(i->iter->nodes[0], i->iter);
}

static int btree_trans_entry_cmp(const void *_l, const void *_r)
{
	const struct btree_trans_entry *l = _l;
	const struct btree_trans_entry *r = _r;

	return btree_iter_cmp(l->iter, r->iter);
}

/* Normal update interface: */

int bch_btree_insert_trans(struct btree_insert_trans *trans,
			   struct disk_reservation *disk_res,
			   struct extent_insert_hook *hook,
			   u64 *journal_seq, unsigned flags)
{
	struct cache_set *c = trans->entries[0].iter->c;
	struct journal_res res = { 0, 0 };
	struct btree_trans_entry *i;
	struct btree_iter *split;
	struct closure cl;
	unsigned u64s;
	int ret;

	closure_init_stack(&cl);

	trans_for_each_entry(trans, i) {
		EBUG_ON(i->iter->level);
		EBUG_ON(bkey_cmp(bkey_start_pos(&i->k->k), i->iter->pos));
		i->done = false;
	}
	trans->did_work = false;

	sort(trans->entries, trans->nr, sizeof(trans->entries[0]),
	     btree_trans_entry_cmp, NULL);

	if (unlikely(!percpu_ref_tryget(&c->writes)))
		return -EROFS;

	trans_for_each_entry(trans, i) {
		i->iter->locks_want = max_t(int, i->iter->locks_want, 0);
		if (unlikely(!bch_btree_iter_upgrade(i->iter))) {
			ret = -EINTR;
			goto err;
		}
	}
retry:
	u64s = 0;
	trans_for_each_entry(trans, i)
		if (!i->done)
			u64s += jset_u64s(i->k->k.u64s);

	ret = test_bit(JOURNAL_REPLAY_DONE, &c->journal.flags)
		? bch_journal_res_get(&c->journal, &res, u64s, u64s)
		: 0;
	if (ret)
		goto err;

	multi_lock_write(trans);

	u64s = 0;
	trans_for_each_entry(trans, i) {
		/* Multiple inserts might go to same leaf: */
		if (!same_leaf_as_prev(trans, i))
			u64s = 0;

		if (!i->done) {
			u64s += i->k->k.u64s;
			if (!bch_btree_node_insert_fits(c,
					i->iter->nodes[0], u64s))
				goto unlock_split;
		}
	}

	ret = 0;
	split = NULL;

	trans_for_each_entry(trans, i) {
		if (i->done)
			continue;

		switch (btree_insert_key(trans, i, disk_res,
					 hook, &res, flags)) {
		case BTREE_INSERT_OK:
			i->done = true;
			break;
		case BTREE_INSERT_JOURNAL_RES_FULL:
		case BTREE_INSERT_NEED_TRAVERSE:
			ret = -EINTR;
			break;
		case BTREE_INSERT_NEED_RESCHED:
			ret = -EAGAIN;
			break;
		case BTREE_INSERT_BTREE_NODE_FULL:
			split = i->iter;
			break;
		}

		if (!trans->did_work && (ret || split))
			break;
	}

	multi_unlock_write(trans);
	bch_journal_res_put(&c->journal, &res, journal_seq);

	if (split)
		goto split;
	if (ret)
		goto err;

	trans_for_each_entry(trans, i)
		if (!same_leaf_as_prev(trans, i))
			bch_btree_node_write_lazy(i->iter->nodes[0], i->iter);

	trans_for_each_entry(trans, i)
		i->iter->locks_want = 0;

out:
	percpu_ref_put(&c->writes);
	return ret;
unlock_split:
	split = i->iter;
	multi_unlock_write(trans);
	/*
	 * have to drop journal res before splitting, because splitting means
	 * allocating new btree nodes, and holding a journal reservation
	 * potentially blocks the allocator:
	 */
	bch_journal_res_put(&c->journal, &res, journal_seq);
split:
	ret = bch_btree_split_leaf(split, flags, &cl);
	if (ret)
		goto err;

	/*
	 * if the split didn't have to drop locks the insert will still be
	 * atomic (in the BTREE_INSERT_ATOMIC sense, what the caller peeked()
	 * and is overwriting won't have changed)
	 */
	goto retry;
err:
	if (ret == -EAGAIN) {
		struct btree_iter *linked;

		for_each_linked_btree_iter(split, linked)
			bch_btree_iter_unlock(linked);
		bch_btree_iter_unlock(split);

		closure_sync(&cl);
		ret = -EINTR;
	}

	/*
	 * Main rule is, BTREE_INSERT_ATOMIC means we can't call
	 * bch_btree_iter_traverse(), because if we have to we either dropped
	 * locks or we need a different btree node (different than the one the
	 * caller was looking at).
	 *
	 * BTREE_INSERT_ATOMIC doesn't mean anything w.r.t. journal
	 * reservations:
	 */
	if (ret == -EINTR && !(flags & BTREE_INSERT_ATOMIC)) {
		trans_for_each_entry(trans, i) {
			ret = bch_btree_iter_traverse(i->iter);
			if (ret)
				goto out;
		}

		ret = 0;
	}

	if (!ret)
		goto retry;

	goto out;
}

/**
 * bch_btree_insert_at - insert bkeys starting at a given btree node
 * @iter:		btree iterator
 * @insert_keys:	list of keys to insert
 * @hook:		insert callback
 * @persistent:		if not null, @persistent will wait on journal write
 * @flags:		BTREE_INSERT_ATOMIC | BTREE_INSERT_NO_MARK_KEY
 *
 * This is top level for common btree insertion/index update code. The control
 * flow goes roughly like:
 *
 * bch_btree_insert_at -- split keys that span interior nodes
 *   bch_btree_insert_node -- split btree nodes when full
 *     btree_split
 *     bch_btree_insert_keys -- get and put journal reservations
 *       btree_insert_key -- call fixup and remove key from keylist
 *         bch_insert_fixup_extent -- handle overlapping extents
 *           bch_btree_insert_and_journal -- add the key to the journal
 *             bch_bset_insert -- actually insert into the bset
 *
 * This function will split keys that span multiple nodes, calling
 * bch_btree_insert_node() for each one. It will not return until all keys
 * have been inserted, or an insert has failed.
 *
 * @persistent will only wait on the journal write if the full keylist was
 * inserted.
 *
 * Return values:
 * -EINTR: locking changed, this function should be called again. Only returned
 *  if passed BTREE_INSERT_ATOMIC.
 * -EROFS: cache set read only
 * -EIO: journal or btree node IO error
 */
int bch_btree_insert_at(struct btree_iter *iter,
			struct bkey_i *insert_key,
			struct disk_reservation *disk_res,
			struct extent_insert_hook *hook,
			u64 *journal_seq, unsigned flags)
{
	struct btree_insert_trans m = {
		.nr = 1,
		.entries = &(struct btree_trans_entry) {
			.iter = iter,
			.k = insert_key,
			.done = false,
		},
	};

	int ret = bch_btree_insert_trans(&m, disk_res,
				hook, journal_seq, flags);
	BUG_ON(!ret != m.entries[0].done);

	return ret;
}

int bch_btree_insert_list_at(struct btree_iter *iter,
			     struct keylist *keys,
			     struct disk_reservation *disk_res,
			     struct extent_insert_hook *hook,
			     u64 *journal_seq, unsigned flags)
{
	BUG_ON(flags & BTREE_INSERT_ATOMIC);
	BUG_ON(bch_keylist_empty(keys));
	verify_keys_sorted(keys);

	while (1) {
		/* need to traverse between each insert */
		int ret = bch_btree_iter_traverse(iter);
		if (ret)
			return ret;

		ret = bch_btree_insert_at(iter, bch_keylist_front(keys),
				disk_res, hook, journal_seq, flags);
		if (ret)
			return ret;

		bch_keylist_dequeue(keys);
		if (bch_keylist_empty(keys))
			return 0;
	}
}

/**
 * bch_btree_insert_check_key - insert dummy key into btree
 *
 * We insert a random key on a cache miss, then compare exchange on it
 * once the cache promotion or backing device read completes. This
 * ensures that if this key is written to after the read, the read will
 * lose and not overwrite the key with stale data.
 *
 * Return values:
 * -EAGAIN: @iter->cl was put on a waitlist waiting for btree node allocation
 * -EINTR: btree node was changed while upgrading to write lock
 */
int bch_btree_insert_check_key(struct btree_iter *iter,
			       struct bkey_i *check_key)
{
	struct bpos saved_pos = iter->pos;
	struct bkey_i_cookie *cookie;
	BKEY_PADDED(key) tmp;
	int ret;

	check_key->k.type = KEY_TYPE_COOKIE;
	set_bkey_val_bytes(&check_key->k, sizeof(struct bch_cookie));

	cookie = bkey_i_to_cookie(check_key);
	get_random_bytes(&cookie->v, sizeof(cookie->v));

	bkey_copy(&tmp.key, check_key);

	/* XXX rewind shouldn't be necessary... */
	BUG_ON(bkey_cmp(iter->pos, bkey_start_pos(&check_key->k)));

	bch_btree_iter_rewind(iter, bkey_start_pos(&check_key->k));

	ret = bch_btree_insert_at(iter, &tmp.key, NULL, NULL,
				  NULL, BTREE_INSERT_ATOMIC);

	bch_btree_iter_set_pos(iter, saved_pos);

	return ret;
}

/**
 * bch_btree_insert - insert keys into the extent btree
 * @c:			pointer to struct cache_set
 * @id:			btree to insert into
 * @insert_keys:	list of keys to insert
 * @hook:		insert callback
 */
int bch_btree_insert(struct cache_set *c, enum btree_id id,
		     struct bkey_i *k,
		     struct disk_reservation *disk_res,
		     struct extent_insert_hook *hook,
		     u64 *journal_seq, int flags)
{
	struct btree_iter iter;
	int ret, ret2;

	bch_btree_iter_init_intent(&iter, c, id, bkey_start_pos(&k->k));

	ret = bch_btree_iter_traverse(&iter);
	if (unlikely(ret))
		goto out;

	ret = bch_btree_insert_at(&iter, k, disk_res,
				  hook, journal_seq, flags);
out:	ret2 = bch_btree_iter_unlock(&iter);

	return ret ?: ret2;
}

/**
 * bch_btree_update - like bch_btree_insert(), but asserts that we're
 * overwriting an existing key
 */
int bch_btree_update(struct cache_set *c, enum btree_id id,
		     struct bkey_i *k, u64 *journal_seq)
{
	struct btree_iter iter;
	struct bkey_s_c u;
	int ret, ret2;

	EBUG_ON(id == BTREE_ID_EXTENTS);

	bch_btree_iter_init_intent(&iter, c, id, k->k.p);

	u = bch_btree_iter_peek_with_holes(&iter);

	if (!u.k || bkey_deleted(u.k))
		return -ENOENT;

	ret = bch_btree_insert_at(&iter, k, NULL, NULL, journal_seq, 0);
	ret2 = bch_btree_iter_unlock(&iter);

	return ret ?: ret2;
}

/*
 * bch_btree_delete_range - delete everything within a given range
 *
 * Range is a half open interval - [start, end)
 */
int bch_btree_delete_range(struct cache_set *c, enum btree_id id,
			   struct bpos start,
			   struct bpos end,
			   u64 version,
			   struct extent_insert_hook *hook,
			   u64 *journal_seq)
{
	struct btree_iter iter;
	struct bkey_s_c k;
	int ret = 0;

	bch_btree_iter_init_intent(&iter, c, id, start);

	while ((k = bch_btree_iter_peek(&iter)).k) {
		unsigned max_sectors = KEY_SIZE_MAX & (~0 << c->block_bits);
		/* really shouldn't be using a bare, unpadded bkey_i */
		struct bkey_i delete;

		if (bkey_cmp(iter.pos, end) >= 0)
			break;

		bkey_init(&delete.k);

		/*
		 * For extents, iter.pos won't necessarily be the same as
		 * bkey_start_pos(k.k) (for non extents they always will be the
		 * same). It's important that we delete starting from iter.pos
		 * because the range we want to delete could start in the middle
		 * of k.
		 *
		 * (bch_btree_iter_peek() does guarantee that iter.pos >=
		 * bkey_start_pos(k.k)).
		 */
		delete.k.p = iter.pos;
		delete.k.version = version;

		if (iter.nodes[0]->keys.ops->is_extents) {
			/*
			 * The extents btree is special - KEY_TYPE_DISCARD is
			 * used for deletions, not KEY_TYPE_DELETED. This is an
			 * internal implementation detail that probably
			 * shouldn't be exposed (internally, KEY_TYPE_DELETED is
			 * used as a proxy for k->size == 0):
			 */
			delete.k.type = KEY_TYPE_DISCARD;

			/* create the biggest key we can */
			bch_key_resize(&delete.k, max_sectors);
			bch_cut_back(end, &delete.k);
		}

		ret = bch_btree_insert_at(&iter, &delete, NULL, hook,
					  journal_seq, BTREE_INSERT_NOFAIL);
		if (ret)
			break;

		bch_btree_iter_cond_resched(&iter);
	}

	return bch_btree_iter_unlock(&iter) ?: ret;
}

/**
 * bch_btree_node_rewrite - Rewrite/move a btree node
 *
 * Returns 0 on success, -EINTR or -EAGAIN on failure (i.e.
 * btree_check_reserve() has to wait)
 */
int bch_btree_node_rewrite(struct btree_iter *iter, struct btree *b,
			   struct closure *cl)
{
	struct cache_set *c = iter->c;
	struct btree *n, *parent = iter->nodes[b->level + 1];
	struct btree_reserve *reserve;
	struct async_split *as;

	iter->locks_want = BTREE_MAX_DEPTH;
	if (!bch_btree_iter_upgrade(iter))
		return -EINTR;

	reserve = bch_btree_reserve_get(c, b, 1, true, cl);
	if (IS_ERR(reserve)) {
		trace_bcache_btree_gc_rewrite_node_fail(b);
		return PTR_ERR(reserve);
	}

	as = bch_async_split_alloc(b, iter);

	bch_async_split_will_free_node(as, b);

	n = btree_node_alloc_replacement(c, b, reserve);
	six_unlock_write(&n->lock);

	trace_bcache_btree_gc_rewrite_node(b);

	bch_btree_node_write(n, &as->cl, NULL);

	bch_btree_node_free_start(c, as, b);

	if (parent) {
		bch_btree_insert_node(parent, iter,
				      &keylist_single(&n->key),
				      reserve, as);
	} else {
		bch_btree_set_root(iter, n, as, reserve);
	}

	btree_open_bucket_put(c, n);

	bch_btree_node_free_inmem(iter, b);

	BUG_ON(!bch_btree_iter_node_replace(iter, n));

	bch_btree_reserve_put(c, reserve);
	return 0;
}