summaryrefslogtreecommitdiffstats
path: root/drivers/md/dm-vdo/indexer/volume.c
blob: 2d8901732f5d19d63704c6a9e87b58b01fe03115 (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
// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright 2023 Red Hat
 */

#include "volume.h"

#include <linux/atomic.h>
#include <linux/dm-bufio.h>
#include <linux/err.h>

#include "errors.h"
#include "logger.h"
#include "memory-alloc.h"
#include "permassert.h"
#include "string-utils.h"
#include "thread-utils.h"

#include "chapter-index.h"
#include "config.h"
#include "geometry.h"
#include "hash-utils.h"
#include "index.h"
#include "sparse-cache.h"

/*
 * The first block of the volume layout is reserved for the volume header, which is no longer used.
 * The remainder of the volume is divided into chapters consisting of several pages of records, and
 * several pages of static index to use to find those records. The index pages are recorded first,
 * followed by the record pages. The chapters are written in order as they are filled, so the
 * volume storage acts as a circular log of the most recent chapters, with each new chapter
 * overwriting the oldest saved one.
 *
 * When a new chapter is filled and closed, the records from that chapter are sorted and
 * interleaved in approximate temporal order, and assigned to record pages. Then a static delta
 * index is generated to store which record page contains each record. The in-memory index page map
 * is also updated to indicate which delta lists fall on each chapter index page. This means that
 * when a record is read, the volume only has to load a single index page and a single record page,
 * rather than search the entire chapter. These index and record pages are written to storage, and
 * the index pages are transferred to the page cache under the theory that the most recently
 * written chapter is likely to be accessed again soon.
 *
 * When reading a record, the volume index will indicate which chapter should contain it. The
 * volume uses the index page map to determine which chapter index page needs to be loaded, and
 * then reads the relevant record page number from the chapter index. Both index and record pages
 * are stored in a page cache when read for the common case that subsequent records need the same
 * pages. The page cache evicts the least recently accessed entries when caching new pages. In
 * addition, the volume uses dm-bufio to manage access to the storage, which may allow for
 * additional caching depending on available system resources.
 *
 * Record requests are handled from cached pages when possible. If a page needs to be read, it is
 * placed on a queue along with the request that wants to read it. Any requests for the same page
 * that arrive while the read is pending are added to the queue entry. A separate reader thread
 * handles the queued reads, adding the page to the cache and updating any requests queued with it
 * so they can continue processing. This allows the index zone threads to continue processing new
 * requests rather than wait for the storage reads.
 *
 * When an index rebuild is necessary, the volume reads each stored chapter to determine which
 * range of chapters contain valid records, so that those records can be used to reconstruct the
 * in-memory volume index.
 */

/* The maximum allowable number of contiguous bad chapters */
#define MAX_BAD_CHAPTERS 100
#define VOLUME_CACHE_MAX_ENTRIES (U16_MAX >> 1)
#define VOLUME_CACHE_QUEUED_FLAG (1 << 15)
#define VOLUME_CACHE_MAX_QUEUED_READS 4096

static const u64 BAD_CHAPTER = U64_MAX;

/*
 * The invalidate counter is two 32 bits fields stored together atomically. The low order 32 bits
 * are the physical page number of the cached page being read. The high order 32 bits are a
 * sequence number. This value is written when the zone that owns it begins or completes a cache
 * search. Any other thread will only read the counter in wait_for_pending_searches() while waiting
 * to update the cache contents.
 */
union invalidate_counter {
	u64 value;
	struct {
		u32 page;
		u32 counter;
	};
};

static inline u32 map_to_page_number(struct index_geometry *geometry, u32 physical_page)
{
	return (physical_page - HEADER_PAGES_PER_VOLUME) % geometry->pages_per_chapter;
}

static inline u32 map_to_chapter_number(struct index_geometry *geometry, u32 physical_page)
{
	return (physical_page - HEADER_PAGES_PER_VOLUME) / geometry->pages_per_chapter;
}

static inline bool is_record_page(struct index_geometry *geometry, u32 physical_page)
{
	return map_to_page_number(geometry, physical_page) >= geometry->index_pages_per_chapter;
}

static u32 map_to_physical_page(const struct index_geometry *geometry, u32 chapter, u32 page)
{
	/* Page zero is the header page, so the first chapter index page is page one. */
	return HEADER_PAGES_PER_VOLUME + (geometry->pages_per_chapter * chapter) + page;
}

static inline union invalidate_counter get_invalidate_counter(struct page_cache *cache,
							      unsigned int zone_number)
{
	return (union invalidate_counter) {
		.value = READ_ONCE(cache->search_pending_counters[zone_number].atomic_value),
	};
}

static inline void set_invalidate_counter(struct page_cache *cache,
					  unsigned int zone_number,
					  union invalidate_counter invalidate_counter)
{
	WRITE_ONCE(cache->search_pending_counters[zone_number].atomic_value,
		   invalidate_counter.value);
}

static inline bool search_pending(union invalidate_counter invalidate_counter)
{
	return (invalidate_counter.counter & 1) != 0;
}

/* Lock the cache for a zone in order to search for a page. */
static void begin_pending_search(struct page_cache *cache, u32 physical_page,
				 unsigned int zone_number)
{
	union invalidate_counter invalidate_counter =
		get_invalidate_counter(cache, zone_number);

	invalidate_counter.page = physical_page;
	invalidate_counter.counter++;
	set_invalidate_counter(cache, zone_number, invalidate_counter);
	ASSERT_LOG_ONLY(search_pending(invalidate_counter),
			"Search is pending for zone %u", zone_number);
	/*
	 * This memory barrier ensures that the write to the invalidate counter is seen by other
	 * threads before this thread accesses the cached page. The corresponding read memory
	 * barrier is in wait_for_pending_searches().
	 */
	smp_mb();
}

/* Unlock the cache for a zone by clearing its invalidate counter. */
static void end_pending_search(struct page_cache *cache, unsigned int zone_number)
{
	union invalidate_counter invalidate_counter;

	/*
	 * This memory barrier ensures that this thread completes reads of the
	 * cached page before other threads see the write to the invalidate
	 * counter.
	 */
	smp_mb();

	invalidate_counter = get_invalidate_counter(cache, zone_number);
	ASSERT_LOG_ONLY(search_pending(invalidate_counter),
			"Search is pending for zone %u", zone_number);
	invalidate_counter.counter++;
	set_invalidate_counter(cache, zone_number, invalidate_counter);
}

static void wait_for_pending_searches(struct page_cache *cache, u32 physical_page)
{
	union invalidate_counter initial_counters[MAX_ZONES];
	unsigned int i;

	/*
	 * We hold the read_threads_mutex. We are waiting for threads that do not hold the
	 * read_threads_mutex. Those threads have "locked" their targeted page by setting the
	 * search_pending_counter. The corresponding write memory barrier is in
	 * begin_pending_search().
	 */
	smp_mb();

	for (i = 0; i < cache->zone_count; i++)
		initial_counters[i] = get_invalidate_counter(cache, i);
	for (i = 0; i < cache->zone_count; i++) {
		if (search_pending(initial_counters[i]) &&
		    (initial_counters[i].page == physical_page)) {
			/*
			 * There is an active search using the physical page. We need to wait for
			 * the search to finish.
			 *
			 * FIXME: Investigate using wait_event() to wait for the search to finish.
			 */
			while (initial_counters[i].value ==
			       get_invalidate_counter(cache, i).value)
				cond_resched();
		}
	}
}

static void release_page_buffer(struct cached_page *page)
{
	if (page->buffer != NULL)
		dm_bufio_release(vdo_forget(page->buffer));
}

static void clear_cache_page(struct page_cache *cache, struct cached_page *page)
{
	/* Do not clear read_pending because the read queue relies on it. */
	release_page_buffer(page);
	page->physical_page = cache->indexable_pages;
	WRITE_ONCE(page->last_used, 0);
}

static void make_page_most_recent(struct page_cache *cache, struct cached_page *page)
{
	/*
	 * ASSERTION: We are either a zone thread holding a search_pending_counter, or we are any
	 * thread holding the read_threads_mutex.
	 */
	if (atomic64_read(&cache->clock) != READ_ONCE(page->last_used))
		WRITE_ONCE(page->last_used, atomic64_inc_return(&cache->clock));
}

/* Select a page to remove from the cache to make space for a new entry. */
static struct cached_page *select_victim_in_cache(struct page_cache *cache)
{
	struct cached_page *page;
	int oldest_index = 0;
	s64 oldest_time = S64_MAX;
	s64 last_used;
	u16 i;

	/* Find the oldest unclaimed page. We hold the read_threads_mutex. */
	for (i = 0; i < cache->cache_slots; i++) {
		/* A page with a pending read must not be replaced. */
		if (cache->cache[i].read_pending)
			continue;

		last_used = READ_ONCE(cache->cache[i].last_used);
		if (last_used <= oldest_time) {
			oldest_time = last_used;
			oldest_index = i;
		}
	}

	page = &cache->cache[oldest_index];
	if (page->physical_page != cache->indexable_pages) {
		WRITE_ONCE(cache->index[page->physical_page], cache->cache_slots);
		wait_for_pending_searches(cache, page->physical_page);
	}

	page->read_pending = true;
	clear_cache_page(cache, page);
	return page;
}

/* Make a newly filled cache entry available to other threads. */
static int put_page_in_cache(struct page_cache *cache, u32 physical_page,
			     struct cached_page *page)
{
	int result;

	/* We hold the read_threads_mutex. */
	result = ASSERT((page->read_pending), "page to install has a pending read");
	if (result != UDS_SUCCESS)
		return result;

	page->physical_page = physical_page;
	make_page_most_recent(cache, page);
	page->read_pending = false;

	/*
	 * We hold the read_threads_mutex, but we must have a write memory barrier before making
	 * the cached_page available to the readers that do not hold the mutex. The corresponding
	 * read memory barrier is in get_page_and_index().
	 */
	smp_wmb();

	/* This assignment also clears the queued flag. */
	WRITE_ONCE(cache->index[physical_page], page - cache->cache);
	return UDS_SUCCESS;
}

static void cancel_page_in_cache(struct page_cache *cache, u32 physical_page,
				 struct cached_page *page)
{
	int result;

	/* We hold the read_threads_mutex. */
	result = ASSERT((page->read_pending), "page to install has a pending read");
	if (result != UDS_SUCCESS)
		return;

	clear_cache_page(cache, page);
	page->read_pending = false;

	/* Clear the mapping and the queued flag for the new page. */
	WRITE_ONCE(cache->index[physical_page], cache->cache_slots);
}

static inline u16 next_queue_position(u16 position)
{
	return (position + 1) % VOLUME_CACHE_MAX_QUEUED_READS;
}

static inline void advance_queue_position(u16 *position)
{
	*position = next_queue_position(*position);
}

static inline bool read_queue_is_full(struct page_cache *cache)
{
	return cache->read_queue_first == next_queue_position(cache->read_queue_last);
}

static bool enqueue_read(struct page_cache *cache, struct uds_request *request,
			 u32 physical_page)
{
	struct queued_read *queue_entry;
	u16 last = cache->read_queue_last;
	u16 read_queue_index;

	/* We hold the read_threads_mutex. */
	if ((cache->index[physical_page] & VOLUME_CACHE_QUEUED_FLAG) == 0) {
		/* This page has no existing entry in the queue. */
		if (read_queue_is_full(cache))
			return false;

		/* Fill in the read queue entry. */
		cache->read_queue[last].physical_page = physical_page;
		cache->read_queue[last].invalid = false;
		cache->read_queue[last].first_request = NULL;
		cache->read_queue[last].last_request = NULL;

		/* Point the cache index to the read queue entry. */
		read_queue_index = last;
		WRITE_ONCE(cache->index[physical_page],
			   read_queue_index | VOLUME_CACHE_QUEUED_FLAG);

		advance_queue_position(&cache->read_queue_last);
	} else {
		/* It's already queued, so add this request to the existing entry. */
		read_queue_index = cache->index[physical_page] & ~VOLUME_CACHE_QUEUED_FLAG;
	}

	request->next_request = NULL;
	queue_entry = &cache->read_queue[read_queue_index];
	if (queue_entry->first_request == NULL)
		queue_entry->first_request = request;
	else
		queue_entry->last_request->next_request = request;
	queue_entry->last_request = request;

	return true;
}

static void enqueue_page_read(struct volume *volume, struct uds_request *request,
			      u32 physical_page)
{
	/* Mark the page as queued, so that chapter invalidation knows to cancel a read. */
	while (!enqueue_read(&volume->page_cache, request, physical_page)) {
		uds_log_debug("Read queue full, waiting for reads to finish");
		uds_wait_cond(&volume->read_threads_read_done_cond,
			      &volume->read_threads_mutex);
	}

	uds_signal_cond(&volume->read_threads_cond);
}

/*
 * Reserve the next read queue entry for processing, but do not actually remove it from the queue.
 * Must be followed by release_queued_requests().
 */
static struct queued_read *reserve_read_queue_entry(struct page_cache *cache)
{
	/* We hold the read_threads_mutex. */
	struct queued_read *entry;
	u16 index_value;
	bool queued;

	/* No items to dequeue */
	if (cache->read_queue_next_read == cache->read_queue_last)
		return NULL;

	entry = &cache->read_queue[cache->read_queue_next_read];
	index_value = cache->index[entry->physical_page];
	queued = (index_value & VOLUME_CACHE_QUEUED_FLAG) != 0;
	/* Check to see if it's still queued before resetting. */
	if (entry->invalid && queued)
		WRITE_ONCE(cache->index[entry->physical_page], cache->cache_slots);

	/*
	 * If a synchronous read has taken this page, set invalid to true so it doesn't get
	 * overwritten. Requests will just be requeued.
	 */
	if (!queued)
		entry->invalid = true;

	entry->reserved = true;
	advance_queue_position(&cache->read_queue_next_read);
	return entry;
}

static inline struct queued_read *wait_to_reserve_read_queue_entry(struct volume *volume)
{
	struct queued_read *queue_entry = NULL;

	while (!volume->read_threads_exiting) {
		queue_entry = reserve_read_queue_entry(&volume->page_cache);
		if (queue_entry != NULL)
			break;

		uds_wait_cond(&volume->read_threads_cond, &volume->read_threads_mutex);
	}

	return queue_entry;
}

static int init_chapter_index_page(const struct volume *volume, u8 *index_page,
				   u32 chapter, u32 index_page_number,
				   struct delta_index_page *chapter_index_page)
{
	u64 ci_virtual;
	u32 ci_chapter;
	u32 lowest_list;
	u32 highest_list;
	struct index_geometry *geometry = volume->geometry;
	int result;

	result = uds_initialize_chapter_index_page(chapter_index_page, geometry,
						   index_page, volume->nonce);
	if (volume->lookup_mode == LOOKUP_FOR_REBUILD)
		return result;

	if (result != UDS_SUCCESS) {
		return uds_log_error_strerror(result,
					      "Reading chapter index page for chapter %u page %u",
					      chapter, index_page_number);
	}

	uds_get_list_number_bounds(volume->index_page_map, chapter, index_page_number,
				   &lowest_list, &highest_list);
	ci_virtual = chapter_index_page->virtual_chapter_number;
	ci_chapter = uds_map_to_physical_chapter(geometry, ci_virtual);
	if ((chapter == ci_chapter) &&
	    (lowest_list == chapter_index_page->lowest_list_number) &&
	    (highest_list == chapter_index_page->highest_list_number))
		return UDS_SUCCESS;

	uds_log_warning("Index page map updated to %llu",
			(unsigned long long) volume->index_page_map->last_update);
	uds_log_warning("Page map expects that chapter %u page %u has range %u to %u, but chapter index page has chapter %llu with range %u to %u",
			chapter, index_page_number, lowest_list, highest_list,
			(unsigned long long) ci_virtual,
			chapter_index_page->lowest_list_number,
			chapter_index_page->highest_list_number);
	return uds_log_error_strerror(UDS_CORRUPT_DATA,
				      "index page map mismatch with chapter index");
}

static int initialize_index_page(const struct volume *volume, u32 physical_page,
				 struct cached_page *page)
{
	u32 chapter = map_to_chapter_number(volume->geometry, physical_page);
	u32 index_page_number = map_to_page_number(volume->geometry, physical_page);

	return init_chapter_index_page(volume, dm_bufio_get_block_data(page->buffer),
				       chapter, index_page_number, &page->index_page);
}

static bool search_record_page(const u8 record_page[],
			       const struct uds_record_name *name,
			       const struct index_geometry *geometry,
			       struct uds_record_data *metadata)
{
	/*
	 * The array of records is sorted by name and stored as a binary tree in heap order, so the
	 * root of the tree is the first array element.
	 */
	u32 node = 0;
	const struct uds_volume_record *records = (const struct uds_volume_record *) record_page;

	while (node < geometry->records_per_page) {
		int result;
		const struct uds_volume_record *record = &records[node];

		result = memcmp(name, &record->name, UDS_RECORD_NAME_SIZE);
		if (result == 0) {
			if (metadata != NULL)
				*metadata = record->data;
			return true;
		}

		/* The children of node N are at indexes 2N+1 and 2N+2. */
		node = ((2 * node) + ((result < 0) ? 1 : 2));
	}

	return false;
}

/*
 * If we've read in a record page, we're going to do an immediate search, to speed up processing by
 * avoiding get_record_from_zone(), and to ensure that requests make progress even when queued. If
 * we've read in an index page, we save the record page number so we don't have to resolve the
 * index page again. We use the location, virtual_chapter, and old_metadata fields in the request
 * to allow the index code to know where to begin processing the request again.
 */
static int search_page(struct cached_page *page, const struct volume *volume,
		       struct uds_request *request, u32 physical_page)
{
	int result;
	enum uds_index_region location;
	u16 record_page_number;

	if (is_record_page(volume->geometry, physical_page)) {
		if (search_record_page(dm_bufio_get_block_data(page->buffer),
				       &request->record_name, volume->geometry,
				       &request->old_metadata))
			location = UDS_LOCATION_RECORD_PAGE_LOOKUP;
		else
			location = UDS_LOCATION_UNAVAILABLE;
	} else {
		result = uds_search_chapter_index_page(&page->index_page,
						       volume->geometry,
						       &request->record_name,
						       &record_page_number);
		if (result != UDS_SUCCESS)
			return result;

		if (record_page_number == NO_CHAPTER_INDEX_ENTRY) {
			location = UDS_LOCATION_UNAVAILABLE;
		} else {
			location = UDS_LOCATION_INDEX_PAGE_LOOKUP;
			*((u16 *) &request->old_metadata) = record_page_number;
		}
	}

	request->location = location;
	request->found = false;
	return UDS_SUCCESS;
}

static int process_entry(struct volume *volume, struct queued_read *entry)
{
	u32 page_number = entry->physical_page;
	struct uds_request *request;
	struct cached_page *page = NULL;
	u8 *page_data;
	int result;

	if (entry->invalid) {
		uds_log_debug("Requeuing requests for invalid page");
		return UDS_SUCCESS;
	}

	page = select_victim_in_cache(&volume->page_cache);

	mutex_unlock(&volume->read_threads_mutex);
	page_data = dm_bufio_read(volume->client, page_number, &page->buffer);
	mutex_lock(&volume->read_threads_mutex);
	if (IS_ERR(page_data)) {
		result = -PTR_ERR(page_data);
		uds_log_warning_strerror(result,
					 "error reading physical page %u from volume",
					 page_number);
		cancel_page_in_cache(&volume->page_cache, page_number, page);
		return result;
	}

	if (entry->invalid) {
		uds_log_warning("Page %u invalidated after read", page_number);
		cancel_page_in_cache(&volume->page_cache, page_number, page);
		return UDS_SUCCESS;
	}

	if (!is_record_page(volume->geometry, page_number)) {
		result = initialize_index_page(volume, page_number, page);
		if (result != UDS_SUCCESS) {
			uds_log_warning("Error initializing chapter index page");
			cancel_page_in_cache(&volume->page_cache, page_number, page);
			return result;
		}
	}

	result = put_page_in_cache(&volume->page_cache, page_number, page);
	if (result != UDS_SUCCESS) {
		uds_log_warning("Error putting page %u in cache", page_number);
		cancel_page_in_cache(&volume->page_cache, page_number, page);
		return result;
	}

	request = entry->first_request;
	while ((request != NULL) && (result == UDS_SUCCESS)) {
		result = search_page(page, volume, request, page_number);
		request = request->next_request;
	}

	return result;
}

static void release_queued_requests(struct volume *volume, struct queued_read *entry,
				    int result)
{
	struct page_cache *cache = &volume->page_cache;
	u16 next_read = cache->read_queue_next_read;
	struct uds_request *request;
	struct uds_request *next;

	for (request = entry->first_request; request != NULL; request = next) {
		next = request->next_request;
		request->status = result;
		request->requeued = true;
		uds_enqueue_request(request, STAGE_INDEX);
	}

	entry->reserved = false;

	/* Move the read_queue_first pointer as far as we can. */
	while ((cache->read_queue_first != next_read) &&
	       (!cache->read_queue[cache->read_queue_first].reserved))
		advance_queue_position(&cache->read_queue_first);
	uds_broadcast_cond(&volume->read_threads_read_done_cond);
}

static void read_thread_function(void *arg)
{
	struct volume *volume = arg;

	uds_log_debug("reader starting");
	mutex_lock(&volume->read_threads_mutex);
	while (true) {
		struct queued_read *queue_entry;
		int result;

		queue_entry = wait_to_reserve_read_queue_entry(volume);
		if (volume->read_threads_exiting)
			break;

		result = process_entry(volume, queue_entry);
		release_queued_requests(volume, queue_entry, result);
	}
	mutex_unlock(&volume->read_threads_mutex);
	uds_log_debug("reader done");
}

static void get_page_and_index(struct page_cache *cache, u32 physical_page,
			       int *queue_index, struct cached_page **page_ptr)
{
	u16 index_value;
	u16 index;
	bool queued;

	/*
	 * ASSERTION: We are either a zone thread holding a search_pending_counter, or we are any
	 * thread holding the read_threads_mutex.
	 *
	 * Holding only a search_pending_counter is the most frequent case.
	 */
	/*
	 * It would be unlikely for the compiler to turn the usage of index_value into two reads of
	 * cache->index, but it would be possible and very bad if those reads did not return the
	 * same bits.
	 */
	index_value = READ_ONCE(cache->index[physical_page]);
	queued = (index_value & VOLUME_CACHE_QUEUED_FLAG) != 0;
	index = index_value & ~VOLUME_CACHE_QUEUED_FLAG;

	if (!queued && (index < cache->cache_slots)) {
		*page_ptr = &cache->cache[index];
		/*
		 * We have acquired access to the cached page, but unless we hold the
		 * read_threads_mutex, we need a read memory barrier now. The corresponding write
		 * memory barrier is in put_page_in_cache().
		 */
		smp_rmb();
	} else {
		*page_ptr = NULL;
	}

	*queue_index = queued ? index : -1;
}

static void get_page_from_cache(struct page_cache *cache, u32 physical_page,
				struct cached_page **page)
{
	/*
	 * ASSERTION: We are in a zone thread.
	 * ASSERTION: We holding a search_pending_counter or the read_threads_mutex.
	 */
	int queue_index = -1;

	get_page_and_index(cache, physical_page, &queue_index, page);
}

static int read_page_locked(struct volume *volume, u32 physical_page,
			    struct cached_page **page_ptr)
{
	int result = UDS_SUCCESS;
	struct cached_page *page = NULL;
	u8 *page_data;

	page = select_victim_in_cache(&volume->page_cache);
	page_data = dm_bufio_read(volume->client, physical_page, &page->buffer);
	if (IS_ERR(page_data)) {
		result = -PTR_ERR(page_data);
		uds_log_warning_strerror(result,
					 "error reading physical page %u from volume",
					 physical_page);
		cancel_page_in_cache(&volume->page_cache, physical_page, page);
		return result;
	}

	if (!is_record_page(volume->geometry, physical_page)) {
		result = initialize_index_page(volume, physical_page, page);
		if (result != UDS_SUCCESS) {
			if (volume->lookup_mode != LOOKUP_FOR_REBUILD)
				uds_log_warning("Corrupt index page %u", physical_page);
			cancel_page_in_cache(&volume->page_cache, physical_page, page);
			return result;
		}
	}

	result = put_page_in_cache(&volume->page_cache, physical_page, page);
	if (result != UDS_SUCCESS) {
		uds_log_warning("Error putting page %u in cache", physical_page);
		cancel_page_in_cache(&volume->page_cache, physical_page, page);
		return result;
	}

	*page_ptr = page;
	return UDS_SUCCESS;
}

/* Retrieve a page from the cache while holding the read threads mutex. */
static int get_volume_page_locked(struct volume *volume, u32 physical_page,
				  struct cached_page **page_ptr)
{
	int result;
	struct cached_page *page = NULL;

	get_page_from_cache(&volume->page_cache, physical_page, &page);
	if (page == NULL) {
		result = read_page_locked(volume, physical_page, &page);
		if (result != UDS_SUCCESS)
			return result;
	} else {
		make_page_most_recent(&volume->page_cache, page);
	}

	*page_ptr = page;
	return UDS_SUCCESS;
}

/* Retrieve a page from the cache while holding a search_pending lock. */
static int get_volume_page_protected(struct volume *volume, struct uds_request *request,
				     u32 physical_page, struct cached_page **page_ptr)
{
	struct cached_page *page;

	get_page_from_cache(&volume->page_cache, physical_page, &page);
	if (page != NULL) {
		if (request->zone_number == 0) {
			/* Only one zone is allowed to update the LRU. */
			make_page_most_recent(&volume->page_cache, page);
		}

		*page_ptr = page;
		return UDS_SUCCESS;
	}

	/* Prepare to enqueue a read for the page. */
	end_pending_search(&volume->page_cache, request->zone_number);
	mutex_lock(&volume->read_threads_mutex);

	/*
	 * Do the lookup again while holding the read mutex (no longer the fast case so this should
	 * be fine to repeat). We need to do this because a page may have been added to the cache
	 * by a reader thread between the time we searched above and the time we went to actually
	 * try to enqueue it below. This could result in us enqueuing another read for a page which
	 * is already in the cache, which would mean we end up with two entries in the cache for
	 * the same page.
	 */
	get_page_from_cache(&volume->page_cache, physical_page, &page);
	if (page == NULL) {
		enqueue_page_read(volume, request, physical_page);
		/*
		 * The performance gain from unlocking first, while "search pending" mode is off,
		 * turns out to be significant in some cases. The page is not available yet so
		 * the order does not matter for correctness as it does below.
		 */
		mutex_unlock(&volume->read_threads_mutex);
		begin_pending_search(&volume->page_cache, physical_page,
				     request->zone_number);
		return UDS_QUEUED;
	}

	/*
	 * Now that the page is loaded, the volume needs to switch to "reader thread unlocked" and
	 * "search pending" state in careful order so no other thread can mess with the data before
	 * the caller gets to look at it.
	 */
	begin_pending_search(&volume->page_cache, physical_page, request->zone_number);
	mutex_unlock(&volume->read_threads_mutex);
	*page_ptr = page;
	return UDS_SUCCESS;
}

static int get_volume_page(struct volume *volume, u32 chapter, u32 page_number,
			   struct cached_page **page_ptr)
{
	int result;
	u32 physical_page = map_to_physical_page(volume->geometry, chapter, page_number);

	mutex_lock(&volume->read_threads_mutex);
	result = get_volume_page_locked(volume, physical_page, page_ptr);
	mutex_unlock(&volume->read_threads_mutex);
	return result;
}

int uds_get_volume_record_page(struct volume *volume, u32 chapter, u32 page_number,
			       u8 **data_ptr)
{
	int result;
	struct cached_page *page = NULL;

	result = get_volume_page(volume, chapter, page_number, &page);
	if (result == UDS_SUCCESS)
		*data_ptr = dm_bufio_get_block_data(page->buffer);
	return result;
}

int uds_get_volume_index_page(struct volume *volume, u32 chapter, u32 page_number,
			      struct delta_index_page **index_page_ptr)
{
	int result;
	struct cached_page *page = NULL;

	result = get_volume_page(volume, chapter, page_number, &page);
	if (result == UDS_SUCCESS)
		*index_page_ptr = &page->index_page;
	return result;
}

/*
 * Find the record page associated with a name in a given index page. This will return UDS_QUEUED
 * if the page in question must be read from storage.
 */
static int search_cached_index_page(struct volume *volume, struct uds_request *request,
				    u32 chapter, u32 index_page_number,
				    u16 *record_page_number)
{
	int result;
	struct cached_page *page = NULL;
	u32 physical_page = map_to_physical_page(volume->geometry, chapter,
						 index_page_number);

	/*
	 * Make sure the invalidate counter is updated before we try and read the mapping. This
	 * prevents this thread from reading a page in the cache which has already been marked for
	 * invalidation by the reader thread, before the reader thread has noticed that the
	 * invalidate_counter has been incremented.
	 */
	begin_pending_search(&volume->page_cache, physical_page, request->zone_number);

	result = get_volume_page_protected(volume, request, physical_page, &page);
	if (result != UDS_SUCCESS) {
		end_pending_search(&volume->page_cache, request->zone_number);
		return result;
	}

	result = uds_search_chapter_index_page(&page->index_page, volume->geometry,
					       &request->record_name,
					       record_page_number);
	end_pending_search(&volume->page_cache, request->zone_number);
	return result;
}

/*
 * Find the metadata associated with a name in a given record page. This will return UDS_QUEUED if
 * the page in question must be read from storage.
 */
int uds_search_cached_record_page(struct volume *volume, struct uds_request *request,
				  u32 chapter, u16 record_page_number, bool *found)
{
	struct cached_page *record_page;
	struct index_geometry *geometry = volume->geometry;
	int result;
	u32 physical_page, page_number;

	*found = false;
	if (record_page_number == NO_CHAPTER_INDEX_ENTRY)
		return UDS_SUCCESS;

	result = ASSERT(record_page_number < geometry->record_pages_per_chapter,
			"0 <= %d < %u", record_page_number,
			geometry->record_pages_per_chapter);
	if (result != UDS_SUCCESS)
		return result;

	page_number = geometry->index_pages_per_chapter + record_page_number;

	physical_page = map_to_physical_page(volume->geometry, chapter, page_number);

	/*
	 * Make sure the invalidate counter is updated before we try and read the mapping. This
	 * prevents this thread from reading a page in the cache which has already been marked for
	 * invalidation by the reader thread, before the reader thread has noticed that the
	 * invalidate_counter has been incremented.
	 */
	begin_pending_search(&volume->page_cache, physical_page, request->zone_number);

	result = get_volume_page_protected(volume, request, physical_page, &record_page);
	if (result != UDS_SUCCESS) {
		end_pending_search(&volume->page_cache, request->zone_number);
		return result;
	}

	if (search_record_page(dm_bufio_get_block_data(record_page->buffer),
			       &request->record_name, geometry, &request->old_metadata))
		*found = true;

	end_pending_search(&volume->page_cache, request->zone_number);
	return UDS_SUCCESS;
}

void uds_prefetch_volume_chapter(const struct volume *volume, u32 chapter)
{
	const struct index_geometry *geometry = volume->geometry;
	u32 physical_page = map_to_physical_page(geometry, chapter, 0);

	dm_bufio_prefetch(volume->client, physical_page, geometry->pages_per_chapter);
}

int uds_read_chapter_index_from_volume(const struct volume *volume, u64 virtual_chapter,
				       struct dm_buffer *volume_buffers[],
				       struct delta_index_page index_pages[])
{
	int result;
	u32 i;
	const struct index_geometry *geometry = volume->geometry;
	u32 physical_chapter = uds_map_to_physical_chapter(geometry, virtual_chapter);
	u32 physical_page = map_to_physical_page(geometry, physical_chapter, 0);

	dm_bufio_prefetch(volume->client, physical_page, geometry->index_pages_per_chapter);
	for (i = 0; i < geometry->index_pages_per_chapter; i++) {
		u8 *index_page;

		index_page = dm_bufio_read(volume->client, physical_page + i,
					   &volume_buffers[i]);
		if (IS_ERR(index_page)) {
			result = -PTR_ERR(index_page);
			uds_log_warning_strerror(result,
						 "error reading physical page %u",
						 physical_page);
			return result;
		}

		result = init_chapter_index_page(volume, index_page, physical_chapter, i,
						 &index_pages[i]);
		if (result != UDS_SUCCESS)
			return result;
	}

	return UDS_SUCCESS;
}

int uds_search_volume_page_cache(struct volume *volume, struct uds_request *request,
				 bool *found)
{
	int result;
	u32 physical_chapter =
		uds_map_to_physical_chapter(volume->geometry, request->virtual_chapter);
	u32 index_page_number;
	u16 record_page_number;

	index_page_number = uds_find_index_page_number(volume->index_page_map,
						       &request->record_name,
						       physical_chapter);

	if (request->location == UDS_LOCATION_INDEX_PAGE_LOOKUP) {
		record_page_number = *((u16 *) &request->old_metadata);
	} else {
		result = search_cached_index_page(volume, request, physical_chapter,
						  index_page_number,
						  &record_page_number);
		if (result != UDS_SUCCESS)
			return result;
	}

	return uds_search_cached_record_page(volume, request, physical_chapter,
					     record_page_number, found);
}

int uds_search_volume_page_cache_for_rebuild(struct volume *volume,
					     const struct uds_record_name *name,
					     u64 virtual_chapter, bool *found)
{
	int result;
	struct index_geometry *geometry = volume->geometry;
	struct cached_page *page;
	u32 physical_chapter = uds_map_to_physical_chapter(geometry, virtual_chapter);
	u32 index_page_number;
	u16 record_page_number;
	u32 page_number;

	*found = false;
	index_page_number =
		uds_find_index_page_number(volume->index_page_map, name,
					   physical_chapter);
	result = get_volume_page(volume, physical_chapter, index_page_number, &page);
	if (result != UDS_SUCCESS)
		return result;

	result = uds_search_chapter_index_page(&page->index_page, geometry, name,
					       &record_page_number);
	if (result != UDS_SUCCESS)
		return result;

	if (record_page_number == NO_CHAPTER_INDEX_ENTRY)
		return UDS_SUCCESS;

	page_number = geometry->index_pages_per_chapter + record_page_number;
	result = get_volume_page(volume, physical_chapter, page_number, &page);
	if (result != UDS_SUCCESS)
		return result;

	*found = search_record_page(dm_bufio_get_block_data(page->buffer), name,
				    geometry, NULL);
	return UDS_SUCCESS;
}

static void invalidate_page(struct page_cache *cache, u32 physical_page)
{
	struct cached_page *page;
	int queue_index = -1;

	/* We hold the read_threads_mutex. */
	get_page_and_index(cache, physical_page, &queue_index, &page);
	if (page != NULL) {
		WRITE_ONCE(cache->index[page->physical_page], cache->cache_slots);
		wait_for_pending_searches(cache, page->physical_page);
		clear_cache_page(cache, page);
	} else if (queue_index > -1) {
		uds_log_debug("setting pending read to invalid");
		cache->read_queue[queue_index].invalid = true;
	}
}

void uds_forget_chapter(struct volume *volume, u64 virtual_chapter)
{
	u32 physical_chapter =
		uds_map_to_physical_chapter(volume->geometry, virtual_chapter);
	u32 first_page = map_to_physical_page(volume->geometry, physical_chapter, 0);
	u32 i;

	uds_log_debug("forgetting chapter %llu", (unsigned long long) virtual_chapter);
	mutex_lock(&volume->read_threads_mutex);
	for (i = 0; i < volume->geometry->pages_per_chapter; i++)
		invalidate_page(&volume->page_cache, first_page + i);
	mutex_unlock(&volume->read_threads_mutex);
}

/*
 * Donate an index pages from a newly written chapter to the page cache since it is likely to be
 * used again soon. The caller must already hold the reader thread mutex.
 */
static int donate_index_page_locked(struct volume *volume, u32 physical_chapter,
				    u32 index_page_number, struct dm_buffer *page_buffer)
{
	int result;
	struct cached_page *page = NULL;
	u32 physical_page =
		map_to_physical_page(volume->geometry, physical_chapter,
				     index_page_number);

	page = select_victim_in_cache(&volume->page_cache);
	page->buffer = page_buffer;
	result = init_chapter_index_page(volume, dm_bufio_get_block_data(page_buffer),
					 physical_chapter, index_page_number,
					 &page->index_page);
	if (result != UDS_SUCCESS) {
		uds_log_warning("Error initialize chapter index page");
		cancel_page_in_cache(&volume->page_cache, physical_page, page);
		return result;
	}

	result = put_page_in_cache(&volume->page_cache, physical_page, page);
	if (result != UDS_SUCCESS) {
		uds_log_warning("Error putting page %u in cache", physical_page);
		cancel_page_in_cache(&volume->page_cache, physical_page, page);
		return result;
	}

	return UDS_SUCCESS;
}

static int write_index_pages(struct volume *volume, u32 physical_chapter_number,
			     struct open_chapter_index *chapter_index)
{
	struct index_geometry *geometry = volume->geometry;
	struct dm_buffer *page_buffer;
	u32 first_index_page = map_to_physical_page(geometry, physical_chapter_number, 0);
	u32 delta_list_number = 0;
	u32 index_page_number;

	for (index_page_number = 0;
	     index_page_number < geometry->index_pages_per_chapter;
	     index_page_number++) {
		u8 *page_data;
		u32 physical_page = first_index_page + index_page_number;
		u32 lists_packed;
		bool last_page;
		int result;

		page_data = dm_bufio_new(volume->client, physical_page, &page_buffer);
		if (IS_ERR(page_data)) {
			return uds_log_warning_strerror(-PTR_ERR(page_data),
							"failed to prepare index page");
		}

		last_page = ((index_page_number + 1) == geometry->index_pages_per_chapter);
		result = uds_pack_open_chapter_index_page(chapter_index, page_data,
							  delta_list_number, last_page,
							  &lists_packed);
		if (result != UDS_SUCCESS) {
			dm_bufio_release(page_buffer);
			return uds_log_warning_strerror(result,
							"failed to pack index page");
		}

		dm_bufio_mark_buffer_dirty(page_buffer);

		if (lists_packed == 0) {
			uds_log_debug("no delta lists packed on chapter %u page %u",
				      physical_chapter_number, index_page_number);
		} else {
			delta_list_number += lists_packed;
		}

		uds_update_index_page_map(volume->index_page_map,
					  chapter_index->virtual_chapter_number,
					  physical_chapter_number, index_page_number,
					  delta_list_number - 1);

		mutex_lock(&volume->read_threads_mutex);
		result = donate_index_page_locked(volume, physical_chapter_number,
						  index_page_number, page_buffer);
		mutex_unlock(&volume->read_threads_mutex);
		if (result != UDS_SUCCESS) {
			dm_bufio_release(page_buffer);
			return result;
		}
	}

	return UDS_SUCCESS;
}

static u32 encode_tree(u8 record_page[],
		       const struct uds_volume_record *sorted_pointers[],
		       u32 next_record, u32 node, u32 node_count)
{
	if (node < node_count) {
		u32 child = (2 * node) + 1;

		next_record = encode_tree(record_page, sorted_pointers, next_record,
					  child, node_count);

		/*
		 * In-order traversal: copy the contents of the next record into the page at the
		 * node offset.
		 */
		memcpy(&record_page[node * BYTES_PER_RECORD],
		       sorted_pointers[next_record++], BYTES_PER_RECORD);

		next_record = encode_tree(record_page, sorted_pointers, next_record,
					  child + 1, node_count);
	}

	return next_record;
}

static int encode_record_page(const struct volume *volume,
			      const struct uds_volume_record records[], u8 record_page[])
{
	int result;
	u32 i;
	u32 records_per_page = volume->geometry->records_per_page;
	const struct uds_volume_record **record_pointers = volume->record_pointers;

	for (i = 0; i < records_per_page; i++)
		record_pointers[i] = &records[i];

	/*
	 * Sort the record pointers by using just the names in the records, which is less work than
	 * sorting the entire record values.
	 */
	BUILD_BUG_ON(offsetof(struct uds_volume_record, name) != 0);
	result = uds_radix_sort(volume->radix_sorter, (const u8 **) record_pointers,
				records_per_page, UDS_RECORD_NAME_SIZE);
	if (result != UDS_SUCCESS)
		return result;

	encode_tree(record_page, record_pointers, 0, 0, records_per_page);
	return UDS_SUCCESS;
}

static int write_record_pages(struct volume *volume, u32 physical_chapter_number,
			      const struct uds_volume_record *records)
{
	u32 record_page_number;
	struct index_geometry *geometry = volume->geometry;
	struct dm_buffer *page_buffer;
	const struct uds_volume_record *next_record = records;
	u32 first_record_page = map_to_physical_page(geometry, physical_chapter_number,
						     geometry->index_pages_per_chapter);

	for (record_page_number = 0;
	     record_page_number < geometry->record_pages_per_chapter;
	     record_page_number++) {
		u8 *page_data;
		u32 physical_page = first_record_page + record_page_number;
		int result;

		page_data = dm_bufio_new(volume->client, physical_page, &page_buffer);
		if (IS_ERR(page_data)) {
			return uds_log_warning_strerror(-PTR_ERR(page_data),
							"failed to prepare record page");
		}

		result = encode_record_page(volume, next_record, page_data);
		if (result != UDS_SUCCESS) {
			dm_bufio_release(page_buffer);
			return uds_log_warning_strerror(result,
							"failed to encode record page %u",
							record_page_number);
		}

		next_record += geometry->records_per_page;
		dm_bufio_mark_buffer_dirty(page_buffer);
		dm_bufio_release(page_buffer);
	}

	return UDS_SUCCESS;
}

int uds_write_chapter(struct volume *volume, struct open_chapter_index *chapter_index,
		      const struct uds_volume_record *records)
{
	int result;
	u32 physical_chapter_number =
		uds_map_to_physical_chapter(volume->geometry,
					    chapter_index->virtual_chapter_number);

	result = write_index_pages(volume, physical_chapter_number, chapter_index);
	if (result != UDS_SUCCESS)
		return result;

	result = write_record_pages(volume, physical_chapter_number, records);
	if (result != UDS_SUCCESS)
		return result;

	result = -dm_bufio_write_dirty_buffers(volume->client);
	if (result != UDS_SUCCESS)
		uds_log_error_strerror(result, "cannot sync chapter to volume");

	return result;
}

static void probe_chapter(struct volume *volume, u32 chapter_number,
			  u64 *virtual_chapter_number)
{
	const struct index_geometry *geometry = volume->geometry;
	u32 expected_list_number = 0;
	u32 i;
	u64 vcn = BAD_CHAPTER;

	*virtual_chapter_number = BAD_CHAPTER;
	dm_bufio_prefetch(volume->client,
			  map_to_physical_page(geometry, chapter_number, 0),
			  geometry->index_pages_per_chapter);

	for (i = 0; i < geometry->index_pages_per_chapter; i++) {
		struct delta_index_page *page;
		int result;

		result = uds_get_volume_index_page(volume, chapter_number, i, &page);
		if (result != UDS_SUCCESS)
			return;

		if (page->virtual_chapter_number == BAD_CHAPTER) {
			uds_log_error("corrupt index page in chapter %u",
				      chapter_number);
			return;
		}

		if (vcn == BAD_CHAPTER) {
			vcn = page->virtual_chapter_number;
		} else if (page->virtual_chapter_number != vcn) {
			uds_log_error("inconsistent chapter %u index page %u: expected vcn %llu, got vcn %llu",
				      chapter_number, i, (unsigned long long) vcn,
				      (unsigned long long) page->virtual_chapter_number);
			return;
		}

		if (expected_list_number != page->lowest_list_number) {
			uds_log_error("inconsistent chapter %u index page %u: expected list number %u, got list number %u",
				      chapter_number, i, expected_list_number,
				      page->lowest_list_number);
			return;
		}
		expected_list_number = page->highest_list_number + 1;

		result = uds_validate_chapter_index_page(page, geometry);
		if (result != UDS_SUCCESS)
			return;
	}

	if (chapter_number != uds_map_to_physical_chapter(geometry, vcn)) {
		uds_log_error("chapter %u vcn %llu is out of phase (%u)", chapter_number,
			      (unsigned long long) vcn, geometry->chapters_per_volume);
		return;
	}

	*virtual_chapter_number = vcn;
}

/* Find the last valid physical chapter in the volume. */
static void find_real_end_of_volume(struct volume *volume, u32 limit, u32 *limit_ptr)
{
	u32 span = 1;
	u32 tries = 0;

	while (limit > 0) {
		u32 chapter = (span > limit) ? 0 : limit - span;
		u64 vcn = 0;

		probe_chapter(volume, chapter, &vcn);
		if (vcn == BAD_CHAPTER) {
			limit = chapter;
			if (++tries > 1)
				span *= 2;
		} else {
			if (span == 1)
				break;
			span /= 2;
			tries = 0;
		}
	}

	*limit_ptr = limit;
}

static int find_chapter_limits(struct volume *volume, u32 chapter_limit, u64 *lowest_vcn,
			       u64 *highest_vcn)
{
	struct index_geometry *geometry = volume->geometry;
	u64 zero_vcn;
	u64 lowest = BAD_CHAPTER;
	u64 highest = BAD_CHAPTER;
	u64 moved_chapter = BAD_CHAPTER;
	u32 left_chapter = 0;
	u32 right_chapter = 0;
	u32 bad_chapters = 0;

	/*
	 * This method assumes there is at most one run of contiguous bad chapters caused by
	 * unflushed writes. Either the bad spot is at the beginning and end, or somewhere in the
	 * middle. Wherever it is, the highest and lowest VCNs are adjacent to it. Otherwise the
	 * volume is cleanly saved and somewhere in the middle of it the highest VCN immediately
	 * precedes the lowest one.
	 */

	/* It doesn't matter if this results in a bad spot (BAD_CHAPTER). */
	probe_chapter(volume, 0, &zero_vcn);

	/*
	 * Binary search for end of the discontinuity in the monotonically increasing virtual
	 * chapter numbers; bad spots are treated as a span of BAD_CHAPTER values. In effect we're
	 * searching for the index of the smallest value less than zero_vcn. In the case we go off
	 * the end it means that chapter 0 has the lowest vcn.
	 *
	 * If a virtual chapter is out-of-order, it will be the one moved by conversion. Always
	 * skip over the moved chapter when searching, adding it to the range at the end if
	 * necessary.
	 */
	if (geometry->remapped_physical > 0) {
		u64 remapped_vcn;

		probe_chapter(volume, geometry->remapped_physical, &remapped_vcn);
		if (remapped_vcn == geometry->remapped_virtual)
			moved_chapter = geometry->remapped_physical;
	}

	left_chapter = 0;
	right_chapter = chapter_limit;

	while (left_chapter < right_chapter) {
		u64 probe_vcn;
		u32 chapter = (left_chapter + right_chapter) / 2;

		if (chapter == moved_chapter)
			chapter--;

		probe_chapter(volume, chapter, &probe_vcn);
		if (zero_vcn <= probe_vcn) {
			left_chapter = chapter + 1;
			if (left_chapter == moved_chapter)
				left_chapter++;
		} else {
			right_chapter = chapter;
		}
	}

	/* If left_chapter goes off the end, chapter 0 has the lowest virtual chapter number.*/
	if (left_chapter >= chapter_limit)
		left_chapter = 0;

	/* At this point, left_chapter is the chapter with the lowest virtual chapter number. */
	probe_chapter(volume, left_chapter, &lowest);

	/* The moved chapter might be the lowest in the range. */
	if ((moved_chapter != BAD_CHAPTER) && (lowest == geometry->remapped_virtual + 1))
		lowest = geometry->remapped_virtual;

	/*
	 * Circularly scan backwards, moving over any bad chapters until encountering a good one,
	 * which is the chapter with the highest vcn.
	 */
	while (highest == BAD_CHAPTER) {
		right_chapter = (right_chapter + chapter_limit - 1) % chapter_limit;
		if (right_chapter == moved_chapter)
			continue;

		probe_chapter(volume, right_chapter, &highest);
		if (bad_chapters++ >= MAX_BAD_CHAPTERS) {
			uds_log_error("too many bad chapters in volume: %u",
				      bad_chapters);
			return UDS_CORRUPT_DATA;
		}
	}

	*lowest_vcn = lowest;
	*highest_vcn = highest;
	return UDS_SUCCESS;
}

/*
 * Find the highest and lowest contiguous chapters present in the volume and determine their
 * virtual chapter numbers. This is used by rebuild.
 */
int uds_find_volume_chapter_boundaries(struct volume *volume, u64 *lowest_vcn,
				       u64 *highest_vcn, bool *is_empty)
{
	u32 chapter_limit = volume->geometry->chapters_per_volume;

	find_real_end_of_volume(volume, chapter_limit, &chapter_limit);
	if (chapter_limit == 0) {
		*lowest_vcn = 0;
		*highest_vcn = 0;
		*is_empty = true;
		return UDS_SUCCESS;
	}

	*is_empty = false;
	return find_chapter_limits(volume, chapter_limit, lowest_vcn, highest_vcn);
}

int __must_check uds_replace_volume_storage(struct volume *volume,
					    struct index_layout *layout,
					    struct block_device *bdev)
{
	int result;
	u32 i;

	result = uds_replace_index_layout_storage(layout, bdev);
	if (result != UDS_SUCCESS)
		return result;

	/* Release all outstanding dm_bufio objects */
	for (i = 0; i < volume->page_cache.indexable_pages; i++)
		volume->page_cache.index[i] = volume->page_cache.cache_slots;
	for (i = 0; i < volume->page_cache.cache_slots; i++)
		clear_cache_page(&volume->page_cache, &volume->page_cache.cache[i]);
	if (volume->sparse_cache != NULL)
		uds_invalidate_sparse_cache(volume->sparse_cache);
	if (volume->client != NULL)
		dm_bufio_client_destroy(vdo_forget(volume->client));

	return uds_open_volume_bufio(layout, volume->geometry->bytes_per_page,
				     volume->reserved_buffers, &volume->client);
}

static int __must_check initialize_page_cache(struct page_cache *cache,
					      const struct index_geometry *geometry,
					      u32 chapters_in_cache,
					      unsigned int zone_count)
{
	int result;
	u32 i;

	cache->indexable_pages = geometry->pages_per_volume + 1;
	cache->cache_slots = chapters_in_cache * geometry->record_pages_per_chapter;
	cache->zone_count = zone_count;
	atomic64_set(&cache->clock, 1);

	result = ASSERT((cache->cache_slots <= VOLUME_CACHE_MAX_ENTRIES),
			"requested cache size, %u, within limit %u",
			cache->cache_slots, VOLUME_CACHE_MAX_ENTRIES);
	if (result != UDS_SUCCESS)
		return result;

	result = vdo_allocate(VOLUME_CACHE_MAX_QUEUED_READS, struct queued_read,
			      "volume read queue", &cache->read_queue);
	if (result != UDS_SUCCESS)
		return result;

	result = vdo_allocate(cache->zone_count, struct search_pending_counter,
			      "Volume Cache Zones", &cache->search_pending_counters);
	if (result != UDS_SUCCESS)
		return result;

	result = vdo_allocate(cache->indexable_pages, u16, "page cache index",
			      &cache->index);
	if (result != UDS_SUCCESS)
		return result;

	result = vdo_allocate(cache->cache_slots, struct cached_page, "page cache cache",
			      &cache->cache);
	if (result != UDS_SUCCESS)
		return result;

	/* Initialize index values to invalid values. */
	for (i = 0; i < cache->indexable_pages; i++)
		cache->index[i] = cache->cache_slots;

	for (i = 0; i < cache->cache_slots; i++)
		clear_cache_page(cache, &cache->cache[i]);

	return UDS_SUCCESS;
}

int uds_make_volume(const struct uds_configuration *config, struct index_layout *layout,
		    struct volume **new_volume)
{
	unsigned int i;
	struct volume *volume = NULL;
	struct index_geometry *geometry;
	unsigned int reserved_buffers;
	int result;

	result = vdo_allocate(1, struct volume, "volume", &volume);
	if (result != UDS_SUCCESS)
		return result;

	volume->nonce = uds_get_volume_nonce(layout);

	result = uds_copy_index_geometry(config->geometry, &volume->geometry);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return uds_log_warning_strerror(result,
						"failed to allocate geometry: error");
	}
	geometry = volume->geometry;

	/*
	 * Reserve a buffer for each entry in the page cache, one for the chapter writer, and one
	 * for each entry in the sparse cache.
	 */
	reserved_buffers = config->cache_chapters * geometry->record_pages_per_chapter;
	reserved_buffers += 1;
	if (uds_is_sparse_index_geometry(geometry))
		reserved_buffers += (config->cache_chapters * geometry->index_pages_per_chapter);
	volume->reserved_buffers = reserved_buffers;
	result = uds_open_volume_bufio(layout, geometry->bytes_per_page,
				       volume->reserved_buffers, &volume->client);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	result = uds_make_radix_sorter(geometry->records_per_page,
				       &volume->radix_sorter);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	result = vdo_allocate(geometry->records_per_page,
			      const struct uds_volume_record *, "record pointers",
			      &volume->record_pointers);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	if (uds_is_sparse_index_geometry(geometry)) {
		size_t page_size = sizeof(struct delta_index_page) + geometry->bytes_per_page;

		result = uds_make_sparse_cache(geometry, config->cache_chapters,
					       config->zone_count,
					       &volume->sparse_cache);
		if (result != UDS_SUCCESS) {
			uds_free_volume(volume);
			return result;
		}

		volume->cache_size =
			page_size * geometry->index_pages_per_chapter * config->cache_chapters;
	}

	result = initialize_page_cache(&volume->page_cache, geometry,
				       config->cache_chapters, config->zone_count);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	volume->cache_size += volume->page_cache.cache_slots * sizeof(struct delta_index_page);
	result = uds_make_index_page_map(geometry, &volume->index_page_map);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	mutex_init(&volume->read_threads_mutex);
	uds_init_cond(&volume->read_threads_read_done_cond);
	uds_init_cond(&volume->read_threads_cond);

	result = vdo_allocate(config->read_threads, struct thread *, "reader threads",
			      &volume->reader_threads);
	if (result != UDS_SUCCESS) {
		uds_free_volume(volume);
		return result;
	}

	for (i = 0; i < config->read_threads; i++) {
		result = vdo_create_thread(read_thread_function, (void *) volume,
					   "reader", &volume->reader_threads[i]);
		if (result != UDS_SUCCESS) {
			uds_free_volume(volume);
			return result;
		}

		volume->read_thread_count = i + 1;
	}

	*new_volume = volume;
	return UDS_SUCCESS;
}

static void uninitialize_page_cache(struct page_cache *cache)
{
	u16 i;

	if (cache->cache != NULL) {
		for (i = 0; i < cache->cache_slots; i++)
			release_page_buffer(&cache->cache[i]);
	}
	vdo_free(cache->index);
	vdo_free(cache->cache);
	vdo_free(cache->search_pending_counters);
	vdo_free(cache->read_queue);
}

void uds_free_volume(struct volume *volume)
{
	if (volume == NULL)
		return;

	if (volume->reader_threads != NULL) {
		unsigned int i;

		/* This works even if some threads weren't started. */
		mutex_lock(&volume->read_threads_mutex);
		volume->read_threads_exiting = true;
		uds_broadcast_cond(&volume->read_threads_cond);
		mutex_unlock(&volume->read_threads_mutex);
		for (i = 0; i < volume->read_thread_count; i++)
			vdo_join_threads(volume->reader_threads[i]);
		vdo_free(volume->reader_threads);
		volume->reader_threads = NULL;
	}

	/* Must destroy the client AFTER freeing the cached pages. */
	uninitialize_page_cache(&volume->page_cache);
	uds_free_sparse_cache(volume->sparse_cache);
	if (volume->client != NULL)
		dm_bufio_client_destroy(vdo_forget(volume->client));

	uds_free_index_page_map(volume->index_page_map);
	uds_free_radix_sorter(volume->radix_sorter);
	vdo_free(volume->geometry);
	vdo_free(volume->record_pointers);
	vdo_free(volume);
}