Merge tag 'for-linus-5.11-rc1b-tag' of git://git.kernel.org/pub/scm/linux/kernel...
[linux-2.6-microblaze.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-core.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 #include <linux/blk-mq.h>
22 #include <linux/mount.h>
23 #include <linux/dax.h>
24
25 #define DM_MSG_PREFIX "table"
26
27 #define NODE_SIZE L1_CACHE_BYTES
28 #define KEYS_PER_NODE (NODE_SIZE / sizeof(sector_t))
29 #define CHILDREN_PER_NODE (KEYS_PER_NODE + 1)
30
31 /*
32  * Similar to ceiling(log_size(n))
33  */
34 static unsigned int int_log(unsigned int n, unsigned int base)
35 {
36         int result = 0;
37
38         while (n > 1) {
39                 n = dm_div_up(n, base);
40                 result++;
41         }
42
43         return result;
44 }
45
46 /*
47  * Calculate the index of the child node of the n'th node k'th key.
48  */
49 static inline unsigned int get_child(unsigned int n, unsigned int k)
50 {
51         return (n * CHILDREN_PER_NODE) + k;
52 }
53
54 /*
55  * Return the n'th node of level l from table t.
56  */
57 static inline sector_t *get_node(struct dm_table *t,
58                                  unsigned int l, unsigned int n)
59 {
60         return t->index[l] + (n * KEYS_PER_NODE);
61 }
62
63 /*
64  * Return the highest key that you could lookup from the n'th
65  * node on level l of the btree.
66  */
67 static sector_t high(struct dm_table *t, unsigned int l, unsigned int n)
68 {
69         for (; l < t->depth - 1; l++)
70                 n = get_child(n, CHILDREN_PER_NODE - 1);
71
72         if (n >= t->counts[l])
73                 return (sector_t) - 1;
74
75         return get_node(t, l, n)[KEYS_PER_NODE - 1];
76 }
77
78 /*
79  * Fills in a level of the btree based on the highs of the level
80  * below it.
81  */
82 static int setup_btree_index(unsigned int l, struct dm_table *t)
83 {
84         unsigned int n, k;
85         sector_t *node;
86
87         for (n = 0U; n < t->counts[l]; n++) {
88                 node = get_node(t, l, n);
89
90                 for (k = 0U; k < KEYS_PER_NODE; k++)
91                         node[k] = high(t, l + 1, get_child(n, k));
92         }
93
94         return 0;
95 }
96
97 void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size)
98 {
99         unsigned long size;
100         void *addr;
101
102         /*
103          * Check that we're not going to overflow.
104          */
105         if (nmemb > (ULONG_MAX / elem_size))
106                 return NULL;
107
108         size = nmemb * elem_size;
109         addr = vzalloc(size);
110
111         return addr;
112 }
113 EXPORT_SYMBOL(dm_vcalloc);
114
115 /*
116  * highs, and targets are managed as dynamic arrays during a
117  * table load.
118  */
119 static int alloc_targets(struct dm_table *t, unsigned int num)
120 {
121         sector_t *n_highs;
122         struct dm_target *n_targets;
123
124         /*
125          * Allocate both the target array and offset array at once.
126          */
127         n_highs = (sector_t *) dm_vcalloc(num, sizeof(struct dm_target) +
128                                           sizeof(sector_t));
129         if (!n_highs)
130                 return -ENOMEM;
131
132         n_targets = (struct dm_target *) (n_highs + num);
133
134         memset(n_highs, -1, sizeof(*n_highs) * num);
135         vfree(t->highs);
136
137         t->num_allocated = num;
138         t->highs = n_highs;
139         t->targets = n_targets;
140
141         return 0;
142 }
143
144 int dm_table_create(struct dm_table **result, fmode_t mode,
145                     unsigned num_targets, struct mapped_device *md)
146 {
147         struct dm_table *t = kzalloc(sizeof(*t), GFP_KERNEL);
148
149         if (!t)
150                 return -ENOMEM;
151
152         INIT_LIST_HEAD(&t->devices);
153
154         if (!num_targets)
155                 num_targets = KEYS_PER_NODE;
156
157         num_targets = dm_round_up(num_targets, KEYS_PER_NODE);
158
159         if (!num_targets) {
160                 kfree(t);
161                 return -ENOMEM;
162         }
163
164         if (alloc_targets(t, num_targets)) {
165                 kfree(t);
166                 return -ENOMEM;
167         }
168
169         t->type = DM_TYPE_NONE;
170         t->mode = mode;
171         t->md = md;
172         *result = t;
173         return 0;
174 }
175
176 static void free_devices(struct list_head *devices, struct mapped_device *md)
177 {
178         struct list_head *tmp, *next;
179
180         list_for_each_safe(tmp, next, devices) {
181                 struct dm_dev_internal *dd =
182                     list_entry(tmp, struct dm_dev_internal, list);
183                 DMWARN("%s: dm_table_destroy: dm_put_device call missing for %s",
184                        dm_device_name(md), dd->dm_dev->name);
185                 dm_put_table_device(md, dd->dm_dev);
186                 kfree(dd);
187         }
188 }
189
190 void dm_table_destroy(struct dm_table *t)
191 {
192         unsigned int i;
193
194         if (!t)
195                 return;
196
197         /* free the indexes */
198         if (t->depth >= 2)
199                 vfree(t->index[t->depth - 2]);
200
201         /* free the targets */
202         for (i = 0; i < t->num_targets; i++) {
203                 struct dm_target *tgt = t->targets + i;
204
205                 if (tgt->type->dtr)
206                         tgt->type->dtr(tgt);
207
208                 dm_put_target_type(tgt->type);
209         }
210
211         vfree(t->highs);
212
213         /* free the device list */
214         free_devices(&t->devices, t->md);
215
216         dm_free_md_mempools(t->mempools);
217
218         kfree(t);
219 }
220
221 /*
222  * See if we've already got a device in the list.
223  */
224 static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev)
225 {
226         struct dm_dev_internal *dd;
227
228         list_for_each_entry (dd, l, list)
229                 if (dd->dm_dev->bdev->bd_dev == dev)
230                         return dd;
231
232         return NULL;
233 }
234
235 /*
236  * If possible, this checks an area of a destination device is invalid.
237  */
238 static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev,
239                                   sector_t start, sector_t len, void *data)
240 {
241         struct queue_limits *limits = data;
242         struct block_device *bdev = dev->bdev;
243         sector_t dev_size =
244                 i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
245         unsigned short logical_block_size_sectors =
246                 limits->logical_block_size >> SECTOR_SHIFT;
247         char b[BDEVNAME_SIZE];
248
249         if (!dev_size)
250                 return 0;
251
252         if ((start >= dev_size) || (start + len > dev_size)) {
253                 DMWARN("%s: %s too small for target: "
254                        "start=%llu, len=%llu, dev_size=%llu",
255                        dm_device_name(ti->table->md), bdevname(bdev, b),
256                        (unsigned long long)start,
257                        (unsigned long long)len,
258                        (unsigned long long)dev_size);
259                 return 1;
260         }
261
262         /*
263          * If the target is mapped to zoned block device(s), check
264          * that the zones are not partially mapped.
265          */
266         if (bdev_zoned_model(bdev) != BLK_ZONED_NONE) {
267                 unsigned int zone_sectors = bdev_zone_sectors(bdev);
268
269                 if (start & (zone_sectors - 1)) {
270                         DMWARN("%s: start=%llu not aligned to h/w zone size %u of %s",
271                                dm_device_name(ti->table->md),
272                                (unsigned long long)start,
273                                zone_sectors, bdevname(bdev, b));
274                         return 1;
275                 }
276
277                 /*
278                  * Note: The last zone of a zoned block device may be smaller
279                  * than other zones. So for a target mapping the end of a
280                  * zoned block device with such a zone, len would not be zone
281                  * aligned. We do not allow such last smaller zone to be part
282                  * of the mapping here to ensure that mappings with multiple
283                  * devices do not end up with a smaller zone in the middle of
284                  * the sector range.
285                  */
286                 if (len & (zone_sectors - 1)) {
287                         DMWARN("%s: len=%llu not aligned to h/w zone size %u of %s",
288                                dm_device_name(ti->table->md),
289                                (unsigned long long)len,
290                                zone_sectors, bdevname(bdev, b));
291                         return 1;
292                 }
293         }
294
295         if (logical_block_size_sectors <= 1)
296                 return 0;
297
298         if (start & (logical_block_size_sectors - 1)) {
299                 DMWARN("%s: start=%llu not aligned to h/w "
300                        "logical block size %u of %s",
301                        dm_device_name(ti->table->md),
302                        (unsigned long long)start,
303                        limits->logical_block_size, bdevname(bdev, b));
304                 return 1;
305         }
306
307         if (len & (logical_block_size_sectors - 1)) {
308                 DMWARN("%s: len=%llu not aligned to h/w "
309                        "logical block size %u of %s",
310                        dm_device_name(ti->table->md),
311                        (unsigned long long)len,
312                        limits->logical_block_size, bdevname(bdev, b));
313                 return 1;
314         }
315
316         return 0;
317 }
318
319 /*
320  * This upgrades the mode on an already open dm_dev, being
321  * careful to leave things as they were if we fail to reopen the
322  * device and not to touch the existing bdev field in case
323  * it is accessed concurrently.
324  */
325 static int upgrade_mode(struct dm_dev_internal *dd, fmode_t new_mode,
326                         struct mapped_device *md)
327 {
328         int r;
329         struct dm_dev *old_dev, *new_dev;
330
331         old_dev = dd->dm_dev;
332
333         r = dm_get_table_device(md, dd->dm_dev->bdev->bd_dev,
334                                 dd->dm_dev->mode | new_mode, &new_dev);
335         if (r)
336                 return r;
337
338         dd->dm_dev = new_dev;
339         dm_put_table_device(md, old_dev);
340
341         return 0;
342 }
343
344 /*
345  * Convert the path to a device
346  */
347 dev_t dm_get_dev_t(const char *path)
348 {
349         dev_t dev;
350
351         if (lookup_bdev(path, &dev))
352                 dev = name_to_dev_t(path);
353         return dev;
354 }
355 EXPORT_SYMBOL_GPL(dm_get_dev_t);
356
357 /*
358  * Add a device to the list, or just increment the usage count if
359  * it's already present.
360  */
361 int dm_get_device(struct dm_target *ti, const char *path, fmode_t mode,
362                   struct dm_dev **result)
363 {
364         int r;
365         dev_t dev;
366         struct dm_dev_internal *dd;
367         struct dm_table *t = ti->table;
368
369         BUG_ON(!t);
370
371         dev = dm_get_dev_t(path);
372         if (!dev)
373                 return -ENODEV;
374
375         dd = find_device(&t->devices, dev);
376         if (!dd) {
377                 dd = kmalloc(sizeof(*dd), GFP_KERNEL);
378                 if (!dd)
379                         return -ENOMEM;
380
381                 if ((r = dm_get_table_device(t->md, dev, mode, &dd->dm_dev))) {
382                         kfree(dd);
383                         return r;
384                 }
385
386                 refcount_set(&dd->count, 1);
387                 list_add(&dd->list, &t->devices);
388                 goto out;
389
390         } else if (dd->dm_dev->mode != (mode | dd->dm_dev->mode)) {
391                 r = upgrade_mode(dd, mode, t->md);
392                 if (r)
393                         return r;
394         }
395         refcount_inc(&dd->count);
396 out:
397         *result = dd->dm_dev;
398         return 0;
399 }
400 EXPORT_SYMBOL(dm_get_device);
401
402 static int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
403                                 sector_t start, sector_t len, void *data)
404 {
405         struct queue_limits *limits = data;
406         struct block_device *bdev = dev->bdev;
407         struct request_queue *q = bdev_get_queue(bdev);
408         char b[BDEVNAME_SIZE];
409
410         if (unlikely(!q)) {
411                 DMWARN("%s: Cannot set limits for nonexistent device %s",
412                        dm_device_name(ti->table->md), bdevname(bdev, b));
413                 return 0;
414         }
415
416         if (blk_stack_limits(limits, &q->limits,
417                         get_start_sect(bdev) + start) < 0)
418                 DMWARN("%s: adding target device %s caused an alignment inconsistency: "
419                        "physical_block_size=%u, logical_block_size=%u, "
420                        "alignment_offset=%u, start=%llu",
421                        dm_device_name(ti->table->md), bdevname(bdev, b),
422                        q->limits.physical_block_size,
423                        q->limits.logical_block_size,
424                        q->limits.alignment_offset,
425                        (unsigned long long) start << SECTOR_SHIFT);
426         return 0;
427 }
428
429 /*
430  * Decrement a device's use count and remove it if necessary.
431  */
432 void dm_put_device(struct dm_target *ti, struct dm_dev *d)
433 {
434         int found = 0;
435         struct list_head *devices = &ti->table->devices;
436         struct dm_dev_internal *dd;
437
438         list_for_each_entry(dd, devices, list) {
439                 if (dd->dm_dev == d) {
440                         found = 1;
441                         break;
442                 }
443         }
444         if (!found) {
445                 DMWARN("%s: device %s not in table devices list",
446                        dm_device_name(ti->table->md), d->name);
447                 return;
448         }
449         if (refcount_dec_and_test(&dd->count)) {
450                 dm_put_table_device(ti->table->md, d);
451                 list_del(&dd->list);
452                 kfree(dd);
453         }
454 }
455 EXPORT_SYMBOL(dm_put_device);
456
457 /*
458  * Checks to see if the target joins onto the end of the table.
459  */
460 static int adjoin(struct dm_table *table, struct dm_target *ti)
461 {
462         struct dm_target *prev;
463
464         if (!table->num_targets)
465                 return !ti->begin;
466
467         prev = &table->targets[table->num_targets - 1];
468         return (ti->begin == (prev->begin + prev->len));
469 }
470
471 /*
472  * Used to dynamically allocate the arg array.
473  *
474  * We do first allocation with GFP_NOIO because dm-mpath and dm-thin must
475  * process messages even if some device is suspended. These messages have a
476  * small fixed number of arguments.
477  *
478  * On the other hand, dm-switch needs to process bulk data using messages and
479  * excessive use of GFP_NOIO could cause trouble.
480  */
481 static char **realloc_argv(unsigned *size, char **old_argv)
482 {
483         char **argv;
484         unsigned new_size;
485         gfp_t gfp;
486
487         if (*size) {
488                 new_size = *size * 2;
489                 gfp = GFP_KERNEL;
490         } else {
491                 new_size = 8;
492                 gfp = GFP_NOIO;
493         }
494         argv = kmalloc_array(new_size, sizeof(*argv), gfp);
495         if (argv && old_argv) {
496                 memcpy(argv, old_argv, *size * sizeof(*argv));
497                 *size = new_size;
498         }
499
500         kfree(old_argv);
501         return argv;
502 }
503
504 /*
505  * Destructively splits up the argument list to pass to ctr.
506  */
507 int dm_split_args(int *argc, char ***argvp, char *input)
508 {
509         char *start, *end = input, *out, **argv = NULL;
510         unsigned array_size = 0;
511
512         *argc = 0;
513
514         if (!input) {
515                 *argvp = NULL;
516                 return 0;
517         }
518
519         argv = realloc_argv(&array_size, argv);
520         if (!argv)
521                 return -ENOMEM;
522
523         while (1) {
524                 /* Skip whitespace */
525                 start = skip_spaces(end);
526
527                 if (!*start)
528                         break;  /* success, we hit the end */
529
530                 /* 'out' is used to remove any back-quotes */
531                 end = out = start;
532                 while (*end) {
533                         /* Everything apart from '\0' can be quoted */
534                         if (*end == '\\' && *(end + 1)) {
535                                 *out++ = *(end + 1);
536                                 end += 2;
537                                 continue;
538                         }
539
540                         if (isspace(*end))
541                                 break;  /* end of token */
542
543                         *out++ = *end++;
544                 }
545
546                 /* have we already filled the array ? */
547                 if ((*argc + 1) > array_size) {
548                         argv = realloc_argv(&array_size, argv);
549                         if (!argv)
550                                 return -ENOMEM;
551                 }
552
553                 /* we know this is whitespace */
554                 if (*end)
555                         end++;
556
557                 /* terminate the string and put it in the array */
558                 *out = '\0';
559                 argv[*argc] = start;
560                 (*argc)++;
561         }
562
563         *argvp = argv;
564         return 0;
565 }
566
567 /*
568  * Impose necessary and sufficient conditions on a devices's table such
569  * that any incoming bio which respects its logical_block_size can be
570  * processed successfully.  If it falls across the boundary between
571  * two or more targets, the size of each piece it gets split into must
572  * be compatible with the logical_block_size of the target processing it.
573  */
574 static int validate_hardware_logical_block_alignment(struct dm_table *table,
575                                                  struct queue_limits *limits)
576 {
577         /*
578          * This function uses arithmetic modulo the logical_block_size
579          * (in units of 512-byte sectors).
580          */
581         unsigned short device_logical_block_size_sects =
582                 limits->logical_block_size >> SECTOR_SHIFT;
583
584         /*
585          * Offset of the start of the next table entry, mod logical_block_size.
586          */
587         unsigned short next_target_start = 0;
588
589         /*
590          * Given an aligned bio that extends beyond the end of a
591          * target, how many sectors must the next target handle?
592          */
593         unsigned short remaining = 0;
594
595         struct dm_target *ti;
596         struct queue_limits ti_limits;
597         unsigned i;
598
599         /*
600          * Check each entry in the table in turn.
601          */
602         for (i = 0; i < dm_table_get_num_targets(table); i++) {
603                 ti = dm_table_get_target(table, i);
604
605                 blk_set_stacking_limits(&ti_limits);
606
607                 /* combine all target devices' limits */
608                 if (ti->type->iterate_devices)
609                         ti->type->iterate_devices(ti, dm_set_device_limits,
610                                                   &ti_limits);
611
612                 /*
613                  * If the remaining sectors fall entirely within this
614                  * table entry are they compatible with its logical_block_size?
615                  */
616                 if (remaining < ti->len &&
617                     remaining & ((ti_limits.logical_block_size >>
618                                   SECTOR_SHIFT) - 1))
619                         break;  /* Error */
620
621                 next_target_start =
622                     (unsigned short) ((next_target_start + ti->len) &
623                                       (device_logical_block_size_sects - 1));
624                 remaining = next_target_start ?
625                     device_logical_block_size_sects - next_target_start : 0;
626         }
627
628         if (remaining) {
629                 DMWARN("%s: table line %u (start sect %llu len %llu) "
630                        "not aligned to h/w logical block size %u",
631                        dm_device_name(table->md), i,
632                        (unsigned long long) ti->begin,
633                        (unsigned long long) ti->len,
634                        limits->logical_block_size);
635                 return -EINVAL;
636         }
637
638         return 0;
639 }
640
641 int dm_table_add_target(struct dm_table *t, const char *type,
642                         sector_t start, sector_t len, char *params)
643 {
644         int r = -EINVAL, argc;
645         char **argv;
646         struct dm_target *tgt;
647
648         if (t->singleton) {
649                 DMERR("%s: target type %s must appear alone in table",
650                       dm_device_name(t->md), t->targets->type->name);
651                 return -EINVAL;
652         }
653
654         BUG_ON(t->num_targets >= t->num_allocated);
655
656         tgt = t->targets + t->num_targets;
657         memset(tgt, 0, sizeof(*tgt));
658
659         if (!len) {
660                 DMERR("%s: zero-length target", dm_device_name(t->md));
661                 return -EINVAL;
662         }
663
664         tgt->type = dm_get_target_type(type);
665         if (!tgt->type) {
666                 DMERR("%s: %s: unknown target type", dm_device_name(t->md), type);
667                 return -EINVAL;
668         }
669
670         if (dm_target_needs_singleton(tgt->type)) {
671                 if (t->num_targets) {
672                         tgt->error = "singleton target type must appear alone in table";
673                         goto bad;
674                 }
675                 t->singleton = true;
676         }
677
678         if (dm_target_always_writeable(tgt->type) && !(t->mode & FMODE_WRITE)) {
679                 tgt->error = "target type may not be included in a read-only table";
680                 goto bad;
681         }
682
683         if (t->immutable_target_type) {
684                 if (t->immutable_target_type != tgt->type) {
685                         tgt->error = "immutable target type cannot be mixed with other target types";
686                         goto bad;
687                 }
688         } else if (dm_target_is_immutable(tgt->type)) {
689                 if (t->num_targets) {
690                         tgt->error = "immutable target type cannot be mixed with other target types";
691                         goto bad;
692                 }
693                 t->immutable_target_type = tgt->type;
694         }
695
696         if (dm_target_has_integrity(tgt->type))
697                 t->integrity_added = 1;
698
699         tgt->table = t;
700         tgt->begin = start;
701         tgt->len = len;
702         tgt->error = "Unknown error";
703
704         /*
705          * Does this target adjoin the previous one ?
706          */
707         if (!adjoin(t, tgt)) {
708                 tgt->error = "Gap in table";
709                 goto bad;
710         }
711
712         r = dm_split_args(&argc, &argv, params);
713         if (r) {
714                 tgt->error = "couldn't split parameters (insufficient memory)";
715                 goto bad;
716         }
717
718         r = tgt->type->ctr(tgt, argc, argv);
719         kfree(argv);
720         if (r)
721                 goto bad;
722
723         t->highs[t->num_targets++] = tgt->begin + tgt->len - 1;
724
725         if (!tgt->num_discard_bios && tgt->discards_supported)
726                 DMWARN("%s: %s: ignoring discards_supported because num_discard_bios is zero.",
727                        dm_device_name(t->md), type);
728
729         return 0;
730
731  bad:
732         DMERR("%s: %s: %s", dm_device_name(t->md), type, tgt->error);
733         dm_put_target_type(tgt->type);
734         return r;
735 }
736
737 /*
738  * Target argument parsing helpers.
739  */
740 static int validate_next_arg(const struct dm_arg *arg,
741                              struct dm_arg_set *arg_set,
742                              unsigned *value, char **error, unsigned grouped)
743 {
744         const char *arg_str = dm_shift_arg(arg_set);
745         char dummy;
746
747         if (!arg_str ||
748             (sscanf(arg_str, "%u%c", value, &dummy) != 1) ||
749             (*value < arg->min) ||
750             (*value > arg->max) ||
751             (grouped && arg_set->argc < *value)) {
752                 *error = arg->error;
753                 return -EINVAL;
754         }
755
756         return 0;
757 }
758
759 int dm_read_arg(const struct dm_arg *arg, struct dm_arg_set *arg_set,
760                 unsigned *value, char **error)
761 {
762         return validate_next_arg(arg, arg_set, value, error, 0);
763 }
764 EXPORT_SYMBOL(dm_read_arg);
765
766 int dm_read_arg_group(const struct dm_arg *arg, struct dm_arg_set *arg_set,
767                       unsigned *value, char **error)
768 {
769         return validate_next_arg(arg, arg_set, value, error, 1);
770 }
771 EXPORT_SYMBOL(dm_read_arg_group);
772
773 const char *dm_shift_arg(struct dm_arg_set *as)
774 {
775         char *r;
776
777         if (as->argc) {
778                 as->argc--;
779                 r = *as->argv;
780                 as->argv++;
781                 return r;
782         }
783
784         return NULL;
785 }
786 EXPORT_SYMBOL(dm_shift_arg);
787
788 void dm_consume_args(struct dm_arg_set *as, unsigned num_args)
789 {
790         BUG_ON(as->argc < num_args);
791         as->argc -= num_args;
792         as->argv += num_args;
793 }
794 EXPORT_SYMBOL(dm_consume_args);
795
796 static bool __table_type_bio_based(enum dm_queue_mode table_type)
797 {
798         return (table_type == DM_TYPE_BIO_BASED ||
799                 table_type == DM_TYPE_DAX_BIO_BASED);
800 }
801
802 static bool __table_type_request_based(enum dm_queue_mode table_type)
803 {
804         return table_type == DM_TYPE_REQUEST_BASED;
805 }
806
807 void dm_table_set_type(struct dm_table *t, enum dm_queue_mode type)
808 {
809         t->type = type;
810 }
811 EXPORT_SYMBOL_GPL(dm_table_set_type);
812
813 /* validate the dax capability of the target device span */
814 int device_supports_dax(struct dm_target *ti, struct dm_dev *dev,
815                         sector_t start, sector_t len, void *data)
816 {
817         int blocksize = *(int *) data, id;
818         bool rc;
819
820         id = dax_read_lock();
821         rc = dax_supported(dev->dax_dev, dev->bdev, blocksize, start, len);
822         dax_read_unlock(id);
823
824         return rc;
825 }
826
827 /* Check devices support synchronous DAX */
828 static int device_dax_synchronous(struct dm_target *ti, struct dm_dev *dev,
829                                   sector_t start, sector_t len, void *data)
830 {
831         return dev->dax_dev && dax_synchronous(dev->dax_dev);
832 }
833
834 bool dm_table_supports_dax(struct dm_table *t,
835                            iterate_devices_callout_fn iterate_fn, int *blocksize)
836 {
837         struct dm_target *ti;
838         unsigned i;
839
840         /* Ensure that all targets support DAX. */
841         for (i = 0; i < dm_table_get_num_targets(t); i++) {
842                 ti = dm_table_get_target(t, i);
843
844                 if (!ti->type->direct_access)
845                         return false;
846
847                 if (!ti->type->iterate_devices ||
848                     !ti->type->iterate_devices(ti, iterate_fn, blocksize))
849                         return false;
850         }
851
852         return true;
853 }
854
855 static int device_is_rq_stackable(struct dm_target *ti, struct dm_dev *dev,
856                                   sector_t start, sector_t len, void *data)
857 {
858         struct block_device *bdev = dev->bdev;
859         struct request_queue *q = bdev_get_queue(bdev);
860
861         /* request-based cannot stack on partitions! */
862         if (bdev_is_partition(bdev))
863                 return false;
864
865         return queue_is_mq(q);
866 }
867
868 static int dm_table_determine_type(struct dm_table *t)
869 {
870         unsigned i;
871         unsigned bio_based = 0, request_based = 0, hybrid = 0;
872         struct dm_target *tgt;
873         struct list_head *devices = dm_table_get_devices(t);
874         enum dm_queue_mode live_md_type = dm_get_md_type(t->md);
875         int page_size = PAGE_SIZE;
876
877         if (t->type != DM_TYPE_NONE) {
878                 /* target already set the table's type */
879                 if (t->type == DM_TYPE_BIO_BASED) {
880                         /* possibly upgrade to a variant of bio-based */
881                         goto verify_bio_based;
882                 }
883                 BUG_ON(t->type == DM_TYPE_DAX_BIO_BASED);
884                 goto verify_rq_based;
885         }
886
887         for (i = 0; i < t->num_targets; i++) {
888                 tgt = t->targets + i;
889                 if (dm_target_hybrid(tgt))
890                         hybrid = 1;
891                 else if (dm_target_request_based(tgt))
892                         request_based = 1;
893                 else
894                         bio_based = 1;
895
896                 if (bio_based && request_based) {
897                         DMERR("Inconsistent table: different target types"
898                               " can't be mixed up");
899                         return -EINVAL;
900                 }
901         }
902
903         if (hybrid && !bio_based && !request_based) {
904                 /*
905                  * The targets can work either way.
906                  * Determine the type from the live device.
907                  * Default to bio-based if device is new.
908                  */
909                 if (__table_type_request_based(live_md_type))
910                         request_based = 1;
911                 else
912                         bio_based = 1;
913         }
914
915         if (bio_based) {
916 verify_bio_based:
917                 /* We must use this table as bio-based */
918                 t->type = DM_TYPE_BIO_BASED;
919                 if (dm_table_supports_dax(t, device_supports_dax, &page_size) ||
920                     (list_empty(devices) && live_md_type == DM_TYPE_DAX_BIO_BASED)) {
921                         t->type = DM_TYPE_DAX_BIO_BASED;
922                 }
923                 return 0;
924         }
925
926         BUG_ON(!request_based); /* No targets in this table */
927
928         t->type = DM_TYPE_REQUEST_BASED;
929
930 verify_rq_based:
931         /*
932          * Request-based dm supports only tables that have a single target now.
933          * To support multiple targets, request splitting support is needed,
934          * and that needs lots of changes in the block-layer.
935          * (e.g. request completion process for partial completion.)
936          */
937         if (t->num_targets > 1) {
938                 DMERR("request-based DM doesn't support multiple targets");
939                 return -EINVAL;
940         }
941
942         if (list_empty(devices)) {
943                 int srcu_idx;
944                 struct dm_table *live_table = dm_get_live_table(t->md, &srcu_idx);
945
946                 /* inherit live table's type */
947                 if (live_table)
948                         t->type = live_table->type;
949                 dm_put_live_table(t->md, srcu_idx);
950                 return 0;
951         }
952
953         tgt = dm_table_get_immutable_target(t);
954         if (!tgt) {
955                 DMERR("table load rejected: immutable target is required");
956                 return -EINVAL;
957         } else if (tgt->max_io_len) {
958                 DMERR("table load rejected: immutable target that splits IO is not supported");
959                 return -EINVAL;
960         }
961
962         /* Non-request-stackable devices can't be used for request-based dm */
963         if (!tgt->type->iterate_devices ||
964             !tgt->type->iterate_devices(tgt, device_is_rq_stackable, NULL)) {
965                 DMERR("table load rejected: including non-request-stackable devices");
966                 return -EINVAL;
967         }
968
969         return 0;
970 }
971
972 enum dm_queue_mode dm_table_get_type(struct dm_table *t)
973 {
974         return t->type;
975 }
976
977 struct target_type *dm_table_get_immutable_target_type(struct dm_table *t)
978 {
979         return t->immutable_target_type;
980 }
981
982 struct dm_target *dm_table_get_immutable_target(struct dm_table *t)
983 {
984         /* Immutable target is implicitly a singleton */
985         if (t->num_targets > 1 ||
986             !dm_target_is_immutable(t->targets[0].type))
987                 return NULL;
988
989         return t->targets;
990 }
991
992 struct dm_target *dm_table_get_wildcard_target(struct dm_table *t)
993 {
994         struct dm_target *ti;
995         unsigned i;
996
997         for (i = 0; i < dm_table_get_num_targets(t); i++) {
998                 ti = dm_table_get_target(t, i);
999                 if (dm_target_is_wildcard(ti->type))
1000                         return ti;
1001         }
1002
1003         return NULL;
1004 }
1005
1006 bool dm_table_bio_based(struct dm_table *t)
1007 {
1008         return __table_type_bio_based(dm_table_get_type(t));
1009 }
1010
1011 bool dm_table_request_based(struct dm_table *t)
1012 {
1013         return __table_type_request_based(dm_table_get_type(t));
1014 }
1015
1016 static int dm_table_alloc_md_mempools(struct dm_table *t, struct mapped_device *md)
1017 {
1018         enum dm_queue_mode type = dm_table_get_type(t);
1019         unsigned per_io_data_size = 0;
1020         unsigned min_pool_size = 0;
1021         struct dm_target *ti;
1022         unsigned i;
1023
1024         if (unlikely(type == DM_TYPE_NONE)) {
1025                 DMWARN("no table type is set, can't allocate mempools");
1026                 return -EINVAL;
1027         }
1028
1029         if (__table_type_bio_based(type))
1030                 for (i = 0; i < t->num_targets; i++) {
1031                         ti = t->targets + i;
1032                         per_io_data_size = max(per_io_data_size, ti->per_io_data_size);
1033                         min_pool_size = max(min_pool_size, ti->num_flush_bios);
1034                 }
1035
1036         t->mempools = dm_alloc_md_mempools(md, type, t->integrity_supported,
1037                                            per_io_data_size, min_pool_size);
1038         if (!t->mempools)
1039                 return -ENOMEM;
1040
1041         return 0;
1042 }
1043
1044 void dm_table_free_md_mempools(struct dm_table *t)
1045 {
1046         dm_free_md_mempools(t->mempools);
1047         t->mempools = NULL;
1048 }
1049
1050 struct dm_md_mempools *dm_table_get_md_mempools(struct dm_table *t)
1051 {
1052         return t->mempools;
1053 }
1054
1055 static int setup_indexes(struct dm_table *t)
1056 {
1057         int i;
1058         unsigned int total = 0;
1059         sector_t *indexes;
1060
1061         /* allocate the space for *all* the indexes */
1062         for (i = t->depth - 2; i >= 0; i--) {
1063                 t->counts[i] = dm_div_up(t->counts[i + 1], CHILDREN_PER_NODE);
1064                 total += t->counts[i];
1065         }
1066
1067         indexes = (sector_t *) dm_vcalloc(total, (unsigned long) NODE_SIZE);
1068         if (!indexes)
1069                 return -ENOMEM;
1070
1071         /* set up internal nodes, bottom-up */
1072         for (i = t->depth - 2; i >= 0; i--) {
1073                 t->index[i] = indexes;
1074                 indexes += (KEYS_PER_NODE * t->counts[i]);
1075                 setup_btree_index(i, t);
1076         }
1077
1078         return 0;
1079 }
1080
1081 /*
1082  * Builds the btree to index the map.
1083  */
1084 static int dm_table_build_index(struct dm_table *t)
1085 {
1086         int r = 0;
1087         unsigned int leaf_nodes;
1088
1089         /* how many indexes will the btree have ? */
1090         leaf_nodes = dm_div_up(t->num_targets, KEYS_PER_NODE);
1091         t->depth = 1 + int_log(leaf_nodes, CHILDREN_PER_NODE);
1092
1093         /* leaf layer has already been set up */
1094         t->counts[t->depth - 1] = leaf_nodes;
1095         t->index[t->depth - 1] = t->highs;
1096
1097         if (t->depth >= 2)
1098                 r = setup_indexes(t);
1099
1100         return r;
1101 }
1102
1103 static bool integrity_profile_exists(struct gendisk *disk)
1104 {
1105         return !!blk_get_integrity(disk);
1106 }
1107
1108 /*
1109  * Get a disk whose integrity profile reflects the table's profile.
1110  * Returns NULL if integrity support was inconsistent or unavailable.
1111  */
1112 static struct gendisk * dm_table_get_integrity_disk(struct dm_table *t)
1113 {
1114         struct list_head *devices = dm_table_get_devices(t);
1115         struct dm_dev_internal *dd = NULL;
1116         struct gendisk *prev_disk = NULL, *template_disk = NULL;
1117         unsigned i;
1118
1119         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1120                 struct dm_target *ti = dm_table_get_target(t, i);
1121                 if (!dm_target_passes_integrity(ti->type))
1122                         goto no_integrity;
1123         }
1124
1125         list_for_each_entry(dd, devices, list) {
1126                 template_disk = dd->dm_dev->bdev->bd_disk;
1127                 if (!integrity_profile_exists(template_disk))
1128                         goto no_integrity;
1129                 else if (prev_disk &&
1130                          blk_integrity_compare(prev_disk, template_disk) < 0)
1131                         goto no_integrity;
1132                 prev_disk = template_disk;
1133         }
1134
1135         return template_disk;
1136
1137 no_integrity:
1138         if (prev_disk)
1139                 DMWARN("%s: integrity not set: %s and %s profile mismatch",
1140                        dm_device_name(t->md),
1141                        prev_disk->disk_name,
1142                        template_disk->disk_name);
1143         return NULL;
1144 }
1145
1146 /*
1147  * Register the mapped device for blk_integrity support if the
1148  * underlying devices have an integrity profile.  But all devices may
1149  * not have matching profiles (checking all devices isn't reliable
1150  * during table load because this table may use other DM device(s) which
1151  * must be resumed before they will have an initialized integity
1152  * profile).  Consequently, stacked DM devices force a 2 stage integrity
1153  * profile validation: First pass during table load, final pass during
1154  * resume.
1155  */
1156 static int dm_table_register_integrity(struct dm_table *t)
1157 {
1158         struct mapped_device *md = t->md;
1159         struct gendisk *template_disk = NULL;
1160
1161         /* If target handles integrity itself do not register it here. */
1162         if (t->integrity_added)
1163                 return 0;
1164
1165         template_disk = dm_table_get_integrity_disk(t);
1166         if (!template_disk)
1167                 return 0;
1168
1169         if (!integrity_profile_exists(dm_disk(md))) {
1170                 t->integrity_supported = true;
1171                 /*
1172                  * Register integrity profile during table load; we can do
1173                  * this because the final profile must match during resume.
1174                  */
1175                 blk_integrity_register(dm_disk(md),
1176                                        blk_get_integrity(template_disk));
1177                 return 0;
1178         }
1179
1180         /*
1181          * If DM device already has an initialized integrity
1182          * profile the new profile should not conflict.
1183          */
1184         if (blk_integrity_compare(dm_disk(md), template_disk) < 0) {
1185                 DMWARN("%s: conflict with existing integrity profile: "
1186                        "%s profile mismatch",
1187                        dm_device_name(t->md),
1188                        template_disk->disk_name);
1189                 return 1;
1190         }
1191
1192         /* Preserve existing integrity profile */
1193         t->integrity_supported = true;
1194         return 0;
1195 }
1196
1197 /*
1198  * Prepares the table for use by building the indices,
1199  * setting the type, and allocating mempools.
1200  */
1201 int dm_table_complete(struct dm_table *t)
1202 {
1203         int r;
1204
1205         r = dm_table_determine_type(t);
1206         if (r) {
1207                 DMERR("unable to determine table type");
1208                 return r;
1209         }
1210
1211         r = dm_table_build_index(t);
1212         if (r) {
1213                 DMERR("unable to build btrees");
1214                 return r;
1215         }
1216
1217         r = dm_table_register_integrity(t);
1218         if (r) {
1219                 DMERR("could not register integrity profile.");
1220                 return r;
1221         }
1222
1223         r = dm_table_alloc_md_mempools(t, t->md);
1224         if (r)
1225                 DMERR("unable to allocate mempools");
1226
1227         return r;
1228 }
1229
1230 static DEFINE_MUTEX(_event_lock);
1231 void dm_table_event_callback(struct dm_table *t,
1232                              void (*fn)(void *), void *context)
1233 {
1234         mutex_lock(&_event_lock);
1235         t->event_fn = fn;
1236         t->event_context = context;
1237         mutex_unlock(&_event_lock);
1238 }
1239
1240 void dm_table_event(struct dm_table *t)
1241 {
1242         mutex_lock(&_event_lock);
1243         if (t->event_fn)
1244                 t->event_fn(t->event_context);
1245         mutex_unlock(&_event_lock);
1246 }
1247 EXPORT_SYMBOL(dm_table_event);
1248
1249 inline sector_t dm_table_get_size(struct dm_table *t)
1250 {
1251         return t->num_targets ? (t->highs[t->num_targets - 1] + 1) : 0;
1252 }
1253 EXPORT_SYMBOL(dm_table_get_size);
1254
1255 struct dm_target *dm_table_get_target(struct dm_table *t, unsigned int index)
1256 {
1257         if (index >= t->num_targets)
1258                 return NULL;
1259
1260         return t->targets + index;
1261 }
1262
1263 /*
1264  * Search the btree for the correct target.
1265  *
1266  * Caller should check returned pointer for NULL
1267  * to trap I/O beyond end of device.
1268  */
1269 struct dm_target *dm_table_find_target(struct dm_table *t, sector_t sector)
1270 {
1271         unsigned int l, n = 0, k = 0;
1272         sector_t *node;
1273
1274         if (unlikely(sector >= dm_table_get_size(t)))
1275                 return NULL;
1276
1277         for (l = 0; l < t->depth; l++) {
1278                 n = get_child(n, k);
1279                 node = get_node(t, l, n);
1280
1281                 for (k = 0; k < KEYS_PER_NODE; k++)
1282                         if (node[k] >= sector)
1283                                 break;
1284         }
1285
1286         return &t->targets[(KEYS_PER_NODE * n) + k];
1287 }
1288
1289 static int count_device(struct dm_target *ti, struct dm_dev *dev,
1290                         sector_t start, sector_t len, void *data)
1291 {
1292         unsigned *num_devices = data;
1293
1294         (*num_devices)++;
1295
1296         return 0;
1297 }
1298
1299 /*
1300  * Check whether a table has no data devices attached using each
1301  * target's iterate_devices method.
1302  * Returns false if the result is unknown because a target doesn't
1303  * support iterate_devices.
1304  */
1305 bool dm_table_has_no_data_devices(struct dm_table *table)
1306 {
1307         struct dm_target *ti;
1308         unsigned i, num_devices;
1309
1310         for (i = 0; i < dm_table_get_num_targets(table); i++) {
1311                 ti = dm_table_get_target(table, i);
1312
1313                 if (!ti->type->iterate_devices)
1314                         return false;
1315
1316                 num_devices = 0;
1317                 ti->type->iterate_devices(ti, count_device, &num_devices);
1318                 if (num_devices)
1319                         return false;
1320         }
1321
1322         return true;
1323 }
1324
1325 static int device_is_zoned_model(struct dm_target *ti, struct dm_dev *dev,
1326                                  sector_t start, sector_t len, void *data)
1327 {
1328         struct request_queue *q = bdev_get_queue(dev->bdev);
1329         enum blk_zoned_model *zoned_model = data;
1330
1331         return q && blk_queue_zoned_model(q) == *zoned_model;
1332 }
1333
1334 static bool dm_table_supports_zoned_model(struct dm_table *t,
1335                                           enum blk_zoned_model zoned_model)
1336 {
1337         struct dm_target *ti;
1338         unsigned i;
1339
1340         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1341                 ti = dm_table_get_target(t, i);
1342
1343                 if (zoned_model == BLK_ZONED_HM &&
1344                     !dm_target_supports_zoned_hm(ti->type))
1345                         return false;
1346
1347                 if (!ti->type->iterate_devices ||
1348                     !ti->type->iterate_devices(ti, device_is_zoned_model, &zoned_model))
1349                         return false;
1350         }
1351
1352         return true;
1353 }
1354
1355 static int device_matches_zone_sectors(struct dm_target *ti, struct dm_dev *dev,
1356                                        sector_t start, sector_t len, void *data)
1357 {
1358         struct request_queue *q = bdev_get_queue(dev->bdev);
1359         unsigned int *zone_sectors = data;
1360
1361         return q && blk_queue_zone_sectors(q) == *zone_sectors;
1362 }
1363
1364 static bool dm_table_matches_zone_sectors(struct dm_table *t,
1365                                           unsigned int zone_sectors)
1366 {
1367         struct dm_target *ti;
1368         unsigned i;
1369
1370         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1371                 ti = dm_table_get_target(t, i);
1372
1373                 if (!ti->type->iterate_devices ||
1374                     !ti->type->iterate_devices(ti, device_matches_zone_sectors, &zone_sectors))
1375                         return false;
1376         }
1377
1378         return true;
1379 }
1380
1381 static int validate_hardware_zoned_model(struct dm_table *table,
1382                                          enum blk_zoned_model zoned_model,
1383                                          unsigned int zone_sectors)
1384 {
1385         if (zoned_model == BLK_ZONED_NONE)
1386                 return 0;
1387
1388         if (!dm_table_supports_zoned_model(table, zoned_model)) {
1389                 DMERR("%s: zoned model is not consistent across all devices",
1390                       dm_device_name(table->md));
1391                 return -EINVAL;
1392         }
1393
1394         /* Check zone size validity and compatibility */
1395         if (!zone_sectors || !is_power_of_2(zone_sectors))
1396                 return -EINVAL;
1397
1398         if (!dm_table_matches_zone_sectors(table, zone_sectors)) {
1399                 DMERR("%s: zone sectors is not consistent across all devices",
1400                       dm_device_name(table->md));
1401                 return -EINVAL;
1402         }
1403
1404         return 0;
1405 }
1406
1407 /*
1408  * Establish the new table's queue_limits and validate them.
1409  */
1410 int dm_calculate_queue_limits(struct dm_table *table,
1411                               struct queue_limits *limits)
1412 {
1413         struct dm_target *ti;
1414         struct queue_limits ti_limits;
1415         unsigned i;
1416         enum blk_zoned_model zoned_model = BLK_ZONED_NONE;
1417         unsigned int zone_sectors = 0;
1418
1419         blk_set_stacking_limits(limits);
1420
1421         for (i = 0; i < dm_table_get_num_targets(table); i++) {
1422                 blk_set_stacking_limits(&ti_limits);
1423
1424                 ti = dm_table_get_target(table, i);
1425
1426                 if (!ti->type->iterate_devices)
1427                         goto combine_limits;
1428
1429                 /*
1430                  * Combine queue limits of all the devices this target uses.
1431                  */
1432                 ti->type->iterate_devices(ti, dm_set_device_limits,
1433                                           &ti_limits);
1434
1435                 if (zoned_model == BLK_ZONED_NONE && ti_limits.zoned != BLK_ZONED_NONE) {
1436                         /*
1437                          * After stacking all limits, validate all devices
1438                          * in table support this zoned model and zone sectors.
1439                          */
1440                         zoned_model = ti_limits.zoned;
1441                         zone_sectors = ti_limits.chunk_sectors;
1442                 }
1443
1444                 /* Set I/O hints portion of queue limits */
1445                 if (ti->type->io_hints)
1446                         ti->type->io_hints(ti, &ti_limits);
1447
1448                 /*
1449                  * Check each device area is consistent with the target's
1450                  * overall queue limits.
1451                  */
1452                 if (ti->type->iterate_devices(ti, device_area_is_invalid,
1453                                               &ti_limits))
1454                         return -EINVAL;
1455
1456 combine_limits:
1457                 /*
1458                  * Merge this target's queue limits into the overall limits
1459                  * for the table.
1460                  */
1461                 if (blk_stack_limits(limits, &ti_limits, 0) < 0)
1462                         DMWARN("%s: adding target device "
1463                                "(start sect %llu len %llu) "
1464                                "caused an alignment inconsistency",
1465                                dm_device_name(table->md),
1466                                (unsigned long long) ti->begin,
1467                                (unsigned long long) ti->len);
1468         }
1469
1470         /*
1471          * Verify that the zoned model and zone sectors, as determined before
1472          * any .io_hints override, are the same across all devices in the table.
1473          * - this is especially relevant if .io_hints is emulating a disk-managed
1474          *   zoned model (aka BLK_ZONED_NONE) on host-managed zoned block devices.
1475          * BUT...
1476          */
1477         if (limits->zoned != BLK_ZONED_NONE) {
1478                 /*
1479                  * ...IF the above limits stacking determined a zoned model
1480                  * validate that all of the table's devices conform to it.
1481                  */
1482                 zoned_model = limits->zoned;
1483                 zone_sectors = limits->chunk_sectors;
1484         }
1485         if (validate_hardware_zoned_model(table, zoned_model, zone_sectors))
1486                 return -EINVAL;
1487
1488         return validate_hardware_logical_block_alignment(table, limits);
1489 }
1490
1491 /*
1492  * Verify that all devices have an integrity profile that matches the
1493  * DM device's registered integrity profile.  If the profiles don't
1494  * match then unregister the DM device's integrity profile.
1495  */
1496 static void dm_table_verify_integrity(struct dm_table *t)
1497 {
1498         struct gendisk *template_disk = NULL;
1499
1500         if (t->integrity_added)
1501                 return;
1502
1503         if (t->integrity_supported) {
1504                 /*
1505                  * Verify that the original integrity profile
1506                  * matches all the devices in this table.
1507                  */
1508                 template_disk = dm_table_get_integrity_disk(t);
1509                 if (template_disk &&
1510                     blk_integrity_compare(dm_disk(t->md), template_disk) >= 0)
1511                         return;
1512         }
1513
1514         if (integrity_profile_exists(dm_disk(t->md))) {
1515                 DMWARN("%s: unable to establish an integrity profile",
1516                        dm_device_name(t->md));
1517                 blk_integrity_unregister(dm_disk(t->md));
1518         }
1519 }
1520
1521 static int device_flush_capable(struct dm_target *ti, struct dm_dev *dev,
1522                                 sector_t start, sector_t len, void *data)
1523 {
1524         unsigned long flush = (unsigned long) data;
1525         struct request_queue *q = bdev_get_queue(dev->bdev);
1526
1527         return q && (q->queue_flags & flush);
1528 }
1529
1530 static bool dm_table_supports_flush(struct dm_table *t, unsigned long flush)
1531 {
1532         struct dm_target *ti;
1533         unsigned i;
1534
1535         /*
1536          * Require at least one underlying device to support flushes.
1537          * t->devices includes internal dm devices such as mirror logs
1538          * so we need to use iterate_devices here, which targets
1539          * supporting flushes must provide.
1540          */
1541         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1542                 ti = dm_table_get_target(t, i);
1543
1544                 if (!ti->num_flush_bios)
1545                         continue;
1546
1547                 if (ti->flush_supported)
1548                         return true;
1549
1550                 if (ti->type->iterate_devices &&
1551                     ti->type->iterate_devices(ti, device_flush_capable, (void *) flush))
1552                         return true;
1553         }
1554
1555         return false;
1556 }
1557
1558 static int device_dax_write_cache_enabled(struct dm_target *ti,
1559                                           struct dm_dev *dev, sector_t start,
1560                                           sector_t len, void *data)
1561 {
1562         struct dax_device *dax_dev = dev->dax_dev;
1563
1564         if (!dax_dev)
1565                 return false;
1566
1567         if (dax_write_cache_enabled(dax_dev))
1568                 return true;
1569         return false;
1570 }
1571
1572 static int dm_table_supports_dax_write_cache(struct dm_table *t)
1573 {
1574         struct dm_target *ti;
1575         unsigned i;
1576
1577         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1578                 ti = dm_table_get_target(t, i);
1579
1580                 if (ti->type->iterate_devices &&
1581                     ti->type->iterate_devices(ti,
1582                                 device_dax_write_cache_enabled, NULL))
1583                         return true;
1584         }
1585
1586         return false;
1587 }
1588
1589 static int device_is_nonrot(struct dm_target *ti, struct dm_dev *dev,
1590                             sector_t start, sector_t len, void *data)
1591 {
1592         struct request_queue *q = bdev_get_queue(dev->bdev);
1593
1594         return q && blk_queue_nonrot(q);
1595 }
1596
1597 static int device_is_not_random(struct dm_target *ti, struct dm_dev *dev,
1598                              sector_t start, sector_t len, void *data)
1599 {
1600         struct request_queue *q = bdev_get_queue(dev->bdev);
1601
1602         return q && !blk_queue_add_random(q);
1603 }
1604
1605 static bool dm_table_all_devices_attribute(struct dm_table *t,
1606                                            iterate_devices_callout_fn func)
1607 {
1608         struct dm_target *ti;
1609         unsigned i;
1610
1611         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1612                 ti = dm_table_get_target(t, i);
1613
1614                 if (!ti->type->iterate_devices ||
1615                     !ti->type->iterate_devices(ti, func, NULL))
1616                         return false;
1617         }
1618
1619         return true;
1620 }
1621
1622 static int device_not_write_same_capable(struct dm_target *ti, struct dm_dev *dev,
1623                                          sector_t start, sector_t len, void *data)
1624 {
1625         struct request_queue *q = bdev_get_queue(dev->bdev);
1626
1627         return q && !q->limits.max_write_same_sectors;
1628 }
1629
1630 static bool dm_table_supports_write_same(struct dm_table *t)
1631 {
1632         struct dm_target *ti;
1633         unsigned i;
1634
1635         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1636                 ti = dm_table_get_target(t, i);
1637
1638                 if (!ti->num_write_same_bios)
1639                         return false;
1640
1641                 if (!ti->type->iterate_devices ||
1642                     ti->type->iterate_devices(ti, device_not_write_same_capable, NULL))
1643                         return false;
1644         }
1645
1646         return true;
1647 }
1648
1649 static int device_not_write_zeroes_capable(struct dm_target *ti, struct dm_dev *dev,
1650                                            sector_t start, sector_t len, void *data)
1651 {
1652         struct request_queue *q = bdev_get_queue(dev->bdev);
1653
1654         return q && !q->limits.max_write_zeroes_sectors;
1655 }
1656
1657 static bool dm_table_supports_write_zeroes(struct dm_table *t)
1658 {
1659         struct dm_target *ti;
1660         unsigned i = 0;
1661
1662         while (i < dm_table_get_num_targets(t)) {
1663                 ti = dm_table_get_target(t, i++);
1664
1665                 if (!ti->num_write_zeroes_bios)
1666                         return false;
1667
1668                 if (!ti->type->iterate_devices ||
1669                     ti->type->iterate_devices(ti, device_not_write_zeroes_capable, NULL))
1670                         return false;
1671         }
1672
1673         return true;
1674 }
1675
1676 static int device_not_nowait_capable(struct dm_target *ti, struct dm_dev *dev,
1677                                      sector_t start, sector_t len, void *data)
1678 {
1679         struct request_queue *q = bdev_get_queue(dev->bdev);
1680
1681         return q && !blk_queue_nowait(q);
1682 }
1683
1684 static bool dm_table_supports_nowait(struct dm_table *t)
1685 {
1686         struct dm_target *ti;
1687         unsigned i = 0;
1688
1689         while (i < dm_table_get_num_targets(t)) {
1690                 ti = dm_table_get_target(t, i++);
1691
1692                 if (!dm_target_supports_nowait(ti->type))
1693                         return false;
1694
1695                 if (!ti->type->iterate_devices ||
1696                     ti->type->iterate_devices(ti, device_not_nowait_capable, NULL))
1697                         return false;
1698         }
1699
1700         return true;
1701 }
1702
1703 static int device_not_discard_capable(struct dm_target *ti, struct dm_dev *dev,
1704                                       sector_t start, sector_t len, void *data)
1705 {
1706         struct request_queue *q = bdev_get_queue(dev->bdev);
1707
1708         return q && !blk_queue_discard(q);
1709 }
1710
1711 static bool dm_table_supports_discards(struct dm_table *t)
1712 {
1713         struct dm_target *ti;
1714         unsigned i;
1715
1716         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1717                 ti = dm_table_get_target(t, i);
1718
1719                 if (!ti->num_discard_bios)
1720                         return false;
1721
1722                 /*
1723                  * Either the target provides discard support (as implied by setting
1724                  * 'discards_supported') or it relies on _all_ data devices having
1725                  * discard support.
1726                  */
1727                 if (!ti->discards_supported &&
1728                     (!ti->type->iterate_devices ||
1729                      ti->type->iterate_devices(ti, device_not_discard_capable, NULL)))
1730                         return false;
1731         }
1732
1733         return true;
1734 }
1735
1736 static int device_not_secure_erase_capable(struct dm_target *ti,
1737                                            struct dm_dev *dev, sector_t start,
1738                                            sector_t len, void *data)
1739 {
1740         struct request_queue *q = bdev_get_queue(dev->bdev);
1741
1742         return q && !blk_queue_secure_erase(q);
1743 }
1744
1745 static bool dm_table_supports_secure_erase(struct dm_table *t)
1746 {
1747         struct dm_target *ti;
1748         unsigned int i;
1749
1750         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1751                 ti = dm_table_get_target(t, i);
1752
1753                 if (!ti->num_secure_erase_bios)
1754                         return false;
1755
1756                 if (!ti->type->iterate_devices ||
1757                     ti->type->iterate_devices(ti, device_not_secure_erase_capable, NULL))
1758                         return false;
1759         }
1760
1761         return true;
1762 }
1763
1764 static int device_requires_stable_pages(struct dm_target *ti,
1765                                         struct dm_dev *dev, sector_t start,
1766                                         sector_t len, void *data)
1767 {
1768         struct request_queue *q = bdev_get_queue(dev->bdev);
1769
1770         return q && blk_queue_stable_writes(q);
1771 }
1772
1773 /*
1774  * If any underlying device requires stable pages, a table must require
1775  * them as well.  Only targets that support iterate_devices are considered:
1776  * don't want error, zero, etc to require stable pages.
1777  */
1778 static bool dm_table_requires_stable_pages(struct dm_table *t)
1779 {
1780         struct dm_target *ti;
1781         unsigned i;
1782
1783         for (i = 0; i < dm_table_get_num_targets(t); i++) {
1784                 ti = dm_table_get_target(t, i);
1785
1786                 if (ti->type->iterate_devices &&
1787                     ti->type->iterate_devices(ti, device_requires_stable_pages, NULL))
1788                         return true;
1789         }
1790
1791         return false;
1792 }
1793
1794 void dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
1795                                struct queue_limits *limits)
1796 {
1797         bool wc = false, fua = false;
1798         int page_size = PAGE_SIZE;
1799
1800         /*
1801          * Copy table's limits to the DM device's request_queue
1802          */
1803         q->limits = *limits;
1804
1805         if (dm_table_supports_nowait(t))
1806                 blk_queue_flag_set(QUEUE_FLAG_NOWAIT, q);
1807         else
1808                 blk_queue_flag_clear(QUEUE_FLAG_NOWAIT, q);
1809
1810         if (!dm_table_supports_discards(t)) {
1811                 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, q);
1812                 /* Must also clear discard limits... */
1813                 q->limits.max_discard_sectors = 0;
1814                 q->limits.max_hw_discard_sectors = 0;
1815                 q->limits.discard_granularity = 0;
1816                 q->limits.discard_alignment = 0;
1817                 q->limits.discard_misaligned = 0;
1818         } else
1819                 blk_queue_flag_set(QUEUE_FLAG_DISCARD, q);
1820
1821         if (dm_table_supports_secure_erase(t))
1822                 blk_queue_flag_set(QUEUE_FLAG_SECERASE, q);
1823
1824         if (dm_table_supports_flush(t, (1UL << QUEUE_FLAG_WC))) {
1825                 wc = true;
1826                 if (dm_table_supports_flush(t, (1UL << QUEUE_FLAG_FUA)))
1827                         fua = true;
1828         }
1829         blk_queue_write_cache(q, wc, fua);
1830
1831         if (dm_table_supports_dax(t, device_supports_dax, &page_size)) {
1832                 blk_queue_flag_set(QUEUE_FLAG_DAX, q);
1833                 if (dm_table_supports_dax(t, device_dax_synchronous, NULL))
1834                         set_dax_synchronous(t->md->dax_dev);
1835         }
1836         else
1837                 blk_queue_flag_clear(QUEUE_FLAG_DAX, q);
1838
1839         if (dm_table_supports_dax_write_cache(t))
1840                 dax_write_cache(t->md->dax_dev, true);
1841
1842         /* Ensure that all underlying devices are non-rotational. */
1843         if (dm_table_all_devices_attribute(t, device_is_nonrot))
1844                 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
1845         else
1846                 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
1847
1848         if (!dm_table_supports_write_same(t))
1849                 q->limits.max_write_same_sectors = 0;
1850         if (!dm_table_supports_write_zeroes(t))
1851                 q->limits.max_write_zeroes_sectors = 0;
1852
1853         dm_table_verify_integrity(t);
1854
1855         /*
1856          * Some devices don't use blk_integrity but still want stable pages
1857          * because they do their own checksumming.
1858          */
1859         if (dm_table_requires_stable_pages(t))
1860                 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
1861         else
1862                 blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
1863
1864         /*
1865          * Determine whether or not this queue's I/O timings contribute
1866          * to the entropy pool, Only request-based targets use this.
1867          * Clear QUEUE_FLAG_ADD_RANDOM if any underlying device does not
1868          * have it set.
1869          */
1870         if (blk_queue_add_random(q) && dm_table_all_devices_attribute(t, device_is_not_random))
1871                 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, q);
1872
1873         /*
1874          * For a zoned target, the number of zones should be updated for the
1875          * correct value to be exposed in sysfs queue/nr_zones. For a BIO based
1876          * target, this is all that is needed.
1877          */
1878 #ifdef CONFIG_BLK_DEV_ZONED
1879         if (blk_queue_is_zoned(q)) {
1880                 WARN_ON_ONCE(queue_is_mq(q));
1881                 q->nr_zones = blkdev_nr_zones(t->md->disk);
1882         }
1883 #endif
1884
1885         blk_queue_update_readahead(q);
1886 }
1887
1888 unsigned int dm_table_get_num_targets(struct dm_table *t)
1889 {
1890         return t->num_targets;
1891 }
1892
1893 struct list_head *dm_table_get_devices(struct dm_table *t)
1894 {
1895         return &t->devices;
1896 }
1897
1898 fmode_t dm_table_get_mode(struct dm_table *t)
1899 {
1900         return t->mode;
1901 }
1902 EXPORT_SYMBOL(dm_table_get_mode);
1903
1904 enum suspend_mode {
1905         PRESUSPEND,
1906         PRESUSPEND_UNDO,
1907         POSTSUSPEND,
1908 };
1909
1910 static void suspend_targets(struct dm_table *t, enum suspend_mode mode)
1911 {
1912         int i = t->num_targets;
1913         struct dm_target *ti = t->targets;
1914
1915         lockdep_assert_held(&t->md->suspend_lock);
1916
1917         while (i--) {
1918                 switch (mode) {
1919                 case PRESUSPEND:
1920                         if (ti->type->presuspend)
1921                                 ti->type->presuspend(ti);
1922                         break;
1923                 case PRESUSPEND_UNDO:
1924                         if (ti->type->presuspend_undo)
1925                                 ti->type->presuspend_undo(ti);
1926                         break;
1927                 case POSTSUSPEND:
1928                         if (ti->type->postsuspend)
1929                                 ti->type->postsuspend(ti);
1930                         break;
1931                 }
1932                 ti++;
1933         }
1934 }
1935
1936 void dm_table_presuspend_targets(struct dm_table *t)
1937 {
1938         if (!t)
1939                 return;
1940
1941         suspend_targets(t, PRESUSPEND);
1942 }
1943
1944 void dm_table_presuspend_undo_targets(struct dm_table *t)
1945 {
1946         if (!t)
1947                 return;
1948
1949         suspend_targets(t, PRESUSPEND_UNDO);
1950 }
1951
1952 void dm_table_postsuspend_targets(struct dm_table *t)
1953 {
1954         if (!t)
1955                 return;
1956
1957         suspend_targets(t, POSTSUSPEND);
1958 }
1959
1960 int dm_table_resume_targets(struct dm_table *t)
1961 {
1962         int i, r = 0;
1963
1964         lockdep_assert_held(&t->md->suspend_lock);
1965
1966         for (i = 0; i < t->num_targets; i++) {
1967                 struct dm_target *ti = t->targets + i;
1968
1969                 if (!ti->type->preresume)
1970                         continue;
1971
1972                 r = ti->type->preresume(ti);
1973                 if (r) {
1974                         DMERR("%s: %s: preresume failed, error = %d",
1975                               dm_device_name(t->md), ti->type->name, r);
1976                         return r;
1977                 }
1978         }
1979
1980         for (i = 0; i < t->num_targets; i++) {
1981                 struct dm_target *ti = t->targets + i;
1982
1983                 if (ti->type->resume)
1984                         ti->type->resume(ti);
1985         }
1986
1987         return 0;
1988 }
1989
1990 struct mapped_device *dm_table_get_md(struct dm_table *t)
1991 {
1992         return t->md;
1993 }
1994 EXPORT_SYMBOL(dm_table_get_md);
1995
1996 const char *dm_table_device_name(struct dm_table *t)
1997 {
1998         return dm_device_name(t->md);
1999 }
2000 EXPORT_SYMBOL_GPL(dm_table_device_name);
2001
2002 void dm_table_run_md_queue_async(struct dm_table *t)
2003 {
2004         if (!dm_table_request_based(t))
2005                 return;
2006
2007         if (t->md->queue)
2008                 blk_mq_run_hw_queues(t->md->queue, true);
2009 }
2010 EXPORT_SYMBOL(dm_table_run_md_queue_async);
2011