dm table: add singleton feature
[cascardo/linux.git] / drivers / md / dm-table.c
1 /*
2  * Copyright (C) 2001 Sistina Software (UK) Limited.
3  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include "dm.h"
9
10 #include <linux/module.h>
11 #include <linux/vmalloc.h>
12 #include <linux/blkdev.h>
13 #include <linux/namei.h>
14 #include <linux/ctype.h>
15 #include <linux/string.h>
16 #include <linux/slab.h>
17 #include <linux/interrupt.h>
18 #include <linux/mutex.h>
19 #include <linux/delay.h>
20 #include <linux/atomic.h>
21
22 #define DM_MSG_PREFIX "table"
23
24 #define MAX_DEPTH 16
25 #define NODE_SIZE L1_CACHE_BYTES
26 #define KEYS_PER_NODE (NODE_SIZE / sizeof(sector_t))
27 #define CHILDREN_PER_NODE (KEYS_PER_NODE + 1)
28
29 /*
30  * The table has always exactly one reference from either mapped_device->map
31  * or hash_cell->new_map. This reference is not counted in table->holders.
32  * A pair of dm_create_table/dm_destroy_table functions is used for table
33  * creation/destruction.
34  *
35  * Temporary references from the other code increase table->holders. A pair
36  * of dm_table_get/dm_table_put functions is used to manipulate it.
37  *
38  * When the table is about to be destroyed, we wait for table->holders to
39  * drop to zero.
40  */
41
42 struct dm_table {
43         struct mapped_device *md;
44         atomic_t holders;
45         unsigned type;
46
47         /* btree table */
48         unsigned int depth;
49         unsigned int counts[MAX_DEPTH]; /* in nodes */
50         sector_t *index[MAX_DEPTH];
51
52         unsigned int num_targets;
53         unsigned int num_allocated;
54         sector_t *highs;
55         struct dm_target *targets;
56
57         unsigned integrity_supported:1;
58         unsigned singleton:1;
59
60         /*
61          * Indicates the rw permissions for the new logical
62          * device.  This should be a combination of FMODE_READ
63          * and FMODE_WRITE.
64          */
65         fmode_t mode;
66
67         /* a list of devices used by this table */
68         struct list_head devices;
69
70         /* events get handed up using this callback */
71         void (*event_fn)(void *);
72         void *event_context;
73
74         struct dm_md_mempools *mempools;
75
76         struct list_head target_callbacks;
77 };
78
79 /*
80  * Similar to ceiling(log_size(n))
81  */
82 static unsigned int int_log(unsigned int n, unsigned int base)
83 {
84         int result = 0;
85
86         while (n > 1) {
87                 n = dm_div_up(n, base);
88                 result++;
89         }
90
91         return result;
92 }
93
94 /*
95  * Calculate the index of the child node of the n'th node k'th key.
96  */
97 static inline unsigned int get_child(unsigned int n, unsigned int k)
98 {
99         return (n * CHILDREN_PER_NODE) + k;
100 }
101
102 /*
103  * Return the n'th node of level l from table t.
104  */
105 static inline sector_t *get_node(struct dm_table *t,
106                                  unsigned int l, unsigned int n)
107 {
108         return t->index[l] + (n * KEYS_PER_NODE);
109 }
110
111 /*
112  * Return the highest key that you could lookup from the n'th
113  * node on level l of the btree.
114  */
115 static sector_t high(struct dm_table *t, unsigned int l, unsigned int n)
116 {
117         for (; l < t->depth - 1; l++)
118                 n = get_child(n, CHILDREN_PER_NODE - 1);
119
120         if (n >= t->counts[l])
121                 return (sector_t) - 1;
122
123         return get_node(t, l, n)[KEYS_PER_NODE - 1];
124 }
125
126 /*
127  * Fills in a level of the btree based on the highs of the level
128  * below it.
129  */
130 static int setup_btree_index(unsigned int l, struct dm_table *t)
131 {
132         unsigned int n, k;
133         sector_t *node;
134
135         for (n = 0U; n < t->counts[l]; n++) {
136                 node = get_node(t, l, n);
137
138                 for (k = 0U; k < KEYS_PER_NODE; k++)
139                         node[k] = high(t, l + 1, get_child(n, k));
140         }
141
142         return 0;
143 }
144
145 void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size)
146 {
147         unsigned long size;
148         void *addr;
149
150         /*
151          * Check that we're not going to overflow.
152          */
153         if (nmemb > (ULONG_MAX / elem_size))
154                 return NULL;
155
156         size = nmemb * elem_size;
157         addr = vzalloc(size);
158
159         return addr;
160 }
161 EXPORT_SYMBOL(dm_vcalloc);
162
163 /*
164  * highs, and targets are managed as dynamic arrays during a
165  * table load.
166  */
167 static int alloc_targets(struct dm_table *t, unsigned int num)
168 {
169         sector_t *n_highs;
170         struct dm_target *n_targets;
171         int n = t->num_targets;
172
173         /*
174          * Allocate both the target array and offset array at once.
175          * Append an empty entry to catch sectors beyond the end of
176          * the device.
177          */
178         n_highs = (sector_t *) dm_vcalloc(num + 1, sizeof(struct dm_target) +
179                                           sizeof(sector_t));
180         if (!n_highs)
181                 return -ENOMEM;
182
183         n_targets = (struct dm_target *) (n_highs + num);
184
185         if (n) {
186                 memcpy(n_highs, t->highs, sizeof(*n_highs) * n);
187                 memcpy(n_targets, t->targets, sizeof(*n_targets) * n);
188         }
189
190         memset(n_highs + n, -1, sizeof(*n_highs) * (num - n));
191         vfree(t->highs);
192
193         t->num_allocated = num;
194         t->highs = n_highs;
195         t->targets = n_targets;
196
197         return 0;
198 }
199
200 int dm_table_create(struct dm_table **result, fmode_t mode,
201                     unsigned num_targets, struct mapped_device *md)
202 {
203         struct dm_table *t = kzalloc(sizeof(*t), GFP_KERNEL);
204
205         if (!t)
206                 return -ENOMEM;
207
208         INIT_LIST_HEAD(&t->devices);
209         INIT_LIST_HEAD(&t->target_callbacks);
210         atomic_set(&t->holders, 0);
211
212         if (!num_targets)
213                 num_targets = KEYS_PER_NODE;
214
215         num_targets = dm_round_up(num_targets, KEYS_PER_NODE);
216
217         if (alloc_targets(t, num_targets)) {
218                 kfree(t);
219                 t = NULL;
220                 return -ENOMEM;
221         }
222
223         t->mode = mode;
224         t->md = md;
225         *result = t;
226         return 0;
227 }
228
229 static void free_devices(struct list_head *devices)
230 {
231         struct list_head *tmp, *next;
232
233         list_for_each_safe(tmp, next, devices) {
234                 struct dm_dev_internal *dd =
235                     list_entry(tmp, struct dm_dev_internal, list);
236                 DMWARN("dm_table_destroy: dm_put_device call missing for %s",
237                        dd->dm_dev.name);
238                 kfree(dd);
239         }
240 }
241
242 void dm_table_destroy(struct dm_table *t)
243 {
244         unsigned int i;
245
246         if (!t)
247                 return;
248
249         while (atomic_read(&t->holders))
250                 msleep(1);
251         smp_mb();
252
253         /* free the indexes */
254         if (t->depth >= 2)
255                 vfree(t->index[t->depth - 2]);
256
257         /* free the targets */
258         for (i = 0; i < t->num_targets; i++) {
259                 struct dm_target *tgt = t->targets + i;
260
261                 if (tgt->type->dtr)
262                         tgt->type->dtr(tgt);
263
264                 dm_put_target_type(tgt->type);
265         }
266
267         vfree(t->highs);
268
269         /* free the device list */
270         if (t->devices.next != &t->devices)
271                 free_devices(&t->devices);
272
273         dm_free_md_mempools(t->mempools);
274
275         kfree(t);
276 }
277
278 void dm_table_get(struct dm_table *t)
279 {
280         atomic_inc(&t->holders);
281 }
282 EXPORT_SYMBOL(dm_table_get);
283
284 void dm_table_put(struct dm_table *t)
285 {
286         if (!t)
287                 return;
288
289         smp_mb__before_atomic_dec();
290         atomic_dec(&t->holders);
291 }
292 EXPORT_SYMBOL(dm_table_put);
293
294 /*
295  * Checks to see if we need to extend highs or targets.
296  */
297 static inline int check_space(struct dm_table *t)
298 {
299         if (t->num_targets >= t->num_allocated)
300                 return alloc_targets(t, t->num_allocated * 2);
301
302         return 0;
303 }
304
305 /*
306  * See if we've already got a device in the list.
307  */
308 static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev)
309 {
310         struct dm_dev_internal *dd;
311
312         list_for_each_entry (dd, l, list)
313                 if (dd->dm_dev.bdev->bd_dev == dev)
314                         return dd;
315
316         return NULL;
317 }
318
319 /*
320  * Open a device so we can use it as a map destination.
321  */
322 static int open_dev(struct dm_dev_internal *d, dev_t dev,
323                     struct mapped_device *md)
324 {
325         static char *_claim_ptr = "I belong to device-mapper";
326         struct block_device *bdev;
327
328         int r;
329
330         BUG_ON(d->dm_dev.bdev);
331
332         bdev = blkdev_get_by_dev(dev, d->dm_dev.mode | FMODE_EXCL, _claim_ptr);
333         if (IS_ERR(bdev))
334                 return PTR_ERR(bdev);
335
336         r = bd_link_disk_holder(bdev, dm_disk(md));
337         if (r) {
338                 blkdev_put(bdev, d->dm_dev.mode | FMODE_EXCL);
339                 return r;
340         }
341
342         d->dm_dev.bdev = bdev;
343         return 0;
344 }
345
346 /*
347  * Close a device that we've been using.
348  */
349 static void close_dev(struct dm_dev_internal *d, struct mapped_device *md)
350 {
351         if (!d->dm_dev.bdev)
352                 return;
353
354         bd_unlink_disk_holder(d->dm_dev.bdev, dm_disk(md));
355         blkdev_put(d->dm_dev.bdev, d->dm_dev.mode | FMODE_EXCL);
356         d->dm_dev.bdev = NULL;
357 }
358
359 /*
360  * If possible, this checks an area of a destination device is invalid.
361  */
362 static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev,
363                                   sector_t start, sector_t len, void *data)
364 {
365         struct request_queue *q;
366         struct queue_limits *limits = data;
367         struct block_device *bdev = dev->bdev;
368         sector_t dev_size =
369                 i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
370         unsigned short logical_block_size_sectors =
371                 limits->logical_block_size >> SECTOR_SHIFT;
372         char b[BDEVNAME_SIZE];
373
374         /*
375          * Some devices exist without request functions,
376          * such as loop devices not yet bound to backing files.
377          * Forbid the use of such devices.
378          */
379         q = bdev_get_queue(bdev);
380         if (!q || !q->make_request_fn) {
381                 DMWARN("%s: %s is not yet initialised: "
382                        "start=%llu, len=%llu, dev_size=%llu",
383                        dm_device_name(ti->table->md), bdevname(bdev, b),
384                        (unsigned long long)start,
385                        (unsigned long long)len,
386                        (unsigned long long)dev_size);
387                 return 1;
388         }
389
390         if (!dev_size)
391                 return 0;
392
393         if ((start >= dev_size) || (start + len > dev_size)) {
394                 DMWARN("%s: %s too small for target: "
395                        "start=%llu, len=%llu, dev_size=%llu",
396                        dm_device_name(ti->table->md), bdevname(bdev, b),
397                        (unsigned long long)start,
398                        (unsigned long long)len,
399                        (unsigned long long)dev_size);
400                 return 1;
401         }
402
403         if (logical_block_size_sectors <= 1)
404                 return 0;
405
406         if (start & (logical_block_size_sectors - 1)) {
407                 DMWARN("%s: start=%llu not aligned to h/w "
408                        "logical block size %u of %s",
409                        dm_device_name(ti->table->md),
410                        (unsigned long long)start,
411                        limits->logical_block_size, bdevname(bdev, b));
412                 return 1;
413         }
414
415         if (len & (logical_block_size_sectors - 1)) {
416                 DMWARN("%s: len=%llu not aligned to h/w "
417                        "logical block size %u of %s",
418                        dm_device_name(ti->table->md),
419                        (unsigned long long)len,
420                        limits->logical_block_size, bdevname(bdev, b));
421                 return 1;
422         }
423
424         return 0;
425 }
426
427 /*
428  * This upgrades the mode on an already open dm_dev, being
429  * careful to leave things as they were if we fail to reopen the
430  * device and not to touch the existing bdev field in case
431  * it is accessed concurrently inside dm_table_any_congested().
432  */
433 static int upgrade_mode(struct dm_dev_internal *dd, fmode_t new_mode,
434                         struct mapped_device *md)
435 {
436         int r;
437         struct dm_dev_internal dd_new, dd_old;
438
439         dd_new = dd_old = *dd;
440
441         dd_new.dm_dev.mode |= new_mode;
442         dd_new.dm_dev.bdev = NULL;
443
444         r = open_dev(&dd_new, dd->dm_dev.bdev->bd_dev, md);
445         if (r)
446                 return r;
447
448         dd->dm_dev.mode |= new_mode;
449         close_dev(&dd_old, md);
450
451         return 0;
452 }
453
454 /*
455  * Add a device to the list, or just increment the usage count if
456  * it's already present.
457  */
458 int dm_get_device(struct dm_target *ti, const char *path, fmode_t mode,
459                   struct dm_dev **result)
460 {
461         int r;
462         dev_t uninitialized_var(dev);
463         struct dm_dev_internal *dd;
464         unsigned int major, minor;
465         struct dm_table *t = ti->table;
466
467         BUG_ON(!t);
468
469         if (sscanf(path, "%u:%u", &major, &minor) == 2) {
470                 /* Extract the major/minor numbers */
471                 dev = MKDEV(major, minor);
472                 if (MAJOR(dev) != major || MINOR(dev) != minor)
473                         return -EOVERFLOW;
474         } else {
475                 /* convert the path to a device */
476                 struct block_device *bdev = lookup_bdev(path);
477
478                 if (IS_ERR(bdev))
479                         return PTR_ERR(bdev);
480                 dev = bdev->bd_dev;
481                 bdput(bdev);
482         }
483
484         dd = find_device(&t->devices, dev);
485         if (!dd) {
486                 dd = kmalloc(sizeof(*dd), GFP_KERNEL);
487                 if (!dd)
488                         return -ENOMEM;
489
490                 dd->dm_dev.mode = mode;
491                 dd->dm_dev.bdev = NULL;
492
493                 if ((r = open_dev(dd, dev, t->md))) {
494                         kfree(dd);
495                         return r;
496                 }
497
498                 format_dev_t(dd->dm_dev.name, dev);
499
500                 atomic_set(&dd->count, 0);
501                 list_add(&dd->list, &t->devices);
502
503         } else if (dd->dm_dev.mode != (mode | dd->dm_dev.mode)) {
504                 r = upgrade_mode(dd, mode, t->md);
505                 if (r)
506                         return r;
507         }
508         atomic_inc(&dd->count);
509
510         *result = &dd->dm_dev;
511         return 0;
512 }
513 EXPORT_SYMBOL(dm_get_device);
514
515 int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
516                          sector_t start, sector_t len, void *data)
517 {
518         struct queue_limits *limits = data;
519         struct block_device *bdev = dev->bdev;
520         struct request_queue *q = bdev_get_queue(bdev);
521         char b[BDEVNAME_SIZE];
522
523         if (unlikely(!q)) {
524                 DMWARN("%s: Cannot set limits for nonexistent device %s",
525                        dm_device_name(ti->table->md), bdevname(bdev, b));
526                 return 0;
527         }
528
529         if (bdev_stack_limits(limits, bdev, start) < 0)
530                 DMWARN("%s: adding target device %s caused an alignment inconsistency: "
531                        "physical_block_size=%u, logical_block_size=%u, "
532                        "alignment_offset=%u, start=%llu",
533                        dm_device_name(ti->table->md), bdevname(bdev, b),
534                        q->limits.physical_block_size,
535                        q->limits.logical_block_size,
536                        q->limits.alignment_offset,
537                        (unsigned long long) start << SECTOR_SHIFT);
538
539         /*
540          * Check if merge fn is supported.
541          * If not we'll force DM to use PAGE_SIZE or
542          * smaller I/O, just to be safe.
543          */
544         if (dm_queue_merge_is_compulsory(q) && !ti->type->merge)
545                 blk_limits_max_hw_sectors(limits,
546                                           (unsigned int) (PAGE_SIZE >> 9));
547         return 0;
548 }
549 EXPORT_SYMBOL_GPL(dm_set_device_limits);
550
551 /*
552  * Decrement a device's use count and remove it if necessary.
553  */
554 void dm_put_device(struct dm_target *ti, struct dm_dev *d)
555 {
556         struct dm_dev_internal *dd = container_of(d, struct dm_dev_internal,
557                                                   dm_dev);
558
559         if (atomic_dec_and_test(&dd->count)) {
560                 close_dev(dd, ti->table->md);
561                 list_del(&dd->list);
562                 kfree(dd);
563         }
564 }
565 EXPORT_SYMBOL(dm_put_device);
566
567 /*
568  * Checks to see if the target joins onto the end of the table.
569  */
570 static int adjoin(struct dm_table *table, struct dm_target *ti)
571 {
572         struct dm_target *prev;
573
574         if (!table->num_targets)
575                 return !ti->begin;
576
577         prev = &table->targets[table->num_targets - 1];
578         return (ti->begin == (prev->begin + prev->len));
579 }
580
581 /*
582  * Used to dynamically allocate the arg array.
583  */
584 static char **realloc_argv(unsigned *array_size, char **old_argv)
585 {
586         char **argv;
587         unsigned new_size;
588
589         new_size = *array_size ? *array_size * 2 : 64;
590         argv = kmalloc(new_size * sizeof(*argv), GFP_KERNEL);
591         if (argv) {
592                 memcpy(argv, old_argv, *array_size * sizeof(*argv));
593                 *array_size = new_size;
594         }
595
596         kfree(old_argv);
597         return argv;
598 }
599
600 /*
601  * Destructively splits up the argument list to pass to ctr.
602  */
603 int dm_split_args(int *argc, char ***argvp, char *input)
604 {
605         char *start, *end = input, *out, **argv = NULL;
606         unsigned array_size = 0;
607
608         *argc = 0;
609
610         if (!input) {
611                 *argvp = NULL;
612                 return 0;
613         }
614
615         argv = realloc_argv(&array_size, argv);
616         if (!argv)
617                 return -ENOMEM;
618
619         while (1) {
620                 /* Skip whitespace */
621                 start = skip_spaces(end);
622
623                 if (!*start)
624                         break;  /* success, we hit the end */
625
626                 /* 'out' is used to remove any back-quotes */
627                 end = out = start;
628                 while (*end) {
629                         /* Everything apart from '\0' can be quoted */
630                         if (*end == '\\' && *(end + 1)) {
631                                 *out++ = *(end + 1);
632                                 end += 2;
633                                 continue;
634                         }
635
636                         if (isspace(*end))
637                                 break;  /* end of token */
638
639                         *out++ = *end++;
640                 }
641
642                 /* have we already filled the array ? */
643                 if ((*argc + 1) > array_size) {
644                         argv = realloc_argv(&array_size, argv);
645                         if (!argv)
646                                 return -ENOMEM;
647                 }
648
649                 /* we know this is whitespace */
650                 if (*end)
651                         end++;
652
653                 /* terminate the string and put it in the array */
654                 *out = '\0';
655                 argv[*argc] = start;
656                 (*argc)++;
657         }
658
659         *argvp = argv;
660         return 0;
661 }
662
663 /*
664  * Impose necessary and sufficient conditions on a devices's table such
665  * that any incoming bio which respects its logical_block_size can be
666  * processed successfully.  If it falls across the boundary between
667  * two or more targets, the size of each piece it gets split into must
668  * be compatible with the logical_block_size of the target processing it.
669  */
670 static int validate_hardware_logical_block_alignment(struct dm_table *table,
671                                                  struct queue_limits *limits)
672 {
673         /*
674          * This function uses arithmetic modulo the logical_block_size
675          * (in units of 512-byte sectors).
676          */
677         unsigned short device_logical_block_size_sects =
678                 limits->logical_block_size >> SECTOR_SHIFT;
679
680         /*
681          * Offset of the start of the next table entry, mod logical_block_size.
682          */
683         unsigned short next_target_start = 0;
684
685         /*
686          * Given an aligned bio that extends beyond the end of a
687          * target, how many sectors must the next target handle?
688          */
689         unsigned short remaining = 0;
690
691         struct dm_target *uninitialized_var(ti);
692         struct queue_limits ti_limits;
693         unsigned i = 0;
694
695         /*
696          * Check each entry in the table in turn.
697          */
698         while (i < dm_table_get_num_targets(table)) {
699                 ti = dm_table_get_target(table, i++);
700
701                 blk_set_default_limits(&ti_limits);
702
703                 /* combine all target devices' limits */
704                 if (ti->type->iterate_devices)
705                         ti->type->iterate_devices(ti, dm_set_device_limits,
706                                                   &ti_limits);
707
708                 /*
709                  * If the remaining sectors fall entirely within this
710                  * table entry are they compatible with its logical_block_size?
711                  */
712                 if (remaining < ti->len &&
713                     remaining & ((ti_limits.logical_block_size >>
714                                   SECTOR_SHIFT) - 1))
715                         break;  /* Error */
716
717                 next_target_start =
718                     (unsigned short) ((next_target_start + ti->len) &
719                                       (device_logical_block_size_sects - 1));
720                 remaining = next_target_start ?
721                     device_logical_block_size_sects - next_target_start : 0;
722         }
723
724         if (remaining) {
725                 DMWARN("%s: table line %u (start sect %llu len %llu) "
726                        "not aligned to h/w logical block size %u",
727                        dm_device_name(table->md), i,
728                        (unsigned long long) ti->begin,
729                        (unsigned long long) ti->len,
730                        limits->logical_block_size);
731                 return -EINVAL;
732         }
733
734         return 0;
735 }
736
737 int dm_table_add_target(struct dm_table *t, const char *type,
738                         sector_t start, sector_t len, char *params)
739 {
740         int r = -EINVAL, argc;
741         char **argv;
742         struct dm_target *tgt;
743
744         if (t->singleton) {
745                 DMERR("%s: target type %s must appear alone in table",
746                       dm_device_name(t->md), t->targets->type->name);
747                 return -EINVAL;
748         }
749
750         if ((r = check_space(t)))
751                 return r;
752
753         tgt = t->targets + t->num_targets;
754         memset(tgt, 0, sizeof(*tgt));
755
756         if (!len) {
757                 DMERR("%s: zero-length target", dm_device_name(t->md));
758                 return -EINVAL;
759         }
760
761         tgt->type = dm_get_target_type(type);
762         if (!tgt->type) {
763                 DMERR("%s: %s: unknown target type", dm_device_name(t->md),
764                       type);
765                 return -EINVAL;
766         }
767
768         if (dm_target_needs_singleton(tgt->type)) {
769                 if (t->num_targets) {
770                         DMERR("%s: target type %s must appear alone in table",
771                               dm_device_name(t->md), type);
772                         return -EINVAL;
773                 }
774                 t->singleton = 1;
775         }
776
777         tgt->table = t;
778         tgt->begin = start;
779         tgt->len = len;
780         tgt->error = "Unknown error";
781
782         /*
783          * Does this target adjoin the previous one ?
784          */
785         if (!adjoin(t, tgt)) {
786                 tgt->error = "Gap in table";
787                 r = -EINVAL;
788                 goto bad;
789         }
790
791         r = dm_split_args(&argc, &argv, params);
792         if (r) {
793                 tgt->error = "couldn't split parameters (insufficient memory)";
794                 goto bad;
795         }
796
797         r = tgt->type->ctr(tgt, argc, argv);
798         kfree(argv);
799         if (r)
800                 goto bad;
801
802         t->highs[t->num_targets++] = tgt->begin + tgt->len - 1;
803
804         if (!tgt->num_discard_requests && tgt->discards_supported)
805                 DMWARN("%s: %s: ignoring discards_supported because num_discard_requests is zero.",
806                        dm_device_name(t->md), type);
807
808         return 0;
809
810  bad:
811         DMERR("%s: %s: %s", dm_device_name(t->md), type, tgt->error);
812         dm_put_target_type(tgt->type);
813         return r;
814 }
815
816 /*
817  * Target argument parsing helpers.
818  */
819 static int validate_next_arg(struct dm_arg *arg, struct dm_arg_set *arg_set,
820                              unsigned *value, char **error, unsigned grouped)
821 {
822         const char *arg_str = dm_shift_arg(arg_set);
823
824         if (!arg_str ||
825             (sscanf(arg_str, "%u", value) != 1) ||
826             (*value < arg->min) ||
827             (*value > arg->max) ||
828             (grouped && arg_set->argc < *value)) {
829                 *error = arg->error;
830                 return -EINVAL;
831         }
832
833         return 0;
834 }
835
836 int dm_read_arg(struct dm_arg *arg, struct dm_arg_set *arg_set,
837                 unsigned *value, char **error)
838 {
839         return validate_next_arg(arg, arg_set, value, error, 0);
840 }
841 EXPORT_SYMBOL(dm_read_arg);
842
843 int dm_read_arg_group(struct dm_arg *arg, struct dm_arg_set *arg_set,
844                       unsigned *value, char **error)
845 {
846         return validate_next_arg(arg, arg_set, value, error, 1);
847 }
848 EXPORT_SYMBOL(dm_read_arg_group);
849
850 const char *dm_shift_arg(struct dm_arg_set *as)
851 {
852         char *r;
853
854         if (as->argc) {
855                 as->argc--;
856                 r = *as->argv;
857                 as->argv++;
858                 return r;
859         }
860
861         return NULL;
862 }
863 EXPORT_SYMBOL(dm_shift_arg);
864
865 void dm_consume_args(struct dm_arg_set *as, unsigned num_args)
866 {
867         BUG_ON(as->argc < num_args);
868         as->argc -= num_args;
869         as->argv += num_args;
870 }
871 EXPORT_SYMBOL(dm_consume_args);
872
873 static int dm_table_set_type(struct dm_table *t)
874 {
875         unsigned i;
876         unsigned bio_based = 0, request_based = 0;
877         struct dm_target *tgt;
878         struct dm_dev_internal *dd;
879         struct list_head *devices;
880
881         for (i = 0; i < t->num_targets; i++) {
882                 tgt = t->targets + i;
883                 if (dm_target_request_based(tgt))
884                         request_based = 1;
885                 else
886                         bio_based = 1;
887
888                 if (bio_based && request_based) {
889                         DMWARN("Inconsistent table: different target types"
890                                " can't be mixed up");
891                         return -EINVAL;
892                 }
893         }
894
895         if (bio_based) {
896                 /* We must use this table as bio-based */
897                 t->type = DM_TYPE_BIO_BASED;
898                 return 0;
899         }
900
901         BUG_ON(!request_based); /* No targets in this table */
902
903         /* Non-request-stackable devices can't be used for request-based dm */
904         devices = dm_table_get_devices(t);
905         list_for_each_entry(dd, devices, list) {
906                 if (!blk_queue_stackable(bdev_get_queue(dd->dm_dev.bdev))) {
907                         DMWARN("table load rejected: including"
908                                " non-request-stackable devices");
909                         return -EINVAL;
910                 }
911         }
912
913         /*
914          * Request-based dm supports only tables that have a single target now.
915          * To support multiple targets, request splitting support is needed,
916          * and that needs lots of changes in the block-layer.
917          * (e.g. request completion process for partial completion.)
918          */
919         if (t->num_targets > 1) {
920                 DMWARN("Request-based dm doesn't support multiple targets yet");
921                 return -EINVAL;
922         }
923
924         t->type = DM_TYPE_REQUEST_BASED;
925
926         return 0;
927 }
928
929 unsigned dm_table_get_type(struct dm_table *t)
930 {
931         return t->type;
932 }
933
934 bool dm_table_request_based(struct dm_table *t)
935 {
936         return dm_table_get_type(t) == DM_TYPE_REQUEST_BASED;
937 }
938
939 int dm_table_alloc_md_mempools(struct dm_table *t)
940 {
941         unsigned type = dm_table_get_type(t);
942
943         if (unlikely(type == DM_TYPE_NONE)) {
944                 DMWARN("no table type is set, can't allocate mempools");
945                 return -EINVAL;
946         }
947
948         t->mempools = dm_alloc_md_mempools(type, t->integrity_supported);
949         if (!t->mempools)
950                 return -ENOMEM;
951
952         return 0;
953 }
954
955 void dm_table_free_md_mempools(struct dm_table *t)
956 {
957         dm_free_md_mempools(t->mempools);
958         t->mempools = NULL;
959 }
960
961 struct dm_md_mempools *dm_table_get_md_mempools(struct dm_table *t)
962 {
963         return t->mempools;
964 }
965
966 static int setup_indexes(struct dm_table *t)
967 {
968         int i;
969         unsigned int total = 0;
970         sector_t *indexes;
971
972         /* allocate the space for *all* the indexes */
973         for (i = t->depth - 2; i >= 0; i--) {
974                 t->counts[i] = dm_div_up(t->counts[i + 1], CHILDREN_PER_NODE);
975                 total += t->counts[i];
976         }
977
978         indexes = (sector_t *) dm_vcalloc(total, (unsigned long) NODE_SIZE);
979         if (!indexes)
980                 return -ENOMEM;
981
982         /* set up internal nodes, bottom-up */
983         for (i = t->depth - 2; i >= 0; i--) {
984                 t->index[i] = indexes;
985                 indexes += (KEYS_PER_NODE * t->counts[i]);
986                 setup_btree_index(i, t);
987         }
988
989         return 0;
990 }
991
992 /*
993  * Builds the btree to index the map.
994  */
995 static int dm_table_build_index(struct dm_table *t)
996 {
997         int r = 0;
998         unsigned int leaf_nodes;
999
1000         /* how many indexes will the btree have ? */
1001         leaf_nodes = dm_div_up(t->num_targets, KEYS_PER_NODE);
1002         t->depth = 1 + int_log(leaf_nodes, CHILDREN_PER_NODE);
1003
1004         /* leaf layer has already been set up */
1005         t->counts[t->depth - 1] = leaf_nodes;
1006         t->index[t->depth - 1] = t->highs;
1007
1008         if (t->depth >= 2)
1009                 r = setup_indexes(t);
1010
1011         return r;
1012 }
1013
1014 /*
1015  * Get a disk whose integrity profile reflects the table's profile.
1016  * If %match_all is true, all devices' profiles must match.
1017  * If %match_all is false, all devices must at least have an
1018  * allocated integrity profile; but uninitialized is ok.
1019  * Returns NULL if integrity support was inconsistent or unavailable.
1020  */
1021 static struct gendisk * dm_table_get_integrity_disk(struct dm_table *t,
1022                                                     bool match_all)
1023 {
1024         struct list_head *devices = dm_table_get_devices(t);
1025         struct dm_dev_internal *dd = NULL;
1026         struct gendisk *prev_disk = NULL, *template_disk = NULL;
1027
1028         list_for_each_entry(dd, devices, list) {
1029                 template_disk = dd->dm_dev.bdev->bd_disk;
1030                 if (!blk_get_integrity(template_disk))
1031                         goto no_integrity;
1032                 if (!match_all && !blk_integrity_is_initialized(template_disk))
1033                         continue; /* skip uninitialized profiles */
1034                 else if (prev_disk &&
1035                          blk_integrity_compare(prev_disk, template_disk) < 0)
1036                         goto no_integrity;
1037                 prev_disk = template_disk;
1038         }
1039
1040         return template_disk;
1041
1042 no_integrity:
1043         if (prev_disk)
1044                 DMWARN("%s: integrity not set: %s and %s profile mismatch",
1045                        dm_device_name(t->md),
1046                        prev_disk->disk_name,
1047                        template_disk->disk_name);
1048         return NULL;
1049 }
1050
1051 /*
1052  * Register the mapped device for blk_integrity support if
1053  * the underlying devices have an integrity profile.  But all devices
1054  * may not have matching profiles (checking all devices isn't reliable
1055  * during table load because this table may use other DM device(s) which
1056  * must be resumed before they will have an initialized integity profile).
1057  * Stacked DM devices force a 2 stage integrity profile validation:
1058  * 1 - during load, validate all initialized integrity profiles match
1059  * 2 - during resume, validate all integrity profiles match
1060  */
1061 static int dm_table_prealloc_integrity(struct dm_table *t, struct mapped_device *md)
1062 {
1063         struct gendisk *template_disk = NULL;
1064
1065         template_disk = dm_table_get_integrity_disk(t, false);
1066         if (!template_disk)
1067                 return 0;
1068
1069         if (!blk_integrity_is_initialized(dm_disk(md))) {
1070                 t->integrity_supported = 1;
1071                 return blk_integrity_register(dm_disk(md), NULL);
1072         }
1073
1074         /*
1075          * If DM device already has an initalized integrity
1076          * profile the new profile should not conflict.
1077          */
1078         if (blk_integrity_is_initialized(template_disk) &&
1079             blk_integrity_compare(dm_disk(md), template_disk) < 0) {
1080                 DMWARN("%s: conflict with existing integrity profile: "
1081                        "%s profile mismatch",
1082                        dm_device_name(t->md),
1083                        template_disk->disk_name);
1084                 return 1;
1085         }
1086
1087         /* Preserve existing initialized integrity profile */
1088         t->integrity_supported = 1;
1089         return 0;
1090 }
1091
1092 /*
1093  * Prepares the table for use by building the indices,
1094  * setting the type, and allocating mempools.
1095  */
1096 int dm_table_complete(struct dm_table *t)
1097 {
1098         int r;
1099
1100         r = dm_table_set_type(t);
1101         if (r) {
1102                 DMERR("unable to set table type");
1103                 return r;
1104         }
1105
1106         r = dm_table_build_index(t);
1107         if (r) {
1108                 DMERR("unable to build btrees");
1109                 return r;
1110         }
1111
1112         r = dm_table_prealloc_integrity(t, t->md);
1113         if (r) {
1114                 DMERR("could not register integrity profile.");
1115                 return r;
1116         }
1117
1118         r = dm_table_alloc_md_mempools(t);
1119         if (r)
1120                 DMERR("unable to allocate mempools");
1121
1122         return r;
1123 }
1124
1125 static DEFINE_MUTEX(_event_lock);
1126 void dm_table_event_callback(struct dm_table *t,
1127                              void (*fn)(void *), void *context)
1128 {
1129         mutex_lock(&_event_lock);
1130         t->event_fn = fn;
1131         t->event_context = context;
1132         mutex_unlock(&_event_lock);
1133 }
1134
1135 void dm_table_event(struct dm_table *t)
1136 {
1137         /*
1138          * You can no longer call dm_table_event() from interrupt
1139          * context, use a bottom half instead.
1140          */
1141         BUG_ON(in_interrupt());
1142
1143         mutex_lock(&_event_lock);
1144         if (t->event_fn)
1145                 t->event_fn(t->event_context);
1146         mutex_unlock(&_event_lock);
1147 }
1148 EXPORT_SYMBOL(dm_table_event);
1149
1150 sector_t dm_table_get_size(struct dm_table *t)
1151 {
1152         return t->num_targets ? (t->highs[t->num_targets - 1] + 1) : 0;
1153 }
1154 EXPORT_SYMBOL(dm_table_get_size);
1155
1156 struct dm_target *dm_table_get_target(struct dm_table *t, unsigned int index)
1157 {
1158         if (index >= t->num_targets)
1159                 return NULL;
1160
1161         return t->targets + index;
1162 }
1163
1164 /*
1165  * Search the btree for the correct target.
1166  *
1167  * Caller should check returned pointer with dm_target_is_valid()
1168  * to trap I/O beyond end of device.
1169  */
1170 struct dm_target *dm_table_find_target(struct dm_table *t, sector_t sector)
1171 {
1172         unsigned int l, n = 0, k = 0;
1173         sector_t *node;
1174
1175         for (l = 0; l < t->depth; l++) {
1176                 n = get_child(n, k);
1177                 node = get_node(t, l, n);
1178
1179                 for (k = 0; k < KEYS_PER_NODE; k++)
1180                         if (node[k] >= sector)
1181                                 break;
1182         }
1183
1184         return &t->targets[(KEYS_PER_NODE * n) + k];
1185 }
1186
1187 /*
1188  * Establish the new table's queue_limits and validate them.
1189  */
1190 int dm_calculate_queue_limits(struct dm_table *table,
1191                               struct queue_limits *limits)
1192 {
1193         struct dm_target *uninitialized_var(ti);
1194         struct queue_limits ti_limits;
1195         unsigned i = 0;
1196
1197         blk_set_default_limits(limits);
1198
1199         while (i < dm_table_get_num_targets(table)) {
1200                 blk_set_default_limits(&ti_limits);
1201
1202                 ti = dm_table_get_target(table, i++);
1203
1204                 if (!ti->type->iterate_devices)
1205                         goto combine_limits;
1206
1207                 /*
1208                  * Combine queue limits of all the devices this target uses.
1209                  */
1210                 ti->type->iterate_devices(ti, dm_set_device_limits,
1211                                           &ti_limits);
1212
1213                 /* Set I/O hints portion of queue limits */
1214                 if (ti->type->io_hints)
1215                         ti->type->io_hints(ti, &ti_limits);
1216
1217                 /*
1218                  * Check each device area is consistent with the target's
1219                  * overall queue limits.
1220                  */
1221                 if (ti->type->iterate_devices(ti, device_area_is_invalid,
1222                                               &ti_limits))
1223                         return -EINVAL;
1224
1225 combine_limits:
1226                 /*
1227                  * Merge this target's queue limits into the overall limits
1228                  * for the table.
1229                  */
1230                 if (blk_stack_limits(limits, &ti_limits, 0) < 0)
1231                         DMWARN("%s: adding target device "
1232                                "(start sect %llu len %llu) "
1233                                "caused an alignment inconsistency",
1234                                dm_device_name(table->md),
1235                                (unsigned long long) ti->begin,
1236                                (unsigned long long) ti->len);
1237         }
1238
1239         return validate_hardware_logical_block_alignment(table, limits);
1240 }
1241
1242 /*
1243  * Set the integrity profile for this device if all devices used have
1244  * matching profiles.  We're quite deep in the resume path but still
1245  * don't know if all devices (particularly DM devices this device
1246  * may be stacked on) have matching profiles.  Even if the profiles
1247  * don't match we have no way to fail (to resume) at this point.
1248  */
1249 static void dm_table_set_integrity(struct dm_table *t)
1250 {
1251         struct gendisk *template_disk = NULL;
1252
1253         if (!blk_get_integrity(dm_disk(t->md)))
1254                 return;
1255
1256         template_disk = dm_table_get_integrity_disk(t, true);
1257         if (template_disk)
1258                 blk_integrity_register(dm_disk(t->md),
1259                                        blk_get_integrity(template_disk));
1260         else if (blk_integrity_is_initialized(dm_disk(t->md)))
1261                 DMWARN("%s: device no longer has a valid integrity profile",
1262                        dm_device_name(t->md));
1263         else
1264                 DMWARN("%s: unable to establish an integrity profile",
1265                        dm_device_name(t->md));
1266 }
1267
1268 static int device_flush_capable(struct dm_target *ti, struct dm_dev *dev,
1269                                 sector_t start, sector_t len, void *data)
1270 {
1271         unsigned flush = (*(unsigned *)data);
1272         struct request_queue *q = bdev_get_queue(dev->bdev);
1273
1274         return q && (q->flush_flags & flush);
1275 }
1276
1277 static bool dm_table_supports_flush(struct dm_table *t, unsigned flush)
1278 {
1279         struct dm_target *ti;
1280         unsigned i = 0;
1281
1282         /*
1283          * Require at least one underlying device to support flushes.
1284          * t->devices includes internal dm devices such as mirror logs
1285          * so we need to use iterate_devices here, which targets
1286          * supporting flushes must provide.
1287          */
1288         while (i < dm_table_get_num_targets(t)) {
1289                 ti = dm_table_get_target(t, i++);
1290
1291                 if (!ti->num_flush_requests)
1292                         continue;
1293
1294                 if (ti->type->iterate_devices &&
1295                     ti->type->iterate_devices(ti, device_flush_capable, &flush))
1296                         return 1;
1297         }
1298
1299         return 0;
1300 }
1301
1302 static bool dm_table_discard_zeroes_data(struct dm_table *t)
1303 {
1304         struct dm_target *ti;
1305         unsigned i = 0;
1306
1307         /* Ensure that all targets supports discard_zeroes_data. */
1308         while (i < dm_table_get_num_targets(t)) {
1309                 ti = dm_table_get_target(t, i++);
1310
1311                 if (ti->discard_zeroes_data_unsupported)
1312                         return 0;
1313         }
1314
1315         return 1;
1316 }
1317
1318 static int device_is_nonrot(struct dm_target *ti, struct dm_dev *dev,
1319                             sector_t start, sector_t len, void *data)
1320 {
1321         struct request_queue *q = bdev_get_queue(dev->bdev);
1322
1323         return q && blk_queue_nonrot(q);
1324 }
1325
1326 static bool dm_table_is_nonrot(struct dm_table *t)
1327 {
1328         struct dm_target *ti;
1329         unsigned i = 0;
1330
1331         /* Ensure that all underlying device are non-rotational. */
1332         while (i < dm_table_get_num_targets(t)) {
1333                 ti = dm_table_get_target(t, i++);
1334
1335                 if (!ti->type->iterate_devices ||
1336                     !ti->type->iterate_devices(ti, device_is_nonrot, NULL))
1337                         return 0;
1338         }
1339
1340         return 1;
1341 }
1342
1343 void dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
1344                                struct queue_limits *limits)
1345 {
1346         unsigned flush = 0;
1347
1348         /*
1349          * Copy table's limits to the DM device's request_queue
1350          */
1351         q->limits = *limits;
1352
1353         if (!dm_table_supports_discards(t))
1354                 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q);
1355         else
1356                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
1357
1358         if (dm_table_supports_flush(t, REQ_FLUSH)) {
1359                 flush |= REQ_FLUSH;
1360                 if (dm_table_supports_flush(t, REQ_FUA))
1361                         flush |= REQ_FUA;
1362         }
1363         blk_queue_flush(q, flush);
1364
1365         if (!dm_table_discard_zeroes_data(t))
1366                 q->limits.discard_zeroes_data = 0;
1367
1368         if (dm_table_is_nonrot(t))
1369                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, q);
1370         else
1371                 queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, q);
1372
1373         dm_table_set_integrity(t);
1374
1375         /*
1376          * QUEUE_FLAG_STACKABLE must be set after all queue settings are
1377          * visible to other CPUs because, once the flag is set, incoming bios
1378          * are processed by request-based dm, which refers to the queue
1379          * settings.
1380          * Until the flag set, bios are passed to bio-based dm and queued to
1381          * md->deferred where queue settings are not needed yet.
1382          * Those bios are passed to request-based dm at the resume time.
1383          */
1384         smp_mb();
1385         if (dm_table_request_based(t))
1386                 queue_flag_set_unlocked(QUEUE_FLAG_STACKABLE, q);
1387 }
1388
1389 unsigned int dm_table_get_num_targets(struct dm_table *t)
1390 {
1391         return t->num_targets;
1392 }
1393
1394 struct list_head *dm_table_get_devices(struct dm_table *t)
1395 {
1396         return &t->devices;
1397 }
1398
1399 fmode_t dm_table_get_mode(struct dm_table *t)
1400 {
1401         return t->mode;
1402 }
1403 EXPORT_SYMBOL(dm_table_get_mode);
1404
1405 static void suspend_targets(struct dm_table *t, unsigned postsuspend)
1406 {
1407         int i = t->num_targets;
1408         struct dm_target *ti = t->targets;
1409
1410         while (i--) {
1411                 if (postsuspend) {
1412                         if (ti->type->postsuspend)
1413                                 ti->type->postsuspend(ti);
1414                 } else if (ti->type->presuspend)
1415                         ti->type->presuspend(ti);
1416
1417                 ti++;
1418         }
1419 }
1420
1421 void dm_table_presuspend_targets(struct dm_table *t)
1422 {
1423         if (!t)
1424                 return;
1425
1426         suspend_targets(t, 0);
1427 }
1428
1429 void dm_table_postsuspend_targets(struct dm_table *t)
1430 {
1431         if (!t)
1432                 return;
1433
1434         suspend_targets(t, 1);
1435 }
1436
1437 int dm_table_resume_targets(struct dm_table *t)
1438 {
1439         int i, r = 0;
1440
1441         for (i = 0; i < t->num_targets; i++) {
1442                 struct dm_target *ti = t->targets + i;
1443
1444                 if (!ti->type->preresume)
1445                         continue;
1446
1447                 r = ti->type->preresume(ti);
1448                 if (r)
1449                         return r;
1450         }
1451
1452         for (i = 0; i < t->num_targets; i++) {
1453                 struct dm_target *ti = t->targets + i;
1454
1455                 if (ti->type->resume)
1456                         ti->type->resume(ti);
1457         }
1458
1459         return 0;
1460 }
1461
1462 void dm_table_add_target_callbacks(struct dm_table *t, struct dm_target_callbacks *cb)
1463 {
1464         list_add(&cb->list, &t->target_callbacks);
1465 }
1466 EXPORT_SYMBOL_GPL(dm_table_add_target_callbacks);
1467
1468 int dm_table_any_congested(struct dm_table *t, int bdi_bits)
1469 {
1470         struct dm_dev_internal *dd;
1471         struct list_head *devices = dm_table_get_devices(t);
1472         struct dm_target_callbacks *cb;
1473         int r = 0;
1474
1475         list_for_each_entry(dd, devices, list) {
1476                 struct request_queue *q = bdev_get_queue(dd->dm_dev.bdev);
1477                 char b[BDEVNAME_SIZE];
1478
1479                 if (likely(q))
1480                         r |= bdi_congested(&q->backing_dev_info, bdi_bits);
1481                 else
1482                         DMWARN_LIMIT("%s: any_congested: nonexistent device %s",
1483                                      dm_device_name(t->md),
1484                                      bdevname(dd->dm_dev.bdev, b));
1485         }
1486
1487         list_for_each_entry(cb, &t->target_callbacks, list)
1488                 if (cb->congested_fn)
1489                         r |= cb->congested_fn(cb, bdi_bits);
1490
1491         return r;
1492 }
1493
1494 int dm_table_any_busy_target(struct dm_table *t)
1495 {
1496         unsigned i;
1497         struct dm_target *ti;
1498
1499         for (i = 0; i < t->num_targets; i++) {
1500                 ti = t->targets + i;
1501                 if (ti->type->busy && ti->type->busy(ti))
1502                         return 1;
1503         }
1504
1505         return 0;
1506 }
1507
1508 struct mapped_device *dm_table_get_md(struct dm_table *t)
1509 {
1510         return t->md;
1511 }
1512 EXPORT_SYMBOL(dm_table_get_md);
1513
1514 static int device_discard_capable(struct dm_target *ti, struct dm_dev *dev,
1515                                   sector_t start, sector_t len, void *data)
1516 {
1517         struct request_queue *q = bdev_get_queue(dev->bdev);
1518
1519         return q && blk_queue_discard(q);
1520 }
1521
1522 bool dm_table_supports_discards(struct dm_table *t)
1523 {
1524         struct dm_target *ti;
1525         unsigned i = 0;
1526
1527         /*
1528          * Unless any target used by the table set discards_supported,
1529          * require at least one underlying device to support discards.
1530          * t->devices includes internal dm devices such as mirror logs
1531          * so we need to use iterate_devices here, which targets
1532          * supporting discard selectively must provide.
1533          */
1534         while (i < dm_table_get_num_targets(t)) {
1535                 ti = dm_table_get_target(t, i++);
1536
1537                 if (!ti->num_discard_requests)
1538                         continue;
1539
1540                 if (ti->discards_supported)
1541                         return 1;
1542
1543                 if (ti->type->iterate_devices &&
1544                     ti->type->iterate_devices(ti, device_discard_capable, NULL))
1545                         return 1;
1546         }
1547
1548         return 0;
1549 }