1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
4 * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
5 *
6 * This file is released under the GPL.
7 */
8
9 #include "dm-core.h"
10 #include "dm-rq.h"
11 #include "dm-uevent.h"
12 #include "dm-ima.h"
13
14 #include <linux/bio-integrity.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/mutex.h>
18 #include <linux/sched/mm.h>
19 #include <linux/sched/signal.h>
20 #include <linux/blkpg.h>
21 #include <linux/bio.h>
22 #include <linux/mempool.h>
23 #include <linux/dax.h>
24 #include <linux/slab.h>
25 #include <linux/idr.h>
26 #include <linux/uio.h>
27 #include <linux/hdreg.h>
28 #include <linux/delay.h>
29 #include <linux/wait.h>
30 #include <linux/pr.h>
31 #include <linux/refcount.h>
32 #include <linux/part_stat.h>
33 #include <linux/blk-crypto.h>
34 #include <linux/blk-crypto-profile.h>
35
36 #define DM_MSG_PREFIX "core"
37
38 /*
39 * Cookies are numeric values sent with CHANGE and REMOVE
40 * uevents while resuming, removing or renaming the device.
41 */
42 #define DM_COOKIE_ENV_VAR_NAME "DM_COOKIE"
43 #define DM_COOKIE_LENGTH 24
44
45 /*
46 * For REQ_POLLED fs bio, this flag is set if we link mapped underlying
47 * dm_io into one list, and reuse bio->bi_private as the list head. Before
48 * ending this fs bio, we will recover its ->bi_private.
49 */
50 #define REQ_DM_POLL_LIST REQ_DRV
51
52 static const char *_name = DM_NAME;
53
54 static unsigned int major;
55 static unsigned int _major;
56
57 static DEFINE_IDR(_minor_idr);
58
59 static DEFINE_SPINLOCK(_minor_lock);
60
61 static void do_deferred_remove(struct work_struct *w);
62
63 static DECLARE_WORK(deferred_remove_work, do_deferred_remove);
64
65 static struct workqueue_struct *deferred_remove_workqueue;
66
67 atomic_t dm_global_event_nr = ATOMIC_INIT(0);
68 DECLARE_WAIT_QUEUE_HEAD(dm_global_eventq);
69
dm_issue_global_event(void)70 void dm_issue_global_event(void)
71 {
72 atomic_inc(&dm_global_event_nr);
73 wake_up(&dm_global_eventq);
74 }
75
76 DEFINE_STATIC_KEY_FALSE(stats_enabled);
77 DEFINE_STATIC_KEY_FALSE(swap_bios_enabled);
78 DEFINE_STATIC_KEY_FALSE(zoned_enabled);
79
80 /*
81 * One of these is allocated (on-stack) per original bio.
82 */
83 struct clone_info {
84 struct dm_table *map;
85 struct bio *bio;
86 struct dm_io *io;
87 sector_t sector;
88 unsigned int sector_count;
89 bool is_abnormal_io:1;
90 bool submit_as_polled:1;
91 };
92
clone_to_tio(struct bio * clone)93 static inline struct dm_target_io *clone_to_tio(struct bio *clone)
94 {
95 return container_of(clone, struct dm_target_io, clone);
96 }
97
dm_per_bio_data(struct bio * bio,size_t data_size)98 void *dm_per_bio_data(struct bio *bio, size_t data_size)
99 {
100 if (!dm_tio_flagged(clone_to_tio(bio), DM_TIO_INSIDE_DM_IO))
101 return (char *)bio - DM_TARGET_IO_BIO_OFFSET - data_size;
102 return (char *)bio - DM_IO_BIO_OFFSET - data_size;
103 }
104 EXPORT_SYMBOL_GPL(dm_per_bio_data);
105
dm_bio_from_per_bio_data(void * data,size_t data_size)106 struct bio *dm_bio_from_per_bio_data(void *data, size_t data_size)
107 {
108 struct dm_io *io = (struct dm_io *)((char *)data + data_size);
109
110 if (io->magic == DM_IO_MAGIC)
111 return (struct bio *)((char *)io + DM_IO_BIO_OFFSET);
112 BUG_ON(io->magic != DM_TIO_MAGIC);
113 return (struct bio *)((char *)io + DM_TARGET_IO_BIO_OFFSET);
114 }
115 EXPORT_SYMBOL_GPL(dm_bio_from_per_bio_data);
116
dm_bio_get_target_bio_nr(const struct bio * bio)117 unsigned int dm_bio_get_target_bio_nr(const struct bio *bio)
118 {
119 return container_of(bio, struct dm_target_io, clone)->target_bio_nr;
120 }
121 EXPORT_SYMBOL_GPL(dm_bio_get_target_bio_nr);
122
123 #define MINOR_ALLOCED ((void *)-1)
124
125 #define DM_NUMA_NODE NUMA_NO_NODE
126 static int dm_numa_node = DM_NUMA_NODE;
127
128 #define DEFAULT_SWAP_BIOS (8 * 1048576 / PAGE_SIZE)
129 static int swap_bios = DEFAULT_SWAP_BIOS;
get_swap_bios(void)130 static int get_swap_bios(void)
131 {
132 int latch = READ_ONCE(swap_bios);
133
134 if (unlikely(latch <= 0))
135 latch = DEFAULT_SWAP_BIOS;
136 return latch;
137 }
138
139 struct table_device {
140 struct list_head list;
141 refcount_t count;
142 struct dm_dev dm_dev;
143 };
144
145 /*
146 * Bio-based DM's mempools' reserved IOs set by the user.
147 */
148 #define RESERVED_BIO_BASED_IOS 16
149 static unsigned int reserved_bio_based_ios = RESERVED_BIO_BASED_IOS;
150
__dm_get_module_param_int(int * module_param,int min,int max)151 static int __dm_get_module_param_int(int *module_param, int min, int max)
152 {
153 int param = READ_ONCE(*module_param);
154 int modified_param = 0;
155 bool modified = true;
156
157 if (param < min)
158 modified_param = min;
159 else if (param > max)
160 modified_param = max;
161 else
162 modified = false;
163
164 if (modified) {
165 (void)cmpxchg(module_param, param, modified_param);
166 param = modified_param;
167 }
168
169 return param;
170 }
171
__dm_get_module_param(unsigned int * module_param,unsigned int def,unsigned int max)172 unsigned int __dm_get_module_param(unsigned int *module_param, unsigned int def, unsigned int max)
173 {
174 unsigned int param = READ_ONCE(*module_param);
175 unsigned int modified_param = 0;
176
177 if (!param)
178 modified_param = def;
179 else if (param > max)
180 modified_param = max;
181
182 if (modified_param) {
183 (void)cmpxchg(module_param, param, modified_param);
184 param = modified_param;
185 }
186
187 return param;
188 }
189
dm_get_reserved_bio_based_ios(void)190 unsigned int dm_get_reserved_bio_based_ios(void)
191 {
192 return __dm_get_module_param(&reserved_bio_based_ios,
193 RESERVED_BIO_BASED_IOS, DM_RESERVED_MAX_IOS);
194 }
195 EXPORT_SYMBOL_GPL(dm_get_reserved_bio_based_ios);
196
dm_get_numa_node(void)197 static unsigned int dm_get_numa_node(void)
198 {
199 return __dm_get_module_param_int(&dm_numa_node,
200 DM_NUMA_NODE, num_online_nodes() - 1);
201 }
202
local_init(void)203 static int __init local_init(void)
204 {
205 int r;
206
207 r = dm_uevent_init();
208 if (r)
209 return r;
210
211 deferred_remove_workqueue = alloc_ordered_workqueue("kdmremove", 0);
212 if (!deferred_remove_workqueue) {
213 r = -ENOMEM;
214 goto out_uevent_exit;
215 }
216
217 _major = major;
218 r = register_blkdev(_major, _name);
219 if (r < 0)
220 goto out_free_workqueue;
221
222 if (!_major)
223 _major = r;
224
225 return 0;
226
227 out_free_workqueue:
228 destroy_workqueue(deferred_remove_workqueue);
229 out_uevent_exit:
230 dm_uevent_exit();
231
232 return r;
233 }
234
local_exit(void)235 static void local_exit(void)
236 {
237 destroy_workqueue(deferred_remove_workqueue);
238
239 unregister_blkdev(_major, _name);
240 dm_uevent_exit();
241
242 _major = 0;
243
244 DMINFO("cleaned up");
245 }
246
247 static int (*_inits[])(void) __initdata = {
248 local_init,
249 dm_target_init,
250 dm_linear_init,
251 dm_stripe_init,
252 dm_io_init,
253 dm_kcopyd_init,
254 dm_interface_init,
255 dm_statistics_init,
256 };
257
258 static void (*_exits[])(void) = {
259 local_exit,
260 dm_target_exit,
261 dm_linear_exit,
262 dm_stripe_exit,
263 dm_io_exit,
264 dm_kcopyd_exit,
265 dm_interface_exit,
266 dm_statistics_exit,
267 };
268
dm_init(void)269 static int __init dm_init(void)
270 {
271 const int count = ARRAY_SIZE(_inits);
272 int r, i;
273
274 #if (IS_ENABLED(CONFIG_IMA) && !IS_ENABLED(CONFIG_IMA_DISABLE_HTABLE))
275 DMWARN("CONFIG_IMA_DISABLE_HTABLE is disabled."
276 " Duplicate IMA measurements will not be recorded in the IMA log.");
277 #endif
278
279 for (i = 0; i < count; i++) {
280 r = _inits[i]();
281 if (r)
282 goto bad;
283 }
284
285 return 0;
286 bad:
287 while (i--)
288 _exits[i]();
289
290 return r;
291 }
292
dm_exit(void)293 static void __exit dm_exit(void)
294 {
295 int i = ARRAY_SIZE(_exits);
296
297 while (i--)
298 _exits[i]();
299
300 /*
301 * Should be empty by this point.
302 */
303 idr_destroy(&_minor_idr);
304 }
305
306 /*
307 * Block device functions
308 */
dm_deleting_md(struct mapped_device * md)309 int dm_deleting_md(struct mapped_device *md)
310 {
311 return test_bit(DMF_DELETING, &md->flags);
312 }
313
dm_blk_open(struct gendisk * disk,blk_mode_t mode)314 static int dm_blk_open(struct gendisk *disk, blk_mode_t mode)
315 {
316 struct mapped_device *md;
317
318 spin_lock(&_minor_lock);
319
320 md = disk->private_data;
321 if (!md)
322 goto out;
323
324 if (test_bit(DMF_FREEING, &md->flags) ||
325 dm_deleting_md(md)) {
326 md = NULL;
327 goto out;
328 }
329
330 dm_get(md);
331 atomic_inc(&md->open_count);
332 out:
333 spin_unlock(&_minor_lock);
334
335 return md ? 0 : -ENXIO;
336 }
337
dm_blk_close(struct gendisk * disk)338 static void dm_blk_close(struct gendisk *disk)
339 {
340 struct mapped_device *md;
341
342 spin_lock(&_minor_lock);
343
344 md = disk->private_data;
345 if (WARN_ON(!md))
346 goto out;
347
348 if (atomic_dec_and_test(&md->open_count) &&
349 (test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
350 queue_work(deferred_remove_workqueue, &deferred_remove_work);
351
352 dm_put(md);
353 out:
354 spin_unlock(&_minor_lock);
355 }
356
dm_open_count(struct mapped_device * md)357 int dm_open_count(struct mapped_device *md)
358 {
359 return atomic_read(&md->open_count);
360 }
361
362 /*
363 * Guarantees nothing is using the device before it's deleted.
364 */
dm_lock_for_deletion(struct mapped_device * md,bool mark_deferred,bool only_deferred)365 int dm_lock_for_deletion(struct mapped_device *md, bool mark_deferred, bool only_deferred)
366 {
367 int r = 0;
368
369 spin_lock(&_minor_lock);
370
371 if (dm_open_count(md)) {
372 r = -EBUSY;
373 if (mark_deferred)
374 set_bit(DMF_DEFERRED_REMOVE, &md->flags);
375 } else if (only_deferred && !test_bit(DMF_DEFERRED_REMOVE, &md->flags))
376 r = -EEXIST;
377 else
378 set_bit(DMF_DELETING, &md->flags);
379
380 spin_unlock(&_minor_lock);
381
382 return r;
383 }
384
dm_cancel_deferred_remove(struct mapped_device * md)385 int dm_cancel_deferred_remove(struct mapped_device *md)
386 {
387 int r = 0;
388
389 spin_lock(&_minor_lock);
390
391 if (test_bit(DMF_DELETING, &md->flags))
392 r = -EBUSY;
393 else
394 clear_bit(DMF_DEFERRED_REMOVE, &md->flags);
395
396 spin_unlock(&_minor_lock);
397
398 return r;
399 }
400
do_deferred_remove(struct work_struct * w)401 static void do_deferred_remove(struct work_struct *w)
402 {
403 dm_deferred_remove();
404 }
405
dm_blk_getgeo(struct block_device * bdev,struct hd_geometry * geo)406 static int dm_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
407 {
408 struct mapped_device *md = bdev->bd_disk->private_data;
409
410 return dm_get_geometry(md, geo);
411 }
412
dm_prepare_ioctl(struct mapped_device * md,int * srcu_idx,struct block_device ** bdev,unsigned int cmd,unsigned long arg,bool * forward)413 static int dm_prepare_ioctl(struct mapped_device *md, int *srcu_idx,
414 struct block_device **bdev, unsigned int cmd,
415 unsigned long arg, bool *forward)
416 {
417 struct dm_target *ti;
418 struct dm_table *map;
419 int r;
420
421 retry:
422 r = -ENOTTY;
423 map = dm_get_live_table(md, srcu_idx);
424 if (!map || !dm_table_get_size(map))
425 return r;
426
427 /* We only support devices that have a single target */
428 if (map->num_targets != 1)
429 return r;
430
431 ti = dm_table_get_target(map, 0);
432 if (!ti->type->prepare_ioctl)
433 return r;
434
435 if (dm_suspended_md(md))
436 return -EAGAIN;
437
438 r = ti->type->prepare_ioctl(ti, bdev, cmd, arg, forward);
439 if (r == -ENOTCONN && *forward && !fatal_signal_pending(current)) {
440 dm_put_live_table(md, *srcu_idx);
441 fsleep(10000);
442 goto retry;
443 }
444
445 return r;
446 }
447
dm_unprepare_ioctl(struct mapped_device * md,int srcu_idx)448 static void dm_unprepare_ioctl(struct mapped_device *md, int srcu_idx)
449 {
450 dm_put_live_table(md, srcu_idx);
451 }
452
dm_blk_ioctl(struct block_device * bdev,blk_mode_t mode,unsigned int cmd,unsigned long arg)453 static int dm_blk_ioctl(struct block_device *bdev, blk_mode_t mode,
454 unsigned int cmd, unsigned long arg)
455 {
456 struct mapped_device *md = bdev->bd_disk->private_data;
457 int r, srcu_idx;
458 bool forward = true;
459
460 r = dm_prepare_ioctl(md, &srcu_idx, &bdev, cmd, arg, &forward);
461 if (!forward || r < 0)
462 goto out;
463
464 if (r > 0) {
465 /*
466 * Target determined this ioctl is being issued against a
467 * subset of the parent bdev; require extra privileges.
468 */
469 if (!capable(CAP_SYS_RAWIO)) {
470 DMDEBUG_LIMIT(
471 "%s: sending ioctl %x to DM device without required privilege.",
472 current->comm, cmd);
473 r = -ENOIOCTLCMD;
474 goto out;
475 }
476 }
477
478 if (!bdev->bd_disk->fops->ioctl)
479 r = -ENOTTY;
480 else
481 r = bdev->bd_disk->fops->ioctl(bdev, mode, cmd, arg);
482 out:
483 dm_unprepare_ioctl(md, srcu_idx);
484 return r;
485 }
486
dm_start_time_ns_from_clone(struct bio * bio)487 u64 dm_start_time_ns_from_clone(struct bio *bio)
488 {
489 return jiffies_to_nsecs(clone_to_tio(bio)->io->start_time);
490 }
491 EXPORT_SYMBOL_GPL(dm_start_time_ns_from_clone);
492
bio_is_flush_with_data(struct bio * bio)493 static inline bool bio_is_flush_with_data(struct bio *bio)
494 {
495 return ((bio->bi_opf & REQ_PREFLUSH) && bio->bi_iter.bi_size);
496 }
497
dm_io_sectors(struct dm_io * io,struct bio * bio)498 static inline unsigned int dm_io_sectors(struct dm_io *io, struct bio *bio)
499 {
500 /*
501 * If REQ_PREFLUSH set, don't account payload, it will be
502 * submitted (and accounted) after this flush completes.
503 */
504 if (bio_is_flush_with_data(bio))
505 return 0;
506 if (unlikely(dm_io_flagged(io, DM_IO_WAS_SPLIT)))
507 return io->sectors;
508 return bio_sectors(bio);
509 }
510
dm_io_acct(struct dm_io * io,bool end)511 static void dm_io_acct(struct dm_io *io, bool end)
512 {
513 struct bio *bio = io->orig_bio;
514
515 if (dm_io_flagged(io, DM_IO_BLK_STAT)) {
516 if (!end)
517 bdev_start_io_acct(bio->bi_bdev, bio_op(bio),
518 io->start_time);
519 else
520 bdev_end_io_acct(bio->bi_bdev, bio_op(bio),
521 dm_io_sectors(io, bio),
522 io->start_time);
523 }
524
525 if (static_branch_unlikely(&stats_enabled) &&
526 unlikely(dm_stats_used(&io->md->stats))) {
527 sector_t sector;
528
529 if (unlikely(dm_io_flagged(io, DM_IO_WAS_SPLIT)))
530 sector = bio_end_sector(bio) - io->sector_offset;
531 else
532 sector = bio->bi_iter.bi_sector;
533
534 dm_stats_account_io(&io->md->stats, bio_data_dir(bio),
535 sector, dm_io_sectors(io, bio),
536 end, io->start_time, &io->stats_aux);
537 }
538 }
539
__dm_start_io_acct(struct dm_io * io)540 static void __dm_start_io_acct(struct dm_io *io)
541 {
542 dm_io_acct(io, false);
543 }
544
dm_start_io_acct(struct dm_io * io,struct bio * clone)545 static void dm_start_io_acct(struct dm_io *io, struct bio *clone)
546 {
547 /*
548 * Ensure IO accounting is only ever started once.
549 */
550 if (dm_io_flagged(io, DM_IO_ACCOUNTED))
551 return;
552
553 /* Expect no possibility for race unless DM_TIO_IS_DUPLICATE_BIO. */
554 if (!clone || likely(dm_tio_is_normal(clone_to_tio(clone)))) {
555 dm_io_set_flag(io, DM_IO_ACCOUNTED);
556 } else {
557 unsigned long flags;
558 /* Can afford locking given DM_TIO_IS_DUPLICATE_BIO */
559 spin_lock_irqsave(&io->lock, flags);
560 if (dm_io_flagged(io, DM_IO_ACCOUNTED)) {
561 spin_unlock_irqrestore(&io->lock, flags);
562 return;
563 }
564 dm_io_set_flag(io, DM_IO_ACCOUNTED);
565 spin_unlock_irqrestore(&io->lock, flags);
566 }
567
568 __dm_start_io_acct(io);
569 }
570
dm_end_io_acct(struct dm_io * io)571 static void dm_end_io_acct(struct dm_io *io)
572 {
573 dm_io_acct(io, true);
574 }
575
alloc_io(struct mapped_device * md,struct bio * bio,gfp_t gfp_mask)576 static struct dm_io *alloc_io(struct mapped_device *md, struct bio *bio, gfp_t gfp_mask)
577 {
578 struct dm_io *io;
579 struct dm_target_io *tio;
580 struct bio *clone;
581
582 clone = bio_alloc_clone(NULL, bio, gfp_mask, &md->mempools->io_bs);
583 if (unlikely(!clone))
584 return NULL;
585 tio = clone_to_tio(clone);
586 tio->flags = 0;
587 dm_tio_set_flag(tio, DM_TIO_INSIDE_DM_IO);
588 tio->io = NULL;
589
590 io = container_of(tio, struct dm_io, tio);
591 io->magic = DM_IO_MAGIC;
592 io->status = BLK_STS_OK;
593
594 /* one ref is for submission, the other is for completion */
595 atomic_set(&io->io_count, 2);
596 this_cpu_inc(*md->pending_io);
597 io->orig_bio = bio;
598 io->md = md;
599 spin_lock_init(&io->lock);
600 io->start_time = jiffies;
601 io->flags = 0;
602 if (blk_queue_io_stat(md->queue))
603 dm_io_set_flag(io, DM_IO_BLK_STAT);
604
605 if (static_branch_unlikely(&stats_enabled) &&
606 unlikely(dm_stats_used(&md->stats)))
607 dm_stats_record_start(&md->stats, &io->stats_aux);
608
609 return io;
610 }
611
free_io(struct dm_io * io)612 static void free_io(struct dm_io *io)
613 {
614 bio_put(&io->tio.clone);
615 }
616
alloc_tio(struct clone_info * ci,struct dm_target * ti,unsigned int target_bio_nr,unsigned int * len,gfp_t gfp_mask)617 static struct bio *alloc_tio(struct clone_info *ci, struct dm_target *ti,
618 unsigned int target_bio_nr, unsigned int *len, gfp_t gfp_mask)
619 {
620 struct mapped_device *md = ci->io->md;
621 struct dm_target_io *tio;
622 struct bio *clone;
623
624 if (!ci->io->tio.io) {
625 /* the dm_target_io embedded in ci->io is available */
626 tio = &ci->io->tio;
627 /* alloc_io() already initialized embedded clone */
628 clone = &tio->clone;
629 } else {
630 clone = bio_alloc_clone(NULL, ci->bio, gfp_mask,
631 &md->mempools->bs);
632 if (!clone)
633 return NULL;
634
635 /* REQ_DM_POLL_LIST shouldn't be inherited */
636 clone->bi_opf &= ~REQ_DM_POLL_LIST;
637
638 tio = clone_to_tio(clone);
639 tio->flags = 0; /* also clears DM_TIO_INSIDE_DM_IO */
640 }
641
642 tio->magic = DM_TIO_MAGIC;
643 tio->io = ci->io;
644 tio->ti = ti;
645 tio->target_bio_nr = target_bio_nr;
646 tio->len_ptr = len;
647 tio->old_sector = 0;
648
649 /* Set default bdev, but target must bio_set_dev() before issuing IO */
650 clone->bi_bdev = md->disk->part0;
651 if (likely(ti != NULL) && unlikely(ti->needs_bio_set_dev))
652 bio_set_dev(clone, md->disk->part0);
653
654 if (len) {
655 clone->bi_iter.bi_size = to_bytes(*len);
656 if (bio_integrity(clone))
657 bio_integrity_trim(clone);
658 }
659
660 return clone;
661 }
662
free_tio(struct bio * clone)663 static void free_tio(struct bio *clone)
664 {
665 if (dm_tio_flagged(clone_to_tio(clone), DM_TIO_INSIDE_DM_IO))
666 return;
667 bio_put(clone);
668 }
669
670 /*
671 * Add the bio to the list of deferred io.
672 */
queue_io(struct mapped_device * md,struct bio * bio)673 static void queue_io(struct mapped_device *md, struct bio *bio)
674 {
675 unsigned long flags;
676
677 spin_lock_irqsave(&md->deferred_lock, flags);
678 bio_list_add(&md->deferred, bio);
679 spin_unlock_irqrestore(&md->deferred_lock, flags);
680 queue_work(md->wq, &md->work);
681 }
682
683 /*
684 * Everyone (including functions in this file), should use this
685 * function to access the md->map field, and make sure they call
686 * dm_put_live_table() when finished.
687 */
dm_get_live_table(struct mapped_device * md,int * srcu_idx)688 struct dm_table *dm_get_live_table(struct mapped_device *md,
689 int *srcu_idx) __acquires(md->io_barrier)
690 {
691 *srcu_idx = srcu_read_lock(&md->io_barrier);
692
693 return srcu_dereference(md->map, &md->io_barrier);
694 }
695
dm_put_live_table(struct mapped_device * md,int srcu_idx)696 void dm_put_live_table(struct mapped_device *md,
697 int srcu_idx) __releases(md->io_barrier)
698 {
699 srcu_read_unlock(&md->io_barrier, srcu_idx);
700 }
701
dm_sync_table(struct mapped_device * md)702 void dm_sync_table(struct mapped_device *md)
703 {
704 synchronize_srcu(&md->io_barrier);
705 synchronize_rcu_expedited();
706 }
707
708 /*
709 * A fast alternative to dm_get_live_table/dm_put_live_table.
710 * The caller must not block between these two functions.
711 */
dm_get_live_table_fast(struct mapped_device * md)712 static struct dm_table *dm_get_live_table_fast(struct mapped_device *md) __acquires(RCU)
713 {
714 rcu_read_lock();
715 return rcu_dereference(md->map);
716 }
717
dm_put_live_table_fast(struct mapped_device * md)718 static void dm_put_live_table_fast(struct mapped_device *md) __releases(RCU)
719 {
720 rcu_read_unlock();
721 }
722
723 static char *_dm_claim_ptr = "I belong to device-mapper";
724
725 /*
726 * Open a table device so we can use it as a map destination.
727 */
open_table_device(struct mapped_device * md,dev_t dev,blk_mode_t mode)728 static struct table_device *open_table_device(struct mapped_device *md,
729 dev_t dev, blk_mode_t mode)
730 {
731 struct table_device *td;
732 struct file *bdev_file;
733 struct block_device *bdev;
734 u64 part_off;
735 int r;
736
737 td = kmalloc_node(sizeof(*td), GFP_KERNEL, md->numa_node_id);
738 if (!td)
739 return ERR_PTR(-ENOMEM);
740 refcount_set(&td->count, 1);
741
742 bdev_file = bdev_file_open_by_dev(dev, mode, _dm_claim_ptr, NULL);
743 if (IS_ERR(bdev_file)) {
744 r = PTR_ERR(bdev_file);
745 goto out_free_td;
746 }
747
748 bdev = file_bdev(bdev_file);
749
750 /*
751 * We can be called before the dm disk is added. In that case we can't
752 * register the holder relation here. It will be done once add_disk was
753 * called.
754 */
755 if (md->disk->slave_dir) {
756 r = bd_link_disk_holder(bdev, md->disk);
757 if (r)
758 goto out_blkdev_put;
759 }
760
761 td->dm_dev.mode = mode;
762 td->dm_dev.bdev = bdev;
763 td->dm_dev.bdev_file = bdev_file;
764 td->dm_dev.dax_dev = fs_dax_get_by_bdev(bdev, &part_off,
765 NULL, NULL);
766 format_dev_t(td->dm_dev.name, dev);
767 list_add(&td->list, &md->table_devices);
768 return td;
769
770 out_blkdev_put:
771 __fput_sync(bdev_file);
772 out_free_td:
773 kfree(td);
774 return ERR_PTR(r);
775 }
776
777 /*
778 * Close a table device that we've been using.
779 */
close_table_device(struct table_device * td,struct mapped_device * md)780 static void close_table_device(struct table_device *td, struct mapped_device *md)
781 {
782 if (md->disk->slave_dir)
783 bd_unlink_disk_holder(td->dm_dev.bdev, md->disk);
784
785 /* Leverage async fput() if DMF_DEFERRED_REMOVE set */
786 if (unlikely(test_bit(DMF_DEFERRED_REMOVE, &md->flags)))
787 fput(td->dm_dev.bdev_file);
788 else
789 __fput_sync(td->dm_dev.bdev_file);
790
791 put_dax(td->dm_dev.dax_dev);
792 list_del(&td->list);
793 kfree(td);
794 }
795
find_table_device(struct list_head * l,dev_t dev,blk_mode_t mode)796 static struct table_device *find_table_device(struct list_head *l, dev_t dev,
797 blk_mode_t mode)
798 {
799 struct table_device *td;
800
801 list_for_each_entry(td, l, list)
802 if (td->dm_dev.bdev->bd_dev == dev && td->dm_dev.mode == mode)
803 return td;
804
805 return NULL;
806 }
807
dm_get_table_device(struct mapped_device * md,dev_t dev,blk_mode_t mode,struct dm_dev ** result)808 int dm_get_table_device(struct mapped_device *md, dev_t dev, blk_mode_t mode,
809 struct dm_dev **result)
810 {
811 struct table_device *td;
812
813 mutex_lock(&md->table_devices_lock);
814 td = find_table_device(&md->table_devices, dev, mode);
815 if (!td) {
816 td = open_table_device(md, dev, mode);
817 if (IS_ERR(td)) {
818 mutex_unlock(&md->table_devices_lock);
819 return PTR_ERR(td);
820 }
821 } else {
822 refcount_inc(&td->count);
823 }
824 mutex_unlock(&md->table_devices_lock);
825
826 *result = &td->dm_dev;
827 return 0;
828 }
829
dm_put_table_device(struct mapped_device * md,struct dm_dev * d)830 void dm_put_table_device(struct mapped_device *md, struct dm_dev *d)
831 {
832 struct table_device *td = container_of(d, struct table_device, dm_dev);
833
834 mutex_lock(&md->table_devices_lock);
835 if (refcount_dec_and_test(&td->count))
836 close_table_device(td, md);
837 mutex_unlock(&md->table_devices_lock);
838 }
839
840 /*
841 * Get the geometry associated with a dm device
842 */
dm_get_geometry(struct mapped_device * md,struct hd_geometry * geo)843 int dm_get_geometry(struct mapped_device *md, struct hd_geometry *geo)
844 {
845 *geo = md->geometry;
846
847 return 0;
848 }
849
850 /*
851 * Set the geometry of a device.
852 */
dm_set_geometry(struct mapped_device * md,struct hd_geometry * geo)853 int dm_set_geometry(struct mapped_device *md, struct hd_geometry *geo)
854 {
855 sector_t sz = (sector_t)geo->cylinders * geo->heads * geo->sectors;
856
857 if (geo->start > sz) {
858 DMERR("Start sector is beyond the geometry limits.");
859 return -EINVAL;
860 }
861
862 md->geometry = *geo;
863
864 return 0;
865 }
866
__noflush_suspending(struct mapped_device * md)867 static int __noflush_suspending(struct mapped_device *md)
868 {
869 return test_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
870 }
871
dm_requeue_add_io(struct dm_io * io,bool first_stage)872 static void dm_requeue_add_io(struct dm_io *io, bool first_stage)
873 {
874 struct mapped_device *md = io->md;
875
876 if (first_stage) {
877 struct dm_io *next = md->requeue_list;
878
879 md->requeue_list = io;
880 io->next = next;
881 } else {
882 bio_list_add_head(&md->deferred, io->orig_bio);
883 }
884 }
885
dm_kick_requeue(struct mapped_device * md,bool first_stage)886 static void dm_kick_requeue(struct mapped_device *md, bool first_stage)
887 {
888 if (first_stage)
889 queue_work(md->wq, &md->requeue_work);
890 else
891 queue_work(md->wq, &md->work);
892 }
893
894 /*
895 * Return true if the dm_io's original bio is requeued.
896 * io->status is updated with error if requeue disallowed.
897 */
dm_handle_requeue(struct dm_io * io,bool first_stage)898 static bool dm_handle_requeue(struct dm_io *io, bool first_stage)
899 {
900 struct bio *bio = io->orig_bio;
901 bool handle_requeue = (io->status == BLK_STS_DM_REQUEUE);
902 bool handle_polled_eagain = ((io->status == BLK_STS_AGAIN) &&
903 (bio->bi_opf & REQ_POLLED));
904 struct mapped_device *md = io->md;
905 bool requeued = false;
906
907 if (handle_requeue || handle_polled_eagain) {
908 unsigned long flags;
909
910 if (bio->bi_opf & REQ_POLLED) {
911 /*
912 * Upper layer won't help us poll split bio
913 * (io->orig_bio may only reflect a subset of the
914 * pre-split original) so clear REQ_POLLED.
915 */
916 bio_clear_polled(bio);
917 }
918
919 /*
920 * Target requested pushing back the I/O or
921 * polled IO hit BLK_STS_AGAIN.
922 */
923 spin_lock_irqsave(&md->deferred_lock, flags);
924 if ((__noflush_suspending(md) &&
925 !WARN_ON_ONCE(dm_is_zone_write(md, bio))) ||
926 handle_polled_eagain || first_stage) {
927 dm_requeue_add_io(io, first_stage);
928 requeued = true;
929 } else {
930 /*
931 * noflush suspend was interrupted or this is
932 * a write to a zoned target.
933 */
934 io->status = BLK_STS_IOERR;
935 }
936 spin_unlock_irqrestore(&md->deferred_lock, flags);
937 }
938
939 if (requeued)
940 dm_kick_requeue(md, first_stage);
941
942 return requeued;
943 }
944
__dm_io_complete(struct dm_io * io,bool first_stage)945 static void __dm_io_complete(struct dm_io *io, bool first_stage)
946 {
947 struct bio *bio = io->orig_bio;
948 struct mapped_device *md = io->md;
949 blk_status_t io_error;
950 bool requeued;
951
952 requeued = dm_handle_requeue(io, first_stage);
953 if (requeued && first_stage)
954 return;
955
956 io_error = io->status;
957 if (dm_io_flagged(io, DM_IO_ACCOUNTED))
958 dm_end_io_acct(io);
959 else if (!io_error) {
960 /*
961 * Must handle target that DM_MAPIO_SUBMITTED only to
962 * then bio_endio() rather than dm_submit_bio_remap()
963 */
964 __dm_start_io_acct(io);
965 dm_end_io_acct(io);
966 }
967 free_io(io);
968 smp_wmb();
969 this_cpu_dec(*md->pending_io);
970
971 /* nudge anyone waiting on suspend queue */
972 if (unlikely(wq_has_sleeper(&md->wait)))
973 wake_up(&md->wait);
974
975 /* Return early if the original bio was requeued */
976 if (requeued)
977 return;
978
979 if (bio_is_flush_with_data(bio)) {
980 /*
981 * Preflush done for flush with data, reissue
982 * without REQ_PREFLUSH.
983 */
984 bio->bi_opf &= ~REQ_PREFLUSH;
985 queue_io(md, bio);
986 } else {
987 /* done with normal IO or empty flush */
988 if (io_error)
989 bio->bi_status = io_error;
990 bio_endio(bio);
991 }
992 }
993
dm_wq_requeue_work(struct work_struct * work)994 static void dm_wq_requeue_work(struct work_struct *work)
995 {
996 struct mapped_device *md = container_of(work, struct mapped_device,
997 requeue_work);
998 unsigned long flags;
999 struct dm_io *io;
1000
1001 /* reuse deferred lock to simplify dm_handle_requeue */
1002 spin_lock_irqsave(&md->deferred_lock, flags);
1003 io = md->requeue_list;
1004 md->requeue_list = NULL;
1005 spin_unlock_irqrestore(&md->deferred_lock, flags);
1006
1007 while (io) {
1008 struct dm_io *next = io->next;
1009
1010 dm_io_rewind(io, &md->disk->bio_split);
1011
1012 io->next = NULL;
1013 __dm_io_complete(io, false);
1014 io = next;
1015 cond_resched();
1016 }
1017 }
1018
1019 /*
1020 * Two staged requeue:
1021 *
1022 * 1) io->orig_bio points to the real original bio, and the part mapped to
1023 * this io must be requeued, instead of other parts of the original bio.
1024 *
1025 * 2) io->orig_bio points to new cloned bio which matches the requeued dm_io.
1026 */
dm_io_complete(struct dm_io * io)1027 static inline void dm_io_complete(struct dm_io *io)
1028 {
1029 /*
1030 * Only dm_io that has been split needs two stage requeue, otherwise
1031 * we may run into long bio clone chain during suspend and OOM could
1032 * be triggered.
1033 *
1034 * Also flush data dm_io won't be marked as DM_IO_WAS_SPLIT, so they
1035 * also aren't handled via the first stage requeue.
1036 */
1037 __dm_io_complete(io, dm_io_flagged(io, DM_IO_WAS_SPLIT));
1038 }
1039
1040 /*
1041 * Decrements the number of outstanding ios that a bio has been
1042 * cloned into, completing the original io if necc.
1043 */
__dm_io_dec_pending(struct dm_io * io)1044 static inline void __dm_io_dec_pending(struct dm_io *io)
1045 {
1046 if (atomic_dec_and_test(&io->io_count))
1047 dm_io_complete(io);
1048 }
1049
dm_io_set_error(struct dm_io * io,blk_status_t error)1050 static void dm_io_set_error(struct dm_io *io, blk_status_t error)
1051 {
1052 unsigned long flags;
1053
1054 /* Push-back supersedes any I/O errors */
1055 spin_lock_irqsave(&io->lock, flags);
1056 if (!(io->status == BLK_STS_DM_REQUEUE &&
1057 __noflush_suspending(io->md))) {
1058 io->status = error;
1059 }
1060 spin_unlock_irqrestore(&io->lock, flags);
1061 }
1062
dm_io_dec_pending(struct dm_io * io,blk_status_t error)1063 static void dm_io_dec_pending(struct dm_io *io, blk_status_t error)
1064 {
1065 if (unlikely(error))
1066 dm_io_set_error(io, error);
1067
1068 __dm_io_dec_pending(io);
1069 }
1070
1071 /*
1072 * The queue_limits are only valid as long as you have a reference
1073 * count on 'md'. But _not_ imposing verification to avoid atomic_read(),
1074 */
dm_get_queue_limits(struct mapped_device * md)1075 static inline struct queue_limits *dm_get_queue_limits(struct mapped_device *md)
1076 {
1077 return &md->queue->limits;
1078 }
1079
swap_bios_limit(struct dm_target * ti,struct bio * bio)1080 static bool swap_bios_limit(struct dm_target *ti, struct bio *bio)
1081 {
1082 return unlikely((bio->bi_opf & REQ_SWAP) != 0) && unlikely(ti->limit_swap_bios);
1083 }
1084
clone_endio(struct bio * bio)1085 static void clone_endio(struct bio *bio)
1086 {
1087 blk_status_t error = bio->bi_status;
1088 struct dm_target_io *tio = clone_to_tio(bio);
1089 struct dm_target *ti = tio->ti;
1090 dm_endio_fn endio = likely(ti != NULL) ? ti->type->end_io : NULL;
1091 struct dm_io *io = tio->io;
1092 struct mapped_device *md = io->md;
1093
1094 if (unlikely(error == BLK_STS_TARGET)) {
1095 if (bio_op(bio) == REQ_OP_DISCARD &&
1096 !bdev_max_discard_sectors(bio->bi_bdev))
1097 blk_queue_disable_discard(md->queue);
1098 else if (bio_op(bio) == REQ_OP_WRITE_ZEROES &&
1099 !bdev_write_zeroes_sectors(bio->bi_bdev))
1100 blk_queue_disable_write_zeroes(md->queue);
1101 }
1102
1103 if (static_branch_unlikely(&zoned_enabled) &&
1104 unlikely(bdev_is_zoned(bio->bi_bdev)))
1105 dm_zone_endio(io, bio);
1106
1107 if (endio) {
1108 int r = endio(ti, bio, &error);
1109
1110 switch (r) {
1111 case DM_ENDIO_REQUEUE:
1112 if (static_branch_unlikely(&zoned_enabled)) {
1113 /*
1114 * Requeuing writes to a sequential zone of a zoned
1115 * target will break the sequential write pattern:
1116 * fail such IO.
1117 */
1118 if (WARN_ON_ONCE(dm_is_zone_write(md, bio)))
1119 error = BLK_STS_IOERR;
1120 else
1121 error = BLK_STS_DM_REQUEUE;
1122 } else
1123 error = BLK_STS_DM_REQUEUE;
1124 fallthrough;
1125 case DM_ENDIO_DONE:
1126 break;
1127 case DM_ENDIO_INCOMPLETE:
1128 /* The target will handle the io */
1129 return;
1130 default:
1131 DMCRIT("unimplemented target endio return value: %d", r);
1132 BUG();
1133 }
1134 }
1135
1136 if (static_branch_unlikely(&swap_bios_enabled) &&
1137 likely(ti != NULL) && unlikely(swap_bios_limit(ti, bio)))
1138 up(&md->swap_bios_semaphore);
1139
1140 free_tio(bio);
1141 dm_io_dec_pending(io, error);
1142 }
1143
1144 /*
1145 * Return maximum size of I/O possible at the supplied sector up to the current
1146 * target boundary.
1147 */
max_io_len_target_boundary(struct dm_target * ti,sector_t target_offset)1148 static inline sector_t max_io_len_target_boundary(struct dm_target *ti,
1149 sector_t target_offset)
1150 {
1151 return ti->len - target_offset;
1152 }
1153
__max_io_len(struct dm_target * ti,sector_t sector,unsigned int max_granularity,unsigned int max_sectors)1154 static sector_t __max_io_len(struct dm_target *ti, sector_t sector,
1155 unsigned int max_granularity,
1156 unsigned int max_sectors)
1157 {
1158 sector_t target_offset = dm_target_offset(ti, sector);
1159 sector_t len = max_io_len_target_boundary(ti, target_offset);
1160
1161 /*
1162 * Does the target need to split IO even further?
1163 * - varied (per target) IO splitting is a tenet of DM; this
1164 * explains why stacked chunk_sectors based splitting via
1165 * bio_split_to_limits() isn't possible here.
1166 */
1167 if (!max_granularity)
1168 return len;
1169 return min_t(sector_t, len,
1170 min(max_sectors ? : queue_max_sectors(ti->table->md->queue),
1171 blk_boundary_sectors_left(target_offset, max_granularity)));
1172 }
1173
max_io_len(struct dm_target * ti,sector_t sector)1174 static inline sector_t max_io_len(struct dm_target *ti, sector_t sector)
1175 {
1176 return __max_io_len(ti, sector, ti->max_io_len, 0);
1177 }
1178
dm_set_target_max_io_len(struct dm_target * ti,sector_t len)1179 int dm_set_target_max_io_len(struct dm_target *ti, sector_t len)
1180 {
1181 if (len > UINT_MAX) {
1182 DMERR("Specified maximum size of target IO (%llu) exceeds limit (%u)",
1183 (unsigned long long)len, UINT_MAX);
1184 ti->error = "Maximum size of target IO is too large";
1185 return -EINVAL;
1186 }
1187
1188 ti->max_io_len = (uint32_t) len;
1189
1190 return 0;
1191 }
1192 EXPORT_SYMBOL_GPL(dm_set_target_max_io_len);
1193
dm_dax_get_live_target(struct mapped_device * md,sector_t sector,int * srcu_idx)1194 static struct dm_target *dm_dax_get_live_target(struct mapped_device *md,
1195 sector_t sector, int *srcu_idx)
1196 __acquires(md->io_barrier)
1197 {
1198 struct dm_table *map;
1199 struct dm_target *ti;
1200
1201 map = dm_get_live_table(md, srcu_idx);
1202 if (!map)
1203 return NULL;
1204
1205 ti = dm_table_find_target(map, sector);
1206 if (!ti)
1207 return NULL;
1208
1209 return ti;
1210 }
1211
dm_dax_direct_access(struct dax_device * dax_dev,pgoff_t pgoff,long nr_pages,enum dax_access_mode mode,void ** kaddr,unsigned long * pfn)1212 static long dm_dax_direct_access(struct dax_device *dax_dev, pgoff_t pgoff,
1213 long nr_pages, enum dax_access_mode mode, void **kaddr,
1214 unsigned long *pfn)
1215 {
1216 struct mapped_device *md = dax_get_private(dax_dev);
1217 sector_t sector = pgoff * PAGE_SECTORS;
1218 struct dm_target *ti;
1219 long len, ret = -EIO;
1220 int srcu_idx;
1221
1222 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1223
1224 if (!ti)
1225 goto out;
1226 if (!ti->type->direct_access)
1227 goto out;
1228 len = max_io_len(ti, sector) / PAGE_SECTORS;
1229 if (len < 1)
1230 goto out;
1231 nr_pages = min(len, nr_pages);
1232 ret = ti->type->direct_access(ti, pgoff, nr_pages, mode, kaddr, pfn);
1233
1234 out:
1235 dm_put_live_table(md, srcu_idx);
1236
1237 return ret;
1238 }
1239
dm_dax_zero_page_range(struct dax_device * dax_dev,pgoff_t pgoff,size_t nr_pages)1240 static int dm_dax_zero_page_range(struct dax_device *dax_dev, pgoff_t pgoff,
1241 size_t nr_pages)
1242 {
1243 struct mapped_device *md = dax_get_private(dax_dev);
1244 sector_t sector = pgoff * PAGE_SECTORS;
1245 struct dm_target *ti;
1246 int ret = -EIO;
1247 int srcu_idx;
1248
1249 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1250
1251 if (!ti)
1252 goto out;
1253 if (WARN_ON(!ti->type->dax_zero_page_range)) {
1254 /*
1255 * ->zero_page_range() is mandatory dax operation. If we are
1256 * here, something is wrong.
1257 */
1258 goto out;
1259 }
1260 ret = ti->type->dax_zero_page_range(ti, pgoff, nr_pages);
1261 out:
1262 dm_put_live_table(md, srcu_idx);
1263
1264 return ret;
1265 }
1266
dm_dax_recovery_write(struct dax_device * dax_dev,pgoff_t pgoff,void * addr,size_t bytes,struct iov_iter * i)1267 static size_t dm_dax_recovery_write(struct dax_device *dax_dev, pgoff_t pgoff,
1268 void *addr, size_t bytes, struct iov_iter *i)
1269 {
1270 struct mapped_device *md = dax_get_private(dax_dev);
1271 sector_t sector = pgoff * PAGE_SECTORS;
1272 struct dm_target *ti;
1273 int srcu_idx;
1274 long ret = 0;
1275
1276 ti = dm_dax_get_live_target(md, sector, &srcu_idx);
1277 if (!ti || !ti->type->dax_recovery_write)
1278 goto out;
1279
1280 ret = ti->type->dax_recovery_write(ti, pgoff, addr, bytes, i);
1281 out:
1282 dm_put_live_table(md, srcu_idx);
1283 return ret;
1284 }
1285
1286 /*
1287 * A target may call dm_accept_partial_bio only from the map routine. It is
1288 * allowed for all bio types except REQ_PREFLUSH, REQ_OP_ZONE_* zone management
1289 * operations, zone append writes (native with REQ_OP_ZONE_APPEND or emulated
1290 * with write BIOs flagged with BIO_EMULATES_ZONE_APPEND) and any bio serviced
1291 * by __send_duplicate_bios().
1292 *
1293 * dm_accept_partial_bio informs the dm that the target only wants to process
1294 * additional n_sectors sectors of the bio and the rest of the data should be
1295 * sent in a next bio.
1296 *
1297 * A diagram that explains the arithmetics:
1298 * +--------------------+---------------+-------+
1299 * | 1 | 2 | 3 |
1300 * +--------------------+---------------+-------+
1301 *
1302 * <-------------- *tio->len_ptr --------------->
1303 * <----- bio_sectors ----->
1304 * <-- n_sectors -->
1305 *
1306 * Region 1 was already iterated over with bio_advance or similar function.
1307 * (it may be empty if the target doesn't use bio_advance)
1308 * Region 2 is the remaining bio size that the target wants to process.
1309 * (it may be empty if region 1 is non-empty, although there is no reason
1310 * to make it empty)
1311 * The target requires that region 3 is to be sent in the next bio.
1312 *
1313 * If the target wants to receive multiple copies of the bio (via num_*bios, etc),
1314 * the partially processed part (the sum of regions 1+2) must be the same for all
1315 * copies of the bio.
1316 */
dm_accept_partial_bio(struct bio * bio,unsigned int n_sectors)1317 void dm_accept_partial_bio(struct bio *bio, unsigned int n_sectors)
1318 {
1319 struct dm_target_io *tio = clone_to_tio(bio);
1320 struct dm_io *io = tio->io;
1321 unsigned int bio_sectors = bio_sectors(bio);
1322
1323 BUG_ON(dm_tio_flagged(tio, DM_TIO_IS_DUPLICATE_BIO));
1324 BUG_ON(bio_sectors > *tio->len_ptr);
1325 BUG_ON(n_sectors > bio_sectors);
1326
1327 if (static_branch_unlikely(&zoned_enabled) &&
1328 unlikely(bdev_is_zoned(bio->bi_bdev))) {
1329 enum req_op op = bio_op(bio);
1330
1331 BUG_ON(op_is_zone_mgmt(op));
1332 BUG_ON(op == REQ_OP_WRITE);
1333 BUG_ON(op == REQ_OP_WRITE_ZEROES);
1334 BUG_ON(op == REQ_OP_ZONE_APPEND);
1335 }
1336
1337 *tio->len_ptr -= bio_sectors - n_sectors;
1338 bio->bi_iter.bi_size = n_sectors << SECTOR_SHIFT;
1339
1340 /*
1341 * __split_and_process_bio() may have already saved mapped part
1342 * for accounting but it is being reduced so update accordingly.
1343 */
1344 dm_io_set_flag(io, DM_IO_WAS_SPLIT);
1345 io->sectors = n_sectors;
1346 io->sector_offset = bio_sectors(io->orig_bio);
1347 }
1348 EXPORT_SYMBOL_GPL(dm_accept_partial_bio);
1349
1350 /*
1351 * @clone: clone bio that DM core passed to target's .map function
1352 * @tgt_clone: clone of @clone bio that target needs submitted
1353 *
1354 * Targets should use this interface to submit bios they take
1355 * ownership of when returning DM_MAPIO_SUBMITTED.
1356 *
1357 * Target should also enable ti->accounts_remapped_io
1358 */
dm_submit_bio_remap(struct bio * clone,struct bio * tgt_clone)1359 void dm_submit_bio_remap(struct bio *clone, struct bio *tgt_clone)
1360 {
1361 struct dm_target_io *tio = clone_to_tio(clone);
1362 struct dm_io *io = tio->io;
1363
1364 /* establish bio that will get submitted */
1365 if (!tgt_clone)
1366 tgt_clone = clone;
1367
1368 /*
1369 * Account io->origin_bio to DM dev on behalf of target
1370 * that took ownership of IO with DM_MAPIO_SUBMITTED.
1371 */
1372 dm_start_io_acct(io, clone);
1373
1374 trace_block_bio_remap(tgt_clone, disk_devt(io->md->disk),
1375 tio->old_sector);
1376 submit_bio_noacct(tgt_clone);
1377 }
1378 EXPORT_SYMBOL_GPL(dm_submit_bio_remap);
1379
__set_swap_bios_limit(struct mapped_device * md,int latch)1380 static noinline void __set_swap_bios_limit(struct mapped_device *md, int latch)
1381 {
1382 mutex_lock(&md->swap_bios_lock);
1383 while (latch < md->swap_bios) {
1384 cond_resched();
1385 down(&md->swap_bios_semaphore);
1386 md->swap_bios--;
1387 }
1388 while (latch > md->swap_bios) {
1389 cond_resched();
1390 up(&md->swap_bios_semaphore);
1391 md->swap_bios++;
1392 }
1393 mutex_unlock(&md->swap_bios_lock);
1394 }
1395
__map_bio(struct bio * clone)1396 static void __map_bio(struct bio *clone)
1397 {
1398 struct dm_target_io *tio = clone_to_tio(clone);
1399 struct dm_target *ti = tio->ti;
1400 struct dm_io *io = tio->io;
1401 struct mapped_device *md = io->md;
1402 int r;
1403
1404 clone->bi_end_io = clone_endio;
1405
1406 /*
1407 * Map the clone.
1408 */
1409 tio->old_sector = clone->bi_iter.bi_sector;
1410
1411 if (static_branch_unlikely(&swap_bios_enabled) &&
1412 unlikely(swap_bios_limit(ti, clone))) {
1413 int latch = get_swap_bios();
1414
1415 if (unlikely(latch != md->swap_bios))
1416 __set_swap_bios_limit(md, latch);
1417 down(&md->swap_bios_semaphore);
1418 }
1419
1420 if (likely(ti->type->map == linear_map))
1421 r = linear_map(ti, clone);
1422 else if (ti->type->map == stripe_map)
1423 r = stripe_map(ti, clone);
1424 else
1425 r = ti->type->map(ti, clone);
1426
1427 switch (r) {
1428 case DM_MAPIO_SUBMITTED:
1429 /* target has assumed ownership of this io */
1430 if (!ti->accounts_remapped_io)
1431 dm_start_io_acct(io, clone);
1432 break;
1433 case DM_MAPIO_REMAPPED:
1434 dm_submit_bio_remap(clone, NULL);
1435 break;
1436 case DM_MAPIO_KILL:
1437 case DM_MAPIO_REQUEUE:
1438 if (static_branch_unlikely(&swap_bios_enabled) &&
1439 unlikely(swap_bios_limit(ti, clone)))
1440 up(&md->swap_bios_semaphore);
1441 free_tio(clone);
1442 if (r == DM_MAPIO_KILL)
1443 dm_io_dec_pending(io, BLK_STS_IOERR);
1444 else
1445 dm_io_dec_pending(io, BLK_STS_DM_REQUEUE);
1446 break;
1447 default:
1448 DMCRIT("unimplemented target map return value: %d", r);
1449 BUG();
1450 }
1451 }
1452
setup_split_accounting(struct clone_info * ci,unsigned int len)1453 static void setup_split_accounting(struct clone_info *ci, unsigned int len)
1454 {
1455 struct dm_io *io = ci->io;
1456
1457 if (ci->sector_count > len) {
1458 /*
1459 * Split needed, save the mapped part for accounting.
1460 * NOTE: dm_accept_partial_bio() will update accordingly.
1461 */
1462 dm_io_set_flag(io, DM_IO_WAS_SPLIT);
1463 io->sectors = len;
1464 io->sector_offset = bio_sectors(ci->bio);
1465 }
1466 }
1467
alloc_multiple_bios(struct bio_list * blist,struct clone_info * ci,struct dm_target * ti,unsigned int num_bios,unsigned * len)1468 static void alloc_multiple_bios(struct bio_list *blist, struct clone_info *ci,
1469 struct dm_target *ti, unsigned int num_bios,
1470 unsigned *len)
1471 {
1472 struct bio *bio;
1473 int try;
1474
1475 for (try = 0; try < 2; try++) {
1476 int bio_nr;
1477
1478 if (try && num_bios > 1)
1479 mutex_lock(&ci->io->md->table_devices_lock);
1480 for (bio_nr = 0; bio_nr < num_bios; bio_nr++) {
1481 bio = alloc_tio(ci, ti, bio_nr, len,
1482 try ? GFP_NOIO : GFP_NOWAIT);
1483 if (!bio)
1484 break;
1485
1486 bio_list_add(blist, bio);
1487 }
1488 if (try && num_bios > 1)
1489 mutex_unlock(&ci->io->md->table_devices_lock);
1490 if (bio_nr == num_bios)
1491 return;
1492
1493 while ((bio = bio_list_pop(blist)))
1494 free_tio(bio);
1495 }
1496 }
1497
__send_duplicate_bios(struct clone_info * ci,struct dm_target * ti,unsigned int num_bios,unsigned int * len)1498 static unsigned int __send_duplicate_bios(struct clone_info *ci, struct dm_target *ti,
1499 unsigned int num_bios, unsigned int *len)
1500 {
1501 struct bio_list blist = BIO_EMPTY_LIST;
1502 struct bio *clone;
1503 unsigned int ret = 0;
1504
1505 if (WARN_ON_ONCE(num_bios == 0)) /* num_bios = 0 is a bug in caller */
1506 return 0;
1507
1508 /* dm_accept_partial_bio() is not supported with shared tio->len_ptr */
1509 if (len)
1510 setup_split_accounting(ci, *len);
1511
1512 /*
1513 * Using alloc_multiple_bios(), even if num_bios is 1, to consistently
1514 * support allocating using GFP_NOWAIT with GFP_NOIO fallback.
1515 */
1516 alloc_multiple_bios(&blist, ci, ti, num_bios, len);
1517 while ((clone = bio_list_pop(&blist))) {
1518 if (num_bios > 1)
1519 dm_tio_set_flag(clone_to_tio(clone), DM_TIO_IS_DUPLICATE_BIO);
1520 __map_bio(clone);
1521 ret += 1;
1522 }
1523
1524 return ret;
1525 }
1526
__send_empty_flush(struct clone_info * ci)1527 static void __send_empty_flush(struct clone_info *ci)
1528 {
1529 struct dm_table *t = ci->map;
1530 struct bio flush_bio;
1531 blk_opf_t opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC;
1532
1533 if ((ci->io->orig_bio->bi_opf & (REQ_IDLE | REQ_SYNC)) ==
1534 (REQ_IDLE | REQ_SYNC))
1535 opf |= REQ_IDLE;
1536
1537 /*
1538 * Use an on-stack bio for this, it's safe since we don't
1539 * need to reference it after submit. It's just used as
1540 * the basis for the clone(s).
1541 */
1542 bio_init(&flush_bio, ci->io->md->disk->part0, NULL, 0, opf);
1543
1544 ci->bio = &flush_bio;
1545 ci->sector_count = 0;
1546 ci->io->tio.clone.bi_iter.bi_size = 0;
1547
1548 if (!t->flush_bypasses_map) {
1549 for (unsigned int i = 0; i < t->num_targets; i++) {
1550 unsigned int bios;
1551 struct dm_target *ti = dm_table_get_target(t, i);
1552
1553 if (unlikely(ti->num_flush_bios == 0))
1554 continue;
1555
1556 atomic_add(ti->num_flush_bios, &ci->io->io_count);
1557 bios = __send_duplicate_bios(ci, ti, ti->num_flush_bios,
1558 NULL);
1559 atomic_sub(ti->num_flush_bios - bios, &ci->io->io_count);
1560 }
1561 } else {
1562 /*
1563 * Note that there's no need to grab t->devices_lock here
1564 * because the targets that support flush optimization don't
1565 * modify the list of devices.
1566 */
1567 struct list_head *devices = dm_table_get_devices(t);
1568 unsigned int len = 0;
1569 struct dm_dev_internal *dd;
1570 list_for_each_entry(dd, devices, list) {
1571 struct bio *clone;
1572 /*
1573 * Note that the structure dm_target_io is not
1574 * associated with any target (because the device may be
1575 * used by multiple targets), so we set tio->ti = NULL.
1576 * We must check for NULL in the I/O processing path, to
1577 * avoid NULL pointer dereference.
1578 */
1579 clone = alloc_tio(ci, NULL, 0, &len, GFP_NOIO);
1580 atomic_add(1, &ci->io->io_count);
1581 bio_set_dev(clone, dd->dm_dev->bdev);
1582 clone->bi_end_io = clone_endio;
1583 dm_submit_bio_remap(clone, NULL);
1584 }
1585 }
1586
1587 /*
1588 * alloc_io() takes one extra reference for submission, so the
1589 * reference won't reach 0 without the following subtraction
1590 */
1591 atomic_sub(1, &ci->io->io_count);
1592
1593 bio_uninit(ci->bio);
1594 }
1595
__send_abnormal_io(struct clone_info * ci,struct dm_target * ti,unsigned int num_bios,unsigned int max_granularity,unsigned int max_sectors)1596 static void __send_abnormal_io(struct clone_info *ci, struct dm_target *ti,
1597 unsigned int num_bios, unsigned int max_granularity,
1598 unsigned int max_sectors)
1599 {
1600 unsigned int len, bios;
1601
1602 len = min_t(sector_t, ci->sector_count,
1603 __max_io_len(ti, ci->sector, max_granularity, max_sectors));
1604
1605 atomic_add(num_bios, &ci->io->io_count);
1606 bios = __send_duplicate_bios(ci, ti, num_bios, &len);
1607 /*
1608 * alloc_io() takes one extra reference for submission, so the
1609 * reference won't reach 0 without the following (+1) subtraction
1610 */
1611 atomic_sub(num_bios - bios + 1, &ci->io->io_count);
1612
1613 ci->sector += len;
1614 ci->sector_count -= len;
1615 }
1616
is_abnormal_io(struct bio * bio)1617 static bool is_abnormal_io(struct bio *bio)
1618 {
1619 switch (bio_op(bio)) {
1620 case REQ_OP_READ:
1621 case REQ_OP_WRITE:
1622 case REQ_OP_FLUSH:
1623 return false;
1624 case REQ_OP_DISCARD:
1625 case REQ_OP_SECURE_ERASE:
1626 case REQ_OP_WRITE_ZEROES:
1627 case REQ_OP_ZONE_RESET_ALL:
1628 return true;
1629 default:
1630 return false;
1631 }
1632 }
1633
__process_abnormal_io(struct clone_info * ci,struct dm_target * ti)1634 static blk_status_t __process_abnormal_io(struct clone_info *ci,
1635 struct dm_target *ti)
1636 {
1637 unsigned int num_bios = 0;
1638 unsigned int max_granularity = 0;
1639 unsigned int max_sectors = 0;
1640 struct queue_limits *limits = dm_get_queue_limits(ti->table->md);
1641
1642 switch (bio_op(ci->bio)) {
1643 case REQ_OP_DISCARD:
1644 num_bios = ti->num_discard_bios;
1645 max_sectors = limits->max_discard_sectors;
1646 if (ti->max_discard_granularity)
1647 max_granularity = max_sectors;
1648 break;
1649 case REQ_OP_SECURE_ERASE:
1650 num_bios = ti->num_secure_erase_bios;
1651 max_sectors = limits->max_secure_erase_sectors;
1652 break;
1653 case REQ_OP_WRITE_ZEROES:
1654 num_bios = ti->num_write_zeroes_bios;
1655 max_sectors = limits->max_write_zeroes_sectors;
1656 break;
1657 default:
1658 break;
1659 }
1660
1661 /*
1662 * Even though the device advertised support for this type of
1663 * request, that does not mean every target supports it, and
1664 * reconfiguration might also have changed that since the
1665 * check was performed.
1666 */
1667 if (unlikely(!num_bios))
1668 return BLK_STS_NOTSUPP;
1669
1670 __send_abnormal_io(ci, ti, num_bios, max_granularity, max_sectors);
1671
1672 return BLK_STS_OK;
1673 }
1674
1675 /*
1676 * Reuse ->bi_private as dm_io list head for storing all dm_io instances
1677 * associated with this bio, and this bio's bi_private needs to be
1678 * stored in dm_io->data before the reuse.
1679 *
1680 * bio->bi_private is owned by fs or upper layer, so block layer won't
1681 * touch it after splitting. Meantime it won't be changed by anyone after
1682 * bio is submitted. So this reuse is safe.
1683 */
dm_poll_list_head(struct bio * bio)1684 static inline struct dm_io **dm_poll_list_head(struct bio *bio)
1685 {
1686 return (struct dm_io **)&bio->bi_private;
1687 }
1688
dm_queue_poll_io(struct bio * bio,struct dm_io * io)1689 static void dm_queue_poll_io(struct bio *bio, struct dm_io *io)
1690 {
1691 struct dm_io **head = dm_poll_list_head(bio);
1692
1693 if (!(bio->bi_opf & REQ_DM_POLL_LIST)) {
1694 bio->bi_opf |= REQ_DM_POLL_LIST;
1695 /*
1696 * Save .bi_private into dm_io, so that we can reuse
1697 * .bi_private as dm_io list head for storing dm_io list
1698 */
1699 io->data = bio->bi_private;
1700
1701 /* tell block layer to poll for completion */
1702 bio->bi_cookie = ~BLK_QC_T_NONE;
1703
1704 io->next = NULL;
1705 } else {
1706 /*
1707 * bio recursed due to split, reuse original poll list,
1708 * and save bio->bi_private too.
1709 */
1710 io->data = (*head)->data;
1711 io->next = *head;
1712 }
1713
1714 *head = io;
1715 }
1716
1717 /*
1718 * Select the correct strategy for processing a non-flush bio.
1719 */
__split_and_process_bio(struct clone_info * ci)1720 static blk_status_t __split_and_process_bio(struct clone_info *ci)
1721 {
1722 struct bio *clone;
1723 struct dm_target *ti;
1724 unsigned int len;
1725
1726 ti = dm_table_find_target(ci->map, ci->sector);
1727 if (unlikely(!ti))
1728 return BLK_STS_IOERR;
1729
1730 if (unlikely(ci->is_abnormal_io))
1731 return __process_abnormal_io(ci, ti);
1732
1733 /*
1734 * Only support bio polling for normal IO, and the target io is
1735 * exactly inside the dm_io instance (verified in dm_poll_dm_io)
1736 */
1737 ci->submit_as_polled = !!(ci->bio->bi_opf & REQ_POLLED);
1738
1739 len = min_t(sector_t, max_io_len(ti, ci->sector), ci->sector_count);
1740 if (ci->bio->bi_opf & REQ_ATOMIC && len != ci->sector_count)
1741 return BLK_STS_IOERR;
1742
1743 setup_split_accounting(ci, len);
1744
1745 if (unlikely(ci->bio->bi_opf & REQ_NOWAIT)) {
1746 if (unlikely(!dm_target_supports_nowait(ti->type)))
1747 return BLK_STS_NOTSUPP;
1748
1749 clone = alloc_tio(ci, ti, 0, &len, GFP_NOWAIT);
1750 if (unlikely(!clone))
1751 return BLK_STS_AGAIN;
1752 } else {
1753 clone = alloc_tio(ci, ti, 0, &len, GFP_NOIO);
1754 }
1755 __map_bio(clone);
1756
1757 ci->sector += len;
1758 ci->sector_count -= len;
1759
1760 return BLK_STS_OK;
1761 }
1762
init_clone_info(struct clone_info * ci,struct dm_io * io,struct dm_table * map,struct bio * bio,bool is_abnormal)1763 static void init_clone_info(struct clone_info *ci, struct dm_io *io,
1764 struct dm_table *map, struct bio *bio, bool is_abnormal)
1765 {
1766 ci->map = map;
1767 ci->io = io;
1768 ci->bio = bio;
1769 ci->is_abnormal_io = is_abnormal;
1770 ci->submit_as_polled = false;
1771 ci->sector = bio->bi_iter.bi_sector;
1772 ci->sector_count = bio_sectors(bio);
1773
1774 /* Shouldn't happen but sector_count was being set to 0 so... */
1775 if (static_branch_unlikely(&zoned_enabled) &&
1776 WARN_ON_ONCE(op_is_zone_mgmt(bio_op(bio)) && ci->sector_count))
1777 ci->sector_count = 0;
1778 }
1779
1780 #ifdef CONFIG_BLK_DEV_ZONED
dm_zone_bio_needs_split(struct bio * bio)1781 static inline bool dm_zone_bio_needs_split(struct bio *bio)
1782 {
1783 /*
1784 * Special case the zone operations that cannot or should not be split.
1785 */
1786 switch (bio_op(bio)) {
1787 case REQ_OP_ZONE_APPEND:
1788 case REQ_OP_ZONE_FINISH:
1789 case REQ_OP_ZONE_RESET:
1790 case REQ_OP_ZONE_RESET_ALL:
1791 return false;
1792 default:
1793 break;
1794 }
1795
1796 /*
1797 * When mapped devices use the block layer zone write plugging, we must
1798 * split any large BIO to the mapped device limits to not submit BIOs
1799 * that span zone boundaries and to avoid potential deadlocks with
1800 * queue freeze operations.
1801 */
1802 return bio_needs_zone_write_plugging(bio) || bio_straddles_zones(bio);
1803 }
1804
dm_zone_plug_bio(struct mapped_device * md,struct bio * bio)1805 static inline bool dm_zone_plug_bio(struct mapped_device *md, struct bio *bio)
1806 {
1807 if (!bio_needs_zone_write_plugging(bio))
1808 return false;
1809 return blk_zone_plug_bio(bio, 0);
1810 }
1811
__send_zone_reset_all_emulated(struct clone_info * ci,struct dm_target * ti)1812 static blk_status_t __send_zone_reset_all_emulated(struct clone_info *ci,
1813 struct dm_target *ti)
1814 {
1815 struct bio_list blist = BIO_EMPTY_LIST;
1816 struct mapped_device *md = ci->io->md;
1817 unsigned int zone_sectors = md->disk->queue->limits.chunk_sectors;
1818 unsigned long *need_reset;
1819 unsigned int i, nr_zones, nr_reset;
1820 unsigned int num_bios = 0;
1821 blk_status_t sts = BLK_STS_OK;
1822 sector_t sector = ti->begin;
1823 struct bio *clone;
1824 int ret;
1825
1826 nr_zones = ti->len >> ilog2(zone_sectors);
1827 need_reset = bitmap_zalloc(nr_zones, GFP_NOIO);
1828 if (!need_reset)
1829 return BLK_STS_RESOURCE;
1830
1831 ret = dm_zone_get_reset_bitmap(md, ci->map, ti->begin,
1832 nr_zones, need_reset);
1833 if (ret) {
1834 sts = BLK_STS_IOERR;
1835 goto free_bitmap;
1836 }
1837
1838 /* If we have no zone to reset, we are done. */
1839 nr_reset = bitmap_weight(need_reset, nr_zones);
1840 if (!nr_reset)
1841 goto free_bitmap;
1842
1843 atomic_add(nr_zones, &ci->io->io_count);
1844
1845 for (i = 0; i < nr_zones; i++) {
1846
1847 if (!test_bit(i, need_reset)) {
1848 sector += zone_sectors;
1849 continue;
1850 }
1851
1852 if (bio_list_empty(&blist)) {
1853 /* This may take a while, so be nice to others */
1854 if (num_bios)
1855 cond_resched();
1856
1857 /*
1858 * We may need to reset thousands of zones, so let's
1859 * not go crazy with the clone allocation.
1860 */
1861 alloc_multiple_bios(&blist, ci, ti, min(nr_reset, 32),
1862 NULL);
1863 }
1864
1865 /* Get a clone and change it to a regular reset operation. */
1866 clone = bio_list_pop(&blist);
1867 clone->bi_opf &= ~REQ_OP_MASK;
1868 clone->bi_opf |= REQ_OP_ZONE_RESET | REQ_SYNC;
1869 clone->bi_iter.bi_sector = sector;
1870 clone->bi_iter.bi_size = 0;
1871 __map_bio(clone);
1872
1873 sector += zone_sectors;
1874 num_bios++;
1875 nr_reset--;
1876 }
1877
1878 WARN_ON_ONCE(!bio_list_empty(&blist));
1879 atomic_sub(nr_zones - num_bios, &ci->io->io_count);
1880 ci->sector_count = 0;
1881
1882 free_bitmap:
1883 bitmap_free(need_reset);
1884
1885 return sts;
1886 }
1887
__send_zone_reset_all_native(struct clone_info * ci,struct dm_target * ti)1888 static void __send_zone_reset_all_native(struct clone_info *ci,
1889 struct dm_target *ti)
1890 {
1891 unsigned int bios;
1892
1893 atomic_add(1, &ci->io->io_count);
1894 bios = __send_duplicate_bios(ci, ti, 1, NULL);
1895 atomic_sub(1 - bios, &ci->io->io_count);
1896
1897 ci->sector_count = 0;
1898 }
1899
__send_zone_reset_all(struct clone_info * ci)1900 static blk_status_t __send_zone_reset_all(struct clone_info *ci)
1901 {
1902 struct dm_table *t = ci->map;
1903 blk_status_t sts = BLK_STS_OK;
1904
1905 for (unsigned int i = 0; i < t->num_targets; i++) {
1906 struct dm_target *ti = dm_table_get_target(t, i);
1907
1908 if (ti->zone_reset_all_supported) {
1909 __send_zone_reset_all_native(ci, ti);
1910 continue;
1911 }
1912
1913 sts = __send_zone_reset_all_emulated(ci, ti);
1914 if (sts != BLK_STS_OK)
1915 break;
1916 }
1917
1918 /* Release the reference that alloc_io() took for submission. */
1919 atomic_sub(1, &ci->io->io_count);
1920
1921 return sts;
1922 }
1923
1924 #else
dm_zone_bio_needs_split(struct bio * bio)1925 static inline bool dm_zone_bio_needs_split(struct bio *bio)
1926 {
1927 return false;
1928 }
dm_zone_plug_bio(struct mapped_device * md,struct bio * bio)1929 static inline bool dm_zone_plug_bio(struct mapped_device *md, struct bio *bio)
1930 {
1931 return false;
1932 }
__send_zone_reset_all(struct clone_info * ci)1933 static blk_status_t __send_zone_reset_all(struct clone_info *ci)
1934 {
1935 return BLK_STS_NOTSUPP;
1936 }
1937 #endif
1938
1939 /*
1940 * Entry point to split a bio into clones and submit them to the targets.
1941 */
dm_split_and_process_bio(struct mapped_device * md,struct dm_table * map,struct bio * bio)1942 static void dm_split_and_process_bio(struct mapped_device *md,
1943 struct dm_table *map, struct bio *bio)
1944 {
1945 struct clone_info ci;
1946 struct dm_io *io;
1947 blk_status_t error = BLK_STS_OK;
1948 bool is_abnormal, need_split;
1949
1950 is_abnormal = is_abnormal_io(bio);
1951 if (static_branch_unlikely(&zoned_enabled)) {
1952 need_split = is_abnormal || dm_zone_bio_needs_split(bio);
1953 } else {
1954 need_split = is_abnormal;
1955 }
1956
1957 if (unlikely(need_split)) {
1958 /*
1959 * Use bio_split_to_limits() for abnormal IO (e.g. discard, etc)
1960 * otherwise associated queue_limits won't be imposed.
1961 * Also split the BIO for mapped devices needing zone append
1962 * emulation to ensure that the BIO does not cross zone
1963 * boundaries.
1964 */
1965 bio = bio_split_to_limits(bio);
1966 if (!bio)
1967 return;
1968 }
1969
1970 /*
1971 * Use the block layer zone write plugging for mapped devices that
1972 * need zone append emulation (e.g. dm-crypt).
1973 */
1974 if (static_branch_unlikely(&zoned_enabled) && dm_zone_plug_bio(md, bio))
1975 return;
1976
1977 /* Only support nowait for normal IO */
1978 if (unlikely(bio->bi_opf & REQ_NOWAIT) && !is_abnormal) {
1979 /*
1980 * Don't support NOWAIT for FLUSH because it may allocate
1981 * multiple bios and there's no easy way how to undo the
1982 * allocations.
1983 */
1984 if (bio->bi_opf & REQ_PREFLUSH) {
1985 bio_wouldblock_error(bio);
1986 return;
1987 }
1988 io = alloc_io(md, bio, GFP_NOWAIT);
1989 if (unlikely(!io)) {
1990 /* Unable to do anything without dm_io. */
1991 bio_wouldblock_error(bio);
1992 return;
1993 }
1994 } else {
1995 io = alloc_io(md, bio, GFP_NOIO);
1996 }
1997 init_clone_info(&ci, io, map, bio, is_abnormal);
1998
1999 if (bio->bi_opf & REQ_PREFLUSH) {
2000 __send_empty_flush(&ci);
2001 /* dm_io_complete submits any data associated with flush */
2002 goto out;
2003 }
2004
2005 if (static_branch_unlikely(&zoned_enabled) &&
2006 (bio_op(bio) == REQ_OP_ZONE_RESET_ALL)) {
2007 error = __send_zone_reset_all(&ci);
2008 goto out;
2009 }
2010
2011 error = __split_and_process_bio(&ci);
2012 if (error || !ci.sector_count)
2013 goto out;
2014 /*
2015 * Remainder must be passed to submit_bio_noacct() so it gets handled
2016 * *after* bios already submitted have been completely processed.
2017 */
2018 bio_trim(bio, io->sectors, ci.sector_count);
2019 trace_block_split(bio, bio->bi_iter.bi_sector);
2020 bio_inc_remaining(bio);
2021 submit_bio_noacct(bio);
2022 out:
2023 /*
2024 * Drop the extra reference count for non-POLLED bio, and hold one
2025 * reference for POLLED bio, which will be released in dm_poll_bio
2026 *
2027 * Add every dm_io instance into the dm_io list head which is stored
2028 * in bio->bi_private, so that dm_poll_bio can poll them all.
2029 */
2030 if (error || !ci.submit_as_polled) {
2031 /*
2032 * In case of submission failure, the extra reference for
2033 * submitting io isn't consumed yet
2034 */
2035 if (error)
2036 atomic_dec(&io->io_count);
2037 dm_io_dec_pending(io, error);
2038 } else
2039 dm_queue_poll_io(bio, io);
2040 }
2041
dm_submit_bio(struct bio * bio)2042 static void dm_submit_bio(struct bio *bio)
2043 {
2044 struct mapped_device *md = bio->bi_bdev->bd_disk->private_data;
2045 int srcu_idx;
2046 struct dm_table *map;
2047
2048 map = dm_get_live_table(md, &srcu_idx);
2049 if (unlikely(!map)) {
2050 DMERR_LIMIT("%s: mapping table unavailable, erroring io",
2051 dm_device_name(md));
2052 bio_io_error(bio);
2053 goto out;
2054 }
2055
2056 /* If suspended, queue this IO for later */
2057 if (unlikely(test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags))) {
2058 if (bio->bi_opf & REQ_NOWAIT)
2059 bio_wouldblock_error(bio);
2060 else if (bio->bi_opf & REQ_RAHEAD)
2061 bio_io_error(bio);
2062 else
2063 queue_io(md, bio);
2064 goto out;
2065 }
2066
2067 dm_split_and_process_bio(md, map, bio);
2068 out:
2069 dm_put_live_table(md, srcu_idx);
2070 }
2071
dm_poll_dm_io(struct dm_io * io,struct io_comp_batch * iob,unsigned int flags)2072 static bool dm_poll_dm_io(struct dm_io *io, struct io_comp_batch *iob,
2073 unsigned int flags)
2074 {
2075 WARN_ON_ONCE(!dm_tio_is_normal(&io->tio));
2076
2077 /* don't poll if the mapped io is done */
2078 if (atomic_read(&io->io_count) > 1)
2079 bio_poll(&io->tio.clone, iob, flags);
2080
2081 /* bio_poll holds the last reference */
2082 return atomic_read(&io->io_count) == 1;
2083 }
2084
dm_poll_bio(struct bio * bio,struct io_comp_batch * iob,unsigned int flags)2085 static int dm_poll_bio(struct bio *bio, struct io_comp_batch *iob,
2086 unsigned int flags)
2087 {
2088 struct dm_io **head = dm_poll_list_head(bio);
2089 struct dm_io *list = *head;
2090 struct dm_io *tmp = NULL;
2091 struct dm_io *curr, *next;
2092
2093 /* Only poll normal bio which was marked as REQ_DM_POLL_LIST */
2094 if (!(bio->bi_opf & REQ_DM_POLL_LIST))
2095 return 0;
2096
2097 WARN_ON_ONCE(!list);
2098
2099 /*
2100 * Restore .bi_private before possibly completing dm_io.
2101 *
2102 * bio_poll() is only possible once @bio has been completely
2103 * submitted via submit_bio_noacct()'s depth-first submission.
2104 * So there is no dm_queue_poll_io() race associated with
2105 * clearing REQ_DM_POLL_LIST here.
2106 */
2107 bio->bi_opf &= ~REQ_DM_POLL_LIST;
2108 bio->bi_private = list->data;
2109
2110 for (curr = list, next = curr->next; curr; curr = next, next =
2111 curr ? curr->next : NULL) {
2112 if (dm_poll_dm_io(curr, iob, flags)) {
2113 /*
2114 * clone_endio() has already occurred, so no
2115 * error handling is needed here.
2116 */
2117 __dm_io_dec_pending(curr);
2118 } else {
2119 curr->next = tmp;
2120 tmp = curr;
2121 }
2122 }
2123
2124 /* Not done? */
2125 if (tmp) {
2126 bio->bi_opf |= REQ_DM_POLL_LIST;
2127 /* Reset bio->bi_private to dm_io list head */
2128 *head = tmp;
2129 return 0;
2130 }
2131 return 1;
2132 }
2133
2134 /*
2135 *---------------------------------------------------------------
2136 * An IDR is used to keep track of allocated minor numbers.
2137 *---------------------------------------------------------------
2138 */
free_minor(int minor)2139 static void free_minor(int minor)
2140 {
2141 spin_lock(&_minor_lock);
2142 idr_remove(&_minor_idr, minor);
2143 spin_unlock(&_minor_lock);
2144 }
2145
2146 /*
2147 * See if the device with a specific minor # is free.
2148 */
specific_minor(int minor)2149 static int specific_minor(int minor)
2150 {
2151 int r;
2152
2153 if (minor >= (1 << MINORBITS))
2154 return -EINVAL;
2155
2156 idr_preload(GFP_KERNEL);
2157 spin_lock(&_minor_lock);
2158
2159 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, minor, minor + 1, GFP_NOWAIT);
2160
2161 spin_unlock(&_minor_lock);
2162 idr_preload_end();
2163 if (r < 0)
2164 return r == -ENOSPC ? -EBUSY : r;
2165 return 0;
2166 }
2167
next_free_minor(int * minor)2168 static int next_free_minor(int *minor)
2169 {
2170 int r;
2171
2172 idr_preload(GFP_KERNEL);
2173 spin_lock(&_minor_lock);
2174
2175 r = idr_alloc(&_minor_idr, MINOR_ALLOCED, 0, 1 << MINORBITS, GFP_NOWAIT);
2176
2177 spin_unlock(&_minor_lock);
2178 idr_preload_end();
2179 if (r < 0)
2180 return r;
2181 *minor = r;
2182 return 0;
2183 }
2184
2185 static const struct block_device_operations dm_blk_dops;
2186 static const struct block_device_operations dm_rq_blk_dops;
2187 static const struct dax_operations dm_dax_ops;
2188
2189 static void dm_wq_work(struct work_struct *work);
2190
2191 #ifdef CONFIG_BLK_INLINE_ENCRYPTION
dm_queue_destroy_crypto_profile(struct request_queue * q)2192 static void dm_queue_destroy_crypto_profile(struct request_queue *q)
2193 {
2194 dm_destroy_crypto_profile(q->crypto_profile);
2195 }
2196
2197 #else /* CONFIG_BLK_INLINE_ENCRYPTION */
2198
dm_queue_destroy_crypto_profile(struct request_queue * q)2199 static inline void dm_queue_destroy_crypto_profile(struct request_queue *q)
2200 {
2201 }
2202 #endif /* !CONFIG_BLK_INLINE_ENCRYPTION */
2203
cleanup_mapped_device(struct mapped_device * md)2204 static void cleanup_mapped_device(struct mapped_device *md)
2205 {
2206 if (md->wq)
2207 destroy_workqueue(md->wq);
2208 dm_free_md_mempools(md->mempools);
2209
2210 if (md->dax_dev) {
2211 dax_remove_host(md->disk);
2212 kill_dax(md->dax_dev);
2213 put_dax(md->dax_dev);
2214 md->dax_dev = NULL;
2215 }
2216
2217 if (md->disk) {
2218 spin_lock(&_minor_lock);
2219 md->disk->private_data = NULL;
2220 spin_unlock(&_minor_lock);
2221 if (dm_get_md_type(md) != DM_TYPE_NONE) {
2222 struct table_device *td;
2223
2224 dm_sysfs_exit(md);
2225 list_for_each_entry(td, &md->table_devices, list) {
2226 bd_unlink_disk_holder(td->dm_dev.bdev,
2227 md->disk);
2228 }
2229
2230 /*
2231 * Hold lock to make sure del_gendisk() won't concurrent
2232 * with open/close_table_device().
2233 */
2234 mutex_lock(&md->table_devices_lock);
2235 del_gendisk(md->disk);
2236 mutex_unlock(&md->table_devices_lock);
2237 }
2238 dm_queue_destroy_crypto_profile(md->queue);
2239 put_disk(md->disk);
2240 }
2241
2242 if (md->pending_io) {
2243 free_percpu(md->pending_io);
2244 md->pending_io = NULL;
2245 }
2246
2247 cleanup_srcu_struct(&md->io_barrier);
2248
2249 mutex_destroy(&md->suspend_lock);
2250 mutex_destroy(&md->type_lock);
2251 mutex_destroy(&md->table_devices_lock);
2252 mutex_destroy(&md->swap_bios_lock);
2253
2254 dm_mq_cleanup_mapped_device(md);
2255 }
2256
2257 /*
2258 * Allocate and initialise a blank device with a given minor.
2259 */
alloc_dev(int minor)2260 static struct mapped_device *alloc_dev(int minor)
2261 {
2262 int r, numa_node_id = dm_get_numa_node();
2263 struct dax_device *dax_dev;
2264 struct mapped_device *md;
2265 void *old_md;
2266
2267 md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id);
2268 if (!md) {
2269 DMERR("unable to allocate device, out of memory.");
2270 return NULL;
2271 }
2272
2273 if (!try_module_get(THIS_MODULE))
2274 goto bad_module_get;
2275
2276 /* get a minor number for the dev */
2277 if (minor == DM_ANY_MINOR)
2278 r = next_free_minor(&minor);
2279 else
2280 r = specific_minor(minor);
2281 if (r < 0)
2282 goto bad_minor;
2283
2284 r = init_srcu_struct(&md->io_barrier);
2285 if (r < 0)
2286 goto bad_io_barrier;
2287
2288 md->numa_node_id = numa_node_id;
2289 md->init_tio_pdu = false;
2290 md->type = DM_TYPE_NONE;
2291 mutex_init(&md->suspend_lock);
2292 mutex_init(&md->type_lock);
2293 mutex_init(&md->table_devices_lock);
2294 spin_lock_init(&md->deferred_lock);
2295 atomic_set(&md->holders, 1);
2296 atomic_set(&md->open_count, 0);
2297 atomic_set(&md->event_nr, 0);
2298 atomic_set(&md->uevent_seq, 0);
2299 INIT_LIST_HEAD(&md->uevent_list);
2300 INIT_LIST_HEAD(&md->table_devices);
2301 spin_lock_init(&md->uevent_lock);
2302
2303 /*
2304 * default to bio-based until DM table is loaded and md->type
2305 * established. If request-based table is loaded: blk-mq will
2306 * override accordingly.
2307 */
2308 md->disk = blk_alloc_disk(NULL, md->numa_node_id);
2309 if (IS_ERR(md->disk)) {
2310 md->disk = NULL;
2311 goto bad;
2312 }
2313 md->queue = md->disk->queue;
2314
2315 init_waitqueue_head(&md->wait);
2316 INIT_WORK(&md->work, dm_wq_work);
2317 INIT_WORK(&md->requeue_work, dm_wq_requeue_work);
2318 init_waitqueue_head(&md->eventq);
2319 init_completion(&md->kobj_holder.completion);
2320
2321 md->requeue_list = NULL;
2322 md->swap_bios = get_swap_bios();
2323 sema_init(&md->swap_bios_semaphore, md->swap_bios);
2324 mutex_init(&md->swap_bios_lock);
2325
2326 md->disk->major = _major;
2327 md->disk->first_minor = minor;
2328 md->disk->minors = 1;
2329 md->disk->flags |= GENHD_FL_NO_PART;
2330 md->disk->fops = &dm_blk_dops;
2331 md->disk->private_data = md;
2332 sprintf(md->disk->disk_name, "dm-%d", minor);
2333
2334 dax_dev = alloc_dax(md, &dm_dax_ops);
2335 if (IS_ERR(dax_dev)) {
2336 if (PTR_ERR(dax_dev) != -EOPNOTSUPP)
2337 goto bad;
2338 } else {
2339 set_dax_nocache(dax_dev);
2340 set_dax_nomc(dax_dev);
2341 md->dax_dev = dax_dev;
2342 if (dax_add_host(dax_dev, md->disk))
2343 goto bad;
2344 }
2345
2346 format_dev_t(md->name, MKDEV(_major, minor));
2347
2348 md->wq = alloc_workqueue("kdmflush/%s", WQ_MEM_RECLAIM, 0, md->name);
2349 if (!md->wq)
2350 goto bad;
2351
2352 md->pending_io = alloc_percpu(unsigned long);
2353 if (!md->pending_io)
2354 goto bad;
2355
2356 r = dm_stats_init(&md->stats);
2357 if (r < 0)
2358 goto bad;
2359
2360 /* Populate the mapping, nobody knows we exist yet */
2361 spin_lock(&_minor_lock);
2362 old_md = idr_replace(&_minor_idr, md, minor);
2363 spin_unlock(&_minor_lock);
2364
2365 BUG_ON(old_md != MINOR_ALLOCED);
2366
2367 return md;
2368
2369 bad:
2370 cleanup_mapped_device(md);
2371 bad_io_barrier:
2372 free_minor(minor);
2373 bad_minor:
2374 module_put(THIS_MODULE);
2375 bad_module_get:
2376 kvfree(md);
2377 return NULL;
2378 }
2379
2380 static void unlock_fs(struct mapped_device *md);
2381
free_dev(struct mapped_device * md)2382 static void free_dev(struct mapped_device *md)
2383 {
2384 int minor = MINOR(disk_devt(md->disk));
2385
2386 unlock_fs(md);
2387
2388 cleanup_mapped_device(md);
2389
2390 WARN_ON_ONCE(!list_empty(&md->table_devices));
2391 dm_stats_cleanup(&md->stats);
2392 free_minor(minor);
2393
2394 module_put(THIS_MODULE);
2395 kvfree(md);
2396 }
2397
2398 /*
2399 * Bind a table to the device.
2400 */
event_callback(void * context)2401 static void event_callback(void *context)
2402 {
2403 unsigned long flags;
2404 LIST_HEAD(uevents);
2405 struct mapped_device *md = context;
2406
2407 spin_lock_irqsave(&md->uevent_lock, flags);
2408 list_splice_init(&md->uevent_list, &uevents);
2409 spin_unlock_irqrestore(&md->uevent_lock, flags);
2410
2411 dm_send_uevents(&uevents, &disk_to_dev(md->disk)->kobj);
2412
2413 atomic_inc(&md->event_nr);
2414 wake_up(&md->eventq);
2415 dm_issue_global_event();
2416 }
2417
2418 /*
2419 * Returns old map, which caller must destroy.
2420 */
__bind(struct mapped_device * md,struct dm_table * t,struct queue_limits * limits)2421 static struct dm_table *__bind(struct mapped_device *md, struct dm_table *t,
2422 struct queue_limits *limits)
2423 {
2424 struct dm_table *old_map;
2425 sector_t size, old_size;
2426 int ret;
2427
2428 lockdep_assert_held(&md->suspend_lock);
2429
2430 size = dm_table_get_size(t);
2431
2432 old_size = dm_get_size(md);
2433
2434 if (!dm_table_supports_size_change(t, old_size, size)) {
2435 old_map = ERR_PTR(-EINVAL);
2436 goto out;
2437 }
2438
2439 set_capacity(md->disk, size);
2440
2441 ret = dm_table_set_restrictions(t, md->queue, limits);
2442 if (ret) {
2443 set_capacity(md->disk, old_size);
2444 old_map = ERR_PTR(ret);
2445 goto out;
2446 }
2447
2448 /*
2449 * Wipe any geometry if the size of the table changed.
2450 */
2451 if (size != old_size)
2452 memset(&md->geometry, 0, sizeof(md->geometry));
2453
2454 dm_table_event_callback(t, event_callback, md);
2455
2456 if (dm_table_request_based(t)) {
2457 /*
2458 * Leverage the fact that request-based DM targets are
2459 * immutable singletons - used to optimize dm_mq_queue_rq.
2460 */
2461 md->immutable_target = dm_table_get_immutable_target(t);
2462
2463 /*
2464 * There is no need to reload with request-based dm because the
2465 * size of front_pad doesn't change.
2466 *
2467 * Note for future: If you are to reload bioset, prep-ed
2468 * requests in the queue may refer to bio from the old bioset,
2469 * so you must walk through the queue to unprep.
2470 */
2471 if (!md->mempools)
2472 md->mempools = t->mempools;
2473 else
2474 dm_free_md_mempools(t->mempools);
2475 } else {
2476 /*
2477 * The md may already have mempools that need changing.
2478 * If so, reload bioset because front_pad may have changed
2479 * because a different table was loaded.
2480 */
2481 dm_free_md_mempools(md->mempools);
2482 md->mempools = t->mempools;
2483 }
2484 t->mempools = NULL;
2485
2486 old_map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
2487 rcu_assign_pointer(md->map, (void *)t);
2488 md->immutable_target_type = dm_table_get_immutable_target_type(t);
2489
2490 if (old_map)
2491 dm_sync_table(md);
2492 out:
2493 return old_map;
2494 }
2495
2496 /*
2497 * Returns unbound table for the caller to free.
2498 */
__unbind(struct mapped_device * md)2499 static struct dm_table *__unbind(struct mapped_device *md)
2500 {
2501 struct dm_table *map = rcu_dereference_protected(md->map, 1);
2502
2503 if (!map)
2504 return NULL;
2505
2506 dm_table_event_callback(map, NULL, NULL);
2507 RCU_INIT_POINTER(md->map, NULL);
2508 dm_sync_table(md);
2509
2510 return map;
2511 }
2512
2513 /*
2514 * Constructor for a new device.
2515 */
dm_create(int minor,struct mapped_device ** result)2516 int dm_create(int minor, struct mapped_device **result)
2517 {
2518 struct mapped_device *md;
2519
2520 md = alloc_dev(minor);
2521 if (!md)
2522 return -ENXIO;
2523
2524 dm_ima_reset_data(md);
2525
2526 *result = md;
2527 return 0;
2528 }
2529
2530 /*
2531 * Functions to manage md->type.
2532 * All are required to hold md->type_lock.
2533 */
dm_lock_md_type(struct mapped_device * md)2534 void dm_lock_md_type(struct mapped_device *md)
2535 {
2536 mutex_lock(&md->type_lock);
2537 }
2538
dm_unlock_md_type(struct mapped_device * md)2539 void dm_unlock_md_type(struct mapped_device *md)
2540 {
2541 mutex_unlock(&md->type_lock);
2542 }
2543
dm_get_md_type(struct mapped_device * md)2544 enum dm_queue_mode dm_get_md_type(struct mapped_device *md)
2545 {
2546 return md->type;
2547 }
2548
dm_get_immutable_target_type(struct mapped_device * md)2549 struct target_type *dm_get_immutable_target_type(struct mapped_device *md)
2550 {
2551 return md->immutable_target_type;
2552 }
2553
2554 /*
2555 * Setup the DM device's queue based on md's type
2556 */
dm_setup_md_queue(struct mapped_device * md,struct dm_table * t)2557 int dm_setup_md_queue(struct mapped_device *md, struct dm_table *t)
2558 {
2559 enum dm_queue_mode type = dm_table_get_type(t);
2560 struct queue_limits limits;
2561 struct table_device *td;
2562 int r;
2563
2564 WARN_ON_ONCE(type == DM_TYPE_NONE);
2565
2566 if (type == DM_TYPE_REQUEST_BASED) {
2567 md->disk->fops = &dm_rq_blk_dops;
2568 r = dm_mq_init_request_queue(md, t);
2569 if (r) {
2570 DMERR("Cannot initialize queue for request-based dm mapped device");
2571 return r;
2572 }
2573 }
2574
2575 r = dm_calculate_queue_limits(t, &limits);
2576 if (r) {
2577 DMERR("Cannot calculate initial queue limits");
2578 return r;
2579 }
2580 r = dm_table_set_restrictions(t, md->queue, &limits);
2581 if (r)
2582 return r;
2583
2584 /*
2585 * Hold lock to make sure add_disk() and del_gendisk() won't concurrent
2586 * with open_table_device() and close_table_device().
2587 */
2588 mutex_lock(&md->table_devices_lock);
2589 r = add_disk(md->disk);
2590 mutex_unlock(&md->table_devices_lock);
2591 if (r)
2592 return r;
2593
2594 /*
2595 * Register the holder relationship for devices added before the disk
2596 * was live.
2597 */
2598 list_for_each_entry(td, &md->table_devices, list) {
2599 r = bd_link_disk_holder(td->dm_dev.bdev, md->disk);
2600 if (r)
2601 goto out_undo_holders;
2602 }
2603
2604 r = dm_sysfs_init(md);
2605 if (r)
2606 goto out_undo_holders;
2607
2608 md->type = type;
2609 return 0;
2610
2611 out_undo_holders:
2612 list_for_each_entry_continue_reverse(td, &md->table_devices, list)
2613 bd_unlink_disk_holder(td->dm_dev.bdev, md->disk);
2614 mutex_lock(&md->table_devices_lock);
2615 del_gendisk(md->disk);
2616 mutex_unlock(&md->table_devices_lock);
2617 return r;
2618 }
2619
dm_get_md(dev_t dev)2620 struct mapped_device *dm_get_md(dev_t dev)
2621 {
2622 struct mapped_device *md;
2623 unsigned int minor = MINOR(dev);
2624
2625 if (MAJOR(dev) != _major || minor >= (1 << MINORBITS))
2626 return NULL;
2627
2628 spin_lock(&_minor_lock);
2629
2630 md = idr_find(&_minor_idr, minor);
2631 if (!md || md == MINOR_ALLOCED || (MINOR(disk_devt(dm_disk(md))) != minor) ||
2632 test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
2633 md = NULL;
2634 goto out;
2635 }
2636 dm_get(md);
2637 out:
2638 spin_unlock(&_minor_lock);
2639
2640 return md;
2641 }
2642 EXPORT_SYMBOL_GPL(dm_get_md);
2643
dm_get_mdptr(struct mapped_device * md)2644 void *dm_get_mdptr(struct mapped_device *md)
2645 {
2646 return md->interface_ptr;
2647 }
2648
dm_set_mdptr(struct mapped_device * md,void * ptr)2649 void dm_set_mdptr(struct mapped_device *md, void *ptr)
2650 {
2651 md->interface_ptr = ptr;
2652 }
2653
dm_get(struct mapped_device * md)2654 void dm_get(struct mapped_device *md)
2655 {
2656 atomic_inc(&md->holders);
2657 BUG_ON(test_bit(DMF_FREEING, &md->flags));
2658 }
2659
dm_hold(struct mapped_device * md)2660 int dm_hold(struct mapped_device *md)
2661 {
2662 spin_lock(&_minor_lock);
2663 if (test_bit(DMF_FREEING, &md->flags)) {
2664 spin_unlock(&_minor_lock);
2665 return -EBUSY;
2666 }
2667 dm_get(md);
2668 spin_unlock(&_minor_lock);
2669 return 0;
2670 }
2671 EXPORT_SYMBOL_GPL(dm_hold);
2672
dm_device_name(struct mapped_device * md)2673 const char *dm_device_name(struct mapped_device *md)
2674 {
2675 return md->name;
2676 }
2677 EXPORT_SYMBOL_GPL(dm_device_name);
2678
__dm_destroy(struct mapped_device * md,bool wait)2679 static void __dm_destroy(struct mapped_device *md, bool wait)
2680 {
2681 struct dm_table *map;
2682 int srcu_idx;
2683
2684 might_sleep();
2685
2686 spin_lock(&_minor_lock);
2687 idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
2688 set_bit(DMF_FREEING, &md->flags);
2689 spin_unlock(&_minor_lock);
2690
2691 blk_mark_disk_dead(md->disk);
2692
2693 /*
2694 * Take suspend_lock so that presuspend and postsuspend methods
2695 * do not race with internal suspend.
2696 */
2697 mutex_lock(&md->suspend_lock);
2698 map = dm_get_live_table(md, &srcu_idx);
2699 if (!dm_suspended_md(md)) {
2700 dm_table_presuspend_targets(map);
2701 set_bit(DMF_SUSPENDED, &md->flags);
2702 set_bit(DMF_POST_SUSPENDING, &md->flags);
2703 dm_table_postsuspend_targets(map);
2704 }
2705 /* dm_put_live_table must be before fsleep, otherwise deadlock is possible */
2706 dm_put_live_table(md, srcu_idx);
2707 mutex_unlock(&md->suspend_lock);
2708
2709 /*
2710 * Rare, but there may be I/O requests still going to complete,
2711 * for example. Wait for all references to disappear.
2712 * No one should increment the reference count of the mapped_device,
2713 * after the mapped_device state becomes DMF_FREEING.
2714 */
2715 if (wait)
2716 while (atomic_read(&md->holders))
2717 fsleep(1000);
2718 else if (atomic_read(&md->holders))
2719 DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
2720 dm_device_name(md), atomic_read(&md->holders));
2721
2722 dm_table_destroy(__unbind(md));
2723 free_dev(md);
2724 }
2725
dm_destroy(struct mapped_device * md)2726 void dm_destroy(struct mapped_device *md)
2727 {
2728 __dm_destroy(md, true);
2729 }
2730
dm_destroy_immediate(struct mapped_device * md)2731 void dm_destroy_immediate(struct mapped_device *md)
2732 {
2733 __dm_destroy(md, false);
2734 }
2735
dm_put(struct mapped_device * md)2736 void dm_put(struct mapped_device *md)
2737 {
2738 atomic_dec(&md->holders);
2739 }
2740 EXPORT_SYMBOL_GPL(dm_put);
2741
dm_in_flight_bios(struct mapped_device * md)2742 static bool dm_in_flight_bios(struct mapped_device *md)
2743 {
2744 int cpu;
2745 unsigned long sum = 0;
2746
2747 for_each_possible_cpu(cpu)
2748 sum += *per_cpu_ptr(md->pending_io, cpu);
2749
2750 return sum != 0;
2751 }
2752
dm_wait_for_bios_completion(struct mapped_device * md,unsigned int task_state)2753 static int dm_wait_for_bios_completion(struct mapped_device *md, unsigned int task_state)
2754 {
2755 int r = 0;
2756 DEFINE_WAIT(wait);
2757
2758 while (true) {
2759 prepare_to_wait(&md->wait, &wait, task_state);
2760
2761 if (!dm_in_flight_bios(md))
2762 break;
2763
2764 if (signal_pending_state(task_state, current)) {
2765 r = -ERESTARTSYS;
2766 break;
2767 }
2768
2769 io_schedule();
2770 }
2771 finish_wait(&md->wait, &wait);
2772
2773 smp_rmb();
2774
2775 return r;
2776 }
2777
dm_wait_for_completion(struct mapped_device * md,unsigned int task_state)2778 static int dm_wait_for_completion(struct mapped_device *md, unsigned int task_state)
2779 {
2780 int r = 0;
2781
2782 if (!queue_is_mq(md->queue))
2783 return dm_wait_for_bios_completion(md, task_state);
2784
2785 while (true) {
2786 if (!blk_mq_queue_inflight(md->queue))
2787 break;
2788
2789 if (signal_pending_state(task_state, current)) {
2790 r = -ERESTARTSYS;
2791 break;
2792 }
2793
2794 fsleep(5000);
2795 }
2796
2797 return r;
2798 }
2799
2800 /*
2801 * Process the deferred bios
2802 */
dm_wq_work(struct work_struct * work)2803 static void dm_wq_work(struct work_struct *work)
2804 {
2805 struct mapped_device *md = container_of(work, struct mapped_device, work);
2806 struct bio *bio;
2807
2808 while (!test_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags)) {
2809 spin_lock_irq(&md->deferred_lock);
2810 bio = bio_list_pop(&md->deferred);
2811 spin_unlock_irq(&md->deferred_lock);
2812
2813 if (!bio)
2814 break;
2815
2816 submit_bio_noacct(bio);
2817 cond_resched();
2818 }
2819 }
2820
dm_queue_flush(struct mapped_device * md)2821 static void dm_queue_flush(struct mapped_device *md)
2822 {
2823 clear_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2824 smp_mb__after_atomic();
2825 queue_work(md->wq, &md->work);
2826 }
2827
2828 /*
2829 * Swap in a new table, returning the old one for the caller to destroy.
2830 */
dm_swap_table(struct mapped_device * md,struct dm_table * table)2831 struct dm_table *dm_swap_table(struct mapped_device *md, struct dm_table *table)
2832 {
2833 struct dm_table *live_map = NULL, *map = ERR_PTR(-EINVAL);
2834 struct queue_limits limits;
2835 int r;
2836
2837 mutex_lock(&md->suspend_lock);
2838
2839 /* device must be suspended */
2840 if (!dm_suspended_md(md))
2841 goto out;
2842
2843 /*
2844 * If the new table has no data devices, retain the existing limits.
2845 * This helps multipath with queue_if_no_path if all paths disappear,
2846 * then new I/O is queued based on these limits, and then some paths
2847 * reappear.
2848 */
2849 if (dm_table_has_no_data_devices(table)) {
2850 live_map = dm_get_live_table_fast(md);
2851 if (live_map)
2852 limits = md->queue->limits;
2853 dm_put_live_table_fast(md);
2854 }
2855
2856 if (!live_map) {
2857 r = dm_calculate_queue_limits(table, &limits);
2858 if (r) {
2859 map = ERR_PTR(r);
2860 goto out;
2861 }
2862 }
2863
2864 map = __bind(md, table, &limits);
2865 dm_issue_global_event();
2866
2867 out:
2868 mutex_unlock(&md->suspend_lock);
2869 return map;
2870 }
2871
2872 /*
2873 * Functions to lock and unlock any filesystem running on the
2874 * device.
2875 */
lock_fs(struct mapped_device * md)2876 static int lock_fs(struct mapped_device *md)
2877 {
2878 int r;
2879
2880 WARN_ON(test_bit(DMF_FROZEN, &md->flags));
2881
2882 r = bdev_freeze(md->disk->part0);
2883 if (!r)
2884 set_bit(DMF_FROZEN, &md->flags);
2885 return r;
2886 }
2887
unlock_fs(struct mapped_device * md)2888 static void unlock_fs(struct mapped_device *md)
2889 {
2890 if (!test_bit(DMF_FROZEN, &md->flags))
2891 return;
2892 bdev_thaw(md->disk->part0);
2893 clear_bit(DMF_FROZEN, &md->flags);
2894 }
2895
2896 /*
2897 * @suspend_flags: DM_SUSPEND_LOCKFS_FLAG and/or DM_SUSPEND_NOFLUSH_FLAG
2898 * @task_state: e.g. TASK_INTERRUPTIBLE or TASK_UNINTERRUPTIBLE
2899 * @dmf_suspended_flag: DMF_SUSPENDED or DMF_SUSPENDED_INTERNALLY
2900 *
2901 * If __dm_suspend returns 0, the device is completely quiescent
2902 * now. There is no request-processing activity. All new requests
2903 * are being added to md->deferred list.
2904 */
__dm_suspend(struct mapped_device * md,struct dm_table * map,unsigned int suspend_flags,unsigned int task_state,int dmf_suspended_flag)2905 static int __dm_suspend(struct mapped_device *md, struct dm_table *map,
2906 unsigned int suspend_flags, unsigned int task_state,
2907 int dmf_suspended_flag)
2908 {
2909 bool do_lockfs = suspend_flags & DM_SUSPEND_LOCKFS_FLAG;
2910 bool noflush = suspend_flags & DM_SUSPEND_NOFLUSH_FLAG;
2911 int r;
2912
2913 lockdep_assert_held(&md->suspend_lock);
2914
2915 /*
2916 * DMF_NOFLUSH_SUSPENDING must be set before presuspend.
2917 * This flag is cleared before dm_suspend returns.
2918 */
2919 if (noflush)
2920 set_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2921 else
2922 DMDEBUG("%s: suspending with flush", dm_device_name(md));
2923
2924 /*
2925 * This gets reverted if there's an error later and the targets
2926 * provide the .presuspend_undo hook.
2927 */
2928 dm_table_presuspend_targets(map);
2929
2930 /*
2931 * Flush I/O to the device.
2932 * Any I/O submitted after lock_fs() may not be flushed.
2933 * noflush takes precedence over do_lockfs.
2934 * (lock_fs() flushes I/Os and waits for them to complete.)
2935 */
2936 if (!noflush && do_lockfs) {
2937 r = lock_fs(md);
2938 if (r) {
2939 dm_table_presuspend_undo_targets(map);
2940 return r;
2941 }
2942 }
2943
2944 /*
2945 * Here we must make sure that no processes are submitting requests
2946 * to target drivers i.e. no one may be executing
2947 * dm_split_and_process_bio from dm_submit_bio.
2948 *
2949 * To get all processes out of dm_split_and_process_bio in dm_submit_bio,
2950 * we take the write lock. To prevent any process from reentering
2951 * dm_split_and_process_bio from dm_submit_bio and quiesce the thread
2952 * (dm_wq_work), we set DMF_BLOCK_IO_FOR_SUSPEND and call
2953 * flush_workqueue(md->wq).
2954 */
2955 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
2956 if (map)
2957 synchronize_srcu(&md->io_barrier);
2958
2959 /*
2960 * Stop md->queue before flushing md->wq in case request-based
2961 * dm defers requests to md->wq from md->queue.
2962 */
2963 if (dm_request_based(md))
2964 dm_stop_queue(md->queue);
2965
2966 flush_workqueue(md->wq);
2967
2968 /*
2969 * At this point no more requests are entering target request routines.
2970 * We call dm_wait_for_completion to wait for all existing requests
2971 * to finish.
2972 */
2973 r = dm_wait_for_completion(md, task_state);
2974 if (!r)
2975 set_bit(dmf_suspended_flag, &md->flags);
2976
2977 if (noflush)
2978 clear_bit(DMF_NOFLUSH_SUSPENDING, &md->flags);
2979 if (map)
2980 synchronize_srcu(&md->io_barrier);
2981
2982 /* were we interrupted ? */
2983 if (r < 0) {
2984 dm_queue_flush(md);
2985
2986 if (dm_request_based(md))
2987 dm_start_queue(md->queue);
2988
2989 unlock_fs(md);
2990 dm_table_presuspend_undo_targets(map);
2991 /* pushback list is already flushed, so skip flush */
2992 }
2993
2994 return r;
2995 }
2996
2997 /*
2998 * We need to be able to change a mapping table under a mounted
2999 * filesystem. For example we might want to move some data in
3000 * the background. Before the table can be swapped with
3001 * dm_bind_table, dm_suspend must be called to flush any in
3002 * flight bios and ensure that any further io gets deferred.
3003 */
3004 /*
3005 * Suspend mechanism in request-based dm.
3006 *
3007 * 1. Flush all I/Os by lock_fs() if needed.
3008 * 2. Stop dispatching any I/O by stopping the request_queue.
3009 * 3. Wait for all in-flight I/Os to be completed or requeued.
3010 *
3011 * To abort suspend, start the request_queue.
3012 */
dm_suspend(struct mapped_device * md,unsigned int suspend_flags)3013 int dm_suspend(struct mapped_device *md, unsigned int suspend_flags)
3014 {
3015 struct dm_table *map = NULL;
3016 int r = 0;
3017
3018 retry:
3019 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3020
3021 if (dm_suspended_md(md)) {
3022 r = -EINVAL;
3023 goto out_unlock;
3024 }
3025
3026 if (dm_suspended_internally_md(md)) {
3027 /* already internally suspended, wait for internal resume */
3028 mutex_unlock(&md->suspend_lock);
3029 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3030 if (r)
3031 return r;
3032 goto retry;
3033 }
3034
3035 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3036 if (!map) {
3037 /* avoid deadlock with fs/namespace.c:do_mount() */
3038 suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
3039 }
3040
3041 r = __dm_suspend(md, map, suspend_flags, TASK_INTERRUPTIBLE, DMF_SUSPENDED);
3042 if (r)
3043 goto out_unlock;
3044
3045 set_bit(DMF_POST_SUSPENDING, &md->flags);
3046 dm_table_postsuspend_targets(map);
3047 clear_bit(DMF_POST_SUSPENDING, &md->flags);
3048
3049 out_unlock:
3050 mutex_unlock(&md->suspend_lock);
3051 return r;
3052 }
3053
__dm_resume(struct mapped_device * md,struct dm_table * map)3054 static int __dm_resume(struct mapped_device *md, struct dm_table *map)
3055 {
3056 if (map) {
3057 int r = dm_table_resume_targets(map);
3058
3059 if (r)
3060 return r;
3061 }
3062
3063 dm_queue_flush(md);
3064
3065 /*
3066 * Flushing deferred I/Os must be done after targets are resumed
3067 * so that mapping of targets can work correctly.
3068 * Request-based dm is queueing the deferred I/Os in its request_queue.
3069 */
3070 if (dm_request_based(md))
3071 dm_start_queue(md->queue);
3072
3073 unlock_fs(md);
3074
3075 return 0;
3076 }
3077
dm_resume(struct mapped_device * md)3078 int dm_resume(struct mapped_device *md)
3079 {
3080 int r;
3081 struct dm_table *map = NULL;
3082
3083 retry:
3084 r = -EINVAL;
3085 mutex_lock_nested(&md->suspend_lock, SINGLE_DEPTH_NESTING);
3086
3087 if (!dm_suspended_md(md))
3088 goto out;
3089
3090 if (dm_suspended_internally_md(md)) {
3091 /* already internally suspended, wait for internal resume */
3092 mutex_unlock(&md->suspend_lock);
3093 r = wait_on_bit(&md->flags, DMF_SUSPENDED_INTERNALLY, TASK_INTERRUPTIBLE);
3094 if (r)
3095 return r;
3096 goto retry;
3097 }
3098
3099 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3100 if (!map || !dm_table_get_size(map))
3101 goto out;
3102
3103 r = __dm_resume(md, map);
3104 if (r)
3105 goto out;
3106
3107 clear_bit(DMF_SUSPENDED, &md->flags);
3108 out:
3109 mutex_unlock(&md->suspend_lock);
3110
3111 return r;
3112 }
3113
3114 /*
3115 * Internal suspend/resume works like userspace-driven suspend. It waits
3116 * until all bios finish and prevents issuing new bios to the target drivers.
3117 * It may be used only from the kernel.
3118 */
3119
__dm_internal_suspend(struct mapped_device * md,unsigned int suspend_flags)3120 static void __dm_internal_suspend(struct mapped_device *md, unsigned int suspend_flags)
3121 {
3122 struct dm_table *map = NULL;
3123
3124 lockdep_assert_held(&md->suspend_lock);
3125
3126 if (md->internal_suspend_count++)
3127 return; /* nested internal suspend */
3128
3129 if (dm_suspended_md(md)) {
3130 set_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3131 return; /* nest suspend */
3132 }
3133
3134 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3135
3136 /*
3137 * Using TASK_UNINTERRUPTIBLE because only NOFLUSH internal suspend is
3138 * supported. Properly supporting a TASK_INTERRUPTIBLE internal suspend
3139 * would require changing .presuspend to return an error -- avoid this
3140 * until there is a need for more elaborate variants of internal suspend.
3141 */
3142 (void) __dm_suspend(md, map, suspend_flags, TASK_UNINTERRUPTIBLE,
3143 DMF_SUSPENDED_INTERNALLY);
3144
3145 set_bit(DMF_POST_SUSPENDING, &md->flags);
3146 dm_table_postsuspend_targets(map);
3147 clear_bit(DMF_POST_SUSPENDING, &md->flags);
3148 }
3149
__dm_internal_resume(struct mapped_device * md)3150 static void __dm_internal_resume(struct mapped_device *md)
3151 {
3152 int r;
3153 struct dm_table *map;
3154
3155 BUG_ON(!md->internal_suspend_count);
3156
3157 if (--md->internal_suspend_count)
3158 return; /* resume from nested internal suspend */
3159
3160 if (dm_suspended_md(md))
3161 goto done; /* resume from nested suspend */
3162
3163 map = rcu_dereference_protected(md->map, lockdep_is_held(&md->suspend_lock));
3164 r = __dm_resume(md, map);
3165 if (r) {
3166 /*
3167 * If a preresume method of some target failed, we are in a
3168 * tricky situation. We can't return an error to the caller. We
3169 * can't fake success because then the "resume" and
3170 * "postsuspend" methods would not be paired correctly, and it
3171 * would break various targets, for example it would cause list
3172 * corruption in the "origin" target.
3173 *
3174 * So, we fake normal suspend here, to make sure that the
3175 * "resume" and "postsuspend" methods will be paired correctly.
3176 */
3177 DMERR("Preresume method failed: %d", r);
3178 set_bit(DMF_SUSPENDED, &md->flags);
3179 }
3180 done:
3181 clear_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3182 smp_mb__after_atomic();
3183 wake_up_bit(&md->flags, DMF_SUSPENDED_INTERNALLY);
3184 }
3185
dm_internal_suspend_noflush(struct mapped_device * md)3186 void dm_internal_suspend_noflush(struct mapped_device *md)
3187 {
3188 mutex_lock(&md->suspend_lock);
3189 __dm_internal_suspend(md, DM_SUSPEND_NOFLUSH_FLAG);
3190 mutex_unlock(&md->suspend_lock);
3191 }
3192 EXPORT_SYMBOL_GPL(dm_internal_suspend_noflush);
3193
dm_internal_resume(struct mapped_device * md)3194 void dm_internal_resume(struct mapped_device *md)
3195 {
3196 mutex_lock(&md->suspend_lock);
3197 __dm_internal_resume(md);
3198 mutex_unlock(&md->suspend_lock);
3199 }
3200 EXPORT_SYMBOL_GPL(dm_internal_resume);
3201
3202 /*
3203 * Fast variants of internal suspend/resume hold md->suspend_lock,
3204 * which prevents interaction with userspace-driven suspend.
3205 */
3206
dm_internal_suspend_fast(struct mapped_device * md)3207 void dm_internal_suspend_fast(struct mapped_device *md)
3208 {
3209 mutex_lock(&md->suspend_lock);
3210 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3211 return;
3212
3213 set_bit(DMF_BLOCK_IO_FOR_SUSPEND, &md->flags);
3214 synchronize_srcu(&md->io_barrier);
3215 flush_workqueue(md->wq);
3216 dm_wait_for_completion(md, TASK_UNINTERRUPTIBLE);
3217 }
3218 EXPORT_SYMBOL_GPL(dm_internal_suspend_fast);
3219
dm_internal_resume_fast(struct mapped_device * md)3220 void dm_internal_resume_fast(struct mapped_device *md)
3221 {
3222 if (dm_suspended_md(md) || dm_suspended_internally_md(md))
3223 goto done;
3224
3225 dm_queue_flush(md);
3226
3227 done:
3228 mutex_unlock(&md->suspend_lock);
3229 }
3230 EXPORT_SYMBOL_GPL(dm_internal_resume_fast);
3231
3232 /*
3233 *---------------------------------------------------------------
3234 * Event notification.
3235 *---------------------------------------------------------------
3236 */
dm_kobject_uevent(struct mapped_device * md,enum kobject_action action,unsigned int cookie,bool need_resize_uevent)3237 int dm_kobject_uevent(struct mapped_device *md, enum kobject_action action,
3238 unsigned int cookie, bool need_resize_uevent)
3239 {
3240 int r;
3241 unsigned int noio_flag;
3242 char udev_cookie[DM_COOKIE_LENGTH];
3243 char *envp[3] = { NULL, NULL, NULL };
3244 char **envpp = envp;
3245 if (cookie) {
3246 snprintf(udev_cookie, DM_COOKIE_LENGTH, "%s=%u",
3247 DM_COOKIE_ENV_VAR_NAME, cookie);
3248 *envpp++ = udev_cookie;
3249 }
3250 if (need_resize_uevent) {
3251 *envpp++ = "RESIZE=1";
3252 }
3253
3254 noio_flag = memalloc_noio_save();
3255
3256 r = kobject_uevent_env(&disk_to_dev(md->disk)->kobj, action, envp);
3257
3258 memalloc_noio_restore(noio_flag);
3259
3260 return r;
3261 }
3262
dm_next_uevent_seq(struct mapped_device * md)3263 uint32_t dm_next_uevent_seq(struct mapped_device *md)
3264 {
3265 return atomic_add_return(1, &md->uevent_seq);
3266 }
3267
dm_get_event_nr(struct mapped_device * md)3268 uint32_t dm_get_event_nr(struct mapped_device *md)
3269 {
3270 return atomic_read(&md->event_nr);
3271 }
3272
dm_wait_event(struct mapped_device * md,int event_nr)3273 int dm_wait_event(struct mapped_device *md, int event_nr)
3274 {
3275 return wait_event_interruptible(md->eventq,
3276 (event_nr != atomic_read(&md->event_nr)));
3277 }
3278
dm_uevent_add(struct mapped_device * md,struct list_head * elist)3279 void dm_uevent_add(struct mapped_device *md, struct list_head *elist)
3280 {
3281 unsigned long flags;
3282
3283 spin_lock_irqsave(&md->uevent_lock, flags);
3284 list_add(elist, &md->uevent_list);
3285 spin_unlock_irqrestore(&md->uevent_lock, flags);
3286 }
3287
3288 /*
3289 * The gendisk is only valid as long as you have a reference
3290 * count on 'md'.
3291 */
dm_disk(struct mapped_device * md)3292 struct gendisk *dm_disk(struct mapped_device *md)
3293 {
3294 return md->disk;
3295 }
3296 EXPORT_SYMBOL_GPL(dm_disk);
3297
dm_kobject(struct mapped_device * md)3298 struct kobject *dm_kobject(struct mapped_device *md)
3299 {
3300 return &md->kobj_holder.kobj;
3301 }
3302
dm_get_from_kobject(struct kobject * kobj)3303 struct mapped_device *dm_get_from_kobject(struct kobject *kobj)
3304 {
3305 struct mapped_device *md;
3306
3307 md = container_of(kobj, struct mapped_device, kobj_holder.kobj);
3308
3309 spin_lock(&_minor_lock);
3310 if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) {
3311 md = NULL;
3312 goto out;
3313 }
3314 dm_get(md);
3315 out:
3316 spin_unlock(&_minor_lock);
3317
3318 return md;
3319 }
3320
dm_suspended_md(struct mapped_device * md)3321 int dm_suspended_md(struct mapped_device *md)
3322 {
3323 return test_bit(DMF_SUSPENDED, &md->flags);
3324 }
3325
dm_post_suspending_md(struct mapped_device * md)3326 static int dm_post_suspending_md(struct mapped_device *md)
3327 {
3328 return test_bit(DMF_POST_SUSPENDING, &md->flags);
3329 }
3330
dm_suspended_internally_md(struct mapped_device * md)3331 int dm_suspended_internally_md(struct mapped_device *md)
3332 {
3333 return test_bit(DMF_SUSPENDED_INTERNALLY, &md->flags);
3334 }
3335
dm_test_deferred_remove_flag(struct mapped_device * md)3336 int dm_test_deferred_remove_flag(struct mapped_device *md)
3337 {
3338 return test_bit(DMF_DEFERRED_REMOVE, &md->flags);
3339 }
3340
dm_suspended(struct dm_target * ti)3341 int dm_suspended(struct dm_target *ti)
3342 {
3343 return dm_suspended_md(ti->table->md);
3344 }
3345 EXPORT_SYMBOL_GPL(dm_suspended);
3346
dm_post_suspending(struct dm_target * ti)3347 int dm_post_suspending(struct dm_target *ti)
3348 {
3349 return dm_post_suspending_md(ti->table->md);
3350 }
3351 EXPORT_SYMBOL_GPL(dm_post_suspending);
3352
dm_noflush_suspending(struct dm_target * ti)3353 int dm_noflush_suspending(struct dm_target *ti)
3354 {
3355 return __noflush_suspending(ti->table->md);
3356 }
3357 EXPORT_SYMBOL_GPL(dm_noflush_suspending);
3358
dm_free_md_mempools(struct dm_md_mempools * pools)3359 void dm_free_md_mempools(struct dm_md_mempools *pools)
3360 {
3361 if (!pools)
3362 return;
3363
3364 bioset_exit(&pools->bs);
3365 bioset_exit(&pools->io_bs);
3366
3367 kfree(pools);
3368 }
3369
3370 struct dm_blkdev_id {
3371 u8 *id;
3372 enum blk_unique_id type;
3373 };
3374
__dm_get_unique_id(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3375 static int __dm_get_unique_id(struct dm_target *ti, struct dm_dev *dev,
3376 sector_t start, sector_t len, void *data)
3377 {
3378 struct dm_blkdev_id *dm_id = data;
3379 const struct block_device_operations *fops = dev->bdev->bd_disk->fops;
3380
3381 if (!fops->get_unique_id)
3382 return 0;
3383
3384 return fops->get_unique_id(dev->bdev->bd_disk, dm_id->id, dm_id->type);
3385 }
3386
3387 /*
3388 * Allow access to get_unique_id() for the first device returning a
3389 * non-zero result. Reasonable use expects all devices to have the
3390 * same unique id.
3391 */
dm_blk_get_unique_id(struct gendisk * disk,u8 * id,enum blk_unique_id type)3392 static int dm_blk_get_unique_id(struct gendisk *disk, u8 *id,
3393 enum blk_unique_id type)
3394 {
3395 struct mapped_device *md = disk->private_data;
3396 struct dm_table *table;
3397 struct dm_target *ti;
3398 int ret = 0, srcu_idx;
3399
3400 struct dm_blkdev_id dm_id = {
3401 .id = id,
3402 .type = type,
3403 };
3404
3405 table = dm_get_live_table(md, &srcu_idx);
3406 if (!table || !dm_table_get_size(table))
3407 goto out;
3408
3409 /* We only support devices that have a single target */
3410 if (table->num_targets != 1)
3411 goto out;
3412 ti = dm_table_get_target(table, 0);
3413
3414 if (!ti->type->iterate_devices)
3415 goto out;
3416
3417 ret = ti->type->iterate_devices(ti, __dm_get_unique_id, &dm_id);
3418 out:
3419 dm_put_live_table(md, srcu_idx);
3420 return ret;
3421 }
3422
3423 struct dm_pr {
3424 u64 old_key;
3425 u64 new_key;
3426 u32 flags;
3427 bool abort;
3428 bool fail_early;
3429 int ret;
3430 enum pr_type type;
3431 struct pr_keys *read_keys;
3432 struct pr_held_reservation *rsv;
3433 };
3434
dm_call_pr(struct block_device * bdev,iterate_devices_callout_fn fn,struct dm_pr * pr)3435 static int dm_call_pr(struct block_device *bdev, iterate_devices_callout_fn fn,
3436 struct dm_pr *pr)
3437 {
3438 struct mapped_device *md = bdev->bd_disk->private_data;
3439 struct dm_table *table;
3440 struct dm_target *ti;
3441 int ret = -ENOTTY, srcu_idx;
3442
3443 table = dm_get_live_table(md, &srcu_idx);
3444 if (!table || !dm_table_get_size(table))
3445 goto out;
3446
3447 /* We only support devices that have a single target */
3448 if (table->num_targets != 1)
3449 goto out;
3450 ti = dm_table_get_target(table, 0);
3451
3452 if (dm_suspended_md(md)) {
3453 ret = -EAGAIN;
3454 goto out;
3455 }
3456
3457 ret = -EINVAL;
3458 if (!ti->type->iterate_devices)
3459 goto out;
3460
3461 ti->type->iterate_devices(ti, fn, pr);
3462 ret = 0;
3463 out:
3464 dm_put_live_table(md, srcu_idx);
3465 return ret;
3466 }
3467
3468 /*
3469 * For register / unregister we need to manually call out to every path.
3470 */
__dm_pr_register(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3471 static int __dm_pr_register(struct dm_target *ti, struct dm_dev *dev,
3472 sector_t start, sector_t len, void *data)
3473 {
3474 struct dm_pr *pr = data;
3475 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3476 int ret;
3477
3478 if (!ops || !ops->pr_register) {
3479 pr->ret = -EOPNOTSUPP;
3480 return -1;
3481 }
3482
3483 ret = ops->pr_register(dev->bdev, pr->old_key, pr->new_key, pr->flags);
3484 if (!ret)
3485 return 0;
3486
3487 if (!pr->ret)
3488 pr->ret = ret;
3489
3490 if (pr->fail_early)
3491 return -1;
3492
3493 return 0;
3494 }
3495
dm_pr_register(struct block_device * bdev,u64 old_key,u64 new_key,u32 flags)3496 static int dm_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
3497 u32 flags)
3498 {
3499 struct dm_pr pr = {
3500 .old_key = old_key,
3501 .new_key = new_key,
3502 .flags = flags,
3503 .fail_early = true,
3504 .ret = 0,
3505 };
3506 int ret;
3507
3508 ret = dm_call_pr(bdev, __dm_pr_register, &pr);
3509 if (ret) {
3510 /* Didn't even get to register a path */
3511 return ret;
3512 }
3513
3514 if (!pr.ret)
3515 return 0;
3516 ret = pr.ret;
3517
3518 if (!new_key)
3519 return ret;
3520
3521 /* unregister all paths if we failed to register any path */
3522 pr.old_key = new_key;
3523 pr.new_key = 0;
3524 pr.flags = 0;
3525 pr.fail_early = false;
3526 (void) dm_call_pr(bdev, __dm_pr_register, &pr);
3527 return ret;
3528 }
3529
3530
__dm_pr_reserve(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3531 static int __dm_pr_reserve(struct dm_target *ti, struct dm_dev *dev,
3532 sector_t start, sector_t len, void *data)
3533 {
3534 struct dm_pr *pr = data;
3535 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3536
3537 if (!ops || !ops->pr_reserve) {
3538 pr->ret = -EOPNOTSUPP;
3539 return -1;
3540 }
3541
3542 pr->ret = ops->pr_reserve(dev->bdev, pr->old_key, pr->type, pr->flags);
3543 if (!pr->ret)
3544 return -1;
3545
3546 return 0;
3547 }
3548
dm_pr_reserve(struct block_device * bdev,u64 key,enum pr_type type,u32 flags)3549 static int dm_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
3550 u32 flags)
3551 {
3552 struct dm_pr pr = {
3553 .old_key = key,
3554 .flags = flags,
3555 .type = type,
3556 .fail_early = false,
3557 .ret = 0,
3558 };
3559 int ret;
3560
3561 ret = dm_call_pr(bdev, __dm_pr_reserve, &pr);
3562 if (ret)
3563 return ret;
3564
3565 return pr.ret;
3566 }
3567
3568 /*
3569 * If there is a non-All Registrants type of reservation, the release must be
3570 * sent down the holding path. For the cases where there is no reservation or
3571 * the path is not the holder the device will also return success, so we must
3572 * try each path to make sure we got the correct path.
3573 */
__dm_pr_release(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3574 static int __dm_pr_release(struct dm_target *ti, struct dm_dev *dev,
3575 sector_t start, sector_t len, void *data)
3576 {
3577 struct dm_pr *pr = data;
3578 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3579
3580 if (!ops || !ops->pr_release) {
3581 pr->ret = -EOPNOTSUPP;
3582 return -1;
3583 }
3584
3585 pr->ret = ops->pr_release(dev->bdev, pr->old_key, pr->type);
3586 if (pr->ret)
3587 return -1;
3588
3589 return 0;
3590 }
3591
dm_pr_release(struct block_device * bdev,u64 key,enum pr_type type)3592 static int dm_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
3593 {
3594 struct dm_pr pr = {
3595 .old_key = key,
3596 .type = type,
3597 .fail_early = false,
3598 };
3599 int ret;
3600
3601 ret = dm_call_pr(bdev, __dm_pr_release, &pr);
3602 if (ret)
3603 return ret;
3604
3605 return pr.ret;
3606 }
3607
__dm_pr_preempt(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3608 static int __dm_pr_preempt(struct dm_target *ti, struct dm_dev *dev,
3609 sector_t start, sector_t len, void *data)
3610 {
3611 struct dm_pr *pr = data;
3612 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3613
3614 if (!ops || !ops->pr_preempt) {
3615 pr->ret = -EOPNOTSUPP;
3616 return -1;
3617 }
3618
3619 pr->ret = ops->pr_preempt(dev->bdev, pr->old_key, pr->new_key, pr->type,
3620 pr->abort);
3621 if (!pr->ret)
3622 return -1;
3623
3624 return 0;
3625 }
3626
dm_pr_preempt(struct block_device * bdev,u64 old_key,u64 new_key,enum pr_type type,bool abort)3627 static int dm_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
3628 enum pr_type type, bool abort)
3629 {
3630 struct dm_pr pr = {
3631 .new_key = new_key,
3632 .old_key = old_key,
3633 .type = type,
3634 .fail_early = false,
3635 };
3636 int ret;
3637
3638 ret = dm_call_pr(bdev, __dm_pr_preempt, &pr);
3639 if (ret)
3640 return ret;
3641
3642 return pr.ret;
3643 }
3644
dm_pr_clear(struct block_device * bdev,u64 key)3645 static int dm_pr_clear(struct block_device *bdev, u64 key)
3646 {
3647 struct mapped_device *md = bdev->bd_disk->private_data;
3648 const struct pr_ops *ops;
3649 int r, srcu_idx;
3650 bool forward = true;
3651
3652 /* Not a real ioctl, but targets must not interpret non-DM ioctls */
3653 r = dm_prepare_ioctl(md, &srcu_idx, &bdev, 0, 0, &forward);
3654 if (r < 0)
3655 goto out;
3656 WARN_ON_ONCE(!forward);
3657
3658 ops = bdev->bd_disk->fops->pr_ops;
3659 if (ops && ops->pr_clear)
3660 r = ops->pr_clear(bdev, key);
3661 else
3662 r = -EOPNOTSUPP;
3663 out:
3664 dm_unprepare_ioctl(md, srcu_idx);
3665 return r;
3666 }
3667
__dm_pr_read_keys(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3668 static int __dm_pr_read_keys(struct dm_target *ti, struct dm_dev *dev,
3669 sector_t start, sector_t len, void *data)
3670 {
3671 struct dm_pr *pr = data;
3672 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3673
3674 if (!ops || !ops->pr_read_keys) {
3675 pr->ret = -EOPNOTSUPP;
3676 return -1;
3677 }
3678
3679 pr->ret = ops->pr_read_keys(dev->bdev, pr->read_keys);
3680 if (!pr->ret)
3681 return -1;
3682
3683 return 0;
3684 }
3685
dm_pr_read_keys(struct block_device * bdev,struct pr_keys * keys)3686 static int dm_pr_read_keys(struct block_device *bdev, struct pr_keys *keys)
3687 {
3688 struct dm_pr pr = {
3689 .read_keys = keys,
3690 };
3691 int ret;
3692
3693 ret = dm_call_pr(bdev, __dm_pr_read_keys, &pr);
3694 if (ret)
3695 return ret;
3696
3697 return pr.ret;
3698 }
3699
__dm_pr_read_reservation(struct dm_target * ti,struct dm_dev * dev,sector_t start,sector_t len,void * data)3700 static int __dm_pr_read_reservation(struct dm_target *ti, struct dm_dev *dev,
3701 sector_t start, sector_t len, void *data)
3702 {
3703 struct dm_pr *pr = data;
3704 const struct pr_ops *ops = dev->bdev->bd_disk->fops->pr_ops;
3705
3706 if (!ops || !ops->pr_read_reservation) {
3707 pr->ret = -EOPNOTSUPP;
3708 return -1;
3709 }
3710
3711 pr->ret = ops->pr_read_reservation(dev->bdev, pr->rsv);
3712 if (!pr->ret)
3713 return -1;
3714
3715 return 0;
3716 }
3717
dm_pr_read_reservation(struct block_device * bdev,struct pr_held_reservation * rsv)3718 static int dm_pr_read_reservation(struct block_device *bdev,
3719 struct pr_held_reservation *rsv)
3720 {
3721 struct dm_pr pr = {
3722 .rsv = rsv,
3723 };
3724 int ret;
3725
3726 ret = dm_call_pr(bdev, __dm_pr_read_reservation, &pr);
3727 if (ret)
3728 return ret;
3729
3730 return pr.ret;
3731 }
3732
3733 static const struct pr_ops dm_pr_ops = {
3734 .pr_register = dm_pr_register,
3735 .pr_reserve = dm_pr_reserve,
3736 .pr_release = dm_pr_release,
3737 .pr_preempt = dm_pr_preempt,
3738 .pr_clear = dm_pr_clear,
3739 .pr_read_keys = dm_pr_read_keys,
3740 .pr_read_reservation = dm_pr_read_reservation,
3741 };
3742
3743 static const struct block_device_operations dm_blk_dops = {
3744 .submit_bio = dm_submit_bio,
3745 .poll_bio = dm_poll_bio,
3746 .open = dm_blk_open,
3747 .release = dm_blk_close,
3748 .ioctl = dm_blk_ioctl,
3749 .getgeo = dm_blk_getgeo,
3750 .report_zones = dm_blk_report_zones,
3751 .get_unique_id = dm_blk_get_unique_id,
3752 .pr_ops = &dm_pr_ops,
3753 .owner = THIS_MODULE
3754 };
3755
3756 static const struct block_device_operations dm_rq_blk_dops = {
3757 .open = dm_blk_open,
3758 .release = dm_blk_close,
3759 .ioctl = dm_blk_ioctl,
3760 .getgeo = dm_blk_getgeo,
3761 .get_unique_id = dm_blk_get_unique_id,
3762 .pr_ops = &dm_pr_ops,
3763 .owner = THIS_MODULE
3764 };
3765
3766 static const struct dax_operations dm_dax_ops = {
3767 .direct_access = dm_dax_direct_access,
3768 .zero_page_range = dm_dax_zero_page_range,
3769 .recovery_write = dm_dax_recovery_write,
3770 };
3771
3772 /*
3773 * module hooks
3774 */
3775 module_init(dm_init);
3776 module_exit(dm_exit);
3777
3778 module_param(major, uint, 0);
3779 MODULE_PARM_DESC(major, "The major number of the device mapper");
3780
3781 module_param(reserved_bio_based_ios, uint, 0644);
3782 MODULE_PARM_DESC(reserved_bio_based_ios, "Reserved IOs in bio-based mempools");
3783
3784 module_param(dm_numa_node, int, 0644);
3785 MODULE_PARM_DESC(dm_numa_node, "NUMA node for DM device memory allocations");
3786
3787 module_param(swap_bios, int, 0644);
3788 MODULE_PARM_DESC(swap_bios, "Maximum allowed inflight swap IOs");
3789
3790 MODULE_DESCRIPTION(DM_NAME " driver");
3791 MODULE_AUTHOR("Joe Thornber <dm-devel@lists.linux.dev>");
3792 MODULE_LICENSE("GPL");
3793