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