780e5d0a066fcf947f1630611c46e4161df13086
[cascardo/linux.git] / drivers / md / dm-mpath.c
1 /*
2  * Copyright (C) 2003 Sistina Software Limited.
3  * Copyright (C) 2004-2005 Red Hat, Inc. All rights reserved.
4  *
5  * This file is released under the GPL.
6  */
7
8 #include <linux/device-mapper.h>
9
10 #include "dm.h"
11 #include "dm-path-selector.h"
12 #include "dm-uevent.h"
13
14 #include <linux/blkdev.h>
15 #include <linux/ctype.h>
16 #include <linux/init.h>
17 #include <linux/mempool.h>
18 #include <linux/module.h>
19 #include <linux/pagemap.h>
20 #include <linux/slab.h>
21 #include <linux/time.h>
22 #include <linux/workqueue.h>
23 #include <linux/delay.h>
24 #include <scsi/scsi_dh.h>
25 #include <linux/atomic.h>
26 #include <linux/blk-mq.h>
27
28 #define DM_MSG_PREFIX "multipath"
29 #define DM_PG_INIT_DELAY_MSECS 2000
30 #define DM_PG_INIT_DELAY_DEFAULT ((unsigned) -1)
31
32 /* Path properties */
33 struct pgpath {
34         struct list_head list;
35
36         struct priority_group *pg;      /* Owning PG */
37         unsigned fail_count;            /* Cumulative failure count */
38
39         struct dm_path path;
40         struct delayed_work activate_path;
41
42         bool is_active:1;               /* Path status */
43 };
44
45 #define path_to_pgpath(__pgp) container_of((__pgp), struct pgpath, path)
46
47 /*
48  * Paths are grouped into Priority Groups and numbered from 1 upwards.
49  * Each has a path selector which controls which path gets used.
50  */
51 struct priority_group {
52         struct list_head list;
53
54         struct multipath *m;            /* Owning multipath instance */
55         struct path_selector ps;
56
57         unsigned pg_num;                /* Reference number */
58         unsigned nr_pgpaths;            /* Number of paths in PG */
59         struct list_head pgpaths;
60
61         bool bypassed:1;                /* Temporarily bypass this PG? */
62 };
63
64 /* Multipath context */
65 struct multipath {
66         struct list_head list;
67         struct dm_target *ti;
68
69         const char *hw_handler_name;
70         char *hw_handler_params;
71
72         spinlock_t lock;
73
74         unsigned nr_priority_groups;
75         struct list_head priority_groups;
76
77         wait_queue_head_t pg_init_wait; /* Wait for pg_init completion */
78
79         struct pgpath *current_pgpath;
80         struct priority_group *current_pg;
81         struct priority_group *next_pg; /* Switch to this PG if set */
82
83         unsigned long flags;            /* Multipath state flags */
84
85         unsigned pg_init_retries;       /* Number of times to retry pg_init */
86         unsigned pg_init_delay_msecs;   /* Number of msecs before pg_init retry */
87
88         atomic_t nr_valid_paths;        /* Total number of usable paths */
89         atomic_t pg_init_in_progress;   /* Only one pg_init allowed at once */
90         atomic_t pg_init_count;         /* Number of times pg_init called */
91
92         struct work_struct trigger_event;
93
94         /*
95          * We must use a mempool of dm_mpath_io structs so that we
96          * can resubmit bios on error.
97          */
98         mempool_t *mpio_pool;
99
100         struct mutex work_mutex;
101 };
102
103 /*
104  * Context information attached to each bio we process.
105  */
106 struct dm_mpath_io {
107         struct pgpath *pgpath;
108         size_t nr_bytes;
109 };
110
111 typedef int (*action_fn) (struct pgpath *pgpath);
112
113 static struct kmem_cache *_mpio_cache;
114
115 static struct workqueue_struct *kmultipathd, *kmpath_handlerd;
116 static void trigger_event(struct work_struct *work);
117 static void activate_path(struct work_struct *work);
118
119 /*-----------------------------------------------
120  * Multipath state flags.
121  *-----------------------------------------------*/
122
123 #define MPATHF_QUEUE_IO 0                       /* Must we queue all I/O? */
124 #define MPATHF_QUEUE_IF_NO_PATH 1               /* Queue I/O if last path fails? */
125 #define MPATHF_SAVED_QUEUE_IF_NO_PATH 2         /* Saved state during suspension */
126 #define MPATHF_RETAIN_ATTACHED_HW_HANDLER 3     /* If there's already a hw_handler present, don't change it. */
127 #define MPATHF_PG_INIT_DISABLED 4               /* pg_init is not currently allowed */
128 #define MPATHF_PG_INIT_REQUIRED 5               /* pg_init needs calling? */
129 #define MPATHF_PG_INIT_DELAY_RETRY 6            /* Delay pg_init retry? */
130
131 /*-----------------------------------------------
132  * Allocation routines
133  *-----------------------------------------------*/
134
135 static struct pgpath *alloc_pgpath(void)
136 {
137         struct pgpath *pgpath = kzalloc(sizeof(*pgpath), GFP_KERNEL);
138
139         if (pgpath) {
140                 pgpath->is_active = true;
141                 INIT_DELAYED_WORK(&pgpath->activate_path, activate_path);
142         }
143
144         return pgpath;
145 }
146
147 static void free_pgpath(struct pgpath *pgpath)
148 {
149         kfree(pgpath);
150 }
151
152 static struct priority_group *alloc_priority_group(void)
153 {
154         struct priority_group *pg;
155
156         pg = kzalloc(sizeof(*pg), GFP_KERNEL);
157
158         if (pg)
159                 INIT_LIST_HEAD(&pg->pgpaths);
160
161         return pg;
162 }
163
164 static void free_pgpaths(struct list_head *pgpaths, struct dm_target *ti)
165 {
166         struct pgpath *pgpath, *tmp;
167
168         list_for_each_entry_safe(pgpath, tmp, pgpaths, list) {
169                 list_del(&pgpath->list);
170                 dm_put_device(ti, pgpath->path.dev);
171                 free_pgpath(pgpath);
172         }
173 }
174
175 static void free_priority_group(struct priority_group *pg,
176                                 struct dm_target *ti)
177 {
178         struct path_selector *ps = &pg->ps;
179
180         if (ps->type) {
181                 ps->type->destroy(ps);
182                 dm_put_path_selector(ps->type);
183         }
184
185         free_pgpaths(&pg->pgpaths, ti);
186         kfree(pg);
187 }
188
189 static struct multipath *alloc_multipath(struct dm_target *ti, bool use_blk_mq)
190 {
191         struct multipath *m;
192
193         m = kzalloc(sizeof(*m), GFP_KERNEL);
194         if (m) {
195                 INIT_LIST_HEAD(&m->priority_groups);
196                 spin_lock_init(&m->lock);
197                 set_bit(MPATHF_QUEUE_IO, &m->flags);
198                 atomic_set(&m->nr_valid_paths, 0);
199                 atomic_set(&m->pg_init_in_progress, 0);
200                 atomic_set(&m->pg_init_count, 0);
201                 m->pg_init_delay_msecs = DM_PG_INIT_DELAY_DEFAULT;
202                 INIT_WORK(&m->trigger_event, trigger_event);
203                 init_waitqueue_head(&m->pg_init_wait);
204                 mutex_init(&m->work_mutex);
205
206                 m->mpio_pool = NULL;
207                 if (!use_blk_mq) {
208                         unsigned min_ios = dm_get_reserved_rq_based_ios();
209
210                         m->mpio_pool = mempool_create_slab_pool(min_ios, _mpio_cache);
211                         if (!m->mpio_pool) {
212                                 kfree(m);
213                                 return NULL;
214                         }
215                 }
216
217                 m->ti = ti;
218                 ti->private = m;
219         }
220
221         return m;
222 }
223
224 static void free_multipath(struct multipath *m)
225 {
226         struct priority_group *pg, *tmp;
227
228         list_for_each_entry_safe(pg, tmp, &m->priority_groups, list) {
229                 list_del(&pg->list);
230                 free_priority_group(pg, m->ti);
231         }
232
233         kfree(m->hw_handler_name);
234         kfree(m->hw_handler_params);
235         mempool_destroy(m->mpio_pool);
236         kfree(m);
237 }
238
239 static struct dm_mpath_io *get_mpio(union map_info *info)
240 {
241         return info->ptr;
242 }
243
244 static struct dm_mpath_io *set_mpio(struct multipath *m, union map_info *info)
245 {
246         struct dm_mpath_io *mpio;
247
248         if (!m->mpio_pool) {
249                 /* Use blk-mq pdu memory requested via per_io_data_size */
250                 mpio = get_mpio(info);
251                 memset(mpio, 0, sizeof(*mpio));
252                 return mpio;
253         }
254
255         mpio = mempool_alloc(m->mpio_pool, GFP_ATOMIC);
256         if (!mpio)
257                 return NULL;
258
259         memset(mpio, 0, sizeof(*mpio));
260         info->ptr = mpio;
261
262         return mpio;
263 }
264
265 static void clear_request_fn_mpio(struct multipath *m, union map_info *info)
266 {
267         /* Only needed for non blk-mq (.request_fn) multipath */
268         if (m->mpio_pool) {
269                 struct dm_mpath_io *mpio = info->ptr;
270
271                 info->ptr = NULL;
272                 mempool_free(mpio, m->mpio_pool);
273         }
274 }
275
276 /*-----------------------------------------------
277  * Path selection
278  *-----------------------------------------------*/
279
280 static int __pg_init_all_paths(struct multipath *m)
281 {
282         struct pgpath *pgpath;
283         unsigned long pg_init_delay = 0;
284
285         if (atomic_read(&m->pg_init_in_progress) || test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
286                 return 0;
287
288         atomic_inc(&m->pg_init_count);
289         clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
290
291         /* Check here to reset pg_init_required */
292         if (!m->current_pg)
293                 return 0;
294
295         if (test_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags))
296                 pg_init_delay = msecs_to_jiffies(m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT ?
297                                                  m->pg_init_delay_msecs : DM_PG_INIT_DELAY_MSECS);
298         list_for_each_entry(pgpath, &m->current_pg->pgpaths, list) {
299                 /* Skip failed paths */
300                 if (!pgpath->is_active)
301                         continue;
302                 if (queue_delayed_work(kmpath_handlerd, &pgpath->activate_path,
303                                        pg_init_delay))
304                         atomic_inc(&m->pg_init_in_progress);
305         }
306         return atomic_read(&m->pg_init_in_progress);
307 }
308
309 static void __switch_pg(struct multipath *m, struct pgpath *pgpath)
310 {
311         m->current_pg = pgpath->pg;
312
313         /* Must we initialise the PG first, and queue I/O till it's ready? */
314         if (m->hw_handler_name) {
315                 set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
316                 set_bit(MPATHF_QUEUE_IO, &m->flags);
317         } else {
318                 clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
319                 clear_bit(MPATHF_QUEUE_IO, &m->flags);
320         }
321
322         atomic_set(&m->pg_init_count, 0);
323 }
324
325 static int __choose_path_in_pg(struct multipath *m, struct priority_group *pg,
326                                size_t nr_bytes)
327 {
328         struct dm_path *path;
329
330         path = pg->ps.type->select_path(&pg->ps, nr_bytes);
331         if (!path)
332                 return -ENXIO;
333
334         m->current_pgpath = path_to_pgpath(path);
335
336         if (m->current_pg != pg)
337                 __switch_pg(m, m->current_pgpath);
338
339         return 0;
340 }
341
342 static void __choose_pgpath(struct multipath *m, size_t nr_bytes)
343 {
344         struct priority_group *pg;
345         bool bypassed = true;
346
347         if (!atomic_read(&m->nr_valid_paths)) {
348                 clear_bit(MPATHF_QUEUE_IO, &m->flags);
349                 goto failed;
350         }
351
352         /* Were we instructed to switch PG? */
353         if (m->next_pg) {
354                 pg = m->next_pg;
355                 m->next_pg = NULL;
356                 if (!__choose_path_in_pg(m, pg, nr_bytes))
357                         return;
358         }
359
360         /* Don't change PG until it has no remaining paths */
361         if (m->current_pg && !__choose_path_in_pg(m, m->current_pg, nr_bytes))
362                 return;
363
364         /*
365          * Loop through priority groups until we find a valid path.
366          * First time we skip PGs marked 'bypassed'.
367          * Second time we only try the ones we skipped, but set
368          * pg_init_delay_retry so we do not hammer controllers.
369          */
370         do {
371                 list_for_each_entry(pg, &m->priority_groups, list) {
372                         if (pg->bypassed == bypassed)
373                                 continue;
374                         if (!__choose_path_in_pg(m, pg, nr_bytes)) {
375                                 if (!bypassed)
376                                         set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
377                                 return;
378                         }
379                 }
380         } while (bypassed--);
381
382 failed:
383         m->current_pgpath = NULL;
384         m->current_pg = NULL;
385 }
386
387 /*
388  * Check whether bios must be queued in the device-mapper core rather
389  * than here in the target.
390  *
391  * m->lock must be held on entry.
392  *
393  * If m->queue_if_no_path and m->saved_queue_if_no_path hold the
394  * same value then we are not between multipath_presuspend()
395  * and multipath_resume() calls and we have no need to check
396  * for the DMF_NOFLUSH_SUSPENDING flag.
397  */
398 static int __must_push_back(struct multipath *m)
399 {
400         return (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) ||
401                 ((test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) !=
402                   test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags)) &&
403                  dm_noflush_suspending(m->ti)));
404 }
405
406 /*
407  * Map cloned requests
408  */
409 static int __multipath_map(struct dm_target *ti, struct request *clone,
410                            union map_info *map_context,
411                            struct request *rq, struct request **__clone)
412 {
413         struct multipath *m = ti->private;
414         int r = DM_MAPIO_REQUEUE;
415         size_t nr_bytes = clone ? blk_rq_bytes(clone) : blk_rq_bytes(rq);
416         struct pgpath *pgpath;
417         struct block_device *bdev;
418         struct dm_mpath_io *mpio;
419
420         spin_lock_irq(&m->lock);
421
422         /* Do we need to select a new pgpath? */
423         if (!m->current_pgpath || !test_bit(MPATHF_QUEUE_IO, &m->flags))
424                 __choose_pgpath(m, nr_bytes);
425
426         pgpath = m->current_pgpath;
427
428         if (!pgpath) {
429                 if (!__must_push_back(m))
430                         r = -EIO;       /* Failed */
431                 goto out_unlock;
432         } else if (test_bit(MPATHF_QUEUE_IO, &m->flags) ||
433                    test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags)) {
434                 __pg_init_all_paths(m);
435                 goto out_unlock;
436         }
437
438         mpio = set_mpio(m, map_context);
439         if (!mpio)
440                 /* ENOMEM, requeue */
441                 goto out_unlock;
442
443         mpio->pgpath = pgpath;
444         mpio->nr_bytes = nr_bytes;
445
446         bdev = pgpath->path.dev->bdev;
447
448         spin_unlock_irq(&m->lock);
449
450         if (clone) {
451                 /*
452                  * Old request-based interface: allocated clone is passed in.
453                  * Used by: .request_fn stacked on .request_fn path(s).
454                  */
455                 clone->q = bdev_get_queue(bdev);
456                 clone->rq_disk = bdev->bd_disk;
457                 clone->cmd_flags |= REQ_FAILFAST_TRANSPORT;
458         } else {
459                 /*
460                  * blk-mq request-based interface; used by both:
461                  * .request_fn stacked on blk-mq path(s) and
462                  * blk-mq stacked on blk-mq path(s).
463                  */
464                 *__clone = blk_mq_alloc_request(bdev_get_queue(bdev),
465                                                 rq_data_dir(rq), BLK_MQ_REQ_NOWAIT);
466                 if (IS_ERR(*__clone)) {
467                         /* ENOMEM, requeue */
468                         clear_request_fn_mpio(m, map_context);
469                         return r;
470                 }
471                 (*__clone)->bio = (*__clone)->biotail = NULL;
472                 (*__clone)->rq_disk = bdev->bd_disk;
473                 (*__clone)->cmd_flags |= REQ_FAILFAST_TRANSPORT;
474         }
475
476         if (pgpath->pg->ps.type->start_io)
477                 pgpath->pg->ps.type->start_io(&pgpath->pg->ps,
478                                               &pgpath->path,
479                                               nr_bytes);
480         return DM_MAPIO_REMAPPED;
481
482 out_unlock:
483         spin_unlock_irq(&m->lock);
484
485         return r;
486 }
487
488 static int multipath_map(struct dm_target *ti, struct request *clone,
489                          union map_info *map_context)
490 {
491         return __multipath_map(ti, clone, map_context, NULL, NULL);
492 }
493
494 static int multipath_clone_and_map(struct dm_target *ti, struct request *rq,
495                                    union map_info *map_context,
496                                    struct request **clone)
497 {
498         return __multipath_map(ti, NULL, map_context, rq, clone);
499 }
500
501 static void multipath_release_clone(struct request *clone)
502 {
503         blk_mq_free_request(clone);
504 }
505
506 /*
507  * If we run out of usable paths, should we queue I/O or error it?
508  */
509 static int queue_if_no_path(struct multipath *m, bool queue_if_no_path,
510                             bool save_old_value)
511 {
512         unsigned long flags;
513
514         spin_lock_irqsave(&m->lock, flags);
515
516         if (save_old_value) {
517                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
518                         set_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
519                 else
520                         clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
521         } else {
522                 if (queue_if_no_path)
523                         set_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
524                 else
525                         clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
526         }
527         if (queue_if_no_path)
528                 set_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
529         else
530                 clear_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
531
532         spin_unlock_irqrestore(&m->lock, flags);
533
534         if (!queue_if_no_path)
535                 dm_table_run_md_queue_async(m->ti->table);
536
537         return 0;
538 }
539
540 /*
541  * An event is triggered whenever a path is taken out of use.
542  * Includes path failure and PG bypass.
543  */
544 static void trigger_event(struct work_struct *work)
545 {
546         struct multipath *m =
547                 container_of(work, struct multipath, trigger_event);
548
549         dm_table_event(m->ti->table);
550 }
551
552 /*-----------------------------------------------------------------
553  * Constructor/argument parsing:
554  * <#multipath feature args> [<arg>]*
555  * <#hw_handler args> [hw_handler [<arg>]*]
556  * <#priority groups>
557  * <initial priority group>
558  *     [<selector> <#selector args> [<arg>]*
559  *      <#paths> <#per-path selector args>
560  *         [<path> [<arg>]* ]+ ]+
561  *---------------------------------------------------------------*/
562 static int parse_path_selector(struct dm_arg_set *as, struct priority_group *pg,
563                                struct dm_target *ti)
564 {
565         int r;
566         struct path_selector_type *pst;
567         unsigned ps_argc;
568
569         static struct dm_arg _args[] = {
570                 {0, 1024, "invalid number of path selector args"},
571         };
572
573         pst = dm_get_path_selector(dm_shift_arg(as));
574         if (!pst) {
575                 ti->error = "unknown path selector type";
576                 return -EINVAL;
577         }
578
579         r = dm_read_arg_group(_args, as, &ps_argc, &ti->error);
580         if (r) {
581                 dm_put_path_selector(pst);
582                 return -EINVAL;
583         }
584
585         r = pst->create(&pg->ps, ps_argc, as->argv);
586         if (r) {
587                 dm_put_path_selector(pst);
588                 ti->error = "path selector constructor failed";
589                 return r;
590         }
591
592         pg->ps.type = pst;
593         dm_consume_args(as, ps_argc);
594
595         return 0;
596 }
597
598 static struct pgpath *parse_path(struct dm_arg_set *as, struct path_selector *ps,
599                                struct dm_target *ti)
600 {
601         int r;
602         struct pgpath *p;
603         struct multipath *m = ti->private;
604         struct request_queue *q = NULL;
605         const char *attached_handler_name;
606
607         /* we need at least a path arg */
608         if (as->argc < 1) {
609                 ti->error = "no device given";
610                 return ERR_PTR(-EINVAL);
611         }
612
613         p = alloc_pgpath();
614         if (!p)
615                 return ERR_PTR(-ENOMEM);
616
617         r = dm_get_device(ti, dm_shift_arg(as), dm_table_get_mode(ti->table),
618                           &p->path.dev);
619         if (r) {
620                 ti->error = "error getting device";
621                 goto bad;
622         }
623
624         if (test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags) || m->hw_handler_name)
625                 q = bdev_get_queue(p->path.dev->bdev);
626
627         if (test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags)) {
628 retain:
629                 attached_handler_name = scsi_dh_attached_handler_name(q, GFP_KERNEL);
630                 if (attached_handler_name) {
631                         /*
632                          * Reset hw_handler_name to match the attached handler
633                          * and clear any hw_handler_params associated with the
634                          * ignored handler.
635                          *
636                          * NB. This modifies the table line to show the actual
637                          * handler instead of the original table passed in.
638                          */
639                         kfree(m->hw_handler_name);
640                         m->hw_handler_name = attached_handler_name;
641
642                         kfree(m->hw_handler_params);
643                         m->hw_handler_params = NULL;
644                 }
645         }
646
647         if (m->hw_handler_name) {
648                 r = scsi_dh_attach(q, m->hw_handler_name);
649                 if (r == -EBUSY) {
650                         char b[BDEVNAME_SIZE];
651
652                         printk(KERN_INFO "dm-mpath: retaining handler on device %s\n",
653                                 bdevname(p->path.dev->bdev, b));
654                         goto retain;
655                 }
656                 if (r < 0) {
657                         ti->error = "error attaching hardware handler";
658                         dm_put_device(ti, p->path.dev);
659                         goto bad;
660                 }
661
662                 if (m->hw_handler_params) {
663                         r = scsi_dh_set_params(q, m->hw_handler_params);
664                         if (r < 0) {
665                                 ti->error = "unable to set hardware "
666                                                         "handler parameters";
667                                 dm_put_device(ti, p->path.dev);
668                                 goto bad;
669                         }
670                 }
671         }
672
673         r = ps->type->add_path(ps, &p->path, as->argc, as->argv, &ti->error);
674         if (r) {
675                 dm_put_device(ti, p->path.dev);
676                 goto bad;
677         }
678
679         return p;
680
681  bad:
682         free_pgpath(p);
683         return ERR_PTR(r);
684 }
685
686 static struct priority_group *parse_priority_group(struct dm_arg_set *as,
687                                                    struct multipath *m)
688 {
689         static struct dm_arg _args[] = {
690                 {1, 1024, "invalid number of paths"},
691                 {0, 1024, "invalid number of selector args"}
692         };
693
694         int r;
695         unsigned i, nr_selector_args, nr_args;
696         struct priority_group *pg;
697         struct dm_target *ti = m->ti;
698
699         if (as->argc < 2) {
700                 as->argc = 0;
701                 ti->error = "not enough priority group arguments";
702                 return ERR_PTR(-EINVAL);
703         }
704
705         pg = alloc_priority_group();
706         if (!pg) {
707                 ti->error = "couldn't allocate priority group";
708                 return ERR_PTR(-ENOMEM);
709         }
710         pg->m = m;
711
712         r = parse_path_selector(as, pg, ti);
713         if (r)
714                 goto bad;
715
716         /*
717          * read the paths
718          */
719         r = dm_read_arg(_args, as, &pg->nr_pgpaths, &ti->error);
720         if (r)
721                 goto bad;
722
723         r = dm_read_arg(_args + 1, as, &nr_selector_args, &ti->error);
724         if (r)
725                 goto bad;
726
727         nr_args = 1 + nr_selector_args;
728         for (i = 0; i < pg->nr_pgpaths; i++) {
729                 struct pgpath *pgpath;
730                 struct dm_arg_set path_args;
731
732                 if (as->argc < nr_args) {
733                         ti->error = "not enough path parameters";
734                         r = -EINVAL;
735                         goto bad;
736                 }
737
738                 path_args.argc = nr_args;
739                 path_args.argv = as->argv;
740
741                 pgpath = parse_path(&path_args, &pg->ps, ti);
742                 if (IS_ERR(pgpath)) {
743                         r = PTR_ERR(pgpath);
744                         goto bad;
745                 }
746
747                 pgpath->pg = pg;
748                 list_add_tail(&pgpath->list, &pg->pgpaths);
749                 dm_consume_args(as, nr_args);
750         }
751
752         return pg;
753
754  bad:
755         free_priority_group(pg, ti);
756         return ERR_PTR(r);
757 }
758
759 static int parse_hw_handler(struct dm_arg_set *as, struct multipath *m)
760 {
761         unsigned hw_argc;
762         int ret;
763         struct dm_target *ti = m->ti;
764
765         static struct dm_arg _args[] = {
766                 {0, 1024, "invalid number of hardware handler args"},
767         };
768
769         if (dm_read_arg_group(_args, as, &hw_argc, &ti->error))
770                 return -EINVAL;
771
772         if (!hw_argc)
773                 return 0;
774
775         m->hw_handler_name = kstrdup(dm_shift_arg(as), GFP_KERNEL);
776
777         if (hw_argc > 1) {
778                 char *p;
779                 int i, j, len = 4;
780
781                 for (i = 0; i <= hw_argc - 2; i++)
782                         len += strlen(as->argv[i]) + 1;
783                 p = m->hw_handler_params = kzalloc(len, GFP_KERNEL);
784                 if (!p) {
785                         ti->error = "memory allocation failed";
786                         ret = -ENOMEM;
787                         goto fail;
788                 }
789                 j = sprintf(p, "%d", hw_argc - 1);
790                 for (i = 0, p+=j+1; i <= hw_argc - 2; i++, p+=j+1)
791                         j = sprintf(p, "%s", as->argv[i]);
792         }
793         dm_consume_args(as, hw_argc - 1);
794
795         return 0;
796 fail:
797         kfree(m->hw_handler_name);
798         m->hw_handler_name = NULL;
799         return ret;
800 }
801
802 static int parse_features(struct dm_arg_set *as, struct multipath *m)
803 {
804         int r;
805         unsigned argc;
806         struct dm_target *ti = m->ti;
807         const char *arg_name;
808
809         static struct dm_arg _args[] = {
810                 {0, 6, "invalid number of feature args"},
811                 {1, 50, "pg_init_retries must be between 1 and 50"},
812                 {0, 60000, "pg_init_delay_msecs must be between 0 and 60000"},
813         };
814
815         r = dm_read_arg_group(_args, as, &argc, &ti->error);
816         if (r)
817                 return -EINVAL;
818
819         if (!argc)
820                 return 0;
821
822         do {
823                 arg_name = dm_shift_arg(as);
824                 argc--;
825
826                 if (!strcasecmp(arg_name, "queue_if_no_path")) {
827                         r = queue_if_no_path(m, true, false);
828                         continue;
829                 }
830
831                 if (!strcasecmp(arg_name, "retain_attached_hw_handler")) {
832                         set_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags);
833                         continue;
834                 }
835
836                 if (!strcasecmp(arg_name, "pg_init_retries") &&
837                     (argc >= 1)) {
838                         r = dm_read_arg(_args + 1, as, &m->pg_init_retries, &ti->error);
839                         argc--;
840                         continue;
841                 }
842
843                 if (!strcasecmp(arg_name, "pg_init_delay_msecs") &&
844                     (argc >= 1)) {
845                         r = dm_read_arg(_args + 2, as, &m->pg_init_delay_msecs, &ti->error);
846                         argc--;
847                         continue;
848                 }
849
850                 ti->error = "Unrecognised multipath feature request";
851                 r = -EINVAL;
852         } while (argc && !r);
853
854         return r;
855 }
856
857 static int multipath_ctr(struct dm_target *ti, unsigned int argc,
858                          char **argv)
859 {
860         /* target arguments */
861         static struct dm_arg _args[] = {
862                 {0, 1024, "invalid number of priority groups"},
863                 {0, 1024, "invalid initial priority group number"},
864         };
865
866         int r;
867         struct multipath *m;
868         struct dm_arg_set as;
869         unsigned pg_count = 0;
870         unsigned next_pg_num;
871         bool use_blk_mq = dm_use_blk_mq(dm_table_get_md(ti->table));
872
873         as.argc = argc;
874         as.argv = argv;
875
876         m = alloc_multipath(ti, use_blk_mq);
877         if (!m) {
878                 ti->error = "can't allocate multipath";
879                 return -EINVAL;
880         }
881
882         r = parse_features(&as, m);
883         if (r)
884                 goto bad;
885
886         r = parse_hw_handler(&as, m);
887         if (r)
888                 goto bad;
889
890         r = dm_read_arg(_args, &as, &m->nr_priority_groups, &ti->error);
891         if (r)
892                 goto bad;
893
894         r = dm_read_arg(_args + 1, &as, &next_pg_num, &ti->error);
895         if (r)
896                 goto bad;
897
898         if ((!m->nr_priority_groups && next_pg_num) ||
899             (m->nr_priority_groups && !next_pg_num)) {
900                 ti->error = "invalid initial priority group";
901                 r = -EINVAL;
902                 goto bad;
903         }
904
905         /* parse the priority groups */
906         while (as.argc) {
907                 struct priority_group *pg;
908                 unsigned nr_valid_paths = atomic_read(&m->nr_valid_paths);
909
910                 pg = parse_priority_group(&as, m);
911                 if (IS_ERR(pg)) {
912                         r = PTR_ERR(pg);
913                         goto bad;
914                 }
915
916                 nr_valid_paths += pg->nr_pgpaths;
917                 atomic_set(&m->nr_valid_paths, nr_valid_paths);
918
919                 list_add_tail(&pg->list, &m->priority_groups);
920                 pg_count++;
921                 pg->pg_num = pg_count;
922                 if (!--next_pg_num)
923                         m->next_pg = pg;
924         }
925
926         if (pg_count != m->nr_priority_groups) {
927                 ti->error = "priority group count mismatch";
928                 r = -EINVAL;
929                 goto bad;
930         }
931
932         ti->num_flush_bios = 1;
933         ti->num_discard_bios = 1;
934         ti->num_write_same_bios = 1;
935         if (use_blk_mq)
936                 ti->per_io_data_size = sizeof(struct dm_mpath_io);
937
938         return 0;
939
940  bad:
941         free_multipath(m);
942         return r;
943 }
944
945 static void multipath_wait_for_pg_init_completion(struct multipath *m)
946 {
947         DECLARE_WAITQUEUE(wait, current);
948
949         add_wait_queue(&m->pg_init_wait, &wait);
950
951         while (1) {
952                 set_current_state(TASK_UNINTERRUPTIBLE);
953
954                 if (!atomic_read(&m->pg_init_in_progress))
955                         break;
956
957                 io_schedule();
958         }
959         set_current_state(TASK_RUNNING);
960
961         remove_wait_queue(&m->pg_init_wait, &wait);
962 }
963
964 static void flush_multipath_work(struct multipath *m)
965 {
966         set_bit(MPATHF_PG_INIT_DISABLED, &m->flags);
967         smp_mb__after_atomic();
968
969         flush_workqueue(kmpath_handlerd);
970         multipath_wait_for_pg_init_completion(m);
971         flush_workqueue(kmultipathd);
972         flush_work(&m->trigger_event);
973
974         clear_bit(MPATHF_PG_INIT_DISABLED, &m->flags);
975         smp_mb__after_atomic();
976 }
977
978 static void multipath_dtr(struct dm_target *ti)
979 {
980         struct multipath *m = ti->private;
981
982         flush_multipath_work(m);
983         free_multipath(m);
984 }
985
986 /*
987  * Take a path out of use.
988  */
989 static int fail_path(struct pgpath *pgpath)
990 {
991         unsigned long flags;
992         struct multipath *m = pgpath->pg->m;
993
994         spin_lock_irqsave(&m->lock, flags);
995
996         if (!pgpath->is_active)
997                 goto out;
998
999         DMWARN("Failing path %s.", pgpath->path.dev->name);
1000
1001         pgpath->pg->ps.type->fail_path(&pgpath->pg->ps, &pgpath->path);
1002         pgpath->is_active = false;
1003         pgpath->fail_count++;
1004
1005         atomic_dec(&m->nr_valid_paths);
1006
1007         if (pgpath == m->current_pgpath)
1008                 m->current_pgpath = NULL;
1009
1010         dm_path_uevent(DM_UEVENT_PATH_FAILED, m->ti,
1011                        pgpath->path.dev->name, atomic_read(&m->nr_valid_paths));
1012
1013         schedule_work(&m->trigger_event);
1014
1015 out:
1016         spin_unlock_irqrestore(&m->lock, flags);
1017
1018         return 0;
1019 }
1020
1021 /*
1022  * Reinstate a previously-failed path
1023  */
1024 static int reinstate_path(struct pgpath *pgpath)
1025 {
1026         int r = 0, run_queue = 0;
1027         unsigned long flags;
1028         struct multipath *m = pgpath->pg->m;
1029         unsigned nr_valid_paths;
1030
1031         spin_lock_irqsave(&m->lock, flags);
1032
1033         if (pgpath->is_active)
1034                 goto out;
1035
1036         DMWARN("Reinstating path %s.", pgpath->path.dev->name);
1037
1038         r = pgpath->pg->ps.type->reinstate_path(&pgpath->pg->ps, &pgpath->path);
1039         if (r)
1040                 goto out;
1041
1042         pgpath->is_active = true;
1043
1044         nr_valid_paths = atomic_inc_return(&m->nr_valid_paths);
1045         if (nr_valid_paths == 1) {
1046                 m->current_pgpath = NULL;
1047                 run_queue = 1;
1048         } else if (m->hw_handler_name && (m->current_pg == pgpath->pg)) {
1049                 if (queue_work(kmpath_handlerd, &pgpath->activate_path.work))
1050                         atomic_inc(&m->pg_init_in_progress);
1051         }
1052
1053         dm_path_uevent(DM_UEVENT_PATH_REINSTATED, m->ti,
1054                        pgpath->path.dev->name, nr_valid_paths);
1055
1056         schedule_work(&m->trigger_event);
1057
1058 out:
1059         spin_unlock_irqrestore(&m->lock, flags);
1060         if (run_queue)
1061                 dm_table_run_md_queue_async(m->ti->table);
1062
1063         return r;
1064 }
1065
1066 /*
1067  * Fail or reinstate all paths that match the provided struct dm_dev.
1068  */
1069 static int action_dev(struct multipath *m, struct dm_dev *dev,
1070                       action_fn action)
1071 {
1072         int r = -EINVAL;
1073         struct pgpath *pgpath;
1074         struct priority_group *pg;
1075
1076         list_for_each_entry(pg, &m->priority_groups, list) {
1077                 list_for_each_entry(pgpath, &pg->pgpaths, list) {
1078                         if (pgpath->path.dev == dev)
1079                                 r = action(pgpath);
1080                 }
1081         }
1082
1083         return r;
1084 }
1085
1086 /*
1087  * Temporarily try to avoid having to use the specified PG
1088  */
1089 static void bypass_pg(struct multipath *m, struct priority_group *pg,
1090                       bool bypassed)
1091 {
1092         unsigned long flags;
1093
1094         spin_lock_irqsave(&m->lock, flags);
1095
1096         pg->bypassed = bypassed;
1097         m->current_pgpath = NULL;
1098         m->current_pg = NULL;
1099
1100         spin_unlock_irqrestore(&m->lock, flags);
1101
1102         schedule_work(&m->trigger_event);
1103 }
1104
1105 /*
1106  * Switch to using the specified PG from the next I/O that gets mapped
1107  */
1108 static int switch_pg_num(struct multipath *m, const char *pgstr)
1109 {
1110         struct priority_group *pg;
1111         unsigned pgnum;
1112         unsigned long flags;
1113         char dummy;
1114
1115         if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1116             (pgnum > m->nr_priority_groups)) {
1117                 DMWARN("invalid PG number supplied to switch_pg_num");
1118                 return -EINVAL;
1119         }
1120
1121         spin_lock_irqsave(&m->lock, flags);
1122         list_for_each_entry(pg, &m->priority_groups, list) {
1123                 pg->bypassed = false;
1124                 if (--pgnum)
1125                         continue;
1126
1127                 m->current_pgpath = NULL;
1128                 m->current_pg = NULL;
1129                 m->next_pg = pg;
1130         }
1131         spin_unlock_irqrestore(&m->lock, flags);
1132
1133         schedule_work(&m->trigger_event);
1134         return 0;
1135 }
1136
1137 /*
1138  * Set/clear bypassed status of a PG.
1139  * PGs are numbered upwards from 1 in the order they were declared.
1140  */
1141 static int bypass_pg_num(struct multipath *m, const char *pgstr, bool bypassed)
1142 {
1143         struct priority_group *pg;
1144         unsigned pgnum;
1145         char dummy;
1146
1147         if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1148             (pgnum > m->nr_priority_groups)) {
1149                 DMWARN("invalid PG number supplied to bypass_pg");
1150                 return -EINVAL;
1151         }
1152
1153         list_for_each_entry(pg, &m->priority_groups, list) {
1154                 if (!--pgnum)
1155                         break;
1156         }
1157
1158         bypass_pg(m, pg, bypassed);
1159         return 0;
1160 }
1161
1162 /*
1163  * Should we retry pg_init immediately?
1164  */
1165 static bool pg_init_limit_reached(struct multipath *m, struct pgpath *pgpath)
1166 {
1167         unsigned long flags;
1168         bool limit_reached = false;
1169
1170         spin_lock_irqsave(&m->lock, flags);
1171
1172         if (atomic_read(&m->pg_init_count) <= m->pg_init_retries &&
1173             !test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
1174                 set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
1175         else
1176                 limit_reached = true;
1177
1178         spin_unlock_irqrestore(&m->lock, flags);
1179
1180         return limit_reached;
1181 }
1182
1183 static void pg_init_done(void *data, int errors)
1184 {
1185         struct pgpath *pgpath = data;
1186         struct priority_group *pg = pgpath->pg;
1187         struct multipath *m = pg->m;
1188         unsigned long flags;
1189         bool delay_retry = false;
1190
1191         /* device or driver problems */
1192         switch (errors) {
1193         case SCSI_DH_OK:
1194                 break;
1195         case SCSI_DH_NOSYS:
1196                 if (!m->hw_handler_name) {
1197                         errors = 0;
1198                         break;
1199                 }
1200                 DMERR("Could not failover the device: Handler scsi_dh_%s "
1201                       "Error %d.", m->hw_handler_name, errors);
1202                 /*
1203                  * Fail path for now, so we do not ping pong
1204                  */
1205                 fail_path(pgpath);
1206                 break;
1207         case SCSI_DH_DEV_TEMP_BUSY:
1208                 /*
1209                  * Probably doing something like FW upgrade on the
1210                  * controller so try the other pg.
1211                  */
1212                 bypass_pg(m, pg, true);
1213                 break;
1214         case SCSI_DH_RETRY:
1215                 /* Wait before retrying. */
1216                 delay_retry = 1;
1217         case SCSI_DH_IMM_RETRY:
1218         case SCSI_DH_RES_TEMP_UNAVAIL:
1219                 if (pg_init_limit_reached(m, pgpath))
1220                         fail_path(pgpath);
1221                 errors = 0;
1222                 break;
1223         case SCSI_DH_DEV_OFFLINED:
1224         default:
1225                 /*
1226                  * We probably do not want to fail the path for a device
1227                  * error, but this is what the old dm did. In future
1228                  * patches we can do more advanced handling.
1229                  */
1230                 fail_path(pgpath);
1231         }
1232
1233         spin_lock_irqsave(&m->lock, flags);
1234         if (errors) {
1235                 if (pgpath == m->current_pgpath) {
1236                         DMERR("Could not failover device. Error %d.", errors);
1237                         m->current_pgpath = NULL;
1238                         m->current_pg = NULL;
1239                 }
1240         } else if (!test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
1241                 pg->bypassed = false;
1242
1243         if (atomic_dec_return(&m->pg_init_in_progress) > 0)
1244                 /* Activations of other paths are still on going */
1245                 goto out;
1246
1247         if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags)) {
1248                 if (delay_retry)
1249                         set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1250                 else
1251                         clear_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1252
1253                 if (__pg_init_all_paths(m))
1254                         goto out;
1255         }
1256         clear_bit(MPATHF_QUEUE_IO, &m->flags);
1257
1258         /*
1259          * Wake up any thread waiting to suspend.
1260          */
1261         wake_up(&m->pg_init_wait);
1262
1263 out:
1264         spin_unlock_irqrestore(&m->lock, flags);
1265 }
1266
1267 static void activate_path(struct work_struct *work)
1268 {
1269         struct pgpath *pgpath =
1270                 container_of(work, struct pgpath, activate_path.work);
1271
1272         if (pgpath->is_active)
1273                 scsi_dh_activate(bdev_get_queue(pgpath->path.dev->bdev),
1274                                  pg_init_done, pgpath);
1275         else
1276                 pg_init_done(pgpath, SCSI_DH_DEV_OFFLINED);
1277 }
1278
1279 static int noretry_error(int error)
1280 {
1281         switch (error) {
1282         case -EOPNOTSUPP:
1283         case -EREMOTEIO:
1284         case -EILSEQ:
1285         case -ENODATA:
1286         case -ENOSPC:
1287                 return 1;
1288         }
1289
1290         /* Anything else could be a path failure, so should be retried */
1291         return 0;
1292 }
1293
1294 /*
1295  * end_io handling
1296  */
1297 static int do_end_io(struct multipath *m, struct request *clone,
1298                      int error, struct dm_mpath_io *mpio)
1299 {
1300         /*
1301          * We don't queue any clone request inside the multipath target
1302          * during end I/O handling, since those clone requests don't have
1303          * bio clones.  If we queue them inside the multipath target,
1304          * we need to make bio clones, that requires memory allocation.
1305          * (See drivers/md/dm.c:end_clone_bio() about why the clone requests
1306          *  don't have bio clones.)
1307          * Instead of queueing the clone request here, we queue the original
1308          * request into dm core, which will remake a clone request and
1309          * clone bios for it and resubmit it later.
1310          */
1311         int r = DM_ENDIO_REQUEUE;
1312         unsigned long flags;
1313
1314         if (!error && !clone->errors)
1315                 return 0;       /* I/O complete */
1316
1317         if (noretry_error(error))
1318                 return error;
1319
1320         if (mpio->pgpath)
1321                 fail_path(mpio->pgpath);
1322
1323         spin_lock_irqsave(&m->lock, flags);
1324         if (!atomic_read(&m->nr_valid_paths)) {
1325                 if (!test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
1326                         if (!__must_push_back(m))
1327                                 r = -EIO;
1328                 } else {
1329                         if (error == -EBADE)
1330                                 r = error;
1331                 }
1332         }
1333         spin_unlock_irqrestore(&m->lock, flags);
1334
1335         return r;
1336 }
1337
1338 static int multipath_end_io(struct dm_target *ti, struct request *clone,
1339                             int error, union map_info *map_context)
1340 {
1341         struct multipath *m = ti->private;
1342         struct dm_mpath_io *mpio = get_mpio(map_context);
1343         struct pgpath *pgpath;
1344         struct path_selector *ps;
1345         int r;
1346
1347         BUG_ON(!mpio);
1348
1349         r = do_end_io(m, clone, error, mpio);
1350         pgpath = mpio->pgpath;
1351         if (pgpath) {
1352                 ps = &pgpath->pg->ps;
1353                 if (ps->type->end_io)
1354                         ps->type->end_io(ps, &pgpath->path, mpio->nr_bytes);
1355         }
1356         clear_request_fn_mpio(m, map_context);
1357
1358         return r;
1359 }
1360
1361 /*
1362  * Suspend can't complete until all the I/O is processed so if
1363  * the last path fails we must error any remaining I/O.
1364  * Note that if the freeze_bdev fails while suspending, the
1365  * queue_if_no_path state is lost - userspace should reset it.
1366  */
1367 static void multipath_presuspend(struct dm_target *ti)
1368 {
1369         struct multipath *m = ti->private;
1370
1371         queue_if_no_path(m, false, true);
1372 }
1373
1374 static void multipath_postsuspend(struct dm_target *ti)
1375 {
1376         struct multipath *m = ti->private;
1377
1378         mutex_lock(&m->work_mutex);
1379         flush_multipath_work(m);
1380         mutex_unlock(&m->work_mutex);
1381 }
1382
1383 /*
1384  * Restore the queue_if_no_path setting.
1385  */
1386 static void multipath_resume(struct dm_target *ti)
1387 {
1388         struct multipath *m = ti->private;
1389
1390         if (test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags))
1391                 set_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
1392         else
1393                 clear_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
1394         smp_mb__after_atomic();
1395 }
1396
1397 /*
1398  * Info output has the following format:
1399  * num_multipath_feature_args [multipath_feature_args]*
1400  * num_handler_status_args [handler_status_args]*
1401  * num_groups init_group_number
1402  *            [A|D|E num_ps_status_args [ps_status_args]*
1403  *             num_paths num_selector_args
1404  *             [path_dev A|F fail_count [selector_args]* ]+ ]+
1405  *
1406  * Table output has the following format (identical to the constructor string):
1407  * num_feature_args [features_args]*
1408  * num_handler_args hw_handler [hw_handler_args]*
1409  * num_groups init_group_number
1410  *     [priority selector-name num_ps_args [ps_args]*
1411  *      num_paths num_selector_args [path_dev [selector_args]* ]+ ]+
1412  */
1413 static void multipath_status(struct dm_target *ti, status_type_t type,
1414                              unsigned status_flags, char *result, unsigned maxlen)
1415 {
1416         int sz = 0;
1417         unsigned long flags;
1418         struct multipath *m = ti->private;
1419         struct priority_group *pg;
1420         struct pgpath *p;
1421         unsigned pg_num;
1422         char state;
1423
1424         spin_lock_irqsave(&m->lock, flags);
1425
1426         /* Features */
1427         if (type == STATUSTYPE_INFO)
1428                 DMEMIT("2 %u %u ", test_bit(MPATHF_QUEUE_IO, &m->flags),
1429                        atomic_read(&m->pg_init_count));
1430         else {
1431                 DMEMIT("%u ", test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) +
1432                               (m->pg_init_retries > 0) * 2 +
1433                               (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT) * 2 +
1434                               test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags));
1435                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
1436                         DMEMIT("queue_if_no_path ");
1437                 if (m->pg_init_retries)
1438                         DMEMIT("pg_init_retries %u ", m->pg_init_retries);
1439                 if (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT)
1440                         DMEMIT("pg_init_delay_msecs %u ", m->pg_init_delay_msecs);
1441                 if (test_bit(MPATHF_RETAIN_ATTACHED_HW_HANDLER, &m->flags))
1442                         DMEMIT("retain_attached_hw_handler ");
1443         }
1444
1445         if (!m->hw_handler_name || type == STATUSTYPE_INFO)
1446                 DMEMIT("0 ");
1447         else
1448                 DMEMIT("1 %s ", m->hw_handler_name);
1449
1450         DMEMIT("%u ", m->nr_priority_groups);
1451
1452         if (m->next_pg)
1453                 pg_num = m->next_pg->pg_num;
1454         else if (m->current_pg)
1455                 pg_num = m->current_pg->pg_num;
1456         else
1457                 pg_num = (m->nr_priority_groups ? 1 : 0);
1458
1459         DMEMIT("%u ", pg_num);
1460
1461         switch (type) {
1462         case STATUSTYPE_INFO:
1463                 list_for_each_entry(pg, &m->priority_groups, list) {
1464                         if (pg->bypassed)
1465                                 state = 'D';    /* Disabled */
1466                         else if (pg == m->current_pg)
1467                                 state = 'A';    /* Currently Active */
1468                         else
1469                                 state = 'E';    /* Enabled */
1470
1471                         DMEMIT("%c ", state);
1472
1473                         if (pg->ps.type->status)
1474                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1475                                                           result + sz,
1476                                                           maxlen - sz);
1477                         else
1478                                 DMEMIT("0 ");
1479
1480                         DMEMIT("%u %u ", pg->nr_pgpaths,
1481                                pg->ps.type->info_args);
1482
1483                         list_for_each_entry(p, &pg->pgpaths, list) {
1484                                 DMEMIT("%s %s %u ", p->path.dev->name,
1485                                        p->is_active ? "A" : "F",
1486                                        p->fail_count);
1487                                 if (pg->ps.type->status)
1488                                         sz += pg->ps.type->status(&pg->ps,
1489                                               &p->path, type, result + sz,
1490                                               maxlen - sz);
1491                         }
1492                 }
1493                 break;
1494
1495         case STATUSTYPE_TABLE:
1496                 list_for_each_entry(pg, &m->priority_groups, list) {
1497                         DMEMIT("%s ", pg->ps.type->name);
1498
1499                         if (pg->ps.type->status)
1500                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1501                                                           result + sz,
1502                                                           maxlen - sz);
1503                         else
1504                                 DMEMIT("0 ");
1505
1506                         DMEMIT("%u %u ", pg->nr_pgpaths,
1507                                pg->ps.type->table_args);
1508
1509                         list_for_each_entry(p, &pg->pgpaths, list) {
1510                                 DMEMIT("%s ", p->path.dev->name);
1511                                 if (pg->ps.type->status)
1512                                         sz += pg->ps.type->status(&pg->ps,
1513                                               &p->path, type, result + sz,
1514                                               maxlen - sz);
1515                         }
1516                 }
1517                 break;
1518         }
1519
1520         spin_unlock_irqrestore(&m->lock, flags);
1521 }
1522
1523 static int multipath_message(struct dm_target *ti, unsigned argc, char **argv)
1524 {
1525         int r = -EINVAL;
1526         struct dm_dev *dev;
1527         struct multipath *m = ti->private;
1528         action_fn action;
1529
1530         mutex_lock(&m->work_mutex);
1531
1532         if (dm_suspended(ti)) {
1533                 r = -EBUSY;
1534                 goto out;
1535         }
1536
1537         if (argc == 1) {
1538                 if (!strcasecmp(argv[0], "queue_if_no_path")) {
1539                         r = queue_if_no_path(m, true, false);
1540                         goto out;
1541                 } else if (!strcasecmp(argv[0], "fail_if_no_path")) {
1542                         r = queue_if_no_path(m, false, false);
1543                         goto out;
1544                 }
1545         }
1546
1547         if (argc != 2) {
1548                 DMWARN("Invalid multipath message arguments. Expected 2 arguments, got %d.", argc);
1549                 goto out;
1550         }
1551
1552         if (!strcasecmp(argv[0], "disable_group")) {
1553                 r = bypass_pg_num(m, argv[1], true);
1554                 goto out;
1555         } else if (!strcasecmp(argv[0], "enable_group")) {
1556                 r = bypass_pg_num(m, argv[1], false);
1557                 goto out;
1558         } else if (!strcasecmp(argv[0], "switch_group")) {
1559                 r = switch_pg_num(m, argv[1]);
1560                 goto out;
1561         } else if (!strcasecmp(argv[0], "reinstate_path"))
1562                 action = reinstate_path;
1563         else if (!strcasecmp(argv[0], "fail_path"))
1564                 action = fail_path;
1565         else {
1566                 DMWARN("Unrecognised multipath message received: %s", argv[0]);
1567                 goto out;
1568         }
1569
1570         r = dm_get_device(ti, argv[1], dm_table_get_mode(ti->table), &dev);
1571         if (r) {
1572                 DMWARN("message: error getting device %s",
1573                        argv[1]);
1574                 goto out;
1575         }
1576
1577         r = action_dev(m, dev, action);
1578
1579         dm_put_device(ti, dev);
1580
1581 out:
1582         mutex_unlock(&m->work_mutex);
1583         return r;
1584 }
1585
1586 static int multipath_prepare_ioctl(struct dm_target *ti,
1587                 struct block_device **bdev, fmode_t *mode)
1588 {
1589         struct multipath *m = ti->private;
1590         unsigned long flags;
1591         int r;
1592
1593         spin_lock_irqsave(&m->lock, flags);
1594
1595         if (!m->current_pgpath)
1596                 __choose_pgpath(m, 0);
1597
1598         if (m->current_pgpath) {
1599                 if (!test_bit(MPATHF_QUEUE_IO, &m->flags)) {
1600                         *bdev = m->current_pgpath->path.dev->bdev;
1601                         *mode = m->current_pgpath->path.dev->mode;
1602                         r = 0;
1603                 } else {
1604                         /* pg_init has not started or completed */
1605                         r = -ENOTCONN;
1606                 }
1607         } else {
1608                 /* No path is available */
1609                 if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
1610                         r = -ENOTCONN;
1611                 else
1612                         r = -EIO;
1613         }
1614
1615         spin_unlock_irqrestore(&m->lock, flags);
1616
1617         if (r == -ENOTCONN) {
1618                 spin_lock_irqsave(&m->lock, flags);
1619                 if (!m->current_pg) {
1620                         /* Path status changed, redo selection */
1621                         __choose_pgpath(m, 0);
1622                 }
1623                 if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
1624                         __pg_init_all_paths(m);
1625                 spin_unlock_irqrestore(&m->lock, flags);
1626                 dm_table_run_md_queue_async(m->ti->table);
1627         }
1628
1629         /*
1630          * Only pass ioctls through if the device sizes match exactly.
1631          */
1632         if (!r && ti->len != i_size_read((*bdev)->bd_inode) >> SECTOR_SHIFT)
1633                 return 1;
1634         return r;
1635 }
1636
1637 static int multipath_iterate_devices(struct dm_target *ti,
1638                                      iterate_devices_callout_fn fn, void *data)
1639 {
1640         struct multipath *m = ti->private;
1641         struct priority_group *pg;
1642         struct pgpath *p;
1643         int ret = 0;
1644
1645         list_for_each_entry(pg, &m->priority_groups, list) {
1646                 list_for_each_entry(p, &pg->pgpaths, list) {
1647                         ret = fn(ti, p->path.dev, ti->begin, ti->len, data);
1648                         if (ret)
1649                                 goto out;
1650                 }
1651         }
1652
1653 out:
1654         return ret;
1655 }
1656
1657 static int pgpath_busy(struct pgpath *pgpath)
1658 {
1659         struct request_queue *q = bdev_get_queue(pgpath->path.dev->bdev);
1660
1661         return blk_lld_busy(q);
1662 }
1663
1664 /*
1665  * We return "busy", only when we can map I/Os but underlying devices
1666  * are busy (so even if we map I/Os now, the I/Os will wait on
1667  * the underlying queue).
1668  * In other words, if we want to kill I/Os or queue them inside us
1669  * due to map unavailability, we don't return "busy".  Otherwise,
1670  * dm core won't give us the I/Os and we can't do what we want.
1671  */
1672 static int multipath_busy(struct dm_target *ti)
1673 {
1674         bool busy = false, has_active = false;
1675         struct multipath *m = ti->private;
1676         struct priority_group *pg;
1677         struct pgpath *pgpath;
1678         unsigned long flags;
1679
1680         spin_lock_irqsave(&m->lock, flags);
1681
1682         /* pg_init in progress or no paths available */
1683         if (atomic_read(&m->pg_init_in_progress) ||
1684             (!atomic_read(&m->nr_valid_paths) && test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))) {
1685                 busy = true;
1686                 goto out;
1687         }
1688         /* Guess which priority_group will be used at next mapping time */
1689         if (unlikely(!m->current_pgpath && m->next_pg))
1690                 pg = m->next_pg;
1691         else if (likely(m->current_pg))
1692                 pg = m->current_pg;
1693         else
1694                 /*
1695                  * We don't know which pg will be used at next mapping time.
1696                  * We don't call __choose_pgpath() here to avoid to trigger
1697                  * pg_init just by busy checking.
1698                  * So we don't know whether underlying devices we will be using
1699                  * at next mapping time are busy or not. Just try mapping.
1700                  */
1701                 goto out;
1702
1703         /*
1704          * If there is one non-busy active path at least, the path selector
1705          * will be able to select it. So we consider such a pg as not busy.
1706          */
1707         busy = true;
1708         list_for_each_entry(pgpath, &pg->pgpaths, list)
1709                 if (pgpath->is_active) {
1710                         has_active = true;
1711                         if (!pgpath_busy(pgpath)) {
1712                                 busy = false;
1713                                 break;
1714                         }
1715                 }
1716
1717         if (!has_active)
1718                 /*
1719                  * No active path in this pg, so this pg won't be used and
1720                  * the current_pg will be changed at next mapping time.
1721                  * We need to try mapping to determine it.
1722                  */
1723                 busy = false;
1724
1725 out:
1726         spin_unlock_irqrestore(&m->lock, flags);
1727
1728         return busy;
1729 }
1730
1731 /*-----------------------------------------------------------------
1732  * Module setup
1733  *---------------------------------------------------------------*/
1734 static struct target_type multipath_target = {
1735         .name = "multipath",
1736         .version = {1, 11, 0},
1737         .features = DM_TARGET_SINGLETON | DM_TARGET_IMMUTABLE,
1738         .module = THIS_MODULE,
1739         .ctr = multipath_ctr,
1740         .dtr = multipath_dtr,
1741         .map_rq = multipath_map,
1742         .clone_and_map_rq = multipath_clone_and_map,
1743         .release_clone_rq = multipath_release_clone,
1744         .rq_end_io = multipath_end_io,
1745         .presuspend = multipath_presuspend,
1746         .postsuspend = multipath_postsuspend,
1747         .resume = multipath_resume,
1748         .status = multipath_status,
1749         .message = multipath_message,
1750         .prepare_ioctl = multipath_prepare_ioctl,
1751         .iterate_devices = multipath_iterate_devices,
1752         .busy = multipath_busy,
1753 };
1754
1755 static int __init dm_multipath_init(void)
1756 {
1757         int r;
1758
1759         /* allocate a slab for the dm_ios */
1760         _mpio_cache = KMEM_CACHE(dm_mpath_io, 0);
1761         if (!_mpio_cache)
1762                 return -ENOMEM;
1763
1764         r = dm_register_target(&multipath_target);
1765         if (r < 0) {
1766                 DMERR("register failed %d", r);
1767                 r = -EINVAL;
1768                 goto bad_register_target;
1769         }
1770
1771         kmultipathd = alloc_workqueue("kmpathd", WQ_MEM_RECLAIM, 0);
1772         if (!kmultipathd) {
1773                 DMERR("failed to create workqueue kmpathd");
1774                 r = -ENOMEM;
1775                 goto bad_alloc_kmultipathd;
1776         }
1777
1778         /*
1779          * A separate workqueue is used to handle the device handlers
1780          * to avoid overloading existing workqueue. Overloading the
1781          * old workqueue would also create a bottleneck in the
1782          * path of the storage hardware device activation.
1783          */
1784         kmpath_handlerd = alloc_ordered_workqueue("kmpath_handlerd",
1785                                                   WQ_MEM_RECLAIM);
1786         if (!kmpath_handlerd) {
1787                 DMERR("failed to create workqueue kmpath_handlerd");
1788                 r = -ENOMEM;
1789                 goto bad_alloc_kmpath_handlerd;
1790         }
1791
1792         DMINFO("version %u.%u.%u loaded",
1793                multipath_target.version[0], multipath_target.version[1],
1794                multipath_target.version[2]);
1795
1796         return 0;
1797
1798 bad_alloc_kmpath_handlerd:
1799         destroy_workqueue(kmultipathd);
1800 bad_alloc_kmultipathd:
1801         dm_unregister_target(&multipath_target);
1802 bad_register_target:
1803         kmem_cache_destroy(_mpio_cache);
1804
1805         return r;
1806 }
1807
1808 static void __exit dm_multipath_exit(void)
1809 {
1810         destroy_workqueue(kmpath_handlerd);
1811         destroy_workqueue(kmultipathd);
1812
1813         dm_unregister_target(&multipath_target);
1814         kmem_cache_destroy(_mpio_cache);
1815 }
1816
1817 module_init(dm_multipath_init);
1818 module_exit(dm_multipath_exit);
1819
1820 MODULE_DESCRIPTION(DM_NAME " multipath target");
1821 MODULE_AUTHOR("Sistina Software <dm-devel@redhat.com>");
1822 MODULE_LICENSE("GPL");