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