xref: /linux/drivers/nvme/host/multipath.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2017-2018 Christoph Hellwig.
4  */
5 
6 #include <linux/backing-dev.h>
7 #include <linux/moduleparam.h>
8 #include <linux/vmalloc.h>
9 #include <trace/events/block.h>
10 #include "nvme.h"
11 
12 bool multipath = true;
13 static bool multipath_always_on;
14 
15 static int multipath_param_set(const char *val, const struct kernel_param *kp)
16 {
17 	int ret;
18 	bool *arg = kp->arg;
19 
20 	ret = param_set_bool(val, kp);
21 	if (ret)
22 		return ret;
23 
24 	if (multipath_always_on && !*arg) {
25 		pr_err("Can't disable multipath when multipath_always_on is configured.\n");
26 		*arg = true;
27 		return -EINVAL;
28 	}
29 
30 	return 0;
31 }
32 
33 static const struct kernel_param_ops multipath_param_ops = {
34 	.set = multipath_param_set,
35 	.get = param_get_bool,
36 };
37 
38 module_param_cb(multipath, &multipath_param_ops, &multipath, 0444);
39 MODULE_PARM_DESC(multipath,
40 	"turn on native support for multiple controllers per subsystem");
41 
42 static int multipath_always_on_set(const char *val,
43 		const struct kernel_param *kp)
44 {
45 	int ret;
46 	bool *arg = kp->arg;
47 
48 	ret = param_set_bool(val, kp);
49 	if (ret < 0)
50 		return ret;
51 
52 	if (*arg)
53 		multipath = true;
54 
55 	return 0;
56 }
57 
58 static const struct kernel_param_ops multipath_always_on_ops = {
59 	.set = multipath_always_on_set,
60 	.get = param_get_bool,
61 };
62 
63 module_param_cb(multipath_always_on, &multipath_always_on_ops,
64 		&multipath_always_on, 0444);
65 MODULE_PARM_DESC(multipath_always_on,
66 	"create multipath node always except for private namespace with non-unique nsid; note that this also implicitly enables native multipath support");
67 
68 static const char *nvme_iopolicy_names[] = {
69 	[NVME_IOPOLICY_NUMA]	= "numa",
70 	[NVME_IOPOLICY_RR]	= "round-robin",
71 	[NVME_IOPOLICY_QD]      = "queue-depth",
72 };
73 
74 static int iopolicy = NVME_IOPOLICY_NUMA;
75 
76 static int nvme_iopolicy_parse(const char *str)
77 {
78 	int i;
79 
80 	for (i = 0; i < ARRAY_SIZE(nvme_iopolicy_names); i++) {
81 		if (sysfs_streq(str, nvme_iopolicy_names[i]))
82 			return i;
83 	}
84 	return -EINVAL;
85 }
86 
87 static int nvme_set_iopolicy(const char *val, const struct kernel_param *kp)
88 {
89 	int policy;
90 
91 	if (!val)
92 		return -EINVAL;
93 
94 	policy = nvme_iopolicy_parse(val);
95 	if (policy < 0)
96 		return policy;
97 
98 	iopolicy = policy;
99 	return 0;
100 }
101 
102 static int nvme_get_iopolicy(char *buf, const struct kernel_param *kp)
103 {
104 	return sprintf(buf, "%s\n", nvme_iopolicy_names[iopolicy]);
105 }
106 
107 module_param_call(iopolicy, nvme_set_iopolicy, nvme_get_iopolicy,
108 	&iopolicy, 0644);
109 MODULE_PARM_DESC(iopolicy,
110 	"Default multipath I/O policy; 'numa' (default), 'round-robin' or 'queue-depth'");
111 
112 void nvme_mpath_default_iopolicy(struct nvme_subsystem *subsys)
113 {
114 	subsys->iopolicy = iopolicy;
115 }
116 
117 void nvme_mpath_unfreeze(struct nvme_subsystem *subsys)
118 {
119 	struct nvme_ns_head *h;
120 
121 	lockdep_assert_held(&subsys->lock);
122 	list_for_each_entry(h, &subsys->nsheads, entry)
123 		if (h->disk)
124 			blk_mq_unfreeze_queue_nomemrestore(h->disk->queue);
125 }
126 
127 void nvme_mpath_wait_freeze(struct nvme_subsystem *subsys)
128 {
129 	struct nvme_ns_head *h;
130 
131 	lockdep_assert_held(&subsys->lock);
132 	list_for_each_entry(h, &subsys->nsheads, entry)
133 		if (h->disk)
134 			blk_mq_freeze_queue_wait(h->disk->queue);
135 }
136 
137 void nvme_mpath_start_freeze(struct nvme_subsystem *subsys)
138 {
139 	struct nvme_ns_head *h;
140 
141 	lockdep_assert_held(&subsys->lock);
142 	list_for_each_entry(h, &subsys->nsheads, entry)
143 		if (h->disk)
144 			blk_freeze_queue_start(h->disk->queue);
145 }
146 
147 void nvme_failover_req(struct request *req)
148 {
149 	struct nvme_ns *ns = req->q->queuedata;
150 	u16 status = nvme_req(req)->status & NVME_SCT_SC_MASK;
151 	unsigned long flags;
152 	struct bio *bio;
153 
154 	nvme_mpath_clear_current_path(ns);
155 	atomic_long_inc(&ns->failover);
156 
157 	/*
158 	 * If we got back an ANA error, we know the controller is alive but not
159 	 * ready to serve this namespace.  Kick of a re-read of the ANA
160 	 * information page, and just try any other available path for now.
161 	 */
162 	if (nvme_is_ana_error(status) && ns->ctrl->ana_log_buf) {
163 		set_bit(NVME_NS_ANA_PENDING, &ns->flags);
164 		queue_work(nvme_wq, &ns->ctrl->ana_work);
165 	}
166 
167 	spin_lock_irqsave(&ns->head->requeue_lock, flags);
168 	for (bio = req->bio; bio; bio = bio->bi_next)
169 		bio_set_dev(bio, ns->head->disk->part0);
170 	blk_steal_bios(&ns->head->requeue_list, req);
171 	spin_unlock_irqrestore(&ns->head->requeue_lock, flags);
172 
173 	nvme_req(req)->status = 0;
174 	nvme_end_req(req);
175 	kblockd_schedule_work(&ns->head->requeue_work);
176 }
177 
178 void nvme_mpath_start_request(struct request *rq)
179 {
180 	struct nvme_ns *ns = rq->q->queuedata;
181 	struct gendisk *disk = ns->head->disk;
182 
183 	if ((READ_ONCE(ns->head->subsys->iopolicy) == NVME_IOPOLICY_QD) &&
184 	    !(nvme_req(rq)->flags & NVME_MPATH_CNT_ACTIVE)) {
185 		atomic_inc(&ns->ctrl->nr_active);
186 		nvme_req(rq)->flags |= NVME_MPATH_CNT_ACTIVE;
187 	}
188 
189 	if (!blk_queue_io_stat(disk->queue) ||
190 	    (nvme_req(rq)->flags & NVME_MPATH_IO_STATS))
191 		return;
192 	if (blk_rq_is_passthrough(rq) &&
193 	    !blk_rq_passthrough_stats(rq, disk->queue))
194 		return;
195 
196 	nvme_req(rq)->flags |= NVME_MPATH_IO_STATS;
197 	nvme_req(rq)->start_time = bdev_start_io_acct(disk->part0, req_op(rq),
198 						      jiffies);
199 }
200 EXPORT_SYMBOL_GPL(nvme_mpath_start_request);
201 
202 void nvme_mpath_end_request(struct request *rq)
203 {
204 	struct nvme_ns *ns = rq->q->queuedata;
205 
206 	if (nvme_req(rq)->flags & NVME_MPATH_CNT_ACTIVE)
207 		atomic_dec_if_positive(&ns->ctrl->nr_active);
208 
209 	if (!(nvme_req(rq)->flags & NVME_MPATH_IO_STATS))
210 		return;
211 	bdev_end_io_acct(ns->head->disk->part0, req_op(rq),
212 			 blk_rq_bytes(rq) >> SECTOR_SHIFT,
213 			 nvme_req(rq)->start_time);
214 }
215 
216 void nvme_kick_requeue_lists(struct nvme_ctrl *ctrl)
217 {
218 	struct nvme_ns *ns;
219 	int srcu_idx;
220 
221 	srcu_idx = srcu_read_lock(&ctrl->srcu);
222 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
223 				 srcu_read_lock_held(&ctrl->srcu)) {
224 		if (!ns->head->disk)
225 			continue;
226 		kblockd_schedule_work(&ns->head->requeue_work);
227 		if (nvme_ctrl_state(ns->ctrl) == NVME_CTRL_LIVE)
228 			disk_uevent(ns->head->disk, KOBJ_CHANGE);
229 	}
230 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
231 }
232 
233 static const char *nvme_ana_state_names[] = {
234 	[0]				= "invalid state",
235 	[NVME_ANA_OPTIMIZED]		= "optimized",
236 	[NVME_ANA_NONOPTIMIZED]		= "non-optimized",
237 	[NVME_ANA_INACCESSIBLE]		= "inaccessible",
238 	[NVME_ANA_PERSISTENT_LOSS]	= "persistent-loss",
239 	[NVME_ANA_CHANGE]		= "change",
240 };
241 
242 bool nvme_mpath_clear_current_path(struct nvme_ns *ns)
243 {
244 	struct nvme_ns_head *head = ns->head;
245 	bool changed = false;
246 	int node;
247 
248 	for_each_node(node) {
249 		if (ns == rcu_access_pointer(head->current_path[node])) {
250 			rcu_assign_pointer(head->current_path[node], NULL);
251 			changed = true;
252 		}
253 	}
254 	return changed;
255 }
256 
257 void nvme_mpath_clear_ctrl_paths(struct nvme_ctrl *ctrl)
258 {
259 	struct nvme_ns *ns;
260 	int srcu_idx;
261 
262 	srcu_idx = srcu_read_lock(&ctrl->srcu);
263 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
264 				 srcu_read_lock_held(&ctrl->srcu)) {
265 		nvme_mpath_clear_current_path(ns);
266 		kblockd_schedule_work(&ns->head->requeue_work);
267 	}
268 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
269 }
270 
271 void nvme_mpath_revalidate_paths(struct nvme_ns_head *head)
272 {
273 	sector_t capacity = get_capacity(head->disk);
274 	struct nvme_ns *ns;
275 	int node;
276 	int srcu_idx;
277 
278 	srcu_idx = srcu_read_lock(&head->srcu);
279 	list_for_each_entry_srcu(ns, &head->list, siblings,
280 				 srcu_read_lock_held(&head->srcu)) {
281 		if (capacity != get_capacity(ns->disk))
282 			clear_bit(NVME_NS_READY, &ns->flags);
283 	}
284 	srcu_read_unlock(&head->srcu, srcu_idx);
285 
286 	for_each_node(node)
287 		rcu_assign_pointer(head->current_path[node], NULL);
288 	kblockd_schedule_work(&head->requeue_work);
289 }
290 
291 #ifdef CONFIG_BLK_DEV_ZONED
292 int nvme_mpath_revalidate_zones(struct nvme_ns_head *head)
293 {
294 	struct gendisk *disk = head->disk;
295 	int ret;
296 
297 	if (!disk || !blk_queue_is_zoned(disk->queue) ||
298 	    !test_bit(NVME_NSHEAD_DISK_LIVE, &head->flags))
299 		return 0;
300 
301 	ret = blk_revalidate_disk_zones(disk);
302 	if (ret)
303 		dev_warn_ratelimited(disk_to_dev(disk),
304 				     "failed to revalidate zoned namespace head: %d\n",
305 				     ret);
306 	return ret;
307 }
308 #endif /* CONFIG_BLK_DEV_ZONED */
309 
310 enum nvme_path_state {
311 	NVME_PATH_ENABLED,
312 	NVME_PATH_DISABLED_CTRL_DOWN,
313 	NVME_PATH_DISABLED_ANA_PENDING,
314 	NVME_PATH_DISABLED_NS_NOT_READY,
315 };
316 
317 static enum nvme_path_state nvme_path_get_state(struct nvme_ns *ns)
318 {
319 	enum nvme_ctrl_state state = nvme_ctrl_state(ns->ctrl);
320 
321 	/*
322 	 * We don't treat NVME_CTRL_DELETING as a disabled path as I/O should
323 	 * still be able to complete assuming that the controller is connected.
324 	 * Otherwise it will fail immediately and return to the requeue list.
325 	 */
326 	if (state != NVME_CTRL_LIVE && state != NVME_CTRL_DELETING)
327 		return NVME_PATH_DISABLED_CTRL_DOWN;
328 	if (test_bit(NVME_NS_ANA_PENDING, &ns->flags))
329 		return NVME_PATH_DISABLED_ANA_PENDING;
330 	if (!test_bit(NVME_NS_READY, &ns->flags))
331 		return NVME_PATH_DISABLED_NS_NOT_READY;
332 	return NVME_PATH_ENABLED;
333 }
334 
335 static bool nvme_path_is_disabled(struct nvme_ns *ns)
336 {
337 	return nvme_path_get_state(ns) != NVME_PATH_ENABLED;
338 }
339 
340 static struct nvme_ns *__nvme_find_path(struct nvme_ns_head *head, int node)
341 	__must_hold_shared(&head->srcu)
342 {
343 	int found_distance = INT_MAX, fallback_distance = INT_MAX, distance;
344 	struct nvme_ns *found = NULL, *fallback = NULL, *ns;
345 
346 	list_for_each_entry_srcu(ns, &head->list, siblings,
347 				 srcu_read_lock_held(&head->srcu)) {
348 		if (nvme_path_is_disabled(ns))
349 			continue;
350 
351 		if (ns->ctrl->numa_node != NUMA_NO_NODE &&
352 		    READ_ONCE(head->subsys->iopolicy) == NVME_IOPOLICY_NUMA)
353 			distance = node_distance(node, ns->ctrl->numa_node);
354 		else
355 			distance = LOCAL_DISTANCE;
356 
357 		switch (ns->ana_state) {
358 		case NVME_ANA_OPTIMIZED:
359 			if (distance < found_distance) {
360 				found_distance = distance;
361 				found = ns;
362 			}
363 			break;
364 		case NVME_ANA_NONOPTIMIZED:
365 			if (distance < fallback_distance) {
366 				fallback_distance = distance;
367 				fallback = ns;
368 			}
369 			break;
370 		default:
371 			break;
372 		}
373 	}
374 
375 	if (!found)
376 		found = fallback;
377 	if (found)
378 		rcu_assign_pointer(head->current_path[node], found);
379 	return found;
380 }
381 
382 static struct nvme_ns *nvme_next_ns(struct nvme_ns_head *head,
383 		struct nvme_ns *ns)
384 	__must_hold_shared(&head->srcu)
385 {
386 	ns = list_next_or_null_rcu(&head->list, &ns->siblings, struct nvme_ns,
387 			siblings);
388 	if (ns)
389 		return ns;
390 	return list_first_or_null_rcu(&head->list, struct nvme_ns, siblings);
391 }
392 
393 static struct nvme_ns *nvme_round_robin_path(struct nvme_ns_head *head)
394 	__must_hold_shared(&head->srcu)
395 {
396 	struct nvme_ns *ns, *found = NULL;
397 	int node = numa_node_id();
398 	struct nvme_ns *old = srcu_dereference(head->current_path[node],
399 					       &head->srcu);
400 
401 	if (unlikely(!old))
402 		return __nvme_find_path(head, node);
403 
404 	if (list_is_singular(&head->list)) {
405 		if (nvme_path_is_disabled(old))
406 			return NULL;
407 		return old;
408 	}
409 
410 	for (ns = nvme_next_ns(head, old);
411 	     ns && ns != old;
412 	     ns = nvme_next_ns(head, ns)) {
413 		if (nvme_path_is_disabled(ns))
414 			continue;
415 
416 		if (ns->ana_state == NVME_ANA_OPTIMIZED) {
417 			found = ns;
418 			goto out;
419 		}
420 		if (ns->ana_state == NVME_ANA_NONOPTIMIZED)
421 			found = ns;
422 	}
423 
424 	/*
425 	 * The loop above skips the current path for round-robin semantics.
426 	 * Fall back to the current path if either:
427 	 *  - no other optimized path found and current is optimized,
428 	 *  - no other usable path found and current is usable.
429 	 */
430 	if (!nvme_path_is_disabled(old) &&
431 	    (old->ana_state == NVME_ANA_OPTIMIZED ||
432 	     (!found && old->ana_state == NVME_ANA_NONOPTIMIZED)))
433 		return old;
434 
435 	if (!found)
436 		return NULL;
437 out:
438 	rcu_assign_pointer(head->current_path[node], found);
439 	return found;
440 }
441 
442 static struct nvme_ns *nvme_queue_depth_path(struct nvme_ns_head *head)
443 	__must_hold_shared(&head->srcu)
444 {
445 	struct nvme_ns *best_opt = NULL, *best_nonopt = NULL, *ns;
446 	unsigned int min_depth_opt = UINT_MAX, min_depth_nonopt = UINT_MAX;
447 	unsigned int depth;
448 
449 	list_for_each_entry_srcu(ns, &head->list, siblings,
450 				 srcu_read_lock_held(&head->srcu)) {
451 		if (nvme_path_is_disabled(ns))
452 			continue;
453 
454 		depth = atomic_read(&ns->ctrl->nr_active);
455 
456 		switch (ns->ana_state) {
457 		case NVME_ANA_OPTIMIZED:
458 			if (depth < min_depth_opt) {
459 				min_depth_opt = depth;
460 				best_opt = ns;
461 			}
462 			break;
463 		case NVME_ANA_NONOPTIMIZED:
464 			if (depth < min_depth_nonopt) {
465 				min_depth_nonopt = depth;
466 				best_nonopt = ns;
467 			}
468 			break;
469 		default:
470 			break;
471 		}
472 
473 		if (min_depth_opt == 0)
474 			return best_opt;
475 	}
476 
477 	return best_opt ? best_opt : best_nonopt;
478 }
479 
480 static inline bool nvme_path_is_optimized(struct nvme_ns *ns)
481 {
482 	return nvme_ctrl_state(ns->ctrl) == NVME_CTRL_LIVE &&
483 		ns->ana_state == NVME_ANA_OPTIMIZED;
484 }
485 
486 static struct nvme_ns *nvme_numa_path(struct nvme_ns_head *head)
487 	__must_hold_shared(&head->srcu)
488 {
489 	int node = numa_node_id();
490 	struct nvme_ns *ns;
491 
492 	ns = srcu_dereference(head->current_path[node], &head->srcu);
493 	if (unlikely(!ns))
494 		return __nvme_find_path(head, node);
495 	if (unlikely(!nvme_path_is_optimized(ns)))
496 		return __nvme_find_path(head, node);
497 	return ns;
498 }
499 
500 inline struct nvme_ns *nvme_find_path(struct nvme_ns_head *head)
501 {
502 	switch (READ_ONCE(head->subsys->iopolicy)) {
503 	case NVME_IOPOLICY_QD:
504 		return nvme_queue_depth_path(head);
505 	case NVME_IOPOLICY_RR:
506 		return nvme_round_robin_path(head);
507 	default:
508 		return nvme_numa_path(head);
509 	}
510 }
511 
512 static inline bool nvme_state_is_live(enum nvme_ana_state state)
513 {
514 	return state == NVME_ANA_OPTIMIZED || state == NVME_ANA_NONOPTIMIZED;
515 }
516 
517 static bool nvme_available_path(struct nvme_ns_head *head)
518 	__must_hold_shared(&head->srcu)
519 {
520 	bool fail_on_ctrl_loss = test_bit(NVME_NSHEAD_FAIL_ON_CTRL_LOSS,
521 					&head->flags);
522 	bool failfast = false;
523 	struct nvme_ns *ns;
524 
525 	if (!test_bit(NVME_NSHEAD_DISK_LIVE, &head->flags))
526 		return false;
527 
528 	list_for_each_entry_srcu(ns, &head->list, siblings,
529 				 srcu_read_lock_held(&head->srcu)) {
530 		if (test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ns->ctrl->flags)) {
531 			failfast = true;
532 			continue;
533 		}
534 		switch (nvme_ctrl_state(ns->ctrl)) {
535 		case NVME_CTRL_LIVE:
536 			if (!nvme_state_is_live(ns->ana_state) &&
537 			    ns->ana_state != NVME_ANA_CHANGE)
538 				continue;
539 			return true;
540 		case NVME_CTRL_RESETTING:
541 			return true;
542 		case NVME_CTRL_CONNECTING:
543 			if (!fail_on_ctrl_loss)
544 				return true;
545 			continue;
546 		default:
547 			break;
548 		}
549 	}
550 
551 	if (failfast || fail_on_ctrl_loss)
552 		return false;
553 
554 	/*
555 	 * If "head->delayed_removal_secs" is configured (i.e., non-zero), do
556 	 * not immediately fail I/O. Instead, requeue the I/O for the configured
557 	 * duration, anticipating that if there's a transient link failure then
558 	 * it may recover within this time window. This parameter is exported to
559 	 * userspace via sysfs, and its default value is zero. It is internally
560 	 * mapped to NVME_NSHEAD_QUEUE_IF_NO_PATH. When delayed_removal_secs is
561 	 * non-zero, this flag is set to true. When zero, the flag is cleared.
562 	 */
563 	return nvme_mpath_queue_if_no_path(head);
564 }
565 
566 static void nvme_ns_head_submit_bio(struct bio *bio)
567 {
568 	struct nvme_ns_head *head = bio->bi_bdev->bd_disk->private_data;
569 	struct device *dev = disk_to_dev(head->disk);
570 	struct nvme_ns *ns;
571 	int srcu_idx;
572 
573 	/*
574 	 * The namespace might be going away and the bio might be moved to a
575 	 * different queue via blk_steal_bios(), so we need to use the bio_split
576 	 * pool from the original queue to allocate the bvecs from.
577 	 */
578 	bio = bio_split_to_limits(bio);
579 	if (!bio)
580 		return;
581 
582 	srcu_idx = srcu_read_lock(&head->srcu);
583 	ns = nvme_find_path(head);
584 	if (likely(ns)) {
585 		bio_set_dev(bio, ns->disk->part0);
586 		/*
587 		 * Use BIO_REMAPPED to skip bio_check_eod() when this bio
588 		 * enters submit_bio_noacct() for the per-path device. The EOD
589 		 * check already passed on the multipath head.
590 		 */
591 		bio_set_flag(bio, BIO_REMAPPED);
592 		bio->bi_opf |= REQ_NVME_MPATH;
593 		trace_block_bio_remap(bio, disk_devt(ns->head->disk),
594 				      bio->bi_iter.bi_sector);
595 		submit_bio_noacct(bio);
596 	} else if (nvme_available_path(head)) {
597 		dev_warn_ratelimited(dev, "no usable path - requeuing I/O\n");
598 
599 		spin_lock_irq(&head->requeue_lock);
600 		bio_list_add(&head->requeue_list, bio);
601 		spin_unlock_irq(&head->requeue_lock);
602 		atomic_long_inc(&head->io_requeue_no_usable_path_count);
603 	} else {
604 		dev_warn_ratelimited(dev, "no available path - failing I/O\n");
605 
606 		bio_io_error(bio);
607 		atomic_long_inc(&head->io_fail_no_available_path_count);
608 	}
609 
610 	srcu_read_unlock(&head->srcu, srcu_idx);
611 }
612 
613 static int nvme_ns_head_open(struct gendisk *disk, blk_mode_t mode)
614 {
615 	if (!nvme_tryget_ns_head(disk->private_data))
616 		return -ENXIO;
617 	return 0;
618 }
619 
620 static void nvme_ns_head_release(struct gendisk *disk)
621 {
622 	nvme_put_ns_head(disk->private_data);
623 }
624 
625 static int nvme_ns_head_get_unique_id(struct gendisk *disk, u8 id[16],
626 		enum blk_unique_id type)
627 {
628 	struct nvme_ns_head *head = disk->private_data;
629 	struct nvme_ns *ns;
630 	int srcu_idx, ret = -EWOULDBLOCK;
631 
632 	srcu_idx = srcu_read_lock(&head->srcu);
633 	ns = nvme_find_path(head);
634 	if (ns)
635 		ret = nvme_ns_get_unique_id(ns, id, type);
636 	srcu_read_unlock(&head->srcu, srcu_idx);
637 	return ret;
638 }
639 
640 #ifdef CONFIG_BLK_DEV_ZONED
641 static int nvme_ns_head_report_zones(struct gendisk *disk, sector_t sector,
642 		unsigned int nr_zones, struct blk_report_zones_args *args)
643 {
644 	struct nvme_ns_head *head = disk->private_data;
645 	struct nvme_ns *ns;
646 	int srcu_idx, ret = -EWOULDBLOCK;
647 
648 	srcu_idx = srcu_read_lock(&head->srcu);
649 	ns = nvme_find_path(head);
650 	if (ns)
651 		ret = nvme_ns_report_zones(ns, sector, nr_zones, args);
652 	srcu_read_unlock(&head->srcu, srcu_idx);
653 	return ret;
654 }
655 #else
656 #define nvme_ns_head_report_zones	NULL
657 #endif /* CONFIG_BLK_DEV_ZONED */
658 
659 const struct block_device_operations nvme_ns_head_ops = {
660 	.owner		= THIS_MODULE,
661 	.submit_bio	= nvme_ns_head_submit_bio,
662 	.open		= nvme_ns_head_open,
663 	.release	= nvme_ns_head_release,
664 	.ioctl		= nvme_ns_head_ioctl,
665 	.compat_ioctl	= blkdev_compat_ptr_ioctl,
666 	.getgeo		= nvme_getgeo,
667 	.get_unique_id	= nvme_ns_head_get_unique_id,
668 	.report_zones	= nvme_ns_head_report_zones,
669 	.pr_ops		= &nvme_pr_ops,
670 };
671 
672 static const struct file_operations nvme_ns_head_chr_fops = {
673 	.owner		= THIS_MODULE,
674 	.unlocked_ioctl	= nvme_ns_head_chr_ioctl,
675 	.compat_ioctl	= compat_ptr_ioctl,
676 	.uring_cmd	= nvme_ns_head_chr_uring_cmd,
677 	.uring_cmd_iopoll = nvme_ns_chr_uring_cmd_iopoll,
678 };
679 
680 static void nvme_add_ns_head_cdev(struct nvme_ns_head *head)
681 {
682 	head->cdev_device.parent = &head->subsys->dev;
683 
684 	if (nvme_cdev_add(&head->cdev, &head->cdev_device,
685 			&nvme_ns_head_chr_fops, THIS_MODULE,
686 			head->subsys->instance, head->instance)) {
687 		dev_err(disk_to_dev(head->disk),
688 			"Unable to create the ng%dn%d device\n",
689 			head->subsys->instance, head->instance);
690 		return;
691 	}
692 	set_bit(NVME_NSHEAD_CDEV_LIVE, &head->flags);
693 }
694 
695 static void nvme_partition_scan_work(struct work_struct *work)
696 {
697 	struct nvme_ns_head *head =
698 		container_of(work, struct nvme_ns_head, partition_scan_work);
699 
700 	if (WARN_ON_ONCE(!test_and_clear_bit(GD_SUPPRESS_PART_SCAN,
701 					     &head->disk->state)))
702 		return;
703 
704 	mutex_lock(&head->disk->open_mutex);
705 	bdev_disk_changed(head->disk, false);
706 	mutex_unlock(&head->disk->open_mutex);
707 }
708 
709 static void nvme_requeue_work(struct work_struct *work)
710 {
711 	struct nvme_ns_head *head =
712 		container_of(work, struct nvme_ns_head, requeue_work);
713 	struct bio *bio, *next;
714 
715 	spin_lock_irq(&head->requeue_lock);
716 	next = bio_list_get(&head->requeue_list);
717 	spin_unlock_irq(&head->requeue_lock);
718 
719 	while ((bio = next) != NULL) {
720 		next = bio->bi_next;
721 		bio->bi_next = NULL;
722 
723 		submit_bio_noacct(bio);
724 	}
725 }
726 
727 static void nvme_remove_head(struct nvme_ns_head *head)
728 {
729 	if (test_and_clear_bit(NVME_NSHEAD_DISK_LIVE, &head->flags)) {
730 		/*
731 		 * Requeue I/O after NVME_NSHEAD_DISK_LIVE has been cleared
732 		 * to allow multipath to fail all I/O. First synchronize to
733 		 * add any bios to the requeue list.
734 		 */
735 		synchronize_srcu(&head->srcu);
736 		kblockd_schedule_work(&head->requeue_work);
737 
738 		if (test_and_clear_bit(NVME_NSHEAD_CDEV_LIVE, &head->flags))
739 			nvme_cdev_del(&head->cdev, &head->cdev_device);
740 		del_gendisk(head->disk);
741 	}
742 	nvme_put_ns_head(head);
743 }
744 
745 static void nvme_remove_head_work(struct work_struct *work)
746 {
747 	struct nvme_ns_head *head = container_of(to_delayed_work(work),
748 			struct nvme_ns_head, remove_work);
749 	bool remove = false;
750 
751 	mutex_lock(&head->subsys->lock);
752 	if (list_empty(&head->list)) {
753 		list_del_init(&head->entry);
754 		remove = true;
755 	}
756 	mutex_unlock(&head->subsys->lock);
757 	if (remove)
758 		nvme_remove_head(head);
759 
760 	module_put(THIS_MODULE);
761 }
762 
763 int nvme_mpath_alloc_disk(struct nvme_ctrl *ctrl, struct nvme_ns_head *head)
764 {
765 	struct queue_limits lim;
766 
767 	mutex_init(&head->lock);
768 	spin_lock_init(&head->requeue_lock);
769 	INIT_WORK(&head->requeue_work, nvme_requeue_work);
770 	INIT_WORK(&head->partition_scan_work, nvme_partition_scan_work);
771 	INIT_DELAYED_WORK(&head->remove_work, nvme_remove_head_work);
772 
773 	/*
774 	 * If "multipath_always_on" is enabled, a multipath node is added
775 	 * regardless of whether the disk is single/multi ported, and whether
776 	 * the namespace is shared or private. If "multipath_always_on" is not
777 	 * enabled, a multipath node is added only if the subsystem supports
778 	 * multiple controllers and the "multipath" option is configured. In
779 	 * either case, for private namespaces, we ensure that the NSID is
780 	 * unique.
781 	 */
782 	if (!multipath_always_on) {
783 		if (!(ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
784 				!multipath)
785 			return 0;
786 	}
787 
788 	if (!nvme_is_unique_nsid(ctrl, head))
789 		return 0;
790 
791 	blk_set_stacking_limits(&lim);
792 	lim.dma_alignment = 3;
793 	lim.features |= BLK_FEAT_IO_STAT | BLK_FEAT_NOWAIT |
794 		BLK_FEAT_POLL | BLK_FEAT_ATOMIC_WRITES | BLK_FEAT_PCI_P2PDMA;
795 
796 	head->disk = blk_alloc_disk(&lim, ctrl->numa_node);
797 	if (IS_ERR(head->disk))
798 		return PTR_ERR(head->disk);
799 	head->disk->fops = &nvme_ns_head_ops;
800 	head->disk->private_data = head;
801 
802 	/*
803 	 * We need to suppress the partition scan from occuring within the
804 	 * controller's scan_work context. If a path error occurs here, the IO
805 	 * will wait until a path becomes available or all paths are torn down,
806 	 * but that action also occurs within scan_work, so it would deadlock.
807 	 * Defer the partition scan to a different context that does not block
808 	 * scan_work.
809 	 */
810 	set_bit(GD_SUPPRESS_PART_SCAN, &head->disk->state);
811 	sprintf(head->disk->disk_name, "nvme%dn%d",
812 			ctrl->subsys->instance, head->instance);
813 	nvme_get_ns_head(head);
814 	return 0;
815 }
816 
817 static void nvme_mpath_set_live(struct nvme_ns *ns)
818 {
819 	struct nvme_ns_head *head = ns->head;
820 	int rc;
821 
822 	if (!head->disk)
823 		return;
824 
825 	/*
826 	 * test_and_set_bit() is used because it is protecting against two nvme
827 	 * paths simultaneously calling device_add_disk() on the same namespace
828 	 * head.
829 	 */
830 	if (!test_and_set_bit(NVME_NSHEAD_DISK_LIVE, &head->flags)) {
831 		rc = device_add_disk(&head->subsys->dev, head->disk,
832 				     nvme_ns_attr_groups);
833 		if (rc) {
834 			clear_bit(NVME_NSHEAD_DISK_LIVE, &head->flags);
835 			return;
836 		}
837 		nvme_add_ns_head_cdev(head);
838 		queue_work(nvme_wq, &head->partition_scan_work);
839 	}
840 
841 	nvme_mpath_add_sysfs_link(ns->head);
842 
843 	mutex_lock(&head->lock);
844 	if (nvme_path_is_optimized(ns)) {
845 		int node, srcu_idx;
846 
847 		srcu_idx = srcu_read_lock(&head->srcu);
848 		for_each_online_node(node)
849 			__nvme_find_path(head, node);
850 		srcu_read_unlock(&head->srcu, srcu_idx);
851 	}
852 	mutex_unlock(&head->lock);
853 
854 	synchronize_srcu(&head->srcu);
855 	nvme_mpath_revalidate_zones(head);
856 	kblockd_schedule_work(&head->requeue_work);
857 }
858 
859 static int nvme_parse_ana_log(struct nvme_ctrl *ctrl, void *data,
860 		int (*cb)(struct nvme_ctrl *ctrl, struct nvme_ana_group_desc *,
861 			void *))
862 		__must_hold(&ctrl->ana_lock)
863 {
864 	void *base = ctrl->ana_log_buf;
865 	size_t offset = sizeof(struct nvme_ana_rsp_hdr);
866 	int error, i;
867 
868 	lockdep_assert_held(&ctrl->ana_lock);
869 
870 	for (i = 0; i < le16_to_cpu(ctrl->ana_log_buf->ngrps); i++) {
871 		struct nvme_ana_group_desc *desc = base + offset;
872 		u32 nr_nsids;
873 		size_t nsid_buf_size;
874 
875 		if (WARN_ON_ONCE(offset > ctrl->ana_log_size ||
876 				 sizeof(*desc) > ctrl->ana_log_size - offset))
877 			return -EINVAL;
878 
879 		nr_nsids = le32_to_cpu(desc->nnsids);
880 		nsid_buf_size = flex_array_size(desc, nsids, nr_nsids);
881 
882 		if (WARN_ON_ONCE(desc->grpid == 0))
883 			return -EINVAL;
884 		if (WARN_ON_ONCE(le32_to_cpu(desc->grpid) > ctrl->anagrpmax))
885 			return -EINVAL;
886 		if (WARN_ON_ONCE(desc->state == 0))
887 			return -EINVAL;
888 		if (WARN_ON_ONCE(desc->state > NVME_ANA_CHANGE))
889 			return -EINVAL;
890 
891 		offset += sizeof(*desc);
892 		if (WARN_ON_ONCE(nsid_buf_size > ctrl->ana_log_size - offset))
893 			return -EINVAL;
894 
895 		error = cb(ctrl, desc, data);
896 		if (error)
897 			return error;
898 
899 		offset += nsid_buf_size;
900 	}
901 
902 	return 0;
903 }
904 
905 static void nvme_update_ns_ana_state(struct nvme_ana_group_desc *desc,
906 		struct nvme_ns *ns)
907 {
908 	ns->ana_grpid = le32_to_cpu(desc->grpid);
909 	ns->ana_state = desc->state;
910 	clear_bit(NVME_NS_ANA_PENDING, &ns->flags);
911 	/*
912 	 * nvme_mpath_set_live() will trigger I/O to the multipath path device
913 	 * and in turn to this path device.  However we cannot accept this I/O
914 	 * if the controller is not live.  This may deadlock if called from
915 	 * nvme_mpath_init_identify() and the ctrl will never complete
916 	 * initialization, preventing I/O from completing.  For this case we
917 	 * will reprocess the ANA log page in nvme_mpath_update() once the
918 	 * controller is ready.
919 	 */
920 	if (nvme_state_is_live(ns->ana_state) &&
921 	    nvme_ctrl_state(ns->ctrl) == NVME_CTRL_LIVE)
922 		nvme_mpath_set_live(ns);
923 	else {
924 		/*
925 		 * Add sysfs link from multipath head gendisk node to path
926 		 * device gendisk node.
927 		 * If path's ana state is live (i.e. state is either optimized
928 		 * or non-optimized) while we alloc the ns then sysfs link would
929 		 * be created from nvme_mpath_set_live(). In that case we would
930 		 * not fallthrough this code path. However for the path's ana
931 		 * state other than live, we call nvme_mpath_set_live() only
932 		 * after ana state transitioned to the live state. But we still
933 		 * want to create the sysfs link from head node to a path device
934 		 * irrespctive of the path's ana state.
935 		 * If we reach through here then it means that path's ana state
936 		 * is not live but still create the sysfs link to this path from
937 		 * head node if head node of the path has already come alive.
938 		 */
939 		if (test_bit(NVME_NSHEAD_DISK_LIVE, &ns->head->flags)) {
940 			nvme_mpath_add_sysfs_link(ns->head);
941 			kblockd_schedule_work(&ns->head->requeue_work);
942 		}
943 	}
944 }
945 
946 static int nvme_update_ana_state(struct nvme_ctrl *ctrl,
947 		struct nvme_ana_group_desc *desc, void *data)
948 {
949 	u32 nr_nsids = le32_to_cpu(desc->nnsids), n = 0;
950 	unsigned *nr_change_groups = data;
951 	struct nvme_ns *ns;
952 	int srcu_idx;
953 
954 	dev_dbg(ctrl->device, "ANA group %d: %s.\n",
955 			le32_to_cpu(desc->grpid),
956 			nvme_ana_state_names[desc->state]);
957 
958 	if (desc->state == NVME_ANA_CHANGE)
959 		(*nr_change_groups)++;
960 
961 	if (!nr_nsids)
962 		return 0;
963 
964 	srcu_idx = srcu_read_lock(&ctrl->srcu);
965 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
966 				 srcu_read_lock_held(&ctrl->srcu)) {
967 		unsigned nsid;
968 again:
969 		nsid = le32_to_cpu(desc->nsids[n]);
970 		if (ns->head->ns_id < nsid)
971 			continue;
972 		if (ns->head->ns_id == nsid)
973 			nvme_update_ns_ana_state(desc, ns);
974 		if (++n == nr_nsids)
975 			break;
976 		if (ns->head->ns_id > nsid)
977 			goto again;
978 	}
979 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
980 	return 0;
981 }
982 
983 static int nvme_read_ana_log(struct nvme_ctrl *ctrl)
984 {
985 	u32 nr_change_groups = 0;
986 	int error;
987 
988 	mutex_lock(&ctrl->ana_lock);
989 	error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_ANA, 0, NVME_CSI_NVM,
990 			ctrl->ana_log_buf, ctrl->ana_log_size, 0);
991 	if (error) {
992 		dev_warn(ctrl->device, "Failed to get ANA log: %d\n", error);
993 		goto out_unlock;
994 	}
995 
996 	error = nvme_parse_ana_log(ctrl, &nr_change_groups,
997 			nvme_update_ana_state);
998 	if (error)
999 		goto out_unlock;
1000 
1001 	/*
1002 	 * In theory we should have an ANATT timer per group as they might enter
1003 	 * the change state at different times.  But that is a lot of overhead
1004 	 * just to protect against a target that keeps entering new changes
1005 	 * states while never finishing previous ones.  But we'll still
1006 	 * eventually time out once all groups are in change state, so this
1007 	 * isn't a big deal.
1008 	 *
1009 	 * We also double the ANATT value to provide some slack for transports
1010 	 * or AEN processing overhead.
1011 	 */
1012 	if (nr_change_groups)
1013 		mod_timer(&ctrl->anatt_timer, ctrl->anatt * HZ * 2 + jiffies);
1014 	else
1015 		timer_delete_sync(&ctrl->anatt_timer);
1016 out_unlock:
1017 	mutex_unlock(&ctrl->ana_lock);
1018 	return error;
1019 }
1020 
1021 static void nvme_ana_work(struct work_struct *work)
1022 {
1023 	struct nvme_ctrl *ctrl = container_of(work, struct nvme_ctrl, ana_work);
1024 
1025 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE)
1026 		return;
1027 
1028 	nvme_read_ana_log(ctrl);
1029 }
1030 
1031 void nvme_mpath_update(struct nvme_ctrl *ctrl)
1032 {
1033 	u32 nr_change_groups = 0;
1034 
1035 	if (!ctrl->ana_log_buf)
1036 		return;
1037 
1038 	mutex_lock(&ctrl->ana_lock);
1039 	nvme_parse_ana_log(ctrl, &nr_change_groups, nvme_update_ana_state);
1040 	mutex_unlock(&ctrl->ana_lock);
1041 }
1042 
1043 static void nvme_anatt_timeout(struct timer_list *t)
1044 {
1045 	struct nvme_ctrl *ctrl = timer_container_of(ctrl, t, anatt_timer);
1046 
1047 	dev_info(ctrl->device, "ANATT timeout, resetting controller.\n");
1048 	nvme_reset_ctrl(ctrl);
1049 }
1050 
1051 void nvme_mpath_stop(struct nvme_ctrl *ctrl)
1052 {
1053 	if (!nvme_ctrl_use_ana(ctrl))
1054 		return;
1055 	timer_delete_sync(&ctrl->anatt_timer);
1056 	cancel_work_sync(&ctrl->ana_work);
1057 }
1058 
1059 #define SUBSYS_ATTR_RW(_name, _mode, _show, _store)  \
1060 	struct device_attribute subsys_attr_##_name =	\
1061 		__ATTR(_name, _mode, _show, _store)
1062 
1063 static ssize_t nvme_subsys_iopolicy_show(struct device *dev,
1064 		struct device_attribute *attr, char *buf)
1065 {
1066 	struct nvme_subsystem *subsys =
1067 		container_of(dev, struct nvme_subsystem, dev);
1068 
1069 	/* A discovery subsystem has no namespaces and hence no I/O paths */
1070 	if (subsys->subtype == NVME_NQN_DISC)
1071 		return sysfs_emit(buf, "none\n");
1072 
1073 	return sysfs_emit(buf, "%s\n",
1074 			  nvme_iopolicy_names[READ_ONCE(subsys->iopolicy)]);
1075 }
1076 
1077 static void nvme_subsys_iopolicy_update(struct nvme_subsystem *subsys,
1078 		int iopolicy)
1079 {
1080 	struct nvme_ctrl *ctrl;
1081 	int old_iopolicy = READ_ONCE(subsys->iopolicy);
1082 
1083 	if (old_iopolicy == iopolicy)
1084 		return;
1085 
1086 	WRITE_ONCE(subsys->iopolicy, iopolicy);
1087 
1088 	/* iopolicy changes clear the mpath by design */
1089 	mutex_lock(&nvme_subsystems_lock);
1090 	list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry)
1091 		nvme_mpath_clear_ctrl_paths(ctrl);
1092 	mutex_unlock(&nvme_subsystems_lock);
1093 
1094 	pr_notice("subsysnqn %s iopolicy changed from %s to %s\n",
1095 			subsys->subnqn,
1096 			nvme_iopolicy_names[old_iopolicy],
1097 			nvme_iopolicy_names[iopolicy]);
1098 }
1099 
1100 static ssize_t nvme_subsys_iopolicy_store(struct device *dev,
1101 		struct device_attribute *attr, const char *buf, size_t count)
1102 {
1103 	struct nvme_subsystem *subsys =
1104 		container_of(dev, struct nvme_subsystem, dev);
1105 	int policy;
1106 
1107 	if (subsys->subtype == NVME_NQN_DISC)
1108 		return -EOPNOTSUPP;
1109 
1110 	policy = nvme_iopolicy_parse(buf);
1111 	if (policy < 0)
1112 		return policy;
1113 
1114 	nvme_subsys_iopolicy_update(subsys, policy);
1115 	return count;
1116 }
1117 SUBSYS_ATTR_RW(iopolicy, S_IRUGO | S_IWUSR,
1118 		      nvme_subsys_iopolicy_show, nvme_subsys_iopolicy_store);
1119 
1120 static ssize_t iopolicies_show(struct device *dev,
1121 			       struct device_attribute *attr, char *buf)
1122 {
1123 	struct nvme_subsystem *subsys =
1124 		container_of(dev, struct nvme_subsystem, dev);
1125 	int i, len = 0;
1126 
1127 	if (subsys->subtype == NVME_NQN_DISC)
1128 		return sysfs_emit(buf, "none\n");
1129 
1130 	for (i = 0; i < ARRAY_SIZE(nvme_iopolicy_names); i++)
1131 		len += sysfs_emit_at(buf, len, "%s%s", i ? " " : "",
1132 				     nvme_iopolicy_names[i]);
1133 
1134 	len += sysfs_emit_at(buf, len, "\n");
1135 	return len;
1136 }
1137 
1138 struct device_attribute subsys_attr_iopolicies = __ATTR_RO(iopolicies);
1139 
1140 static ssize_t ana_grpid_show(struct device *dev, struct device_attribute *attr,
1141 		char *buf)
1142 {
1143 	return sysfs_emit(buf, "%d\n", nvme_get_ns_from_dev(dev)->ana_grpid);
1144 }
1145 DEVICE_ATTR_RO(ana_grpid);
1146 
1147 static ssize_t ana_state_show(struct device *dev, struct device_attribute *attr,
1148 		char *buf)
1149 {
1150 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1151 
1152 	return sysfs_emit(buf, "%s\n", nvme_ana_state_names[ns->ana_state]);
1153 }
1154 DEVICE_ATTR_RO(ana_state);
1155 
1156 static ssize_t queue_depth_show(struct device *dev,
1157 		struct device_attribute *attr, char *buf)
1158 {
1159 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1160 
1161 	if (ns->head->subsys->iopolicy != NVME_IOPOLICY_QD)
1162 		return 0;
1163 
1164 	return sysfs_emit(buf, "%d\n", atomic_read(&ns->ctrl->nr_active));
1165 }
1166 DEVICE_ATTR_RO(queue_depth);
1167 
1168 static const char * const nvme_path_state_names[] = {
1169 	[NVME_PATH_ENABLED]			= "enabled",
1170 	[NVME_PATH_DISABLED_CTRL_DOWN]		= "ctrl-down",
1171 	[NVME_PATH_DISABLED_ANA_PENDING]	= "ana-pending",
1172 	[NVME_PATH_DISABLED_NS_NOT_READY]	= "ns-not-ready",
1173 };
1174 
1175 static ssize_t path_state_show(struct device *dev,
1176 		struct device_attribute *attr, char *buf)
1177 {
1178 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1179 	enum nvme_path_state state = nvme_path_get_state(ns);
1180 	const char *name = "unknown";
1181 
1182 	if (state < ARRAY_SIZE(nvme_path_state_names) &&
1183 	    nvme_path_state_names[state])
1184 		name = nvme_path_state_names[state];
1185 
1186 	return sysfs_emit(buf, "%s\n", name);
1187 }
1188 DEVICE_ATTR_RO(path_state);
1189 
1190 static ssize_t numa_nodes_show(struct device *dev, struct device_attribute *attr,
1191 		char *buf)
1192 {
1193 	int node, srcu_idx;
1194 	nodemask_t numa_nodes;
1195 	struct nvme_ns *current_ns;
1196 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1197 	struct nvme_ns_head *head = ns->head;
1198 
1199 	if (head->subsys->iopolicy != NVME_IOPOLICY_NUMA)
1200 		return 0;
1201 
1202 	nodes_clear(numa_nodes);
1203 
1204 	srcu_idx = srcu_read_lock(&head->srcu);
1205 	for_each_node(node) {
1206 		current_ns = srcu_dereference(head->current_path[node],
1207 				&head->srcu);
1208 		if (ns == current_ns)
1209 			node_set(node, numa_nodes);
1210 	}
1211 	srcu_read_unlock(&head->srcu, srcu_idx);
1212 
1213 	return sysfs_emit(buf, "%*pbl\n", nodemask_pr_args(&numa_nodes));
1214 }
1215 DEVICE_ATTR_RO(numa_nodes);
1216 
1217 static ssize_t delayed_removal_secs_show(struct device *dev,
1218 		struct device_attribute *attr, char *buf)
1219 {
1220 	struct gendisk *disk = dev_to_disk(dev);
1221 	struct nvme_ns_head *head = disk->private_data;
1222 	int ret;
1223 
1224 	mutex_lock(&head->subsys->lock);
1225 	ret = sysfs_emit(buf, "%u\n", head->delayed_removal_secs);
1226 	mutex_unlock(&head->subsys->lock);
1227 	return ret;
1228 }
1229 
1230 static ssize_t delayed_removal_secs_store(struct device *dev,
1231 		struct device_attribute *attr, const char *buf, size_t count)
1232 {
1233 	struct gendisk *disk = dev_to_disk(dev);
1234 	struct nvme_ns_head *head = disk->private_data;
1235 	unsigned int sec;
1236 	int ret;
1237 
1238 	ret = kstrtouint(buf, 0, &sec);
1239 	if (ret < 0)
1240 		return ret;
1241 
1242 	mutex_lock(&head->subsys->lock);
1243 	head->delayed_removal_secs = sec;
1244 	assign_bit(NVME_NSHEAD_QUEUE_IF_NO_PATH, &head->flags, sec);
1245 	mutex_unlock(&head->subsys->lock);
1246 	/*
1247 	 * Ensure that update to NVME_NSHEAD_QUEUE_IF_NO_PATH is seen
1248 	 * by its reader.
1249 	 */
1250 	synchronize_srcu(&head->srcu);
1251 
1252 	return count;
1253 }
1254 
1255 DEVICE_ATTR_RW(delayed_removal_secs);
1256 
1257 static ssize_t fail_on_ctrl_loss_show(struct device *dev,
1258 		struct device_attribute *attr, char *buf)
1259 {
1260 	struct gendisk *disk = dev_to_disk(dev);
1261 	struct nvme_ns_head *head = disk->private_data;
1262 
1263 	return sysfs_emit(buf, test_bit(NVME_NSHEAD_FAIL_ON_CTRL_LOSS,
1264 			&head->flags) ? "on\n" : "off\n");
1265 }
1266 
1267 static ssize_t fail_on_ctrl_loss_store(struct device *dev,
1268 		struct device_attribute *attr, const char *buf, size_t count)
1269 {
1270 	struct gendisk *disk = dev_to_disk(dev);
1271 	struct nvme_ns_head *head = disk->private_data;
1272 	bool enable;
1273 	int ret;
1274 
1275 	ret = kstrtobool(buf, &enable);
1276 	if (ret < 0)
1277 		return ret;
1278 
1279 	if (enable) {
1280 		if (test_and_set_bit(NVME_NSHEAD_FAIL_ON_CTRL_LOSS, &head->flags))
1281 			return count;
1282 	} else {
1283 		if (!test_and_clear_bit(NVME_NSHEAD_FAIL_ON_CTRL_LOSS,
1284 					&head->flags))
1285 			return count;
1286 	}
1287 
1288 	synchronize_srcu(&head->srcu);
1289 
1290 	if (enable)
1291 		kblockd_schedule_work(&head->requeue_work);
1292 
1293 	return count;
1294 }
1295 
1296 DEVICE_ATTR_RW(fail_on_ctrl_loss);
1297 
1298 static ssize_t multipath_failover_count_show(struct device *dev,
1299 		struct device_attribute *attr, char *buf)
1300 {
1301 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1302 
1303 	return sysfs_emit(buf, "%lu\n", atomic_long_read(&ns->failover));
1304 }
1305 
1306 static ssize_t multipath_failover_count_store(struct device *dev,
1307 		struct device_attribute *attr, const char *buf, size_t count)
1308 {
1309 	unsigned long failover;
1310 	int ret;
1311 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1312 
1313 	ret = kstrtoul(buf, 0, &failover);
1314 	if (ret)
1315 		return -EINVAL;
1316 
1317 	atomic_long_set(&ns->failover, failover);
1318 
1319 	return count;
1320 }
1321 
1322 DEVICE_ATTR_RW(multipath_failover_count);
1323 
1324 static ssize_t io_requeue_no_usable_path_count_show(struct device *dev,
1325 		struct device_attribute *attr, char *buf)
1326 {
1327 	struct gendisk *disk = dev_to_disk(dev);
1328 	struct nvme_ns_head *head = disk->private_data;
1329 
1330 	return sysfs_emit(buf, "%lu\n",
1331 		    atomic_long_read(&head->io_requeue_no_usable_path_count));
1332 }
1333 
1334 static ssize_t io_requeue_no_usable_path_count_store(struct device *dev,
1335 		struct device_attribute *attr, const char *buf, size_t count)
1336 {
1337 	int err;
1338 	unsigned long requeue_cnt;
1339 	struct gendisk *disk = dev_to_disk(dev);
1340 	struct nvme_ns_head *head = disk->private_data;
1341 
1342 	err = kstrtoul(buf, 0, &requeue_cnt);
1343 	if (err)
1344 		return -EINVAL;
1345 
1346 	atomic_long_set(&head->io_requeue_no_usable_path_count, requeue_cnt);
1347 
1348 	return count;
1349 }
1350 
1351 DEVICE_ATTR_RW(io_requeue_no_usable_path_count);
1352 
1353 static ssize_t io_fail_no_available_path_count_show(struct device *dev,
1354 		struct device_attribute *attr, char *buf)
1355 {
1356 	struct gendisk *disk = dev_to_disk(dev);
1357 	struct nvme_ns_head *head = disk->private_data;
1358 
1359 	return sysfs_emit(buf, "%lu\n",
1360 		    atomic_long_read(&head->io_fail_no_available_path_count));
1361 }
1362 
1363 static ssize_t io_fail_no_available_path_count_store(struct device *dev,
1364 		struct device_attribute *attr, const char *buf, size_t count)
1365 {
1366 	int err;
1367 	unsigned long fail_cnt;
1368 	struct gendisk *disk = dev_to_disk(dev);
1369 	struct nvme_ns_head *head = disk->private_data;
1370 
1371 	err = kstrtoul(buf, 0, &fail_cnt);
1372 	if (err)
1373 		return -EINVAL;
1374 
1375 	atomic_long_set(&head->io_fail_no_available_path_count, fail_cnt);
1376 
1377 	return count;
1378 }
1379 
1380 DEVICE_ATTR_RW(io_fail_no_available_path_count);
1381 
1382 static int nvme_lookup_ana_group_desc(struct nvme_ctrl *ctrl,
1383 		struct nvme_ana_group_desc *desc, void *data)
1384 {
1385 	struct nvme_ana_group_desc *dst = data;
1386 
1387 	if (desc->grpid != dst->grpid)
1388 		return 0;
1389 
1390 	*dst = *desc;
1391 	return -ENXIO; /* just break out of the loop */
1392 }
1393 
1394 void nvme_mpath_add_sysfs_link(struct nvme_ns_head *head)
1395 {
1396 	struct device *target;
1397 	int rc, srcu_idx;
1398 	struct nvme_ns *ns;
1399 	struct kobject *kobj;
1400 
1401 	/*
1402 	 * Ensure head disk node is already added otherwise we may get invalid
1403 	 * kobj for head disk node
1404 	 */
1405 	if (!test_bit(GD_ADDED, &head->disk->state))
1406 		return;
1407 
1408 	kobj = &disk_to_dev(head->disk)->kobj;
1409 
1410 	/*
1411 	 * loop through each ns chained through the head->list and create the
1412 	 * sysfs link from head node to the ns path node
1413 	 */
1414 	srcu_idx = srcu_read_lock(&head->srcu);
1415 
1416 	list_for_each_entry_srcu(ns, &head->list, siblings,
1417 				 srcu_read_lock_held(&head->srcu)) {
1418 		/*
1419 		 * Ensure that ns path disk node is already added otherwise we
1420 		 * may get invalid kobj name for target
1421 		 */
1422 		if (!test_bit(GD_ADDED, &ns->disk->state))
1423 			continue;
1424 
1425 		/*
1426 		 * Avoid creating link if it already exists for the given path.
1427 		 * When path ana state transitions from optimized to non-
1428 		 * optimized or vice-versa, the nvme_mpath_set_live() is
1429 		 * invoked which in truns call this function. Now if the sysfs
1430 		 * link already exists for the given path and we attempt to re-
1431 		 * create the link then sysfs code would warn about it loudly.
1432 		 * So we evaluate NVME_NS_SYSFS_ATTR_LINK flag here to ensure
1433 		 * that we're not creating duplicate link.
1434 		 * The test_and_set_bit() is used because it is protecting
1435 		 * against multiple nvme paths being simultaneously added.
1436 		 */
1437 		if (test_and_set_bit(NVME_NS_SYSFS_ATTR_LINK, &ns->flags))
1438 			continue;
1439 
1440 		target = disk_to_dev(ns->disk);
1441 		/*
1442 		 * Create sysfs link from head gendisk kobject @kobj to the
1443 		 * ns path gendisk kobject @target->kobj.
1444 		 */
1445 		rc = sysfs_add_link_to_group(kobj, nvme_ns_mpath_attr_group.name,
1446 				&target->kobj, dev_name(target));
1447 		if (unlikely(rc)) {
1448 			dev_err(disk_to_dev(ns->head->disk),
1449 					"failed to create link to %s\n",
1450 					dev_name(target));
1451 			clear_bit(NVME_NS_SYSFS_ATTR_LINK, &ns->flags);
1452 		}
1453 	}
1454 
1455 	srcu_read_unlock(&head->srcu, srcu_idx);
1456 }
1457 
1458 void nvme_mpath_remove_sysfs_link(struct nvme_ns *ns)
1459 {
1460 	struct device *target;
1461 	struct kobject *kobj;
1462 
1463 	if (!test_bit(NVME_NS_SYSFS_ATTR_LINK, &ns->flags))
1464 		return;
1465 
1466 	target = disk_to_dev(ns->disk);
1467 	kobj = &disk_to_dev(ns->head->disk)->kobj;
1468 	sysfs_remove_link_from_group(kobj, nvme_ns_mpath_attr_group.name,
1469 			dev_name(target));
1470 	clear_bit(NVME_NS_SYSFS_ATTR_LINK, &ns->flags);
1471 }
1472 
1473 void nvme_mpath_add_disk(struct nvme_ns *ns, __le32 anagrpid)
1474 {
1475 	if (nvme_ctrl_use_ana(ns->ctrl)) {
1476 		struct nvme_ana_group_desc desc = {
1477 			.grpid = anagrpid,
1478 			.state = 0,
1479 		};
1480 
1481 		mutex_lock(&ns->ctrl->ana_lock);
1482 		ns->ana_grpid = le32_to_cpu(anagrpid);
1483 		nvme_parse_ana_log(ns->ctrl, &desc, nvme_lookup_ana_group_desc);
1484 		mutex_unlock(&ns->ctrl->ana_lock);
1485 		if (desc.state) {
1486 			/* found the group desc: update */
1487 			nvme_update_ns_ana_state(&desc, ns);
1488 		} else {
1489 			/* group desc not found: trigger a re-read */
1490 			set_bit(NVME_NS_ANA_PENDING, &ns->flags);
1491 			queue_work(nvme_wq, &ns->ctrl->ana_work);
1492 		}
1493 	} else {
1494 		ns->ana_state = NVME_ANA_OPTIMIZED;
1495 		nvme_mpath_set_live(ns);
1496 	}
1497 
1498 }
1499 
1500 void nvme_mpath_remove_disk(struct nvme_ns_head *head)
1501 {
1502 	bool remove = false;
1503 
1504 	if (!head->disk)
1505 		return;
1506 
1507 	mutex_lock(&head->subsys->lock);
1508 	/*
1509 	 * We are called when all paths have been removed, and at that point
1510 	 * head->list is expected to be empty. However, nvme_ns_remove() and
1511 	 * nvme_init_ns_head() can run concurrently and so if head->delayed_
1512 	 * removal_secs is configured, it is possible that by the time we reach
1513 	 * this point, head->list may no longer be empty. Therefore, we recheck
1514 	 * head->list here. If it is no longer empty then we skip enqueuing the
1515 	 * delayed head removal work.
1516 	 */
1517 	if (!list_empty(&head->list))
1518 		goto out;
1519 
1520 	/*
1521 	 * Ensure that no one could remove this module while the head
1522 	 * remove work is pending.
1523 	 */
1524 	if (head->delayed_removal_secs && try_module_get(THIS_MODULE)) {
1525 		mod_delayed_work(nvme_wq, &head->remove_work,
1526 				head->delayed_removal_secs * HZ);
1527 	} else {
1528 		list_del_init(&head->entry);
1529 		remove = true;
1530 	}
1531 out:
1532 	mutex_unlock(&head->subsys->lock);
1533 	if (remove)
1534 		nvme_remove_head(head);
1535 }
1536 
1537 void nvme_mpath_put_disk(struct nvme_ns_head *head)
1538 {
1539 	if (!head->disk)
1540 		return;
1541 	/* make sure all pending bios are cleaned up */
1542 	kblockd_schedule_work(&head->requeue_work);
1543 	flush_work(&head->requeue_work);
1544 	flush_work(&head->partition_scan_work);
1545 	put_disk(head->disk);
1546 }
1547 
1548 void nvme_mpath_init_ctrl(struct nvme_ctrl *ctrl)
1549 {
1550 	mutex_init(&ctrl->ana_lock);
1551 	timer_setup(&ctrl->anatt_timer, nvme_anatt_timeout, 0);
1552 	INIT_WORK(&ctrl->ana_work, nvme_ana_work);
1553 }
1554 
1555 int nvme_mpath_init_identify(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1556 {
1557 	size_t max_transfer_size = ctrl->max_hw_sectors << SECTOR_SHIFT;
1558 	size_t ana_log_size;
1559 	int error = 0;
1560 
1561 	/* check if multipath is enabled and we have the capability */
1562 	if (!multipath || !ctrl->subsys ||
1563 	    !(ctrl->subsys->cmic & NVME_CTRL_CMIC_ANA))
1564 		return 0;
1565 
1566 	/* initialize this in the identify path to cover controller resets */
1567 	atomic_set(&ctrl->nr_active, 0);
1568 
1569 	if (!ctrl->max_namespaces ||
1570 	    ctrl->max_namespaces > le32_to_cpu(id->nn)) {
1571 		dev_err(ctrl->device,
1572 			"Invalid MNAN value %u\n", ctrl->max_namespaces);
1573 		return -EINVAL;
1574 	}
1575 
1576 	ctrl->anacap = id->anacap;
1577 	ctrl->anatt = id->anatt;
1578 	ctrl->nanagrpid = le32_to_cpu(id->nanagrpid);
1579 	ctrl->anagrpmax = le32_to_cpu(id->anagrpmax);
1580 
1581 	ana_log_size = sizeof(struct nvme_ana_rsp_hdr) +
1582 		ctrl->nanagrpid * sizeof(struct nvme_ana_group_desc) +
1583 		ctrl->max_namespaces * sizeof(__le32);
1584 	if (ana_log_size > max_transfer_size) {
1585 		dev_err(ctrl->device,
1586 			"ANA log page size (%zd) larger than MDTS (%zd).\n",
1587 			ana_log_size, max_transfer_size);
1588 		dev_err(ctrl->device, "disabling ANA support.\n");
1589 		goto out_uninit;
1590 	}
1591 	if (ana_log_size > ctrl->ana_log_size) {
1592 		nvme_mpath_stop(ctrl);
1593 		nvme_mpath_uninit(ctrl);
1594 		ctrl->ana_log_buf = kvmalloc(ana_log_size, GFP_KERNEL);
1595 		if (!ctrl->ana_log_buf)
1596 			return -ENOMEM;
1597 	}
1598 	ctrl->ana_log_size = ana_log_size;
1599 	error = nvme_read_ana_log(ctrl);
1600 	if (error)
1601 		goto out_uninit;
1602 	return 0;
1603 
1604 out_uninit:
1605 	nvme_mpath_uninit(ctrl);
1606 	return error;
1607 }
1608 
1609 void nvme_mpath_uninit(struct nvme_ctrl *ctrl)
1610 {
1611 	kvfree(ctrl->ana_log_buf);
1612 	ctrl->ana_log_buf = NULL;
1613 	ctrl->ana_log_size = 0;
1614 }
1615