summaryrefslogtreecommitdiff
path: root/drivers/md/bcache/bset.c
blob: a3fc6973cf8ade374a503e037f12274717c915a7 (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
/*
 * Code for working with individual keys, and sorted sets of keys with in a
 * btree node
 *
 * Copyright 2012 Google, Inc.
 */

#define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__

#include "util.h"
#include "bset.h"

#include <asm/unaligned.h>
#include <linux/dynamic_fault.h>
#include <linux/console.h>
#include <linux/random.h>
#include <linux/prefetch.h>

static bool keys_out_of_order(struct bkey *prev, struct bkey *next,
			      bool is_extents)
{
	return bkey_cmp(prev->p, bkey_start_pos(next)) > 0 ||
		((is_extents
		  ? !bkey_deleted(next)
		  : !bkey_deleted(prev)) &&
		 !bkey_cmp(prev->p, next->p));
}

#ifdef CONFIG_BCACHE_DEBUG

void bch_dump_bset(struct btree_keys *b, struct bset *i, unsigned set)
{
	struct bkey *k, *next;
	char buf[80];

	for (k = i->start; k < bset_bkey_last(i); k = next) {
		next = bkey_next(k);

		bch_bkey_to_text(buf, sizeof(buf), k);
		printk(KERN_ERR "block %u key %u/%u: %s\n", set,
		       (unsigned) ((u64 *) k - i->_data), i->u64s, buf);

		if (next == bset_bkey_last(i))
			continue;

		if (bkey_cmp(bkey_start_pos(next), k->p) < 0)
			printk(KERN_ERR "Key skipped backwards\n");
		else if (!b->ops->is_extents &&
			 !bkey_deleted(k) &&
			 !bkey_cmp(next->p, k->p))
			printk(KERN_ERR "Duplicate keys\n");
	}
}

void bch_dump_bucket(struct btree_keys *b)
{
	unsigned i;

	console_lock();
	for (i = 0; i <= b->nsets; i++)
		bch_dump_bset(b, b->set[i].data,
			      bset_sector_offset(b, b->set[i].data));
	console_unlock();
}

s64 bch_count_data(struct btree_keys *b)
{
	struct btree_node_iter iter;
	struct bkey *k;
	u64 ret = 0;

	if (!btree_keys_expensive_checks(b))
		return -1;

	if (b->ops->is_extents)
		for_each_btree_node_key_all(b, k, &iter)
			ret += k->size;
	return ret;
}

#endif

/* Auxiliary search trees */

/* 32 bits total: */
#define BKEY_MID_BITS		5
#define BKEY_EXPONENT_BITS	8
#define BKEY_MANTISSA_BITS	(32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
#define BKEY_MANTISSA_MASK	((1 << BKEY_MANTISSA_BITS) - 1)

#define BFLOAT_FAILED		((1 << BKEY_EXPONENT_BITS) - 1)

struct bkey_float {
	unsigned	exponent:BKEY_EXPONENT_BITS;
	unsigned	m:BKEY_MID_BITS;
	unsigned	mantissa:BKEY_MANTISSA_BITS;
} __packed;

/*
 * BSET_CACHELINE was originally intended to match the hardware cacheline size -
 * it used to be 64, but I realized the lookup code would touch slightly less
 * memory if it was 128.
 *
 * It definites the number of bytes (in struct bset) per struct bkey_float in
 * the auxiliar search tree - when we're done searching the bset_float tree we
 * have this many bytes left that we do a linear search over.
 *
 * Since (after level 5) every level of the bset_tree is on a new cacheline,
 * we're touching one fewer cacheline in the bset tree in exchange for one more
 * cacheline in the linear search - but the linear search might stop before it
 * gets to the second cacheline.
 */

#define BSET_CACHELINE		128

/* Space required for the btree node keys */
static inline size_t btree_keys_bytes(struct btree_keys *b)
{
	return PAGE_SIZE << b->page_order;
}

static inline size_t btree_keys_cachelines(struct btree_keys *b)
{
	return btree_keys_bytes(b) / BSET_CACHELINE;
}

/* Space required for the auxiliary search trees */
static inline size_t bset_tree_bytes(struct btree_keys *b)
{
	return btree_keys_cachelines(b) * sizeof(struct bkey_float);
}

/* Space required for the prev pointers */
static inline size_t bset_prev_bytes(struct btree_keys *b)
{
	return btree_keys_cachelines(b) * sizeof(uint8_t);
}

/* Memory allocation */

void bch_btree_keys_free(struct btree_keys *b)
{
	struct bset_tree *t = b->set;

	if (bset_prev_bytes(b) < PAGE_SIZE)
		kfree(t->prev);
	else
		free_pages((unsigned long) t->prev,
			   get_order(bset_prev_bytes(b)));

	if (bset_tree_bytes(b) < PAGE_SIZE)
		kfree(t->tree);
	else
		free_pages((unsigned long) t->tree,
			   get_order(bset_tree_bytes(b)));

	free_pages((unsigned long) t->data, b->page_order);

	t->prev = NULL;
	t->tree = NULL;
	t->data = NULL;
}
EXPORT_SYMBOL(bch_btree_keys_free);

int bch_btree_keys_alloc(struct btree_keys *b, unsigned page_order, gfp_t gfp)
{
	struct bset_tree *t = b->set;

	BUG_ON(t->data);

	b->page_order = page_order;

	t->data = (void *) __get_free_pages(gfp, b->page_order);
	if (!t->data)
		goto err;

	t->tree = bset_tree_bytes(b) < PAGE_SIZE
		? kmalloc(bset_tree_bytes(b), gfp)
		: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
	if (!t->tree)
		goto err;

	t->prev = bset_prev_bytes(b) < PAGE_SIZE
		? kmalloc(bset_prev_bytes(b), gfp)
		: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
	if (!t->prev)
		goto err;

	return 0;
err:
	bch_btree_keys_free(b);
	return -ENOMEM;
}
EXPORT_SYMBOL(bch_btree_keys_alloc);

void bch_btree_keys_init(struct btree_keys *b, const struct btree_keys_ops *ops,
			 bool *expensive_debug_checks)
{
	unsigned i;

	b->ops			= ops;
	b->nsets		= 0;
	b->last_set_unwritten	= 0;
	b->nr_live_u64s		= 0;
#ifdef CONFIG_BCACHE_DEBUG
	b->expensive_debug_checks = expensive_debug_checks;
#endif

	/* XXX: shouldn't be needed */
	for (i = 0; i < MAX_BSETS; i++)
		b->set[i].size = 0;
	/*
	 * Second loop starts at 1 because b->keys[0]->data is the memory we
	 * allocated
	 */
	for (i = 1; i < MAX_BSETS; i++)
		b->set[i].data = NULL;
}
EXPORT_SYMBOL(bch_btree_keys_init);

/* Binary tree stuff for auxiliary search trees */

static unsigned inorder_next(unsigned j, unsigned size)
{
	if (j * 2 + 1 < size) {
		j = j * 2 + 1;

		while (j * 2 < size)
			j *= 2;
	} else
		j >>= ffz(j) + 1;

	return j;
}

static unsigned inorder_prev(unsigned j, unsigned size)
{
	if (j * 2 < size) {
		j = j * 2;

		while (j * 2 + 1 < size)
			j = j * 2 + 1;
	} else
		j >>= ffs(j);

	return j;
}

/* I have no idea why this code works... and I'm the one who wrote it
 *
 * However, I do know what it does:
 * Given a binary tree constructed in an array (i.e. how you normally implement
 * a heap), it converts a node in the tree - referenced by array index - to the
 * index it would have if you did an inorder traversal.
 *
 * Also tested for every j, size up to size somewhere around 6 million.
 *
 * The binary tree starts at array index 1, not 0
 * extra is a function of size:
 *   extra = (size - rounddown_pow_of_two(size - 1)) << 1;
 */
static inline unsigned __to_inorder(unsigned j, unsigned size, unsigned extra)
{
	unsigned b = fls(j);
	unsigned shift = fls(size - 1) - b;

	j  ^= 1U << (b - 1);
	j <<= 1;
	j  |= 1;
	j <<= shift;

	if (j > extra)
		j -= (j - extra) >> 1;

	return j;
}

static inline unsigned to_inorder(unsigned j, struct bset_tree *t)
{
	return __to_inorder(j, t->size, t->extra);
}

static unsigned __inorder_to_tree(unsigned j, unsigned size, unsigned extra)
{
	unsigned shift;

	if (j > extra)
		j += j - extra;

	shift = ffs(j);

	j >>= shift;
	j  |= roundup_pow_of_two(size) >> shift;

	return j;
}

static unsigned inorder_to_tree(unsigned j, struct bset_tree *t)
{
	return __inorder_to_tree(j, t->size, t->extra);
}

#if 0
void inorder_test(void)
{
	unsigned long done = 0;
	ktime_t start = ktime_get();

	for (unsigned size = 2;
	     size < 65536000;
	     size++) {
		unsigned extra = (size - rounddown_pow_of_two(size - 1)) << 1;
		unsigned i = 1, j = rounddown_pow_of_two(size - 1);

		if (!(size % 4096))
			printk(KERN_NOTICE "loop %u, %llu per us\n", size,
			       done / ktime_us_delta(ktime_get(), start));

		while (1) {
			if (__inorder_to_tree(i, size, extra) != j)
				panic("size %10u j %10u i %10u", size, j, i);

			if (__to_inorder(j, size, extra) != i)
				panic("size %10u j %10u i %10u", size, j, i);

			if (j == rounddown_pow_of_two(size) - 1)
				break;

			BUG_ON(inorder_prev(inorder_next(j, size), size) != j);

			j = inorder_next(j, size);
			i++;
		}

		done += size - 1;
	}
}
#endif

/*
 * Cacheline/offset <-> bkey pointer arithmetic:
 *
 * t->tree is a binary search tree in an array; each node corresponds to a key
 * in one cacheline in t->set (BSET_CACHELINE bytes).
 *
 * This means we don't have to store the full index of the key that a node in
 * the binary tree points to; to_inorder() gives us the cacheline, and then
 * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
 *
 * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
 * make this work.
 *
 * To construct the bfloat for an arbitrary key we need to know what the key
 * immediately preceding it is: we have to check if the two keys differ in the
 * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
 * of the previous key so we can walk backwards to it from t->tree[j]'s key.
 */

static struct bkey *cacheline_to_bkey(struct bset_tree *t, unsigned cacheline,
				      unsigned offset)
{
	return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
}

static unsigned bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
{
	return ((void *) k - (void *) t->data) / BSET_CACHELINE;
}

static unsigned bkey_to_cacheline_offset(struct bset_tree *t,
					 unsigned cacheline,
					 struct bkey *k)
{
	size_t m = (u64 *) k - (u64 *) cacheline_to_bkey(t, cacheline, 0);

	BUG_ON(m > (1U << BKEY_MID_BITS) - 1);
	return m;
}

static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned j)
{
	return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
}

static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned j)
{
	return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
}

/*
 * For the write set - the one we're currently inserting keys into - we don't
 * maintain a full search tree, we just keep a simple lookup table in t->prev.
 */
static struct bkey *table_to_bkey(struct bset_tree *t, unsigned cacheline)
{
	return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
}

static inline unsigned bfloat_mantissa(struct bpos pos,
				       struct bkey_float *f)
{
#ifdef __LITTLE_ENDIAN
	u64 *ptr = (u64 *) (pos.kw + (f->exponent >> 5));
#else
	u64 *ptr = (u64 *) (pos.kw - (f->exponent >> 5));
#endif
	return (get_unaligned(ptr) >> (f->exponent & 31)) &
		BKEY_MANTISSA_MASK;
}

static void make_bfloat(struct bset_tree *t, unsigned j)
{
	struct bkey_float *f = &t->tree[j];
	struct bkey *m = tree_to_bkey(t, j);
	struct bkey *p = tree_to_prev_bkey(t, j);

	struct bkey *l = is_power_of_2(j)
		? t->data->start
		: tree_to_prev_bkey(t, j >> ffs(j));

	struct bkey *r = is_power_of_2(j + 1)
		? bset_bkey_idx(t->data, t->data->u64s - t->end.u64s)
		: tree_to_bkey(t, j >> (ffz(j) + 1));

	BUG_ON(m < l || m > r);
	BUG_ON(bkey_next(p) != m);

	if (l->p.inode ^ r->p.inode)
		f->exponent = fls64(l->p.inode ^ r->p.inode) + 96;
	else if (l->p.offset ^ r->p.offset)
		f->exponent = fls64(l->p.offset ^ r->p.offset) + 32;
	else
		f->exponent = fls64(l->p.snapshot ^ r->p.snapshot);

	f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);

	/*
	 * Setting f->exponent = 127 flags this node as failed, and causes the
	 * lookup code to fall back to comparing against the original key.
	 */

	if (bfloat_mantissa(m->p, f) != bfloat_mantissa(p->p, f))
		f->mantissa = bfloat_mantissa(m->p, f) - 1;
	else
		f->exponent = BFLOAT_FAILED;
}

static void bset_alloc_tree(struct btree_keys *b, struct bset_tree *t)
{
	if (t != b->set) {
		unsigned j = roundup(t[-1].size,
				     64 / sizeof(struct bkey_float));

		t->tree = t[-1].tree + j;
		t->prev = t[-1].prev + j;
	}

	while (t < b->set + MAX_BSETS)
		t++->size = 0;
}

static void bch_bset_build_unwritten_tree(struct btree_keys *b)
{
	struct bset_tree *t = bset_tree_last(b);

	BUG_ON(b->last_set_unwritten);
	b->last_set_unwritten = 1;

	bset_alloc_tree(b, t);

	if (t->tree != b->set->tree + btree_keys_cachelines(b)) {
		t->prev[0] = bkey_to_cacheline_offset(t, 0, t->data->start);
		t->size = 1;
	}
}

void bch_bset_init_next(struct btree_keys *b, struct bset *i)
{
	memset(i, 0, sizeof(*i));

	if (i != b->set->data) {
		b->set[++b->nsets].data = i;
		i->seq = b->set->data->seq;
	} else
		get_random_bytes(&i->seq, sizeof(uint64_t));

	bch_bset_build_unwritten_tree(b);
}
EXPORT_SYMBOL(bch_bset_init_next);

void bch_bset_build_written_tree(struct btree_keys *b)
{
	struct bset_tree *t = bset_tree_last(b);
	struct bkey *prev = NULL, *k = t->data->start;
	unsigned j, cacheline = 1;

	b->last_set_unwritten = 0;

	bset_alloc_tree(b, t);

	t->size = min_t(unsigned,
			bkey_to_cacheline(t, bset_bkey_last(t->data)),
			b->set->tree + btree_keys_cachelines(b) - t->tree);
retry:
	if (t->size < 2) {
		t->size = 0;
		return;
	}

	t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;

	/* First we figure out where the first key in each cacheline is */
	for (j = inorder_next(0, t->size);
	     j;
	     j = inorder_next(j, t->size)) {
		while (bkey_to_cacheline(t, k) < cacheline)
			prev = k, k = bkey_next(k);

		if (k >= bset_bkey_last(t->data)) {
			t->size--;
			goto retry;
		}

		t->prev[j] = prev->u64s;
		t->tree[j].m = bkey_to_cacheline_offset(t, cacheline++, k);

		BUG_ON(tree_to_prev_bkey(t, j) != prev);
		BUG_ON(tree_to_bkey(t, j) != k);
	}

	while (bkey_next(k) != bset_bkey_last(t->data))
		k = bkey_next(k);

	t->end = *k;

	/* Then we build the tree */
	for (j = inorder_next(0, t->size);
	     j;
	     j = inorder_next(j, t->size))
		make_bfloat(t, j);
}
EXPORT_SYMBOL(bch_bset_build_written_tree);

struct bkey *bkey_prev(struct btree_keys *b, struct bset_tree *t,
		       struct bkey *k)
{
	struct bkey *p;
	int j;

	if (k == t->data->start)
		return NULL;

	j = min(bkey_to_cacheline(t, k), t->size);

	do {
		if (--j <= 0) {
			p = t->data->start;
			break;

		}

		p = bset_written(b, t)
			? tree_to_bkey(t, inorder_to_tree(j, t))
			: table_to_bkey(t, j);
	} while (p == k);

	while (bkey_next(p) != k)
		p = bkey_next(p);

	return p;
}

/* Insert */

static void verify_insert_pos(struct btree_keys *b,
			      struct bkey *prev,
			      struct bkey *where,
			      struct bkey *insert)
{
#ifdef CONFIG_BCACHE_DEBUG
	struct bset_tree *t = bset_tree_last(b);

	BUG_ON(prev &&
	       keys_out_of_order(prev, insert, b->ops->is_extents));

	BUG_ON(where != bset_bkey_last(t->data) &&
	       keys_out_of_order(insert, where, b->ops->is_extents));
#endif
}

/**
 * Used by extent fixup functions which insert entries into the bset.
 * We have to update the iterator's cached ->end pointer.
 *
 * @top must be in the last bset.
 */
static void bch_btree_node_iter_fix(struct btree_node_iter *iter,
				    const struct bkey *where)
{
	struct btree_node_iter_set *set;
	u64 n = where->u64s;

	BUG_ON(iter->used > MAX_BSETS);

	for (set = iter->data;
	     set < iter->data + iter->used;
	     set++)
		if (set->end >= where) {
			set->end = (struct bkey *) ((u64 *) set->end + n);

			if (set->k >= where)
				set->k = (struct bkey *) ((u64 *) set->k + n);
			break;
		}
}

/**
 * bch_bset_fix_invalidated_key() - given an existing  key @k that has been
 * modified, fix any auxiliary search tree by remaking all the nodes in the
 * auxiliary search tree that @k corresponds to
 */
void bch_bset_fix_invalidated_key(struct btree_keys *b, struct bkey *k)
{
	struct bset_tree *t;
	unsigned inorder, j = 1;

	for (t = b->set; t <= bset_tree_last(b); t++)
		if (k < bset_bkey_last(t->data))
			goto found_set;

	BUG();
found_set:
	if (!t->size || !bset_written(b, t))
		return;

	inorder = bkey_to_cacheline(t, k);

	if (k == t->data->start)
		for (j = 1; j < t->size; j = j * 2)
			make_bfloat(t, j);

	if (bkey_next(k) == bset_bkey_last(t->data)) {
		t->end = *k;

		for (j = 1; j < t->size; j = j * 2 + 1)
			make_bfloat(t, j);
	}

	j = inorder_to_tree(inorder, t);

	if (j &&
	    j < t->size &&
	    k == tree_to_bkey(t, j)) {
		/* Fix the auxiliary search tree node this key corresponds to */
		make_bfloat(t, j);

		/* Children for which this key is the right side boundary */
		for (j = j * 2; j < t->size; j = j * 2 + 1)
			make_bfloat(t, j);
	}

	j = inorder_to_tree(inorder + 1, t);

	if (j &&
	    j < t->size &&
	    k == tree_to_prev_bkey(t, j)) {
		make_bfloat(t, j);

		/* Children for which this key is the left side boundary */
		for (j = j * 2 + 1; j < t->size; j = j * 2)
			make_bfloat(t, j);
	}
}
EXPORT_SYMBOL(bch_bset_fix_invalidated_key);

static void bch_bset_fix_lookup_table(struct btree_keys *b,
				      struct bset_tree *t,
				      struct bkey *k)
{
	unsigned shift = k->u64s;
	unsigned j = bkey_to_cacheline(t, k);

	/* We're getting called from btree_split() or btree_gc, just bail out */
	if (!t->size)
		return;

	/* k is the key we just inserted; we need to find the entry in the
	 * lookup table for the first key that is strictly greater than k:
	 * it's either k's cacheline or the next one
	 */
	while (j < t->size &&
	       table_to_bkey(t, j) <= k)
		j++;

	/* Adjust all the lookup table entries, and find a new key for any that
	 * have gotten too big
	 */
	for (; j < t->size; j++) {
		t->prev[j] += shift;

		if (t->prev[j] > 7) {
			k = table_to_bkey(t, j - 1);

			while (k < cacheline_to_bkey(t, j, 0))
				k = bkey_next(k);

			t->prev[j] = bkey_to_cacheline_offset(t, j, k);
		}
	}

	if (t->size == b->set->tree + btree_keys_cachelines(b) - t->tree)
		return;

	/* Possibly add a new entry to the end of the lookup table */

	for (k = table_to_bkey(t, t->size - 1);
	     k != bset_bkey_last(t->data);
	     k = bkey_next(k))
		if (t->size == bkey_to_cacheline(t, k)) {
			t->prev[t->size] = bkey_to_cacheline_offset(t, t->size, k);
			t->size++;
		}
}

void bch_bset_insert(struct btree_keys *b,
		     struct btree_node_iter *iter,
		     struct bkey *insert)
{
	struct bset_tree *t = bset_tree_last(b);
	struct bset *i = t->data;
	struct bkey *prev = NULL;
	struct bkey *where = bch_btree_node_iter_bset_pos(iter, i) ?:
		bset_bkey_last(i);
	BKEY_PADDED(k) tmp;

	BUG_ON(insert->u64s > bch_btree_keys_u64s_remaining(b));
	BUG_ON(b->ops->is_extents &&
	       (!insert->size || bkey_deleted(insert)));
	BUG_ON(!b->last_set_unwritten);
	BUG_ON(where < i->start);
	BUG_ON(where > bset_bkey_last(i));

	while (where != bset_bkey_last(i) &&
	       keys_out_of_order(insert, where, b->ops->is_extents))
		prev = where, where = bkey_next(where);

	if (!prev)
		prev = bkey_prev(b, t, where);

	verify_insert_pos(b, prev, where, insert);

	/* prev is in the tree, if we merge we're done */
	if (prev &&
	    bch_bkey_try_merge_inline(b, iter, prev, insert))
		return;

	if (where != bset_bkey_last(i) &&
	    b->ops->is_extents &&
	    where->u64s == insert->u64s && !where->size) {
		if (!bkey_deleted(insert))
			b->nr_live_u64s += insert->u64s;

		bkey_copy(where, insert);

		/*
		 * We're modifying a key that might be the btree node iter's
		 * current position for that bset, so we have to resort it -
		 * this isn't an issue for back merges because then the insert
		 * key comes after the key being modified, so the iter will have
		 * advanced past it.
		 */
		bch_btree_node_iter_sort(iter);
		return;
	}

	if (where != bset_bkey_last(i) &&
	    bkey_bytes(insert) <= sizeof(tmp)) {
		bkey_copy(&tmp.k, insert);
		insert = &tmp.k;

		/*
		 * bch_bkey_try_merge() modifies the left argument, but we can't
		 * modify insert since the caller needs to be able to journal
		 * the key that was actually inserted (and it can't just pass us
		 * a copy of insert, since ->insert_fixup() might trim insert if
		 * this is a replace operation)
		 */
		if (bch_bkey_try_merge_inline(b, iter, insert, where)) {
			bkey_copy(where, insert);
			return;
		}
	}

	memmove((uint64_t *) where + insert->u64s,
		where,
		(void *) bset_bkey_last(i) - (void *) where);

	bkey_copy(where, insert);
	i->u64s += insert->u64s;

	if (!bkey_deleted(insert))
		b->nr_live_u64s += insert->u64s;

	bch_bset_fix_lookup_table(b, t, where);
	bch_btree_node_iter_fix(iter, where);

	bch_btree_node_iter_verify(b, iter);
}
EXPORT_SYMBOL(bch_bset_insert);

/* Lookup */

__attribute__((flatten))
static struct bkey *bset_search_write_set(struct bset_tree *t,
					  struct bpos search)
{
	unsigned li = 0, ri = t->size;

	while (li + 1 != ri) {
		unsigned m = (li + ri) >> 1;

		if (bkey_cmp(table_to_bkey(t, m)->p, search) >= 0)
			ri = m;
		else
			li = m;
	}

	return table_to_bkey(t, li);
}

__attribute__((flatten))
static struct bkey *bset_search_tree(struct bset_tree *t,
				     struct bpos search)
{
	struct bkey_float *f = &t->tree[1];
	unsigned inorder, n = 1;

	/* don't ask. */
	if (!search.snapshot-- &&
	    !search.offset-- &&
	    !search.inode--)
		BUG();

	while (1) {
		if (likely(n << 4 < t->size)) {
			prefetch(&t->tree[n << 4]);
		} else if (n << 3 < t->size) {
			inorder = to_inorder(n, t);
			prefetch(cacheline_to_bkey(t, inorder, 0));
			prefetch(cacheline_to_bkey(t, inorder + 1, 0));
			prefetch(cacheline_to_bkey(t, inorder + 2, 0));
			prefetch(cacheline_to_bkey(t, inorder + 3, 0));
		} else if (n >= t->size)
			break;

		f = &t->tree[n];

		/*
		 * n = (f->mantissa > bfloat_mantissa())
		 *	? n * 2
		 *	: n * 2 + 1;
		 *
		 * We need to subtract 1 from f->mantissa for the sign bit trick
		 * to work  - that's done in make_bfloat()
		 */
		if (likely(f->exponent != BFLOAT_FAILED))
			n = n * 2 + (((unsigned)
				      (f->mantissa -
				       bfloat_mantissa(search, f))) >> 31);
		else
			n = (bkey_cmp(tree_to_bkey(t, n)->p, search) > 0)
				? n * 2
				: n * 2 + 1;
	}

	inorder = to_inorder(n >> 1, t);

	/*
	 * n would have been the node we recursed to - the low bit tells us if
	 * we recursed left or recursed right.
	 */
	if (n & 1) {
		return cacheline_to_bkey(t, inorder, f->m);
	} else {
		if (--inorder) {
			f = &t->tree[inorder_prev(n >> 1, t->size)];
			return cacheline_to_bkey(t, inorder, f->m);
		} else
			return t->data->start;
	}
}

/*
 * Returns the first key greater than or equal to @search
 */
__always_inline
static struct bkey *bch_bset_search(struct btree_keys *b, struct bset_tree *t,
				    struct bpos search)
{
	struct bkey *m;

	/*
	 * First, we search for a cacheline, then lastly we do a linear search
	 * within that cacheline.
	 *
	 * To search for the cacheline, there's three different possibilities:
	 *  * The set is too small to have a search tree, so we just do a linear
	 *    search over the whole set.
	 *  * The set is the one we're currently inserting into; keeping a full
	 *    auxiliary search tree up to date would be too expensive, so we
	 *    use a much simpler lookup table to do a binary search -
	 *    bset_search_write_set().
	 *  * Or we use the auxiliary search tree we constructed earlier -
	 *    bset_search_tree()
	 */

	if (unlikely(!t->size)) {
		m = t->data->start;
	} else if (bset_written(b, t)) {
		/*
		 * Each node in the auxiliary search tree covers a certain range
		 * of bits, and keys above and below the set it covers might
		 * differ outside those bits - so we have to special case the
		 * start and end - handle that here:
		 */

		if (unlikely(bkey_cmp(search, t->end.p) > 0))
			return bset_bkey_last(t->data);

		if (unlikely(bkey_cmp(search, t->data->start->p) <= 0))
			return t->data->start;

		m = bset_search_tree(t, search);
	} else {
		EBUG_ON(!b->nsets &&
			t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));

		m = bset_search_write_set(t, search);
	}

	while (m != bset_bkey_last(t->data) &&
	       bkey_cmp(m->p, search) < 0)
		m = bkey_next(m);

	if (btree_keys_expensive_checks(b)) {
		struct bkey *p = bkey_prev(b, t, m);

		BUG_ON(p && bkey_cmp(p->p, search) >= 0);
	}

	return m;
}

/* Btree node iterator */

static inline bool btree_node_iter_cmp(struct btree_node_iter *iter,
				       struct btree_node_iter_set l,
				       struct btree_node_iter_set r)
{
	s64 c = bkey_cmp(l.k->p, r.k->p);

	/*
	 * For non extents, when keys compare equal the deleted keys have to
	 * come first - so that bch_btree_node_iter_next_check() can detect
	 * duplicate nondeleted keys (and possibly other reasons?)
	 *
	 * For extents, bkey_deleted() is used as a proxy for k->size == 0, so
	 * deleted keys have to sort last.
	 */
	return c ? c > 0
		: iter->is_extents
		? bkey_deleted(l.k) > bkey_deleted(r.k)
		: bkey_deleted(l.k) < bkey_deleted(r.k);
}

void bch_btree_node_iter_push(struct btree_node_iter *iter,
			      struct bkey *k, struct bkey *end)
{
	if (k != end) {
		struct btree_node_iter_set n =
			((struct btree_node_iter_set) { k, end });
		unsigned i;

		for (i = 0;
		     i < iter->used &&
		     btree_node_iter_cmp(iter, n, iter->data[i]);
		     i++)
			;

		BUG_ON(iter->used >= iter->size);
		memmove(&iter->data[i + 1],
			&iter->data[i],
			(iter->used - i) * sizeof(struct btree_node_iter_set));
		iter->used++;
		iter->data[i] = n;
	}
}

static void __bch_btree_node_iter_init(struct btree_keys *b,
				       struct btree_node_iter *iter,
				       struct bset_tree *start)
{
	iter->size = ARRAY_SIZE(iter->data);
	iter->used = 0;
	iter->is_extents = b->ops->is_extents;

#ifdef CONFIG_BCACHE_DEBUG
	iter->b = b;
#endif
}

void bch_btree_node_iter_init(struct btree_keys *b,
			      struct btree_node_iter *iter,
			      struct bpos search)
{
	struct bset_tree *t;

	__bch_btree_node_iter_init(b, iter, b->set);

	for (t = b->set; t <= b->set + b->nsets; t++)
		bch_btree_node_iter_push(iter,
					 bch_bset_search(b, t, search),
					 bset_bkey_last(t->data));
}
EXPORT_SYMBOL(bch_btree_node_iter_init);

void bch_btree_node_iter_init_from_start(struct btree_keys *b,
					 struct btree_node_iter *iter)
{
	struct bset_tree *t;

	__bch_btree_node_iter_init(b, iter, b->set);

	for (t = b->set; t <= b->set + b->nsets; t++)
		bch_btree_node_iter_push(iter,
					 t->data->start,
					 bset_bkey_last(t->data));
}
EXPORT_SYMBOL(bch_btree_node_iter_init_from_start);

struct bkey *bch_btree_node_iter_bset_pos(struct btree_node_iter *iter,
					  struct bset *i)
{
	struct btree_node_iter_set *set;

	BUG_ON(iter->used > MAX_BSETS);

	for (set = iter->data;
	     set < iter->data + iter->used;
	     set++)
		if (bset_bkey_last(i) == set->end)
			return set->k;

	return NULL;
}

static inline void btree_node_iter_sift(struct btree_node_iter *iter, unsigned start)
{
	unsigned i;

	BUG_ON(iter->used > MAX_BSETS);

	for (i = start;
	     i + 1 < iter->used &&
	     btree_node_iter_cmp(iter, iter->data[i], iter->data[i + 1]);
	     i++)
		swap(iter->data[i], iter->data[i + 1]);
}

void bch_btree_node_iter_sort(struct btree_node_iter *iter)
{
	int i;

	BUG_ON(iter->used > MAX_BSETS);

	for (i = iter->used - 1; i >= 0; --i)
		btree_node_iter_sift(iter, i);
}
EXPORT_SYMBOL(bch_btree_node_iter_sort);

/**
 * bch_btree_node_iter_advance - advance @iter by one key
 *
 * Doesn't do debugchecks - for cases where (insert_fixup_extent()) a bset might
 * momentarily have out of order extents.
 */
void bch_btree_node_iter_advance(struct btree_node_iter *iter)
{
	iter->data->k = bkey_next(iter->data->k);

	BUG_ON(iter->data->k > iter->data->end);

	if (iter->data->k == iter->data->end) {
		BUG_ON(iter->used == 0);
		iter->data[0] = iter->data[--iter->used];
	}

	btree_node_iter_sift(iter, 0);
}
EXPORT_SYMBOL(bch_btree_node_iter_advance);

#ifdef CONFIG_BCACHE_DEBUG
void bch_btree_node_iter_verify(struct btree_keys *b,
				struct btree_node_iter *iter)
{
	struct btree_node_iter_set *set;
	struct bset_tree *t;

	BUG_ON(iter->used > MAX_BSETS);

	for (set = iter->data;
	     set < iter->data + iter->used;
	     set++) {
		BUG_ON(set + 1 < iter->data + iter->used &&
		       btree_node_iter_cmp(iter, set[0], set[1]));

		for (t =  b->set;
		     t <= b->set + b->nsets;
		     t++)
			if (set->end == bset_bkey_last(t->data))
				goto next;
		BUG();
next:
		;
	}
}

static void bch_btree_node_iter_next_check(struct btree_node_iter *iter,
					   struct bkey *k)
{
	if (!bch_btree_node_iter_end(iter) &&
	    keys_out_of_order(k, iter->data->k, iter->is_extents)) {
		char buf1[80], buf2[80];

		bch_dump_bucket(iter->b);
		bch_bkey_to_text(buf1, sizeof(buf1), k);
		bch_bkey_to_text(buf2, sizeof(buf2), iter->data->k);
		panic("out of order/overlapping:\n%s\n%s\n", buf1, buf2);
	}
}

struct bkey *bch_btree_node_iter_next_all(struct btree_node_iter *iter)
{
	struct bkey *ret = bch_btree_node_iter_peek_all(iter);

	if (ret) {
		bch_btree_node_iter_advance(iter);
		bch_btree_node_iter_next_check(iter, ret);
	}

	return ret;
}
EXPORT_SYMBOL(bch_btree_node_iter_next_all);
#endif

/* Mergesort */

/**
 * btree_count_keys - count live keys in a btree node
 */
size_t bch_btree_count_u64s(struct btree_keys *b)
{
	struct bkey *k;
	struct btree_node_iter iter;
	size_t ret = 0;

	for_each_btree_node_key(b, k, &iter)
		ret += k->u64s;

	return ret;
}

void bch_bset_sort_state_free(struct bset_sort_state *state)
{
	if (state->pool)
		mempool_destroy(state->pool);
}
EXPORT_SYMBOL(bch_bset_sort_state_free);

int bch_bset_sort_state_init(struct bset_sort_state *state, unsigned page_order)
{
	spin_lock_init(&state->time.lock);

	state->page_order = page_order;
	state->crit_factor = int_sqrt(1 << page_order);

	state->pool = mempool_create_page_pool(1, page_order);
	if (!state->pool)
		return -ENOMEM;

	return 0;
}
EXPORT_SYMBOL(bch_bset_sort_state_init);

static void btree_mergesort(struct btree_keys *b, struct bset *bset,
			    struct btree_node_iter *iter,
			    ptr_filter_fn filter, bool merge)
{
	struct bkey *k, *prev = NULL, *out = bset->start;

	while (!bch_btree_node_iter_end(iter)) {
		k = bch_btree_node_iter_next_all(iter);

		bkey_copy(out, k);

		if (filter && filter(b, out))
			continue;

		if (bkey_deleted(out))
			continue;

		if (merge && prev && bch_bkey_try_merge(b, prev, out))
			continue;

		prev = out;
		out = bkey_next(out);
	}

	bset->u64s = (u64 *) out - bset->_data;

	pr_debug("sorted %i keys", bset->u64s);
}

static void __btree_sort(struct btree_keys *b, struct btree_node_iter *iter,
			 unsigned start, unsigned order,
			 ptr_filter_fn filter, btree_keys_sort_fn sort,
			 struct bset_sort_state *state)
{
	uint64_t start_time;
	bool used_mempool = false;
	struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOWAIT,
						     order);
	if (!out) {
		struct page *outp;

		BUG_ON(order > state->page_order);

		outp = mempool_alloc(state->pool, GFP_NOIO);
		out = page_address(outp);
		used_mempool = true;
		order = state->page_order;
	}

	start_time = local_clock();

	/*
	 * If we're only doing a partial sort (start != 0), then we can't merge
	 * extents because that might produce extents that overlap with 0 size
	 * extents in bsets we aren't sorting:
	 */
	if (!sort)
		btree_mergesort(b, out, iter, filter, !start);
	else
		sort(b, out, iter);

	b->nsets = start;

	if (!start && order == b->page_order) {
		/*
		 * Our temporary buffer is the same size as the btree node's
		 * buffer, we can just swap buffers instead of doing a big
		 * memcpy()
		 */

		out->magic	= b->set->data->magic;
		out->seq	= b->set->data->seq;
		out->version	= b->set->data->version;
		swap(out, b->set->data);
	} else {
		b->set[start].data->u64s = out->u64s;
		memcpy(b->set[start].data->start, out->start,
		       (void *) bset_bkey_last(out) - (void *) out->start);
	}

	if (used_mempool)
		mempool_free(virt_to_page(out), state->pool);
	else
		free_pages((unsigned long) out, order);

	bch_bset_build_written_tree(b);

	/* sort can merge keys - need to recalculate */
	b->nr_live_u64s = start
		? bch_btree_count_u64s(b)
		: b->set->data->u64s;

	verify_nr_live_u64s(b);

	if (!start)
		bch_time_stats_update(&state->time, start_time);
}

void bch_btree_sort_partial(struct btree_keys *b, unsigned start,
			    ptr_filter_fn filter,
			    struct bset_sort_state *state)
{
	size_t order = b->page_order, u64s = 0;
	struct btree_node_iter iter;
	struct bset_tree *t;

	__bch_btree_node_iter_init(b, &iter, &b->set[start]);

	for (t = b->set + start; t <= b->set + b->nsets; t++)
		bch_btree_node_iter_push(&iter,
					 t->data->start,
					 bset_bkey_last(t->data));

	if (start) {
		for (t = b->set + start; t <= b->set + b->nsets; t++)
			u64s += t->data->u64s;

		order = get_order(__set_bytes(b->set->data, u64s));
	}

	__btree_sort(b, &iter, start, order, filter, false, state);
}
EXPORT_SYMBOL(bch_btree_sort_partial);

void bch_btree_sort_and_fix_extents(struct btree_keys *b,
				    struct btree_node_iter *iter,
				    btree_keys_sort_fn sort,
				    struct bset_sort_state *state)
{
	BUG_ON(!sort);
	__btree_sort(b, iter, 0, b->page_order, NULL, sort, state);
}

/**
 * bch_btree_sort_into - sort with a specified output, instead of allocating
 * temporary space
 *
 * does not create the auxiliary search tree
 */
void bch_btree_sort_into(struct btree_keys *dst,
			 struct btree_keys *src,
			 ptr_filter_fn filter,
			 struct bset_sort_state *state)
{
	uint64_t start_time = local_clock();

	struct btree_node_iter iter;
	bch_btree_node_iter_init_from_start(src, &iter);

	btree_mergesort(src, dst->set->data, &iter, filter, true);

	bch_time_stats_update(&state->time, start_time);

	dst->nr_live_u64s = dst->set->data->u64s;
	dst->nsets = 0;
	/* No auxiliary search tree yet */
	dst->set->size = 0;
}

#define SORT_CRIT	(4096 / sizeof(uint64_t))

void bch_btree_sort_lazy(struct btree_keys *b,
			 ptr_filter_fn filter,
			 struct bset_sort_state *state)
{
	unsigned crit = SORT_CRIT;
	int i;

	/* Don't sort if nothing to do */
	if (!b->nsets)
		goto out;

	for (i = b->nsets - 1; i >= 0; --i) {
		crit *= state->crit_factor;

		if (b->set[i].data->u64s < crit) {
			bch_btree_sort_partial(b, i, filter, state);
			return;
		}
	}

	/* Sort if we'd overflow */
	if (b->nsets + 1 == MAX_BSETS) {
		bch_btree_sort(b, filter, state);
		return;
	}

out:
	bch_bset_build_written_tree(b);
}
EXPORT_SYMBOL(bch_btree_sort_lazy);

void bch_btree_keys_stats(struct btree_keys *b, struct bset_stats *stats)
{
	unsigned i;

	for (i = 0; i <= b->nsets; i++) {
		struct bset_tree *t = &b->set[i];
		size_t bytes = t->data->u64s * sizeof(u64);
		size_t j;

		if (bset_written(b, t)) {
			stats->sets_written++;
			stats->bytes_written += bytes;

			if (t->size)
				stats->floats += t->size - 1;

			for (j = 1; j < t->size; j++)
				if (t->tree[j].exponent == BFLOAT_FAILED)
					stats->failed++;
		} else {
			stats->sets_unwritten++;
			stats->bytes_unwritten += bytes;
		}
	}
}