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