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