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