xref: /linux/drivers/md/dm-mpath.c (revision 51d81e14fe6788dc6463064c7517480f2acd2724)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2003 Sistina Software Limited.
4  * Copyright (C) 2004-2005 Red Hat, Inc. All rights reserved.
5  *
6  * This file is released under the GPL.
7  */
8 
9 #include <linux/device-mapper.h>
10 
11 #include "dm-rq.h"
12 #include "dm-bio-record.h"
13 #include "dm-path-selector.h"
14 #include "dm-uevent.h"
15 
16 #include <linux/blkdev.h>
17 #include <linux/ctype.h>
18 #include <linux/init.h>
19 #include <linux/mempool.h>
20 #include <linux/module.h>
21 #include <linux/pagemap.h>
22 #include <linux/slab.h>
23 #include <linux/time.h>
24 #include <linux/timer.h>
25 #include <linux/workqueue.h>
26 #include <linux/delay.h>
27 #include <scsi/scsi_dh.h>
28 #include <linux/atomic.h>
29 #include <linux/blk-mq.h>
30 
31 static struct workqueue_struct *dm_mpath_wq;
32 
33 #define DM_MSG_PREFIX "multipath"
34 #define DM_PG_INIT_DELAY_MSECS 2000
35 #define DM_PG_INIT_DELAY_DEFAULT ((unsigned int) -1)
36 #define QUEUE_IF_NO_PATH_TIMEOUT_DEFAULT 0
37 
38 static unsigned long queue_if_no_path_timeout_secs = QUEUE_IF_NO_PATH_TIMEOUT_DEFAULT;
39 
40 /* Path properties */
41 struct pgpath {
42 	struct list_head list;
43 
44 	struct priority_group *pg;	/* Owning PG */
45 	unsigned int fail_count;		/* Cumulative failure count */
46 
47 	struct dm_path path;
48 	struct delayed_work activate_path;
49 
50 	bool is_active:1;		/* Path status */
51 };
52 
53 #define path_to_pgpath(__pgp) container_of((__pgp), struct pgpath, path)
54 
55 /*
56  * Paths are grouped into Priority Groups and numbered from 1 upwards.
57  * Each has a path selector which controls which path gets used.
58  */
59 struct priority_group {
60 	struct list_head list;
61 
62 	struct multipath *m;		/* Owning multipath instance */
63 	struct path_selector ps;
64 
65 	unsigned int pg_num;		/* Reference number */
66 	unsigned int nr_pgpaths;		/* Number of paths in PG */
67 	struct list_head pgpaths;
68 
69 	bool bypassed:1;		/* Temporarily bypass this PG? */
70 };
71 
72 /* Multipath context */
73 struct multipath {
74 	unsigned long flags;		/* Multipath state flags */
75 
76 	spinlock_t lock;
77 	enum dm_queue_mode queue_mode;
78 
79 	struct pgpath *current_pgpath;
80 	struct priority_group *current_pg;
81 	struct priority_group *next_pg;	/* Switch to this PG if set */
82 	struct priority_group *last_probed_pg;
83 
84 	atomic_t nr_valid_paths;	/* Total number of usable paths */
85 	unsigned int nr_priority_groups;
86 	struct list_head priority_groups;
87 
88 	const char *hw_handler_name;
89 	char *hw_handler_params;
90 	wait_queue_head_t pg_init_wait;	/* Wait for pg_init completion */
91 	wait_queue_head_t probe_wait;   /* Wait for probing paths */
92 	unsigned int pg_init_retries;	/* Number of times to retry pg_init */
93 	unsigned int pg_init_delay_msecs;	/* Number of msecs before pg_init retry */
94 	atomic_t pg_init_in_progress;	/* Only one pg_init allowed at once */
95 	atomic_t pg_init_count;		/* Number of times pg_init called */
96 
97 	struct mutex work_mutex;
98 	struct work_struct trigger_event;
99 	struct dm_target *ti;
100 
101 	struct work_struct process_queued_bios;
102 	struct bio_list queued_bios;
103 
104 	struct timer_list nopath_timer;	/* Timeout for queue_if_no_path */
105 };
106 
107 /*
108  * Context information attached to each io we process.
109  */
110 struct dm_mpath_io {
111 	struct pgpath *pgpath;
112 	size_t nr_bytes;
113 	u64 start_time_ns;
114 };
115 
116 typedef int (*action_fn) (struct pgpath *pgpath);
117 
118 static struct workqueue_struct *kmultipathd, *kmpath_handlerd;
119 static void trigger_event(struct work_struct *work);
120 static void activate_or_offline_path(struct pgpath *pgpath);
121 static void activate_path_work(struct work_struct *work);
122 static void process_queued_bios(struct work_struct *work);
123 static void queue_if_no_path_timeout_work(struct timer_list *t);
124 
125 /*
126  *-----------------------------------------------
127  * Multipath state flags.
128  *-----------------------------------------------
129  */
130 #define MPATHF_QUEUE_IO 0			/* Must we queue all I/O? */
131 #define MPATHF_QUEUE_IF_NO_PATH 1		/* Queue I/O if last path fails? */
132 #define MPATHF_SAVED_QUEUE_IF_NO_PATH 2		/* Saved state during suspension */
133 /* MPATHF_RETAIN_ATTACHED_HW_HANDLER no longer has any effect */
134 #define MPATHF_PG_INIT_DISABLED 4		/* pg_init is not currently allowed */
135 #define MPATHF_PG_INIT_REQUIRED 5		/* pg_init needs calling? */
136 #define MPATHF_PG_INIT_DELAY_RETRY 6		/* Delay pg_init retry? */
137 #define MPATHF_DELAY_PG_SWITCH 7		/* Delay switching pg if it still has paths */
138 #define MPATHF_NEED_PG_SWITCH 8			/* Need to switch pgs after the delay has ended */
139 
140 static bool mpath_double_check_test_bit(int MPATHF_bit, struct multipath *m)
141 {
142 	bool r = test_bit(MPATHF_bit, &m->flags);
143 
144 	if (r) {
145 		unsigned long flags;
146 
147 		spin_lock_irqsave(&m->lock, flags);
148 		r = test_bit(MPATHF_bit, &m->flags);
149 		spin_unlock_irqrestore(&m->lock, flags);
150 	}
151 
152 	return r;
153 }
154 
155 /*
156  *-----------------------------------------------
157  * Allocation routines
158  *-----------------------------------------------
159  */
160 static struct pgpath *alloc_pgpath(void)
161 {
162 	struct pgpath *pgpath = kzalloc_obj(*pgpath);
163 
164 	if (!pgpath)
165 		return NULL;
166 
167 	pgpath->is_active = true;
168 
169 	return pgpath;
170 }
171 
172 static void free_pgpath(struct pgpath *pgpath)
173 {
174 	kfree(pgpath);
175 }
176 
177 static struct priority_group *alloc_priority_group(void)
178 {
179 	struct priority_group *pg;
180 
181 	pg = kzalloc_obj(*pg);
182 
183 	if (pg)
184 		INIT_LIST_HEAD(&pg->pgpaths);
185 
186 	return pg;
187 }
188 
189 static void free_pgpaths(struct list_head *pgpaths, struct dm_target *ti)
190 {
191 	struct pgpath *pgpath, *tmp;
192 
193 	list_for_each_entry_safe(pgpath, tmp, pgpaths, list) {
194 		list_del(&pgpath->list);
195 		dm_put_device(ti, pgpath->path.dev);
196 		free_pgpath(pgpath);
197 	}
198 }
199 
200 static void free_priority_group(struct priority_group *pg,
201 				struct dm_target *ti)
202 {
203 	struct path_selector *ps = &pg->ps;
204 
205 	if (ps->type) {
206 		ps->type->destroy(ps);
207 		dm_put_path_selector(ps->type);
208 	}
209 
210 	free_pgpaths(&pg->pgpaths, ti);
211 	kfree(pg);
212 }
213 
214 static struct multipath *alloc_multipath(struct dm_target *ti)
215 {
216 	struct multipath *m;
217 
218 	m = kzalloc_obj(*m);
219 	if (m) {
220 		INIT_LIST_HEAD(&m->priority_groups);
221 		spin_lock_init(&m->lock);
222 		atomic_set(&m->nr_valid_paths, 0);
223 		INIT_WORK(&m->trigger_event, trigger_event);
224 		mutex_init(&m->work_mutex);
225 
226 		m->queue_mode = DM_TYPE_NONE;
227 		m->pg_init_delay_msecs = DM_PG_INIT_DELAY_DEFAULT;
228 
229 		m->ti = ti;
230 		ti->private = m;
231 
232 		timer_setup(&m->nopath_timer, queue_if_no_path_timeout_work, 0);
233 	}
234 
235 	return m;
236 }
237 
238 static int alloc_multipath_stage2(struct dm_target *ti, struct multipath *m)
239 {
240 	if (m->queue_mode == DM_TYPE_NONE)
241 		m->queue_mode = DM_TYPE_REQUEST_BASED;
242 	else if (m->queue_mode == DM_TYPE_BIO_BASED)
243 		INIT_WORK(&m->process_queued_bios, process_queued_bios);
244 
245 	dm_table_set_type(ti->table, m->queue_mode);
246 
247 	/*
248 	 * Init fields that are only used when a scsi_dh is attached
249 	 * - must do this unconditionally (really doesn't hurt non-SCSI uses)
250 	 */
251 	set_bit(MPATHF_QUEUE_IO, &m->flags);
252 	atomic_set(&m->pg_init_in_progress, 0);
253 	atomic_set(&m->pg_init_count, 0);
254 	init_waitqueue_head(&m->pg_init_wait);
255 	init_waitqueue_head(&m->probe_wait);
256 
257 	return 0;
258 }
259 
260 static void free_multipath(struct multipath *m)
261 {
262 	struct priority_group *pg, *tmp;
263 
264 	list_for_each_entry_safe(pg, tmp, &m->priority_groups, list) {
265 		list_del(&pg->list);
266 		free_priority_group(pg, m->ti);
267 	}
268 
269 	kfree(m->hw_handler_name);
270 	kfree(m->hw_handler_params);
271 	mutex_destroy(&m->work_mutex);
272 	kfree(m);
273 }
274 
275 static struct dm_mpath_io *get_mpio(union map_info *info)
276 {
277 	return info->ptr;
278 }
279 
280 static size_t multipath_per_bio_data_size(void)
281 {
282 	return sizeof(struct dm_mpath_io) + sizeof(struct dm_bio_details);
283 }
284 
285 static struct dm_mpath_io *get_mpio_from_bio(struct bio *bio)
286 {
287 	return dm_per_bio_data(bio, multipath_per_bio_data_size());
288 }
289 
290 static struct dm_bio_details *get_bio_details_from_mpio(struct dm_mpath_io *mpio)
291 {
292 	/* dm_bio_details is immediately after the dm_mpath_io in bio's per-bio-data */
293 	void *bio_details = mpio + 1;
294 	return bio_details;
295 }
296 
297 static void multipath_init_per_bio_data(struct bio *bio, struct dm_mpath_io **mpio_p)
298 {
299 	struct dm_mpath_io *mpio = get_mpio_from_bio(bio);
300 	struct dm_bio_details *bio_details = get_bio_details_from_mpio(mpio);
301 
302 	mpio->nr_bytes = bio->bi_iter.bi_size;
303 	mpio->pgpath = NULL;
304 	mpio->start_time_ns = 0;
305 	*mpio_p = mpio;
306 
307 	dm_bio_record(bio_details, bio);
308 }
309 
310 /*
311  *-----------------------------------------------
312  * Path selection
313  *-----------------------------------------------
314  */
315 static int __pg_init_all_paths(struct multipath *m)
316 {
317 	struct pgpath *pgpath;
318 	unsigned long pg_init_delay = 0;
319 
320 	lockdep_assert_held(&m->lock);
321 
322 	if (atomic_read(&m->pg_init_in_progress) || test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
323 		return 0;
324 
325 	atomic_inc(&m->pg_init_count);
326 	clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
327 
328 	/* Check here to reset pg_init_required */
329 	if (!m->current_pg)
330 		return 0;
331 
332 	if (test_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags))
333 		pg_init_delay = msecs_to_jiffies(m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT ?
334 						 m->pg_init_delay_msecs : DM_PG_INIT_DELAY_MSECS);
335 	list_for_each_entry(pgpath, &m->current_pg->pgpaths, list) {
336 		/* Skip failed paths */
337 		if (!pgpath->is_active)
338 			continue;
339 		if (queue_delayed_work(kmpath_handlerd, &pgpath->activate_path,
340 				       pg_init_delay))
341 			atomic_inc(&m->pg_init_in_progress);
342 	}
343 	return atomic_read(&m->pg_init_in_progress);
344 }
345 
346 static int pg_init_all_paths(struct multipath *m)
347 {
348 	int ret;
349 	unsigned long flags;
350 
351 	spin_lock_irqsave(&m->lock, flags);
352 	ret = __pg_init_all_paths(m);
353 	spin_unlock_irqrestore(&m->lock, flags);
354 
355 	return ret;
356 }
357 
358 static void __switch_pg(struct multipath *m, struct priority_group *pg)
359 {
360 	lockdep_assert_held(&m->lock);
361 
362 	m->current_pg = pg;
363 
364 	/* Must we initialise the PG first, and queue I/O till it's ready? */
365 	if (m->hw_handler_name) {
366 		set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
367 		set_bit(MPATHF_QUEUE_IO, &m->flags);
368 	} else {
369 		clear_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
370 		clear_bit(MPATHF_QUEUE_IO, &m->flags);
371 	}
372 
373 	atomic_set(&m->pg_init_count, 0);
374 }
375 
376 static struct pgpath *choose_path_in_pg(struct multipath *m,
377 					struct priority_group *pg,
378 					size_t nr_bytes)
379 {
380 	unsigned long flags;
381 	struct dm_path *path;
382 	struct pgpath *pgpath;
383 
384 	path = pg->ps.type->select_path(&pg->ps, nr_bytes);
385 	if (!path)
386 		return ERR_PTR(-ENXIO);
387 
388 	pgpath = path_to_pgpath(path);
389 
390 	if (unlikely(READ_ONCE(m->current_pg) != pg)) {
391 		/* Only update current_pgpath if pg changed */
392 		spin_lock_irqsave(&m->lock, flags);
393 		m->current_pgpath = pgpath;
394 		__switch_pg(m, pg);
395 		spin_unlock_irqrestore(&m->lock, flags);
396 	}
397 
398 	return pgpath;
399 }
400 
401 static struct pgpath *choose_pgpath(struct multipath *m, size_t nr_bytes)
402 {
403 	unsigned long flags;
404 	struct priority_group *pg;
405 	struct pgpath *pgpath;
406 	unsigned int bypassed = 1;
407 
408 	if (!atomic_read(&m->nr_valid_paths)) {
409 		spin_lock_irqsave(&m->lock, flags);
410 		clear_bit(MPATHF_QUEUE_IO, &m->flags);
411 		spin_unlock_irqrestore(&m->lock, flags);
412 		goto failed;
413 	}
414 
415 	/* Don't change PG until it has no remaining paths */
416 	pg = READ_ONCE(m->current_pg);
417 	if (pg) {
418 		pgpath = choose_path_in_pg(m, pg, nr_bytes);
419 		if (!IS_ERR_OR_NULL(pgpath))
420 			return pgpath;
421 	}
422 
423 	/* Were we instructed to switch PG? */
424 	if (READ_ONCE(m->next_pg)) {
425 		spin_lock_irqsave(&m->lock, flags);
426 		pg = m->next_pg;
427 		if (!pg) {
428 			spin_unlock_irqrestore(&m->lock, flags);
429 			goto check_all_pgs;
430 		}
431 		m->next_pg = NULL;
432 		spin_unlock_irqrestore(&m->lock, flags);
433 		pgpath = choose_path_in_pg(m, pg, nr_bytes);
434 		if (!IS_ERR_OR_NULL(pgpath))
435 			return pgpath;
436 	}
437 check_all_pgs:
438 	/*
439 	 * Loop through priority groups until we find a valid path.
440 	 * First time we skip PGs marked 'bypassed'.
441 	 * Second time we only try the ones we skipped, but set
442 	 * pg_init_delay_retry so we do not hammer controllers.
443 	 */
444 	do {
445 		list_for_each_entry(pg, &m->priority_groups, list) {
446 			if (pg->bypassed == !!bypassed)
447 				continue;
448 			pgpath = choose_path_in_pg(m, pg, nr_bytes);
449 			if (!IS_ERR_OR_NULL(pgpath)) {
450 				if (!bypassed) {
451 					spin_lock_irqsave(&m->lock, flags);
452 					set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
453 					spin_unlock_irqrestore(&m->lock, flags);
454 				}
455 				return pgpath;
456 			}
457 		}
458 	} while (bypassed--);
459 
460 failed:
461 	spin_lock_irqsave(&m->lock, flags);
462 	m->current_pgpath = NULL;
463 	m->current_pg = NULL;
464 	spin_unlock_irqrestore(&m->lock, flags);
465 
466 	return NULL;
467 }
468 
469 /*
470  * dm_report_EIO() is a macro instead of a function to make pr_debug_ratelimited()
471  * report the function name and line number of the function from which
472  * it has been invoked.
473  */
474 #define dm_report_EIO(m)						\
475 	DMDEBUG_LIMIT("%s: returning EIO; QIFNP = %d; SQIFNP = %d; DNFS = %d", \
476 		      dm_table_device_name((m)->ti->table),		\
477 		      test_bit(MPATHF_QUEUE_IF_NO_PATH, &(m)->flags),	\
478 		      test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &(m)->flags), \
479 		      dm_noflush_suspending((m)->ti))
480 
481 /*
482  * Check whether bios must be queued in the device-mapper core rather
483  * than here in the target.
484  */
485 static bool __must_push_back(struct multipath *m)
486 {
487 	return dm_noflush_suspending(m->ti);
488 }
489 
490 static bool must_push_back_rq(struct multipath *m)
491 {
492 	unsigned long flags;
493 	bool ret;
494 
495 	spin_lock_irqsave(&m->lock, flags);
496 	ret = (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) || __must_push_back(m));
497 	spin_unlock_irqrestore(&m->lock, flags);
498 
499 	return ret;
500 }
501 
502 /*
503  * Map cloned requests (request-based multipath)
504  */
505 static int multipath_clone_and_map(struct dm_target *ti, struct request *rq,
506 				   union map_info *map_context,
507 				   struct request **__clone)
508 {
509 	struct multipath *m = ti->private;
510 	size_t nr_bytes = blk_rq_bytes(rq);
511 	struct pgpath *pgpath;
512 	struct block_device *bdev;
513 	struct dm_mpath_io *mpio = get_mpio(map_context);
514 	struct request_queue *q;
515 	struct request *clone;
516 
517 	/* Do we need to select a new pgpath? */
518 	pgpath = READ_ONCE(m->current_pgpath);
519 	if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
520 		pgpath = choose_pgpath(m, nr_bytes);
521 
522 	if (!pgpath) {
523 		if (must_push_back_rq(m))
524 			return DM_MAPIO_DELAY_REQUEUE;
525 		dm_report_EIO(m);	/* Failed */
526 		return DM_MAPIO_KILL;
527 	} else if (mpath_double_check_test_bit(MPATHF_QUEUE_IO, m) ||
528 		   mpath_double_check_test_bit(MPATHF_PG_INIT_REQUIRED, m)) {
529 		pg_init_all_paths(m);
530 		return DM_MAPIO_DELAY_REQUEUE;
531 	}
532 
533 	mpio->pgpath = pgpath;
534 	mpio->nr_bytes = nr_bytes;
535 
536 	bdev = pgpath->path.dev->bdev;
537 	q = bdev_get_queue(bdev);
538 	clone = blk_mq_alloc_request(q, rq->cmd_flags | REQ_NOMERGE,
539 			BLK_MQ_REQ_NOWAIT);
540 	if (IS_ERR(clone)) {
541 		/* EBUSY, ENODEV or EWOULDBLOCK: requeue */
542 		if (blk_queue_dying(q)) {
543 			atomic_inc(&m->pg_init_in_progress);
544 			activate_or_offline_path(pgpath);
545 			return DM_MAPIO_DELAY_REQUEUE;
546 		}
547 
548 		/*
549 		 * blk-mq's SCHED_RESTART can cover this requeue, so we
550 		 * needn't deal with it by DELAY_REQUEUE. More importantly,
551 		 * we have to return DM_MAPIO_REQUEUE so that blk-mq can
552 		 * get the queue busy feedback (via BLK_STS_RESOURCE),
553 		 * otherwise I/O merging can suffer.
554 		 */
555 		return DM_MAPIO_REQUEUE;
556 	}
557 	clone->bio = clone->biotail = NULL;
558 	clone->cmd_flags |= REQ_FAILFAST_TRANSPORT;
559 	*__clone = clone;
560 
561 	if (pgpath->pg->ps.type->start_io)
562 		pgpath->pg->ps.type->start_io(&pgpath->pg->ps,
563 					      &pgpath->path,
564 					      nr_bytes);
565 	return DM_MAPIO_REMAPPED;
566 }
567 
568 static void multipath_release_clone(struct request *clone,
569 				    union map_info *map_context)
570 {
571 	if (unlikely(map_context)) {
572 		/*
573 		 * non-NULL map_context means caller is still map
574 		 * method; must undo multipath_clone_and_map()
575 		 */
576 		struct dm_mpath_io *mpio = get_mpio(map_context);
577 		struct pgpath *pgpath = mpio->pgpath;
578 
579 		if (pgpath && pgpath->pg->ps.type->end_io)
580 			pgpath->pg->ps.type->end_io(&pgpath->pg->ps,
581 						    &pgpath->path,
582 						    mpio->nr_bytes,
583 						    clone->io_start_time_ns);
584 	}
585 
586 	blk_mq_free_request(clone);
587 }
588 
589 /*
590  * Map cloned bios (bio-based multipath)
591  */
592 
593 static void __multipath_queue_bio(struct multipath *m, struct bio *bio)
594 {
595 	/* Queue for the daemon to resubmit */
596 	bio_list_add(&m->queued_bios, bio);
597 	if (!test_bit(MPATHF_QUEUE_IO, &m->flags))
598 		queue_work(kmultipathd, &m->process_queued_bios);
599 }
600 
601 static void multipath_queue_bio(struct multipath *m, struct bio *bio)
602 {
603 	unsigned long flags;
604 
605 	spin_lock_irqsave(&m->lock, flags);
606 	__multipath_queue_bio(m, bio);
607 	spin_unlock_irqrestore(&m->lock, flags);
608 }
609 
610 static struct pgpath *__map_bio(struct multipath *m, struct bio *bio)
611 {
612 	struct pgpath *pgpath;
613 
614 	/* Do we need to select a new pgpath? */
615 	pgpath = READ_ONCE(m->current_pgpath);
616 	if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
617 		pgpath = choose_pgpath(m, bio->bi_iter.bi_size);
618 
619 	if (!pgpath) {
620 		spin_lock_irq(&m->lock);
621 		if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
622 			__multipath_queue_bio(m, bio);
623 			pgpath = ERR_PTR(-EAGAIN);
624 		}
625 		spin_unlock_irq(&m->lock);
626 
627 	} else if (mpath_double_check_test_bit(MPATHF_QUEUE_IO, m) ||
628 		   mpath_double_check_test_bit(MPATHF_PG_INIT_REQUIRED, m)) {
629 		multipath_queue_bio(m, bio);
630 		pg_init_all_paths(m);
631 		return ERR_PTR(-EAGAIN);
632 	}
633 
634 	return pgpath;
635 }
636 
637 static int __multipath_map_bio(struct multipath *m, struct bio *bio,
638 			       struct dm_mpath_io *mpio)
639 {
640 	struct pgpath *pgpath = __map_bio(m, bio);
641 
642 	if (IS_ERR(pgpath))
643 		return DM_MAPIO_SUBMITTED;
644 
645 	if (!pgpath) {
646 		if (__must_push_back(m))
647 			return DM_MAPIO_REQUEUE;
648 		dm_report_EIO(m);
649 		return DM_MAPIO_KILL;
650 	}
651 
652 	mpio->pgpath = pgpath;
653 
654 	if (dm_ps_use_hr_timer(pgpath->pg->ps.type))
655 		mpio->start_time_ns = ktime_get_ns();
656 
657 	bio->bi_status = 0;
658 	bio_set_dev(bio, pgpath->path.dev->bdev);
659 	bio->bi_opf |= REQ_FAILFAST_TRANSPORT;
660 
661 	if (pgpath->pg->ps.type->start_io)
662 		pgpath->pg->ps.type->start_io(&pgpath->pg->ps,
663 					      &pgpath->path,
664 					      mpio->nr_bytes);
665 	return DM_MAPIO_REMAPPED;
666 }
667 
668 static int multipath_map_bio(struct dm_target *ti, struct bio *bio)
669 {
670 	struct multipath *m = ti->private;
671 	struct dm_mpath_io *mpio = NULL;
672 
673 	multipath_init_per_bio_data(bio, &mpio);
674 	return __multipath_map_bio(m, bio, mpio);
675 }
676 
677 static void process_queued_io_list(struct multipath *m)
678 {
679 	if (m->queue_mode == DM_TYPE_REQUEST_BASED)
680 		dm_mq_kick_requeue_list(dm_table_get_md(m->ti->table));
681 	else if (m->queue_mode == DM_TYPE_BIO_BASED)
682 		queue_work(kmultipathd, &m->process_queued_bios);
683 }
684 
685 static void process_queued_bios(struct work_struct *work)
686 {
687 	int r;
688 	struct bio *bio;
689 	struct bio_list bios;
690 	struct blk_plug plug;
691 	struct multipath *m =
692 		container_of(work, struct multipath, process_queued_bios);
693 
694 	bio_list_init(&bios);
695 
696 	spin_lock_irq(&m->lock);
697 
698 	if (bio_list_empty(&m->queued_bios)) {
699 		spin_unlock_irq(&m->lock);
700 		return;
701 	}
702 
703 	bio_list_merge_init(&bios, &m->queued_bios);
704 
705 	spin_unlock_irq(&m->lock);
706 
707 	blk_start_plug(&plug);
708 	while ((bio = bio_list_pop(&bios))) {
709 		struct dm_mpath_io *mpio = get_mpio_from_bio(bio);
710 
711 		dm_bio_restore(get_bio_details_from_mpio(mpio), bio);
712 		r = __multipath_map_bio(m, bio, mpio);
713 		switch (r) {
714 		case DM_MAPIO_KILL:
715 			bio->bi_status = BLK_STS_IOERR;
716 			bio_endio(bio);
717 			break;
718 		case DM_MAPIO_REQUEUE:
719 			bio->bi_status = BLK_STS_DM_REQUEUE;
720 			bio_endio(bio);
721 			break;
722 		case DM_MAPIO_REMAPPED:
723 			submit_bio_noacct(bio);
724 			break;
725 		case DM_MAPIO_SUBMITTED:
726 			break;
727 		default:
728 			WARN_ONCE(true, "__multipath_map_bio() returned %d\n", r);
729 		}
730 	}
731 	blk_finish_plug(&plug);
732 }
733 
734 /*
735  * If we run out of usable paths, should we queue I/O or error it?
736  */
737 static int queue_if_no_path(struct multipath *m, bool f_queue_if_no_path,
738 			    bool save_old_value, const char *caller)
739 {
740 	unsigned long flags;
741 	bool queue_if_no_path_bit, saved_queue_if_no_path_bit;
742 	const char *dm_dev_name = dm_table_device_name(m->ti->table);
743 
744 	DMDEBUG("%s: %s caller=%s f_queue_if_no_path=%d save_old_value=%d",
745 		dm_dev_name, __func__, caller, f_queue_if_no_path, save_old_value);
746 
747 	spin_lock_irqsave(&m->lock, flags);
748 
749 	queue_if_no_path_bit = test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
750 	saved_queue_if_no_path_bit = test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
751 
752 	if (save_old_value) {
753 		if (unlikely(!queue_if_no_path_bit && saved_queue_if_no_path_bit)) {
754 			DMERR("%s: QIFNP disabled but saved as enabled, saving again loses state, not saving!",
755 			      dm_dev_name);
756 		} else
757 			assign_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags, queue_if_no_path_bit);
758 	} else if (!f_queue_if_no_path && saved_queue_if_no_path_bit) {
759 		/* due to "fail_if_no_path" message, need to honor it. */
760 		clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
761 	}
762 	assign_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags, f_queue_if_no_path);
763 
764 	DMDEBUG("%s: after %s changes; QIFNP = %d; SQIFNP = %d; DNFS = %d",
765 		dm_dev_name, __func__,
766 		test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags),
767 		test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags),
768 		dm_noflush_suspending(m->ti));
769 
770 	spin_unlock_irqrestore(&m->lock, flags);
771 
772 	if (!f_queue_if_no_path) {
773 		dm_table_run_md_queue_async(m->ti->table);
774 		process_queued_io_list(m);
775 	}
776 
777 	return 0;
778 }
779 
780 /*
781  * If the queue_if_no_path timeout fires, turn off queue_if_no_path and
782  * process any queued I/O.
783  */
784 static void queue_if_no_path_timeout_work(struct timer_list *t)
785 {
786 	struct multipath *m = timer_container_of(m, t, nopath_timer);
787 
788 	DMWARN("queue_if_no_path timeout on %s, failing queued IO",
789 	       dm_table_device_name(m->ti->table));
790 	queue_if_no_path(m, false, false, __func__);
791 }
792 
793 /*
794  * Enable the queue_if_no_path timeout if necessary.
795  * Called with m->lock held.
796  */
797 static void enable_nopath_timeout(struct multipath *m)
798 {
799 	unsigned long queue_if_no_path_timeout =
800 		READ_ONCE(queue_if_no_path_timeout_secs) * HZ;
801 
802 	lockdep_assert_held(&m->lock);
803 
804 	if (queue_if_no_path_timeout > 0 &&
805 	    atomic_read(&m->nr_valid_paths) == 0 &&
806 	    test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
807 		mod_timer(&m->nopath_timer,
808 			  jiffies + queue_if_no_path_timeout);
809 	}
810 }
811 
812 static void disable_nopath_timeout(struct multipath *m)
813 {
814 	timer_delete_sync(&m->nopath_timer);
815 }
816 
817 /*
818  * An event is triggered whenever a path is taken out of use.
819  * Includes path failure and PG bypass.
820  */
821 static void trigger_event(struct work_struct *work)
822 {
823 	struct multipath *m =
824 		container_of(work, struct multipath, trigger_event);
825 
826 	dm_table_event(m->ti->table);
827 }
828 
829 /*
830  *---------------------------------------------------------------
831  * Constructor/argument parsing:
832  * <#multipath feature args> [<arg>]*
833  * <#hw_handler args> [hw_handler [<arg>]*]
834  * <#priority groups>
835  * <initial priority group>
836  *     [<selector> <#selector args> [<arg>]*
837  *      <#paths> <#per-path selector args>
838  *         [<path> [<arg>]* ]+ ]+
839  *---------------------------------------------------------------
840  */
841 static int parse_path_selector(struct dm_arg_set *as, struct priority_group *pg,
842 			       struct dm_target *ti)
843 {
844 	int r;
845 	struct path_selector_type *pst;
846 	unsigned int ps_argc;
847 
848 	static const struct dm_arg _args[] = {
849 		{0, 1024, "invalid number of path selector args"},
850 	};
851 
852 	pst = dm_get_path_selector(dm_shift_arg(as));
853 	if (!pst) {
854 		ti->error = "unknown path selector type";
855 		return -EINVAL;
856 	}
857 
858 	r = dm_read_arg_group(_args, as, &ps_argc, &ti->error);
859 	if (r) {
860 		dm_put_path_selector(pst);
861 		return -EINVAL;
862 	}
863 
864 	r = pst->create(&pg->ps, ps_argc, as->argv);
865 	if (r) {
866 		dm_put_path_selector(pst);
867 		ti->error = "path selector constructor failed";
868 		return r;
869 	}
870 
871 	pg->ps.type = pst;
872 	dm_consume_args(as, ps_argc);
873 
874 	return 0;
875 }
876 
877 static int setup_scsi_dh(struct block_device *bdev, struct multipath *m,
878 			 const char **attached_handler_name, char **error)
879 {
880 	struct request_queue *q = bdev_get_queue(bdev);
881 	int r;
882 
883 	if (*attached_handler_name) {
884 		/*
885 		 * Clear any hw_handler_params associated with a
886 		 * handler that isn't already attached.
887 		 */
888 		if (m->hw_handler_name && strcmp(*attached_handler_name,
889 						 m->hw_handler_name)) {
890 			kfree(m->hw_handler_params);
891 			m->hw_handler_params = NULL;
892 		}
893 
894 		/*
895 		 * Reset hw_handler_name to match the attached handler
896 		 *
897 		 * NB. This modifies the table line to show the actual
898 		 * handler instead of the original table passed in.
899 		 */
900 		kfree(m->hw_handler_name);
901 		m->hw_handler_name = *attached_handler_name;
902 		*attached_handler_name = NULL;
903 	}
904 
905 	if (m->hw_handler_name) {
906 		r = scsi_dh_attach(q, m->hw_handler_name);
907 		if (r < 0) {
908 			*error = "error attaching hardware handler";
909 			return r;
910 		}
911 
912 		if (m->hw_handler_params) {
913 			r = scsi_dh_set_params(q, m->hw_handler_params);
914 			if (r < 0) {
915 				*error = "unable to set hardware handler parameters";
916 				return r;
917 			}
918 		}
919 	}
920 
921 	return 0;
922 }
923 
924 static struct pgpath *parse_path(struct dm_arg_set *as, struct path_selector *ps,
925 				 struct dm_target *ti)
926 {
927 	int r;
928 	struct pgpath *p;
929 	struct multipath *m = ti->private;
930 	struct request_queue *q;
931 	const char *attached_handler_name = NULL;
932 
933 	/* we need at least a path arg */
934 	if (as->argc < 1) {
935 		ti->error = "no device given";
936 		return ERR_PTR(-EINVAL);
937 	}
938 
939 	p = alloc_pgpath();
940 	if (!p)
941 		return ERR_PTR(-ENOMEM);
942 
943 	r = dm_get_device(ti, dm_shift_arg(as), dm_table_get_mode(ti->table),
944 			  &p->path.dev);
945 	if (r) {
946 		ti->error = "error getting device";
947 		goto bad;
948 	}
949 
950 	q = bdev_get_queue(p->path.dev->bdev);
951 	attached_handler_name = scsi_dh_attached_handler_name(q, GFP_KERNEL);
952 	if (IS_ERR(attached_handler_name)) {
953 		if (PTR_ERR(attached_handler_name) == -ENODEV) {
954 			if (m->hw_handler_name) {
955 				DMERR("hardware handlers are only allowed for SCSI devices");
956 				kfree(m->hw_handler_name);
957 				m->hw_handler_name = NULL;
958 			}
959 			attached_handler_name = NULL;
960 		} else {
961 			r = PTR_ERR(attached_handler_name);
962 			ti->error = "error allocating handler name";
963 			goto bad_put_device;
964 		}
965 	}
966 	if (attached_handler_name || m->hw_handler_name) {
967 		INIT_DELAYED_WORK(&p->activate_path, activate_path_work);
968 		r = setup_scsi_dh(p->path.dev->bdev, m, &attached_handler_name, &ti->error);
969 		kfree(attached_handler_name);
970 		if (r)
971 			goto bad_put_device;
972 	}
973 
974 	r = ps->type->add_path(ps, &p->path, as->argc, as->argv, &ti->error);
975 	if (r)
976 		goto bad_put_device;
977 
978 	return p;
979 
980 bad_put_device:
981 	dm_put_device(ti, p->path.dev);
982 bad:
983 	free_pgpath(p);
984 	return ERR_PTR(r);
985 }
986 
987 static struct priority_group *parse_priority_group(struct dm_arg_set *as,
988 						   struct multipath *m)
989 {
990 	static const struct dm_arg _args[] = {
991 		{1, 1024, "invalid number of paths"},
992 		{0, 1024, "invalid number of selector args"}
993 	};
994 
995 	int r;
996 	unsigned int i, nr_selector_args, nr_args;
997 	struct priority_group *pg;
998 	struct dm_target *ti = m->ti;
999 
1000 	if (as->argc < 2) {
1001 		as->argc = 0;
1002 		ti->error = "not enough priority group arguments";
1003 		return ERR_PTR(-EINVAL);
1004 	}
1005 
1006 	pg = alloc_priority_group();
1007 	if (!pg) {
1008 		ti->error = "couldn't allocate priority group";
1009 		return ERR_PTR(-ENOMEM);
1010 	}
1011 	pg->m = m;
1012 
1013 	r = parse_path_selector(as, pg, ti);
1014 	if (r)
1015 		goto bad;
1016 
1017 	/*
1018 	 * read the paths
1019 	 */
1020 	r = dm_read_arg(_args, as, &pg->nr_pgpaths, &ti->error);
1021 	if (r)
1022 		goto bad;
1023 
1024 	r = dm_read_arg(_args + 1, as, &nr_selector_args, &ti->error);
1025 	if (r)
1026 		goto bad;
1027 
1028 	nr_args = 1 + nr_selector_args;
1029 	for (i = 0; i < pg->nr_pgpaths; i++) {
1030 		struct pgpath *pgpath;
1031 		struct dm_arg_set path_args;
1032 
1033 		if (as->argc < nr_args) {
1034 			ti->error = "not enough path parameters";
1035 			r = -EINVAL;
1036 			goto bad;
1037 		}
1038 
1039 		path_args.argc = nr_args;
1040 		path_args.argv = as->argv;
1041 
1042 		pgpath = parse_path(&path_args, &pg->ps, ti);
1043 		if (IS_ERR(pgpath)) {
1044 			r = PTR_ERR(pgpath);
1045 			goto bad;
1046 		}
1047 
1048 		pgpath->pg = pg;
1049 		list_add_tail(&pgpath->list, &pg->pgpaths);
1050 		dm_consume_args(as, nr_args);
1051 	}
1052 
1053 	return pg;
1054 
1055  bad:
1056 	free_priority_group(pg, ti);
1057 	return ERR_PTR(r);
1058 }
1059 
1060 static int parse_hw_handler(struct dm_arg_set *as, struct multipath *m)
1061 {
1062 	unsigned int hw_argc;
1063 	int ret;
1064 	struct dm_target *ti = m->ti;
1065 
1066 	static const struct dm_arg _args[] = {
1067 		{0, 1024, "invalid number of hardware handler args"},
1068 	};
1069 
1070 	if (dm_read_arg_group(_args, as, &hw_argc, &ti->error))
1071 		return -EINVAL;
1072 
1073 	if (!hw_argc)
1074 		return 0;
1075 
1076 	if (m->queue_mode == DM_TYPE_BIO_BASED) {
1077 		dm_consume_args(as, hw_argc);
1078 		DMERR("bio-based multipath doesn't allow hardware handler args");
1079 		return 0;
1080 	}
1081 
1082 	m->hw_handler_name = kstrdup(dm_shift_arg(as), GFP_KERNEL);
1083 	if (!m->hw_handler_name)
1084 		return -EINVAL;
1085 
1086 	if (hw_argc > 1) {
1087 		char *p;
1088 		int i, j, len = 4;
1089 
1090 		for (i = 0; i <= hw_argc - 2; i++)
1091 			len += strlen(as->argv[i]) + 1;
1092 		p = m->hw_handler_params = kzalloc(len, GFP_KERNEL);
1093 		if (!p) {
1094 			ti->error = "memory allocation failed";
1095 			ret = -ENOMEM;
1096 			goto fail;
1097 		}
1098 		j = sprintf(p, "%d", hw_argc - 1);
1099 		for (i = 0, p += j + 1; i <= hw_argc - 2; i++, p += j + 1)
1100 			j = sprintf(p, "%s", as->argv[i]);
1101 	}
1102 	dm_consume_args(as, hw_argc - 1);
1103 
1104 	return 0;
1105 fail:
1106 	kfree(m->hw_handler_name);
1107 	m->hw_handler_name = NULL;
1108 	return ret;
1109 }
1110 
1111 static int parse_features(struct dm_arg_set *as, struct multipath *m)
1112 {
1113 	int r;
1114 	unsigned int argc;
1115 	struct dm_target *ti = m->ti;
1116 	const char *arg_name;
1117 
1118 	static const struct dm_arg _args[] = {
1119 		{0, 8, "invalid number of feature args"},
1120 		{1, 50, "pg_init_retries must be between 1 and 50"},
1121 		{0, 60000, "pg_init_delay_msecs must be between 0 and 60000"},
1122 	};
1123 
1124 	r = dm_read_arg_group(_args, as, &argc, &ti->error);
1125 	if (r)
1126 		return -EINVAL;
1127 
1128 	if (!argc)
1129 		return 0;
1130 
1131 	do {
1132 		arg_name = dm_shift_arg(as);
1133 		argc--;
1134 
1135 		if (!strcasecmp(arg_name, "queue_if_no_path")) {
1136 			r = queue_if_no_path(m, true, false, __func__);
1137 			continue;
1138 		}
1139 
1140 		if (!strcasecmp(arg_name, "retain_attached_hw_handler")) {
1141 			/* no longer has any effect */
1142 			continue;
1143 		}
1144 
1145 		if (!strcasecmp(arg_name, "pg_init_retries") &&
1146 		    (argc >= 1)) {
1147 			r = dm_read_arg(_args + 1, as, &m->pg_init_retries, &ti->error);
1148 			argc--;
1149 			continue;
1150 		}
1151 
1152 		if (!strcasecmp(arg_name, "pg_init_delay_msecs") &&
1153 		    (argc >= 1)) {
1154 			r = dm_read_arg(_args + 2, as, &m->pg_init_delay_msecs, &ti->error);
1155 			argc--;
1156 			continue;
1157 		}
1158 
1159 		if (!strcasecmp(arg_name, "queue_mode") &&
1160 		    (argc >= 1)) {
1161 			const char *queue_mode_name = dm_shift_arg(as);
1162 
1163 			if (!strcasecmp(queue_mode_name, "bio"))
1164 				m->queue_mode = DM_TYPE_BIO_BASED;
1165 			else if (!strcasecmp(queue_mode_name, "rq") ||
1166 				 !strcasecmp(queue_mode_name, "mq"))
1167 				m->queue_mode = DM_TYPE_REQUEST_BASED;
1168 			else {
1169 				ti->error = "Unknown 'queue_mode' requested";
1170 				r = -EINVAL;
1171 			}
1172 			argc--;
1173 			continue;
1174 		}
1175 
1176 		ti->error = "Unrecognised multipath feature request";
1177 		r = -EINVAL;
1178 	} while (argc && !r);
1179 
1180 	return r;
1181 }
1182 
1183 static int multipath_ctr(struct dm_target *ti, unsigned int argc, char **argv)
1184 {
1185 	/* target arguments */
1186 	static const struct dm_arg _args[] = {
1187 		{0, 1024, "invalid number of priority groups"},
1188 		{0, 1024, "invalid initial priority group number"},
1189 	};
1190 
1191 	int r;
1192 	struct multipath *m;
1193 	struct dm_arg_set as;
1194 	unsigned int pg_count = 0;
1195 	unsigned int next_pg_num;
1196 
1197 	as.argc = argc;
1198 	as.argv = argv;
1199 
1200 	m = alloc_multipath(ti);
1201 	if (!m) {
1202 		ti->error = "can't allocate multipath";
1203 		return -EINVAL;
1204 	}
1205 
1206 	r = parse_features(&as, m);
1207 	if (r)
1208 		goto bad;
1209 
1210 	r = alloc_multipath_stage2(ti, m);
1211 	if (r)
1212 		goto bad;
1213 
1214 	r = parse_hw_handler(&as, m);
1215 	if (r)
1216 		goto bad;
1217 
1218 	r = dm_read_arg(_args, &as, &m->nr_priority_groups, &ti->error);
1219 	if (r)
1220 		goto bad;
1221 
1222 	r = dm_read_arg(_args + 1, &as, &next_pg_num, &ti->error);
1223 	if (r)
1224 		goto bad;
1225 
1226 	if ((!m->nr_priority_groups && next_pg_num) ||
1227 	    (m->nr_priority_groups && !next_pg_num)) {
1228 		ti->error = "invalid initial priority group";
1229 		r = -EINVAL;
1230 		goto bad;
1231 	}
1232 
1233 	/* parse the priority groups */
1234 	while (as.argc) {
1235 		struct priority_group *pg;
1236 		unsigned int nr_valid_paths = atomic_read(&m->nr_valid_paths);
1237 
1238 		pg = parse_priority_group(&as, m);
1239 		if (IS_ERR(pg)) {
1240 			r = PTR_ERR(pg);
1241 			goto bad;
1242 		}
1243 
1244 		nr_valid_paths += pg->nr_pgpaths;
1245 		atomic_set(&m->nr_valid_paths, nr_valid_paths);
1246 
1247 		list_add_tail(&pg->list, &m->priority_groups);
1248 		pg_count++;
1249 		pg->pg_num = pg_count;
1250 		if (!--next_pg_num)
1251 			m->next_pg = pg;
1252 	}
1253 
1254 	if (pg_count != m->nr_priority_groups) {
1255 		ti->error = "priority group count mismatch";
1256 		r = -EINVAL;
1257 		goto bad;
1258 	}
1259 
1260 	spin_lock_irq(&m->lock);
1261 	enable_nopath_timeout(m);
1262 	spin_unlock_irq(&m->lock);
1263 
1264 	ti->num_flush_bios = 1;
1265 	ti->num_discard_bios = 1;
1266 	ti->num_write_zeroes_bios = 1;
1267 	if (m->queue_mode == DM_TYPE_BIO_BASED)
1268 		ti->per_io_data_size = multipath_per_bio_data_size();
1269 	else
1270 		ti->per_io_data_size = sizeof(struct dm_mpath_io);
1271 
1272 	return 0;
1273 
1274  bad:
1275 	free_multipath(m);
1276 	return r;
1277 }
1278 
1279 static void multipath_wait_for_pg_init_completion(struct multipath *m)
1280 {
1281 	DEFINE_WAIT(wait);
1282 
1283 	while (1) {
1284 		prepare_to_wait(&m->pg_init_wait, &wait, TASK_UNINTERRUPTIBLE);
1285 
1286 		if (!atomic_read(&m->pg_init_in_progress))
1287 			break;
1288 
1289 		io_schedule();
1290 	}
1291 	finish_wait(&m->pg_init_wait, &wait);
1292 }
1293 
1294 static void flush_multipath_work(struct multipath *m)
1295 {
1296 	if (m->hw_handler_name) {
1297 		if (!atomic_read(&m->pg_init_in_progress))
1298 			goto skip;
1299 
1300 		spin_lock_irq(&m->lock);
1301 		if (atomic_read(&m->pg_init_in_progress) &&
1302 		    !test_and_set_bit(MPATHF_PG_INIT_DISABLED, &m->flags)) {
1303 			spin_unlock_irq(&m->lock);
1304 
1305 			flush_workqueue(kmpath_handlerd);
1306 			multipath_wait_for_pg_init_completion(m);
1307 
1308 			spin_lock_irq(&m->lock);
1309 			clear_bit(MPATHF_PG_INIT_DISABLED, &m->flags);
1310 		}
1311 		spin_unlock_irq(&m->lock);
1312 	}
1313 skip:
1314 	if (m->queue_mode == DM_TYPE_BIO_BASED)
1315 		flush_work(&m->process_queued_bios);
1316 	flush_work(&m->trigger_event);
1317 }
1318 
1319 static void multipath_dtr(struct dm_target *ti)
1320 {
1321 	struct multipath *m = ti->private;
1322 
1323 	disable_nopath_timeout(m);
1324 	flush_multipath_work(m);
1325 	free_multipath(m);
1326 }
1327 
1328 /*
1329  * Take a path out of use.
1330  */
1331 static int fail_path(struct pgpath *pgpath)
1332 {
1333 	unsigned long flags;
1334 	struct multipath *m = pgpath->pg->m;
1335 
1336 	spin_lock_irqsave(&m->lock, flags);
1337 
1338 	if (!pgpath->is_active)
1339 		goto out;
1340 
1341 	DMWARN("%s: Failing path %s.",
1342 	       dm_table_device_name(m->ti->table),
1343 	       pgpath->path.dev->name);
1344 
1345 	pgpath->pg->ps.type->fail_path(&pgpath->pg->ps, &pgpath->path);
1346 	pgpath->is_active = false;
1347 	pgpath->fail_count++;
1348 
1349 	atomic_dec(&m->nr_valid_paths);
1350 
1351 	if (pgpath == m->current_pgpath)
1352 		m->current_pgpath = NULL;
1353 
1354 	dm_path_uevent(DM_UEVENT_PATH_FAILED, m->ti,
1355 		       pgpath->path.dev->name, atomic_read(&m->nr_valid_paths));
1356 
1357 	queue_work(dm_mpath_wq, &m->trigger_event);
1358 
1359 	enable_nopath_timeout(m);
1360 
1361 out:
1362 	spin_unlock_irqrestore(&m->lock, flags);
1363 
1364 	return 0;
1365 }
1366 
1367 /*
1368  * Reinstate a previously-failed path
1369  */
1370 static int reinstate_path(struct pgpath *pgpath)
1371 {
1372 	int r = 0, run_queue = 0;
1373 	struct multipath *m = pgpath->pg->m;
1374 	unsigned int nr_valid_paths;
1375 
1376 	spin_lock_irq(&m->lock);
1377 
1378 	if (pgpath->is_active)
1379 		goto out;
1380 
1381 	DMWARN("%s: Reinstating path %s.",
1382 	       dm_table_device_name(m->ti->table),
1383 	       pgpath->path.dev->name);
1384 
1385 	r = pgpath->pg->ps.type->reinstate_path(&pgpath->pg->ps, &pgpath->path);
1386 	if (r)
1387 		goto out;
1388 
1389 	pgpath->is_active = true;
1390 
1391 	nr_valid_paths = atomic_inc_return(&m->nr_valid_paths);
1392 	if (nr_valid_paths == 1) {
1393 		m->current_pgpath = NULL;
1394 		run_queue = 1;
1395 	} else if (m->hw_handler_name && (m->current_pg == pgpath->pg)) {
1396 		if (queue_work(kmpath_handlerd, &pgpath->activate_path.work))
1397 			atomic_inc(&m->pg_init_in_progress);
1398 	}
1399 
1400 	dm_path_uevent(DM_UEVENT_PATH_REINSTATED, m->ti,
1401 		       pgpath->path.dev->name, nr_valid_paths);
1402 
1403 	schedule_work(&m->trigger_event);
1404 
1405 out:
1406 	spin_unlock_irq(&m->lock);
1407 	if (run_queue) {
1408 		dm_table_run_md_queue_async(m->ti->table);
1409 		process_queued_io_list(m);
1410 	}
1411 
1412 	if (pgpath->is_active)
1413 		disable_nopath_timeout(m);
1414 
1415 	return r;
1416 }
1417 
1418 /*
1419  * Fail or reinstate all paths that match the provided struct dm_dev.
1420  */
1421 static int action_dev(struct multipath *m, dev_t dev, action_fn action)
1422 {
1423 	int r = -EINVAL;
1424 	struct pgpath *pgpath;
1425 	struct priority_group *pg;
1426 
1427 	list_for_each_entry(pg, &m->priority_groups, list) {
1428 		list_for_each_entry(pgpath, &pg->pgpaths, list) {
1429 			if (pgpath->path.dev->bdev->bd_dev == dev)
1430 				r = action(pgpath);
1431 		}
1432 	}
1433 
1434 	return r;
1435 }
1436 
1437 /*
1438  * Temporarily try to avoid having to use the specified PG
1439  */
1440 static void bypass_pg(struct multipath *m, struct priority_group *pg,
1441 		      bool bypassed, bool can_be_delayed)
1442 {
1443 	unsigned long flags;
1444 
1445 	spin_lock_irqsave(&m->lock, flags);
1446 
1447 	pg->bypassed = bypassed;
1448 	if (can_be_delayed && test_bit(MPATHF_DELAY_PG_SWITCH, &m->flags))
1449 		set_bit(MPATHF_NEED_PG_SWITCH, &m->flags);
1450 	else {
1451 		m->current_pgpath = NULL;
1452 		m->current_pg = NULL;
1453 	}
1454 
1455 	spin_unlock_irqrestore(&m->lock, flags);
1456 
1457 	schedule_work(&m->trigger_event);
1458 }
1459 
1460 /*
1461  * Switch to using the specified PG from the next I/O that gets mapped
1462  */
1463 static int switch_pg_num(struct multipath *m, const char *pgstr)
1464 {
1465 	struct priority_group *pg;
1466 	unsigned int pgnum;
1467 	char dummy;
1468 
1469 	if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1470 	    !m->nr_priority_groups || (pgnum > m->nr_priority_groups)) {
1471 		DMWARN("invalid PG number supplied to %s", __func__);
1472 		return -EINVAL;
1473 	}
1474 
1475 	spin_lock_irq(&m->lock);
1476 	list_for_each_entry(pg, &m->priority_groups, list) {
1477 		pg->bypassed = false;
1478 		if (--pgnum)
1479 			continue;
1480 
1481 		if (test_bit(MPATHF_DELAY_PG_SWITCH, &m->flags))
1482 			set_bit(MPATHF_NEED_PG_SWITCH, &m->flags);
1483 		else {
1484 			m->current_pgpath = NULL;
1485 			m->current_pg = NULL;
1486 		}
1487 		m->next_pg = pg;
1488 	}
1489 	spin_unlock_irq(&m->lock);
1490 
1491 	schedule_work(&m->trigger_event);
1492 	return 0;
1493 }
1494 
1495 /*
1496  * Set/clear bypassed status of a PG.
1497  * PGs are numbered upwards from 1 in the order they were declared.
1498  */
1499 static int bypass_pg_num(struct multipath *m, const char *pgstr, bool bypassed)
1500 {
1501 	struct priority_group *pg;
1502 	unsigned int pgnum;
1503 	char dummy;
1504 
1505 	if (!pgstr || (sscanf(pgstr, "%u%c", &pgnum, &dummy) != 1) || !pgnum ||
1506 	    !m->nr_priority_groups || (pgnum > m->nr_priority_groups)) {
1507 		DMWARN("invalid PG number supplied to bypass_pg");
1508 		return -EINVAL;
1509 	}
1510 
1511 	list_for_each_entry(pg, &m->priority_groups, list) {
1512 		if (!--pgnum)
1513 			break;
1514 	}
1515 
1516 	bypass_pg(m, pg, bypassed, true);
1517 	return 0;
1518 }
1519 
1520 /*
1521  * Should we retry pg_init immediately?
1522  */
1523 static bool pg_init_limit_reached(struct multipath *m, struct pgpath *pgpath)
1524 {
1525 	unsigned long flags;
1526 	bool limit_reached = false;
1527 
1528 	spin_lock_irqsave(&m->lock, flags);
1529 
1530 	if (atomic_read(&m->pg_init_count) <= m->pg_init_retries &&
1531 	    !test_bit(MPATHF_PG_INIT_DISABLED, &m->flags))
1532 		set_bit(MPATHF_PG_INIT_REQUIRED, &m->flags);
1533 	else
1534 		limit_reached = true;
1535 
1536 	spin_unlock_irqrestore(&m->lock, flags);
1537 
1538 	return limit_reached;
1539 }
1540 
1541 static void pg_init_done(void *data, int errors)
1542 {
1543 	struct pgpath *pgpath = data;
1544 	struct priority_group *pg = pgpath->pg;
1545 	struct multipath *m = pg->m;
1546 	unsigned long flags;
1547 	bool delay_retry = false;
1548 
1549 	/* device or driver problems */
1550 	switch (errors) {
1551 	case SCSI_DH_OK:
1552 		break;
1553 	case SCSI_DH_NOSYS:
1554 		if (!m->hw_handler_name) {
1555 			errors = 0;
1556 			break;
1557 		}
1558 		DMERR("Could not failover the device: Handler scsi_dh_%s "
1559 		      "Error %d.", m->hw_handler_name, errors);
1560 		/*
1561 		 * Fail path for now, so we do not ping pong
1562 		 */
1563 		fail_path(pgpath);
1564 		break;
1565 	case SCSI_DH_DEV_TEMP_BUSY:
1566 		/*
1567 		 * Probably doing something like FW upgrade on the
1568 		 * controller so try the other pg.
1569 		 */
1570 		bypass_pg(m, pg, true, false);
1571 		break;
1572 	case SCSI_DH_RETRY:
1573 		/* Wait before retrying. */
1574 		delay_retry = true;
1575 		fallthrough;
1576 	case SCSI_DH_IMM_RETRY:
1577 	case SCSI_DH_RES_TEMP_UNAVAIL:
1578 		if (pg_init_limit_reached(m, pgpath))
1579 			fail_path(pgpath);
1580 		errors = 0;
1581 		break;
1582 	case SCSI_DH_DEV_OFFLINED:
1583 	default:
1584 		/*
1585 		 * We probably do not want to fail the path for a device
1586 		 * error, but this is what the old dm did. In future
1587 		 * patches we can do more advanced handling.
1588 		 */
1589 		fail_path(pgpath);
1590 	}
1591 
1592 	spin_lock_irqsave(&m->lock, flags);
1593 	if (errors) {
1594 		if (pgpath == m->current_pgpath) {
1595 			DMERR("Could not failover device. Error %d.", errors);
1596 			m->current_pgpath = NULL;
1597 			m->current_pg = NULL;
1598 		}
1599 	} else if (!test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
1600 		pg->bypassed = false;
1601 
1602 	if (atomic_dec_return(&m->pg_init_in_progress) > 0)
1603 		/* Activations of other paths are still on going */
1604 		goto out;
1605 
1606 	if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags)) {
1607 		if (delay_retry)
1608 			set_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1609 		else
1610 			clear_bit(MPATHF_PG_INIT_DELAY_RETRY, &m->flags);
1611 
1612 		if (__pg_init_all_paths(m))
1613 			goto out;
1614 	}
1615 	clear_bit(MPATHF_QUEUE_IO, &m->flags);
1616 
1617 	process_queued_io_list(m);
1618 
1619 	/*
1620 	 * Wake up any thread waiting to suspend.
1621 	 */
1622 	wake_up(&m->pg_init_wait);
1623 
1624 out:
1625 	spin_unlock_irqrestore(&m->lock, flags);
1626 }
1627 
1628 static void activate_or_offline_path(struct pgpath *pgpath)
1629 {
1630 	struct request_queue *q = bdev_get_queue(pgpath->path.dev->bdev);
1631 
1632 	if (pgpath->is_active && !blk_queue_dying(q))
1633 		scsi_dh_activate(q, pg_init_done, pgpath);
1634 	else
1635 		pg_init_done(pgpath, SCSI_DH_DEV_OFFLINED);
1636 }
1637 
1638 static void activate_path_work(struct work_struct *work)
1639 {
1640 	struct pgpath *pgpath =
1641 		container_of(work, struct pgpath, activate_path.work);
1642 
1643 	activate_or_offline_path(pgpath);
1644 }
1645 
1646 static int multipath_end_io(struct dm_target *ti, struct request *clone,
1647 			    blk_status_t error, union map_info *map_context)
1648 {
1649 	struct dm_mpath_io *mpio = get_mpio(map_context);
1650 	struct pgpath *pgpath = mpio->pgpath;
1651 	int r = DM_ENDIO_DONE;
1652 
1653 	/*
1654 	 * We don't queue any clone request inside the multipath target
1655 	 * during end I/O handling, since those clone requests don't have
1656 	 * bio clones.  If we queue them inside the multipath target,
1657 	 * we need to make bio clones, that requires memory allocation.
1658 	 * (See drivers/md/dm-rq.c:end_clone_bio() about why the clone requests
1659 	 *  don't have bio clones.)
1660 	 * Instead of queueing the clone request here, we queue the original
1661 	 * request into dm core, which will remake a clone request and
1662 	 * clone bios for it and resubmit it later.
1663 	 */
1664 	if (error && blk_path_error(error)) {
1665 		struct multipath *m = ti->private;
1666 
1667 		if (error == BLK_STS_RESOURCE)
1668 			r = DM_ENDIO_DELAY_REQUEUE;
1669 		else
1670 			r = DM_ENDIO_REQUEUE;
1671 
1672 		if (pgpath)
1673 			fail_path(pgpath);
1674 
1675 		if (!atomic_read(&m->nr_valid_paths) &&
1676 		    !must_push_back_rq(m)) {
1677 			if (error == BLK_STS_IOERR)
1678 				dm_report_EIO(m);
1679 			/* complete with the original error */
1680 			r = DM_ENDIO_DONE;
1681 		}
1682 	}
1683 
1684 	if (pgpath) {
1685 		struct path_selector *ps = &pgpath->pg->ps;
1686 
1687 		if (ps->type->end_io)
1688 			ps->type->end_io(ps, &pgpath->path, mpio->nr_bytes,
1689 					 clone->io_start_time_ns);
1690 	}
1691 
1692 	return r;
1693 }
1694 
1695 static int multipath_end_io_bio(struct dm_target *ti, struct bio *clone,
1696 				blk_status_t *error)
1697 {
1698 	struct multipath *m = ti->private;
1699 	struct dm_mpath_io *mpio = get_mpio_from_bio(clone);
1700 	struct pgpath *pgpath = mpio->pgpath;
1701 	unsigned long flags;
1702 	int r = DM_ENDIO_DONE;
1703 
1704 	if (!*error || !blk_path_error(*error))
1705 		goto done;
1706 
1707 	if (pgpath)
1708 		fail_path(pgpath);
1709 
1710 	if (!atomic_read(&m->nr_valid_paths)) {
1711 		spin_lock_irqsave(&m->lock, flags);
1712 		if (!test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
1713 			if (__must_push_back(m)) {
1714 				r = DM_ENDIO_REQUEUE;
1715 			} else {
1716 				dm_report_EIO(m);
1717 				*error = BLK_STS_IOERR;
1718 			}
1719 			spin_unlock_irqrestore(&m->lock, flags);
1720 			goto done;
1721 		}
1722 		spin_unlock_irqrestore(&m->lock, flags);
1723 	}
1724 
1725 	multipath_queue_bio(m, clone);
1726 	r = DM_ENDIO_INCOMPLETE;
1727 done:
1728 	if (pgpath) {
1729 		struct path_selector *ps = &pgpath->pg->ps;
1730 
1731 		if (ps->type->end_io)
1732 			ps->type->end_io(ps, &pgpath->path, mpio->nr_bytes,
1733 					 (mpio->start_time_ns ?:
1734 					  dm_start_time_ns_from_clone(clone)));
1735 	}
1736 
1737 	return r;
1738 }
1739 
1740 /*
1741  * Suspend with flush can't complete until all the I/O is processed
1742  * so if the last path fails we must error any remaining I/O.
1743  * - Note that if the freeze_bdev fails while suspending, the
1744  *   queue_if_no_path state is lost - userspace should reset it.
1745  * Otherwise, during noflush suspend, queue_if_no_path will not change.
1746  */
1747 static void multipath_presuspend(struct dm_target *ti)
1748 {
1749 	struct multipath *m = ti->private;
1750 
1751 	/* FIXME: bio-based shouldn't need to always disable queue_if_no_path */
1752 	if (m->queue_mode == DM_TYPE_BIO_BASED || !dm_noflush_suspending(m->ti))
1753 		queue_if_no_path(m, false, true, __func__);
1754 }
1755 
1756 static void multipath_postsuspend(struct dm_target *ti)
1757 {
1758 	struct multipath *m = ti->private;
1759 
1760 	mutex_lock(&m->work_mutex);
1761 	flush_multipath_work(m);
1762 	mutex_unlock(&m->work_mutex);
1763 }
1764 
1765 /*
1766  * Restore the queue_if_no_path setting.
1767  */
1768 static void multipath_resume(struct dm_target *ti)
1769 {
1770 	struct multipath *m = ti->private;
1771 
1772 	spin_lock_irq(&m->lock);
1773 	if (test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags)) {
1774 		set_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags);
1775 		clear_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags);
1776 	}
1777 
1778 	DMDEBUG("%s: %s finished; QIFNP = %d; SQIFNP = %d",
1779 		dm_table_device_name(m->ti->table), __func__,
1780 		test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags),
1781 		test_bit(MPATHF_SAVED_QUEUE_IF_NO_PATH, &m->flags));
1782 
1783 	spin_unlock_irq(&m->lock);
1784 }
1785 
1786 /*
1787  * Info output has the following format:
1788  * num_multipath_feature_args [multipath_feature_args]*
1789  * num_handler_status_args [handler_status_args]*
1790  * num_groups init_group_number
1791  *            [A|D|E num_ps_status_args [ps_status_args]*
1792  *             num_paths num_selector_args
1793  *             [path_dev A|F fail_count [selector_args]* ]+ ]+
1794  *
1795  * Table output has the following format (identical to the constructor string):
1796  * num_feature_args [features_args]*
1797  * num_handler_args hw_handler [hw_handler_args]*
1798  * num_groups init_group_number
1799  *     [priority selector-name num_ps_args [ps_args]*
1800  *      num_paths num_selector_args [path_dev [selector_args]* ]+ ]+
1801  */
1802 static void multipath_status(struct dm_target *ti, status_type_t type,
1803 			     unsigned int status_flags, char *result, unsigned int maxlen)
1804 {
1805 	int sz = 0, pg_counter, pgpath_counter;
1806 	struct multipath *m = ti->private;
1807 	struct priority_group *pg;
1808 	struct pgpath *p;
1809 	unsigned int pg_num;
1810 	char state;
1811 
1812 	spin_lock_irq(&m->lock);
1813 
1814 	/* Features */
1815 	if (type == STATUSTYPE_INFO)
1816 		DMEMIT("2 %u %u ", test_bit(MPATHF_QUEUE_IO, &m->flags),
1817 		       atomic_read(&m->pg_init_count));
1818 	else {
1819 		DMEMIT("%u ", test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags) +
1820 			      (m->pg_init_retries > 0) * 2 +
1821 			      (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT) * 2 +
1822 			      (m->queue_mode != DM_TYPE_REQUEST_BASED) * 2);
1823 
1824 		if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
1825 			DMEMIT("queue_if_no_path ");
1826 		if (m->pg_init_retries)
1827 			DMEMIT("pg_init_retries %u ", m->pg_init_retries);
1828 		if (m->pg_init_delay_msecs != DM_PG_INIT_DELAY_DEFAULT)
1829 			DMEMIT("pg_init_delay_msecs %u ", m->pg_init_delay_msecs);
1830 		if (m->queue_mode != DM_TYPE_REQUEST_BASED) {
1831 			switch (m->queue_mode) {
1832 			case DM_TYPE_BIO_BASED:
1833 				DMEMIT("queue_mode bio ");
1834 				break;
1835 			default:
1836 				WARN_ON_ONCE(true);
1837 				break;
1838 			}
1839 		}
1840 	}
1841 
1842 	if (!m->hw_handler_name || type == STATUSTYPE_INFO)
1843 		DMEMIT("0 ");
1844 	else
1845 		DMEMIT("1 %s ", m->hw_handler_name);
1846 
1847 	DMEMIT("%u ", m->nr_priority_groups);
1848 
1849 	if (m->current_pg)
1850 		pg_num = m->current_pg->pg_num;
1851 	else if (m->next_pg)
1852 		pg_num = m->next_pg->pg_num;
1853 	else
1854 		pg_num = (m->nr_priority_groups ? 1 : 0);
1855 
1856 	DMEMIT("%u ", pg_num);
1857 
1858 	switch (type) {
1859 	case STATUSTYPE_INFO:
1860 		list_for_each_entry(pg, &m->priority_groups, list) {
1861 			if (pg->bypassed)
1862 				state = 'D';	/* Disabled */
1863 			else if (pg == m->current_pg)
1864 				state = 'A';	/* Currently Active */
1865 			else
1866 				state = 'E';	/* Enabled */
1867 
1868 			DMEMIT("%c ", state);
1869 
1870 			if (pg->ps.type->status)
1871 				sz += pg->ps.type->status(&pg->ps, NULL, type,
1872 							  result + sz,
1873 							  maxlen - sz);
1874 			else
1875 				DMEMIT("0 ");
1876 
1877 			DMEMIT("%u %u ", pg->nr_pgpaths,
1878 			       pg->ps.type->info_args);
1879 
1880 			list_for_each_entry(p, &pg->pgpaths, list) {
1881 				DMEMIT("%s %s %u ", p->path.dev->name,
1882 				       p->is_active ? "A" : "F",
1883 				       p->fail_count);
1884 				if (pg->ps.type->status)
1885 					sz += pg->ps.type->status(&pg->ps,
1886 					      &p->path, type, result + sz,
1887 					      maxlen - sz);
1888 			}
1889 		}
1890 		break;
1891 
1892 	case STATUSTYPE_TABLE:
1893 		list_for_each_entry(pg, &m->priority_groups, list) {
1894 			DMEMIT("%s ", pg->ps.type->name);
1895 
1896 			if (pg->ps.type->status)
1897 				sz += pg->ps.type->status(&pg->ps, NULL, type,
1898 							  result + sz,
1899 							  maxlen - sz);
1900 			else
1901 				DMEMIT("0 ");
1902 
1903 			DMEMIT("%u %u ", pg->nr_pgpaths,
1904 			       pg->ps.type->table_args);
1905 
1906 			list_for_each_entry(p, &pg->pgpaths, list) {
1907 				DMEMIT("%s ", p->path.dev->name);
1908 				if (pg->ps.type->status)
1909 					sz += pg->ps.type->status(&pg->ps,
1910 					      &p->path, type, result + sz,
1911 					      maxlen - sz);
1912 			}
1913 		}
1914 		break;
1915 
1916 	case STATUSTYPE_IMA:
1917 		sz = 0; /*reset the result pointer*/
1918 
1919 		DMEMIT_TARGET_NAME_VERSION(ti->type);
1920 		DMEMIT(",nr_priority_groups=%u", m->nr_priority_groups);
1921 
1922 		pg_counter = 0;
1923 		list_for_each_entry(pg, &m->priority_groups, list) {
1924 			if (pg->bypassed)
1925 				state = 'D';	/* Disabled */
1926 			else if (pg == m->current_pg)
1927 				state = 'A';	/* Currently Active */
1928 			else
1929 				state = 'E';	/* Enabled */
1930 			DMEMIT(",pg_state_%d=%c", pg_counter, state);
1931 			DMEMIT(",nr_pgpaths_%d=%u", pg_counter, pg->nr_pgpaths);
1932 			DMEMIT(",path_selector_name_%d=%s", pg_counter, pg->ps.type->name);
1933 
1934 			pgpath_counter = 0;
1935 			list_for_each_entry(p, &pg->pgpaths, list) {
1936 				DMEMIT(",path_name_%d_%d=%s,is_active_%d_%d=%c,fail_count_%d_%d=%u",
1937 				       pg_counter, pgpath_counter, p->path.dev->name,
1938 				       pg_counter, pgpath_counter, p->is_active ? 'A' : 'F',
1939 				       pg_counter, pgpath_counter, p->fail_count);
1940 				if (pg->ps.type->status) {
1941 					DMEMIT(",path_selector_status_%d_%d=",
1942 					       pg_counter, pgpath_counter);
1943 					sz += pg->ps.type->status(&pg->ps, &p->path,
1944 								  type, result + sz,
1945 								  maxlen - sz);
1946 				}
1947 				pgpath_counter++;
1948 			}
1949 			pg_counter++;
1950 		}
1951 		DMEMIT(";");
1952 		break;
1953 	}
1954 
1955 	spin_unlock_irq(&m->lock);
1956 }
1957 
1958 static int multipath_message(struct dm_target *ti, unsigned int argc, char **argv,
1959 			     char *result, unsigned int maxlen)
1960 {
1961 	int r = -EINVAL;
1962 	dev_t dev;
1963 	struct multipath *m = ti->private;
1964 	action_fn action;
1965 
1966 	mutex_lock(&m->work_mutex);
1967 
1968 	if (dm_suspended(ti)) {
1969 		r = -EBUSY;
1970 		goto out;
1971 	}
1972 
1973 	if (argc == 1) {
1974 		if (!strcasecmp(argv[0], "queue_if_no_path")) {
1975 			r = queue_if_no_path(m, true, false, __func__);
1976 			spin_lock_irq(&m->lock);
1977 			enable_nopath_timeout(m);
1978 			spin_unlock_irq(&m->lock);
1979 			goto out;
1980 		} else if (!strcasecmp(argv[0], "fail_if_no_path")) {
1981 			r = queue_if_no_path(m, false, false, __func__);
1982 			disable_nopath_timeout(m);
1983 			goto out;
1984 		}
1985 	}
1986 
1987 	if (argc != 2) {
1988 		DMWARN("Invalid multipath message arguments. Expected 2 arguments, got %d.", argc);
1989 		goto out;
1990 	}
1991 
1992 	if (!strcasecmp(argv[0], "disable_group")) {
1993 		r = bypass_pg_num(m, argv[1], true);
1994 		goto out;
1995 	} else if (!strcasecmp(argv[0], "enable_group")) {
1996 		r = bypass_pg_num(m, argv[1], false);
1997 		goto out;
1998 	} else if (!strcasecmp(argv[0], "switch_group")) {
1999 		r = switch_pg_num(m, argv[1]);
2000 		goto out;
2001 	} else if (!strcasecmp(argv[0], "reinstate_path"))
2002 		action = reinstate_path;
2003 	else if (!strcasecmp(argv[0], "fail_path"))
2004 		action = fail_path;
2005 	else {
2006 		DMWARN("Unrecognised multipath message received: %s", argv[0]);
2007 		goto out;
2008 	}
2009 
2010 	r = dm_devt_from_path(argv[1], &dev);
2011 	if (r) {
2012 		DMWARN("message: error getting device %s",
2013 		       argv[1]);
2014 		goto out;
2015 	}
2016 
2017 	r = action_dev(m, dev, action);
2018 
2019 out:
2020 	mutex_unlock(&m->work_mutex);
2021 	return r;
2022 }
2023 
2024 /*
2025  * Perform a minimal read from the given path to find out whether the
2026  * path still works.  If a path error occurs, fail it.
2027  */
2028 static int probe_path(struct pgpath *pgpath)
2029 {
2030 	struct block_device *bdev = pgpath->path.dev->bdev;
2031 	unsigned int read_size = bdev_logical_block_size(bdev);
2032 	struct page *page;
2033 	struct bio *bio;
2034 	blk_status_t status;
2035 	int r = 0;
2036 
2037 	if (WARN_ON_ONCE(read_size > PAGE_SIZE))
2038 		return -EINVAL;
2039 
2040 	page = alloc_page(GFP_KERNEL);
2041 	if (!page)
2042 		return -ENOMEM;
2043 
2044 	/* Perform a minimal read: Sector 0, length read_size */
2045 	bio = bio_alloc(bdev, 1, REQ_OP_READ, GFP_KERNEL);
2046 	if (!bio) {
2047 		r = -ENOMEM;
2048 		goto out;
2049 	}
2050 
2051 	bio->bi_iter.bi_sector = 0;
2052 	__bio_add_page(bio, page, read_size, 0);
2053 	submit_bio_wait(bio);
2054 	status = bio->bi_status;
2055 	bio_put(bio);
2056 
2057 	if (status && blk_path_error(status))
2058 		fail_path(pgpath);
2059 
2060 out:
2061 	__free_page(page);
2062 	return r;
2063 }
2064 
2065 /*
2066  * Probe all active paths in current_pg to find out whether they still work.
2067  * Fail all paths that do not work.
2068  *
2069  * Return -ENOTCONN if no valid path is left (even outside of current_pg). We
2070  * cannot probe paths in other pgs without switching current_pg, so if valid
2071  * paths are only in different pgs, they may or may not work. Additionally
2072  * we should not probe paths in a pathgroup that is in the process of
2073  * Initializing. Userspace can submit a request and we'll switch and wait
2074  * for the pathgroup to be initialized. If the request fails, it may need to
2075  * probe again.
2076  */
2077 static int probe_active_paths(struct multipath *m)
2078 {
2079 	struct pgpath *pgpath;
2080 	struct priority_group *pg = NULL;
2081 	int r = 0;
2082 
2083 	spin_lock_irq(&m->lock);
2084 	if (test_bit(MPATHF_DELAY_PG_SWITCH, &m->flags)) {
2085 		wait_event_lock_irq(m->probe_wait,
2086 				    !test_bit(MPATHF_DELAY_PG_SWITCH, &m->flags),
2087 				    m->lock);
2088 		/*
2089 		 * if we waited because a probe was already in progress,
2090 		 * and it probed the current active pathgroup, don't
2091 		 * reprobe. Just return the number of valid paths
2092 		 */
2093 		if (m->current_pg == m->last_probed_pg)
2094 			goto skip_probe;
2095 	}
2096 	if (!m->current_pg || dm_suspended(m->ti) ||
2097 	    test_bit(MPATHF_QUEUE_IO, &m->flags))
2098 		goto skip_probe;
2099 	set_bit(MPATHF_DELAY_PG_SWITCH, &m->flags);
2100 	pg = m->last_probed_pg = m->current_pg;
2101 	spin_unlock_irq(&m->lock);
2102 
2103 	list_for_each_entry(pgpath, &pg->pgpaths, list) {
2104 		if (pg != READ_ONCE(m->current_pg) ||
2105 		    dm_suspended(m->ti))
2106 			goto out;
2107 		if (!pgpath->is_active)
2108 			continue;
2109 
2110 		r = probe_path(pgpath);
2111 		if (r < 0)
2112 			goto out;
2113 	}
2114 
2115 out:
2116 	spin_lock_irq(&m->lock);
2117 	clear_bit(MPATHF_DELAY_PG_SWITCH, &m->flags);
2118 	if (test_and_clear_bit(MPATHF_NEED_PG_SWITCH, &m->flags)) {
2119 		m->current_pgpath = NULL;
2120 		m->current_pg = NULL;
2121 	}
2122 skip_probe:
2123 	if (r == 0 && !atomic_read(&m->nr_valid_paths))
2124 		r = -ENOTCONN;
2125 	spin_unlock_irq(&m->lock);
2126 	if (pg)
2127 		wake_up(&m->probe_wait);
2128 	return r;
2129 }
2130 
2131 static int multipath_prepare_ioctl(struct dm_target *ti,
2132 				   struct block_device **bdev,
2133 				   unsigned int cmd, unsigned long arg,
2134 				   bool *forward)
2135 {
2136 	struct multipath *m = ti->private;
2137 	struct pgpath *pgpath;
2138 	int r;
2139 
2140 	if (_IOC_TYPE(cmd) == DM_IOCTL) {
2141 		*forward = false;
2142 		switch (cmd) {
2143 		case DM_MPATH_PROBE_PATHS:
2144 			return probe_active_paths(m);
2145 		default:
2146 			return -ENOTTY;
2147 		}
2148 	}
2149 
2150 	pgpath = READ_ONCE(m->current_pgpath);
2151 	if (!pgpath || !mpath_double_check_test_bit(MPATHF_QUEUE_IO, m))
2152 		pgpath = choose_pgpath(m, 0);
2153 
2154 	if (pgpath) {
2155 		if (!mpath_double_check_test_bit(MPATHF_QUEUE_IO, m)) {
2156 			*bdev = pgpath->path.dev->bdev;
2157 			r = 0;
2158 		} else {
2159 			/* pg_init has not started or completed */
2160 			r = -ENOTCONN;
2161 		}
2162 	} else {
2163 		/* No path is available */
2164 		r = -EIO;
2165 		spin_lock_irq(&m->lock);
2166 		if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags))
2167 			r = -ENOTCONN;
2168 		spin_unlock_irq(&m->lock);
2169 	}
2170 
2171 	if (r == -ENOTCONN) {
2172 		if (!READ_ONCE(m->current_pg)) {
2173 			/* Path status changed, redo selection */
2174 			(void) choose_pgpath(m, 0);
2175 		}
2176 		spin_lock_irq(&m->lock);
2177 		if (test_bit(MPATHF_PG_INIT_REQUIRED, &m->flags))
2178 			(void) __pg_init_all_paths(m);
2179 		spin_unlock_irq(&m->lock);
2180 		dm_table_run_md_queue_async(m->ti->table);
2181 		process_queued_io_list(m);
2182 	}
2183 
2184 	/*
2185 	 * Only pass ioctls through if the device sizes match exactly.
2186 	 */
2187 	if (!r && ti->len != bdev_nr_sectors((*bdev)))
2188 		return 1;
2189 	return r;
2190 }
2191 
2192 static int multipath_iterate_devices(struct dm_target *ti,
2193 				     iterate_devices_callout_fn fn, void *data)
2194 {
2195 	struct multipath *m = ti->private;
2196 	struct priority_group *pg;
2197 	struct pgpath *p;
2198 	int ret = 0;
2199 
2200 	list_for_each_entry(pg, &m->priority_groups, list) {
2201 		list_for_each_entry(p, &pg->pgpaths, list) {
2202 			ret = fn(ti, p->path.dev, ti->begin, ti->len, data);
2203 			if (ret)
2204 				goto out;
2205 		}
2206 	}
2207 
2208 out:
2209 	return ret;
2210 }
2211 
2212 static int pgpath_busy(struct pgpath *pgpath)
2213 {
2214 	struct request_queue *q = bdev_get_queue(pgpath->path.dev->bdev);
2215 
2216 	return blk_lld_busy(q);
2217 }
2218 
2219 /*
2220  * We return "busy", only when we can map I/Os but underlying devices
2221  * are busy (so even if we map I/Os now, the I/Os will wait on
2222  * the underlying queue).
2223  * In other words, if we want to kill I/Os or queue them inside us
2224  * due to map unavailability, we don't return "busy".  Otherwise,
2225  * dm core won't give us the I/Os and we can't do what we want.
2226  */
2227 static int multipath_busy(struct dm_target *ti)
2228 {
2229 	bool busy = false, has_active = false;
2230 	struct multipath *m = ti->private;
2231 	struct priority_group *pg, *next_pg;
2232 	struct pgpath *pgpath;
2233 
2234 	/* pg_init in progress */
2235 	if (atomic_read(&m->pg_init_in_progress))
2236 		return true;
2237 
2238 	/* no paths available, for blk-mq: rely on IO mapping to delay requeue */
2239 	if (!atomic_read(&m->nr_valid_paths)) {
2240 		unsigned long flags;
2241 
2242 		spin_lock_irqsave(&m->lock, flags);
2243 		if (test_bit(MPATHF_QUEUE_IF_NO_PATH, &m->flags)) {
2244 			spin_unlock_irqrestore(&m->lock, flags);
2245 			return (m->queue_mode != DM_TYPE_REQUEST_BASED);
2246 		}
2247 		spin_unlock_irqrestore(&m->lock, flags);
2248 	}
2249 
2250 	/* Guess which priority_group will be used at next mapping time */
2251 	pg = READ_ONCE(m->current_pg);
2252 	next_pg = READ_ONCE(m->next_pg);
2253 	if (unlikely(!READ_ONCE(m->current_pgpath) && next_pg))
2254 		pg = next_pg;
2255 
2256 	if (!pg) {
2257 		/*
2258 		 * We don't know which pg will be used at next mapping time.
2259 		 * We don't call choose_pgpath() here to avoid to trigger
2260 		 * pg_init just by busy checking.
2261 		 * So we don't know whether underlying devices we will be using
2262 		 * at next mapping time are busy or not. Just try mapping.
2263 		 */
2264 		return busy;
2265 	}
2266 
2267 	/*
2268 	 * If there is one non-busy active path at least, the path selector
2269 	 * will be able to select it. So we consider such a pg as not busy.
2270 	 */
2271 	busy = true;
2272 	list_for_each_entry(pgpath, &pg->pgpaths, list) {
2273 		if (pgpath->is_active) {
2274 			has_active = true;
2275 			if (!pgpath_busy(pgpath)) {
2276 				busy = false;
2277 				break;
2278 			}
2279 		}
2280 	}
2281 
2282 	if (!has_active) {
2283 		/*
2284 		 * No active path in this pg, so this pg won't be used and
2285 		 * the current_pg will be changed at next mapping time.
2286 		 * We need to try mapping to determine it.
2287 		 */
2288 		busy = false;
2289 	}
2290 
2291 	return busy;
2292 }
2293 
2294 /*
2295  *---------------------------------------------------------------
2296  * Module setup
2297  *---------------------------------------------------------------
2298  */
2299 static struct target_type multipath_target = {
2300 	.name = "multipath",
2301 	.version = {1, 15, 0},
2302 	.features = DM_TARGET_SINGLETON | DM_TARGET_IMMUTABLE |
2303 		    DM_TARGET_PASSES_INTEGRITY | DM_TARGET_ATOMIC_WRITES,
2304 	.module = THIS_MODULE,
2305 	.ctr = multipath_ctr,
2306 	.dtr = multipath_dtr,
2307 	.clone_and_map_rq = multipath_clone_and_map,
2308 	.release_clone_rq = multipath_release_clone,
2309 	.rq_end_io = multipath_end_io,
2310 	.map = multipath_map_bio,
2311 	.end_io = multipath_end_io_bio,
2312 	.presuspend = multipath_presuspend,
2313 	.postsuspend = multipath_postsuspend,
2314 	.resume = multipath_resume,
2315 	.status = multipath_status,
2316 	.message = multipath_message,
2317 	.prepare_ioctl = multipath_prepare_ioctl,
2318 	.iterate_devices = multipath_iterate_devices,
2319 	.busy = multipath_busy,
2320 };
2321 
2322 static int __init dm_multipath_init(void)
2323 {
2324 	int r = -ENOMEM;
2325 
2326 	kmultipathd = alloc_workqueue("kmpathd", WQ_MEM_RECLAIM | WQ_PERCPU,
2327 				      0);
2328 	if (!kmultipathd) {
2329 		DMERR("failed to create workqueue kmpathd");
2330 		goto bad_alloc_kmultipathd;
2331 	}
2332 
2333 	/*
2334 	 * A separate workqueue is used to handle the device handlers
2335 	 * to avoid overloading existing workqueue. Overloading the
2336 	 * old workqueue would also create a bottleneck in the
2337 	 * path of the storage hardware device activation.
2338 	 */
2339 	kmpath_handlerd = alloc_ordered_workqueue("kmpath_handlerd",
2340 						  WQ_MEM_RECLAIM);
2341 	if (!kmpath_handlerd) {
2342 		DMERR("failed to create workqueue kmpath_handlerd");
2343 		goto bad_alloc_kmpath_handlerd;
2344 	}
2345 
2346 	dm_mpath_wq = alloc_workqueue("dm_mpath_wq", WQ_PERCPU, 0);
2347 	if (!dm_mpath_wq) {
2348 		DMERR("failed to create workqueue dm_mpath_wq");
2349 		goto bad_alloc_dm_mpath_wq;
2350 	}
2351 
2352 	r = dm_register_target(&multipath_target);
2353 	if (r < 0)
2354 		goto bad_register_target;
2355 
2356 	return 0;
2357 
2358 bad_register_target:
2359 	destroy_workqueue(dm_mpath_wq);
2360 bad_alloc_dm_mpath_wq:
2361 	destroy_workqueue(kmpath_handlerd);
2362 bad_alloc_kmpath_handlerd:
2363 	destroy_workqueue(kmultipathd);
2364 bad_alloc_kmultipathd:
2365 	return r;
2366 }
2367 
2368 static void __exit dm_multipath_exit(void)
2369 {
2370 	destroy_workqueue(dm_mpath_wq);
2371 	destroy_workqueue(kmpath_handlerd);
2372 	destroy_workqueue(kmultipathd);
2373 
2374 	dm_unregister_target(&multipath_target);
2375 }
2376 
2377 module_init(dm_multipath_init);
2378 module_exit(dm_multipath_exit);
2379 
2380 module_param_named(queue_if_no_path_timeout_secs, queue_if_no_path_timeout_secs, ulong, 0644);
2381 MODULE_PARM_DESC(queue_if_no_path_timeout_secs, "No available paths queue IO timeout in seconds");
2382 
2383 MODULE_DESCRIPTION(DM_NAME " multipath target");
2384 MODULE_AUTHOR("Sistina Software <dm-devel@lists.linux.dev>");
2385 MODULE_LICENSE("GPL");
2386