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