dm mpath: change attached scsi_dh
[linux-2.6.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-bio-record.h"
12 #include "dm-uevent.h"
13
14 #include <linux/ctype.h>
15 #include <linux/init.h>
16 #include <linux/mempool.h>
17 #include <linux/module.h>
18 #include <linux/pagemap.h>
19 #include <linux/slab.h>
20 #include <linux/time.h>
21 #include <linux/workqueue.h>
22 #include <scsi/scsi_dh.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 };
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         struct work_struct activate_path;
68         struct pgpath *pgpath_to_activate;
69         unsigned nr_priority_groups;
70         struct list_head priority_groups;
71         unsigned pg_init_required;      /* pg_init needs calling? */
72         unsigned pg_init_in_progress;   /* Only one pg_init allowed at once */
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 bio_list 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
99 /*
100  * Context information attached to each bio we process.
101  */
102 struct dm_mpath_io {
103         struct pgpath *pgpath;
104         struct dm_bio_details details;
105 };
106
107 typedef int (*action_fn) (struct pgpath *pgpath);
108
109 #define MIN_IOS 256     /* Mempool size */
110
111 static struct kmem_cache *_mpio_cache;
112
113 static struct workqueue_struct *kmultipathd, *kmpath_handlerd;
114 static void process_queued_ios(struct work_struct *work);
115 static void trigger_event(struct work_struct *work);
116 static void activate_path(struct work_struct *work);
117 static void deactivate_path(struct work_struct *work);
118
119
120 /*-----------------------------------------------
121  * Allocation routines
122  *-----------------------------------------------*/
123
124 static struct pgpath *alloc_pgpath(void)
125 {
126         struct pgpath *pgpath = kzalloc(sizeof(*pgpath), GFP_KERNEL);
127
128         if (pgpath) {
129                 pgpath->is_active = 1;
130                 INIT_WORK(&pgpath->deactivate_path, deactivate_path);
131         }
132
133         return pgpath;
134 }
135
136 static void free_pgpath(struct pgpath *pgpath)
137 {
138         kfree(pgpath);
139 }
140
141 static void deactivate_path(struct work_struct *work)
142 {
143         struct pgpath *pgpath =
144                 container_of(work, struct pgpath, deactivate_path);
145
146         blk_abort_queue(pgpath->path.dev->bdev->bd_disk->queue);
147 }
148
149 static struct priority_group *alloc_priority_group(void)
150 {
151         struct priority_group *pg;
152
153         pg = kzalloc(sizeof(*pg), GFP_KERNEL);
154
155         if (pg)
156                 INIT_LIST_HEAD(&pg->pgpaths);
157
158         return pg;
159 }
160
161 static void free_pgpaths(struct list_head *pgpaths, struct dm_target *ti)
162 {
163         unsigned long flags;
164         struct pgpath *pgpath, *tmp;
165         struct multipath *m = ti->private;
166
167         list_for_each_entry_safe(pgpath, tmp, pgpaths, list) {
168                 list_del(&pgpath->list);
169                 if (m->hw_handler_name)
170                         scsi_dh_detach(bdev_get_queue(pgpath->path.dev->bdev));
171                 dm_put_device(ti, pgpath->path.dev);
172                 spin_lock_irqsave(&m->lock, flags);
173                 if (m->pgpath_to_activate == pgpath)
174                         m->pgpath_to_activate = NULL;
175                 spin_unlock_irqrestore(&m->lock, flags);
176                 free_pgpath(pgpath);
177         }
178 }
179
180 static void free_priority_group(struct priority_group *pg,
181                                 struct dm_target *ti)
182 {
183         struct path_selector *ps = &pg->ps;
184
185         if (ps->type) {
186                 ps->type->destroy(ps);
187                 dm_put_path_selector(ps->type);
188         }
189
190         free_pgpaths(&pg->pgpaths, ti);
191         kfree(pg);
192 }
193
194 static struct multipath *alloc_multipath(struct dm_target *ti)
195 {
196         struct multipath *m;
197
198         m = kzalloc(sizeof(*m), GFP_KERNEL);
199         if (m) {
200                 INIT_LIST_HEAD(&m->priority_groups);
201                 spin_lock_init(&m->lock);
202                 m->queue_io = 1;
203                 INIT_WORK(&m->process_queued_ios, process_queued_ios);
204                 INIT_WORK(&m->trigger_event, trigger_event);
205                 INIT_WORK(&m->activate_path, activate_path);
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         mempool_destroy(m->mpio_pool);
229         kfree(m);
230 }
231
232
233 /*-----------------------------------------------
234  * Path selection
235  *-----------------------------------------------*/
236
237 static void __switch_pg(struct multipath *m, struct pgpath *pgpath)
238 {
239         m->current_pg = pgpath->pg;
240
241         /* Must we initialise the PG first, and queue I/O till it's ready? */
242         if (m->hw_handler_name) {
243                 m->pg_init_required = 1;
244                 m->queue_io = 1;
245         } else {
246                 m->pg_init_required = 0;
247                 m->queue_io = 0;
248         }
249
250         m->pg_init_count = 0;
251 }
252
253 static int __choose_path_in_pg(struct multipath *m, struct priority_group *pg)
254 {
255         struct dm_path *path;
256
257         path = pg->ps.type->select_path(&pg->ps, &m->repeat_count);
258         if (!path)
259                 return -ENXIO;
260
261         m->current_pgpath = path_to_pgpath(path);
262
263         if (m->current_pg != pg)
264                 __switch_pg(m, m->current_pgpath);
265
266         return 0;
267 }
268
269 static void __choose_pgpath(struct multipath *m)
270 {
271         struct priority_group *pg;
272         unsigned bypassed = 1;
273
274         if (!m->nr_valid_paths)
275                 goto failed;
276
277         /* Were we instructed to switch PG? */
278         if (m->next_pg) {
279                 pg = m->next_pg;
280                 m->next_pg = NULL;
281                 if (!__choose_path_in_pg(m, pg))
282                         return;
283         }
284
285         /* Don't change PG until it has no remaining paths */
286         if (m->current_pg && !__choose_path_in_pg(m, m->current_pg))
287                 return;
288
289         /*
290          * Loop through priority groups until we find a valid path.
291          * First time we skip PGs marked 'bypassed'.
292          * Second time we only try the ones we skipped.
293          */
294         do {
295                 list_for_each_entry(pg, &m->priority_groups, list) {
296                         if (pg->bypassed == bypassed)
297                                 continue;
298                         if (!__choose_path_in_pg(m, pg))
299                                 return;
300                 }
301         } while (bypassed--);
302
303 failed:
304         m->current_pgpath = NULL;
305         m->current_pg = NULL;
306 }
307
308 /*
309  * Check whether bios must be queued in the device-mapper core rather
310  * than here in the target.
311  *
312  * m->lock must be held on entry.
313  *
314  * If m->queue_if_no_path and m->saved_queue_if_no_path hold the
315  * same value then we are not between multipath_presuspend()
316  * and multipath_resume() calls and we have no need to check
317  * for the DMF_NOFLUSH_SUSPENDING flag.
318  */
319 static int __must_push_back(struct multipath *m)
320 {
321         return (m->queue_if_no_path != m->saved_queue_if_no_path &&
322                 dm_noflush_suspending(m->ti));
323 }
324
325 static int map_io(struct multipath *m, struct bio *bio,
326                   struct dm_mpath_io *mpio, unsigned was_queued)
327 {
328         int r = DM_MAPIO_REMAPPED;
329         unsigned long flags;
330         struct pgpath *pgpath;
331
332         spin_lock_irqsave(&m->lock, flags);
333
334         /* Do we need to select a new pgpath? */
335         if (!m->current_pgpath ||
336             (!m->queue_io && (m->repeat_count && --m->repeat_count == 0)))
337                 __choose_pgpath(m);
338
339         pgpath = m->current_pgpath;
340
341         if (was_queued)
342                 m->queue_size--;
343
344         if ((pgpath && m->queue_io) ||
345             (!pgpath && m->queue_if_no_path)) {
346                 /* Queue for the daemon to resubmit */
347                 bio_list_add(&m->queued_ios, bio);
348                 m->queue_size++;
349                 if ((m->pg_init_required && !m->pg_init_in_progress) ||
350                     !m->queue_io)
351                         queue_work(kmultipathd, &m->process_queued_ios);
352                 pgpath = NULL;
353                 r = DM_MAPIO_SUBMITTED;
354         } else if (pgpath)
355                 bio->bi_bdev = pgpath->path.dev->bdev;
356         else if (__must_push_back(m))
357                 r = DM_MAPIO_REQUEUE;
358         else
359                 r = -EIO;       /* Failed */
360
361         mpio->pgpath = pgpath;
362
363         spin_unlock_irqrestore(&m->lock, flags);
364
365         return r;
366 }
367
368 /*
369  * If we run out of usable paths, should we queue I/O or error it?
370  */
371 static int queue_if_no_path(struct multipath *m, unsigned queue_if_no_path,
372                             unsigned save_old_value)
373 {
374         unsigned long flags;
375
376         spin_lock_irqsave(&m->lock, flags);
377
378         if (save_old_value)
379                 m->saved_queue_if_no_path = m->queue_if_no_path;
380         else
381                 m->saved_queue_if_no_path = queue_if_no_path;
382         m->queue_if_no_path = queue_if_no_path;
383         if (!m->queue_if_no_path && m->queue_size)
384                 queue_work(kmultipathd, &m->process_queued_ios);
385
386         spin_unlock_irqrestore(&m->lock, flags);
387
388         return 0;
389 }
390
391 /*-----------------------------------------------------------------
392  * The multipath daemon is responsible for resubmitting queued ios.
393  *---------------------------------------------------------------*/
394
395 static void dispatch_queued_ios(struct multipath *m)
396 {
397         int r;
398         unsigned long flags;
399         struct bio *bio = NULL, *next;
400         struct dm_mpath_io *mpio;
401         union map_info *info;
402
403         spin_lock_irqsave(&m->lock, flags);
404         bio = bio_list_get(&m->queued_ios);
405         spin_unlock_irqrestore(&m->lock, flags);
406
407         while (bio) {
408                 next = bio->bi_next;
409                 bio->bi_next = NULL;
410
411                 info = dm_get_mapinfo(bio);
412                 mpio = info->ptr;
413
414                 r = map_io(m, bio, mpio, 1);
415                 if (r < 0)
416                         bio_endio(bio, r);
417                 else if (r == DM_MAPIO_REMAPPED)
418                         generic_make_request(bio);
419                 else if (r == DM_MAPIO_REQUEUE)
420                         bio_endio(bio, -EIO);
421
422                 bio = next;
423         }
424 }
425
426 static void process_queued_ios(struct work_struct *work)
427 {
428         struct multipath *m =
429                 container_of(work, struct multipath, process_queued_ios);
430         struct pgpath *pgpath = NULL;
431         unsigned init_required = 0, must_queue = 1;
432         unsigned long flags;
433
434         spin_lock_irqsave(&m->lock, flags);
435
436         if (!m->queue_size)
437                 goto out;
438
439         if (!m->current_pgpath)
440                 __choose_pgpath(m);
441
442         pgpath = m->current_pgpath;
443
444         if ((pgpath && !m->queue_io) ||
445             (!pgpath && !m->queue_if_no_path))
446                 must_queue = 0;
447
448         if (m->pg_init_required && !m->pg_init_in_progress && pgpath) {
449                 m->pgpath_to_activate = pgpath;
450                 m->pg_init_count++;
451                 m->pg_init_required = 0;
452                 m->pg_init_in_progress = 1;
453                 init_required = 1;
454         }
455
456 out:
457         spin_unlock_irqrestore(&m->lock, flags);
458
459         if (init_required)
460                 queue_work(kmpath_handlerd, &m->activate_path);
461
462         if (!must_queue)
463                 dispatch_queued_ios(m);
464 }
465
466 /*
467  * An event is triggered whenever a path is taken out of use.
468  * Includes path failure and PG bypass.
469  */
470 static void trigger_event(struct work_struct *work)
471 {
472         struct multipath *m =
473                 container_of(work, struct multipath, trigger_event);
474
475         dm_table_event(m->ti->table);
476 }
477
478 /*-----------------------------------------------------------------
479  * Constructor/argument parsing:
480  * <#multipath feature args> [<arg>]*
481  * <#hw_handler args> [hw_handler [<arg>]*]
482  * <#priority groups>
483  * <initial priority group>
484  *     [<selector> <#selector args> [<arg>]*
485  *      <#paths> <#per-path selector args>
486  *         [<path> [<arg>]* ]+ ]+
487  *---------------------------------------------------------------*/
488 struct param {
489         unsigned min;
490         unsigned max;
491         char *error;
492 };
493
494 static int read_param(struct param *param, char *str, unsigned *v, char **error)
495 {
496         if (!str ||
497             (sscanf(str, "%u", v) != 1) ||
498             (*v < param->min) ||
499             (*v > param->max)) {
500                 *error = param->error;
501                 return -EINVAL;
502         }
503
504         return 0;
505 }
506
507 struct arg_set {
508         unsigned argc;
509         char **argv;
510 };
511
512 static char *shift(struct arg_set *as)
513 {
514         char *r;
515
516         if (as->argc) {
517                 as->argc--;
518                 r = *as->argv;
519                 as->argv++;
520                 return r;
521         }
522
523         return NULL;
524 }
525
526 static void consume(struct arg_set *as, unsigned n)
527 {
528         BUG_ON (as->argc < n);
529         as->argc -= n;
530         as->argv += n;
531 }
532
533 static int parse_path_selector(struct arg_set *as, struct priority_group *pg,
534                                struct dm_target *ti)
535 {
536         int r;
537         struct path_selector_type *pst;
538         unsigned ps_argc;
539
540         static struct param _params[] = {
541                 {0, 1024, "invalid number of path selector args"},
542         };
543
544         pst = dm_get_path_selector(shift(as));
545         if (!pst) {
546                 ti->error = "unknown path selector type";
547                 return -EINVAL;
548         }
549
550         r = read_param(_params, shift(as), &ps_argc, &ti->error);
551         if (r) {
552                 dm_put_path_selector(pst);
553                 return -EINVAL;
554         }
555
556         if (ps_argc > as->argc) {
557                 dm_put_path_selector(pst);
558                 ti->error = "not enough arguments for path selector";
559                 return -EINVAL;
560         }
561
562         r = pst->create(&pg->ps, ps_argc, as->argv);
563         if (r) {
564                 dm_put_path_selector(pst);
565                 ti->error = "path selector constructor failed";
566                 return r;
567         }
568
569         pg->ps.type = pst;
570         consume(as, ps_argc);
571
572         return 0;
573 }
574
575 static struct pgpath *parse_path(struct arg_set *as, struct path_selector *ps,
576                                struct dm_target *ti)
577 {
578         int r;
579         struct pgpath *p;
580         struct multipath *m = ti->private;
581
582         /* we need at least a path arg */
583         if (as->argc < 1) {
584                 ti->error = "no device given";
585                 return ERR_PTR(-EINVAL);
586         }
587
588         p = alloc_pgpath();
589         if (!p)
590                 return ERR_PTR(-ENOMEM);
591
592         r = dm_get_device(ti, shift(as), ti->begin, ti->len,
593                           dm_table_get_mode(ti->table), &p->path.dev);
594         if (r) {
595                 ti->error = "error getting device";
596                 goto bad;
597         }
598
599         if (m->hw_handler_name) {
600                 struct request_queue *q = bdev_get_queue(p->path.dev->bdev);
601
602                 r = scsi_dh_attach(q, m->hw_handler_name);
603                 if (r == -EBUSY) {
604                         /*
605                          * Already attached to different hw_handler,
606                          * try to reattach with correct one.
607                          */
608                         scsi_dh_detach(q);
609                         r = scsi_dh_attach(q, m->hw_handler_name);
610                 }
611
612                 if (r < 0) {
613                         ti->error = "error attaching hardware handler";
614                         dm_put_device(ti, p->path.dev);
615                         goto bad;
616                 }
617         }
618
619         r = ps->type->add_path(ps, &p->path, as->argc, as->argv, &ti->error);
620         if (r) {
621                 dm_put_device(ti, p->path.dev);
622                 goto bad;
623         }
624
625         return p;
626
627  bad:
628         free_pgpath(p);
629         return ERR_PTR(r);
630 }
631
632 static struct priority_group *parse_priority_group(struct arg_set *as,
633                                                    struct multipath *m)
634 {
635         static struct param _params[] = {
636                 {1, 1024, "invalid number of paths"},
637                 {0, 1024, "invalid number of selector args"}
638         };
639
640         int r;
641         unsigned i, nr_selector_args, nr_params;
642         struct priority_group *pg;
643         struct dm_target *ti = m->ti;
644
645         if (as->argc < 2) {
646                 as->argc = 0;
647                 ti->error = "not enough priority group arguments";
648                 return ERR_PTR(-EINVAL);
649         }
650
651         pg = alloc_priority_group();
652         if (!pg) {
653                 ti->error = "couldn't allocate priority group";
654                 return ERR_PTR(-ENOMEM);
655         }
656         pg->m = m;
657
658         r = parse_path_selector(as, pg, ti);
659         if (r)
660                 goto bad;
661
662         /*
663          * read the paths
664          */
665         r = read_param(_params, shift(as), &pg->nr_pgpaths, &ti->error);
666         if (r)
667                 goto bad;
668
669         r = read_param(_params + 1, shift(as), &nr_selector_args, &ti->error);
670         if (r)
671                 goto bad;
672
673         nr_params = 1 + nr_selector_args;
674         for (i = 0; i < pg->nr_pgpaths; i++) {
675                 struct pgpath *pgpath;
676                 struct arg_set path_args;
677
678                 if (as->argc < nr_params) {
679                         ti->error = "not enough path parameters";
680                         goto bad;
681                 }
682
683                 path_args.argc = nr_params;
684                 path_args.argv = as->argv;
685
686                 pgpath = parse_path(&path_args, &pg->ps, ti);
687                 if (IS_ERR(pgpath)) {
688                         r = PTR_ERR(pgpath);
689                         goto bad;
690                 }
691
692                 pgpath->pg = pg;
693                 list_add_tail(&pgpath->list, &pg->pgpaths);
694                 consume(as, nr_params);
695         }
696
697         return pg;
698
699  bad:
700         free_priority_group(pg, ti);
701         return ERR_PTR(r);
702 }
703
704 static int parse_hw_handler(struct arg_set *as, struct multipath *m)
705 {
706         unsigned hw_argc;
707         struct dm_target *ti = m->ti;
708
709         static struct param _params[] = {
710                 {0, 1024, "invalid number of hardware handler args"},
711         };
712
713         if (read_param(_params, shift(as), &hw_argc, &ti->error))
714                 return -EINVAL;
715
716         if (!hw_argc)
717                 return 0;
718
719         if (hw_argc > as->argc) {
720                 ti->error = "not enough arguments for hardware handler";
721                 return -EINVAL;
722         }
723
724         m->hw_handler_name = kstrdup(shift(as), GFP_KERNEL);
725         request_module("scsi_dh_%s", m->hw_handler_name);
726         if (scsi_dh_handler_exist(m->hw_handler_name) == 0) {
727                 ti->error = "unknown hardware handler type";
728                 kfree(m->hw_handler_name);
729                 m->hw_handler_name = NULL;
730                 return -EINVAL;
731         }
732
733         if (hw_argc > 1)
734                 DMWARN("Ignoring user-specified arguments for "
735                        "hardware handler \"%s\"", m->hw_handler_name);
736         consume(as, hw_argc - 1);
737
738         return 0;
739 }
740
741 static int parse_features(struct arg_set *as, struct multipath *m)
742 {
743         int r;
744         unsigned argc;
745         struct dm_target *ti = m->ti;
746         const char *param_name;
747
748         static struct param _params[] = {
749                 {0, 3, "invalid number of feature args"},
750                 {1, 50, "pg_init_retries must be between 1 and 50"},
751         };
752
753         r = read_param(_params, shift(as), &argc, &ti->error);
754         if (r)
755                 return -EINVAL;
756
757         if (!argc)
758                 return 0;
759
760         do {
761                 param_name = shift(as);
762                 argc--;
763
764                 if (!strnicmp(param_name, MESG_STR("queue_if_no_path"))) {
765                         r = queue_if_no_path(m, 1, 0);
766                         continue;
767                 }
768
769                 if (!strnicmp(param_name, MESG_STR("pg_init_retries")) &&
770                     (argc >= 1)) {
771                         r = read_param(_params + 1, shift(as),
772                                        &m->pg_init_retries, &ti->error);
773                         argc--;
774                         continue;
775                 }
776
777                 ti->error = "Unrecognised multipath feature request";
778                 r = -EINVAL;
779         } while (argc && !r);
780
781         return r;
782 }
783
784 static int multipath_ctr(struct dm_target *ti, unsigned int argc,
785                          char **argv)
786 {
787         /* target parameters */
788         static struct param _params[] = {
789                 {1, 1024, "invalid number of priority groups"},
790                 {1, 1024, "invalid initial priority group number"},
791         };
792
793         int r;
794         struct multipath *m;
795         struct arg_set as;
796         unsigned pg_count = 0;
797         unsigned next_pg_num;
798
799         as.argc = argc;
800         as.argv = argv;
801
802         m = alloc_multipath(ti);
803         if (!m) {
804                 ti->error = "can't allocate multipath";
805                 return -EINVAL;
806         }
807
808         r = parse_features(&as, m);
809         if (r)
810                 goto bad;
811
812         r = parse_hw_handler(&as, m);
813         if (r)
814                 goto bad;
815
816         r = read_param(_params, shift(&as), &m->nr_priority_groups, &ti->error);
817         if (r)
818                 goto bad;
819
820         r = read_param(_params + 1, shift(&as), &next_pg_num, &ti->error);
821         if (r)
822                 goto bad;
823
824         /* parse the priority groups */
825         while (as.argc) {
826                 struct priority_group *pg;
827
828                 pg = parse_priority_group(&as, m);
829                 if (IS_ERR(pg)) {
830                         r = PTR_ERR(pg);
831                         goto bad;
832                 }
833
834                 m->nr_valid_paths += pg->nr_pgpaths;
835                 list_add_tail(&pg->list, &m->priority_groups);
836                 pg_count++;
837                 pg->pg_num = pg_count;
838                 if (!--next_pg_num)
839                         m->next_pg = pg;
840         }
841
842         if (pg_count != m->nr_priority_groups) {
843                 ti->error = "priority group count mismatch";
844                 r = -EINVAL;
845                 goto bad;
846         }
847
848         return 0;
849
850  bad:
851         free_multipath(m);
852         return r;
853 }
854
855 static void multipath_dtr(struct dm_target *ti)
856 {
857         struct multipath *m = (struct multipath *) ti->private;
858
859         flush_workqueue(kmpath_handlerd);
860         flush_workqueue(kmultipathd);
861         free_multipath(m);
862 }
863
864 /*
865  * Map bios, recording original fields for later in case we have to resubmit
866  */
867 static int multipath_map(struct dm_target *ti, struct bio *bio,
868                          union map_info *map_context)
869 {
870         int r;
871         struct dm_mpath_io *mpio;
872         struct multipath *m = (struct multipath *) ti->private;
873
874         mpio = mempool_alloc(m->mpio_pool, GFP_NOIO);
875         dm_bio_record(&mpio->details, bio);
876
877         map_context->ptr = mpio;
878         bio->bi_rw |= (1 << BIO_RW_FAILFAST_TRANSPORT);
879         r = map_io(m, bio, mpio, 0);
880         if (r < 0 || r == DM_MAPIO_REQUEUE)
881                 mempool_free(mpio, m->mpio_pool);
882
883         return r;
884 }
885
886 /*
887  * Take a path out of use.
888  */
889 static int fail_path(struct pgpath *pgpath)
890 {
891         unsigned long flags;
892         struct multipath *m = pgpath->pg->m;
893
894         spin_lock_irqsave(&m->lock, flags);
895
896         if (!pgpath->is_active)
897                 goto out;
898
899         DMWARN("Failing path %s.", pgpath->path.dev->name);
900
901         pgpath->pg->ps.type->fail_path(&pgpath->pg->ps, &pgpath->path);
902         pgpath->is_active = 0;
903         pgpath->fail_count++;
904
905         m->nr_valid_paths--;
906
907         if (pgpath == m->current_pgpath)
908                 m->current_pgpath = NULL;
909
910         dm_path_uevent(DM_UEVENT_PATH_FAILED, m->ti,
911                       pgpath->path.dev->name, m->nr_valid_paths);
912
913         schedule_work(&m->trigger_event);
914         queue_work(kmultipathd, &pgpath->deactivate_path);
915
916 out:
917         spin_unlock_irqrestore(&m->lock, flags);
918
919         return 0;
920 }
921
922 /*
923  * Reinstate a previously-failed path
924  */
925 static int reinstate_path(struct pgpath *pgpath)
926 {
927         int r = 0;
928         unsigned long flags;
929         struct multipath *m = pgpath->pg->m;
930
931         spin_lock_irqsave(&m->lock, flags);
932
933         if (pgpath->is_active)
934                 goto out;
935
936         if (!pgpath->pg->ps.type->reinstate_path) {
937                 DMWARN("Reinstate path not supported by path selector %s",
938                        pgpath->pg->ps.type->name);
939                 r = -EINVAL;
940                 goto out;
941         }
942
943         r = pgpath->pg->ps.type->reinstate_path(&pgpath->pg->ps, &pgpath->path);
944         if (r)
945                 goto out;
946
947         pgpath->is_active = 1;
948
949         m->current_pgpath = NULL;
950         if (!m->nr_valid_paths++ && m->queue_size)
951                 queue_work(kmultipathd, &m->process_queued_ios);
952
953         dm_path_uevent(DM_UEVENT_PATH_REINSTATED, m->ti,
954                       pgpath->path.dev->name, m->nr_valid_paths);
955
956         schedule_work(&m->trigger_event);
957
958 out:
959         spin_unlock_irqrestore(&m->lock, flags);
960
961         return r;
962 }
963
964 /*
965  * Fail or reinstate all paths that match the provided struct dm_dev.
966  */
967 static int action_dev(struct multipath *m, struct dm_dev *dev,
968                       action_fn action)
969 {
970         int r = 0;
971         struct pgpath *pgpath;
972         struct priority_group *pg;
973
974         list_for_each_entry(pg, &m->priority_groups, list) {
975                 list_for_each_entry(pgpath, &pg->pgpaths, list) {
976                         if (pgpath->path.dev == dev)
977                                 r = action(pgpath);
978                 }
979         }
980
981         return r;
982 }
983
984 /*
985  * Temporarily try to avoid having to use the specified PG
986  */
987 static void bypass_pg(struct multipath *m, struct priority_group *pg,
988                       int bypassed)
989 {
990         unsigned long flags;
991
992         spin_lock_irqsave(&m->lock, flags);
993
994         pg->bypassed = bypassed;
995         m->current_pgpath = NULL;
996         m->current_pg = NULL;
997
998         spin_unlock_irqrestore(&m->lock, flags);
999
1000         schedule_work(&m->trigger_event);
1001 }
1002
1003 /*
1004  * Switch to using the specified PG from the next I/O that gets mapped
1005  */
1006 static int switch_pg_num(struct multipath *m, const char *pgstr)
1007 {
1008         struct priority_group *pg;
1009         unsigned pgnum;
1010         unsigned long flags;
1011
1012         if (!pgstr || (sscanf(pgstr, "%u", &pgnum) != 1) || !pgnum ||
1013             (pgnum > m->nr_priority_groups)) {
1014                 DMWARN("invalid PG number supplied to switch_pg_num");
1015                 return -EINVAL;
1016         }
1017
1018         spin_lock_irqsave(&m->lock, flags);
1019         list_for_each_entry(pg, &m->priority_groups, list) {
1020                 pg->bypassed = 0;
1021                 if (--pgnum)
1022                         continue;
1023
1024                 m->current_pgpath = NULL;
1025                 m->current_pg = NULL;
1026                 m->next_pg = pg;
1027         }
1028         spin_unlock_irqrestore(&m->lock, flags);
1029
1030         schedule_work(&m->trigger_event);
1031         return 0;
1032 }
1033
1034 /*
1035  * Set/clear bypassed status of a PG.
1036  * PGs are numbered upwards from 1 in the order they were declared.
1037  */
1038 static int bypass_pg_num(struct multipath *m, const char *pgstr, int bypassed)
1039 {
1040         struct priority_group *pg;
1041         unsigned pgnum;
1042
1043         if (!pgstr || (sscanf(pgstr, "%u", &pgnum) != 1) || !pgnum ||
1044             (pgnum > m->nr_priority_groups)) {
1045                 DMWARN("invalid PG number supplied to bypass_pg");
1046                 return -EINVAL;
1047         }
1048
1049         list_for_each_entry(pg, &m->priority_groups, list) {
1050                 if (!--pgnum)
1051                         break;
1052         }
1053
1054         bypass_pg(m, pg, bypassed);
1055         return 0;
1056 }
1057
1058 /*
1059  * Should we retry pg_init immediately?
1060  */
1061 static int pg_init_limit_reached(struct multipath *m, struct pgpath *pgpath)
1062 {
1063         unsigned long flags;
1064         int limit_reached = 0;
1065
1066         spin_lock_irqsave(&m->lock, flags);
1067
1068         if (m->pg_init_count <= m->pg_init_retries)
1069                 m->pg_init_required = 1;
1070         else
1071                 limit_reached = 1;
1072
1073         spin_unlock_irqrestore(&m->lock, flags);
1074
1075         return limit_reached;
1076 }
1077
1078 static void pg_init_done(struct dm_path *path, int errors)
1079 {
1080         struct pgpath *pgpath = path_to_pgpath(path);
1081         struct priority_group *pg = pgpath->pg;
1082         struct multipath *m = pg->m;
1083         unsigned long flags;
1084
1085         /* device or driver problems */
1086         switch (errors) {
1087         case SCSI_DH_OK:
1088                 break;
1089         case SCSI_DH_NOSYS:
1090                 if (!m->hw_handler_name) {
1091                         errors = 0;
1092                         break;
1093                 }
1094                 DMERR("Cannot failover device because scsi_dh_%s was not "
1095                       "loaded.", m->hw_handler_name);
1096                 /*
1097                  * Fail path for now, so we do not ping pong
1098                  */
1099                 fail_path(pgpath);
1100                 break;
1101         case SCSI_DH_DEV_TEMP_BUSY:
1102                 /*
1103                  * Probably doing something like FW upgrade on the
1104                  * controller so try the other pg.
1105                  */
1106                 bypass_pg(m, pg, 1);
1107                 break;
1108         /* TODO: For SCSI_DH_RETRY we should wait a couple seconds */
1109         case SCSI_DH_RETRY:
1110         case SCSI_DH_IMM_RETRY:
1111         case SCSI_DH_RES_TEMP_UNAVAIL:
1112                 if (pg_init_limit_reached(m, pgpath))
1113                         fail_path(pgpath);
1114                 errors = 0;
1115                 break;
1116         default:
1117                 /*
1118                  * We probably do not want to fail the path for a device
1119                  * error, but this is what the old dm did. In future
1120                  * patches we can do more advanced handling.
1121                  */
1122                 fail_path(pgpath);
1123         }
1124
1125         spin_lock_irqsave(&m->lock, flags);
1126         if (errors) {
1127                 DMERR("Could not failover device. Error %d.", errors);
1128                 m->current_pgpath = NULL;
1129                 m->current_pg = NULL;
1130         } else if (!m->pg_init_required) {
1131                 m->queue_io = 0;
1132                 pg->bypassed = 0;
1133         }
1134
1135         m->pg_init_in_progress = 0;
1136         queue_work(kmultipathd, &m->process_queued_ios);
1137         spin_unlock_irqrestore(&m->lock, flags);
1138 }
1139
1140 static void activate_path(struct work_struct *work)
1141 {
1142         int ret;
1143         struct multipath *m =
1144                 container_of(work, struct multipath, activate_path);
1145         struct dm_path *path;
1146         unsigned long flags;
1147
1148         spin_lock_irqsave(&m->lock, flags);
1149         path = &m->pgpath_to_activate->path;
1150         m->pgpath_to_activate = NULL;
1151         spin_unlock_irqrestore(&m->lock, flags);
1152         if (!path)
1153                 return;
1154         ret = scsi_dh_activate(bdev_get_queue(path->dev->bdev));
1155         pg_init_done(path, ret);
1156 }
1157
1158 /*
1159  * end_io handling
1160  */
1161 static int do_end_io(struct multipath *m, struct bio *bio,
1162                      int error, struct dm_mpath_io *mpio)
1163 {
1164         unsigned long flags;
1165
1166         if (!error)
1167                 return 0;       /* I/O complete */
1168
1169         if ((error == -EWOULDBLOCK) && bio_rw_ahead(bio))
1170                 return error;
1171
1172         if (error == -EOPNOTSUPP)
1173                 return error;
1174
1175         spin_lock_irqsave(&m->lock, flags);
1176         if (!m->nr_valid_paths) {
1177                 if (__must_push_back(m)) {
1178                         spin_unlock_irqrestore(&m->lock, flags);
1179                         return DM_ENDIO_REQUEUE;
1180                 } else if (!m->queue_if_no_path) {
1181                         spin_unlock_irqrestore(&m->lock, flags);
1182                         return -EIO;
1183                 } else {
1184                         spin_unlock_irqrestore(&m->lock, flags);
1185                         goto requeue;
1186                 }
1187         }
1188         spin_unlock_irqrestore(&m->lock, flags);
1189
1190         if (mpio->pgpath)
1191                 fail_path(mpio->pgpath);
1192
1193       requeue:
1194         dm_bio_restore(&mpio->details, bio);
1195
1196         /* queue for the daemon to resubmit or fail */
1197         spin_lock_irqsave(&m->lock, flags);
1198         bio_list_add(&m->queued_ios, bio);
1199         m->queue_size++;
1200         if (!m->queue_io)
1201                 queue_work(kmultipathd, &m->process_queued_ios);
1202         spin_unlock_irqrestore(&m->lock, flags);
1203
1204         return DM_ENDIO_INCOMPLETE;     /* io not complete */
1205 }
1206
1207 static int multipath_end_io(struct dm_target *ti, struct bio *bio,
1208                             int error, union map_info *map_context)
1209 {
1210         struct multipath *m = ti->private;
1211         struct dm_mpath_io *mpio = map_context->ptr;
1212         struct pgpath *pgpath = mpio->pgpath;
1213         struct path_selector *ps;
1214         int r;
1215
1216         r  = do_end_io(m, bio, error, mpio);
1217         if (pgpath) {
1218                 ps = &pgpath->pg->ps;
1219                 if (ps->type->end_io)
1220                         ps->type->end_io(ps, &pgpath->path);
1221         }
1222         if (r != DM_ENDIO_INCOMPLETE)
1223                 mempool_free(mpio, m->mpio_pool);
1224
1225         return r;
1226 }
1227
1228 /*
1229  * Suspend can't complete until all the I/O is processed so if
1230  * the last path fails we must error any remaining I/O.
1231  * Note that if the freeze_bdev fails while suspending, the
1232  * queue_if_no_path state is lost - userspace should reset it.
1233  */
1234 static void multipath_presuspend(struct dm_target *ti)
1235 {
1236         struct multipath *m = (struct multipath *) ti->private;
1237
1238         queue_if_no_path(m, 0, 1);
1239 }
1240
1241 /*
1242  * Restore the queue_if_no_path setting.
1243  */
1244 static void multipath_resume(struct dm_target *ti)
1245 {
1246         struct multipath *m = (struct multipath *) ti->private;
1247         unsigned long flags;
1248
1249         spin_lock_irqsave(&m->lock, flags);
1250         m->queue_if_no_path = m->saved_queue_if_no_path;
1251         spin_unlock_irqrestore(&m->lock, flags);
1252 }
1253
1254 /*
1255  * Info output has the following format:
1256  * num_multipath_feature_args [multipath_feature_args]*
1257  * num_handler_status_args [handler_status_args]*
1258  * num_groups init_group_number
1259  *            [A|D|E num_ps_status_args [ps_status_args]*
1260  *             num_paths num_selector_args
1261  *             [path_dev A|F fail_count [selector_args]* ]+ ]+
1262  *
1263  * Table output has the following format (identical to the constructor string):
1264  * num_feature_args [features_args]*
1265  * num_handler_args hw_handler [hw_handler_args]*
1266  * num_groups init_group_number
1267  *     [priority selector-name num_ps_args [ps_args]*
1268  *      num_paths num_selector_args [path_dev [selector_args]* ]+ ]+
1269  */
1270 static int multipath_status(struct dm_target *ti, status_type_t type,
1271                             char *result, unsigned int maxlen)
1272 {
1273         int sz = 0;
1274         unsigned long flags;
1275         struct multipath *m = (struct multipath *) ti->private;
1276         struct priority_group *pg;
1277         struct pgpath *p;
1278         unsigned pg_num;
1279         char state;
1280
1281         spin_lock_irqsave(&m->lock, flags);
1282
1283         /* Features */
1284         if (type == STATUSTYPE_INFO)
1285                 DMEMIT("2 %u %u ", m->queue_size, m->pg_init_count);
1286         else {
1287                 DMEMIT("%u ", m->queue_if_no_path +
1288                               (m->pg_init_retries > 0) * 2);
1289                 if (m->queue_if_no_path)
1290                         DMEMIT("queue_if_no_path ");
1291                 if (m->pg_init_retries)
1292                         DMEMIT("pg_init_retries %u ", m->pg_init_retries);
1293         }
1294
1295         if (!m->hw_handler_name || type == STATUSTYPE_INFO)
1296                 DMEMIT("0 ");
1297         else
1298                 DMEMIT("1 %s ", m->hw_handler_name);
1299
1300         DMEMIT("%u ", m->nr_priority_groups);
1301
1302         if (m->next_pg)
1303                 pg_num = m->next_pg->pg_num;
1304         else if (m->current_pg)
1305                 pg_num = m->current_pg->pg_num;
1306         else
1307                         pg_num = 1;
1308
1309         DMEMIT("%u ", pg_num);
1310
1311         switch (type) {
1312         case STATUSTYPE_INFO:
1313                 list_for_each_entry(pg, &m->priority_groups, list) {
1314                         if (pg->bypassed)
1315                                 state = 'D';    /* Disabled */
1316                         else if (pg == m->current_pg)
1317                                 state = 'A';    /* Currently Active */
1318                         else
1319                                 state = 'E';    /* Enabled */
1320
1321                         DMEMIT("%c ", state);
1322
1323                         if (pg->ps.type->status)
1324                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1325                                                           result + sz,
1326                                                           maxlen - sz);
1327                         else
1328                                 DMEMIT("0 ");
1329
1330                         DMEMIT("%u %u ", pg->nr_pgpaths,
1331                                pg->ps.type->info_args);
1332
1333                         list_for_each_entry(p, &pg->pgpaths, list) {
1334                                 DMEMIT("%s %s %u ", p->path.dev->name,
1335                                        p->is_active ? "A" : "F",
1336                                        p->fail_count);
1337                                 if (pg->ps.type->status)
1338                                         sz += pg->ps.type->status(&pg->ps,
1339                                               &p->path, type, result + sz,
1340                                               maxlen - sz);
1341                         }
1342                 }
1343                 break;
1344
1345         case STATUSTYPE_TABLE:
1346                 list_for_each_entry(pg, &m->priority_groups, list) {
1347                         DMEMIT("%s ", pg->ps.type->name);
1348
1349                         if (pg->ps.type->status)
1350                                 sz += pg->ps.type->status(&pg->ps, NULL, type,
1351                                                           result + sz,
1352                                                           maxlen - sz);
1353                         else
1354                                 DMEMIT("0 ");
1355
1356                         DMEMIT("%u %u ", pg->nr_pgpaths,
1357                                pg->ps.type->table_args);
1358
1359                         list_for_each_entry(p, &pg->pgpaths, list) {
1360                                 DMEMIT("%s ", p->path.dev->name);
1361                                 if (pg->ps.type->status)
1362                                         sz += pg->ps.type->status(&pg->ps,
1363                                               &p->path, type, result + sz,
1364                                               maxlen - sz);
1365                         }
1366                 }
1367                 break;
1368         }
1369
1370         spin_unlock_irqrestore(&m->lock, flags);
1371
1372         return 0;
1373 }
1374
1375 static int multipath_message(struct dm_target *ti, unsigned argc, char **argv)
1376 {
1377         int r;
1378         struct dm_dev *dev;
1379         struct multipath *m = (struct multipath *) ti->private;
1380         action_fn action;
1381
1382         if (argc == 1) {
1383                 if (!strnicmp(argv[0], MESG_STR("queue_if_no_path")))
1384                         return queue_if_no_path(m, 1, 0);
1385                 else if (!strnicmp(argv[0], MESG_STR("fail_if_no_path")))
1386                         return queue_if_no_path(m, 0, 0);
1387         }
1388
1389         if (argc != 2)
1390                 goto error;
1391
1392         if (!strnicmp(argv[0], MESG_STR("disable_group")))
1393                 return bypass_pg_num(m, argv[1], 1);
1394         else if (!strnicmp(argv[0], MESG_STR("enable_group")))
1395                 return bypass_pg_num(m, argv[1], 0);
1396         else if (!strnicmp(argv[0], MESG_STR("switch_group")))
1397                 return switch_pg_num(m, argv[1]);
1398         else if (!strnicmp(argv[0], MESG_STR("reinstate_path")))
1399                 action = reinstate_path;
1400         else if (!strnicmp(argv[0], MESG_STR("fail_path")))
1401                 action = fail_path;
1402         else
1403                 goto error;
1404
1405         r = dm_get_device(ti, argv[1], ti->begin, ti->len,
1406                           dm_table_get_mode(ti->table), &dev);
1407         if (r) {
1408                 DMWARN("message: error getting device %s",
1409                        argv[1]);
1410                 return -EINVAL;
1411         }
1412
1413         r = action_dev(m, dev, action);
1414
1415         dm_put_device(ti, dev);
1416
1417         return r;
1418
1419 error:
1420         DMWARN("Unrecognised multipath message received.");
1421         return -EINVAL;
1422 }
1423
1424 static int multipath_ioctl(struct dm_target *ti, unsigned int cmd,
1425                            unsigned long arg)
1426 {
1427         struct multipath *m = (struct multipath *) ti->private;
1428         struct block_device *bdev = NULL;
1429         fmode_t mode = 0;
1430         unsigned long flags;
1431         int r = 0;
1432
1433         spin_lock_irqsave(&m->lock, flags);
1434
1435         if (!m->current_pgpath)
1436                 __choose_pgpath(m);
1437
1438         if (m->current_pgpath) {
1439                 bdev = m->current_pgpath->path.dev->bdev;
1440                 mode = m->current_pgpath->path.dev->mode;
1441         }
1442
1443         if (m->queue_io)
1444                 r = -EAGAIN;
1445         else if (!bdev)
1446                 r = -EIO;
1447
1448         spin_unlock_irqrestore(&m->lock, flags);
1449
1450         return r ? : __blkdev_driver_ioctl(bdev, mode, cmd, arg);
1451 }
1452
1453 /*-----------------------------------------------------------------
1454  * Module setup
1455  *---------------------------------------------------------------*/
1456 static struct target_type multipath_target = {
1457         .name = "multipath",
1458         .version = {1, 0, 5},
1459         .module = THIS_MODULE,
1460         .ctr = multipath_ctr,
1461         .dtr = multipath_dtr,
1462         .map = multipath_map,
1463         .end_io = multipath_end_io,
1464         .presuspend = multipath_presuspend,
1465         .resume = multipath_resume,
1466         .status = multipath_status,
1467         .message = multipath_message,
1468         .ioctl  = multipath_ioctl,
1469 };
1470
1471 static int __init dm_multipath_init(void)
1472 {
1473         int r;
1474
1475         /* allocate a slab for the dm_ios */
1476         _mpio_cache = KMEM_CACHE(dm_mpath_io, 0);
1477         if (!_mpio_cache)
1478                 return -ENOMEM;
1479
1480         r = dm_register_target(&multipath_target);
1481         if (r < 0) {
1482                 DMERR("register failed %d", r);
1483                 kmem_cache_destroy(_mpio_cache);
1484                 return -EINVAL;
1485         }
1486
1487         kmultipathd = create_workqueue("kmpathd");
1488         if (!kmultipathd) {
1489                 DMERR("failed to create workqueue kmpathd");
1490                 dm_unregister_target(&multipath_target);
1491                 kmem_cache_destroy(_mpio_cache);
1492                 return -ENOMEM;
1493         }
1494
1495         /*
1496          * A separate workqueue is used to handle the device handlers
1497          * to avoid overloading existing workqueue. Overloading the
1498          * old workqueue would also create a bottleneck in the
1499          * path of the storage hardware device activation.
1500          */
1501         kmpath_handlerd = create_singlethread_workqueue("kmpath_handlerd");
1502         if (!kmpath_handlerd) {
1503                 DMERR("failed to create workqueue kmpath_handlerd");
1504                 destroy_workqueue(kmultipathd);
1505                 dm_unregister_target(&multipath_target);
1506                 kmem_cache_destroy(_mpio_cache);
1507                 return -ENOMEM;
1508         }
1509
1510         DMINFO("version %u.%u.%u loaded",
1511                multipath_target.version[0], multipath_target.version[1],
1512                multipath_target.version[2]);
1513
1514         return r;
1515 }
1516
1517 static void __exit dm_multipath_exit(void)
1518 {
1519         destroy_workqueue(kmpath_handlerd);
1520         destroy_workqueue(kmultipathd);
1521
1522         dm_unregister_target(&multipath_target);
1523         kmem_cache_destroy(_mpio_cache);
1524 }
1525
1526 module_init(dm_multipath_init);
1527 module_exit(dm_multipath_exit);
1528
1529 MODULE_DESCRIPTION(DM_NAME " multipath target");
1530 MODULE_AUTHOR("Sistina Software <dm-devel@redhat.com>");
1531 MODULE_LICENSE("GPL");