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