GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / md / dm-thin-metadata.c
1 /*
2  * Copyright (C) 2011-2012 Red Hat, Inc.
3  *
4  * This file is released under the GPL.
5  */
6
7 #include "dm-thin-metadata.h"
8 #include "persistent-data/dm-btree.h"
9 #include "persistent-data/dm-space-map.h"
10 #include "persistent-data/dm-space-map-disk.h"
11 #include "persistent-data/dm-transaction-manager.h"
12
13 #include <linux/list.h>
14 #include <linux/device-mapper.h>
15 #include <linux/workqueue.h>
16
17 /*--------------------------------------------------------------------------
18  * As far as the metadata goes, there is:
19  *
20  * - A superblock in block zero, taking up fewer than 512 bytes for
21  *   atomic writes.
22  *
23  * - A space map managing the metadata blocks.
24  *
25  * - A space map managing the data blocks.
26  *
27  * - A btree mapping our internal thin dev ids onto struct disk_device_details.
28  *
29  * - A hierarchical btree, with 2 levels which effectively maps (thin
30  *   dev id, virtual block) -> block_time.  Block time is a 64-bit
31  *   field holding the time in the low 24 bits, and block in the top 48
32  *   bits.
33  *
34  * BTrees consist solely of btree_nodes, that fill a block.  Some are
35  * internal nodes, as such their values are a __le64 pointing to other
36  * nodes.  Leaf nodes can store data of any reasonable size (ie. much
37  * smaller than the block size).  The nodes consist of the header,
38  * followed by an array of keys, followed by an array of values.  We have
39  * to binary search on the keys so they're all held together to help the
40  * cpu cache.
41  *
42  * Space maps have 2 btrees:
43  *
44  * - One maps a uint64_t onto a struct index_entry.  Which points to a
45  *   bitmap block, and has some details about how many free entries there
46  *   are etc.
47  *
48  * - The bitmap blocks have a header (for the checksum).  Then the rest
49  *   of the block is pairs of bits.  With the meaning being:
50  *
51  *   0 - ref count is 0
52  *   1 - ref count is 1
53  *   2 - ref count is 2
54  *   3 - ref count is higher than 2
55  *
56  * - If the count is higher than 2 then the ref count is entered in a
57  *   second btree that directly maps the block_address to a uint32_t ref
58  *   count.
59  *
60  * The space map metadata variant doesn't have a bitmaps btree.  Instead
61  * it has one single blocks worth of index_entries.  This avoids
62  * recursive issues with the bitmap btree needing to allocate space in
63  * order to insert.  With a small data block size such as 64k the
64  * metadata support data devices that are hundreds of terrabytes.
65  *
66  * The space maps allocate space linearly from front to back.  Space that
67  * is freed in a transaction is never recycled within that transaction.
68  * To try and avoid fragmenting _free_ space the allocator always goes
69  * back and fills in gaps.
70  *
71  * All metadata io is in THIN_METADATA_BLOCK_SIZE sized/aligned chunks
72  * from the block manager.
73  *--------------------------------------------------------------------------*/
74
75 #define DM_MSG_PREFIX   "thin metadata"
76
77 #define THIN_SUPERBLOCK_MAGIC 27022010
78 #define THIN_SUPERBLOCK_LOCATION 0
79 #define THIN_VERSION 2
80 #define SECTOR_TO_BLOCK_SHIFT 3
81
82 /*
83  * For btree insert:
84  *  3 for btree insert +
85  *  2 for btree lookup used within space map
86  * For btree remove:
87  *  2 for shadow spine +
88  *  4 for rebalance 3 child node
89  */
90 #define THIN_MAX_CONCURRENT_LOCKS 6
91
92 /* This should be plenty */
93 #define SPACE_MAP_ROOT_SIZE 128
94
95 /*
96  * Little endian on-disk superblock and device details.
97  */
98 struct thin_disk_superblock {
99         __le32 csum;    /* Checksum of superblock except for this field. */
100         __le32 flags;
101         __le64 blocknr; /* This block number, dm_block_t. */
102
103         __u8 uuid[16];
104         __le64 magic;
105         __le32 version;
106         __le32 time;
107
108         __le64 trans_id;
109
110         /*
111          * Root held by userspace transactions.
112          */
113         __le64 held_root;
114
115         __u8 data_space_map_root[SPACE_MAP_ROOT_SIZE];
116         __u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
117
118         /*
119          * 2-level btree mapping (dev_id, (dev block, time)) -> data block
120          */
121         __le64 data_mapping_root;
122
123         /*
124          * Device detail root mapping dev_id -> device_details
125          */
126         __le64 device_details_root;
127
128         __le32 data_block_size;         /* In 512-byte sectors. */
129
130         __le32 metadata_block_size;     /* In 512-byte sectors. */
131         __le64 metadata_nr_blocks;
132
133         __le32 compat_flags;
134         __le32 compat_ro_flags;
135         __le32 incompat_flags;
136 } __packed;
137
138 struct disk_device_details {
139         __le64 mapped_blocks;
140         __le64 transaction_id;          /* When created. */
141         __le32 creation_time;
142         __le32 snapshotted_time;
143 } __packed;
144
145 struct dm_pool_metadata {
146         struct hlist_node hash;
147
148         struct block_device *bdev;
149         struct dm_block_manager *bm;
150         struct dm_space_map *metadata_sm;
151         struct dm_space_map *data_sm;
152         struct dm_transaction_manager *tm;
153         struct dm_transaction_manager *nb_tm;
154
155         /*
156          * Two-level btree.
157          * First level holds thin_dev_t.
158          * Second level holds mappings.
159          */
160         struct dm_btree_info info;
161
162         /*
163          * Non-blocking version of the above.
164          */
165         struct dm_btree_info nb_info;
166
167         /*
168          * Just the top level for deleting whole devices.
169          */
170         struct dm_btree_info tl_info;
171
172         /*
173          * Just the bottom level for creating new devices.
174          */
175         struct dm_btree_info bl_info;
176
177         /*
178          * Describes the device details btree.
179          */
180         struct dm_btree_info details_info;
181
182         struct rw_semaphore root_lock;
183         uint32_t time;
184         dm_block_t root;
185         dm_block_t details_root;
186         struct list_head thin_devices;
187         uint64_t trans_id;
188         unsigned long flags;
189         sector_t data_block_size;
190
191         /*
192          * We reserve a section of the metadata for commit overhead.
193          * All reported space does *not* include this.
194          */
195         dm_block_t metadata_reserve;
196
197         /*
198          * Set if a transaction has to be aborted but the attempt to roll back
199          * to the previous (good) transaction failed.  The only pool metadata
200          * operation possible in this state is the closing of the device.
201          */
202         bool fail_io:1;
203
204         /*
205          * Reading the space map roots can fail, so we read it into these
206          * buffers before the superblock is locked and updated.
207          */
208         __u8 data_space_map_root[SPACE_MAP_ROOT_SIZE];
209         __u8 metadata_space_map_root[SPACE_MAP_ROOT_SIZE];
210 };
211
212 struct dm_thin_device {
213         struct list_head list;
214         struct dm_pool_metadata *pmd;
215         dm_thin_id id;
216
217         int open_count;
218         bool changed:1;
219         bool aborted_with_changes:1;
220         uint64_t mapped_blocks;
221         uint64_t transaction_id;
222         uint32_t creation_time;
223         uint32_t snapshotted_time;
224 };
225
226 /*----------------------------------------------------------------
227  * superblock validator
228  *--------------------------------------------------------------*/
229
230 #define SUPERBLOCK_CSUM_XOR 160774
231
232 static void sb_prepare_for_write(struct dm_block_validator *v,
233                                  struct dm_block *b,
234                                  size_t block_size)
235 {
236         struct thin_disk_superblock *disk_super = dm_block_data(b);
237
238         disk_super->blocknr = cpu_to_le64(dm_block_location(b));
239         disk_super->csum = cpu_to_le32(dm_bm_checksum(&disk_super->flags,
240                                                       block_size - sizeof(__le32),
241                                                       SUPERBLOCK_CSUM_XOR));
242 }
243
244 static int sb_check(struct dm_block_validator *v,
245                     struct dm_block *b,
246                     size_t block_size)
247 {
248         struct thin_disk_superblock *disk_super = dm_block_data(b);
249         __le32 csum_le;
250
251         if (dm_block_location(b) != le64_to_cpu(disk_super->blocknr)) {
252                 DMERR("sb_check failed: blocknr %llu: "
253                       "wanted %llu", le64_to_cpu(disk_super->blocknr),
254                       (unsigned long long)dm_block_location(b));
255                 return -ENOTBLK;
256         }
257
258         if (le64_to_cpu(disk_super->magic) != THIN_SUPERBLOCK_MAGIC) {
259                 DMERR("sb_check failed: magic %llu: "
260                       "wanted %llu", le64_to_cpu(disk_super->magic),
261                       (unsigned long long)THIN_SUPERBLOCK_MAGIC);
262                 return -EILSEQ;
263         }
264
265         csum_le = cpu_to_le32(dm_bm_checksum(&disk_super->flags,
266                                              block_size - sizeof(__le32),
267                                              SUPERBLOCK_CSUM_XOR));
268         if (csum_le != disk_super->csum) {
269                 DMERR("sb_check failed: csum %u: wanted %u",
270                       le32_to_cpu(csum_le), le32_to_cpu(disk_super->csum));
271                 return -EILSEQ;
272         }
273
274         return 0;
275 }
276
277 static struct dm_block_validator sb_validator = {
278         .name = "superblock",
279         .prepare_for_write = sb_prepare_for_write,
280         .check = sb_check
281 };
282
283 /*----------------------------------------------------------------
284  * Methods for the btree value types
285  *--------------------------------------------------------------*/
286
287 static uint64_t pack_block_time(dm_block_t b, uint32_t t)
288 {
289         return (b << 24) | t;
290 }
291
292 static void unpack_block_time(uint64_t v, dm_block_t *b, uint32_t *t)
293 {
294         *b = v >> 24;
295         *t = v & ((1 << 24) - 1);
296 }
297
298 static void data_block_inc(void *context, const void *value_le)
299 {
300         struct dm_space_map *sm = context;
301         __le64 v_le;
302         uint64_t b;
303         uint32_t t;
304
305         memcpy(&v_le, value_le, sizeof(v_le));
306         unpack_block_time(le64_to_cpu(v_le), &b, &t);
307         dm_sm_inc_block(sm, b);
308 }
309
310 static void data_block_dec(void *context, const void *value_le)
311 {
312         struct dm_space_map *sm = context;
313         __le64 v_le;
314         uint64_t b;
315         uint32_t t;
316
317         memcpy(&v_le, value_le, sizeof(v_le));
318         unpack_block_time(le64_to_cpu(v_le), &b, &t);
319         dm_sm_dec_block(sm, b);
320 }
321
322 static int data_block_equal(void *context, const void *value1_le, const void *value2_le)
323 {
324         __le64 v1_le, v2_le;
325         uint64_t b1, b2;
326         uint32_t t;
327
328         memcpy(&v1_le, value1_le, sizeof(v1_le));
329         memcpy(&v2_le, value2_le, sizeof(v2_le));
330         unpack_block_time(le64_to_cpu(v1_le), &b1, &t);
331         unpack_block_time(le64_to_cpu(v2_le), &b2, &t);
332
333         return b1 == b2;
334 }
335
336 static void subtree_inc(void *context, const void *value)
337 {
338         struct dm_btree_info *info = context;
339         __le64 root_le;
340         uint64_t root;
341
342         memcpy(&root_le, value, sizeof(root_le));
343         root = le64_to_cpu(root_le);
344         dm_tm_inc(info->tm, root);
345 }
346
347 static void subtree_dec(void *context, const void *value)
348 {
349         struct dm_btree_info *info = context;
350         __le64 root_le;
351         uint64_t root;
352
353         memcpy(&root_le, value, sizeof(root_le));
354         root = le64_to_cpu(root_le);
355         if (dm_btree_del(info, root))
356                 DMERR("btree delete failed");
357 }
358
359 static int subtree_equal(void *context, const void *value1_le, const void *value2_le)
360 {
361         __le64 v1_le, v2_le;
362         memcpy(&v1_le, value1_le, sizeof(v1_le));
363         memcpy(&v2_le, value2_le, sizeof(v2_le));
364
365         return v1_le == v2_le;
366 }
367
368 /*----------------------------------------------------------------*/
369
370 static int superblock_lock_zero(struct dm_pool_metadata *pmd,
371                                 struct dm_block **sblock)
372 {
373         return dm_bm_write_lock_zero(pmd->bm, THIN_SUPERBLOCK_LOCATION,
374                                      &sb_validator, sblock);
375 }
376
377 static int superblock_lock(struct dm_pool_metadata *pmd,
378                            struct dm_block **sblock)
379 {
380         return dm_bm_write_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION,
381                                 &sb_validator, sblock);
382 }
383
384 static int __superblock_all_zeroes(struct dm_block_manager *bm, int *result)
385 {
386         int r;
387         unsigned i;
388         struct dm_block *b;
389         __le64 *data_le, zero = cpu_to_le64(0);
390         unsigned block_size = dm_bm_block_size(bm) / sizeof(__le64);
391
392         /*
393          * We can't use a validator here - it may be all zeroes.
394          */
395         r = dm_bm_read_lock(bm, THIN_SUPERBLOCK_LOCATION, NULL, &b);
396         if (r)
397                 return r;
398
399         data_le = dm_block_data(b);
400         *result = 1;
401         for (i = 0; i < block_size; i++) {
402                 if (data_le[i] != zero) {
403                         *result = 0;
404                         break;
405                 }
406         }
407
408         dm_bm_unlock(b);
409
410         return 0;
411 }
412
413 static void __setup_btree_details(struct dm_pool_metadata *pmd)
414 {
415         pmd->info.tm = pmd->tm;
416         pmd->info.levels = 2;
417         pmd->info.value_type.context = pmd->data_sm;
418         pmd->info.value_type.size = sizeof(__le64);
419         pmd->info.value_type.inc = data_block_inc;
420         pmd->info.value_type.dec = data_block_dec;
421         pmd->info.value_type.equal = data_block_equal;
422
423         memcpy(&pmd->nb_info, &pmd->info, sizeof(pmd->nb_info));
424         pmd->nb_info.tm = pmd->nb_tm;
425
426         pmd->tl_info.tm = pmd->tm;
427         pmd->tl_info.levels = 1;
428         pmd->tl_info.value_type.context = &pmd->bl_info;
429         pmd->tl_info.value_type.size = sizeof(__le64);
430         pmd->tl_info.value_type.inc = subtree_inc;
431         pmd->tl_info.value_type.dec = subtree_dec;
432         pmd->tl_info.value_type.equal = subtree_equal;
433
434         pmd->bl_info.tm = pmd->tm;
435         pmd->bl_info.levels = 1;
436         pmd->bl_info.value_type.context = pmd->data_sm;
437         pmd->bl_info.value_type.size = sizeof(__le64);
438         pmd->bl_info.value_type.inc = data_block_inc;
439         pmd->bl_info.value_type.dec = data_block_dec;
440         pmd->bl_info.value_type.equal = data_block_equal;
441
442         pmd->details_info.tm = pmd->tm;
443         pmd->details_info.levels = 1;
444         pmd->details_info.value_type.context = NULL;
445         pmd->details_info.value_type.size = sizeof(struct disk_device_details);
446         pmd->details_info.value_type.inc = NULL;
447         pmd->details_info.value_type.dec = NULL;
448         pmd->details_info.value_type.equal = NULL;
449 }
450
451 static int save_sm_roots(struct dm_pool_metadata *pmd)
452 {
453         int r;
454         size_t len;
455
456         r = dm_sm_root_size(pmd->metadata_sm, &len);
457         if (r < 0)
458                 return r;
459
460         r = dm_sm_copy_root(pmd->metadata_sm, &pmd->metadata_space_map_root, len);
461         if (r < 0)
462                 return r;
463
464         r = dm_sm_root_size(pmd->data_sm, &len);
465         if (r < 0)
466                 return r;
467
468         return dm_sm_copy_root(pmd->data_sm, &pmd->data_space_map_root, len);
469 }
470
471 static void copy_sm_roots(struct dm_pool_metadata *pmd,
472                           struct thin_disk_superblock *disk)
473 {
474         memcpy(&disk->metadata_space_map_root,
475                &pmd->metadata_space_map_root,
476                sizeof(pmd->metadata_space_map_root));
477
478         memcpy(&disk->data_space_map_root,
479                &pmd->data_space_map_root,
480                sizeof(pmd->data_space_map_root));
481 }
482
483 static int __write_initial_superblock(struct dm_pool_metadata *pmd)
484 {
485         int r;
486         struct dm_block *sblock;
487         struct thin_disk_superblock *disk_super;
488         sector_t bdev_size = i_size_read(pmd->bdev->bd_inode) >> SECTOR_SHIFT;
489
490         if (bdev_size > THIN_METADATA_MAX_SECTORS)
491                 bdev_size = THIN_METADATA_MAX_SECTORS;
492
493         r = dm_sm_commit(pmd->data_sm);
494         if (r < 0)
495                 return r;
496
497         r = dm_tm_pre_commit(pmd->tm);
498         if (r < 0)
499                 return r;
500
501         r = save_sm_roots(pmd);
502         if (r < 0)
503                 return r;
504
505         r = superblock_lock_zero(pmd, &sblock);
506         if (r)
507                 return r;
508
509         disk_super = dm_block_data(sblock);
510         disk_super->flags = 0;
511         memset(disk_super->uuid, 0, sizeof(disk_super->uuid));
512         disk_super->magic = cpu_to_le64(THIN_SUPERBLOCK_MAGIC);
513         disk_super->version = cpu_to_le32(THIN_VERSION);
514         disk_super->time = 0;
515         disk_super->trans_id = 0;
516         disk_super->held_root = 0;
517
518         copy_sm_roots(pmd, disk_super);
519
520         disk_super->data_mapping_root = cpu_to_le64(pmd->root);
521         disk_super->device_details_root = cpu_to_le64(pmd->details_root);
522         disk_super->metadata_block_size = cpu_to_le32(THIN_METADATA_BLOCK_SIZE);
523         disk_super->metadata_nr_blocks = cpu_to_le64(bdev_size >> SECTOR_TO_BLOCK_SHIFT);
524         disk_super->data_block_size = cpu_to_le32(pmd->data_block_size);
525
526         return dm_tm_commit(pmd->tm, sblock);
527 }
528
529 static int __format_metadata(struct dm_pool_metadata *pmd)
530 {
531         int r;
532
533         r = dm_tm_create_with_sm(pmd->bm, THIN_SUPERBLOCK_LOCATION,
534                                  &pmd->tm, &pmd->metadata_sm);
535         if (r < 0) {
536                 DMERR("tm_create_with_sm failed");
537                 return r;
538         }
539
540         pmd->data_sm = dm_sm_disk_create(pmd->tm, 0);
541         if (IS_ERR(pmd->data_sm)) {
542                 DMERR("sm_disk_create failed");
543                 r = PTR_ERR(pmd->data_sm);
544                 goto bad_cleanup_tm;
545         }
546
547         pmd->nb_tm = dm_tm_create_non_blocking_clone(pmd->tm);
548         if (!pmd->nb_tm) {
549                 DMERR("could not create non-blocking clone tm");
550                 r = -ENOMEM;
551                 goto bad_cleanup_data_sm;
552         }
553
554         __setup_btree_details(pmd);
555
556         r = dm_btree_empty(&pmd->info, &pmd->root);
557         if (r < 0)
558                 goto bad_cleanup_nb_tm;
559
560         r = dm_btree_empty(&pmd->details_info, &pmd->details_root);
561         if (r < 0) {
562                 DMERR("couldn't create devices root");
563                 goto bad_cleanup_nb_tm;
564         }
565
566         r = __write_initial_superblock(pmd);
567         if (r)
568                 goto bad_cleanup_nb_tm;
569
570         return 0;
571
572 bad_cleanup_nb_tm:
573         dm_tm_destroy(pmd->nb_tm);
574 bad_cleanup_data_sm:
575         dm_sm_destroy(pmd->data_sm);
576 bad_cleanup_tm:
577         dm_tm_destroy(pmd->tm);
578         dm_sm_destroy(pmd->metadata_sm);
579
580         return r;
581 }
582
583 static int __check_incompat_features(struct thin_disk_superblock *disk_super,
584                                      struct dm_pool_metadata *pmd)
585 {
586         uint32_t features;
587
588         features = le32_to_cpu(disk_super->incompat_flags) & ~THIN_FEATURE_INCOMPAT_SUPP;
589         if (features) {
590                 DMERR("could not access metadata due to unsupported optional features (%lx).",
591                       (unsigned long)features);
592                 return -EINVAL;
593         }
594
595         /*
596          * Check for read-only metadata to skip the following RDWR checks.
597          */
598         if (get_disk_ro(pmd->bdev->bd_disk))
599                 return 0;
600
601         features = le32_to_cpu(disk_super->compat_ro_flags) & ~THIN_FEATURE_COMPAT_RO_SUPP;
602         if (features) {
603                 DMERR("could not access metadata RDWR due to unsupported optional features (%lx).",
604                       (unsigned long)features);
605                 return -EINVAL;
606         }
607
608         return 0;
609 }
610
611 static int __open_metadata(struct dm_pool_metadata *pmd)
612 {
613         int r;
614         struct dm_block *sblock;
615         struct thin_disk_superblock *disk_super;
616
617         r = dm_bm_read_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION,
618                             &sb_validator, &sblock);
619         if (r < 0) {
620                 DMERR("couldn't read superblock");
621                 return r;
622         }
623
624         disk_super = dm_block_data(sblock);
625
626         /* Verify the data block size hasn't changed */
627         if (le32_to_cpu(disk_super->data_block_size) != pmd->data_block_size) {
628                 DMERR("changing the data block size (from %u to %llu) is not supported",
629                       le32_to_cpu(disk_super->data_block_size),
630                       (unsigned long long)pmd->data_block_size);
631                 r = -EINVAL;
632                 goto bad_unlock_sblock;
633         }
634
635         r = __check_incompat_features(disk_super, pmd);
636         if (r < 0)
637                 goto bad_unlock_sblock;
638
639         r = dm_tm_open_with_sm(pmd->bm, THIN_SUPERBLOCK_LOCATION,
640                                disk_super->metadata_space_map_root,
641                                sizeof(disk_super->metadata_space_map_root),
642                                &pmd->tm, &pmd->metadata_sm);
643         if (r < 0) {
644                 DMERR("tm_open_with_sm failed");
645                 goto bad_unlock_sblock;
646         }
647
648         pmd->data_sm = dm_sm_disk_open(pmd->tm, disk_super->data_space_map_root,
649                                        sizeof(disk_super->data_space_map_root));
650         if (IS_ERR(pmd->data_sm)) {
651                 DMERR("sm_disk_open failed");
652                 r = PTR_ERR(pmd->data_sm);
653                 goto bad_cleanup_tm;
654         }
655
656         pmd->nb_tm = dm_tm_create_non_blocking_clone(pmd->tm);
657         if (!pmd->nb_tm) {
658                 DMERR("could not create non-blocking clone tm");
659                 r = -ENOMEM;
660                 goto bad_cleanup_data_sm;
661         }
662
663         __setup_btree_details(pmd);
664         dm_bm_unlock(sblock);
665
666         return 0;
667
668 bad_cleanup_data_sm:
669         dm_sm_destroy(pmd->data_sm);
670 bad_cleanup_tm:
671         dm_tm_destroy(pmd->tm);
672         dm_sm_destroy(pmd->metadata_sm);
673 bad_unlock_sblock:
674         dm_bm_unlock(sblock);
675
676         return r;
677 }
678
679 static int __open_or_format_metadata(struct dm_pool_metadata *pmd, bool format_device)
680 {
681         int r, unformatted;
682
683         r = __superblock_all_zeroes(pmd->bm, &unformatted);
684         if (r)
685                 return r;
686
687         if (unformatted)
688                 return format_device ? __format_metadata(pmd) : -EPERM;
689
690         return __open_metadata(pmd);
691 }
692
693 static int __create_persistent_data_objects(struct dm_pool_metadata *pmd, bool format_device)
694 {
695         int r;
696
697         pmd->bm = dm_block_manager_create(pmd->bdev, THIN_METADATA_BLOCK_SIZE << SECTOR_SHIFT,
698                                           THIN_MAX_CONCURRENT_LOCKS);
699         if (IS_ERR(pmd->bm)) {
700                 DMERR("could not create block manager");
701                 r = PTR_ERR(pmd->bm);
702                 pmd->bm = NULL;
703                 return r;
704         }
705
706         r = __open_or_format_metadata(pmd, format_device);
707         if (r) {
708                 dm_block_manager_destroy(pmd->bm);
709                 pmd->bm = NULL;
710         }
711
712         return r;
713 }
714
715 static void __destroy_persistent_data_objects(struct dm_pool_metadata *pmd)
716 {
717         dm_sm_destroy(pmd->data_sm);
718         dm_sm_destroy(pmd->metadata_sm);
719         dm_tm_destroy(pmd->nb_tm);
720         dm_tm_destroy(pmd->tm);
721         dm_block_manager_destroy(pmd->bm);
722 }
723
724 static int __begin_transaction(struct dm_pool_metadata *pmd)
725 {
726         int r;
727         struct thin_disk_superblock *disk_super;
728         struct dm_block *sblock;
729
730         /*
731          * We re-read the superblock every time.  Shouldn't need to do this
732          * really.
733          */
734         r = dm_bm_read_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION,
735                             &sb_validator, &sblock);
736         if (r)
737                 return r;
738
739         disk_super = dm_block_data(sblock);
740         pmd->time = le32_to_cpu(disk_super->time);
741         pmd->root = le64_to_cpu(disk_super->data_mapping_root);
742         pmd->details_root = le64_to_cpu(disk_super->device_details_root);
743         pmd->trans_id = le64_to_cpu(disk_super->trans_id);
744         pmd->flags = le32_to_cpu(disk_super->flags);
745         pmd->data_block_size = le32_to_cpu(disk_super->data_block_size);
746
747         dm_bm_unlock(sblock);
748         return 0;
749 }
750
751 static int __write_changed_details(struct dm_pool_metadata *pmd)
752 {
753         int r;
754         struct dm_thin_device *td, *tmp;
755         struct disk_device_details details;
756         uint64_t key;
757
758         list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) {
759                 if (!td->changed)
760                         continue;
761
762                 key = td->id;
763
764                 details.mapped_blocks = cpu_to_le64(td->mapped_blocks);
765                 details.transaction_id = cpu_to_le64(td->transaction_id);
766                 details.creation_time = cpu_to_le32(td->creation_time);
767                 details.snapshotted_time = cpu_to_le32(td->snapshotted_time);
768                 __dm_bless_for_disk(&details);
769
770                 r = dm_btree_insert(&pmd->details_info, pmd->details_root,
771                                     &key, &details, &pmd->details_root);
772                 if (r)
773                         return r;
774
775                 if (td->open_count)
776                         td->changed = 0;
777                 else {
778                         list_del(&td->list);
779                         kfree(td);
780                 }
781         }
782
783         return 0;
784 }
785
786 static int __commit_transaction(struct dm_pool_metadata *pmd)
787 {
788         int r;
789         struct thin_disk_superblock *disk_super;
790         struct dm_block *sblock;
791
792         /*
793          * We need to know if the thin_disk_superblock exceeds a 512-byte sector.
794          */
795         BUILD_BUG_ON(sizeof(struct thin_disk_superblock) > 512);
796
797         r = __write_changed_details(pmd);
798         if (r < 0)
799                 return r;
800
801         r = dm_sm_commit(pmd->data_sm);
802         if (r < 0)
803                 return r;
804
805         r = dm_tm_pre_commit(pmd->tm);
806         if (r < 0)
807                 return r;
808
809         r = save_sm_roots(pmd);
810         if (r < 0)
811                 return r;
812
813         r = superblock_lock(pmd, &sblock);
814         if (r)
815                 return r;
816
817         disk_super = dm_block_data(sblock);
818         disk_super->time = cpu_to_le32(pmd->time);
819         disk_super->data_mapping_root = cpu_to_le64(pmd->root);
820         disk_super->device_details_root = cpu_to_le64(pmd->details_root);
821         disk_super->trans_id = cpu_to_le64(pmd->trans_id);
822         disk_super->flags = cpu_to_le32(pmd->flags);
823
824         copy_sm_roots(pmd, disk_super);
825
826         return dm_tm_commit(pmd->tm, sblock);
827 }
828
829 static void __set_metadata_reserve(struct dm_pool_metadata *pmd)
830 {
831         int r;
832         dm_block_t total;
833         dm_block_t max_blocks = 4096; /* 16M */
834
835         r = dm_sm_get_nr_blocks(pmd->metadata_sm, &total);
836         if (r) {
837                 DMERR("could not get size of metadata device");
838                 pmd->metadata_reserve = max_blocks;
839         } else
840                 pmd->metadata_reserve = min(max_blocks, div_u64(total, 10));
841 }
842
843 struct dm_pool_metadata *dm_pool_metadata_open(struct block_device *bdev,
844                                                sector_t data_block_size,
845                                                bool format_device)
846 {
847         int r;
848         struct dm_pool_metadata *pmd;
849
850         pmd = kmalloc(sizeof(*pmd), GFP_KERNEL);
851         if (!pmd) {
852                 DMERR("could not allocate metadata struct");
853                 return ERR_PTR(-ENOMEM);
854         }
855
856         init_rwsem(&pmd->root_lock);
857         pmd->time = 0;
858         INIT_LIST_HEAD(&pmd->thin_devices);
859         pmd->fail_io = false;
860         pmd->bdev = bdev;
861         pmd->data_block_size = data_block_size;
862
863         r = __create_persistent_data_objects(pmd, format_device);
864         if (r) {
865                 kfree(pmd);
866                 return ERR_PTR(r);
867         }
868
869         r = __begin_transaction(pmd);
870         if (r < 0) {
871                 if (dm_pool_metadata_close(pmd) < 0)
872                         DMWARN("%s: dm_pool_metadata_close() failed.", __func__);
873                 return ERR_PTR(r);
874         }
875
876         __set_metadata_reserve(pmd);
877
878         return pmd;
879 }
880
881 int dm_pool_metadata_close(struct dm_pool_metadata *pmd)
882 {
883         int r;
884         unsigned open_devices = 0;
885         struct dm_thin_device *td, *tmp;
886
887         down_read(&pmd->root_lock);
888         list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) {
889                 if (td->open_count)
890                         open_devices++;
891                 else {
892                         list_del(&td->list);
893                         kfree(td);
894                 }
895         }
896         up_read(&pmd->root_lock);
897
898         if (open_devices) {
899                 DMERR("attempt to close pmd when %u device(s) are still open",
900                        open_devices);
901                 return -EBUSY;
902         }
903
904         if (!pmd->fail_io && !dm_bm_is_read_only(pmd->bm)) {
905                 r = __commit_transaction(pmd);
906                 if (r < 0)
907                         DMWARN("%s: __commit_transaction() failed, error = %d",
908                                __func__, r);
909         }
910
911         if (!pmd->fail_io)
912                 __destroy_persistent_data_objects(pmd);
913
914         kfree(pmd);
915         return 0;
916 }
917
918 /*
919  * __open_device: Returns @td corresponding to device with id @dev,
920  * creating it if @create is set and incrementing @td->open_count.
921  * On failure, @td is undefined.
922  */
923 static int __open_device(struct dm_pool_metadata *pmd,
924                          dm_thin_id dev, int create,
925                          struct dm_thin_device **td)
926 {
927         int r, changed = 0;
928         struct dm_thin_device *td2;
929         uint64_t key = dev;
930         struct disk_device_details details_le;
931
932         /*
933          * If the device is already open, return it.
934          */
935         list_for_each_entry(td2, &pmd->thin_devices, list)
936                 if (td2->id == dev) {
937                         /*
938                          * May not create an already-open device.
939                          */
940                         if (create)
941                                 return -EEXIST;
942
943                         td2->open_count++;
944                         *td = td2;
945                         return 0;
946                 }
947
948         /*
949          * Check the device exists.
950          */
951         r = dm_btree_lookup(&pmd->details_info, pmd->details_root,
952                             &key, &details_le);
953         if (r) {
954                 if (r != -ENODATA || !create)
955                         return r;
956
957                 /*
958                  * Create new device.
959                  */
960                 changed = 1;
961                 details_le.mapped_blocks = 0;
962                 details_le.transaction_id = cpu_to_le64(pmd->trans_id);
963                 details_le.creation_time = cpu_to_le32(pmd->time);
964                 details_le.snapshotted_time = cpu_to_le32(pmd->time);
965         }
966
967         *td = kmalloc(sizeof(**td), GFP_NOIO);
968         if (!*td)
969                 return -ENOMEM;
970
971         (*td)->pmd = pmd;
972         (*td)->id = dev;
973         (*td)->open_count = 1;
974         (*td)->changed = changed;
975         (*td)->aborted_with_changes = false;
976         (*td)->mapped_blocks = le64_to_cpu(details_le.mapped_blocks);
977         (*td)->transaction_id = le64_to_cpu(details_le.transaction_id);
978         (*td)->creation_time = le32_to_cpu(details_le.creation_time);
979         (*td)->snapshotted_time = le32_to_cpu(details_le.snapshotted_time);
980
981         list_add(&(*td)->list, &pmd->thin_devices);
982
983         return 0;
984 }
985
986 static void __close_device(struct dm_thin_device *td)
987 {
988         --td->open_count;
989 }
990
991 static int __create_thin(struct dm_pool_metadata *pmd,
992                          dm_thin_id dev)
993 {
994         int r;
995         dm_block_t dev_root;
996         uint64_t key = dev;
997         struct disk_device_details details_le;
998         struct dm_thin_device *td;
999         __le64 value;
1000
1001         r = dm_btree_lookup(&pmd->details_info, pmd->details_root,
1002                             &key, &details_le);
1003         if (!r)
1004                 return -EEXIST;
1005
1006         /*
1007          * Create an empty btree for the mappings.
1008          */
1009         r = dm_btree_empty(&pmd->bl_info, &dev_root);
1010         if (r)
1011                 return r;
1012
1013         /*
1014          * Insert it into the main mapping tree.
1015          */
1016         value = cpu_to_le64(dev_root);
1017         __dm_bless_for_disk(&value);
1018         r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root);
1019         if (r) {
1020                 dm_btree_del(&pmd->bl_info, dev_root);
1021                 return r;
1022         }
1023
1024         r = __open_device(pmd, dev, 1, &td);
1025         if (r) {
1026                 dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root);
1027                 dm_btree_del(&pmd->bl_info, dev_root);
1028                 return r;
1029         }
1030         __close_device(td);
1031
1032         return r;
1033 }
1034
1035 int dm_pool_create_thin(struct dm_pool_metadata *pmd, dm_thin_id dev)
1036 {
1037         int r = -EINVAL;
1038
1039         down_write(&pmd->root_lock);
1040         if (!pmd->fail_io)
1041                 r = __create_thin(pmd, dev);
1042         up_write(&pmd->root_lock);
1043
1044         return r;
1045 }
1046
1047 static int __set_snapshot_details(struct dm_pool_metadata *pmd,
1048                                   struct dm_thin_device *snap,
1049                                   dm_thin_id origin, uint32_t time)
1050 {
1051         int r;
1052         struct dm_thin_device *td;
1053
1054         r = __open_device(pmd, origin, 0, &td);
1055         if (r)
1056                 return r;
1057
1058         td->changed = 1;
1059         td->snapshotted_time = time;
1060
1061         snap->mapped_blocks = td->mapped_blocks;
1062         snap->snapshotted_time = time;
1063         __close_device(td);
1064
1065         return 0;
1066 }
1067
1068 static int __create_snap(struct dm_pool_metadata *pmd,
1069                          dm_thin_id dev, dm_thin_id origin)
1070 {
1071         int r;
1072         dm_block_t origin_root;
1073         uint64_t key = origin, dev_key = dev;
1074         struct dm_thin_device *td;
1075         struct disk_device_details details_le;
1076         __le64 value;
1077
1078         /* check this device is unused */
1079         r = dm_btree_lookup(&pmd->details_info, pmd->details_root,
1080                             &dev_key, &details_le);
1081         if (!r)
1082                 return -EEXIST;
1083
1084         /* find the mapping tree for the origin */
1085         r = dm_btree_lookup(&pmd->tl_info, pmd->root, &key, &value);
1086         if (r)
1087                 return r;
1088         origin_root = le64_to_cpu(value);
1089
1090         /* clone the origin, an inc will do */
1091         dm_tm_inc(pmd->tm, origin_root);
1092
1093         /* insert into the main mapping tree */
1094         value = cpu_to_le64(origin_root);
1095         __dm_bless_for_disk(&value);
1096         key = dev;
1097         r = dm_btree_insert(&pmd->tl_info, pmd->root, &key, &value, &pmd->root);
1098         if (r) {
1099                 dm_tm_dec(pmd->tm, origin_root);
1100                 return r;
1101         }
1102
1103         pmd->time++;
1104
1105         r = __open_device(pmd, dev, 1, &td);
1106         if (r)
1107                 goto bad;
1108
1109         r = __set_snapshot_details(pmd, td, origin, pmd->time);
1110         __close_device(td);
1111
1112         if (r)
1113                 goto bad;
1114
1115         return 0;
1116
1117 bad:
1118         dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root);
1119         dm_btree_remove(&pmd->details_info, pmd->details_root,
1120                         &key, &pmd->details_root);
1121         return r;
1122 }
1123
1124 int dm_pool_create_snap(struct dm_pool_metadata *pmd,
1125                                  dm_thin_id dev,
1126                                  dm_thin_id origin)
1127 {
1128         int r = -EINVAL;
1129
1130         down_write(&pmd->root_lock);
1131         if (!pmd->fail_io)
1132                 r = __create_snap(pmd, dev, origin);
1133         up_write(&pmd->root_lock);
1134
1135         return r;
1136 }
1137
1138 static int __delete_device(struct dm_pool_metadata *pmd, dm_thin_id dev)
1139 {
1140         int r;
1141         uint64_t key = dev;
1142         struct dm_thin_device *td;
1143
1144         /* TODO: failure should mark the transaction invalid */
1145         r = __open_device(pmd, dev, 0, &td);
1146         if (r)
1147                 return r;
1148
1149         if (td->open_count > 1) {
1150                 __close_device(td);
1151                 return -EBUSY;
1152         }
1153
1154         list_del(&td->list);
1155         kfree(td);
1156         r = dm_btree_remove(&pmd->details_info, pmd->details_root,
1157                             &key, &pmd->details_root);
1158         if (r)
1159                 return r;
1160
1161         r = dm_btree_remove(&pmd->tl_info, pmd->root, &key, &pmd->root);
1162         if (r)
1163                 return r;
1164
1165         return 0;
1166 }
1167
1168 int dm_pool_delete_thin_device(struct dm_pool_metadata *pmd,
1169                                dm_thin_id dev)
1170 {
1171         int r = -EINVAL;
1172
1173         down_write(&pmd->root_lock);
1174         if (!pmd->fail_io)
1175                 r = __delete_device(pmd, dev);
1176         up_write(&pmd->root_lock);
1177
1178         return r;
1179 }
1180
1181 int dm_pool_set_metadata_transaction_id(struct dm_pool_metadata *pmd,
1182                                         uint64_t current_id,
1183                                         uint64_t new_id)
1184 {
1185         int r = -EINVAL;
1186
1187         down_write(&pmd->root_lock);
1188
1189         if (pmd->fail_io)
1190                 goto out;
1191
1192         if (pmd->trans_id != current_id) {
1193                 DMERR("mismatched transaction id");
1194                 goto out;
1195         }
1196
1197         pmd->trans_id = new_id;
1198         r = 0;
1199
1200 out:
1201         up_write(&pmd->root_lock);
1202
1203         return r;
1204 }
1205
1206 int dm_pool_get_metadata_transaction_id(struct dm_pool_metadata *pmd,
1207                                         uint64_t *result)
1208 {
1209         int r = -EINVAL;
1210
1211         down_read(&pmd->root_lock);
1212         if (!pmd->fail_io) {
1213                 *result = pmd->trans_id;
1214                 r = 0;
1215         }
1216         up_read(&pmd->root_lock);
1217
1218         return r;
1219 }
1220
1221 static int __reserve_metadata_snap(struct dm_pool_metadata *pmd)
1222 {
1223         int r, inc;
1224         struct thin_disk_superblock *disk_super;
1225         struct dm_block *copy, *sblock;
1226         dm_block_t held_root;
1227
1228         /*
1229          * We commit to ensure the btree roots which we increment in a
1230          * moment are up to date.
1231          */
1232         __commit_transaction(pmd);
1233
1234         /*
1235          * Copy the superblock.
1236          */
1237         dm_sm_inc_block(pmd->metadata_sm, THIN_SUPERBLOCK_LOCATION);
1238         r = dm_tm_shadow_block(pmd->tm, THIN_SUPERBLOCK_LOCATION,
1239                                &sb_validator, &copy, &inc);
1240         if (r)
1241                 return r;
1242
1243         BUG_ON(!inc);
1244
1245         held_root = dm_block_location(copy);
1246         disk_super = dm_block_data(copy);
1247
1248         if (le64_to_cpu(disk_super->held_root)) {
1249                 DMWARN("Pool metadata snapshot already exists: release this before taking another.");
1250
1251                 dm_tm_dec(pmd->tm, held_root);
1252                 dm_tm_unlock(pmd->tm, copy);
1253                 return -EBUSY;
1254         }
1255
1256         /*
1257          * Wipe the spacemap since we're not publishing this.
1258          */
1259         memset(&disk_super->data_space_map_root, 0,
1260                sizeof(disk_super->data_space_map_root));
1261         memset(&disk_super->metadata_space_map_root, 0,
1262                sizeof(disk_super->metadata_space_map_root));
1263
1264         /*
1265          * Increment the data structures that need to be preserved.
1266          */
1267         dm_tm_inc(pmd->tm, le64_to_cpu(disk_super->data_mapping_root));
1268         dm_tm_inc(pmd->tm, le64_to_cpu(disk_super->device_details_root));
1269         dm_tm_unlock(pmd->tm, copy);
1270
1271         /*
1272          * Write the held root into the superblock.
1273          */
1274         r = superblock_lock(pmd, &sblock);
1275         if (r) {
1276                 dm_tm_dec(pmd->tm, held_root);
1277                 return r;
1278         }
1279
1280         disk_super = dm_block_data(sblock);
1281         disk_super->held_root = cpu_to_le64(held_root);
1282         dm_bm_unlock(sblock);
1283         return 0;
1284 }
1285
1286 int dm_pool_reserve_metadata_snap(struct dm_pool_metadata *pmd)
1287 {
1288         int r = -EINVAL;
1289
1290         down_write(&pmd->root_lock);
1291         if (!pmd->fail_io)
1292                 r = __reserve_metadata_snap(pmd);
1293         up_write(&pmd->root_lock);
1294
1295         return r;
1296 }
1297
1298 static int __release_metadata_snap(struct dm_pool_metadata *pmd)
1299 {
1300         int r;
1301         struct thin_disk_superblock *disk_super;
1302         struct dm_block *sblock, *copy;
1303         dm_block_t held_root;
1304
1305         r = superblock_lock(pmd, &sblock);
1306         if (r)
1307                 return r;
1308
1309         disk_super = dm_block_data(sblock);
1310         held_root = le64_to_cpu(disk_super->held_root);
1311         disk_super->held_root = cpu_to_le64(0);
1312
1313         dm_bm_unlock(sblock);
1314
1315         if (!held_root) {
1316                 DMWARN("No pool metadata snapshot found: nothing to release.");
1317                 return -EINVAL;
1318         }
1319
1320         r = dm_tm_read_lock(pmd->tm, held_root, &sb_validator, &copy);
1321         if (r)
1322                 return r;
1323
1324         disk_super = dm_block_data(copy);
1325         dm_btree_del(&pmd->info, le64_to_cpu(disk_super->data_mapping_root));
1326         dm_btree_del(&pmd->details_info, le64_to_cpu(disk_super->device_details_root));
1327         dm_sm_dec_block(pmd->metadata_sm, held_root);
1328
1329         dm_tm_unlock(pmd->tm, copy);
1330
1331         return 0;
1332 }
1333
1334 int dm_pool_release_metadata_snap(struct dm_pool_metadata *pmd)
1335 {
1336         int r = -EINVAL;
1337
1338         down_write(&pmd->root_lock);
1339         if (!pmd->fail_io)
1340                 r = __release_metadata_snap(pmd);
1341         up_write(&pmd->root_lock);
1342
1343         return r;
1344 }
1345
1346 static int __get_metadata_snap(struct dm_pool_metadata *pmd,
1347                                dm_block_t *result)
1348 {
1349         int r;
1350         struct thin_disk_superblock *disk_super;
1351         struct dm_block *sblock;
1352
1353         r = dm_bm_read_lock(pmd->bm, THIN_SUPERBLOCK_LOCATION,
1354                             &sb_validator, &sblock);
1355         if (r)
1356                 return r;
1357
1358         disk_super = dm_block_data(sblock);
1359         *result = le64_to_cpu(disk_super->held_root);
1360
1361         dm_bm_unlock(sblock);
1362
1363         return 0;
1364 }
1365
1366 int dm_pool_get_metadata_snap(struct dm_pool_metadata *pmd,
1367                               dm_block_t *result)
1368 {
1369         int r = -EINVAL;
1370
1371         down_read(&pmd->root_lock);
1372         if (!pmd->fail_io)
1373                 r = __get_metadata_snap(pmd, result);
1374         up_read(&pmd->root_lock);
1375
1376         return r;
1377 }
1378
1379 int dm_pool_open_thin_device(struct dm_pool_metadata *pmd, dm_thin_id dev,
1380                              struct dm_thin_device **td)
1381 {
1382         int r = -EINVAL;
1383
1384         down_write(&pmd->root_lock);
1385         if (!pmd->fail_io)
1386                 r = __open_device(pmd, dev, 0, td);
1387         up_write(&pmd->root_lock);
1388
1389         return r;
1390 }
1391
1392 int dm_pool_close_thin_device(struct dm_thin_device *td)
1393 {
1394         down_write(&td->pmd->root_lock);
1395         __close_device(td);
1396         up_write(&td->pmd->root_lock);
1397
1398         return 0;
1399 }
1400
1401 dm_thin_id dm_thin_dev_id(struct dm_thin_device *td)
1402 {
1403         return td->id;
1404 }
1405
1406 /*
1407  * Check whether @time (of block creation) is older than @td's last snapshot.
1408  * If so then the associated block is shared with the last snapshot device.
1409  * Any block on a device created *after* the device last got snapshotted is
1410  * necessarily not shared.
1411  */
1412 static bool __snapshotted_since(struct dm_thin_device *td, uint32_t time)
1413 {
1414         return td->snapshotted_time > time;
1415 }
1416
1417 static void unpack_lookup_result(struct dm_thin_device *td, __le64 value,
1418                                  struct dm_thin_lookup_result *result)
1419 {
1420         uint64_t block_time = 0;
1421         dm_block_t exception_block;
1422         uint32_t exception_time;
1423
1424         block_time = le64_to_cpu(value);
1425         unpack_block_time(block_time, &exception_block, &exception_time);
1426         result->block = exception_block;
1427         result->shared = __snapshotted_since(td, exception_time);
1428 }
1429
1430 static int __find_block(struct dm_thin_device *td, dm_block_t block,
1431                         int can_issue_io, struct dm_thin_lookup_result *result)
1432 {
1433         int r;
1434         __le64 value;
1435         struct dm_pool_metadata *pmd = td->pmd;
1436         dm_block_t keys[2] = { td->id, block };
1437         struct dm_btree_info *info;
1438
1439         if (can_issue_io) {
1440                 info = &pmd->info;
1441         } else
1442                 info = &pmd->nb_info;
1443
1444         r = dm_btree_lookup(info, pmd->root, keys, &value);
1445         if (!r)
1446                 unpack_lookup_result(td, value, result);
1447
1448         return r;
1449 }
1450
1451 int dm_thin_find_block(struct dm_thin_device *td, dm_block_t block,
1452                        int can_issue_io, struct dm_thin_lookup_result *result)
1453 {
1454         int r;
1455         struct dm_pool_metadata *pmd = td->pmd;
1456
1457         down_read(&pmd->root_lock);
1458         if (pmd->fail_io) {
1459                 up_read(&pmd->root_lock);
1460                 return -EINVAL;
1461         }
1462
1463         r = __find_block(td, block, can_issue_io, result);
1464
1465         up_read(&pmd->root_lock);
1466         return r;
1467 }
1468
1469 static int __find_next_mapped_block(struct dm_thin_device *td, dm_block_t block,
1470                                           dm_block_t *vblock,
1471                                           struct dm_thin_lookup_result *result)
1472 {
1473         int r;
1474         __le64 value;
1475         struct dm_pool_metadata *pmd = td->pmd;
1476         dm_block_t keys[2] = { td->id, block };
1477
1478         r = dm_btree_lookup_next(&pmd->info, pmd->root, keys, vblock, &value);
1479         if (!r)
1480                 unpack_lookup_result(td, value, result);
1481
1482         return r;
1483 }
1484
1485 static int __find_mapped_range(struct dm_thin_device *td,
1486                                dm_block_t begin, dm_block_t end,
1487                                dm_block_t *thin_begin, dm_block_t *thin_end,
1488                                dm_block_t *pool_begin, bool *maybe_shared)
1489 {
1490         int r;
1491         dm_block_t pool_end;
1492         struct dm_thin_lookup_result lookup;
1493
1494         if (end < begin)
1495                 return -ENODATA;
1496
1497         r = __find_next_mapped_block(td, begin, &begin, &lookup);
1498         if (r)
1499                 return r;
1500
1501         if (begin >= end)
1502                 return -ENODATA;
1503
1504         *thin_begin = begin;
1505         *pool_begin = lookup.block;
1506         *maybe_shared = lookup.shared;
1507
1508         begin++;
1509         pool_end = *pool_begin + 1;
1510         while (begin != end) {
1511                 r = __find_block(td, begin, true, &lookup);
1512                 if (r) {
1513                         if (r == -ENODATA)
1514                                 break;
1515                         else
1516                                 return r;
1517                 }
1518
1519                 if ((lookup.block != pool_end) ||
1520                     (lookup.shared != *maybe_shared))
1521                         break;
1522
1523                 pool_end++;
1524                 begin++;
1525         }
1526
1527         *thin_end = begin;
1528         return 0;
1529 }
1530
1531 int dm_thin_find_mapped_range(struct dm_thin_device *td,
1532                               dm_block_t begin, dm_block_t end,
1533                               dm_block_t *thin_begin, dm_block_t *thin_end,
1534                               dm_block_t *pool_begin, bool *maybe_shared)
1535 {
1536         int r = -EINVAL;
1537         struct dm_pool_metadata *pmd = td->pmd;
1538
1539         down_read(&pmd->root_lock);
1540         if (!pmd->fail_io) {
1541                 r = __find_mapped_range(td, begin, end, thin_begin, thin_end,
1542                                         pool_begin, maybe_shared);
1543         }
1544         up_read(&pmd->root_lock);
1545
1546         return r;
1547 }
1548
1549 static int __insert(struct dm_thin_device *td, dm_block_t block,
1550                     dm_block_t data_block)
1551 {
1552         int r, inserted;
1553         __le64 value;
1554         struct dm_pool_metadata *pmd = td->pmd;
1555         dm_block_t keys[2] = { td->id, block };
1556
1557         value = cpu_to_le64(pack_block_time(data_block, pmd->time));
1558         __dm_bless_for_disk(&value);
1559
1560         r = dm_btree_insert_notify(&pmd->info, pmd->root, keys, &value,
1561                                    &pmd->root, &inserted);
1562         if (r)
1563                 return r;
1564
1565         td->changed = 1;
1566         if (inserted)
1567                 td->mapped_blocks++;
1568
1569         return 0;
1570 }
1571
1572 int dm_thin_insert_block(struct dm_thin_device *td, dm_block_t block,
1573                          dm_block_t data_block)
1574 {
1575         int r = -EINVAL;
1576
1577         down_write(&td->pmd->root_lock);
1578         if (!td->pmd->fail_io)
1579                 r = __insert(td, block, data_block);
1580         up_write(&td->pmd->root_lock);
1581
1582         return r;
1583 }
1584
1585 static int __remove(struct dm_thin_device *td, dm_block_t block)
1586 {
1587         int r;
1588         struct dm_pool_metadata *pmd = td->pmd;
1589         dm_block_t keys[2] = { td->id, block };
1590
1591         r = dm_btree_remove(&pmd->info, pmd->root, keys, &pmd->root);
1592         if (r)
1593                 return r;
1594
1595         td->mapped_blocks--;
1596         td->changed = 1;
1597
1598         return 0;
1599 }
1600
1601 static int __remove_range(struct dm_thin_device *td, dm_block_t begin, dm_block_t end)
1602 {
1603         int r;
1604         unsigned count, total_count = 0;
1605         struct dm_pool_metadata *pmd = td->pmd;
1606         dm_block_t keys[1] = { td->id };
1607         __le64 value;
1608         dm_block_t mapping_root;
1609
1610         /*
1611          * Find the mapping tree
1612          */
1613         r = dm_btree_lookup(&pmd->tl_info, pmd->root, keys, &value);
1614         if (r)
1615                 return r;
1616
1617         /*
1618          * Remove from the mapping tree, taking care to inc the
1619          * ref count so it doesn't get deleted.
1620          */
1621         mapping_root = le64_to_cpu(value);
1622         dm_tm_inc(pmd->tm, mapping_root);
1623         r = dm_btree_remove(&pmd->tl_info, pmd->root, keys, &pmd->root);
1624         if (r)
1625                 return r;
1626
1627         /*
1628          * Remove leaves stops at the first unmapped entry, so we have to
1629          * loop round finding mapped ranges.
1630          */
1631         while (begin < end) {
1632                 r = dm_btree_lookup_next(&pmd->bl_info, mapping_root, &begin, &begin, &value);
1633                 if (r == -ENODATA)
1634                         break;
1635
1636                 if (r)
1637                         return r;
1638
1639                 if (begin >= end)
1640                         break;
1641
1642                 r = dm_btree_remove_leaves(&pmd->bl_info, mapping_root, &begin, end, &mapping_root, &count);
1643                 if (r)
1644                         return r;
1645
1646                 total_count += count;
1647         }
1648
1649         td->mapped_blocks -= total_count;
1650         td->changed = 1;
1651
1652         /*
1653          * Reinsert the mapping tree.
1654          */
1655         value = cpu_to_le64(mapping_root);
1656         __dm_bless_for_disk(&value);
1657         return dm_btree_insert(&pmd->tl_info, pmd->root, keys, &value, &pmd->root);
1658 }
1659
1660 int dm_thin_remove_block(struct dm_thin_device *td, dm_block_t block)
1661 {
1662         int r = -EINVAL;
1663
1664         down_write(&td->pmd->root_lock);
1665         if (!td->pmd->fail_io)
1666                 r = __remove(td, block);
1667         up_write(&td->pmd->root_lock);
1668
1669         return r;
1670 }
1671
1672 int dm_thin_remove_range(struct dm_thin_device *td,
1673                          dm_block_t begin, dm_block_t end)
1674 {
1675         int r = -EINVAL;
1676
1677         down_write(&td->pmd->root_lock);
1678         if (!td->pmd->fail_io)
1679                 r = __remove_range(td, begin, end);
1680         up_write(&td->pmd->root_lock);
1681
1682         return r;
1683 }
1684
1685 int dm_pool_block_is_shared(struct dm_pool_metadata *pmd, dm_block_t b, bool *result)
1686 {
1687         int r;
1688         uint32_t ref_count;
1689
1690         down_read(&pmd->root_lock);
1691         r = dm_sm_get_count(pmd->data_sm, b, &ref_count);
1692         if (!r)
1693                 *result = (ref_count > 1);
1694         up_read(&pmd->root_lock);
1695
1696         return r;
1697 }
1698
1699 int dm_pool_inc_data_range(struct dm_pool_metadata *pmd, dm_block_t b, dm_block_t e)
1700 {
1701         int r = 0;
1702
1703         down_write(&pmd->root_lock);
1704         for (; b != e; b++) {
1705                 r = dm_sm_inc_block(pmd->data_sm, b);
1706                 if (r)
1707                         break;
1708         }
1709         up_write(&pmd->root_lock);
1710
1711         return r;
1712 }
1713
1714 int dm_pool_dec_data_range(struct dm_pool_metadata *pmd, dm_block_t b, dm_block_t e)
1715 {
1716         int r = 0;
1717
1718         down_write(&pmd->root_lock);
1719         for (; b != e; b++) {
1720                 r = dm_sm_dec_block(pmd->data_sm, b);
1721                 if (r)
1722                         break;
1723         }
1724         up_write(&pmd->root_lock);
1725
1726         return r;
1727 }
1728
1729 bool dm_thin_changed_this_transaction(struct dm_thin_device *td)
1730 {
1731         int r;
1732
1733         down_read(&td->pmd->root_lock);
1734         r = td->changed;
1735         up_read(&td->pmd->root_lock);
1736
1737         return r;
1738 }
1739
1740 bool dm_pool_changed_this_transaction(struct dm_pool_metadata *pmd)
1741 {
1742         bool r = false;
1743         struct dm_thin_device *td, *tmp;
1744
1745         down_read(&pmd->root_lock);
1746         list_for_each_entry_safe(td, tmp, &pmd->thin_devices, list) {
1747                 if (td->changed) {
1748                         r = td->changed;
1749                         break;
1750                 }
1751         }
1752         up_read(&pmd->root_lock);
1753
1754         return r;
1755 }
1756
1757 bool dm_thin_aborted_changes(struct dm_thin_device *td)
1758 {
1759         bool r;
1760
1761         down_read(&td->pmd->root_lock);
1762         r = td->aborted_with_changes;
1763         up_read(&td->pmd->root_lock);
1764
1765         return r;
1766 }
1767
1768 int dm_pool_alloc_data_block(struct dm_pool_metadata *pmd, dm_block_t *result)
1769 {
1770         int r = -EINVAL;
1771
1772         down_write(&pmd->root_lock);
1773         if (!pmd->fail_io)
1774                 r = dm_sm_new_block(pmd->data_sm, result);
1775         up_write(&pmd->root_lock);
1776
1777         return r;
1778 }
1779
1780 int dm_pool_commit_metadata(struct dm_pool_metadata *pmd)
1781 {
1782         int r = -EINVAL;
1783
1784         down_write(&pmd->root_lock);
1785         if (pmd->fail_io)
1786                 goto out;
1787
1788         r = __commit_transaction(pmd);
1789         if (r <= 0)
1790                 goto out;
1791
1792         /*
1793          * Open the next transaction.
1794          */
1795         r = __begin_transaction(pmd);
1796 out:
1797         up_write(&pmd->root_lock);
1798         return r;
1799 }
1800
1801 static void __set_abort_with_changes_flags(struct dm_pool_metadata *pmd)
1802 {
1803         struct dm_thin_device *td;
1804
1805         list_for_each_entry(td, &pmd->thin_devices, list)
1806                 td->aborted_with_changes = td->changed;
1807 }
1808
1809 int dm_pool_abort_metadata(struct dm_pool_metadata *pmd)
1810 {
1811         int r = -EINVAL;
1812
1813         down_write(&pmd->root_lock);
1814         if (pmd->fail_io)
1815                 goto out;
1816
1817         __set_abort_with_changes_flags(pmd);
1818         __destroy_persistent_data_objects(pmd);
1819         r = __create_persistent_data_objects(pmd, false);
1820         if (r)
1821                 pmd->fail_io = true;
1822
1823 out:
1824         up_write(&pmd->root_lock);
1825
1826         return r;
1827 }
1828
1829 int dm_pool_get_free_block_count(struct dm_pool_metadata *pmd, dm_block_t *result)
1830 {
1831         int r = -EINVAL;
1832
1833         down_read(&pmd->root_lock);
1834         if (!pmd->fail_io)
1835                 r = dm_sm_get_nr_free(pmd->data_sm, result);
1836         up_read(&pmd->root_lock);
1837
1838         return r;
1839 }
1840
1841 int dm_pool_get_free_metadata_block_count(struct dm_pool_metadata *pmd,
1842                                           dm_block_t *result)
1843 {
1844         int r = -EINVAL;
1845
1846         down_read(&pmd->root_lock);
1847         if (!pmd->fail_io)
1848                 r = dm_sm_get_nr_free(pmd->metadata_sm, result);
1849
1850         if (!r) {
1851                 if (*result < pmd->metadata_reserve)
1852                         *result = 0;
1853                 else
1854                         *result -= pmd->metadata_reserve;
1855         }
1856         up_read(&pmd->root_lock);
1857
1858         return r;
1859 }
1860
1861 int dm_pool_get_metadata_dev_size(struct dm_pool_metadata *pmd,
1862                                   dm_block_t *result)
1863 {
1864         int r = -EINVAL;
1865
1866         down_read(&pmd->root_lock);
1867         if (!pmd->fail_io)
1868                 r = dm_sm_get_nr_blocks(pmd->metadata_sm, result);
1869         up_read(&pmd->root_lock);
1870
1871         return r;
1872 }
1873
1874 int dm_pool_get_data_dev_size(struct dm_pool_metadata *pmd, dm_block_t *result)
1875 {
1876         int r = -EINVAL;
1877
1878         down_read(&pmd->root_lock);
1879         if (!pmd->fail_io)
1880                 r = dm_sm_get_nr_blocks(pmd->data_sm, result);
1881         up_read(&pmd->root_lock);
1882
1883         return r;
1884 }
1885
1886 int dm_thin_get_mapped_count(struct dm_thin_device *td, dm_block_t *result)
1887 {
1888         int r = -EINVAL;
1889         struct dm_pool_metadata *pmd = td->pmd;
1890
1891         down_read(&pmd->root_lock);
1892         if (!pmd->fail_io) {
1893                 *result = td->mapped_blocks;
1894                 r = 0;
1895         }
1896         up_read(&pmd->root_lock);
1897
1898         return r;
1899 }
1900
1901 static int __highest_block(struct dm_thin_device *td, dm_block_t *result)
1902 {
1903         int r;
1904         __le64 value_le;
1905         dm_block_t thin_root;
1906         struct dm_pool_metadata *pmd = td->pmd;
1907
1908         r = dm_btree_lookup(&pmd->tl_info, pmd->root, &td->id, &value_le);
1909         if (r)
1910                 return r;
1911
1912         thin_root = le64_to_cpu(value_le);
1913
1914         return dm_btree_find_highest_key(&pmd->bl_info, thin_root, result);
1915 }
1916
1917 int dm_thin_get_highest_mapped_block(struct dm_thin_device *td,
1918                                      dm_block_t *result)
1919 {
1920         int r = -EINVAL;
1921         struct dm_pool_metadata *pmd = td->pmd;
1922
1923         down_read(&pmd->root_lock);
1924         if (!pmd->fail_io)
1925                 r = __highest_block(td, result);
1926         up_read(&pmd->root_lock);
1927
1928         return r;
1929 }
1930
1931 static int __resize_space_map(struct dm_space_map *sm, dm_block_t new_count)
1932 {
1933         int r;
1934         dm_block_t old_count;
1935
1936         r = dm_sm_get_nr_blocks(sm, &old_count);
1937         if (r)
1938                 return r;
1939
1940         if (new_count == old_count)
1941                 return 0;
1942
1943         if (new_count < old_count) {
1944                 DMERR("cannot reduce size of space map");
1945                 return -EINVAL;
1946         }
1947
1948         return dm_sm_extend(sm, new_count - old_count);
1949 }
1950
1951 int dm_pool_resize_data_dev(struct dm_pool_metadata *pmd, dm_block_t new_count)
1952 {
1953         int r = -EINVAL;
1954
1955         down_write(&pmd->root_lock);
1956         if (!pmd->fail_io)
1957                 r = __resize_space_map(pmd->data_sm, new_count);
1958         up_write(&pmd->root_lock);
1959
1960         return r;
1961 }
1962
1963 int dm_pool_resize_metadata_dev(struct dm_pool_metadata *pmd, dm_block_t new_count)
1964 {
1965         int r = -EINVAL;
1966
1967         down_write(&pmd->root_lock);
1968         if (!pmd->fail_io) {
1969                 r = __resize_space_map(pmd->metadata_sm, new_count);
1970                 if (!r)
1971                         __set_metadata_reserve(pmd);
1972         }
1973         up_write(&pmd->root_lock);
1974
1975         return r;
1976 }
1977
1978 void dm_pool_metadata_read_only(struct dm_pool_metadata *pmd)
1979 {
1980         down_write(&pmd->root_lock);
1981         dm_bm_set_read_only(pmd->bm);
1982         up_write(&pmd->root_lock);
1983 }
1984
1985 void dm_pool_metadata_read_write(struct dm_pool_metadata *pmd)
1986 {
1987         down_write(&pmd->root_lock);
1988         dm_bm_set_read_write(pmd->bm);
1989         up_write(&pmd->root_lock);
1990 }
1991
1992 int dm_pool_register_metadata_threshold(struct dm_pool_metadata *pmd,
1993                                         dm_block_t threshold,
1994                                         dm_sm_threshold_fn fn,
1995                                         void *context)
1996 {
1997         int r;
1998
1999         down_write(&pmd->root_lock);
2000         r = dm_sm_register_threshold_callback(pmd->metadata_sm, threshold, fn, context);
2001         up_write(&pmd->root_lock);
2002
2003         return r;
2004 }
2005
2006 int dm_pool_metadata_set_needs_check(struct dm_pool_metadata *pmd)
2007 {
2008         int r = -EINVAL;
2009         struct dm_block *sblock;
2010         struct thin_disk_superblock *disk_super;
2011
2012         down_write(&pmd->root_lock);
2013         if (pmd->fail_io)
2014                 goto out;
2015
2016         pmd->flags |= THIN_METADATA_NEEDS_CHECK_FLAG;
2017
2018         r = superblock_lock(pmd, &sblock);
2019         if (r) {
2020                 DMERR("couldn't lock superblock");
2021                 goto out;
2022         }
2023
2024         disk_super = dm_block_data(sblock);
2025         disk_super->flags = cpu_to_le32(pmd->flags);
2026
2027         dm_bm_unlock(sblock);
2028 out:
2029         up_write(&pmd->root_lock);
2030         return r;
2031 }
2032
2033 bool dm_pool_metadata_needs_check(struct dm_pool_metadata *pmd)
2034 {
2035         bool needs_check;
2036
2037         down_read(&pmd->root_lock);
2038         needs_check = pmd->flags & THIN_METADATA_NEEDS_CHECK_FLAG;
2039         up_read(&pmd->root_lock);
2040
2041         return needs_check;
2042 }
2043
2044 void dm_pool_issue_prefetches(struct dm_pool_metadata *pmd)
2045 {
2046         down_read(&pmd->root_lock);
2047         if (!pmd->fail_io)
2048                 dm_tm_issue_prefetches(pmd->tm);
2049         up_read(&pmd->root_lock);
2050 }