xref: /openbmc/linux/drivers/nvme/host/multipath.c (revision aaa746ad)
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 module_param(multipath, bool, 0444);
14 MODULE_PARM_DESC(multipath,
15 	"turn on native support for multiple controllers per subsystem");
16 
17 static const char *nvme_iopolicy_names[] = {
18 	[NVME_IOPOLICY_NUMA]	= "numa",
19 	[NVME_IOPOLICY_RR]	= "round-robin",
20 };
21 
22 static int iopolicy = NVME_IOPOLICY_NUMA;
23 
24 static int nvme_set_iopolicy(const char *val, const struct kernel_param *kp)
25 {
26 	if (!val)
27 		return -EINVAL;
28 	if (!strncmp(val, "numa", 4))
29 		iopolicy = NVME_IOPOLICY_NUMA;
30 	else if (!strncmp(val, "round-robin", 11))
31 		iopolicy = NVME_IOPOLICY_RR;
32 	else
33 		return -EINVAL;
34 
35 	return 0;
36 }
37 
38 static int nvme_get_iopolicy(char *buf, const struct kernel_param *kp)
39 {
40 	return sprintf(buf, "%s\n", nvme_iopolicy_names[iopolicy]);
41 }
42 
43 module_param_call(iopolicy, nvme_set_iopolicy, nvme_get_iopolicy,
44 	&iopolicy, 0644);
45 MODULE_PARM_DESC(iopolicy,
46 	"Default multipath I/O policy; 'numa' (default) or 'round-robin'");
47 
48 void nvme_mpath_default_iopolicy(struct nvme_subsystem *subsys)
49 {
50 	subsys->iopolicy = iopolicy;
51 }
52 
53 void nvme_mpath_unfreeze(struct nvme_subsystem *subsys)
54 {
55 	struct nvme_ns_head *h;
56 
57 	lockdep_assert_held(&subsys->lock);
58 	list_for_each_entry(h, &subsys->nsheads, entry)
59 		if (h->disk)
60 			blk_mq_unfreeze_queue(h->disk->queue);
61 }
62 
63 void nvme_mpath_wait_freeze(struct nvme_subsystem *subsys)
64 {
65 	struct nvme_ns_head *h;
66 
67 	lockdep_assert_held(&subsys->lock);
68 	list_for_each_entry(h, &subsys->nsheads, entry)
69 		if (h->disk)
70 			blk_mq_freeze_queue_wait(h->disk->queue);
71 }
72 
73 void nvme_mpath_start_freeze(struct nvme_subsystem *subsys)
74 {
75 	struct nvme_ns_head *h;
76 
77 	lockdep_assert_held(&subsys->lock);
78 	list_for_each_entry(h, &subsys->nsheads, entry)
79 		if (h->disk)
80 			blk_freeze_queue_start(h->disk->queue);
81 }
82 
83 void nvme_failover_req(struct request *req)
84 {
85 	struct nvme_ns *ns = req->q->queuedata;
86 	u16 status = nvme_req(req)->status & 0x7ff;
87 	unsigned long flags;
88 	struct bio *bio;
89 
90 	nvme_mpath_clear_current_path(ns);
91 
92 	/*
93 	 * If we got back an ANA error, we know the controller is alive but not
94 	 * ready to serve this namespace.  Kick of a re-read of the ANA
95 	 * information page, and just try any other available path for now.
96 	 */
97 	if (nvme_is_ana_error(status) && ns->ctrl->ana_log_buf) {
98 		set_bit(NVME_NS_ANA_PENDING, &ns->flags);
99 		queue_work(nvme_wq, &ns->ctrl->ana_work);
100 	}
101 
102 	spin_lock_irqsave(&ns->head->requeue_lock, flags);
103 	for (bio = req->bio; bio; bio = bio->bi_next) {
104 		bio_set_dev(bio, ns->head->disk->part0);
105 		if (bio->bi_opf & REQ_POLLED) {
106 			bio->bi_opf &= ~REQ_POLLED;
107 			bio->bi_cookie = BLK_QC_T_NONE;
108 		}
109 	}
110 	blk_steal_bios(&ns->head->requeue_list, req);
111 	spin_unlock_irqrestore(&ns->head->requeue_lock, flags);
112 
113 	blk_mq_end_request(req, 0);
114 	kblockd_schedule_work(&ns->head->requeue_work);
115 }
116 
117 void nvme_mpath_start_request(struct request *rq)
118 {
119 	struct nvme_ns *ns = rq->q->queuedata;
120 	struct gendisk *disk = ns->head->disk;
121 
122 	if (!blk_queue_io_stat(disk->queue) || blk_rq_is_passthrough(rq))
123 		return;
124 
125 	nvme_req(rq)->flags |= NVME_MPATH_IO_STATS;
126 	nvme_req(rq)->start_time = bdev_start_io_acct(disk->part0,
127 					blk_rq_bytes(rq) >> SECTOR_SHIFT,
128 					req_op(rq), jiffies);
129 }
130 EXPORT_SYMBOL_GPL(nvme_mpath_start_request);
131 
132 void nvme_mpath_end_request(struct request *rq)
133 {
134 	struct nvme_ns *ns = rq->q->queuedata;
135 
136 	if (!(nvme_req(rq)->flags & NVME_MPATH_IO_STATS))
137 		return;
138 	bdev_end_io_acct(ns->head->disk->part0, req_op(rq),
139 		nvme_req(rq)->start_time);
140 }
141 
142 void nvme_kick_requeue_lists(struct nvme_ctrl *ctrl)
143 {
144 	struct nvme_ns *ns;
145 
146 	down_read(&ctrl->namespaces_rwsem);
147 	list_for_each_entry(ns, &ctrl->namespaces, list) {
148 		if (!ns->head->disk)
149 			continue;
150 		kblockd_schedule_work(&ns->head->requeue_work);
151 		if (ctrl->state == NVME_CTRL_LIVE)
152 			disk_uevent(ns->head->disk, KOBJ_CHANGE);
153 	}
154 	up_read(&ctrl->namespaces_rwsem);
155 }
156 
157 static const char *nvme_ana_state_names[] = {
158 	[0]				= "invalid state",
159 	[NVME_ANA_OPTIMIZED]		= "optimized",
160 	[NVME_ANA_NONOPTIMIZED]		= "non-optimized",
161 	[NVME_ANA_INACCESSIBLE]		= "inaccessible",
162 	[NVME_ANA_PERSISTENT_LOSS]	= "persistent-loss",
163 	[NVME_ANA_CHANGE]		= "change",
164 };
165 
166 bool nvme_mpath_clear_current_path(struct nvme_ns *ns)
167 {
168 	struct nvme_ns_head *head = ns->head;
169 	bool changed = false;
170 	int node;
171 
172 	if (!head)
173 		goto out;
174 
175 	for_each_node(node) {
176 		if (ns == rcu_access_pointer(head->current_path[node])) {
177 			rcu_assign_pointer(head->current_path[node], NULL);
178 			changed = true;
179 		}
180 	}
181 out:
182 	return changed;
183 }
184 
185 void nvme_mpath_clear_ctrl_paths(struct nvme_ctrl *ctrl)
186 {
187 	struct nvme_ns *ns;
188 
189 	down_read(&ctrl->namespaces_rwsem);
190 	list_for_each_entry(ns, &ctrl->namespaces, list) {
191 		nvme_mpath_clear_current_path(ns);
192 		kblockd_schedule_work(&ns->head->requeue_work);
193 	}
194 	up_read(&ctrl->namespaces_rwsem);
195 }
196 
197 void nvme_mpath_revalidate_paths(struct nvme_ns *ns)
198 {
199 	struct nvme_ns_head *head = ns->head;
200 	sector_t capacity = get_capacity(head->disk);
201 	int node;
202 	int srcu_idx;
203 
204 	srcu_idx = srcu_read_lock(&head->srcu);
205 	list_for_each_entry_rcu(ns, &head->list, siblings) {
206 		if (capacity != get_capacity(ns->disk))
207 			clear_bit(NVME_NS_READY, &ns->flags);
208 	}
209 	srcu_read_unlock(&head->srcu, srcu_idx);
210 
211 	for_each_node(node)
212 		rcu_assign_pointer(head->current_path[node], NULL);
213 	kblockd_schedule_work(&head->requeue_work);
214 }
215 
216 static bool nvme_path_is_disabled(struct nvme_ns *ns)
217 {
218 	/*
219 	 * We don't treat NVME_CTRL_DELETING as a disabled path as I/O should
220 	 * still be able to complete assuming that the controller is connected.
221 	 * Otherwise it will fail immediately and return to the requeue list.
222 	 */
223 	if (ns->ctrl->state != NVME_CTRL_LIVE &&
224 	    ns->ctrl->state != NVME_CTRL_DELETING)
225 		return true;
226 	if (test_bit(NVME_NS_ANA_PENDING, &ns->flags) ||
227 	    !test_bit(NVME_NS_READY, &ns->flags))
228 		return true;
229 	return false;
230 }
231 
232 static struct nvme_ns *__nvme_find_path(struct nvme_ns_head *head, int node)
233 {
234 	int found_distance = INT_MAX, fallback_distance = INT_MAX, distance;
235 	struct nvme_ns *found = NULL, *fallback = NULL, *ns;
236 
237 	list_for_each_entry_rcu(ns, &head->list, siblings) {
238 		if (nvme_path_is_disabled(ns))
239 			continue;
240 
241 		if (READ_ONCE(head->subsys->iopolicy) == NVME_IOPOLICY_NUMA)
242 			distance = node_distance(node, ns->ctrl->numa_node);
243 		else
244 			distance = LOCAL_DISTANCE;
245 
246 		switch (ns->ana_state) {
247 		case NVME_ANA_OPTIMIZED:
248 			if (distance < found_distance) {
249 				found_distance = distance;
250 				found = ns;
251 			}
252 			break;
253 		case NVME_ANA_NONOPTIMIZED:
254 			if (distance < fallback_distance) {
255 				fallback_distance = distance;
256 				fallback = ns;
257 			}
258 			break;
259 		default:
260 			break;
261 		}
262 	}
263 
264 	if (!found)
265 		found = fallback;
266 	if (found)
267 		rcu_assign_pointer(head->current_path[node], found);
268 	return found;
269 }
270 
271 static struct nvme_ns *nvme_next_ns(struct nvme_ns_head *head,
272 		struct nvme_ns *ns)
273 {
274 	ns = list_next_or_null_rcu(&head->list, &ns->siblings, struct nvme_ns,
275 			siblings);
276 	if (ns)
277 		return ns;
278 	return list_first_or_null_rcu(&head->list, struct nvme_ns, siblings);
279 }
280 
281 static struct nvme_ns *nvme_round_robin_path(struct nvme_ns_head *head,
282 		int node, struct nvme_ns *old)
283 {
284 	struct nvme_ns *ns, *found = NULL;
285 
286 	if (list_is_singular(&head->list)) {
287 		if (nvme_path_is_disabled(old))
288 			return NULL;
289 		return old;
290 	}
291 
292 	for (ns = nvme_next_ns(head, old);
293 	     ns && ns != old;
294 	     ns = nvme_next_ns(head, ns)) {
295 		if (nvme_path_is_disabled(ns))
296 			continue;
297 
298 		if (ns->ana_state == NVME_ANA_OPTIMIZED) {
299 			found = ns;
300 			goto out;
301 		}
302 		if (ns->ana_state == NVME_ANA_NONOPTIMIZED)
303 			found = ns;
304 	}
305 
306 	/*
307 	 * The loop above skips the current path for round-robin semantics.
308 	 * Fall back to the current path if either:
309 	 *  - no other optimized path found and current is optimized,
310 	 *  - no other usable path found and current is usable.
311 	 */
312 	if (!nvme_path_is_disabled(old) &&
313 	    (old->ana_state == NVME_ANA_OPTIMIZED ||
314 	     (!found && old->ana_state == NVME_ANA_NONOPTIMIZED)))
315 		return old;
316 
317 	if (!found)
318 		return NULL;
319 out:
320 	rcu_assign_pointer(head->current_path[node], found);
321 	return found;
322 }
323 
324 static inline bool nvme_path_is_optimized(struct nvme_ns *ns)
325 {
326 	return ns->ctrl->state == NVME_CTRL_LIVE &&
327 		ns->ana_state == NVME_ANA_OPTIMIZED;
328 }
329 
330 inline struct nvme_ns *nvme_find_path(struct nvme_ns_head *head)
331 {
332 	int node = numa_node_id();
333 	struct nvme_ns *ns;
334 
335 	ns = srcu_dereference(head->current_path[node], &head->srcu);
336 	if (unlikely(!ns))
337 		return __nvme_find_path(head, node);
338 
339 	if (READ_ONCE(head->subsys->iopolicy) == NVME_IOPOLICY_RR)
340 		return nvme_round_robin_path(head, node, ns);
341 	if (unlikely(!nvme_path_is_optimized(ns)))
342 		return __nvme_find_path(head, node);
343 	return ns;
344 }
345 
346 static bool nvme_available_path(struct nvme_ns_head *head)
347 {
348 	struct nvme_ns *ns;
349 
350 	list_for_each_entry_rcu(ns, &head->list, siblings) {
351 		if (test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ns->ctrl->flags))
352 			continue;
353 		switch (ns->ctrl->state) {
354 		case NVME_CTRL_LIVE:
355 		case NVME_CTRL_RESETTING:
356 		case NVME_CTRL_CONNECTING:
357 			/* fallthru */
358 			return true;
359 		default:
360 			break;
361 		}
362 	}
363 	return false;
364 }
365 
366 static void nvme_ns_head_submit_bio(struct bio *bio)
367 {
368 	struct nvme_ns_head *head = bio->bi_bdev->bd_disk->private_data;
369 	struct device *dev = disk_to_dev(head->disk);
370 	struct nvme_ns *ns;
371 	int srcu_idx;
372 
373 	/*
374 	 * The namespace might be going away and the bio might be moved to a
375 	 * different queue via blk_steal_bios(), so we need to use the bio_split
376 	 * pool from the original queue to allocate the bvecs from.
377 	 */
378 	bio = bio_split_to_limits(bio);
379 
380 	srcu_idx = srcu_read_lock(&head->srcu);
381 	ns = nvme_find_path(head);
382 	if (likely(ns)) {
383 		bio_set_dev(bio, ns->disk->part0);
384 		bio->bi_opf |= REQ_NVME_MPATH;
385 		trace_block_bio_remap(bio, disk_devt(ns->head->disk),
386 				      bio->bi_iter.bi_sector);
387 		submit_bio_noacct(bio);
388 	} else if (nvme_available_path(head)) {
389 		dev_warn_ratelimited(dev, "no usable path - requeuing I/O\n");
390 
391 		spin_lock_irq(&head->requeue_lock);
392 		bio_list_add(&head->requeue_list, bio);
393 		spin_unlock_irq(&head->requeue_lock);
394 	} else {
395 		dev_warn_ratelimited(dev, "no available path - failing I/O\n");
396 
397 		bio_io_error(bio);
398 	}
399 
400 	srcu_read_unlock(&head->srcu, srcu_idx);
401 }
402 
403 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
404 {
405 	if (!nvme_tryget_ns_head(bdev->bd_disk->private_data))
406 		return -ENXIO;
407 	return 0;
408 }
409 
410 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
411 {
412 	nvme_put_ns_head(disk->private_data);
413 }
414 
415 #ifdef CONFIG_BLK_DEV_ZONED
416 static int nvme_ns_head_report_zones(struct gendisk *disk, sector_t sector,
417 		unsigned int nr_zones, report_zones_cb cb, void *data)
418 {
419 	struct nvme_ns_head *head = disk->private_data;
420 	struct nvme_ns *ns;
421 	int srcu_idx, ret = -EWOULDBLOCK;
422 
423 	srcu_idx = srcu_read_lock(&head->srcu);
424 	ns = nvme_find_path(head);
425 	if (ns)
426 		ret = nvme_ns_report_zones(ns, sector, nr_zones, cb, data);
427 	srcu_read_unlock(&head->srcu, srcu_idx);
428 	return ret;
429 }
430 #else
431 #define nvme_ns_head_report_zones	NULL
432 #endif /* CONFIG_BLK_DEV_ZONED */
433 
434 const struct block_device_operations nvme_ns_head_ops = {
435 	.owner		= THIS_MODULE,
436 	.submit_bio	= nvme_ns_head_submit_bio,
437 	.open		= nvme_ns_head_open,
438 	.release	= nvme_ns_head_release,
439 	.ioctl		= nvme_ns_head_ioctl,
440 	.compat_ioctl	= blkdev_compat_ptr_ioctl,
441 	.getgeo		= nvme_getgeo,
442 	.report_zones	= nvme_ns_head_report_zones,
443 	.pr_ops		= &nvme_pr_ops,
444 };
445 
446 static inline struct nvme_ns_head *cdev_to_ns_head(struct cdev *cdev)
447 {
448 	return container_of(cdev, struct nvme_ns_head, cdev);
449 }
450 
451 static int nvme_ns_head_chr_open(struct inode *inode, struct file *file)
452 {
453 	if (!nvme_tryget_ns_head(cdev_to_ns_head(inode->i_cdev)))
454 		return -ENXIO;
455 	return 0;
456 }
457 
458 static int nvme_ns_head_chr_release(struct inode *inode, struct file *file)
459 {
460 	nvme_put_ns_head(cdev_to_ns_head(inode->i_cdev));
461 	return 0;
462 }
463 
464 static const struct file_operations nvme_ns_head_chr_fops = {
465 	.owner		= THIS_MODULE,
466 	.open		= nvme_ns_head_chr_open,
467 	.release	= nvme_ns_head_chr_release,
468 	.unlocked_ioctl	= nvme_ns_head_chr_ioctl,
469 	.compat_ioctl	= compat_ptr_ioctl,
470 	.uring_cmd	= nvme_ns_head_chr_uring_cmd,
471 	.uring_cmd_iopoll = nvme_ns_head_chr_uring_cmd_iopoll,
472 };
473 
474 static int nvme_add_ns_head_cdev(struct nvme_ns_head *head)
475 {
476 	int ret;
477 
478 	head->cdev_device.parent = &head->subsys->dev;
479 	ret = dev_set_name(&head->cdev_device, "ng%dn%d",
480 			   head->subsys->instance, head->instance);
481 	if (ret)
482 		return ret;
483 	ret = nvme_cdev_add(&head->cdev, &head->cdev_device,
484 			    &nvme_ns_head_chr_fops, THIS_MODULE);
485 	return ret;
486 }
487 
488 static void nvme_requeue_work(struct work_struct *work)
489 {
490 	struct nvme_ns_head *head =
491 		container_of(work, struct nvme_ns_head, requeue_work);
492 	struct bio *bio, *next;
493 
494 	spin_lock_irq(&head->requeue_lock);
495 	next = bio_list_get(&head->requeue_list);
496 	spin_unlock_irq(&head->requeue_lock);
497 
498 	while ((bio = next) != NULL) {
499 		next = bio->bi_next;
500 		bio->bi_next = NULL;
501 
502 		submit_bio_noacct(bio);
503 	}
504 }
505 
506 int nvme_mpath_alloc_disk(struct nvme_ctrl *ctrl, struct nvme_ns_head *head)
507 {
508 	bool vwc = false;
509 
510 	mutex_init(&head->lock);
511 	bio_list_init(&head->requeue_list);
512 	spin_lock_init(&head->requeue_lock);
513 	INIT_WORK(&head->requeue_work, nvme_requeue_work);
514 
515 	/*
516 	 * Add a multipath node if the subsystems supports multiple controllers.
517 	 * We also do this for private namespaces as the namespace sharing flag
518 	 * could change after a rescan.
519 	 */
520 	if (!(ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
521 	    !nvme_is_unique_nsid(ctrl, head) || !multipath)
522 		return 0;
523 
524 	head->disk = blk_alloc_disk(ctrl->numa_node);
525 	if (!head->disk)
526 		return -ENOMEM;
527 	head->disk->fops = &nvme_ns_head_ops;
528 	head->disk->private_data = head;
529 	sprintf(head->disk->disk_name, "nvme%dn%d",
530 			ctrl->subsys->instance, head->instance);
531 
532 	blk_queue_flag_set(QUEUE_FLAG_NONROT, head->disk->queue);
533 	blk_queue_flag_set(QUEUE_FLAG_NOWAIT, head->disk->queue);
534 	blk_queue_flag_set(QUEUE_FLAG_IO_STAT, head->disk->queue);
535 	/*
536 	 * This assumes all controllers that refer to a namespace either
537 	 * support poll queues or not.  That is not a strict guarantee,
538 	 * but if the assumption is wrong the effect is only suboptimal
539 	 * performance but not correctness problem.
540 	 */
541 	if (ctrl->tagset->nr_maps > HCTX_TYPE_POLL &&
542 	    ctrl->tagset->map[HCTX_TYPE_POLL].nr_queues)
543 		blk_queue_flag_set(QUEUE_FLAG_POLL, head->disk->queue);
544 
545 	/* set to a default value of 512 until the disk is validated */
546 	blk_queue_logical_block_size(head->disk->queue, 512);
547 	blk_set_stacking_limits(&head->disk->queue->limits);
548 	blk_queue_dma_alignment(head->disk->queue, 3);
549 
550 	/* we need to propagate up the VMC settings */
551 	if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
552 		vwc = true;
553 	blk_queue_write_cache(head->disk->queue, vwc, vwc);
554 	return 0;
555 }
556 
557 static void nvme_mpath_set_live(struct nvme_ns *ns)
558 {
559 	struct nvme_ns_head *head = ns->head;
560 	int rc;
561 
562 	if (!head->disk)
563 		return;
564 
565 	/*
566 	 * test_and_set_bit() is used because it is protecting against two nvme
567 	 * paths simultaneously calling device_add_disk() on the same namespace
568 	 * head.
569 	 */
570 	if (!test_and_set_bit(NVME_NSHEAD_DISK_LIVE, &head->flags)) {
571 		rc = device_add_disk(&head->subsys->dev, head->disk,
572 				     nvme_ns_id_attr_groups);
573 		if (rc) {
574 			clear_bit(NVME_NSHEAD_DISK_LIVE, &ns->flags);
575 			return;
576 		}
577 		nvme_add_ns_head_cdev(head);
578 	}
579 
580 	mutex_lock(&head->lock);
581 	if (nvme_path_is_optimized(ns)) {
582 		int node, srcu_idx;
583 
584 		srcu_idx = srcu_read_lock(&head->srcu);
585 		for_each_node(node)
586 			__nvme_find_path(head, node);
587 		srcu_read_unlock(&head->srcu, srcu_idx);
588 	}
589 	mutex_unlock(&head->lock);
590 
591 	synchronize_srcu(&head->srcu);
592 	kblockd_schedule_work(&head->requeue_work);
593 }
594 
595 static int nvme_parse_ana_log(struct nvme_ctrl *ctrl, void *data,
596 		int (*cb)(struct nvme_ctrl *ctrl, struct nvme_ana_group_desc *,
597 			void *))
598 {
599 	void *base = ctrl->ana_log_buf;
600 	size_t offset = sizeof(struct nvme_ana_rsp_hdr);
601 	int error, i;
602 
603 	lockdep_assert_held(&ctrl->ana_lock);
604 
605 	for (i = 0; i < le16_to_cpu(ctrl->ana_log_buf->ngrps); i++) {
606 		struct nvme_ana_group_desc *desc = base + offset;
607 		u32 nr_nsids;
608 		size_t nsid_buf_size;
609 
610 		if (WARN_ON_ONCE(offset > ctrl->ana_log_size - sizeof(*desc)))
611 			return -EINVAL;
612 
613 		nr_nsids = le32_to_cpu(desc->nnsids);
614 		nsid_buf_size = flex_array_size(desc, nsids, nr_nsids);
615 
616 		if (WARN_ON_ONCE(desc->grpid == 0))
617 			return -EINVAL;
618 		if (WARN_ON_ONCE(le32_to_cpu(desc->grpid) > ctrl->anagrpmax))
619 			return -EINVAL;
620 		if (WARN_ON_ONCE(desc->state == 0))
621 			return -EINVAL;
622 		if (WARN_ON_ONCE(desc->state > NVME_ANA_CHANGE))
623 			return -EINVAL;
624 
625 		offset += sizeof(*desc);
626 		if (WARN_ON_ONCE(offset > ctrl->ana_log_size - nsid_buf_size))
627 			return -EINVAL;
628 
629 		error = cb(ctrl, desc, data);
630 		if (error)
631 			return error;
632 
633 		offset += nsid_buf_size;
634 	}
635 
636 	return 0;
637 }
638 
639 static inline bool nvme_state_is_live(enum nvme_ana_state state)
640 {
641 	return state == NVME_ANA_OPTIMIZED || state == NVME_ANA_NONOPTIMIZED;
642 }
643 
644 static void nvme_update_ns_ana_state(struct nvme_ana_group_desc *desc,
645 		struct nvme_ns *ns)
646 {
647 	ns->ana_grpid = le32_to_cpu(desc->grpid);
648 	ns->ana_state = desc->state;
649 	clear_bit(NVME_NS_ANA_PENDING, &ns->flags);
650 	/*
651 	 * nvme_mpath_set_live() will trigger I/O to the multipath path device
652 	 * and in turn to this path device.  However we cannot accept this I/O
653 	 * if the controller is not live.  This may deadlock if called from
654 	 * nvme_mpath_init_identify() and the ctrl will never complete
655 	 * initialization, preventing I/O from completing.  For this case we
656 	 * will reprocess the ANA log page in nvme_mpath_update() once the
657 	 * controller is ready.
658 	 */
659 	if (nvme_state_is_live(ns->ana_state) &&
660 	    ns->ctrl->state == NVME_CTRL_LIVE)
661 		nvme_mpath_set_live(ns);
662 }
663 
664 static int nvme_update_ana_state(struct nvme_ctrl *ctrl,
665 		struct nvme_ana_group_desc *desc, void *data)
666 {
667 	u32 nr_nsids = le32_to_cpu(desc->nnsids), n = 0;
668 	unsigned *nr_change_groups = data;
669 	struct nvme_ns *ns;
670 
671 	dev_dbg(ctrl->device, "ANA group %d: %s.\n",
672 			le32_to_cpu(desc->grpid),
673 			nvme_ana_state_names[desc->state]);
674 
675 	if (desc->state == NVME_ANA_CHANGE)
676 		(*nr_change_groups)++;
677 
678 	if (!nr_nsids)
679 		return 0;
680 
681 	down_read(&ctrl->namespaces_rwsem);
682 	list_for_each_entry(ns, &ctrl->namespaces, list) {
683 		unsigned nsid;
684 again:
685 		nsid = le32_to_cpu(desc->nsids[n]);
686 		if (ns->head->ns_id < nsid)
687 			continue;
688 		if (ns->head->ns_id == nsid)
689 			nvme_update_ns_ana_state(desc, ns);
690 		if (++n == nr_nsids)
691 			break;
692 		if (ns->head->ns_id > nsid)
693 			goto again;
694 	}
695 	up_read(&ctrl->namespaces_rwsem);
696 	return 0;
697 }
698 
699 static int nvme_read_ana_log(struct nvme_ctrl *ctrl)
700 {
701 	u32 nr_change_groups = 0;
702 	int error;
703 
704 	mutex_lock(&ctrl->ana_lock);
705 	error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_ANA, 0, NVME_CSI_NVM,
706 			ctrl->ana_log_buf, ctrl->ana_log_size, 0);
707 	if (error) {
708 		dev_warn(ctrl->device, "Failed to get ANA log: %d\n", error);
709 		goto out_unlock;
710 	}
711 
712 	error = nvme_parse_ana_log(ctrl, &nr_change_groups,
713 			nvme_update_ana_state);
714 	if (error)
715 		goto out_unlock;
716 
717 	/*
718 	 * In theory we should have an ANATT timer per group as they might enter
719 	 * the change state at different times.  But that is a lot of overhead
720 	 * just to protect against a target that keeps entering new changes
721 	 * states while never finishing previous ones.  But we'll still
722 	 * eventually time out once all groups are in change state, so this
723 	 * isn't a big deal.
724 	 *
725 	 * We also double the ANATT value to provide some slack for transports
726 	 * or AEN processing overhead.
727 	 */
728 	if (nr_change_groups)
729 		mod_timer(&ctrl->anatt_timer, ctrl->anatt * HZ * 2 + jiffies);
730 	else
731 		del_timer_sync(&ctrl->anatt_timer);
732 out_unlock:
733 	mutex_unlock(&ctrl->ana_lock);
734 	return error;
735 }
736 
737 static void nvme_ana_work(struct work_struct *work)
738 {
739 	struct nvme_ctrl *ctrl = container_of(work, struct nvme_ctrl, ana_work);
740 
741 	if (ctrl->state != NVME_CTRL_LIVE)
742 		return;
743 
744 	nvme_read_ana_log(ctrl);
745 }
746 
747 void nvme_mpath_update(struct nvme_ctrl *ctrl)
748 {
749 	u32 nr_change_groups = 0;
750 
751 	if (!ctrl->ana_log_buf)
752 		return;
753 
754 	mutex_lock(&ctrl->ana_lock);
755 	nvme_parse_ana_log(ctrl, &nr_change_groups, nvme_update_ana_state);
756 	mutex_unlock(&ctrl->ana_lock);
757 }
758 
759 static void nvme_anatt_timeout(struct timer_list *t)
760 {
761 	struct nvme_ctrl *ctrl = from_timer(ctrl, t, anatt_timer);
762 
763 	dev_info(ctrl->device, "ANATT timeout, resetting controller.\n");
764 	nvme_reset_ctrl(ctrl);
765 }
766 
767 void nvme_mpath_stop(struct nvme_ctrl *ctrl)
768 {
769 	if (!nvme_ctrl_use_ana(ctrl))
770 		return;
771 	del_timer_sync(&ctrl->anatt_timer);
772 	cancel_work_sync(&ctrl->ana_work);
773 }
774 
775 #define SUBSYS_ATTR_RW(_name, _mode, _show, _store)  \
776 	struct device_attribute subsys_attr_##_name =	\
777 		__ATTR(_name, _mode, _show, _store)
778 
779 static ssize_t nvme_subsys_iopolicy_show(struct device *dev,
780 		struct device_attribute *attr, char *buf)
781 {
782 	struct nvme_subsystem *subsys =
783 		container_of(dev, struct nvme_subsystem, dev);
784 
785 	return sysfs_emit(buf, "%s\n",
786 			  nvme_iopolicy_names[READ_ONCE(subsys->iopolicy)]);
787 }
788 
789 static ssize_t nvme_subsys_iopolicy_store(struct device *dev,
790 		struct device_attribute *attr, const char *buf, size_t count)
791 {
792 	struct nvme_subsystem *subsys =
793 		container_of(dev, struct nvme_subsystem, dev);
794 	int i;
795 
796 	for (i = 0; i < ARRAY_SIZE(nvme_iopolicy_names); i++) {
797 		if (sysfs_streq(buf, nvme_iopolicy_names[i])) {
798 			WRITE_ONCE(subsys->iopolicy, i);
799 			return count;
800 		}
801 	}
802 
803 	return -EINVAL;
804 }
805 SUBSYS_ATTR_RW(iopolicy, S_IRUGO | S_IWUSR,
806 		      nvme_subsys_iopolicy_show, nvme_subsys_iopolicy_store);
807 
808 static ssize_t ana_grpid_show(struct device *dev, struct device_attribute *attr,
809 		char *buf)
810 {
811 	return sysfs_emit(buf, "%d\n", nvme_get_ns_from_dev(dev)->ana_grpid);
812 }
813 DEVICE_ATTR_RO(ana_grpid);
814 
815 static ssize_t ana_state_show(struct device *dev, struct device_attribute *attr,
816 		char *buf)
817 {
818 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
819 
820 	return sysfs_emit(buf, "%s\n", nvme_ana_state_names[ns->ana_state]);
821 }
822 DEVICE_ATTR_RO(ana_state);
823 
824 static int nvme_lookup_ana_group_desc(struct nvme_ctrl *ctrl,
825 		struct nvme_ana_group_desc *desc, void *data)
826 {
827 	struct nvme_ana_group_desc *dst = data;
828 
829 	if (desc->grpid != dst->grpid)
830 		return 0;
831 
832 	*dst = *desc;
833 	return -ENXIO; /* just break out of the loop */
834 }
835 
836 void nvme_mpath_add_disk(struct nvme_ns *ns, __le32 anagrpid)
837 {
838 	if (nvme_ctrl_use_ana(ns->ctrl)) {
839 		struct nvme_ana_group_desc desc = {
840 			.grpid = anagrpid,
841 			.state = 0,
842 		};
843 
844 		mutex_lock(&ns->ctrl->ana_lock);
845 		ns->ana_grpid = le32_to_cpu(anagrpid);
846 		nvme_parse_ana_log(ns->ctrl, &desc, nvme_lookup_ana_group_desc);
847 		mutex_unlock(&ns->ctrl->ana_lock);
848 		if (desc.state) {
849 			/* found the group desc: update */
850 			nvme_update_ns_ana_state(&desc, ns);
851 		} else {
852 			/* group desc not found: trigger a re-read */
853 			set_bit(NVME_NS_ANA_PENDING, &ns->flags);
854 			queue_work(nvme_wq, &ns->ctrl->ana_work);
855 		}
856 	} else {
857 		ns->ana_state = NVME_ANA_OPTIMIZED;
858 		nvme_mpath_set_live(ns);
859 	}
860 
861 	if (blk_queue_stable_writes(ns->queue) && ns->head->disk)
862 		blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES,
863 				   ns->head->disk->queue);
864 #ifdef CONFIG_BLK_DEV_ZONED
865 	if (blk_queue_is_zoned(ns->queue) && ns->head->disk)
866 		ns->head->disk->nr_zones = ns->disk->nr_zones;
867 #endif
868 }
869 
870 void nvme_mpath_shutdown_disk(struct nvme_ns_head *head)
871 {
872 	if (!head->disk)
873 		return;
874 	kblockd_schedule_work(&head->requeue_work);
875 	if (test_bit(NVME_NSHEAD_DISK_LIVE, &head->flags)) {
876 		nvme_cdev_del(&head->cdev, &head->cdev_device);
877 		del_gendisk(head->disk);
878 	}
879 }
880 
881 void nvme_mpath_remove_disk(struct nvme_ns_head *head)
882 {
883 	if (!head->disk)
884 		return;
885 	blk_mark_disk_dead(head->disk);
886 	/* make sure all pending bios are cleaned up */
887 	kblockd_schedule_work(&head->requeue_work);
888 	flush_work(&head->requeue_work);
889 	put_disk(head->disk);
890 }
891 
892 void nvme_mpath_init_ctrl(struct nvme_ctrl *ctrl)
893 {
894 	mutex_init(&ctrl->ana_lock);
895 	timer_setup(&ctrl->anatt_timer, nvme_anatt_timeout, 0);
896 	INIT_WORK(&ctrl->ana_work, nvme_ana_work);
897 }
898 
899 int nvme_mpath_init_identify(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
900 {
901 	size_t max_transfer_size = ctrl->max_hw_sectors << SECTOR_SHIFT;
902 	size_t ana_log_size;
903 	int error = 0;
904 
905 	/* check if multipath is enabled and we have the capability */
906 	if (!multipath || !ctrl->subsys ||
907 	    !(ctrl->subsys->cmic & NVME_CTRL_CMIC_ANA))
908 		return 0;
909 
910 	if (!ctrl->max_namespaces ||
911 	    ctrl->max_namespaces > le32_to_cpu(id->nn)) {
912 		dev_err(ctrl->device,
913 			"Invalid MNAN value %u\n", ctrl->max_namespaces);
914 		return -EINVAL;
915 	}
916 
917 	ctrl->anacap = id->anacap;
918 	ctrl->anatt = id->anatt;
919 	ctrl->nanagrpid = le32_to_cpu(id->nanagrpid);
920 	ctrl->anagrpmax = le32_to_cpu(id->anagrpmax);
921 
922 	ana_log_size = sizeof(struct nvme_ana_rsp_hdr) +
923 		ctrl->nanagrpid * sizeof(struct nvme_ana_group_desc) +
924 		ctrl->max_namespaces * sizeof(__le32);
925 	if (ana_log_size > max_transfer_size) {
926 		dev_err(ctrl->device,
927 			"ANA log page size (%zd) larger than MDTS (%zd).\n",
928 			ana_log_size, max_transfer_size);
929 		dev_err(ctrl->device, "disabling ANA support.\n");
930 		goto out_uninit;
931 	}
932 	if (ana_log_size > ctrl->ana_log_size) {
933 		nvme_mpath_stop(ctrl);
934 		nvme_mpath_uninit(ctrl);
935 		ctrl->ana_log_buf = kvmalloc(ana_log_size, GFP_KERNEL);
936 		if (!ctrl->ana_log_buf)
937 			return -ENOMEM;
938 	}
939 	ctrl->ana_log_size = ana_log_size;
940 	error = nvme_read_ana_log(ctrl);
941 	if (error)
942 		goto out_uninit;
943 	return 0;
944 
945 out_uninit:
946 	nvme_mpath_uninit(ctrl);
947 	return error;
948 }
949 
950 void nvme_mpath_uninit(struct nvme_ctrl *ctrl)
951 {
952 	kvfree(ctrl->ana_log_buf);
953 	ctrl->ana_log_buf = NULL;
954 	ctrl->ana_log_size = 0;
955 }
956