dm: add missing SPDX-License-Indentifiers
[platform/kernel/linux-starfive.git] / drivers / md / dm-mpath.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2003 Sistina Software Limited.
4  * Copyright (C) 2004-2005 Red Hat, Inc. All rights reserved.
5  *
6  * This file is released under the GPL.
7  */
8
9 #include <linux/device-mapper.h>
10
11 #include "dm-rq.h"
12 #include "dm-bio-record.h"
13 #include "dm-path-selector.h"
14 #include "dm-uevent.h"
15
16 #include <linux/blkdev.h>
17 #include <linux/ctype.h>
18 #include <linux/init.h>
19 #include <linux/mempool.h>
20 #include <linux/module.h>
21 #include <linux/pagemap.h>
22 #include <linux/slab.h>
23 #include <linux/time.h>
24 #include <linux/timer.h>
25 #include <linux/workqueue.h>
26 #include <linux/delay.h>
27 #include <scsi/scsi_dh.h>
28 #include <linux/atomic.h>
29 #include <linux/blk-mq.h>
30
31 #define DM_MSG_PREFIX "multipath"
32 #define DM_PG_INIT_DELAY_MSECS 2000
33 #define DM_PG_INIT_DELAY_DEFAULT ((unsigned) -1)
34 #define QUEUE_IF_NO_PATH_TIMEOUT_DEFAULT 0
35
36 static unsigned long queue_if_no_path_timeout_secs = QUEUE_IF_NO_PATH_TIMEOUT_DEFAULT;
37
38 /* Path properties */
39 struct pgpath {
40         struct list_head list;
41
42         struct priority_group *pg;      /* Owning PG */
43         unsigned fail_count;            /* Cumulative failure count */
44
45         struct dm_path path;
46         struct delayed_work activate_path;
47
48         bool is_active:1;               /* Path status */
49 };
50
51 #define path_to_pgpath(__pgp) container_of((__pgp), struct pgpath, path)
52
53 /*
54  * Paths are grouped into Priority Groups and numbered from 1 upwards.
55  * Each has a path selector which controls which path gets used.
56  */
57 struct priority_group {
58         struct list_head list;
59
60         struct multipath *m;            /* Owning multipath instance */
61         struct path_selector ps;
62
63         unsigned pg_num;                /* Reference number */
64         unsigned nr_pgpaths;            /* Number of paths in PG */
65         struct list_head pgpaths;
66
67         bool bypassed:1;                /* Temporarily bypass this PG? */
68 };
69
70 /* Multipath context */
71 struct multipath {
72         unsigned long flags;            /* Multipath state flags */
73
74         spinlock_t lock;
75         enum dm_queue_mode queue_mode;
76
77         struct pgpath *current_pgpath;
78         struct priority_group *current_pg;
79         struct priority_group *next_pg; /* Switch to this PG if set */
80
81         atomic_t nr_valid_paths;        /* Total number of usable paths */
82         unsigned nr_priority_groups;
83         struct list_head priority_groups;
84
85         const char *hw_handler_name;
86         char *hw_handler_params;
87         wait_queue_head_t pg_init_wait; /* Wait for pg_init completion */
88         unsigned pg_init_retries;       /* Number of times to retry pg_init */
89         unsigned pg_init_delay_msecs;   /* Number of msecs before pg_init retry */
90         atomic_t pg_init_in_progress;   /* Only one pg_init allowed at once */
91         atomic_t pg_init_count;         /* Number of times pg_init called */
92
93         struct mutex work_mutex;
94         struct work_struct trigger_event;
95         struct dm_target *ti;
96
97         struct work_struct process_queued_bios;
98         struct bio_list queued_bios;
99
100         struct timer_list nopath_timer; /* Timeout for queue_if_no_path */
101 };
102
103 /*
104  * Context information attached to each io we process.
105  */
106 struct dm_mpath_io {
107         struct pgpath *pgpath;
108         size_t nr_bytes;
109         u64 start_time_ns;
110 };
111
112 typedef int (*action_fn) (struct pgpath *pgpath);
113
114 static struct workqueue_struct *kmultipathd, *kmpath_handlerd;
115 static void trigger_event(struct work_struct *work);
116 static void activate_or_offline_path(struct pgpath *pgpath);
117 static void activate_path_work(struct work_struct *work);
118 static void process_queued_bios(struct work_struct *work);
119 static void queue_if_no_path_timeout_work(struct timer_list *t);
120
121 /*-----------------------------------------------
122  * Multipath state flags.
123  *-----------------------------------------------*/
124
125 #define MPATHF_QUEUE_IO 0                       /* Must we queue all I/O? */
126 #define MPATHF_QUEUE_IF_NO_PATH 1               /* Queue I/O if last path fails? */
127 #define MPATHF_SAVED_QUEUE_IF_NO_PATH 2         /* Saved state during suspension */
128 #define MPATHF_RETAIN_ATTACHED_HW_HANDLER 3     /* If there's already a hw_handler present, don't change it. */
129 #define MPATHF_PG_INIT_DISABLED 4               /* pg_init is not currently allowed */
130 #define MPATHF_PG_INIT_REQUIRED 5               /* pg_init needs calling? */
131 #define MPATHF_PG_INIT_DELAY_RETRY 6            /* Delay pg_init retry? */
132
133 static bool mpath_double_check_test_bit(int MPATHF_bit, struct multipath *m)
134 {
135         bool r = test_bit(MPATHF_bit, &m->flags);
136
137         if (r) {
138                 unsigned long flags;
139                 spin_lock_irqsave(&m->lock, flags);
140                 r = test_bit(MPATHF_bit, &m->flags);
141                 spin_unlock_irqrestore(&m->lock, flags);
142         }
143
144         return r;
145 }
146
147 /*-----------------------------------------------
148  * Allocation routines
149  *-----------------------------------------------*/
150
151 static struct pgpath *alloc_pgpath(void)
152 {
153         struct pgpath *pgpath = kzalloc(sizeof(*pgpath), GFP_KERNEL);
154
155         if (!pgpath)
156                 return NULL;
157
158         pgpath->is_active = true;
159
160         return pgpath;
161 }
162
163 static void free_pgpath(struct pgpath *pgpath)
164 {
165         kfree(pgpath);
166 }
167
168 static struct priority_group *alloc_priority_group(void)
169 {
170         struct priority_group *pg;
171
172         pg = kzalloc(sizeof(*pg), GFP_KERNEL);
173
174         if (pg)
175                 INIT_LIST_HEAD(&pg->pgpaths);
176
177         return pg;
178 }
179
180 static void free_pgpaths(struct list_head *pgpaths, struct dm_target *ti)
181 {
182         struct pgpath *pgpath, *tmp;
183
184         list_for_each_entry_safe(pgpath, tmp, pgpaths, list) {
185                 list_del(&pgpath->list);
186                 dm_put_device(ti, pgpath->path.dev);
187                 free_pgpath(pgpath);
188         }
189 }
190
191 static void free_priority_group(struct priority_group *pg,
192                                 struct dm_target *ti)
193 {
194         struct path_selector *ps = &pg->ps;
195
196         if (ps->type) {
197                 ps->type->destroy(ps);
198                 dm_put_path_selector(ps->type);
199         }
200
201         free_pgpaths(&pg->pgpaths, ti);
202         kfree(pg);
203 }
204
205 static struct multipath *alloc_multipath(struct dm_target *ti)
206 {
207         struct multipath *m;
208
209         m = kzalloc(sizeof(*m), GFP_KERNEL);
210         if (m) {
211                 INIT_LIST_HEAD(&m->priority_groups);
212                 spin_lock_init(&m->lock);
213                 atomic_set(&m->nr_valid_paths, 0);
214                 INIT_WORK(&m->trigger_event, trigger_event);
215                 mutex_init(&m->work_mutex);
216
217                 m->queue_mode = DM_TYPE_NONE;
218
219                 m->ti = ti;
220                 ti->private = m;
221
222                 timer_setup(&m->nopath_timer, queue_if_no_path_timeout_work, 0);
223         }
224
225         return m;
226 }
227
228 static int alloc_multipath_stage2(struct dm_target *ti, struct multipath *m)
229 {
230         if (m->queue_mode == DM_TYPE_NONE) {
231                 m->queue_mode = DM_TYPE_REQUEST_BASED;
232         } else if (m->queue_mode == DM_TYPE_BIO_BASED) {
233                 INIT_WORK(&m->process_queued_bios, process_queued_bios);
234                 /*
235                  * bio-based doesn't support any direct scsi_dh management;
236                  * it just discovers if a scsi_dh is attached.
237                  */
238                 set_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags);
239         }
240
241         dm_table_set_type(ti->table, m->queue_mode);
242
243         /*
244          * Init fields that are only used when a scsi_dh is attached
245          * - must do this unconditionally (really doesn't hurt non-SCSI uses)
246          */
247         set_bit(MPATHF_QUEUE_IO, &m->flags);
248         atomic_set(&m->pg_init_in_progress, 0);
249         atomic_set(&m->pg_init_count, 0);
250         m->pg_init_delay_msecs = DM_PG_INIT_DELAY_DEFAULT;
251         init_waitqueue_head(&m->pg_init_wait);
252
253         return 0;
254 }
255
256 static void free_multipath(struct multipath *m)
257 {
258         struct priority_group *pg, *tmp;
259
260         list_for_each_entry_safe(pg, tmp, &m->priority_groups, list) {
261                 list_del(&pg->list);
262                 free_priority_group(pg, m->ti);
263         }
264
265         kfree(m->hw_handler_name);
266         kfree(m->hw_handler_params);
267         mutex_destroy(&m->work_mutex);
268         kfree(m);
269 }
270
271 static struct dm_mpath_io *get_mpio(union map_info *info)
272 {
273         return info->ptr;
274 }
275
276 static size_t multipath_per_bio_data_size(void)
277 {
278         return sizeof(struct dm_mpath_io) + sizeof(struct dm_bio_details);
279 }
280
281 static struct dm_mpath_io *get_mpio_from_bio(struct bio *bio)
282 {
283         return dm_per_bio_data(bio, multipath_per_bio_data_size());
284 }
285
286 static struct dm_bio_details *get_bio_details_from_mpio(struct dm_mpath_io *mpio)
287 {
288         /* dm_bio_details is immediately after the dm_mpath_io in bio's per-bio-data */
289         void *bio_details = mpio + 1;
290         return bio_details;
291 }
292
293 static void multipath_init_per_bio_data(struct bio *bio, struct dm_mpath_io **mpio_p)
294 {
295         struct dm_mpath_io *mpio = get_mpio_from_bio(bio);
296         struct dm_bio_details *bio_details = get_bio_details_from_mpio(mpio);
297
298         mpio->nr_bytes = bio->bi_iter.bi_size;
299         mpio->pgpath = NULL;
300         mpio->start_time_ns = 0;
301         *mpio_p = mpio;
302
303         dm_bio_record(bio_details, bio);
304 }
305
306 /*-----------------------------------------------
307  * Path selection
308  *-----------------------------------------------*/
309
310 static int __pg_init_all_paths(struct multipath *m)
311 {
312         struct pgpath *pgpath;
313         unsigned long pg_init_delay = 0;
314
315         lockdep_assert_held(&m->lock);
316
317         if (atomic_read(&m->pg_init_in_progress) || test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
318                 return 0;
319
320         atomic_inc(&m->pg_init_count);
321         clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
322
323         /* Check here to reset pg_init_required */
324         if (!m->current_pg)
325                 return 0;
326
327         if (test_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags))
328                 pg_init_delay = msecs_to_jiffies(m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT ?
329                                                  m->pg_init_delay_msecs : DM_PG_INIT_DELAY_MSECS);
330         list_for_each_entry(pgpath, &m->current_pg->pgpaths, list) {
331                 /* Skip failed paths */
332                 if (!pgpath->is_active)
333                         continue;
334                 if (queue_delayed_work(kmpath_handlerd, &pgpath->activate_path,
335                                        pg_init_delay))
336                         atomic_inc(&m->pg_init_in_progress);
337         }
338         return atomic_read(&m->pg_init_in_progress);
339 }
340
341 static int pg_init_all_paths(struct multipath *m)
342 {
343         int ret;
344         unsigned long flags;
345
346         spin_lock_irqsave(&m->lock, flags);
347         ret = __pg_init_all_paths(m);
348         spin_unlock_irqrestore(&m->lock, flags);
349
350         return ret;
351 }
352
353 static void __switch_pg(struct multipath *m, struct priority_group *pg)
354 {
355         lockdep_assert_held(&m->lock);
356
357         m->current_pg = pg;
358
359         /* Must we initialise the PG first, and queue I/O till it's ready? */
360         if (m->hw_handler_name) {
361                 set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
362                 set_bit(MPATHF_QUEUE_IO, &m->flags);
363         } else {
364                 clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
365                 clear_bit(MPATHF_QUEUE_IO, &m->flags);
366         }
367
368         atomic_set(&m->pg_init_count, 0);
369 }
370
371 static struct pgpath *choose_path_in_pg(struct multipath *m,
372                                         struct priority_group *pg,
373                                         size_t nr_bytes)
374 {
375         unsigned long flags;
376         struct dm_path *path;
377         struct pgpath *pgpath;
378
379         path = pg->ps.type->select_path(&pg->ps, nr_bytes);
380         if (!path)
381                 return ERR_PTR(-ENXIO);
382
383         pgpath = path_to_pgpath(path);
384
385         if (unlikely(READ_ONCE(m->current_pg) != pg)) {
386                 /* Only update current_pgpath if pg changed */
387                 spin_lock_irqsave(&m->lock, flags);
388                 m->current_pgpath = pgpath;
389                 __switch_pg(m, pg);
390                 spin_unlock_irqrestore(&m->lock, flags);
391         }
392
393         return pgpath;
394 }
395
396 static struct pgpath *choose_pgpath(struct multipath *m, size_t nr_bytes)
397 {
398         unsigned long flags;
399         struct priority_group *pg;
400         struct pgpath *pgpath;
401         unsigned bypassed = 1;
402
403         if (!atomic_read(&m->nr_valid_paths)) {
404                 spin_lock_irqsave(&m->lock, flags);
405                 clear_bit(MPATHF_QUEUE_IO, &m->flags);
406                 spin_unlock_irqrestore(&m->lock, flags);
407                 goto failed;
408         }
409
410         /* Were we instructed to switch PG? */
411         if (READ_ONCE(m->next_pg)) {
412                 spin_lock_irqsave(&m->lock, flags);
413                 pg = m->next_pg;
414                 if (!pg) {
415                         spin_unlock_irqrestore(&m->lock, flags);
416                         goto check_current_pg;
417                 }
418                 m->next_pg = NULL;
419                 spin_unlock_irqrestore(&m->lock, flags);
420                 pgpath = choose_path_in_pg(m, pg, nr_bytes);
421                 if (!IS_ERR_OR_NULL(pgpath))
422                         return pgpath;
423         }
424
425         /* Don't change PG until it has no remaining paths */
426 check_current_pg:
427         pg = READ_ONCE(m->current_pg);
428         if (pg) {
429                 pgpath = choose_path_in_pg(m, pg, nr_bytes);
430                 if (!IS_ERR_OR_NULL(pgpath))
431                         return pgpath;
432         }
433
434         /*
435          * Loop through priority groups until we find a valid path.
436          * First time we skip PGs marked 'bypassed'.
437          * Second time we only try the ones we skipped, but set
438          * pg_init_delay_retry so we do not hammer controllers.
439          */
440         do {
441                 list_for_each_entry(pg, &m->priority_groups, list) {
442                         if (pg->bypassed == !!bypassed)
443                                 continue;
444                         pgpath = choose_path_in_pg(m, pg, nr_bytes);
445                         if (!IS_ERR_OR_NULL(pgpath)) {
446                                 if (!bypassed) {
447                                         spin_lock_irqsave(&m->lock, flags);
448                                         set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
449                                         spin_unlock_irqrestore(&m->lock, flags);
450                                 }
451                                 return pgpath;
452                         }
453                 }
454         } while (bypassed--);
455
456 failed:
457         spin_lock_irqsave(&m->lock, flags);
458         m->current_pgpath = NULL;
459         m->current_pg = NULL;
460         spin_unlock_irqrestore(&m->lock, flags);
461
462         return NULL;
463 }
464
465 /*
466  * dm_report_EIO() is a macro instead of a function to make pr_debug_ratelimited()
467  * report the function name and line number of the function from which
468  * it has been invoked.
469  */
470 #define dm_report_EIO(m)                                                \
471 do {                                                                    \
472         DMDEBUG_LIMIT("%s: returning EIO; QIFNP = %d; SQIFNP = %d; DNFS = %d", \
473                       dm_table_device_name((m)->ti->table),             \
474                       test_bit(MPATHF_QUEUE_IF_NO_PATH, &(m)->flags),   \
475                       test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &(m)->flags), \
476                       dm_noflush_suspending((m)->ti));                  \
477 } while (0)
478
479 /*
480  * Check whether bios must be queued in the device-mapper core rather
481  * than here in the target.
482  */
483 static bool __must_push_back(struct multipath *m)
484 {
485         return dm_noflush_suspending(m->ti);
486 }
487
488 static bool must_push_back_rq(struct multipath *m)
489 {
490         unsigned long flags;
491         bool ret;
492
493         spin_lock_irqsave(&m->lock, flags);
494         ret = (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) || __must_push_back(m));
495         spin_unlock_irqrestore(&m->lock, flags);
496
497         return ret;
498 }
499
500 /*
501  * Map cloned requests (request-based multipath)
502  */
503 static int multipath_clone_and_map(struct dm_target *ti, struct request *rq,
504                                    union map_info *map_context,
505                                    struct request **__clone)
506 {
507         struct multipath *m = ti->private;
508         size_t nr_bytes = blk_rq_bytes(rq);
509         struct pgpath *pgpath;
510         struct block_device *bdev;
511         struct dm_mpath_io *mpio = get_mpio(map_context);
512         struct request_queue *q;
513         struct request *clone;
514
515         /* Do we need to select a new pgpath? */
516         pgpath = READ_ONCE(m->current_pgpath);
517         if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
518                 pgpath = choose_pgpath(m, nr_bytes);
519
520         if (!pgpath) {
521                 if (must_push_back_rq(m))
522                         return DM_MAPIO_DELAY_REQUEUE;
523                 dm_report_EIO(m);       /* Failed */
524                 return DM_MAPIO_KILL;
525         } else if (mpath_double_check_test_bit(MPATHF_QUEUE_IO, m) ||
526                    mpath_double_check_test_bit(MPATHF_PG_INIT_REQUIRED, m)) {
527                 pg_init_all_paths(m);
528                 return DM_MAPIO_DELAY_REQUEUE;
529         }
530
531         mpio->pgpath = pgpath;
532         mpio->nr_bytes = nr_bytes;
533
534         bdev = pgpath->path.dev->bdev;
535         q = bdev_get_queue(bdev);
536         clone = blk_mq_alloc_request(q, rq->cmd_flags | REQ_NOMERGE,
537                         BLK_MQ_REQ_NOWAIT);
538         if (IS_ERR(clone)) {
539                 /* EBUSY, ENODEV or EWOULDBLOCK: requeue */
540                 if (blk_queue_dying(q)) {
541                         atomic_inc(&m->pg_init_in_progress);
542                         activate_or_offline_path(pgpath);
543                         return DM_MAPIO_DELAY_REQUEUE;
544                 }
545
546                 /*
547                  * blk-mq's SCHED_RESTART can cover this requeue, so we
548                  * needn't deal with it by DELAY_REQUEUE. More importantly,
549                  * we have to return DM_MAPIO_REQUEUE so that blk-mq can
550                  * get the queue busy feedback (via BLK_STS_RESOURCE),
551                  * otherwise I/O merging can suffer.
552                  */
553                 return DM_MAPIO_REQUEUE;
554         }
555         clone->bio = clone->biotail = NULL;
556         clone->cmd_flags |= REQ_FAILFAST_TRANSPORT;
557         *__clone = clone;
558
559         if (pgpath->pg->ps.type->start_io)
560                 pgpath->pg->ps.type->start_io(&pgpath->pg->ps,
561                                               &pgpath->path,
562                                               nr_bytes);
563         return DM_MAPIO_REMAPPED;
564 }
565
566 static void multipath_release_clone(struct request *clone,
567                                     union map_info *map_context)
568 {
569         if (unlikely(map_context)) {
570                 /*
571                  * non-NULL map_context means caller is still map
572                  * method; must undo multipath_clone_and_map()
573                  */
574                 struct dm_mpath_io *mpio = get_mpio(map_context);
575                 struct pgpath *pgpath = mpio->pgpath;
576
577                 if (pgpath && pgpath->pg->ps.type->end_io)
578                         pgpath->pg->ps.type->end_io(&pgpath->pg->ps,
579                                                     &pgpath->path,
580                                                     mpio->nr_bytes,
581                                                     clone->io_start_time_ns);
582         }
583
584         blk_mq_free_request(clone);
585 }
586
587 /*
588  * Map cloned bios (bio-based multipath)
589  */
590
591 static void __multipath_queue_bio(struct multipath *m, struct bio *bio)
592 {
593         /* Queue for the daemon to resubmit */
594         bio_list_add(&m->queued_bios, bio);
595         if (!test_bit(MPATHF_QUEUE_IO, &m->flags))
596                 queue_work(kmultipathd, &m->process_queued_bios);
597 }
598
599 static void multipath_queue_bio(struct multipath *m, struct bio *bio)
600 {
601         unsigned long flags;
602
603         spin_lock_irqsave(&m->lock, flags);
604         __multipath_queue_bio(m, bio);
605         spin_unlock_irqrestore(&m->lock, flags);
606 }
607
608 static struct pgpath *__map_bio(struct multipath *m, struct bio *bio)
609 {
610         struct pgpath *pgpath;
611         unsigned long flags;
612
613         /* Do we need to select a new pgpath? */
614         pgpath = READ_ONCE(m->current_pgpath);
615         if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
616                 pgpath = choose_pgpath(m, bio->bi_iter.bi_size);
617
618         if (!pgpath) {
619                 spin_lock_irqsave(&m->lock, flags);
620                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
621                         __multipath_queue_bio(m, bio);
622                         pgpath = ERR_PTR(-EAGAIN);
623                 }
624                 spin_unlock_irqrestore(&m->lock, flags);
625
626         } else if (mpath_double_check_test_bit(MPATHF_QUEUE_IO, m) ||
627                    mpath_double_check_test_bit(MPATHF_PG_INIT_REQUIRED, m)) {
628                 multipath_queue_bio(m, bio);
629                 pg_init_all_paths(m);
630                 return ERR_PTR(-EAGAIN);
631         }
632
633         return pgpath;
634 }
635
636 static int __multipath_map_bio(struct multipath *m, struct bio *bio,
637                                struct dm_mpath_io *mpio)
638 {
639         struct pgpath *pgpath = __map_bio(m, bio);
640
641         if (IS_ERR(pgpath))
642                 return DM_MAPIO_SUBMITTED;
643
644         if (!pgpath) {
645                 if (__must_push_back(m))
646                         return DM_MAPIO_REQUEUE;
647                 dm_report_EIO(m);
648                 return DM_MAPIO_KILL;
649         }
650
651         mpio->pgpath = pgpath;
652
653         if (dm_ps_use_hr_timer(pgpath->pg->ps.type))
654                 mpio->start_time_ns = ktime_get_ns();
655
656         bio->bi_status = 0;
657         bio_set_dev(bio, pgpath->path.dev->bdev);
658         bio->bi_opf |= REQ_FAILFAST_TRANSPORT;
659
660         if (pgpath->pg->ps.type->start_io)
661                 pgpath->pg->ps.type->start_io(&pgpath->pg->ps,
662                                               &pgpath->path,
663                                               mpio->nr_bytes);
664         return DM_MAPIO_REMAPPED;
665 }
666
667 static int multipath_map_bio(struct dm_target *ti, struct bio *bio)
668 {
669         struct multipath *m = ti->private;
670         struct dm_mpath_io *mpio = NULL;
671
672         multipath_init_per_bio_data(bio, &mpio);
673         return __multipath_map_bio(m, bio, mpio);
674 }
675
676 static void process_queued_io_list(struct multipath *m)
677 {
678         if (m->queue_mode == DM_TYPE_REQUEST_BASED)
679                 dm_mq_kick_requeue_list(dm_table_get_md(m->ti->table));
680         else if (m->queue_mode == DM_TYPE_BIO_BASED)
681                 queue_work(kmultipathd, &m->process_queued_bios);
682 }
683
684 static void process_queued_bios(struct work_struct *work)
685 {
686         int r;
687         unsigned long flags;
688         struct bio *bio;
689         struct bio_list bios;
690         struct blk_plug plug;
691         struct multipath *m =
692                 container_of(work, struct multipath, process_queued_bios);
693
694         bio_list_init(&bios);
695
696         spin_lock_irqsave(&m->lock, flags);
697
698         if (bio_list_empty(&m->queued_bios)) {
699                 spin_unlock_irqrestore(&m->lock, flags);
700                 return;
701         }
702
703         bio_list_merge(&bios, &m->queued_bios);
704         bio_list_init(&m->queued_bios);
705
706         spin_unlock_irqrestore(&m->lock, flags);
707
708         blk_start_plug(&plug);
709         while ((bio = bio_list_pop(&bios))) {
710                 struct dm_mpath_io *mpio = get_mpio_from_bio(bio);
711                 dm_bio_restore(get_bio_details_from_mpio(mpio), bio);
712                 r = __multipath_map_bio(m, bio, mpio);
713                 switch (r) {
714                 case DM_MAPIO_KILL:
715                         bio->bi_status = BLK_STS_IOERR;
716                         bio_endio(bio);
717                         break;
718                 case DM_MAPIO_REQUEUE:
719                         bio->bi_status = BLK_STS_DM_REQUEUE;
720                         bio_endio(bio);
721                         break;
722                 case DM_MAPIO_REMAPPED:
723                         submit_bio_noacct(bio);
724                         break;
725                 case DM_MAPIO_SUBMITTED:
726                         break;
727                 default:
728                         WARN_ONCE(true, "__multipath_map_bio() returned %d\n", r);
729                 }
730         }
731         blk_finish_plug(&plug);
732 }
733
734 /*
735  * If we run out of usable paths, should we queue I/O or error it?
736  */
737 static int queue_if_no_path(struct multipath *m, bool queue_if_no_path,
738                             bool save_old_value, const char *caller)
739 {
740         unsigned long flags;
741         bool queue_if_no_path_bit, saved_queue_if_no_path_bit;
742         const char *dm_dev_name = dm_table_device_name(m->ti->table);
743
744         DMDEBUG("%s: %s caller=%s queue_if_no_path=%d save_old_value=%d",
745                 dm_dev_name, __func__, caller, queue_if_no_path, save_old_value);
746
747         spin_lock_irqsave(&m->lock, flags);
748
749         queue_if_no_path_bit = test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
750         saved_queue_if_no_path_bit = test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
751
752         if (save_old_value) {
753                 if (unlikely(!queue_if_no_path_bit && saved_queue_if_no_path_bit)) {
754                         DMERR("%s: QIFNP disabled but saved as enabled, saving again loses state, not saving!",
755                               dm_dev_name);
756                 } else
757                         assign_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags, queue_if_no_path_bit);
758         } else if (!queue_if_no_path && saved_queue_if_no_path_bit) {
759                 /* due to "fail_if_no_path" message, need to honor it. */
760                 clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
761         }
762         assign_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags, queue_if_no_path);
763
764         DMDEBUG("%s: after %s changes; QIFNP = %d; SQIFNP = %d; DNFS = %d",
765                 dm_dev_name, __func__,
766                 test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags),
767                 test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags),
768                 dm_noflush_suspending(m->ti));
769
770         spin_unlock_irqrestore(&m->lock, flags);
771
772         if (!queue_if_no_path) {
773                 dm_table_run_md_queue_async(m->ti->table);
774                 process_queued_io_list(m);
775         }
776
777         return 0;
778 }
779
780 /*
781  * If the queue_if_no_path timeout fires, turn off queue_if_no_path and
782  * process any queued I/O.
783  */
784 static void queue_if_no_path_timeout_work(struct timer_list *t)
785 {
786         struct multipath *m = from_timer(m, t, nopath_timer);
787
788         DMWARN("queue_if_no_path timeout on %s, failing queued IO",
789                dm_table_device_name(m->ti->table));
790         queue_if_no_path(m, false, false, __func__);
791 }
792
793 /*
794  * Enable the queue_if_no_path timeout if necessary.
795  * Called with m->lock held.
796  */
797 static void enable_nopath_timeout(struct multipath *m)
798 {
799         unsigned long queue_if_no_path_timeout =
800                 READ_ONCE(queue_if_no_path_timeout_secs) * HZ;
801
802         lockdep_assert_held(&m->lock);
803
804         if (queue_if_no_path_timeout > 0 &&
805             atomic_read(&m->nr_valid_paths) == 0 &&
806             test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
807                 mod_timer(&m->nopath_timer,
808                           jiffies + queue_if_no_path_timeout);
809         }
810 }
811
812 static void disable_nopath_timeout(struct multipath *m)
813 {
814         del_timer_sync(&m->nopath_timer);
815 }
816
817 /*
818  * An event is triggered whenever a path is taken out of use.
819  * Includes path failure and PG bypass.
820  */
821 static void trigger_event(struct work_struct *work)
822 {
823         struct multipath *m =
824                 container_of(work, struct multipath, trigger_event);
825
826         dm_table_event(m->ti->table);
827 }
828
829 /*-----------------------------------------------------------------
830  * Constructor/argument parsing:
831  * <#multipath feature args> [<arg>]*
832  * <#hw_handler args> [hw_handler [<arg>]*]
833  * <#priority groups>
834  * <initial priority group>
835  *     [<selector> <#selector args> [<arg>]*
836  *      <#paths> <#per-path selector args>
837  *         [<path> [<arg>]* ]+ ]+
838  *---------------------------------------------------------------*/
839 static int parse_path_selector(struct dm_arg_set *as, struct priority_group *pg,
840                                struct dm_target *ti)
841 {
842         int r;
843         struct path_selector_type *pst;
844         unsigned ps_argc;
845
846         static const struct dm_arg _args[] = {
847                 {0, 1024, "invalid number of path selector args"},
848         };
849
850         pst = dm_get_path_selector(dm_shift_arg(as));
851         if (!pst) {
852                 ti->error = "unknown path selector type";
853                 return -EINVAL;
854         }
855
856         r = dm_read_arg_group(_args, as, &ps_argc, &ti->error);
857         if (r) {
858                 dm_put_path_selector(pst);
859                 return -EINVAL;
860         }
861
862         r = pst->create(&pg->ps, ps_argc, as->argv);
863         if (r) {
864                 dm_put_path_selector(pst);
865                 ti->error = "path selector constructor failed";
866                 return r;
867         }
868
869         pg->ps.type = pst;
870         dm_consume_args(as, ps_argc);
871
872         return 0;
873 }
874
875 static int setup_scsi_dh(struct block_device *bdev, struct multipath *m,
876                          const char **attached_handler_name, char **error)
877 {
878         struct request_queue *q = bdev_get_queue(bdev);
879         int r;
880
881         if (mpath_double_check_test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, m)) {
882 retain:
883                 if (*attached_handler_name) {
884                         /*
885                          * Clear any hw_handler_params associated with a
886                          * handler that isn't already attached.
887                          */
888                         if (m->hw_handler_name && strcmp(*attached_handler_name, m->hw_handler_name)) {
889                                 kfree(m->hw_handler_params);
890                                 m->hw_handler_params = NULL;
891                         }
892
893                         /*
894                          * Reset hw_handler_name to match the attached handler
895                          *
896                          * NB. This modifies the table line to show the actual
897                          * handler instead of the original table passed in.
898                          */
899                         kfree(m->hw_handler_name);
900                         m->hw_handler_name = *attached_handler_name;
901                         *attached_handler_name = NULL;
902                 }
903         }
904
905         if (m->hw_handler_name) {
906                 r = scsi_dh_attach(q, m->hw_handler_name);
907                 if (r == -EBUSY) {
908                         DMINFO("retaining handler on device %pg", bdev);
909                         goto retain;
910                 }
911                 if (r < 0) {
912                         *error = "error attaching hardware handler";
913                         return r;
914                 }
915
916                 if (m->hw_handler_params) {
917                         r = scsi_dh_set_params(q, m->hw_handler_params);
918                         if (r < 0) {
919                                 *error = "unable to set hardware handler parameters";
920                                 return r;
921                         }
922                 }
923         }
924
925         return 0;
926 }
927
928 static struct pgpath *parse_path(struct dm_arg_set *as, struct path_selector *ps,
929                                  struct dm_target *ti)
930 {
931         int r;
932         struct pgpath *p;
933         struct multipath *m = ti->private;
934         struct request_queue *q;
935         const char *attached_handler_name = NULL;
936
937         /* we need at least a path arg */
938         if (as->argc < 1) {
939                 ti->error = "no device given";
940                 return ERR_PTR(-EINVAL);
941         }
942
943         p = alloc_pgpath();
944         if (!p)
945                 return ERR_PTR(-ENOMEM);
946
947         r = dm_get_device(ti, dm_shift_arg(as), dm_table_get_mode(ti->table),
948                           &p->path.dev);
949         if (r) {
950                 ti->error = "error getting device";
951                 goto bad;
952         }
953
954         q = bdev_get_queue(p->path.dev->bdev);
955         attached_handler_name = scsi_dh_attached_handler_name(q, GFP_KERNEL);
956         if (attached_handler_name || m->hw_handler_name) {
957                 INIT_DELAYED_WORK(&p->activate_path, activate_path_work);
958                 r = setup_scsi_dh(p->path.dev->bdev, m, &attached_handler_name, &ti->error);
959                 kfree(attached_handler_name);
960                 if (r) {
961                         dm_put_device(ti, p->path.dev);
962                         goto bad;
963                 }
964         }
965
966         r = ps->type->add_path(ps, &p->path, as->argc, as->argv, &ti->error);
967         if (r) {
968                 dm_put_device(ti, p->path.dev);
969                 goto bad;
970         }
971
972         return p;
973  bad:
974         free_pgpath(p);
975         return ERR_PTR(r);
976 }
977
978 static struct priority_group *parse_priority_group(struct dm_arg_set *as,
979                                                    struct multipath *m)
980 {
981         static const struct dm_arg _args[] = {
982                 {1, 1024, "invalid number of paths"},
983                 {0, 1024, "invalid number of selector args"}
984         };
985
986         int r;
987         unsigned i, nr_selector_args, nr_args;
988         struct priority_group *pg;
989         struct dm_target *ti = m->ti;
990
991         if (as->argc < 2) {
992                 as->argc = 0;
993                 ti->error = "not enough priority group arguments";
994                 return ERR_PTR(-EINVAL);
995         }
996
997         pg = alloc_priority_group();
998         if (!pg) {
999                 ti->error = "couldn't allocate priority group";
1000                 return ERR_PTR(-ENOMEM);
1001         }
1002         pg->m = m;
1003
1004         r = parse_path_selector(as, pg, ti);
1005         if (r)
1006                 goto bad;
1007
1008         /*
1009          * read the paths
1010          */
1011         r = dm_read_arg(_args, as, &pg->nr_pgpaths, &ti->error);
1012         if (r)
1013                 goto bad;
1014
1015         r = dm_read_arg(_args + 1, as, &nr_selector_args, &ti->error);
1016         if (r)
1017                 goto bad;
1018
1019         nr_args = 1 + nr_selector_args;
1020         for (i = 0; i < pg->nr_pgpaths; i++) {
1021                 struct pgpath *pgpath;
1022                 struct dm_arg_set path_args;
1023
1024                 if (as->argc < nr_args) {
1025                         ti->error = "not enough path parameters";
1026                         r = -EINVAL;
1027                         goto bad;
1028                 }
1029
1030                 path_args.argc = nr_args;
1031                 path_args.argv = as->argv;
1032
1033                 pgpath = parse_path(&path_args, &pg->ps, ti);
1034                 if (IS_ERR(pgpath)) {
1035                         r = PTR_ERR(pgpath);
1036                         goto bad;
1037                 }
1038
1039                 pgpath->pg = pg;
1040                 list_add_tail(&pgpath->list, &pg->pgpaths);
1041                 dm_consume_args(as, nr_args);
1042         }
1043
1044         return pg;
1045
1046  bad:
1047         free_priority_group(pg, ti);
1048         return ERR_PTR(r);
1049 }
1050
1051 static int parse_hw_handler(struct dm_arg_set *as, struct multipath *m)
1052 {
1053         unsigned hw_argc;
1054         int ret;
1055         struct dm_target *ti = m->ti;
1056
1057         static const struct dm_arg _args[] = {
1058                 {0, 1024, "invalid number of hardware handler args"},
1059         };
1060
1061         if (dm_read_arg_group(_args, as, &hw_argc, &ti->error))
1062                 return -EINVAL;
1063
1064         if (!hw_argc)
1065                 return 0;
1066
1067         if (m->queue_mode == DM_TYPE_BIO_BASED) {
1068                 dm_consume_args(as, hw_argc);
1069                 DMERR("bio-based multipath doesn't allow hardware handler args");
1070                 return 0;
1071         }
1072
1073         m->hw_handler_name = kstrdup(dm_shift_arg(as), GFP_KERNEL);
1074         if (!m->hw_handler_name)
1075                 return -EINVAL;
1076
1077         if (hw_argc > 1) {
1078                 char *p;
1079                 int i, j, len = 4;
1080
1081                 for (i = 0; i <= hw_argc - 2; i++)
1082                         len += strlen(as->argv[i]) + 1;
1083                 p = m->hw_handler_params = kzalloc(len, GFP_KERNEL);
1084                 if (!p) {
1085                         ti->error = "memory allocation failed";
1086                         ret = -ENOMEM;
1087                         goto fail;
1088                 }
1089                 j = sprintf(p, "%d", hw_argc - 1);
1090                 for (i = 0, p+=j+1; i <= hw_argc - 2; i++, p+=j+1)
1091                         j = sprintf(p, "%s", as->argv[i]);
1092         }
1093         dm_consume_args(as, hw_argc - 1);
1094
1095         return 0;
1096 fail:
1097         kfree(m->hw_handler_name);
1098         m->hw_handler_name = NULL;
1099         return ret;
1100 }
1101
1102 static int parse_features(struct dm_arg_set *as, struct multipath *m)
1103 {
1104         int r;
1105         unsigned argc;
1106         struct dm_target *ti = m->ti;
1107         const char *arg_name;
1108
1109         static const struct dm_arg _args[] = {
1110                 {0, 8, "invalid number of feature args"},
1111                 {1, 50, "pg_init_retries must be between 1 and 50"},
1112                 {0, 60000, "pg_init_delay_msecs must be between 0 and 60000"},
1113         };
1114
1115         r = dm_read_arg_group(_args, as, &argc, &ti->error);
1116         if (r)
1117                 return -EINVAL;
1118
1119         if (!argc)
1120                 return 0;
1121
1122         do {
1123                 arg_name = dm_shift_arg(as);
1124                 argc--;
1125
1126                 if (!strcasecmp(arg_name, "queue_if_no_path")) {
1127                         r = queue_if_no_path(m, true, false, __func__);
1128                         continue;
1129                 }
1130
1131                 if (!strcasecmp(arg_name, "retain_attached_hw_handler")) {
1132                         set_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags);
1133                         continue;
1134                 }
1135
1136                 if (!strcasecmp(arg_name, "pg_init_retries") &&
1137                     (argc >= 1)) {
1138                         r = dm_read_arg(_args + 1, as, &m->pg_init_retries, &ti->error);
1139                         argc--;
1140                         continue;
1141                 }
1142
1143                 if (!strcasecmp(arg_name, "pg_init_delay_msecs") &&
1144                     (argc >= 1)) {
1145                         r = dm_read_arg(_args + 2, as, &m->pg_init_delay_msecs, &ti->error);
1146                         argc--;
1147                         continue;
1148                 }
1149
1150                 if (!strcasecmp(arg_name, "queue_mode") &&
1151                     (argc >= 1)) {
1152                         const char *queue_mode_name = dm_shift_arg(as);
1153
1154                         if (!strcasecmp(queue_mode_name, "bio"))
1155                                 m->queue_mode = DM_TYPE_BIO_BASED;
1156                         else if (!strcasecmp(queue_mode_name, "rq") ||
1157                                  !strcasecmp(queue_mode_name, "mq"))
1158                                 m->queue_mode = DM_TYPE_REQUEST_BASED;
1159                         else {
1160                                 ti->error = "Unknown 'queue_mode' requested";
1161                                 r = -EINVAL;
1162                         }
1163                         argc--;
1164                         continue;
1165                 }
1166
1167                 ti->error = "Unrecognised multipath feature request";
1168                 r = -EINVAL;
1169         } while (argc && !r);
1170
1171         return r;
1172 }
1173
1174 static int multipath_ctr(struct dm_target *ti, unsigned argc, char **argv)
1175 {
1176         /* target arguments */
1177         static const struct dm_arg _args[] = {
1178                 {0, 1024, "invalid number of priority groups"},
1179                 {0, 1024, "invalid initial priority group number"},
1180         };
1181
1182         int r;
1183         struct multipath *m;
1184         struct dm_arg_set as;
1185         unsigned pg_count = 0;
1186         unsigned next_pg_num;
1187         unsigned long flags;
1188
1189         as.argc = argc;
1190         as.argv = argv;
1191
1192         m = alloc_multipath(ti);
1193         if (!m) {
1194                 ti->error = "can't allocate multipath";
1195                 return -EINVAL;
1196         }
1197
1198         r = parse_features(&as, m);
1199         if (r)
1200                 goto bad;
1201
1202         r = alloc_multipath_stage2(ti, m);
1203         if (r)
1204                 goto bad;
1205
1206         r = parse_hw_handler(&as, m);
1207         if (r)
1208                 goto bad;
1209
1210         r = dm_read_arg(_args, &as, &m->nr_priority_groups, &ti->error);
1211         if (r)
1212                 goto bad;
1213
1214         r = dm_read_arg(_args + 1, &as, &next_pg_num, &ti->error);
1215         if (r)
1216                 goto bad;
1217
1218         if ((!m->nr_priority_groups && next_pg_num) ||
1219             (m->nr_priority_groups && !next_pg_num)) {
1220                 ti->error = "invalid initial priority group";
1221                 r = -EINVAL;
1222                 goto bad;
1223         }
1224
1225         /* parse the priority groups */
1226         while (as.argc) {
1227                 struct priority_group *pg;
1228                 unsigned nr_valid_paths = atomic_read(&m->nr_valid_paths);
1229
1230                 pg = parse_priority_group(&as, m);
1231                 if (IS_ERR(pg)) {
1232                         r = PTR_ERR(pg);
1233                         goto bad;
1234                 }
1235
1236                 nr_valid_paths += pg->nr_pgpaths;
1237                 atomic_set(&m->nr_valid_paths, nr_valid_paths);
1238
1239                 list_add_tail(&pg->list, &m->priority_groups);
1240                 pg_count++;
1241                 pg->pg_num = pg_count;
1242                 if (!--next_pg_num)
1243                         m->next_pg = pg;
1244         }
1245
1246         if (pg_count != m->nr_priority_groups) {
1247                 ti->error = "priority group count mismatch";
1248                 r = -EINVAL;
1249                 goto bad;
1250         }
1251
1252         spin_lock_irqsave(&m->lock, flags);
1253         enable_nopath_timeout(m);
1254         spin_unlock_irqrestore(&m->lock, flags);
1255
1256         ti->num_flush_bios = 1;
1257         ti->num_discard_bios = 1;
1258         ti->num_write_zeroes_bios = 1;
1259         if (m->queue_mode == DM_TYPE_BIO_BASED)
1260                 ti->per_io_data_size = multipath_per_bio_data_size();
1261         else
1262                 ti->per_io_data_size = sizeof(struct dm_mpath_io);
1263
1264         return 0;
1265
1266  bad:
1267         free_multipath(m);
1268         return r;
1269 }
1270
1271 static void multipath_wait_for_pg_init_completion(struct multipath *m)
1272 {
1273         DEFINE_WAIT(wait);
1274
1275         while (1) {
1276                 prepare_to_wait(&m->pg_init_wait, &wait, TASK_UNINTERRUPTIBLE);
1277
1278                 if (!atomic_read(&m->pg_init_in_progress))
1279                         break;
1280
1281                 io_schedule();
1282         }
1283         finish_wait(&m->pg_init_wait, &wait);
1284 }
1285
1286 static void flush_multipath_work(struct multipath *m)
1287 {
1288         if (m->hw_handler_name) {
1289                 unsigned long flags;
1290
1291                 if (!atomic_read(&m->pg_init_in_progress))
1292                         goto skip;
1293
1294                 spin_lock_irqsave(&m->lock, flags);
1295                 if (atomic_read(&m->pg_init_in_progress) &&
1296                     !test_and_set_bit(MPATHF_PG_INIT_DISABLED, &m->flags)) {
1297                         spin_unlock_irqrestore(&m->lock, flags);
1298
1299                         flush_workqueue(kmpath_handlerd);
1300                         multipath_wait_for_pg_init_completion(m);
1301
1302                         spin_lock_irqsave(&m->lock, flags);
1303                         clear_bit(MPATHF_PG_INIT_DISABLED, &m->flags);
1304                 }
1305                 spin_unlock_irqrestore(&m->lock, flags);
1306         }
1307 skip:
1308         if (m->queue_mode == DM_TYPE_BIO_BASED)
1309                 flush_work(&m->process_queued_bios);
1310         flush_work(&m->trigger_event);
1311 }
1312
1313 static void multipath_dtr(struct dm_target *ti)
1314 {
1315         struct multipath *m = ti->private;
1316
1317         disable_nopath_timeout(m);
1318         flush_multipath_work(m);
1319         free_multipath(m);
1320 }
1321
1322 /*
1323  * Take a path out of use.
1324  */
1325 static int fail_path(struct pgpath *pgpath)
1326 {
1327         unsigned long flags;
1328         struct multipath *m = pgpath->pg->m;
1329
1330         spin_lock_irqsave(&m->lock, flags);
1331
1332         if (!pgpath->is_active)
1333                 goto out;
1334
1335         DMWARN("%s: Failing path %s.",
1336                dm_table_device_name(m->ti->table),
1337                pgpath->path.dev->name);
1338
1339         pgpath->pg->ps.type->fail_path(&pgpath->pg->ps, &pgpath->path);
1340         pgpath->is_active = false;
1341         pgpath->fail_count++;
1342
1343         atomic_dec(&m->nr_valid_paths);
1344
1345         if (pgpath == m->current_pgpath)
1346                 m->current_pgpath = NULL;
1347
1348         dm_path_uevent(DM_UEVENT_PATH_FAILED, m->ti,
1349                        pgpath->path.dev->name, atomic_read(&m->nr_valid_paths));
1350
1351         schedule_work(&m->trigger_event);
1352
1353         enable_nopath_timeout(m);
1354
1355 out:
1356         spin_unlock_irqrestore(&m->lock, flags);
1357
1358         return 0;
1359 }
1360
1361 /*
1362  * Reinstate a previously-failed path
1363  */
1364 static int reinstate_path(struct pgpath *pgpath)
1365 {
1366         int r = 0, run_queue = 0;
1367         unsigned long flags;
1368         struct multipath *m = pgpath->pg->m;
1369         unsigned nr_valid_paths;
1370
1371         spin_lock_irqsave(&m->lock, flags);
1372
1373         if (pgpath->is_active)
1374                 goto out;
1375
1376         DMWARN("%s: Reinstating path %s.",
1377                dm_table_device_name(m->ti->table),
1378                pgpath->path.dev->name);
1379
1380         r = pgpath->pg->ps.type->reinstate_path(&pgpath->pg->ps, &pgpath->path);
1381         if (r)
1382                 goto out;
1383
1384         pgpath->is_active = true;
1385
1386         nr_valid_paths = atomic_inc_return(&m->nr_valid_paths);
1387         if (nr_valid_paths == 1) {
1388                 m->current_pgpath = NULL;
1389                 run_queue = 1;
1390         } else if (m->hw_handler_name && (m->current_pg == pgpath->pg)) {
1391                 if (queue_work(kmpath_handlerd, &pgpath->activate_path.work))
1392                         atomic_inc(&m->pg_init_in_progress);
1393         }
1394
1395         dm_path_uevent(DM_UEVENT_PATH_REINSTATED, m->ti,
1396                        pgpath->path.dev->name, nr_valid_paths);
1397
1398         schedule_work(&m->trigger_event);
1399
1400 out:
1401         spin_unlock_irqrestore(&m->lock, flags);
1402         if (run_queue) {
1403                 dm_table_run_md_queue_async(m->ti->table);
1404                 process_queued_io_list(m);
1405         }
1406
1407         if (pgpath->is_active)
1408                 disable_nopath_timeout(m);
1409
1410         return r;
1411 }
1412
1413 /*
1414  * Fail or reinstate all paths that match the provided struct dm_dev.
1415  */
1416 static int action_dev(struct multipath *m, struct dm_dev *dev,
1417                       action_fn action)
1418 {
1419         int r = -EINVAL;
1420         struct pgpath *pgpath;
1421         struct priority_group *pg;
1422
1423         list_for_each_entry(pg, &m->priority_groups, list) {
1424                 list_for_each_entry(pgpath, &pg->pgpaths, list) {
1425                         if (pgpath->path.dev == dev)
1426                                 r = action(pgpath);
1427                 }
1428         }
1429
1430         return r;
1431 }
1432
1433 /*
1434  * Temporarily try to avoid having to use the specified PG
1435  */
1436 static void bypass_pg(struct multipath *m, struct priority_group *pg,
1437                       bool bypassed)
1438 {
1439         unsigned long flags;
1440
1441         spin_lock_irqsave(&m->lock, flags);
1442
1443         pg->bypassed = bypassed;
1444         m->current_pgpath = NULL;
1445         m->current_pg = NULL;
1446
1447         spin_unlock_irqrestore(&m->lock, flags);
1448
1449         schedule_work(&m->trigger_event);
1450 }
1451
1452 /*
1453  * Switch to using the specified PG from the next I/O that gets mapped
1454  */
1455 static int switch_pg_num(struct multipath *m, const char *pgstr)
1456 {
1457         struct priority_group *pg;
1458         unsigned pgnum;
1459         unsigned long flags;
1460         char dummy;
1461
1462         if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1463             !m->nr_priority_groups || (pgnum > m->nr_priority_groups)) {
1464                 DMWARN("invalid PG number supplied to switch_pg_num");
1465                 return -EINVAL;
1466         }
1467
1468         spin_lock_irqsave(&m->lock, flags);
1469         list_for_each_entry(pg, &m->priority_groups, list) {
1470                 pg->bypassed = false;
1471                 if (--pgnum)
1472                         continue;
1473
1474                 m->current_pgpath = NULL;
1475                 m->current_pg = NULL;
1476                 m->next_pg = pg;
1477         }
1478         spin_unlock_irqrestore(&m->lock, flags);
1479
1480         schedule_work(&m->trigger_event);
1481         return 0;
1482 }
1483
1484 /*
1485  * Set/clear bypassed status of a PG.
1486  * PGs are numbered upwards from 1 in the order they were declared.
1487  */
1488 static int bypass_pg_num(struct multipath *m, const char *pgstr, bool bypassed)
1489 {
1490         struct priority_group *pg;
1491         unsigned pgnum;
1492         char dummy;
1493
1494         if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1495             !m->nr_priority_groups || (pgnum > m->nr_priority_groups)) {
1496                 DMWARN("invalid PG number supplied to bypass_pg");
1497                 return -EINVAL;
1498         }
1499
1500         list_for_each_entry(pg, &m->priority_groups, list) {
1501                 if (!--pgnum)
1502                         break;
1503         }
1504
1505         bypass_pg(m, pg, bypassed);
1506         return 0;
1507 }
1508
1509 /*
1510  * Should we retry pg_init immediately?
1511  */
1512 static bool pg_init_limit_reached(struct multipath *m, struct pgpath *pgpath)
1513 {
1514         unsigned long flags;
1515         bool limit_reached = false;
1516
1517         spin_lock_irqsave(&m->lock, flags);
1518
1519         if (atomic_read(&m->pg_init_count) <= m->pg_init_retries &&
1520             !test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
1521                 set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
1522         else
1523                 limit_reached = true;
1524
1525         spin_unlock_irqrestore(&m->lock, flags);
1526
1527         return limit_reached;
1528 }
1529
1530 static void pg_init_done(void *data, int errors)
1531 {
1532         struct pgpath *pgpath = data;
1533         struct priority_group *pg = pgpath->pg;
1534         struct multipath *m = pg->m;
1535         unsigned long flags;
1536         bool delay_retry = false;
1537
1538         /* device or driver problems */
1539         switch (errors) {
1540         case SCSI_DH_OK:
1541                 break;
1542         case SCSI_DH_NOSYS:
1543                 if (!m->hw_handler_name) {
1544                         errors = 0;
1545                         break;
1546                 }
1547                 DMERR("Could not failover the device: Handler scsi_dh_%s "
1548                       "Error %d.", m->hw_handler_name, errors);
1549                 /*
1550                  * Fail path for now, so we do not ping pong
1551                  */
1552                 fail_path(pgpath);
1553                 break;
1554         case SCSI_DH_DEV_TEMP_BUSY:
1555                 /*
1556                  * Probably doing something like FW upgrade on the
1557                  * controller so try the other pg.
1558                  */
1559                 bypass_pg(m, pg, true);
1560                 break;
1561         case SCSI_DH_RETRY:
1562                 /* Wait before retrying. */
1563                 delay_retry = true;
1564                 fallthrough;
1565         case SCSI_DH_IMM_RETRY:
1566         case SCSI_DH_RES_TEMP_UNAVAIL:
1567                 if (pg_init_limit_reached(m, pgpath))
1568                         fail_path(pgpath);
1569                 errors = 0;
1570                 break;
1571         case SCSI_DH_DEV_OFFLINED:
1572         default:
1573                 /*
1574                  * We probably do not want to fail the path for a device
1575                  * error, but this is what the old dm did. In future
1576                  * patches we can do more advanced handling.
1577                  */
1578                 fail_path(pgpath);
1579         }
1580
1581         spin_lock_irqsave(&m->lock, flags);
1582         if (errors) {
1583                 if (pgpath == m->current_pgpath) {
1584                         DMERR("Could not failover device. Error %d.", errors);
1585                         m->current_pgpath = NULL;
1586                         m->current_pg = NULL;
1587                 }
1588         } else if (!test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
1589                 pg->bypassed = false;
1590
1591         if (atomic_dec_return(&m->pg_init_in_progress) > 0)
1592                 /* Activations of other paths are still on going */
1593                 goto out;
1594
1595         if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags)) {
1596                 if (delay_retry)
1597                         set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1598                 else
1599                         clear_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1600
1601                 if (__pg_init_all_paths(m))
1602                         goto out;
1603         }
1604         clear_bit(MPATHF_QUEUE_IO, &m->flags);
1605
1606         process_queued_io_list(m);
1607
1608         /*
1609          * Wake up any thread waiting to suspend.
1610          */
1611         wake_up(&m->pg_init_wait);
1612
1613 out:
1614         spin_unlock_irqrestore(&m->lock, flags);
1615 }
1616
1617 static void activate_or_offline_path(struct pgpath *pgpath)
1618 {
1619         struct request_queue *q = bdev_get_queue(pgpath->path.dev->bdev);
1620
1621         if (pgpath->is_active && !blk_queue_dying(q))
1622                 scsi_dh_activate(q, pg_init_done, pgpath);
1623         else
1624                 pg_init_done(pgpath, SCSI_DH_DEV_OFFLINED);
1625 }
1626
1627 static void activate_path_work(struct work_struct *work)
1628 {
1629         struct pgpath *pgpath =
1630                 container_of(work, struct pgpath, activate_path.work);
1631
1632         activate_or_offline_path(pgpath);
1633 }
1634
1635 static int multipath_end_io(struct dm_target *ti, struct request *clone,
1636                             blk_status_t error, union map_info *map_context)
1637 {
1638         struct dm_mpath_io *mpio = get_mpio(map_context);
1639         struct pgpath *pgpath = mpio->pgpath;
1640         int r = DM_ENDIO_DONE;
1641
1642         /*
1643          * We don't queue any clone request inside the multipath target
1644          * during end I/O handling, since those clone requests don't have
1645          * bio clones.  If we queue them inside the multipath target,
1646          * we need to make bio clones, that requires memory allocation.
1647          * (See drivers/md/dm-rq.c:end_clone_bio() about why the clone requests
1648          *  don't have bio clones.)
1649          * Instead of queueing the clone request here, we queue the original
1650          * request into dm core, which will remake a clone request and
1651          * clone bios for it and resubmit it later.
1652          */
1653         if (error && blk_path_error(error)) {
1654                 struct multipath *m = ti->private;
1655
1656                 if (error == BLK_STS_RESOURCE)
1657                         r = DM_ENDIO_DELAY_REQUEUE;
1658                 else
1659                         r = DM_ENDIO_REQUEUE;
1660
1661                 if (pgpath)
1662                         fail_path(pgpath);
1663
1664                 if (!atomic_read(&m->nr_valid_paths) &&
1665                     !must_push_back_rq(m)) {
1666                         if (error == BLK_STS_IOERR)
1667                                 dm_report_EIO(m);
1668                         /* complete with the original error */
1669                         r = DM_ENDIO_DONE;
1670                 }
1671         }
1672
1673         if (pgpath) {
1674                 struct path_selector *ps = &pgpath->pg->ps;
1675
1676                 if (ps->type->end_io)
1677                         ps->type->end_io(ps, &pgpath->path, mpio->nr_bytes,
1678                                          clone->io_start_time_ns);
1679         }
1680
1681         return r;
1682 }
1683
1684 static int multipath_end_io_bio(struct dm_target *ti, struct bio *clone,
1685                                 blk_status_t *error)
1686 {
1687         struct multipath *m = ti->private;
1688         struct dm_mpath_io *mpio = get_mpio_from_bio(clone);
1689         struct pgpath *pgpath = mpio->pgpath;
1690         unsigned long flags;
1691         int r = DM_ENDIO_DONE;
1692
1693         if (!*error || !blk_path_error(*error))
1694                 goto done;
1695
1696         if (pgpath)
1697                 fail_path(pgpath);
1698
1699         if (!atomic_read(&m->nr_valid_paths)) {
1700                 spin_lock_irqsave(&m->lock, flags);
1701                 if (!test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
1702                         if (__must_push_back(m)) {
1703                                 r = DM_ENDIO_REQUEUE;
1704                         } else {
1705                                 dm_report_EIO(m);
1706                                 *error = BLK_STS_IOERR;
1707                         }
1708                         spin_unlock_irqrestore(&m->lock, flags);
1709                         goto done;
1710                 }
1711                 spin_unlock_irqrestore(&m->lock, flags);
1712         }
1713
1714         multipath_queue_bio(m, clone);
1715         r = DM_ENDIO_INCOMPLETE;
1716 done:
1717         if (pgpath) {
1718                 struct path_selector *ps = &pgpath->pg->ps;
1719
1720                 if (ps->type->end_io)
1721                         ps->type->end_io(ps, &pgpath->path, mpio->nr_bytes,
1722                                          (mpio->start_time_ns ?:
1723                                           dm_start_time_ns_from_clone(clone)));
1724         }
1725
1726         return r;
1727 }
1728
1729 /*
1730  * Suspend with flush can't complete until all the I/O is processed
1731  * so if the last path fails we must error any remaining I/O.
1732  * - Note that if the freeze_bdev fails while suspending, the
1733  *   queue_if_no_path state is lost - userspace should reset it.
1734  * Otherwise, during noflush suspend, queue_if_no_path will not change.
1735  */
1736 static void multipath_presuspend(struct dm_target *ti)
1737 {
1738         struct multipath *m = ti->private;
1739
1740         /* FIXME: bio-based shouldn't need to always disable queue_if_no_path */
1741         if (m->queue_mode == DM_TYPE_BIO_BASED || !dm_noflush_suspending(m->ti))
1742                 queue_if_no_path(m, false, true, __func__);
1743 }
1744
1745 static void multipath_postsuspend(struct dm_target *ti)
1746 {
1747         struct multipath *m = ti->private;
1748
1749         mutex_lock(&m->work_mutex);
1750         flush_multipath_work(m);
1751         mutex_unlock(&m->work_mutex);
1752 }
1753
1754 /*
1755  * Restore the queue_if_no_path setting.
1756  */
1757 static void multipath_resume(struct dm_target *ti)
1758 {
1759         struct multipath *m = ti->private;
1760         unsigned long flags;
1761
1762         spin_lock_irqsave(&m->lock, flags);
1763         if (test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags)) {
1764                 set_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
1765                 clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
1766         }
1767
1768         DMDEBUG("%s: %s finished; QIFNP = %d; SQIFNP = %d",
1769                 dm_table_device_name(m->ti->table), __func__,
1770                 test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags),
1771                 test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags));
1772
1773         spin_unlock_irqrestore(&m->lock, flags);
1774 }
1775
1776 /*
1777  * Info output has the following format:
1778  * num_multipath_feature_args [multipath_feature_args]*
1779  * num_handler_status_args [handler_status_args]*
1780  * num_groups init_group_number
1781  *            [A|D|E num_ps_status_args [ps_status_args]*
1782  *             num_paths num_selector_args
1783  *             [path_dev A|F fail_count [selector_args]* ]+ ]+
1784  *
1785  * Table output has the following format (identical to the constructor string):
1786  * num_feature_args [features_args]*
1787  * num_handler_args hw_handler [hw_handler_args]*
1788  * num_groups init_group_number
1789  *     [priority selector-name num_ps_args [ps_args]*
1790  *      num_paths num_selector_args [path_dev [selector_args]* ]+ ]+
1791  */
1792 static void multipath_status(struct dm_target *ti, status_type_t type,
1793                              unsigned status_flags, char *result, unsigned maxlen)
1794 {
1795         int sz = 0, pg_counter, pgpath_counter;
1796         unsigned long flags;
1797         struct multipath *m = ti->private;
1798         struct priority_group *pg;
1799         struct pgpath *p;
1800         unsigned pg_num;
1801         char state;
1802
1803         spin_lock_irqsave(&m->lock, flags);
1804
1805         /* Features */
1806         if (type == STATUSTYPE_INFO)
1807                 DMEMIT("2 %u %u ", test_bit(MPATHF_QUEUE_IO, &m->flags),
1808                        atomic_read(&m->pg_init_count));
1809         else {
1810                 DMEMIT("%u ", test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) +
1811                               (m->pg_init_retries > 0) * 2 +
1812                               (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT) * 2 +
1813                               test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags) +
1814                               (m->queue_mode != DM_TYPE_REQUEST_BASED) * 2);
1815
1816                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
1817                         DMEMIT("queue_if_no_path ");
1818                 if (m->pg_init_retries)
1819                         DMEMIT("pg_init_retries %u ", m->pg_init_retries);
1820                 if (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT)
1821                         DMEMIT("pg_init_delay_msecs %u ", m->pg_init_delay_msecs);
1822                 if (test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags))
1823                         DMEMIT("retain_attached_hw_handler ");
1824                 if (m->queue_mode != DM_TYPE_REQUEST_BASED) {
1825                         switch(m->queue_mode) {
1826                         case DM_TYPE_BIO_BASED:
1827                                 DMEMIT("queue_mode bio ");
1828                                 break;
1829                         default:
1830                                 WARN_ON_ONCE(true);
1831                                 break;
1832                         }
1833                 }
1834         }
1835
1836         if (!m->hw_handler_name || type == STATUSTYPE_INFO)
1837                 DMEMIT("0 ");
1838         else
1839                 DMEMIT("1 %s ", m->hw_handler_name);
1840
1841         DMEMIT("%u ", m->nr_priority_groups);
1842
1843         if (m->next_pg)
1844                 pg_num = m->next_pg->pg_num;
1845         else if (m->current_pg)
1846                 pg_num = m->current_pg->pg_num;
1847         else
1848                 pg_num = (m->nr_priority_groups ? 1 : 0);
1849
1850         DMEMIT("%u ", pg_num);
1851
1852         switch (type) {
1853         case STATUSTYPE_INFO:
1854                 list_for_each_entry(pg, &m->priority_groups, list) {
1855                         if (pg->bypassed)
1856                                 state = 'D';    /* Disabled */
1857                         else if (pg == m->current_pg)
1858                                 state = 'A';    /* Currently Active */
1859                         else
1860                                 state = 'E';    /* Enabled */
1861
1862                         DMEMIT("%c ", state);
1863
1864                         if (pg->ps.type->status)
1865                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1866                                                           result + sz,
1867                                                           maxlen - sz);
1868                         else
1869                                 DMEMIT("0 ");
1870
1871                         DMEMIT("%u %u ", pg->nr_pgpaths,
1872                                pg->ps.type->info_args);
1873
1874                         list_for_each_entry(p, &pg->pgpaths, list) {
1875                                 DMEMIT("%s %s %u ", p->path.dev->name,
1876                                        p->is_active ? "A" : "F",
1877                                        p->fail_count);
1878                                 if (pg->ps.type->status)
1879                                         sz += pg->ps.type->status(&pg->ps,
1880                                               &p->path, type, result + sz,
1881                                               maxlen - sz);
1882                         }
1883                 }
1884                 break;
1885
1886         case STATUSTYPE_TABLE:
1887                 list_for_each_entry(pg, &m->priority_groups, list) {
1888                         DMEMIT("%s ", pg->ps.type->name);
1889
1890                         if (pg->ps.type->status)
1891                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1892                                                           result + sz,
1893                                                           maxlen - sz);
1894                         else
1895                                 DMEMIT("0 ");
1896
1897                         DMEMIT("%u %u ", pg->nr_pgpaths,
1898                                pg->ps.type->table_args);
1899
1900                         list_for_each_entry(p, &pg->pgpaths, list) {
1901                                 DMEMIT("%s ", p->path.dev->name);
1902                                 if (pg->ps.type->status)
1903                                         sz += pg->ps.type->status(&pg->ps,
1904                                               &p->path, type, result + sz,
1905                                               maxlen - sz);
1906                         }
1907                 }
1908                 break;
1909
1910         case STATUSTYPE_IMA:
1911                 sz = 0; /*reset the result pointer*/
1912
1913                 DMEMIT_TARGET_NAME_VERSION(ti->type);
1914                 DMEMIT(",nr_priority_groups=%u", m->nr_priority_groups);
1915
1916                 pg_counter = 0;
1917                 list_for_each_entry(pg, &m->priority_groups, list) {
1918                         if (pg->bypassed)
1919                                 state = 'D';    /* Disabled */
1920                         else if (pg == m->current_pg)
1921                                 state = 'A';    /* Currently Active */
1922                         else
1923                                 state = 'E';    /* Enabled */
1924                         DMEMIT(",pg_state_%d=%c", pg_counter, state);
1925                         DMEMIT(",nr_pgpaths_%d=%u", pg_counter, pg->nr_pgpaths);
1926                         DMEMIT(",path_selector_name_%d=%s", pg_counter, pg->ps.type->name);
1927
1928                         pgpath_counter = 0;
1929                         list_for_each_entry(p, &pg->pgpaths, list) {
1930                                 DMEMIT(",path_name_%d_%d=%s,is_active_%d_%d=%c,fail_count_%d_%d=%u",
1931                                        pg_counter, pgpath_counter, p->path.dev->name,
1932                                        pg_counter, pgpath_counter, p->is_active ? 'A' : 'F',
1933                                        pg_counter, pgpath_counter, p->fail_count);
1934                                 if (pg->ps.type->status) {
1935                                         DMEMIT(",path_selector_status_%d_%d=",
1936                                                pg_counter, pgpath_counter);
1937                                         sz += pg->ps.type->status(&pg->ps, &p->path,
1938                                                                   type, result + sz,
1939                                                                   maxlen - sz);
1940                                 }
1941                                 pgpath_counter++;
1942                         }
1943                         pg_counter++;
1944                 }
1945                 DMEMIT(";");
1946                 break;
1947         }
1948
1949         spin_unlock_irqrestore(&m->lock, flags);
1950 }
1951
1952 static int multipath_message(struct dm_target *ti, unsigned argc, char **argv,
1953                              char *result, unsigned maxlen)
1954 {
1955         int r = -EINVAL;
1956         struct dm_dev *dev;
1957         struct multipath *m = ti->private;
1958         action_fn action;
1959         unsigned long flags;
1960
1961         mutex_lock(&m->work_mutex);
1962
1963         if (dm_suspended(ti)) {
1964                 r = -EBUSY;
1965                 goto out;
1966         }
1967
1968         if (argc == 1) {
1969                 if (!strcasecmp(argv[0], "queue_if_no_path")) {
1970                         r = queue_if_no_path(m, true, false, __func__);
1971                         spin_lock_irqsave(&m->lock, flags);
1972                         enable_nopath_timeout(m);
1973                         spin_unlock_irqrestore(&m->lock, flags);
1974                         goto out;
1975                 } else if (!strcasecmp(argv[0], "fail_if_no_path")) {
1976                         r = queue_if_no_path(m, false, false, __func__);
1977                         disable_nopath_timeout(m);
1978                         goto out;
1979                 }
1980         }
1981
1982         if (argc != 2) {
1983                 DMWARN("Invalid multipath message arguments. Expected 2 arguments, got %d.", argc);
1984                 goto out;
1985         }
1986
1987         if (!strcasecmp(argv[0], "disable_group")) {
1988                 r = bypass_pg_num(m, argv[1], true);
1989                 goto out;
1990         } else if (!strcasecmp(argv[0], "enable_group")) {
1991                 r = bypass_pg_num(m, argv[1], false);
1992                 goto out;
1993         } else if (!strcasecmp(argv[0], "switch_group")) {
1994                 r = switch_pg_num(m, argv[1]);
1995                 goto out;
1996         } else if (!strcasecmp(argv[0], "reinstate_path"))
1997                 action = reinstate_path;
1998         else if (!strcasecmp(argv[0], "fail_path"))
1999                 action = fail_path;
2000         else {
2001                 DMWARN("Unrecognised multipath message received: %s", argv[0]);
2002                 goto out;
2003         }
2004
2005         r = dm_get_device(ti, argv[1], dm_table_get_mode(ti->table), &dev);
2006         if (r) {
2007                 DMWARN("message: error getting device %s",
2008                        argv[1]);
2009                 goto out;
2010         }
2011
2012         r = action_dev(m, dev, action);
2013
2014         dm_put_device(ti, dev);
2015
2016 out:
2017         mutex_unlock(&m->work_mutex);
2018         return r;
2019 }
2020
2021 static int multipath_prepare_ioctl(struct dm_target *ti,
2022                                    struct block_device **bdev)
2023 {
2024         struct multipath *m = ti->private;
2025         struct pgpath *pgpath;
2026         unsigned long flags;
2027         int r;
2028
2029         pgpath = READ_ONCE(m->current_pgpath);
2030         if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
2031                 pgpath = choose_pgpath(m, 0);
2032
2033         if (pgpath) {
2034                 if (!mpath_double_check_test_bit(MPATHF_QUEUE_IO, m)) {
2035                         *bdev = pgpath->path.dev->bdev;
2036                         r = 0;
2037                 } else {
2038                         /* pg_init has not started or completed */
2039                         r = -ENOTCONN;
2040                 }
2041         } else {
2042                 /* No path is available */
2043                 r = -EIO;
2044                 spin_lock_irqsave(&m->lock, flags);
2045                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
2046                         r = -ENOTCONN;
2047                 spin_unlock_irqrestore(&m->lock, flags);
2048         }
2049
2050         if (r == -ENOTCONN) {
2051                 if (!READ_ONCE(m->current_pg)) {
2052                         /* Path status changed, redo selection */
2053                         (void) choose_pgpath(m, 0);
2054                 }
2055                 spin_lock_irqsave(&m->lock, flags);
2056                 if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
2057                         (void) __pg_init_all_paths(m);
2058                 spin_unlock_irqrestore(&m->lock, flags);
2059                 dm_table_run_md_queue_async(m->ti->table);
2060                 process_queued_io_list(m);
2061         }
2062
2063         /*
2064          * Only pass ioctls through if the device sizes match exactly.
2065          */
2066         if (!r && ti->len != bdev_nr_sectors((*bdev)))
2067                 return 1;
2068         return r;
2069 }
2070
2071 static int multipath_iterate_devices(struct dm_target *ti,
2072                                      iterate_devices_callout_fn fn, void *data)
2073 {
2074         struct multipath *m = ti->private;
2075         struct priority_group *pg;
2076         struct pgpath *p;
2077         int ret = 0;
2078
2079         list_for_each_entry(pg, &m->priority_groups, list) {
2080                 list_for_each_entry(p, &pg->pgpaths, list) {
2081                         ret = fn(ti, p->path.dev, ti->begin, ti->len, data);
2082                         if (ret)
2083                                 goto out;
2084                 }
2085         }
2086
2087 out:
2088         return ret;
2089 }
2090
2091 static int pgpath_busy(struct pgpath *pgpath)
2092 {
2093         struct request_queue *q = bdev_get_queue(pgpath->path.dev->bdev);
2094
2095         return blk_lld_busy(q);
2096 }
2097
2098 /*
2099  * We return "busy", only when we can map I/Os but underlying devices
2100  * are busy (so even if we map I/Os now, the I/Os will wait on
2101  * the underlying queue).
2102  * In other words, if we want to kill I/Os or queue them inside us
2103  * due to map unavailability, we don't return "busy".  Otherwise,
2104  * dm core won't give us the I/Os and we can't do what we want.
2105  */
2106 static int multipath_busy(struct dm_target *ti)
2107 {
2108         bool busy = false, has_active = false;
2109         struct multipath *m = ti->private;
2110         struct priority_group *pg, *next_pg;
2111         struct pgpath *pgpath;
2112
2113         /* pg_init in progress */
2114         if (atomic_read(&m->pg_init_in_progress))
2115                 return true;
2116
2117         /* no paths available, for blk-mq: rely on IO mapping to delay requeue */
2118         if (!atomic_read(&m->nr_valid_paths)) {
2119                 unsigned long flags;
2120                 spin_lock_irqsave(&m->lock, flags);
2121                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
2122                         spin_unlock_irqrestore(&m->lock, flags);
2123                         return (m->queue_mode != DM_TYPE_REQUEST_BASED);
2124                 }
2125                 spin_unlock_irqrestore(&m->lock, flags);
2126         }
2127
2128         /* Guess which priority_group will be used at next mapping time */
2129         pg = READ_ONCE(m->current_pg);
2130         next_pg = READ_ONCE(m->next_pg);
2131         if (unlikely(!READ_ONCE(m->current_pgpath) && next_pg))
2132                 pg = next_pg;
2133
2134         if (!pg) {
2135                 /*
2136                  * We don't know which pg will be used at next mapping time.
2137                  * We don't call choose_pgpath() here to avoid to trigger
2138                  * pg_init just by busy checking.
2139                  * So we don't know whether underlying devices we will be using
2140                  * at next mapping time are busy or not. Just try mapping.
2141                  */
2142                 return busy;
2143         }
2144
2145         /*
2146          * If there is one non-busy active path at least, the path selector
2147          * will be able to select it. So we consider such a pg as not busy.
2148          */
2149         busy = true;
2150         list_for_each_entry(pgpath, &pg->pgpaths, list) {
2151                 if (pgpath->is_active) {
2152                         has_active = true;
2153                         if (!pgpath_busy(pgpath)) {
2154                                 busy = false;
2155                                 break;
2156                         }
2157                 }
2158         }
2159
2160         if (!has_active) {
2161                 /*
2162                  * No active path in this pg, so this pg won't be used and
2163                  * the current_pg will be changed at next mapping time.
2164                  * We need to try mapping to determine it.
2165                  */
2166                 busy = false;
2167         }
2168
2169         return busy;
2170 }
2171
2172 /*-----------------------------------------------------------------
2173  * Module setup
2174  *---------------------------------------------------------------*/
2175 static struct target_type multipath_target = {
2176         .name = "multipath",
2177         .version = {1, 14, 0},
2178         .features = DM_TARGET_SINGLETON | DM_TARGET_IMMUTABLE |
2179                     DM_TARGET_PASSES_INTEGRITY,
2180         .module = THIS_MODULE,
2181         .ctr = multipath_ctr,
2182         .dtr = multipath_dtr,
2183         .clone_and_map_rq = multipath_clone_and_map,
2184         .release_clone_rq = multipath_release_clone,
2185         .rq_end_io = multipath_end_io,
2186         .map = multipath_map_bio,
2187         .end_io = multipath_end_io_bio,
2188         .presuspend = multipath_presuspend,
2189         .postsuspend = multipath_postsuspend,
2190         .resume = multipath_resume,
2191         .status = multipath_status,
2192         .message = multipath_message,
2193         .prepare_ioctl = multipath_prepare_ioctl,
2194         .iterate_devices = multipath_iterate_devices,
2195         .busy = multipath_busy,
2196 };
2197
2198 static int __init dm_multipath_init(void)
2199 {
2200         int r;
2201
2202         kmultipathd = alloc_workqueue("kmpathd", WQ_MEM_RECLAIM, 0);
2203         if (!kmultipathd) {
2204                 DMERR("failed to create workqueue kmpathd");
2205                 r = -ENOMEM;
2206                 goto bad_alloc_kmultipathd;
2207         }
2208
2209         /*
2210          * A separate workqueue is used to handle the device handlers
2211          * to avoid overloading existing workqueue. Overloading the
2212          * old workqueue would also create a bottleneck in the
2213          * path of the storage hardware device activation.
2214          */
2215         kmpath_handlerd = alloc_ordered_workqueue("kmpath_handlerd",
2216                                                   WQ_MEM_RECLAIM);
2217         if (!kmpath_handlerd) {
2218                 DMERR("failed to create workqueue kmpath_handlerd");
2219                 r = -ENOMEM;
2220                 goto bad_alloc_kmpath_handlerd;
2221         }
2222
2223         r = dm_register_target(&multipath_target);
2224         if (r < 0) {
2225                 DMERR("request-based register failed %d", r);
2226                 r = -EINVAL;
2227                 goto bad_register_target;
2228         }
2229
2230         return 0;
2231
2232 bad_register_target:
2233         destroy_workqueue(kmpath_handlerd);
2234 bad_alloc_kmpath_handlerd:
2235         destroy_workqueue(kmultipathd);
2236 bad_alloc_kmultipathd:
2237         return r;
2238 }
2239
2240 static void __exit dm_multipath_exit(void)
2241 {
2242         destroy_workqueue(kmpath_handlerd);
2243         destroy_workqueue(kmultipathd);
2244
2245         dm_unregister_target(&multipath_target);
2246 }
2247
2248 module_init(dm_multipath_init);
2249 module_exit(dm_multipath_exit);
2250
2251 module_param_named(queue_if_no_path_timeout_secs,
2252                    queue_if_no_path_timeout_secs, ulong, S_IRUGO | S_IWUSR);
2253 MODULE_PARM_DESC(queue_if_no_path_timeout_secs, "No available paths queue IO timeout in seconds");
2254
2255 MODULE_DESCRIPTION(DM_NAME " multipath target");
2256 MODULE_AUTHOR("Sistina Software <dm-devel@redhat.com>");
2257 MODULE_LICENSE("GPL");