Merge branch 'develop' of 10.10.10.29:/home/rockchip/kernel into develop
[firefly-linux-kernel-4.4.55.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/slab.h>
16 #include <linux/interrupt.h>
17 #include <linux/mutex.h>
18 #include <linux/delay.h>
19 #include <asm/atomic.h>
20
21 #define DM_MSG_PREFIX "table"
22
23 #define MAX_DEPTH 16
24 #define NODE_SIZE L1_CACHE_BYTES
25 #define KEYS_PER_NODE (NODE_SIZE / sizeof(sector_t))
26 #define CHILDREN_PER_NODE (KEYS_PER_NODE + 1)
27
28 /*
29  * The table has always exactly one reference from either mapped_device->map
30  * or hash_cell->new_map. This reference is not counted in table->holders.
31  * A pair of dm_create_table/dm_destroy_table functions is used for table
32  * creation/destruction.
33  *
34  * Temporary references from the other code increase table->holders. A pair
35  * of dm_table_get/dm_table_put functions is used to manipulate it.
36  *
37  * When the table is about to be destroyed, we wait for table->holders to
38  * drop to zero.
39  */
40
41 struct dm_table {
42         struct mapped_device *md;
43         atomic_t holders;
44         unsigned type;
45
46         /* btree table */
47         unsigned int depth;
48         unsigned int counts[MAX_DEPTH]; /* in nodes */
49         sector_t *index[MAX_DEPTH];
50
51         unsigned int num_targets;
52         unsigned int num_allocated;
53         sector_t *highs;
54         struct dm_target *targets;
55
56         /*
57          * Indicates the rw permissions for the new logical
58          * device.  This should be a combination of FMODE_READ
59          * and FMODE_WRITE.
60          */
61         fmode_t mode;
62
63         /* a list of devices used by this table */
64         struct list_head devices;
65
66         /* events get handed up using this callback */
67         void (*event_fn)(void *);
68         void *event_context;
69
70         struct dm_md_mempools *mempools;
71 };
72
73 /*
74  * Similar to ceiling(log_size(n))
75  */
76 static unsigned int int_log(unsigned int n, unsigned int base)
77 {
78         int result = 0;
79
80         while (n > 1) {
81                 n = dm_div_up(n, base);
82                 result++;
83         }
84
85         return result;
86 }
87
88 /*
89  * Calculate the index of the child node of the n'th node k'th key.
90  */
91 static inline unsigned int get_child(unsigned int n, unsigned int k)
92 {
93         return (n * CHILDREN_PER_NODE) + k;
94 }
95
96 /*
97  * Return the n'th node of level l from table t.
98  */
99 static inline sector_t *get_node(struct dm_table *t,
100                                  unsigned int l, unsigned int n)
101 {
102         return t->index[l] + (n * KEYS_PER_NODE);
103 }
104
105 /*
106  * Return the highest key that you could lookup from the n'th
107  * node on level l of the btree.
108  */
109 static sector_t high(struct dm_table *t, unsigned int l, unsigned int n)
110 {
111         for (; l < t->depth - 1; l++)
112                 n = get_child(n, CHILDREN_PER_NODE - 1);
113
114         if (n >= t->counts[l])
115                 return (sector_t) - 1;
116
117         return get_node(t, l, n)[KEYS_PER_NODE - 1];
118 }
119
120 /*
121  * Fills in a level of the btree based on the highs of the level
122  * below it.
123  */
124 static int setup_btree_index(unsigned int l, struct dm_table *t)
125 {
126         unsigned int n, k;
127         sector_t *node;
128
129         for (n = 0U; n < t->counts[l]; n++) {
130                 node = get_node(t, l, n);
131
132                 for (k = 0U; k < KEYS_PER_NODE; k++)
133                         node[k] = high(t, l + 1, get_child(n, k));
134         }
135
136         return 0;
137 }
138
139 void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size)
140 {
141         unsigned long size;
142         void *addr;
143
144         /*
145          * Check that we're not going to overflow.
146          */
147         if (nmemb > (ULONG_MAX / elem_size))
148                 return NULL;
149
150         size = nmemb * elem_size;
151         addr = vmalloc(size);
152         if (addr)
153                 memset(addr, 0, size);
154
155         return addr;
156 }
157
158 /*
159  * highs, and targets are managed as dynamic arrays during a
160  * table load.
161  */
162 static int alloc_targets(struct dm_table *t, unsigned int num)
163 {
164         sector_t *n_highs;
165         struct dm_target *n_targets;
166         int n = t->num_targets;
167
168         /*
169          * Allocate both the target array and offset array at once.
170          * Append an empty entry to catch sectors beyond the end of
171          * the device.
172          */
173         n_highs = (sector_t *) dm_vcalloc(num + 1, sizeof(struct dm_target) +
174                                           sizeof(sector_t));
175         if (!n_highs)
176                 return -ENOMEM;
177
178         n_targets = (struct dm_target *) (n_highs + num);
179
180         if (n) {
181                 memcpy(n_highs, t->highs, sizeof(*n_highs) * n);
182                 memcpy(n_targets, t->targets, sizeof(*n_targets) * n);
183         }
184
185         memset(n_highs + n, -1, sizeof(*n_highs) * (num - n));
186         vfree(t->highs);
187
188         t->num_allocated = num;
189         t->highs = n_highs;
190         t->targets = n_targets;
191
192         return 0;
193 }
194
195 int dm_table_create(struct dm_table **result, fmode_t mode,
196                     unsigned num_targets, struct mapped_device *md)
197 {
198         struct dm_table *t = kzalloc(sizeof(*t), GFP_KERNEL);
199
200         if (!t)
201                 return -ENOMEM;
202
203         INIT_LIST_HEAD(&t->devices);
204         atomic_set(&t->holders, 0);
205
206         if (!num_targets)
207                 num_targets = KEYS_PER_NODE;
208
209         num_targets = dm_round_up(num_targets, KEYS_PER_NODE);
210
211         if (alloc_targets(t, num_targets)) {
212                 kfree(t);
213                 t = NULL;
214                 return -ENOMEM;
215         }
216
217         t->mode = mode;
218         t->md = md;
219         *result = t;
220         return 0;
221 }
222
223 static void free_devices(struct list_head *devices)
224 {
225         struct list_head *tmp, *next;
226
227         list_for_each_safe(tmp, next, devices) {
228                 struct dm_dev_internal *dd =
229                     list_entry(tmp, struct dm_dev_internal, list);
230                 DMWARN("dm_table_destroy: dm_put_device call missing for %s",
231                        dd->dm_dev.name);
232                 kfree(dd);
233         }
234 }
235
236 void dm_table_destroy(struct dm_table *t)
237 {
238         unsigned int i;
239
240         while (atomic_read(&t->holders))
241                 msleep(1);
242         smp_mb();
243
244         /* free the indexes (see dm_table_complete) */
245         if (t->depth >= 2)
246                 vfree(t->index[t->depth - 2]);
247
248         /* free the targets */
249         for (i = 0; i < t->num_targets; i++) {
250                 struct dm_target *tgt = t->targets + i;
251
252                 if (tgt->type->dtr)
253                         tgt->type->dtr(tgt);
254
255                 dm_put_target_type(tgt->type);
256         }
257
258         vfree(t->highs);
259
260         /* free the device list */
261         if (t->devices.next != &t->devices)
262                 free_devices(&t->devices);
263
264         dm_free_md_mempools(t->mempools);
265
266         kfree(t);
267 }
268
269 void dm_table_get(struct dm_table *t)
270 {
271         atomic_inc(&t->holders);
272 }
273
274 void dm_table_put(struct dm_table *t)
275 {
276         if (!t)
277                 return;
278
279         smp_mb__before_atomic_dec();
280         atomic_dec(&t->holders);
281 }
282
283 /*
284  * Checks to see if we need to extend highs or targets.
285  */
286 static inline int check_space(struct dm_table *t)
287 {
288         if (t->num_targets >= t->num_allocated)
289                 return alloc_targets(t, t->num_allocated * 2);
290
291         return 0;
292 }
293
294 /*
295  * See if we've already got a device in the list.
296  */
297 static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev)
298 {
299         struct dm_dev_internal *dd;
300
301         list_for_each_entry (dd, l, list)
302                 if (dd->dm_dev.bdev->bd_dev == dev)
303                         return dd;
304
305         return NULL;
306 }
307
308 /*
309  * Open a device so we can use it as a map destination.
310  */
311 static int open_dev(struct dm_dev_internal *d, dev_t dev,
312                     struct mapped_device *md)
313 {
314         static char *_claim_ptr = "I belong to device-mapper";
315         struct block_device *bdev;
316
317         int r;
318
319         BUG_ON(d->dm_dev.bdev);
320
321         bdev = open_by_devnum(dev, d->dm_dev.mode);
322         if (IS_ERR(bdev))
323                 return PTR_ERR(bdev);
324         r = bd_claim_by_disk(bdev, _claim_ptr, dm_disk(md));
325         if (r)
326                 blkdev_put(bdev, d->dm_dev.mode);
327         else
328                 d->dm_dev.bdev = bdev;
329         return r;
330 }
331
332 /*
333  * Close a device that we've been using.
334  */
335 static void close_dev(struct dm_dev_internal *d, struct mapped_device *md)
336 {
337         if (!d->dm_dev.bdev)
338                 return;
339
340         bd_release_from_disk(d->dm_dev.bdev, dm_disk(md));
341         blkdev_put(d->dm_dev.bdev, d->dm_dev.mode);
342         d->dm_dev.bdev = NULL;
343 }
344
345 /*
346  * If possible, this checks an area of a destination device is invalid.
347  */
348 static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev,
349                                   sector_t start, sector_t len, void *data)
350 {
351         struct request_queue *q;
352         struct queue_limits *limits = data;
353         struct block_device *bdev = dev->bdev;
354         sector_t dev_size =
355                 i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
356         unsigned short logical_block_size_sectors =
357                 limits->logical_block_size >> SECTOR_SHIFT;
358         char b[BDEVNAME_SIZE];
359
360         /*
361          * Some devices exist without request functions,
362          * such as loop devices not yet bound to backing files.
363          * Forbid the use of such devices.
364          */
365         q = bdev_get_queue(bdev);
366         if (!q || !q->make_request_fn) {
367                 DMWARN("%s: %s is not yet initialised: "
368                        "start=%llu, len=%llu, dev_size=%llu",
369                        dm_device_name(ti->table->md), bdevname(bdev, b),
370                        (unsigned long long)start,
371                        (unsigned long long)len,
372                        (unsigned long long)dev_size);
373                 return 1;
374         }
375
376         if (!dev_size)
377                 return 0;
378
379         if ((start >= dev_size) || (start + len > dev_size)) {
380                 DMWARN("%s: %s too small for target: "
381                        "start=%llu, len=%llu, dev_size=%llu",
382                        dm_device_name(ti->table->md), bdevname(bdev, b),
383                        (unsigned long long)start,
384                        (unsigned long long)len,
385                        (unsigned long long)dev_size);
386                 return 1;
387         }
388
389         if (logical_block_size_sectors <= 1)
390                 return 0;
391
392         if (start & (logical_block_size_sectors - 1)) {
393                 DMWARN("%s: start=%llu not aligned to h/w "
394                        "logical block size %u of %s",
395                        dm_device_name(ti->table->md),
396                        (unsigned long long)start,
397                        limits->logical_block_size, bdevname(bdev, b));
398                 return 1;
399         }
400
401         if (len & (logical_block_size_sectors - 1)) {
402                 DMWARN("%s: len=%llu not aligned to h/w "
403                        "logical block size %u of %s",
404                        dm_device_name(ti->table->md),
405                        (unsigned long long)len,
406                        limits->logical_block_size, bdevname(bdev, b));
407                 return 1;
408         }
409
410         return 0;
411 }
412
413 /*
414  * This upgrades the mode on an already open dm_dev, being
415  * careful to leave things as they were if we fail to reopen the
416  * device and not to touch the existing bdev field in case
417  * it is accessed concurrently inside dm_table_any_congested().
418  */
419 static int upgrade_mode(struct dm_dev_internal *dd, fmode_t new_mode,
420                         struct mapped_device *md)
421 {
422         int r;
423         struct dm_dev_internal dd_new, dd_old;
424
425         dd_new = dd_old = *dd;
426
427         dd_new.dm_dev.mode |= new_mode;
428         dd_new.dm_dev.bdev = NULL;
429
430         r = open_dev(&dd_new, dd->dm_dev.bdev->bd_dev, md);
431         if (r)
432                 return r;
433
434         dd->dm_dev.mode |= new_mode;
435         close_dev(&dd_old, md);
436
437         return 0;
438 }
439
440 /*
441  * Add a device to the list, or just increment the usage count if
442  * it's already present.
443  */
444 static int __table_get_device(struct dm_table *t, struct dm_target *ti,
445                               const char *path, sector_t start, sector_t len,
446                               fmode_t mode, struct dm_dev **result)
447 {
448         int r;
449         dev_t uninitialized_var(dev);
450         struct dm_dev_internal *dd;
451         unsigned int major, minor;
452
453         BUG_ON(!t);
454
455         if (sscanf(path, "%u:%u", &major, &minor) == 2) {
456                 /* Extract the major/minor numbers */
457                 dev = MKDEV(major, minor);
458                 if (MAJOR(dev) != major || MINOR(dev) != minor)
459                         return -EOVERFLOW;
460         } else {
461                 /* convert the path to a device */
462                 struct block_device *bdev = lookup_bdev(path);
463
464                 if (IS_ERR(bdev))
465                         return PTR_ERR(bdev);
466                 dev = bdev->bd_dev;
467                 bdput(bdev);
468         }
469
470         dd = find_device(&t->devices, dev);
471         if (!dd) {
472                 dd = kmalloc(sizeof(*dd), GFP_KERNEL);
473                 if (!dd)
474                         return -ENOMEM;
475
476                 dd->dm_dev.mode = mode;
477                 dd->dm_dev.bdev = NULL;
478
479                 if ((r = open_dev(dd, dev, t->md))) {
480                         kfree(dd);
481                         return r;
482                 }
483
484                 format_dev_t(dd->dm_dev.name, dev);
485
486                 atomic_set(&dd->count, 0);
487                 list_add(&dd->list, &t->devices);
488
489         } else if (dd->dm_dev.mode != (mode | dd->dm_dev.mode)) {
490                 r = upgrade_mode(dd, mode, t->md);
491                 if (r)
492                         return r;
493         }
494         atomic_inc(&dd->count);
495
496         *result = &dd->dm_dev;
497         return 0;
498 }
499
500 /*
501  * Returns the minimum that is _not_ zero, unless both are zero.
502  */
503 #define min_not_zero(l, r) (l == 0) ? r : ((r == 0) ? l : min(l, r))
504
505 int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
506                          sector_t start, sector_t len, void *data)
507 {
508         struct queue_limits *limits = data;
509         struct block_device *bdev = dev->bdev;
510         struct request_queue *q = bdev_get_queue(bdev);
511         char b[BDEVNAME_SIZE];
512
513         if (unlikely(!q)) {
514                 DMWARN("%s: Cannot set limits for nonexistent device %s",
515                        dm_device_name(ti->table->md), bdevname(bdev, b));
516                 return 0;
517         }
518
519         if (bdev_stack_limits(limits, bdev, start) < 0)
520                 DMWARN("%s: adding target device %s caused an alignment inconsistency: "
521                        "physical_block_size=%u, logical_block_size=%u, "
522                        "alignment_offset=%u, start=%llu",
523                        dm_device_name(ti->table->md), bdevname(bdev, b),
524                        q->limits.physical_block_size,
525                        q->limits.logical_block_size,
526                        q->limits.alignment_offset,
527                        (unsigned long long) start << SECTOR_SHIFT);
528
529         /*
530          * Check if merge fn is supported.
531          * If not we'll force DM to use PAGE_SIZE or
532          * smaller I/O, just to be safe.
533          */
534
535         if (q->merge_bvec_fn && !ti->type->merge)
536                 limits->max_sectors =
537                         min_not_zero(limits->max_sectors,
538                                      (unsigned int) (PAGE_SIZE >> 9));
539         return 0;
540 }
541 EXPORT_SYMBOL_GPL(dm_set_device_limits);
542
543 int dm_get_device(struct dm_target *ti, const char *path, sector_t start,
544                   sector_t len, fmode_t mode, struct dm_dev **result)
545 {
546         return __table_get_device(ti->table, ti, path,
547                                   start, len, mode, result);
548 }
549
550
551 /*
552  * Decrement a devices 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
566 /*
567  * Checks to see if the target joins onto the end of the table.
568  */
569 static int adjoin(struct dm_table *table, struct dm_target *ti)
570 {
571         struct dm_target *prev;
572
573         if (!table->num_targets)
574                 return !ti->begin;
575
576         prev = &table->targets[table->num_targets - 1];
577         return (ti->begin == (prev->begin + prev->len));
578 }
579
580 /*
581  * Used to dynamically allocate the arg array.
582  */
583 static char **realloc_argv(unsigned *array_size, char **old_argv)
584 {
585         char **argv;
586         unsigned new_size;
587
588         new_size = *array_size ? *array_size * 2 : 64;
589         argv = kmalloc(new_size * sizeof(*argv), GFP_KERNEL);
590         if (argv) {
591                 memcpy(argv, old_argv, *array_size * sizeof(*argv));
592                 *array_size = new_size;
593         }
594
595         kfree(old_argv);
596         return argv;
597 }
598
599 /*
600  * Destructively splits up the argument list to pass to ctr.
601  */
602 int dm_split_args(int *argc, char ***argvp, char *input)
603 {
604         char *start, *end = input, *out, **argv = NULL;
605         unsigned array_size = 0;
606
607         *argc = 0;
608
609         if (!input) {
610                 *argvp = NULL;
611                 return 0;
612         }
613
614         argv = realloc_argv(&array_size, argv);
615         if (!argv)
616                 return -ENOMEM;
617
618         while (1) {
619                 start = end;
620
621                 /* Skip whitespace */
622                 while (*start && isspace(*start))
623                         start++;
624
625                 if (!*start)
626                         break;  /* success, we hit the end */
627
628                 /* 'out' is used to remove any back-quotes */
629                 end = out = start;
630                 while (*end) {
631                         /* Everything apart from '\0' can be quoted */
632                         if (*end == '\\' && *(end + 1)) {
633                                 *out++ = *(end + 1);
634                                 end += 2;
635                                 continue;
636                         }
637
638                         if (isspace(*end))
639                                 break;  /* end of token */
640
641                         *out++ = *end++;
642                 }
643
644                 /* have we already filled the array ? */
645                 if ((*argc + 1) > array_size) {
646                         argv = realloc_argv(&array_size, argv);
647                         if (!argv)
648                                 return -ENOMEM;
649                 }
650
651                 /* we know this is whitespace */
652                 if (*end)
653                         end++;
654
655                 /* terminate the string and put it in the array */
656                 *out = '\0';
657                 argv[*argc] = start;
658                 (*argc)++;
659         }
660
661         *argvp = argv;
662         return 0;
663 }
664
665 /*
666  * Impose necessary and sufficient conditions on a devices's table such
667  * that any incoming bio which respects its logical_block_size can be
668  * processed successfully.  If it falls across the boundary between
669  * two or more targets, the size of each piece it gets split into must
670  * be compatible with the logical_block_size of the target processing it.
671  */
672 static int validate_hardware_logical_block_alignment(struct dm_table *table,
673                                                  struct queue_limits *limits)
674 {
675         /*
676          * This function uses arithmetic modulo the logical_block_size
677          * (in units of 512-byte sectors).
678          */
679         unsigned short device_logical_block_size_sects =
680                 limits->logical_block_size >> SECTOR_SHIFT;
681
682         /*
683          * Offset of the start of the next table entry, mod logical_block_size.
684          */
685         unsigned short next_target_start = 0;
686
687         /*
688          * Given an aligned bio that extends beyond the end of a
689          * target, how many sectors must the next target handle?
690          */
691         unsigned short remaining = 0;
692
693         struct dm_target *uninitialized_var(ti);
694         struct queue_limits ti_limits;
695         unsigned i = 0;
696
697         /*
698          * Check each entry in the table in turn.
699          */
700         while (i < dm_table_get_num_targets(table)) {
701                 ti = dm_table_get_target(table, i++);
702
703                 blk_set_default_limits(&ti_limits);
704
705                 /* combine all target devices' limits */
706                 if (ti->type->iterate_devices)
707                         ti->type->iterate_devices(ti, dm_set_device_limits,
708                                                   &ti_limits);
709
710                 /*
711                  * If the remaining sectors fall entirely within this
712                  * table entry are they compatible with its logical_block_size?
713                  */
714                 if (remaining < ti->len &&
715                     remaining & ((ti_limits.logical_block_size >>
716                                   SECTOR_SHIFT) - 1))
717                         break;  /* Error */
718
719                 next_target_start =
720                     (unsigned short) ((next_target_start + ti->len) &
721                                       (device_logical_block_size_sects - 1));
722                 remaining = next_target_start ?
723                     device_logical_block_size_sects - next_target_start : 0;
724         }
725
726         if (remaining) {
727                 DMWARN("%s: table line %u (start sect %llu len %llu) "
728                        "not aligned to h/w logical block size %u",
729                        dm_device_name(table->md), i,
730                        (unsigned long long) ti->begin,
731                        (unsigned long long) ti->len,
732                        limits->logical_block_size);
733                 return -EINVAL;
734         }
735
736         return 0;
737 }
738
739 int dm_table_add_target(struct dm_table *t, const char *type,
740                         sector_t start, sector_t len, char *params)
741 {
742         int r = -EINVAL, argc;
743         char **argv;
744         struct dm_target *tgt;
745
746         if ((r = check_space(t)))
747                 return r;
748
749         tgt = t->targets + t->num_targets;
750         memset(tgt, 0, sizeof(*tgt));
751
752         if (!len) {
753                 DMERR("%s: zero-length target", dm_device_name(t->md));
754                 return -EINVAL;
755         }
756
757         tgt->type = dm_get_target_type(type);
758         if (!tgt->type) {
759                 DMERR("%s: %s: unknown target type", dm_device_name(t->md),
760                       type);
761                 return -EINVAL;
762         }
763
764         tgt->table = t;
765         tgt->begin = start;
766         tgt->len = len;
767         tgt->error = "Unknown error";
768
769         /*
770          * Does this target adjoin the previous one ?
771          */
772         if (!adjoin(t, tgt)) {
773                 tgt->error = "Gap in table";
774                 r = -EINVAL;
775                 goto bad;
776         }
777
778         r = dm_split_args(&argc, &argv, params);
779         if (r) {
780                 tgt->error = "couldn't split parameters (insufficient memory)";
781                 goto bad;
782         }
783
784         r = tgt->type->ctr(tgt, argc, argv);
785         kfree(argv);
786         if (r)
787                 goto bad;
788
789         t->highs[t->num_targets++] = tgt->begin + tgt->len - 1;
790
791         return 0;
792
793  bad:
794         DMERR("%s: %s: %s", dm_device_name(t->md), type, tgt->error);
795         dm_put_target_type(tgt->type);
796         return r;
797 }
798
799 int dm_table_set_type(struct dm_table *t)
800 {
801         unsigned i;
802         unsigned bio_based = 0, request_based = 0;
803         struct dm_target *tgt;
804         struct dm_dev_internal *dd;
805         struct list_head *devices;
806
807         for (i = 0; i < t->num_targets; i++) {
808                 tgt = t->targets + i;
809                 if (dm_target_request_based(tgt))
810                         request_based = 1;
811                 else
812                         bio_based = 1;
813
814                 if (bio_based && request_based) {
815                         DMWARN("Inconsistent table: different target types"
816                                " can't be mixed up");
817                         return -EINVAL;
818                 }
819         }
820
821         if (bio_based) {
822                 /* We must use this table as bio-based */
823                 t->type = DM_TYPE_BIO_BASED;
824                 return 0;
825         }
826
827         BUG_ON(!request_based); /* No targets in this table */
828
829         /* Non-request-stackable devices can't be used for request-based dm */
830         devices = dm_table_get_devices(t);
831         list_for_each_entry(dd, devices, list) {
832                 if (!blk_queue_stackable(bdev_get_queue(dd->dm_dev.bdev))) {
833                         DMWARN("table load rejected: including"
834                                " non-request-stackable devices");
835                         return -EINVAL;
836                 }
837         }
838
839         /*
840          * Request-based dm supports only tables that have a single target now.
841          * To support multiple targets, request splitting support is needed,
842          * and that needs lots of changes in the block-layer.
843          * (e.g. request completion process for partial completion.)
844          */
845         if (t->num_targets > 1) {
846                 DMWARN("Request-based dm doesn't support multiple targets yet");
847                 return -EINVAL;
848         }
849
850         t->type = DM_TYPE_REQUEST_BASED;
851
852         return 0;
853 }
854
855 unsigned dm_table_get_type(struct dm_table *t)
856 {
857         return t->type;
858 }
859
860 bool dm_table_request_based(struct dm_table *t)
861 {
862         return dm_table_get_type(t) == DM_TYPE_REQUEST_BASED;
863 }
864
865 int dm_table_alloc_md_mempools(struct dm_table *t)
866 {
867         unsigned type = dm_table_get_type(t);
868
869         if (unlikely(type == DM_TYPE_NONE)) {
870                 DMWARN("no table type is set, can't allocate mempools");
871                 return -EINVAL;
872         }
873
874         t->mempools = dm_alloc_md_mempools(type);
875         if (!t->mempools)
876                 return -ENOMEM;
877
878         return 0;
879 }
880
881 void dm_table_free_md_mempools(struct dm_table *t)
882 {
883         dm_free_md_mempools(t->mempools);
884         t->mempools = NULL;
885 }
886
887 struct dm_md_mempools *dm_table_get_md_mempools(struct dm_table *t)
888 {
889         return t->mempools;
890 }
891
892 static int setup_indexes(struct dm_table *t)
893 {
894         int i;
895         unsigned int total = 0;
896         sector_t *indexes;
897
898         /* allocate the space for *all* the indexes */
899         for (i = t->depth - 2; i >= 0; i--) {
900                 t->counts[i] = dm_div_up(t->counts[i + 1], CHILDREN_PER_NODE);
901                 total += t->counts[i];
902         }
903
904         indexes = (sector_t *) dm_vcalloc(total, (unsigned long) NODE_SIZE);
905         if (!indexes)
906                 return -ENOMEM;
907
908         /* set up internal nodes, bottom-up */
909         for (i = t->depth - 2; i >= 0; i--) {
910                 t->index[i] = indexes;
911                 indexes += (KEYS_PER_NODE * t->counts[i]);
912                 setup_btree_index(i, t);
913         }
914
915         return 0;
916 }
917
918 /*
919  * Builds the btree to index the map.
920  */
921 int dm_table_complete(struct dm_table *t)
922 {
923         int r = 0;
924         unsigned int leaf_nodes;
925
926         /* how many indexes will the btree have ? */
927         leaf_nodes = dm_div_up(t->num_targets, KEYS_PER_NODE);
928         t->depth = 1 + int_log(leaf_nodes, CHILDREN_PER_NODE);
929
930         /* leaf layer has already been set up */
931         t->counts[t->depth - 1] = leaf_nodes;
932         t->index[t->depth - 1] = t->highs;
933
934         if (t->depth >= 2)
935                 r = setup_indexes(t);
936
937         return r;
938 }
939
940 static DEFINE_MUTEX(_event_lock);
941 void dm_table_event_callback(struct dm_table *t,
942                              void (*fn)(void *), void *context)
943 {
944         mutex_lock(&_event_lock);
945         t->event_fn = fn;
946         t->event_context = context;
947         mutex_unlock(&_event_lock);
948 }
949
950 void dm_table_event(struct dm_table *t)
951 {
952         /*
953          * You can no longer call dm_table_event() from interrupt
954          * context, use a bottom half instead.
955          */
956         BUG_ON(in_interrupt());
957
958         mutex_lock(&_event_lock);
959         if (t->event_fn)
960                 t->event_fn(t->event_context);
961         mutex_unlock(&_event_lock);
962 }
963
964 sector_t dm_table_get_size(struct dm_table *t)
965 {
966         return t->num_targets ? (t->highs[t->num_targets - 1] + 1) : 0;
967 }
968
969 struct dm_target *dm_table_get_target(struct dm_table *t, unsigned int index)
970 {
971         if (index >= t->num_targets)
972                 return NULL;
973
974         return t->targets + index;
975 }
976
977 /*
978  * Search the btree for the correct target.
979  *
980  * Caller should check returned pointer with dm_target_is_valid()
981  * to trap I/O beyond end of device.
982  */
983 struct dm_target *dm_table_find_target(struct dm_table *t, sector_t sector)
984 {
985         unsigned int l, n = 0, k = 0;
986         sector_t *node;
987
988         for (l = 0; l < t->depth; l++) {
989                 n = get_child(n, k);
990                 node = get_node(t, l, n);
991
992                 for (k = 0; k < KEYS_PER_NODE; k++)
993                         if (node[k] >= sector)
994                                 break;
995         }
996
997         return &t->targets[(KEYS_PER_NODE * n) + k];
998 }
999
1000 /*
1001  * Establish the new table's queue_limits and validate them.
1002  */
1003 int dm_calculate_queue_limits(struct dm_table *table,
1004                               struct queue_limits *limits)
1005 {
1006         struct dm_target *uninitialized_var(ti);
1007         struct queue_limits ti_limits;
1008         unsigned i = 0;
1009
1010         blk_set_default_limits(limits);
1011
1012         while (i < dm_table_get_num_targets(table)) {
1013                 blk_set_default_limits(&ti_limits);
1014
1015                 ti = dm_table_get_target(table, i++);
1016
1017                 if (!ti->type->iterate_devices)
1018                         goto combine_limits;
1019
1020                 /*
1021                  * Combine queue limits of all the devices this target uses.
1022                  */
1023                 ti->type->iterate_devices(ti, dm_set_device_limits,
1024                                           &ti_limits);
1025
1026                 /* Set I/O hints portion of queue limits */
1027                 if (ti->type->io_hints)
1028                         ti->type->io_hints(ti, &ti_limits);
1029
1030                 /*
1031                  * Check each device area is consistent with the target's
1032                  * overall queue limits.
1033                  */
1034                 if (ti->type->iterate_devices(ti, device_area_is_invalid,
1035                                               &ti_limits))
1036                         return -EINVAL;
1037
1038 combine_limits:
1039                 /*
1040                  * Merge this target's queue limits into the overall limits
1041                  * for the table.
1042                  */
1043                 if (blk_stack_limits(limits, &ti_limits, 0) < 0)
1044                         DMWARN("%s: adding target device "
1045                                "(start sect %llu len %llu) "
1046                                "caused an alignment inconsistency",
1047                                dm_device_name(table->md),
1048                                (unsigned long long) ti->begin,
1049                                (unsigned long long) ti->len);
1050         }
1051
1052         return validate_hardware_logical_block_alignment(table, limits);
1053 }
1054
1055 /*
1056  * Set the integrity profile for this device if all devices used have
1057  * matching profiles.
1058  */
1059 static void dm_table_set_integrity(struct dm_table *t)
1060 {
1061         struct list_head *devices = dm_table_get_devices(t);
1062         struct dm_dev_internal *prev = NULL, *dd = NULL;
1063
1064         if (!blk_get_integrity(dm_disk(t->md)))
1065                 return;
1066
1067         list_for_each_entry(dd, devices, list) {
1068                 if (prev &&
1069                     blk_integrity_compare(prev->dm_dev.bdev->bd_disk,
1070                                           dd->dm_dev.bdev->bd_disk) < 0) {
1071                         DMWARN("%s: integrity not set: %s and %s mismatch",
1072                                dm_device_name(t->md),
1073                                prev->dm_dev.bdev->bd_disk->disk_name,
1074                                dd->dm_dev.bdev->bd_disk->disk_name);
1075                         goto no_integrity;
1076                 }
1077                 prev = dd;
1078         }
1079
1080         if (!prev || !bdev_get_integrity(prev->dm_dev.bdev))
1081                 goto no_integrity;
1082
1083         blk_integrity_register(dm_disk(t->md),
1084                                bdev_get_integrity(prev->dm_dev.bdev));
1085
1086         return;
1087
1088 no_integrity:
1089         blk_integrity_register(dm_disk(t->md), NULL);
1090
1091         return;
1092 }
1093
1094 void dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
1095                                struct queue_limits *limits)
1096 {
1097         /*
1098          * Copy table's limits to the DM device's request_queue
1099          */
1100         q->limits = *limits;
1101
1102         dm_table_set_integrity(t);
1103
1104         /*
1105          * QUEUE_FLAG_STACKABLE must be set after all queue settings are
1106          * visible to other CPUs because, once the flag is set, incoming bios
1107          * are processed by request-based dm, which refers to the queue
1108          * settings.
1109          * Until the flag set, bios are passed to bio-based dm and queued to
1110          * md->deferred where queue settings are not needed yet.
1111          * Those bios are passed to request-based dm at the resume time.
1112          */
1113         smp_mb();
1114         if (dm_table_request_based(t))
1115                 queue_flag_set_unlocked(QUEUE_FLAG_STACKABLE, q);
1116 }
1117
1118 unsigned int dm_table_get_num_targets(struct dm_table *t)
1119 {
1120         return t->num_targets;
1121 }
1122
1123 struct list_head *dm_table_get_devices(struct dm_table *t)
1124 {
1125         return &t->devices;
1126 }
1127
1128 fmode_t dm_table_get_mode(struct dm_table *t)
1129 {
1130         return t->mode;
1131 }
1132
1133 static void suspend_targets(struct dm_table *t, unsigned postsuspend)
1134 {
1135         int i = t->num_targets;
1136         struct dm_target *ti = t->targets;
1137
1138         while (i--) {
1139                 if (postsuspend) {
1140                         if (ti->type->postsuspend)
1141                                 ti->type->postsuspend(ti);
1142                 } else if (ti->type->presuspend)
1143                         ti->type->presuspend(ti);
1144
1145                 ti++;
1146         }
1147 }
1148
1149 void dm_table_presuspend_targets(struct dm_table *t)
1150 {
1151         if (!t)
1152                 return;
1153
1154         suspend_targets(t, 0);
1155 }
1156
1157 void dm_table_postsuspend_targets(struct dm_table *t)
1158 {
1159         if (!t)
1160                 return;
1161
1162         suspend_targets(t, 1);
1163 }
1164
1165 int dm_table_resume_targets(struct dm_table *t)
1166 {
1167         int i, r = 0;
1168
1169         for (i = 0; i < t->num_targets; i++) {
1170                 struct dm_target *ti = t->targets + i;
1171
1172                 if (!ti->type->preresume)
1173                         continue;
1174
1175                 r = ti->type->preresume(ti);
1176                 if (r)
1177                         return r;
1178         }
1179
1180         for (i = 0; i < t->num_targets; i++) {
1181                 struct dm_target *ti = t->targets + i;
1182
1183                 if (ti->type->resume)
1184                         ti->type->resume(ti);
1185         }
1186
1187         return 0;
1188 }
1189
1190 int dm_table_any_congested(struct dm_table *t, int bdi_bits)
1191 {
1192         struct dm_dev_internal *dd;
1193         struct list_head *devices = dm_table_get_devices(t);
1194         int r = 0;
1195
1196         list_for_each_entry(dd, devices, list) {
1197                 struct request_queue *q = bdev_get_queue(dd->dm_dev.bdev);
1198                 char b[BDEVNAME_SIZE];
1199
1200                 if (likely(q))
1201                         r |= bdi_congested(&q->backing_dev_info, bdi_bits);
1202                 else
1203                         DMWARN_LIMIT("%s: any_congested: nonexistent device %s",
1204                                      dm_device_name(t->md),
1205                                      bdevname(dd->dm_dev.bdev, b));
1206         }
1207
1208         return r;
1209 }
1210
1211 int dm_table_any_busy_target(struct dm_table *t)
1212 {
1213         unsigned i;
1214         struct dm_target *ti;
1215
1216         for (i = 0; i < t->num_targets; i++) {
1217                 ti = t->targets + i;
1218                 if (ti->type->busy && ti->type->busy(ti))
1219                         return 1;
1220         }
1221
1222         return 0;
1223 }
1224
1225 void dm_table_unplug_all(struct dm_table *t)
1226 {
1227         struct dm_dev_internal *dd;
1228         struct list_head *devices = dm_table_get_devices(t);
1229
1230         list_for_each_entry(dd, devices, list) {
1231                 struct request_queue *q = bdev_get_queue(dd->dm_dev.bdev);
1232                 char b[BDEVNAME_SIZE];
1233
1234                 if (likely(q))
1235                         blk_unplug(q);
1236                 else
1237                         DMWARN_LIMIT("%s: Cannot unplug nonexistent device %s",
1238                                      dm_device_name(t->md),
1239                                      bdevname(dd->dm_dev.bdev, b));
1240         }
1241 }
1242
1243 struct mapped_device *dm_table_get_md(struct dm_table *t)
1244 {
1245         dm_get(t->md);
1246
1247         return t->md;
1248 }
1249
1250 EXPORT_SYMBOL(dm_vcalloc);
1251 EXPORT_SYMBOL(dm_get_device);
1252 EXPORT_SYMBOL(dm_put_device);
1253 EXPORT_SYMBOL(dm_table_event);
1254 EXPORT_SYMBOL(dm_table_get_size);
1255 EXPORT_SYMBOL(dm_table_get_mode);
1256 EXPORT_SYMBOL(dm_table_get_md);
1257 EXPORT_SYMBOL(dm_table_put);
1258 EXPORT_SYMBOL(dm_table_get);
1259 EXPORT_SYMBOL(dm_table_unplug_all);