xref: /linux/drivers/md/dm-cache-metadata.c (revision 5a32083d03fb543f63489b2946c4948398579ba0)
1 /*
2  * Copyright (C) 2012 Red Hat, Inc.
3  *
4  * This file is released under the GPL.
5  */
6 
7 #include "dm-cache-metadata.h"
8 
9 #include "persistent-data/dm-array.h"
10 #include "persistent-data/dm-bitset.h"
11 #include "persistent-data/dm-space-map.h"
12 #include "persistent-data/dm-space-map-disk.h"
13 #include "persistent-data/dm-transaction-manager.h"
14 
15 #include <linux/device-mapper.h>
16 
17 /*----------------------------------------------------------------*/
18 
19 #define DM_MSG_PREFIX   "cache metadata"
20 
21 #define CACHE_SUPERBLOCK_MAGIC 06142003
22 #define CACHE_SUPERBLOCK_LOCATION 0
23 
24 /*
25  * defines a range of metadata versions that this module can handle.
26  */
27 #define MIN_CACHE_VERSION 1
28 #define MAX_CACHE_VERSION 1
29 
30 #define CACHE_METADATA_CACHE_SIZE 64
31 
32 /*
33  *  3 for btree insert +
34  *  2 for btree lookup used within space map
35  */
36 #define CACHE_MAX_CONCURRENT_LOCKS 5
37 #define SPACE_MAP_ROOT_SIZE 128
38 
39 enum superblock_flag_bits {
40 	/* for spotting crashes that would invalidate the dirty bitset */
41 	CLEAN_SHUTDOWN,
42 };
43 
44 /*
45  * Each mapping from cache block -> origin block carries a set of flags.
46  */
47 enum mapping_bits {
48 	/*
49 	 * A valid mapping.  Because we're using an array we clear this
50 	 * flag for an non existant mapping.
51 	 */
52 	M_VALID = 1,
53 
54 	/*
55 	 * The data on the cache is different from that on the origin.
56 	 */
57 	M_DIRTY = 2
58 };
59 
60 struct cache_disk_superblock {
61 	__le32 csum;
62 	__le32 flags;
63 	__le64 blocknr;
64 
65 	__u8 uuid[16];
66 	__le64 magic;
67 	__le32 version;
68 
69 	__u8 policy_name[CACHE_POLICY_NAME_SIZE];
70 	__le32 policy_hint_size;
71 
72 	__u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
73 	__le64 mapping_root;
74 	__le64 hint_root;
75 
76 	__le64 discard_root;
77 	__le64 discard_block_size;
78 	__le64 discard_nr_blocks;
79 
80 	__le32 data_block_size;
81 	__le32 metadata_block_size;
82 	__le32 cache_blocks;
83 
84 	__le32 compat_flags;
85 	__le32 compat_ro_flags;
86 	__le32 incompat_flags;
87 
88 	__le32 read_hits;
89 	__le32 read_misses;
90 	__le32 write_hits;
91 	__le32 write_misses;
92 
93 	__le32 policy_version[CACHE_POLICY_VERSION_SIZE];
94 } __packed;
95 
96 struct dm_cache_metadata {
97 	struct block_device *bdev;
98 	struct dm_block_manager *bm;
99 	struct dm_space_map *metadata_sm;
100 	struct dm_transaction_manager *tm;
101 
102 	struct dm_array_info info;
103 	struct dm_array_info hint_info;
104 	struct dm_disk_bitset discard_info;
105 
106 	struct rw_semaphore root_lock;
107 	dm_block_t root;
108 	dm_block_t hint_root;
109 	dm_block_t discard_root;
110 
111 	sector_t discard_block_size;
112 	dm_oblock_t discard_nr_blocks;
113 
114 	sector_t data_block_size;
115 	dm_cblock_t cache_blocks;
116 	bool changed:1;
117 	bool clean_when_opened:1;
118 
119 	char policy_name[CACHE_POLICY_NAME_SIZE];
120 	unsigned policy_version[CACHE_POLICY_VERSION_SIZE];
121 	size_t policy_hint_size;
122 	struct dm_cache_statistics stats;
123 
124 	/*
125 	 * Reading the space map root can fail, so we read it into this
126 	 * buffer before the superblock is locked and updated.
127 	 */
128 	__u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
129 };
130 
131 /*-------------------------------------------------------------------
132  * superblock validator
133  *-----------------------------------------------------------------*/
134 
135 #define SUPERBLOCK_CSUM_XOR 9031977
136 
137 static void sb_prepare_for_write(struct dm_block_validator *v,
138 				 struct dm_block *b,
139 				 size_t sb_block_size)
140 {
141 	struct cache_disk_superblock *disk_super = dm_block_data(b);
142 
143 	disk_super->blocknr = cpu_to_le64(dm_block_location(b));
144 	disk_super->csum = cpu_to_le32(dm_bm_checksum(&disk_super->flags,
145 						      sb_block_size - sizeof(__le32),
146 						      SUPERBLOCK_CSUM_XOR));
147 }
148 
149 static int check_metadata_version(struct cache_disk_superblock *disk_super)
150 {
151 	uint32_t metadata_version = le32_to_cpu(disk_super->version);
152 	if (metadata_version < MIN_CACHE_VERSION || metadata_version > MAX_CACHE_VERSION) {
153 		DMERR("Cache metadata version %u found, but only versions between %u and %u supported.",
154 		      metadata_version, MIN_CACHE_VERSION, MAX_CACHE_VERSION);
155 		return -EINVAL;
156 	}
157 
158 	return 0;
159 }
160 
161 static int sb_check(struct dm_block_validator *v,
162 		    struct dm_block *b,
163 		    size_t sb_block_size)
164 {
165 	struct cache_disk_superblock *disk_super = dm_block_data(b);
166 	__le32 csum_le;
167 
168 	if (dm_block_location(b) != le64_to_cpu(disk_super->blocknr)) {
169 		DMERR("sb_check failed: blocknr %llu: wanted %llu",
170 		      le64_to_cpu(disk_super->blocknr),
171 		      (unsigned long long)dm_block_location(b));
172 		return -ENOTBLK;
173 	}
174 
175 	if (le64_to_cpu(disk_super->magic) != CACHE_SUPERBLOCK_MAGIC) {
176 		DMERR("sb_check failed: magic %llu: wanted %llu",
177 		      le64_to_cpu(disk_super->magic),
178 		      (unsigned long long)CACHE_SUPERBLOCK_MAGIC);
179 		return -EILSEQ;
180 	}
181 
182 	csum_le = cpu_to_le32(dm_bm_checksum(&disk_super->flags,
183 					     sb_block_size - sizeof(__le32),
184 					     SUPERBLOCK_CSUM_XOR));
185 	if (csum_le != disk_super->csum) {
186 		DMERR("sb_check failed: csum %u: wanted %u",
187 		      le32_to_cpu(csum_le), le32_to_cpu(disk_super->csum));
188 		return -EILSEQ;
189 	}
190 
191 	return check_metadata_version(disk_super);
192 }
193 
194 static struct dm_block_validator sb_validator = {
195 	.name = "superblock",
196 	.prepare_for_write = sb_prepare_for_write,
197 	.check = sb_check
198 };
199 
200 /*----------------------------------------------------------------*/
201 
202 static int superblock_read_lock(struct dm_cache_metadata *cmd,
203 				struct dm_block **sblock)
204 {
205 	return dm_bm_read_lock(cmd->bm, CACHE_SUPERBLOCK_LOCATION,
206 			       &sb_validator, sblock);
207 }
208 
209 static int superblock_lock_zero(struct dm_cache_metadata *cmd,
210 				struct dm_block **sblock)
211 {
212 	return dm_bm_write_lock_zero(cmd->bm, CACHE_SUPERBLOCK_LOCATION,
213 				     &sb_validator, sblock);
214 }
215 
216 static int superblock_lock(struct dm_cache_metadata *cmd,
217 			   struct dm_block **sblock)
218 {
219 	return dm_bm_write_lock(cmd->bm, CACHE_SUPERBLOCK_LOCATION,
220 				&sb_validator, sblock);
221 }
222 
223 /*----------------------------------------------------------------*/
224 
225 static int __superblock_all_zeroes(struct dm_block_manager *bm, bool *result)
226 {
227 	int r;
228 	unsigned i;
229 	struct dm_block *b;
230 	__le64 *data_le, zero = cpu_to_le64(0);
231 	unsigned sb_block_size = dm_bm_block_size(bm) / sizeof(__le64);
232 
233 	/*
234 	 * We can't use a validator here - it may be all zeroes.
235 	 */
236 	r = dm_bm_read_lock(bm, CACHE_SUPERBLOCK_LOCATION, NULL, &b);
237 	if (r)
238 		return r;
239 
240 	data_le = dm_block_data(b);
241 	*result = true;
242 	for (i = 0; i < sb_block_size; i++) {
243 		if (data_le[i] != zero) {
244 			*result = false;
245 			break;
246 		}
247 	}
248 
249 	return dm_bm_unlock(b);
250 }
251 
252 static void __setup_mapping_info(struct dm_cache_metadata *cmd)
253 {
254 	struct dm_btree_value_type vt;
255 
256 	vt.context = NULL;
257 	vt.size = sizeof(__le64);
258 	vt.inc = NULL;
259 	vt.dec = NULL;
260 	vt.equal = NULL;
261 	dm_array_info_init(&cmd->info, cmd->tm, &vt);
262 
263 	if (cmd->policy_hint_size) {
264 		vt.size = sizeof(__le32);
265 		dm_array_info_init(&cmd->hint_info, cmd->tm, &vt);
266 	}
267 }
268 
269 static int __save_sm_root(struct dm_cache_metadata *cmd)
270 {
271 	int r;
272 	size_t metadata_len;
273 
274 	r = dm_sm_root_size(cmd->metadata_sm, &metadata_len);
275 	if (r < 0)
276 		return r;
277 
278 	return dm_sm_copy_root(cmd->metadata_sm, &cmd->metadata_space_map_root,
279 			       metadata_len);
280 }
281 
282 static void __copy_sm_root(struct dm_cache_metadata *cmd,
283 			   struct cache_disk_superblock *disk_super)
284 {
285 	memcpy(&disk_super->metadata_space_map_root,
286 	       &cmd->metadata_space_map_root,
287 	       sizeof(cmd->metadata_space_map_root));
288 }
289 
290 static int __write_initial_superblock(struct dm_cache_metadata *cmd)
291 {
292 	int r;
293 	struct dm_block *sblock;
294 	struct cache_disk_superblock *disk_super;
295 	sector_t bdev_size = i_size_read(cmd->bdev->bd_inode) >> SECTOR_SHIFT;
296 
297 	/* FIXME: see if we can lose the max sectors limit */
298 	if (bdev_size > DM_CACHE_METADATA_MAX_SECTORS)
299 		bdev_size = DM_CACHE_METADATA_MAX_SECTORS;
300 
301 	r = dm_tm_pre_commit(cmd->tm);
302 	if (r < 0)
303 		return r;
304 
305 	/*
306 	 * dm_sm_copy_root() can fail.  So we need to do it before we start
307 	 * updating the superblock.
308 	 */
309 	r = __save_sm_root(cmd);
310 	if (r)
311 		return r;
312 
313 	r = superblock_lock_zero(cmd, &sblock);
314 	if (r)
315 		return r;
316 
317 	disk_super = dm_block_data(sblock);
318 	disk_super->flags = 0;
319 	memset(disk_super->uuid, 0, sizeof(disk_super->uuid));
320 	disk_super->magic = cpu_to_le64(CACHE_SUPERBLOCK_MAGIC);
321 	disk_super->version = cpu_to_le32(MAX_CACHE_VERSION);
322 	memset(disk_super->policy_name, 0, sizeof(disk_super->policy_name));
323 	memset(disk_super->policy_version, 0, sizeof(disk_super->policy_version));
324 	disk_super->policy_hint_size = 0;
325 
326 	__copy_sm_root(cmd, disk_super);
327 
328 	disk_super->mapping_root = cpu_to_le64(cmd->root);
329 	disk_super->hint_root = cpu_to_le64(cmd->hint_root);
330 	disk_super->discard_root = cpu_to_le64(cmd->discard_root);
331 	disk_super->discard_block_size = cpu_to_le64(cmd->discard_block_size);
332 	disk_super->discard_nr_blocks = cpu_to_le64(from_oblock(cmd->discard_nr_blocks));
333 	disk_super->metadata_block_size = cpu_to_le32(DM_CACHE_METADATA_BLOCK_SIZE >> SECTOR_SHIFT);
334 	disk_super->data_block_size = cpu_to_le32(cmd->data_block_size);
335 	disk_super->cache_blocks = cpu_to_le32(0);
336 
337 	disk_super->read_hits = cpu_to_le32(0);
338 	disk_super->read_misses = cpu_to_le32(0);
339 	disk_super->write_hits = cpu_to_le32(0);
340 	disk_super->write_misses = cpu_to_le32(0);
341 
342 	return dm_tm_commit(cmd->tm, sblock);
343 }
344 
345 static int __format_metadata(struct dm_cache_metadata *cmd)
346 {
347 	int r;
348 
349 	r = dm_tm_create_with_sm(cmd->bm, CACHE_SUPERBLOCK_LOCATION,
350 				 &cmd->tm, &cmd->metadata_sm);
351 	if (r < 0) {
352 		DMERR("tm_create_with_sm failed");
353 		return r;
354 	}
355 
356 	__setup_mapping_info(cmd);
357 
358 	r = dm_array_empty(&cmd->info, &cmd->root);
359 	if (r < 0)
360 		goto bad;
361 
362 	dm_disk_bitset_init(cmd->tm, &cmd->discard_info);
363 
364 	r = dm_bitset_empty(&cmd->discard_info, &cmd->discard_root);
365 	if (r < 0)
366 		goto bad;
367 
368 	cmd->discard_block_size = 0;
369 	cmd->discard_nr_blocks = 0;
370 
371 	r = __write_initial_superblock(cmd);
372 	if (r)
373 		goto bad;
374 
375 	cmd->clean_when_opened = true;
376 	return 0;
377 
378 bad:
379 	dm_tm_destroy(cmd->tm);
380 	dm_sm_destroy(cmd->metadata_sm);
381 
382 	return r;
383 }
384 
385 static int __check_incompat_features(struct cache_disk_superblock *disk_super,
386 				     struct dm_cache_metadata *cmd)
387 {
388 	uint32_t features;
389 
390 	features = le32_to_cpu(disk_super->incompat_flags) & ~DM_CACHE_FEATURE_INCOMPAT_SUPP;
391 	if (features) {
392 		DMERR("could not access metadata due to unsupported optional features (%lx).",
393 		      (unsigned long)features);
394 		return -EINVAL;
395 	}
396 
397 	/*
398 	 * Check for read-only metadata to skip the following RDWR checks.
399 	 */
400 	if (get_disk_ro(cmd->bdev->bd_disk))
401 		return 0;
402 
403 	features = le32_to_cpu(disk_super->compat_ro_flags) & ~DM_CACHE_FEATURE_COMPAT_RO_SUPP;
404 	if (features) {
405 		DMERR("could not access metadata RDWR due to unsupported optional features (%lx).",
406 		      (unsigned long)features);
407 		return -EINVAL;
408 	}
409 
410 	return 0;
411 }
412 
413 static int __open_metadata(struct dm_cache_metadata *cmd)
414 {
415 	int r;
416 	struct dm_block *sblock;
417 	struct cache_disk_superblock *disk_super;
418 	unsigned long sb_flags;
419 
420 	r = superblock_read_lock(cmd, &sblock);
421 	if (r < 0) {
422 		DMERR("couldn't read lock superblock");
423 		return r;
424 	}
425 
426 	disk_super = dm_block_data(sblock);
427 
428 	r = __check_incompat_features(disk_super, cmd);
429 	if (r < 0)
430 		goto bad;
431 
432 	r = dm_tm_open_with_sm(cmd->bm, CACHE_SUPERBLOCK_LOCATION,
433 			       disk_super->metadata_space_map_root,
434 			       sizeof(disk_super->metadata_space_map_root),
435 			       &cmd->tm, &cmd->metadata_sm);
436 	if (r < 0) {
437 		DMERR("tm_open_with_sm failed");
438 		goto bad;
439 	}
440 
441 	__setup_mapping_info(cmd);
442 	dm_disk_bitset_init(cmd->tm, &cmd->discard_info);
443 	sb_flags = le32_to_cpu(disk_super->flags);
444 	cmd->clean_when_opened = test_bit(CLEAN_SHUTDOWN, &sb_flags);
445 	return dm_bm_unlock(sblock);
446 
447 bad:
448 	dm_bm_unlock(sblock);
449 	return r;
450 }
451 
452 static int __open_or_format_metadata(struct dm_cache_metadata *cmd,
453 				     bool format_device)
454 {
455 	int r;
456 	bool unformatted = false;
457 
458 	r = __superblock_all_zeroes(cmd->bm, &unformatted);
459 	if (r)
460 		return r;
461 
462 	if (unformatted)
463 		return format_device ? __format_metadata(cmd) : -EPERM;
464 
465 	return __open_metadata(cmd);
466 }
467 
468 static int __create_persistent_data_objects(struct dm_cache_metadata *cmd,
469 					    bool may_format_device)
470 {
471 	int r;
472 	cmd->bm = dm_block_manager_create(cmd->bdev, DM_CACHE_METADATA_BLOCK_SIZE,
473 					  CACHE_METADATA_CACHE_SIZE,
474 					  CACHE_MAX_CONCURRENT_LOCKS);
475 	if (IS_ERR(cmd->bm)) {
476 		DMERR("could not create block manager");
477 		return PTR_ERR(cmd->bm);
478 	}
479 
480 	r = __open_or_format_metadata(cmd, may_format_device);
481 	if (r)
482 		dm_block_manager_destroy(cmd->bm);
483 
484 	return r;
485 }
486 
487 static void __destroy_persistent_data_objects(struct dm_cache_metadata *cmd)
488 {
489 	dm_sm_destroy(cmd->metadata_sm);
490 	dm_tm_destroy(cmd->tm);
491 	dm_block_manager_destroy(cmd->bm);
492 }
493 
494 typedef unsigned long (*flags_mutator)(unsigned long);
495 
496 static void update_flags(struct cache_disk_superblock *disk_super,
497 			 flags_mutator mutator)
498 {
499 	uint32_t sb_flags = mutator(le32_to_cpu(disk_super->flags));
500 	disk_super->flags = cpu_to_le32(sb_flags);
501 }
502 
503 static unsigned long set_clean_shutdown(unsigned long flags)
504 {
505 	set_bit(CLEAN_SHUTDOWN, &flags);
506 	return flags;
507 }
508 
509 static unsigned long clear_clean_shutdown(unsigned long flags)
510 {
511 	clear_bit(CLEAN_SHUTDOWN, &flags);
512 	return flags;
513 }
514 
515 static void read_superblock_fields(struct dm_cache_metadata *cmd,
516 				   struct cache_disk_superblock *disk_super)
517 {
518 	cmd->root = le64_to_cpu(disk_super->mapping_root);
519 	cmd->hint_root = le64_to_cpu(disk_super->hint_root);
520 	cmd->discard_root = le64_to_cpu(disk_super->discard_root);
521 	cmd->discard_block_size = le64_to_cpu(disk_super->discard_block_size);
522 	cmd->discard_nr_blocks = to_oblock(le64_to_cpu(disk_super->discard_nr_blocks));
523 	cmd->data_block_size = le32_to_cpu(disk_super->data_block_size);
524 	cmd->cache_blocks = to_cblock(le32_to_cpu(disk_super->cache_blocks));
525 	strncpy(cmd->policy_name, disk_super->policy_name, sizeof(cmd->policy_name));
526 	cmd->policy_version[0] = le32_to_cpu(disk_super->policy_version[0]);
527 	cmd->policy_version[1] = le32_to_cpu(disk_super->policy_version[1]);
528 	cmd->policy_version[2] = le32_to_cpu(disk_super->policy_version[2]);
529 	cmd->policy_hint_size = le32_to_cpu(disk_super->policy_hint_size);
530 
531 	cmd->stats.read_hits = le32_to_cpu(disk_super->read_hits);
532 	cmd->stats.read_misses = le32_to_cpu(disk_super->read_misses);
533 	cmd->stats.write_hits = le32_to_cpu(disk_super->write_hits);
534 	cmd->stats.write_misses = le32_to_cpu(disk_super->write_misses);
535 
536 	cmd->changed = false;
537 }
538 
539 /*
540  * The mutator updates the superblock flags.
541  */
542 static int __begin_transaction_flags(struct dm_cache_metadata *cmd,
543 				     flags_mutator mutator)
544 {
545 	int r;
546 	struct cache_disk_superblock *disk_super;
547 	struct dm_block *sblock;
548 
549 	r = superblock_lock(cmd, &sblock);
550 	if (r)
551 		return r;
552 
553 	disk_super = dm_block_data(sblock);
554 	update_flags(disk_super, mutator);
555 	read_superblock_fields(cmd, disk_super);
556 	dm_bm_unlock(sblock);
557 
558 	return dm_bm_flush(cmd->bm);
559 }
560 
561 static int __begin_transaction(struct dm_cache_metadata *cmd)
562 {
563 	int r;
564 	struct cache_disk_superblock *disk_super;
565 	struct dm_block *sblock;
566 
567 	/*
568 	 * We re-read the superblock every time.  Shouldn't need to do this
569 	 * really.
570 	 */
571 	r = superblock_read_lock(cmd, &sblock);
572 	if (r)
573 		return r;
574 
575 	disk_super = dm_block_data(sblock);
576 	read_superblock_fields(cmd, disk_super);
577 	dm_bm_unlock(sblock);
578 
579 	return 0;
580 }
581 
582 static int __commit_transaction(struct dm_cache_metadata *cmd,
583 				flags_mutator mutator)
584 {
585 	int r;
586 	struct cache_disk_superblock *disk_super;
587 	struct dm_block *sblock;
588 
589 	/*
590 	 * We need to know if the cache_disk_superblock exceeds a 512-byte sector.
591 	 */
592 	BUILD_BUG_ON(sizeof(struct cache_disk_superblock) > 512);
593 
594 	r = dm_bitset_flush(&cmd->discard_info, cmd->discard_root,
595 			    &cmd->discard_root);
596 	if (r)
597 		return r;
598 
599 	r = dm_tm_pre_commit(cmd->tm);
600 	if (r < 0)
601 		return r;
602 
603 	r = __save_sm_root(cmd);
604 	if (r)
605 		return r;
606 
607 	r = superblock_lock(cmd, &sblock);
608 	if (r)
609 		return r;
610 
611 	disk_super = dm_block_data(sblock);
612 
613 	if (mutator)
614 		update_flags(disk_super, mutator);
615 
616 	disk_super->mapping_root = cpu_to_le64(cmd->root);
617 	disk_super->hint_root = cpu_to_le64(cmd->hint_root);
618 	disk_super->discard_root = cpu_to_le64(cmd->discard_root);
619 	disk_super->discard_block_size = cpu_to_le64(cmd->discard_block_size);
620 	disk_super->discard_nr_blocks = cpu_to_le64(from_oblock(cmd->discard_nr_blocks));
621 	disk_super->cache_blocks = cpu_to_le32(from_cblock(cmd->cache_blocks));
622 	strncpy(disk_super->policy_name, cmd->policy_name, sizeof(disk_super->policy_name));
623 	disk_super->policy_version[0] = cpu_to_le32(cmd->policy_version[0]);
624 	disk_super->policy_version[1] = cpu_to_le32(cmd->policy_version[1]);
625 	disk_super->policy_version[2] = cpu_to_le32(cmd->policy_version[2]);
626 
627 	disk_super->read_hits = cpu_to_le32(cmd->stats.read_hits);
628 	disk_super->read_misses = cpu_to_le32(cmd->stats.read_misses);
629 	disk_super->write_hits = cpu_to_le32(cmd->stats.write_hits);
630 	disk_super->write_misses = cpu_to_le32(cmd->stats.write_misses);
631 	__copy_sm_root(cmd, disk_super);
632 
633 	return dm_tm_commit(cmd->tm, sblock);
634 }
635 
636 /*----------------------------------------------------------------*/
637 
638 /*
639  * The mappings are held in a dm-array that has 64-bit values stored in
640  * little-endian format.  The index is the cblock, the high 48bits of the
641  * value are the oblock and the low 16 bit the flags.
642  */
643 #define FLAGS_MASK ((1 << 16) - 1)
644 
645 static __le64 pack_value(dm_oblock_t block, unsigned flags)
646 {
647 	uint64_t value = from_oblock(block);
648 	value <<= 16;
649 	value = value | (flags & FLAGS_MASK);
650 	return cpu_to_le64(value);
651 }
652 
653 static void unpack_value(__le64 value_le, dm_oblock_t *block, unsigned *flags)
654 {
655 	uint64_t value = le64_to_cpu(value_le);
656 	uint64_t b = value >> 16;
657 	*block = to_oblock(b);
658 	*flags = value & FLAGS_MASK;
659 }
660 
661 /*----------------------------------------------------------------*/
662 
663 struct dm_cache_metadata *dm_cache_metadata_open(struct block_device *bdev,
664 						 sector_t data_block_size,
665 						 bool may_format_device,
666 						 size_t policy_hint_size)
667 {
668 	int r;
669 	struct dm_cache_metadata *cmd;
670 
671 	cmd = kzalloc(sizeof(*cmd), GFP_KERNEL);
672 	if (!cmd) {
673 		DMERR("could not allocate metadata struct");
674 		return NULL;
675 	}
676 
677 	init_rwsem(&cmd->root_lock);
678 	cmd->bdev = bdev;
679 	cmd->data_block_size = data_block_size;
680 	cmd->cache_blocks = 0;
681 	cmd->policy_hint_size = policy_hint_size;
682 	cmd->changed = true;
683 
684 	r = __create_persistent_data_objects(cmd, may_format_device);
685 	if (r) {
686 		kfree(cmd);
687 		return ERR_PTR(r);
688 	}
689 
690 	r = __begin_transaction_flags(cmd, clear_clean_shutdown);
691 	if (r < 0) {
692 		dm_cache_metadata_close(cmd);
693 		return ERR_PTR(r);
694 	}
695 
696 	return cmd;
697 }
698 
699 void dm_cache_metadata_close(struct dm_cache_metadata *cmd)
700 {
701 	__destroy_persistent_data_objects(cmd);
702 	kfree(cmd);
703 }
704 
705 /*
706  * Checks that the given cache block is either unmapped or clean.
707  */
708 static int block_unmapped_or_clean(struct dm_cache_metadata *cmd, dm_cblock_t b,
709 				   bool *result)
710 {
711 	int r;
712 	__le64 value;
713 	dm_oblock_t ob;
714 	unsigned flags;
715 
716 	r = dm_array_get_value(&cmd->info, cmd->root, from_cblock(b), &value);
717 	if (r) {
718 		DMERR("block_unmapped_or_clean failed");
719 		return r;
720 	}
721 
722 	unpack_value(value, &ob, &flags);
723 	*result = !((flags & M_VALID) && (flags & M_DIRTY));
724 
725 	return 0;
726 }
727 
728 static int blocks_are_unmapped_or_clean(struct dm_cache_metadata *cmd,
729 					dm_cblock_t begin, dm_cblock_t end,
730 					bool *result)
731 {
732 	int r;
733 	*result = true;
734 
735 	while (begin != end) {
736 		r = block_unmapped_or_clean(cmd, begin, result);
737 		if (r)
738 			return r;
739 
740 		if (!*result) {
741 			DMERR("cache block %llu is dirty",
742 			      (unsigned long long) from_cblock(begin));
743 			return 0;
744 		}
745 
746 		begin = to_cblock(from_cblock(begin) + 1);
747 	}
748 
749 	return 0;
750 }
751 
752 int dm_cache_resize(struct dm_cache_metadata *cmd, dm_cblock_t new_cache_size)
753 {
754 	int r;
755 	bool clean;
756 	__le64 null_mapping = pack_value(0, 0);
757 
758 	down_write(&cmd->root_lock);
759 	__dm_bless_for_disk(&null_mapping);
760 
761 	if (from_cblock(new_cache_size) < from_cblock(cmd->cache_blocks)) {
762 		r = blocks_are_unmapped_or_clean(cmd, new_cache_size, cmd->cache_blocks, &clean);
763 		if (r) {
764 			__dm_unbless_for_disk(&null_mapping);
765 			goto out;
766 		}
767 
768 		if (!clean) {
769 			DMERR("unable to shrink cache due to dirty blocks");
770 			r = -EINVAL;
771 			__dm_unbless_for_disk(&null_mapping);
772 			goto out;
773 		}
774 	}
775 
776 	r = dm_array_resize(&cmd->info, cmd->root, from_cblock(cmd->cache_blocks),
777 			    from_cblock(new_cache_size),
778 			    &null_mapping, &cmd->root);
779 	if (!r)
780 		cmd->cache_blocks = new_cache_size;
781 	cmd->changed = true;
782 
783 out:
784 	up_write(&cmd->root_lock);
785 
786 	return r;
787 }
788 
789 int dm_cache_discard_bitset_resize(struct dm_cache_metadata *cmd,
790 				   sector_t discard_block_size,
791 				   dm_oblock_t new_nr_entries)
792 {
793 	int r;
794 
795 	down_write(&cmd->root_lock);
796 	r = dm_bitset_resize(&cmd->discard_info,
797 			     cmd->discard_root,
798 			     from_oblock(cmd->discard_nr_blocks),
799 			     from_oblock(new_nr_entries),
800 			     false, &cmd->discard_root);
801 	if (!r) {
802 		cmd->discard_block_size = discard_block_size;
803 		cmd->discard_nr_blocks = new_nr_entries;
804 	}
805 
806 	cmd->changed = true;
807 	up_write(&cmd->root_lock);
808 
809 	return r;
810 }
811 
812 static int __set_discard(struct dm_cache_metadata *cmd, dm_oblock_t b)
813 {
814 	return dm_bitset_set_bit(&cmd->discard_info, cmd->discard_root,
815 				 from_oblock(b), &cmd->discard_root);
816 }
817 
818 static int __clear_discard(struct dm_cache_metadata *cmd, dm_oblock_t b)
819 {
820 	return dm_bitset_clear_bit(&cmd->discard_info, cmd->discard_root,
821 				   from_oblock(b), &cmd->discard_root);
822 }
823 
824 static int __is_discarded(struct dm_cache_metadata *cmd, dm_oblock_t b,
825 			  bool *is_discarded)
826 {
827 	return dm_bitset_test_bit(&cmd->discard_info, cmd->discard_root,
828 				  from_oblock(b), &cmd->discard_root,
829 				  is_discarded);
830 }
831 
832 static int __discard(struct dm_cache_metadata *cmd,
833 		     dm_oblock_t dblock, bool discard)
834 {
835 	int r;
836 
837 	r = (discard ? __set_discard : __clear_discard)(cmd, dblock);
838 	if (r)
839 		return r;
840 
841 	cmd->changed = true;
842 	return 0;
843 }
844 
845 int dm_cache_set_discard(struct dm_cache_metadata *cmd,
846 			 dm_oblock_t dblock, bool discard)
847 {
848 	int r;
849 
850 	down_write(&cmd->root_lock);
851 	r = __discard(cmd, dblock, discard);
852 	up_write(&cmd->root_lock);
853 
854 	return r;
855 }
856 
857 static int __load_discards(struct dm_cache_metadata *cmd,
858 			   load_discard_fn fn, void *context)
859 {
860 	int r = 0;
861 	dm_block_t b;
862 	bool discard;
863 
864 	for (b = 0; b < from_oblock(cmd->discard_nr_blocks); b++) {
865 		dm_oblock_t dblock = to_oblock(b);
866 
867 		if (cmd->clean_when_opened) {
868 			r = __is_discarded(cmd, dblock, &discard);
869 			if (r)
870 				return r;
871 		} else
872 			discard = false;
873 
874 		r = fn(context, cmd->discard_block_size, dblock, discard);
875 		if (r)
876 			break;
877 	}
878 
879 	return r;
880 }
881 
882 int dm_cache_load_discards(struct dm_cache_metadata *cmd,
883 			   load_discard_fn fn, void *context)
884 {
885 	int r;
886 
887 	down_read(&cmd->root_lock);
888 	r = __load_discards(cmd, fn, context);
889 	up_read(&cmd->root_lock);
890 
891 	return r;
892 }
893 
894 dm_cblock_t dm_cache_size(struct dm_cache_metadata *cmd)
895 {
896 	dm_cblock_t r;
897 
898 	down_read(&cmd->root_lock);
899 	r = cmd->cache_blocks;
900 	up_read(&cmd->root_lock);
901 
902 	return r;
903 }
904 
905 static int __remove(struct dm_cache_metadata *cmd, dm_cblock_t cblock)
906 {
907 	int r;
908 	__le64 value = pack_value(0, 0);
909 
910 	__dm_bless_for_disk(&value);
911 	r = dm_array_set_value(&cmd->info, cmd->root, from_cblock(cblock),
912 			       &value, &cmd->root);
913 	if (r)
914 		return r;
915 
916 	cmd->changed = true;
917 	return 0;
918 }
919 
920 int dm_cache_remove_mapping(struct dm_cache_metadata *cmd, dm_cblock_t cblock)
921 {
922 	int r;
923 
924 	down_write(&cmd->root_lock);
925 	r = __remove(cmd, cblock);
926 	up_write(&cmd->root_lock);
927 
928 	return r;
929 }
930 
931 static int __insert(struct dm_cache_metadata *cmd,
932 		    dm_cblock_t cblock, dm_oblock_t oblock)
933 {
934 	int r;
935 	__le64 value = pack_value(oblock, M_VALID);
936 	__dm_bless_for_disk(&value);
937 
938 	r = dm_array_set_value(&cmd->info, cmd->root, from_cblock(cblock),
939 			       &value, &cmd->root);
940 	if (r)
941 		return r;
942 
943 	cmd->changed = true;
944 	return 0;
945 }
946 
947 int dm_cache_insert_mapping(struct dm_cache_metadata *cmd,
948 			    dm_cblock_t cblock, dm_oblock_t oblock)
949 {
950 	int r;
951 
952 	down_write(&cmd->root_lock);
953 	r = __insert(cmd, cblock, oblock);
954 	up_write(&cmd->root_lock);
955 
956 	return r;
957 }
958 
959 struct thunk {
960 	load_mapping_fn fn;
961 	void *context;
962 
963 	struct dm_cache_metadata *cmd;
964 	bool respect_dirty_flags;
965 	bool hints_valid;
966 };
967 
968 static bool policy_unchanged(struct dm_cache_metadata *cmd,
969 			     struct dm_cache_policy *policy)
970 {
971 	const char *policy_name = dm_cache_policy_get_name(policy);
972 	const unsigned *policy_version = dm_cache_policy_get_version(policy);
973 	size_t policy_hint_size = dm_cache_policy_get_hint_size(policy);
974 
975 	/*
976 	 * Ensure policy names match.
977 	 */
978 	if (strncmp(cmd->policy_name, policy_name, sizeof(cmd->policy_name)))
979 		return false;
980 
981 	/*
982 	 * Ensure policy major versions match.
983 	 */
984 	if (cmd->policy_version[0] != policy_version[0])
985 		return false;
986 
987 	/*
988 	 * Ensure policy hint sizes match.
989 	 */
990 	if (cmd->policy_hint_size != policy_hint_size)
991 		return false;
992 
993 	return true;
994 }
995 
996 static bool hints_array_initialized(struct dm_cache_metadata *cmd)
997 {
998 	return cmd->hint_root && cmd->policy_hint_size;
999 }
1000 
1001 static bool hints_array_available(struct dm_cache_metadata *cmd,
1002 				  struct dm_cache_policy *policy)
1003 {
1004 	return cmd->clean_when_opened && policy_unchanged(cmd, policy) &&
1005 		hints_array_initialized(cmd);
1006 }
1007 
1008 static int __load_mapping(void *context, uint64_t cblock, void *leaf)
1009 {
1010 	int r = 0;
1011 	bool dirty;
1012 	__le64 value;
1013 	__le32 hint_value = 0;
1014 	dm_oblock_t oblock;
1015 	unsigned flags;
1016 	struct thunk *thunk = context;
1017 	struct dm_cache_metadata *cmd = thunk->cmd;
1018 
1019 	memcpy(&value, leaf, sizeof(value));
1020 	unpack_value(value, &oblock, &flags);
1021 
1022 	if (flags & M_VALID) {
1023 		if (thunk->hints_valid) {
1024 			r = dm_array_get_value(&cmd->hint_info, cmd->hint_root,
1025 					       cblock, &hint_value);
1026 			if (r && r != -ENODATA)
1027 				return r;
1028 		}
1029 
1030 		dirty = thunk->respect_dirty_flags ? (flags & M_DIRTY) : true;
1031 		r = thunk->fn(thunk->context, oblock, to_cblock(cblock),
1032 			      dirty, le32_to_cpu(hint_value), thunk->hints_valid);
1033 	}
1034 
1035 	return r;
1036 }
1037 
1038 static int __load_mappings(struct dm_cache_metadata *cmd,
1039 			   struct dm_cache_policy *policy,
1040 			   load_mapping_fn fn, void *context)
1041 {
1042 	struct thunk thunk;
1043 
1044 	thunk.fn = fn;
1045 	thunk.context = context;
1046 
1047 	thunk.cmd = cmd;
1048 	thunk.respect_dirty_flags = cmd->clean_when_opened;
1049 	thunk.hints_valid = hints_array_available(cmd, policy);
1050 
1051 	return dm_array_walk(&cmd->info, cmd->root, __load_mapping, &thunk);
1052 }
1053 
1054 int dm_cache_load_mappings(struct dm_cache_metadata *cmd,
1055 			   struct dm_cache_policy *policy,
1056 			   load_mapping_fn fn, void *context)
1057 {
1058 	int r;
1059 
1060 	down_read(&cmd->root_lock);
1061 	r = __load_mappings(cmd, policy, fn, context);
1062 	up_read(&cmd->root_lock);
1063 
1064 	return r;
1065 }
1066 
1067 static int __dump_mapping(void *context, uint64_t cblock, void *leaf)
1068 {
1069 	int r = 0;
1070 	__le64 value;
1071 	dm_oblock_t oblock;
1072 	unsigned flags;
1073 
1074 	memcpy(&value, leaf, sizeof(value));
1075 	unpack_value(value, &oblock, &flags);
1076 
1077 	return r;
1078 }
1079 
1080 static int __dump_mappings(struct dm_cache_metadata *cmd)
1081 {
1082 	return dm_array_walk(&cmd->info, cmd->root, __dump_mapping, NULL);
1083 }
1084 
1085 void dm_cache_dump(struct dm_cache_metadata *cmd)
1086 {
1087 	down_read(&cmd->root_lock);
1088 	__dump_mappings(cmd);
1089 	up_read(&cmd->root_lock);
1090 }
1091 
1092 int dm_cache_changed_this_transaction(struct dm_cache_metadata *cmd)
1093 {
1094 	int r;
1095 
1096 	down_read(&cmd->root_lock);
1097 	r = cmd->changed;
1098 	up_read(&cmd->root_lock);
1099 
1100 	return r;
1101 }
1102 
1103 static int __dirty(struct dm_cache_metadata *cmd, dm_cblock_t cblock, bool dirty)
1104 {
1105 	int r;
1106 	unsigned flags;
1107 	dm_oblock_t oblock;
1108 	__le64 value;
1109 
1110 	r = dm_array_get_value(&cmd->info, cmd->root, from_cblock(cblock), &value);
1111 	if (r)
1112 		return r;
1113 
1114 	unpack_value(value, &oblock, &flags);
1115 
1116 	if (((flags & M_DIRTY) && dirty) || (!(flags & M_DIRTY) && !dirty))
1117 		/* nothing to be done */
1118 		return 0;
1119 
1120 	value = pack_value(oblock, (flags & ~M_DIRTY) | (dirty ? M_DIRTY : 0));
1121 	__dm_bless_for_disk(&value);
1122 
1123 	r = dm_array_set_value(&cmd->info, cmd->root, from_cblock(cblock),
1124 			       &value, &cmd->root);
1125 	if (r)
1126 		return r;
1127 
1128 	cmd->changed = true;
1129 	return 0;
1130 
1131 }
1132 
1133 int dm_cache_set_dirty(struct dm_cache_metadata *cmd,
1134 		       dm_cblock_t cblock, bool dirty)
1135 {
1136 	int r;
1137 
1138 	down_write(&cmd->root_lock);
1139 	r = __dirty(cmd, cblock, dirty);
1140 	up_write(&cmd->root_lock);
1141 
1142 	return r;
1143 }
1144 
1145 void dm_cache_metadata_get_stats(struct dm_cache_metadata *cmd,
1146 				 struct dm_cache_statistics *stats)
1147 {
1148 	down_read(&cmd->root_lock);
1149 	*stats = cmd->stats;
1150 	up_read(&cmd->root_lock);
1151 }
1152 
1153 void dm_cache_metadata_set_stats(struct dm_cache_metadata *cmd,
1154 				 struct dm_cache_statistics *stats)
1155 {
1156 	down_write(&cmd->root_lock);
1157 	cmd->stats = *stats;
1158 	up_write(&cmd->root_lock);
1159 }
1160 
1161 int dm_cache_commit(struct dm_cache_metadata *cmd, bool clean_shutdown)
1162 {
1163 	int r;
1164 	flags_mutator mutator = (clean_shutdown ? set_clean_shutdown :
1165 				 clear_clean_shutdown);
1166 
1167 	down_write(&cmd->root_lock);
1168 	r = __commit_transaction(cmd, mutator);
1169 	if (r)
1170 		goto out;
1171 
1172 	r = __begin_transaction(cmd);
1173 
1174 out:
1175 	up_write(&cmd->root_lock);
1176 	return r;
1177 }
1178 
1179 int dm_cache_get_free_metadata_block_count(struct dm_cache_metadata *cmd,
1180 					   dm_block_t *result)
1181 {
1182 	int r = -EINVAL;
1183 
1184 	down_read(&cmd->root_lock);
1185 	r = dm_sm_get_nr_free(cmd->metadata_sm, result);
1186 	up_read(&cmd->root_lock);
1187 
1188 	return r;
1189 }
1190 
1191 int dm_cache_get_metadata_dev_size(struct dm_cache_metadata *cmd,
1192 				   dm_block_t *result)
1193 {
1194 	int r = -EINVAL;
1195 
1196 	down_read(&cmd->root_lock);
1197 	r = dm_sm_get_nr_blocks(cmd->metadata_sm, result);
1198 	up_read(&cmd->root_lock);
1199 
1200 	return r;
1201 }
1202 
1203 /*----------------------------------------------------------------*/
1204 
1205 static int begin_hints(struct dm_cache_metadata *cmd, struct dm_cache_policy *policy)
1206 {
1207 	int r;
1208 	__le32 value;
1209 	size_t hint_size;
1210 	const char *policy_name = dm_cache_policy_get_name(policy);
1211 	const unsigned *policy_version = dm_cache_policy_get_version(policy);
1212 
1213 	if (!policy_name[0] ||
1214 	    (strlen(policy_name) > sizeof(cmd->policy_name) - 1))
1215 		return -EINVAL;
1216 
1217 	if (!policy_unchanged(cmd, policy)) {
1218 		strncpy(cmd->policy_name, policy_name, sizeof(cmd->policy_name));
1219 		memcpy(cmd->policy_version, policy_version, sizeof(cmd->policy_version));
1220 
1221 		hint_size = dm_cache_policy_get_hint_size(policy);
1222 		if (!hint_size)
1223 			return 0; /* short-circuit hints initialization */
1224 		cmd->policy_hint_size = hint_size;
1225 
1226 		if (cmd->hint_root) {
1227 			r = dm_array_del(&cmd->hint_info, cmd->hint_root);
1228 			if (r)
1229 				return r;
1230 		}
1231 
1232 		r = dm_array_empty(&cmd->hint_info, &cmd->hint_root);
1233 		if (r)
1234 			return r;
1235 
1236 		value = cpu_to_le32(0);
1237 		__dm_bless_for_disk(&value);
1238 		r = dm_array_resize(&cmd->hint_info, cmd->hint_root, 0,
1239 				    from_cblock(cmd->cache_blocks),
1240 				    &value, &cmd->hint_root);
1241 		if (r)
1242 			return r;
1243 	}
1244 
1245 	return 0;
1246 }
1247 
1248 int dm_cache_begin_hints(struct dm_cache_metadata *cmd, struct dm_cache_policy *policy)
1249 {
1250 	int r;
1251 
1252 	down_write(&cmd->root_lock);
1253 	r = begin_hints(cmd, policy);
1254 	up_write(&cmd->root_lock);
1255 
1256 	return r;
1257 }
1258 
1259 static int save_hint(struct dm_cache_metadata *cmd, dm_cblock_t cblock,
1260 		     uint32_t hint)
1261 {
1262 	int r;
1263 	__le32 value = cpu_to_le32(hint);
1264 	__dm_bless_for_disk(&value);
1265 
1266 	r = dm_array_set_value(&cmd->hint_info, cmd->hint_root,
1267 			       from_cblock(cblock), &value, &cmd->hint_root);
1268 	cmd->changed = true;
1269 
1270 	return r;
1271 }
1272 
1273 int dm_cache_save_hint(struct dm_cache_metadata *cmd, dm_cblock_t cblock,
1274 		       uint32_t hint)
1275 {
1276 	int r;
1277 
1278 	if (!hints_array_initialized(cmd))
1279 		return 0;
1280 
1281 	down_write(&cmd->root_lock);
1282 	r = save_hint(cmd, cblock, hint);
1283 	up_write(&cmd->root_lock);
1284 
1285 	return r;
1286 }
1287 
1288 int dm_cache_metadata_all_clean(struct dm_cache_metadata *cmd, bool *result)
1289 {
1290 	return blocks_are_unmapped_or_clean(cmd, 0, cmd->cache_blocks, result);
1291 }
1292