xref: /openbmc/linux/drivers/nvme/host/core.c (revision 61cb9ac6)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVM Express device driver
4  * Copyright (c) 2011-2014, Intel Corporation.
5  */
6 
7 #include <linux/blkdev.h>
8 #include <linux/blk-mq.h>
9 #include <linux/compat.h>
10 #include <linux/delay.h>
11 #include <linux/errno.h>
12 #include <linux/hdreg.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/backing-dev.h>
16 #include <linux/list_sort.h>
17 #include <linux/slab.h>
18 #include <linux/types.h>
19 #include <linux/pr.h>
20 #include <linux/ptrace.h>
21 #include <linux/nvme_ioctl.h>
22 #include <linux/pm_qos.h>
23 #include <asm/unaligned.h>
24 
25 #include "nvme.h"
26 #include "fabrics.h"
27 
28 #define CREATE_TRACE_POINTS
29 #include "trace.h"
30 
31 #define NVME_MINORS		(1U << MINORBITS)
32 
33 unsigned int admin_timeout = 60;
34 module_param(admin_timeout, uint, 0644);
35 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
36 EXPORT_SYMBOL_GPL(admin_timeout);
37 
38 unsigned int nvme_io_timeout = 30;
39 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
40 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
41 EXPORT_SYMBOL_GPL(nvme_io_timeout);
42 
43 static unsigned char shutdown_timeout = 5;
44 module_param(shutdown_timeout, byte, 0644);
45 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
46 
47 static u8 nvme_max_retries = 5;
48 module_param_named(max_retries, nvme_max_retries, byte, 0644);
49 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
50 
51 static unsigned long default_ps_max_latency_us = 100000;
52 module_param(default_ps_max_latency_us, ulong, 0644);
53 MODULE_PARM_DESC(default_ps_max_latency_us,
54 		 "max power saving latency for new devices; use PM QOS to change per device");
55 
56 static bool force_apst;
57 module_param(force_apst, bool, 0644);
58 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
59 
60 static unsigned long apst_primary_timeout_ms = 100;
61 module_param(apst_primary_timeout_ms, ulong, 0644);
62 MODULE_PARM_DESC(apst_primary_timeout_ms,
63 	"primary APST timeout in ms");
64 
65 static unsigned long apst_secondary_timeout_ms = 2000;
66 module_param(apst_secondary_timeout_ms, ulong, 0644);
67 MODULE_PARM_DESC(apst_secondary_timeout_ms,
68 	"secondary APST timeout in ms");
69 
70 static unsigned long apst_primary_latency_tol_us = 15000;
71 module_param(apst_primary_latency_tol_us, ulong, 0644);
72 MODULE_PARM_DESC(apst_primary_latency_tol_us,
73 	"primary APST latency tolerance in us");
74 
75 static unsigned long apst_secondary_latency_tol_us = 100000;
76 module_param(apst_secondary_latency_tol_us, ulong, 0644);
77 MODULE_PARM_DESC(apst_secondary_latency_tol_us,
78 	"secondary APST latency tolerance in us");
79 
80 static bool streams;
81 module_param(streams, bool, 0644);
82 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
83 
84 /*
85  * nvme_wq - hosts nvme related works that are not reset or delete
86  * nvme_reset_wq - hosts nvme reset works
87  * nvme_delete_wq - hosts nvme delete works
88  *
89  * nvme_wq will host works such as scan, aen handling, fw activation,
90  * keep-alive, periodic reconnects etc. nvme_reset_wq
91  * runs reset works which also flush works hosted on nvme_wq for
92  * serialization purposes. nvme_delete_wq host controller deletion
93  * works which flush reset works for serialization.
94  */
95 struct workqueue_struct *nvme_wq;
96 EXPORT_SYMBOL_GPL(nvme_wq);
97 
98 struct workqueue_struct *nvme_reset_wq;
99 EXPORT_SYMBOL_GPL(nvme_reset_wq);
100 
101 struct workqueue_struct *nvme_delete_wq;
102 EXPORT_SYMBOL_GPL(nvme_delete_wq);
103 
104 static LIST_HEAD(nvme_subsystems);
105 static DEFINE_MUTEX(nvme_subsystems_lock);
106 
107 static DEFINE_IDA(nvme_instance_ida);
108 static dev_t nvme_ctrl_base_chr_devt;
109 static struct class *nvme_class;
110 static struct class *nvme_subsys_class;
111 
112 static DEFINE_IDA(nvme_ns_chr_minor_ida);
113 static dev_t nvme_ns_chr_devt;
114 static struct class *nvme_ns_chr_class;
115 
116 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
117 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
118 					   unsigned nsid);
119 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
120 				   struct nvme_command *cmd);
121 
122 /*
123  * Prepare a queue for teardown.
124  *
125  * This must forcibly unquiesce queues to avoid blocking dispatch, and only set
126  * the capacity to 0 after that to avoid blocking dispatchers that may be
127  * holding bd_butex.  This will end buffered writers dirtying pages that can't
128  * be synced.
129  */
130 static void nvme_set_queue_dying(struct nvme_ns *ns)
131 {
132 	if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
133 		return;
134 
135 	blk_set_queue_dying(ns->queue);
136 	blk_mq_unquiesce_queue(ns->queue);
137 
138 	set_capacity_and_notify(ns->disk, 0);
139 }
140 
141 void nvme_queue_scan(struct nvme_ctrl *ctrl)
142 {
143 	/*
144 	 * Only new queue scan work when admin and IO queues are both alive
145 	 */
146 	if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset)
147 		queue_work(nvme_wq, &ctrl->scan_work);
148 }
149 
150 /*
151  * Use this function to proceed with scheduling reset_work for a controller
152  * that had previously been set to the resetting state. This is intended for
153  * code paths that can't be interrupted by other reset attempts. A hot removal
154  * may prevent this from succeeding.
155  */
156 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
157 {
158 	if (ctrl->state != NVME_CTRL_RESETTING)
159 		return -EBUSY;
160 	if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
161 		return -EBUSY;
162 	return 0;
163 }
164 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
165 
166 static void nvme_failfast_work(struct work_struct *work)
167 {
168 	struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
169 			struct nvme_ctrl, failfast_work);
170 
171 	if (ctrl->state != NVME_CTRL_CONNECTING)
172 		return;
173 
174 	set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
175 	dev_info(ctrl->device, "failfast expired\n");
176 	nvme_kick_requeue_lists(ctrl);
177 }
178 
179 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
180 {
181 	if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
182 		return;
183 
184 	schedule_delayed_work(&ctrl->failfast_work,
185 			      ctrl->opts->fast_io_fail_tmo * HZ);
186 }
187 
188 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
189 {
190 	if (!ctrl->opts)
191 		return;
192 
193 	cancel_delayed_work_sync(&ctrl->failfast_work);
194 	clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
195 }
196 
197 
198 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
199 {
200 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
201 		return -EBUSY;
202 	if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
203 		return -EBUSY;
204 	return 0;
205 }
206 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
207 
208 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
209 {
210 	int ret;
211 
212 	ret = nvme_reset_ctrl(ctrl);
213 	if (!ret) {
214 		flush_work(&ctrl->reset_work);
215 		if (ctrl->state != NVME_CTRL_LIVE)
216 			ret = -ENETRESET;
217 	}
218 
219 	return ret;
220 }
221 
222 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
223 {
224 	dev_info(ctrl->device,
225 		 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
226 
227 	flush_work(&ctrl->reset_work);
228 	nvme_stop_ctrl(ctrl);
229 	nvme_remove_namespaces(ctrl);
230 	ctrl->ops->delete_ctrl(ctrl);
231 	nvme_uninit_ctrl(ctrl);
232 }
233 
234 static void nvme_delete_ctrl_work(struct work_struct *work)
235 {
236 	struct nvme_ctrl *ctrl =
237 		container_of(work, struct nvme_ctrl, delete_work);
238 
239 	nvme_do_delete_ctrl(ctrl);
240 }
241 
242 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
243 {
244 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
245 		return -EBUSY;
246 	if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
247 		return -EBUSY;
248 	return 0;
249 }
250 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
251 
252 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
253 {
254 	/*
255 	 * Keep a reference until nvme_do_delete_ctrl() complete,
256 	 * since ->delete_ctrl can free the controller.
257 	 */
258 	nvme_get_ctrl(ctrl);
259 	if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
260 		nvme_do_delete_ctrl(ctrl);
261 	nvme_put_ctrl(ctrl);
262 }
263 
264 static blk_status_t nvme_error_status(u16 status)
265 {
266 	switch (status & 0x7ff) {
267 	case NVME_SC_SUCCESS:
268 		return BLK_STS_OK;
269 	case NVME_SC_CAP_EXCEEDED:
270 		return BLK_STS_NOSPC;
271 	case NVME_SC_LBA_RANGE:
272 	case NVME_SC_CMD_INTERRUPTED:
273 	case NVME_SC_NS_NOT_READY:
274 		return BLK_STS_TARGET;
275 	case NVME_SC_BAD_ATTRIBUTES:
276 	case NVME_SC_ONCS_NOT_SUPPORTED:
277 	case NVME_SC_INVALID_OPCODE:
278 	case NVME_SC_INVALID_FIELD:
279 	case NVME_SC_INVALID_NS:
280 		return BLK_STS_NOTSUPP;
281 	case NVME_SC_WRITE_FAULT:
282 	case NVME_SC_READ_ERROR:
283 	case NVME_SC_UNWRITTEN_BLOCK:
284 	case NVME_SC_ACCESS_DENIED:
285 	case NVME_SC_READ_ONLY:
286 	case NVME_SC_COMPARE_FAILED:
287 		return BLK_STS_MEDIUM;
288 	case NVME_SC_GUARD_CHECK:
289 	case NVME_SC_APPTAG_CHECK:
290 	case NVME_SC_REFTAG_CHECK:
291 	case NVME_SC_INVALID_PI:
292 		return BLK_STS_PROTECTION;
293 	case NVME_SC_RESERVATION_CONFLICT:
294 		return BLK_STS_NEXUS;
295 	case NVME_SC_HOST_PATH_ERROR:
296 		return BLK_STS_TRANSPORT;
297 	case NVME_SC_ZONE_TOO_MANY_ACTIVE:
298 		return BLK_STS_ZONE_ACTIVE_RESOURCE;
299 	case NVME_SC_ZONE_TOO_MANY_OPEN:
300 		return BLK_STS_ZONE_OPEN_RESOURCE;
301 	default:
302 		return BLK_STS_IOERR;
303 	}
304 }
305 
306 static void nvme_retry_req(struct request *req)
307 {
308 	unsigned long delay = 0;
309 	u16 crd;
310 
311 	/* The mask and shift result must be <= 3 */
312 	crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
313 	if (crd)
314 		delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
315 
316 	nvme_req(req)->retries++;
317 	blk_mq_requeue_request(req, false);
318 	blk_mq_delay_kick_requeue_list(req->q, delay);
319 }
320 
321 enum nvme_disposition {
322 	COMPLETE,
323 	RETRY,
324 	FAILOVER,
325 };
326 
327 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
328 {
329 	if (likely(nvme_req(req)->status == 0))
330 		return COMPLETE;
331 
332 	if (blk_noretry_request(req) ||
333 	    (nvme_req(req)->status & NVME_SC_DNR) ||
334 	    nvme_req(req)->retries >= nvme_max_retries)
335 		return COMPLETE;
336 
337 	if (req->cmd_flags & REQ_NVME_MPATH) {
338 		if (nvme_is_path_error(nvme_req(req)->status) ||
339 		    blk_queue_dying(req->q))
340 			return FAILOVER;
341 	} else {
342 		if (blk_queue_dying(req->q))
343 			return COMPLETE;
344 	}
345 
346 	return RETRY;
347 }
348 
349 static inline void nvme_end_req(struct request *req)
350 {
351 	blk_status_t status = nvme_error_status(nvme_req(req)->status);
352 
353 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
354 	    req_op(req) == REQ_OP_ZONE_APPEND)
355 		req->__sector = nvme_lba_to_sect(req->q->queuedata,
356 			le64_to_cpu(nvme_req(req)->result.u64));
357 
358 	nvme_trace_bio_complete(req);
359 	blk_mq_end_request(req, status);
360 }
361 
362 void nvme_complete_rq(struct request *req)
363 {
364 	trace_nvme_complete_rq(req);
365 	nvme_cleanup_cmd(req);
366 
367 	if (nvme_req(req)->ctrl->kas)
368 		nvme_req(req)->ctrl->comp_seen = true;
369 
370 	switch (nvme_decide_disposition(req)) {
371 	case COMPLETE:
372 		nvme_end_req(req);
373 		return;
374 	case RETRY:
375 		nvme_retry_req(req);
376 		return;
377 	case FAILOVER:
378 		nvme_failover_req(req);
379 		return;
380 	}
381 }
382 EXPORT_SYMBOL_GPL(nvme_complete_rq);
383 
384 /*
385  * Called to unwind from ->queue_rq on a failed command submission so that the
386  * multipathing code gets called to potentially failover to another path.
387  * The caller needs to unwind all transport specific resource allocations and
388  * must return propagate the return value.
389  */
390 blk_status_t nvme_host_path_error(struct request *req)
391 {
392 	nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
393 	blk_mq_set_request_complete(req);
394 	nvme_complete_rq(req);
395 	return BLK_STS_OK;
396 }
397 EXPORT_SYMBOL_GPL(nvme_host_path_error);
398 
399 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
400 {
401 	dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
402 				"Cancelling I/O %d", req->tag);
403 
404 	/* don't abort one completed request */
405 	if (blk_mq_request_completed(req))
406 		return true;
407 
408 	nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
409 	nvme_req(req)->flags |= NVME_REQ_CANCELLED;
410 	blk_mq_complete_request(req);
411 	return true;
412 }
413 EXPORT_SYMBOL_GPL(nvme_cancel_request);
414 
415 void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
416 {
417 	if (ctrl->tagset) {
418 		blk_mq_tagset_busy_iter(ctrl->tagset,
419 				nvme_cancel_request, ctrl);
420 		blk_mq_tagset_wait_completed_request(ctrl->tagset);
421 	}
422 }
423 EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
424 
425 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
426 {
427 	if (ctrl->admin_tagset) {
428 		blk_mq_tagset_busy_iter(ctrl->admin_tagset,
429 				nvme_cancel_request, ctrl);
430 		blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
431 	}
432 }
433 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
434 
435 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
436 		enum nvme_ctrl_state new_state)
437 {
438 	enum nvme_ctrl_state old_state;
439 	unsigned long flags;
440 	bool changed = false;
441 
442 	spin_lock_irqsave(&ctrl->lock, flags);
443 
444 	old_state = ctrl->state;
445 	switch (new_state) {
446 	case NVME_CTRL_LIVE:
447 		switch (old_state) {
448 		case NVME_CTRL_NEW:
449 		case NVME_CTRL_RESETTING:
450 		case NVME_CTRL_CONNECTING:
451 			changed = true;
452 			fallthrough;
453 		default:
454 			break;
455 		}
456 		break;
457 	case NVME_CTRL_RESETTING:
458 		switch (old_state) {
459 		case NVME_CTRL_NEW:
460 		case NVME_CTRL_LIVE:
461 			changed = true;
462 			fallthrough;
463 		default:
464 			break;
465 		}
466 		break;
467 	case NVME_CTRL_CONNECTING:
468 		switch (old_state) {
469 		case NVME_CTRL_NEW:
470 		case NVME_CTRL_RESETTING:
471 			changed = true;
472 			fallthrough;
473 		default:
474 			break;
475 		}
476 		break;
477 	case NVME_CTRL_DELETING:
478 		switch (old_state) {
479 		case NVME_CTRL_LIVE:
480 		case NVME_CTRL_RESETTING:
481 		case NVME_CTRL_CONNECTING:
482 			changed = true;
483 			fallthrough;
484 		default:
485 			break;
486 		}
487 		break;
488 	case NVME_CTRL_DELETING_NOIO:
489 		switch (old_state) {
490 		case NVME_CTRL_DELETING:
491 		case NVME_CTRL_DEAD:
492 			changed = true;
493 			fallthrough;
494 		default:
495 			break;
496 		}
497 		break;
498 	case NVME_CTRL_DEAD:
499 		switch (old_state) {
500 		case NVME_CTRL_DELETING:
501 			changed = true;
502 			fallthrough;
503 		default:
504 			break;
505 		}
506 		break;
507 	default:
508 		break;
509 	}
510 
511 	if (changed) {
512 		ctrl->state = new_state;
513 		wake_up_all(&ctrl->state_wq);
514 	}
515 
516 	spin_unlock_irqrestore(&ctrl->lock, flags);
517 	if (!changed)
518 		return false;
519 
520 	if (ctrl->state == NVME_CTRL_LIVE) {
521 		if (old_state == NVME_CTRL_CONNECTING)
522 			nvme_stop_failfast_work(ctrl);
523 		nvme_kick_requeue_lists(ctrl);
524 	} else if (ctrl->state == NVME_CTRL_CONNECTING &&
525 		old_state == NVME_CTRL_RESETTING) {
526 		nvme_start_failfast_work(ctrl);
527 	}
528 	return changed;
529 }
530 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
531 
532 /*
533  * Returns true for sink states that can't ever transition back to live.
534  */
535 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
536 {
537 	switch (ctrl->state) {
538 	case NVME_CTRL_NEW:
539 	case NVME_CTRL_LIVE:
540 	case NVME_CTRL_RESETTING:
541 	case NVME_CTRL_CONNECTING:
542 		return false;
543 	case NVME_CTRL_DELETING:
544 	case NVME_CTRL_DELETING_NOIO:
545 	case NVME_CTRL_DEAD:
546 		return true;
547 	default:
548 		WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
549 		return true;
550 	}
551 }
552 
553 /*
554  * Waits for the controller state to be resetting, or returns false if it is
555  * not possible to ever transition to that state.
556  */
557 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
558 {
559 	wait_event(ctrl->state_wq,
560 		   nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
561 		   nvme_state_terminal(ctrl));
562 	return ctrl->state == NVME_CTRL_RESETTING;
563 }
564 EXPORT_SYMBOL_GPL(nvme_wait_reset);
565 
566 static void nvme_free_ns_head(struct kref *ref)
567 {
568 	struct nvme_ns_head *head =
569 		container_of(ref, struct nvme_ns_head, ref);
570 
571 	nvme_mpath_remove_disk(head);
572 	ida_simple_remove(&head->subsys->ns_ida, head->instance);
573 	cleanup_srcu_struct(&head->srcu);
574 	nvme_put_subsystem(head->subsys);
575 	kfree(head);
576 }
577 
578 bool nvme_tryget_ns_head(struct nvme_ns_head *head)
579 {
580 	return kref_get_unless_zero(&head->ref);
581 }
582 
583 void nvme_put_ns_head(struct nvme_ns_head *head)
584 {
585 	kref_put(&head->ref, nvme_free_ns_head);
586 }
587 
588 static void nvme_free_ns(struct kref *kref)
589 {
590 	struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
591 
592 	put_disk(ns->disk);
593 	nvme_put_ns_head(ns->head);
594 	nvme_put_ctrl(ns->ctrl);
595 	kfree(ns);
596 }
597 
598 static inline bool nvme_get_ns(struct nvme_ns *ns)
599 {
600 	return kref_get_unless_zero(&ns->kref);
601 }
602 
603 void nvme_put_ns(struct nvme_ns *ns)
604 {
605 	kref_put(&ns->kref, nvme_free_ns);
606 }
607 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
608 
609 static inline void nvme_clear_nvme_request(struct request *req)
610 {
611 	nvme_req(req)->status = 0;
612 	nvme_req(req)->retries = 0;
613 	nvme_req(req)->flags = 0;
614 	req->rq_flags |= RQF_DONTPREP;
615 }
616 
617 static inline unsigned int nvme_req_op(struct nvme_command *cmd)
618 {
619 	return nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
620 }
621 
622 static inline void nvme_init_request(struct request *req,
623 		struct nvme_command *cmd)
624 {
625 	if (req->q->queuedata)
626 		req->timeout = NVME_IO_TIMEOUT;
627 	else /* no queuedata implies admin queue */
628 		req->timeout = NVME_ADMIN_TIMEOUT;
629 
630 	/* passthru commands should let the driver set the SGL flags */
631 	cmd->common.flags &= ~NVME_CMD_SGL_ALL;
632 
633 	req->cmd_flags |= REQ_FAILFAST_DRIVER;
634 	if (req->mq_hctx->type == HCTX_TYPE_POLL)
635 		req->cmd_flags |= REQ_HIPRI;
636 	nvme_clear_nvme_request(req);
637 	memcpy(nvme_req(req)->cmd, cmd, sizeof(*cmd));
638 }
639 
640 struct request *nvme_alloc_request(struct request_queue *q,
641 		struct nvme_command *cmd, blk_mq_req_flags_t flags)
642 {
643 	struct request *req;
644 
645 	req = blk_mq_alloc_request(q, nvme_req_op(cmd), flags);
646 	if (!IS_ERR(req))
647 		nvme_init_request(req, cmd);
648 	return req;
649 }
650 EXPORT_SYMBOL_GPL(nvme_alloc_request);
651 
652 static struct request *nvme_alloc_request_qid(struct request_queue *q,
653 		struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
654 {
655 	struct request *req;
656 
657 	req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), flags,
658 			qid ? qid - 1 : 0);
659 	if (!IS_ERR(req))
660 		nvme_init_request(req, cmd);
661 	return req;
662 }
663 
664 /*
665  * For something we're not in a state to send to the device the default action
666  * is to busy it and retry it after the controller state is recovered.  However,
667  * if the controller is deleting or if anything is marked for failfast or
668  * nvme multipath it is immediately failed.
669  *
670  * Note: commands used to initialize the controller will be marked for failfast.
671  * Note: nvme cli/ioctl commands are marked for failfast.
672  */
673 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl,
674 		struct request *rq)
675 {
676 	if (ctrl->state != NVME_CTRL_DELETING_NOIO &&
677 	    ctrl->state != NVME_CTRL_DEAD &&
678 	    !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) &&
679 	    !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
680 		return BLK_STS_RESOURCE;
681 	return nvme_host_path_error(rq);
682 }
683 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command);
684 
685 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
686 		bool queue_live)
687 {
688 	struct nvme_request *req = nvme_req(rq);
689 
690 	/*
691 	 * currently we have a problem sending passthru commands
692 	 * on the admin_q if the controller is not LIVE because we can't
693 	 * make sure that they are going out after the admin connect,
694 	 * controller enable and/or other commands in the initialization
695 	 * sequence. until the controller will be LIVE, fail with
696 	 * BLK_STS_RESOURCE so that they will be rescheduled.
697 	 */
698 	if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD))
699 		return false;
700 
701 	if (ctrl->ops->flags & NVME_F_FABRICS) {
702 		/*
703 		 * Only allow commands on a live queue, except for the connect
704 		 * command, which is require to set the queue live in the
705 		 * appropinquate states.
706 		 */
707 		switch (ctrl->state) {
708 		case NVME_CTRL_CONNECTING:
709 			if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) &&
710 			    req->cmd->fabrics.fctype == nvme_fabrics_type_connect)
711 				return true;
712 			break;
713 		default:
714 			break;
715 		case NVME_CTRL_DEAD:
716 			return false;
717 		}
718 	}
719 
720 	return queue_live;
721 }
722 EXPORT_SYMBOL_GPL(__nvme_check_ready);
723 
724 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
725 {
726 	struct nvme_command c = { };
727 
728 	c.directive.opcode = nvme_admin_directive_send;
729 	c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
730 	c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
731 	c.directive.dtype = NVME_DIR_IDENTIFY;
732 	c.directive.tdtype = NVME_DIR_STREAMS;
733 	c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
734 
735 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
736 }
737 
738 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
739 {
740 	return nvme_toggle_streams(ctrl, false);
741 }
742 
743 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
744 {
745 	return nvme_toggle_streams(ctrl, true);
746 }
747 
748 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
749 				  struct streams_directive_params *s, u32 nsid)
750 {
751 	struct nvme_command c = { };
752 
753 	memset(s, 0, sizeof(*s));
754 
755 	c.directive.opcode = nvme_admin_directive_recv;
756 	c.directive.nsid = cpu_to_le32(nsid);
757 	c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
758 	c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
759 	c.directive.dtype = NVME_DIR_STREAMS;
760 
761 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
762 }
763 
764 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
765 {
766 	struct streams_directive_params s;
767 	int ret;
768 
769 	if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
770 		return 0;
771 	if (!streams)
772 		return 0;
773 
774 	ret = nvme_enable_streams(ctrl);
775 	if (ret)
776 		return ret;
777 
778 	ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
779 	if (ret)
780 		goto out_disable_stream;
781 
782 	ctrl->nssa = le16_to_cpu(s.nssa);
783 	if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
784 		dev_info(ctrl->device, "too few streams (%u) available\n",
785 					ctrl->nssa);
786 		goto out_disable_stream;
787 	}
788 
789 	ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
790 	dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
791 	return 0;
792 
793 out_disable_stream:
794 	nvme_disable_streams(ctrl);
795 	return ret;
796 }
797 
798 /*
799  * Check if 'req' has a write hint associated with it. If it does, assign
800  * a valid namespace stream to the write.
801  */
802 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
803 				     struct request *req, u16 *control,
804 				     u32 *dsmgmt)
805 {
806 	enum rw_hint streamid = req->write_hint;
807 
808 	if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
809 		streamid = 0;
810 	else {
811 		streamid--;
812 		if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
813 			return;
814 
815 		*control |= NVME_RW_DTYPE_STREAMS;
816 		*dsmgmt |= streamid << 16;
817 	}
818 
819 	if (streamid < ARRAY_SIZE(req->q->write_hints))
820 		req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
821 }
822 
823 static inline void nvme_setup_flush(struct nvme_ns *ns,
824 		struct nvme_command *cmnd)
825 {
826 	cmnd->common.opcode = nvme_cmd_flush;
827 	cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
828 }
829 
830 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
831 		struct nvme_command *cmnd)
832 {
833 	unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
834 	struct nvme_dsm_range *range;
835 	struct bio *bio;
836 
837 	/*
838 	 * Some devices do not consider the DSM 'Number of Ranges' field when
839 	 * determining how much data to DMA. Always allocate memory for maximum
840 	 * number of segments to prevent device reading beyond end of buffer.
841 	 */
842 	static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
843 
844 	range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
845 	if (!range) {
846 		/*
847 		 * If we fail allocation our range, fallback to the controller
848 		 * discard page. If that's also busy, it's safe to return
849 		 * busy, as we know we can make progress once that's freed.
850 		 */
851 		if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
852 			return BLK_STS_RESOURCE;
853 
854 		range = page_address(ns->ctrl->discard_page);
855 	}
856 
857 	__rq_for_each_bio(bio, req) {
858 		u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
859 		u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
860 
861 		if (n < segments) {
862 			range[n].cattr = cpu_to_le32(0);
863 			range[n].nlb = cpu_to_le32(nlb);
864 			range[n].slba = cpu_to_le64(slba);
865 		}
866 		n++;
867 	}
868 
869 	if (WARN_ON_ONCE(n != segments)) {
870 		if (virt_to_page(range) == ns->ctrl->discard_page)
871 			clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
872 		else
873 			kfree(range);
874 		return BLK_STS_IOERR;
875 	}
876 
877 	cmnd->dsm.opcode = nvme_cmd_dsm;
878 	cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
879 	cmnd->dsm.nr = cpu_to_le32(segments - 1);
880 	cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
881 
882 	req->special_vec.bv_page = virt_to_page(range);
883 	req->special_vec.bv_offset = offset_in_page(range);
884 	req->special_vec.bv_len = alloc_size;
885 	req->rq_flags |= RQF_SPECIAL_PAYLOAD;
886 
887 	return BLK_STS_OK;
888 }
889 
890 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
891 		struct request *req, struct nvme_command *cmnd)
892 {
893 	if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
894 		return nvme_setup_discard(ns, req, cmnd);
895 
896 	cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
897 	cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
898 	cmnd->write_zeroes.slba =
899 		cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
900 	cmnd->write_zeroes.length =
901 		cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
902 	if (nvme_ns_has_pi(ns))
903 		cmnd->write_zeroes.control = cpu_to_le16(NVME_RW_PRINFO_PRACT);
904 	else
905 		cmnd->write_zeroes.control = 0;
906 	return BLK_STS_OK;
907 }
908 
909 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
910 		struct request *req, struct nvme_command *cmnd,
911 		enum nvme_opcode op)
912 {
913 	struct nvme_ctrl *ctrl = ns->ctrl;
914 	u16 control = 0;
915 	u32 dsmgmt = 0;
916 
917 	if (req->cmd_flags & REQ_FUA)
918 		control |= NVME_RW_FUA;
919 	if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
920 		control |= NVME_RW_LR;
921 
922 	if (req->cmd_flags & REQ_RAHEAD)
923 		dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
924 
925 	cmnd->rw.opcode = op;
926 	cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
927 	cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
928 	cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
929 
930 	if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
931 		nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
932 
933 	if (ns->ms) {
934 		/*
935 		 * If formated with metadata, the block layer always provides a
936 		 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled.  Else
937 		 * we enable the PRACT bit for protection information or set the
938 		 * namespace capacity to zero to prevent any I/O.
939 		 */
940 		if (!blk_integrity_rq(req)) {
941 			if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
942 				return BLK_STS_NOTSUPP;
943 			control |= NVME_RW_PRINFO_PRACT;
944 		}
945 
946 		switch (ns->pi_type) {
947 		case NVME_NS_DPS_PI_TYPE3:
948 			control |= NVME_RW_PRINFO_PRCHK_GUARD;
949 			break;
950 		case NVME_NS_DPS_PI_TYPE1:
951 		case NVME_NS_DPS_PI_TYPE2:
952 			control |= NVME_RW_PRINFO_PRCHK_GUARD |
953 					NVME_RW_PRINFO_PRCHK_REF;
954 			if (op == nvme_cmd_zone_append)
955 				control |= NVME_RW_APPEND_PIREMAP;
956 			cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
957 			break;
958 		}
959 	}
960 
961 	cmnd->rw.control = cpu_to_le16(control);
962 	cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
963 	return 0;
964 }
965 
966 void nvme_cleanup_cmd(struct request *req)
967 {
968 	if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
969 		struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
970 
971 		if (req->special_vec.bv_page == ctrl->discard_page)
972 			clear_bit_unlock(0, &ctrl->discard_page_busy);
973 		else
974 			kfree(bvec_virt(&req->special_vec));
975 	}
976 }
977 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
978 
979 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
980 {
981 	struct nvme_command *cmd = nvme_req(req)->cmd;
982 	blk_status_t ret = BLK_STS_OK;
983 
984 	if (!(req->rq_flags & RQF_DONTPREP)) {
985 		nvme_clear_nvme_request(req);
986 		memset(cmd, 0, sizeof(*cmd));
987 	}
988 
989 	switch (req_op(req)) {
990 	case REQ_OP_DRV_IN:
991 	case REQ_OP_DRV_OUT:
992 		/* these are setup prior to execution in nvme_init_request() */
993 		break;
994 	case REQ_OP_FLUSH:
995 		nvme_setup_flush(ns, cmd);
996 		break;
997 	case REQ_OP_ZONE_RESET_ALL:
998 	case REQ_OP_ZONE_RESET:
999 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
1000 		break;
1001 	case REQ_OP_ZONE_OPEN:
1002 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
1003 		break;
1004 	case REQ_OP_ZONE_CLOSE:
1005 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
1006 		break;
1007 	case REQ_OP_ZONE_FINISH:
1008 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
1009 		break;
1010 	case REQ_OP_WRITE_ZEROES:
1011 		ret = nvme_setup_write_zeroes(ns, req, cmd);
1012 		break;
1013 	case REQ_OP_DISCARD:
1014 		ret = nvme_setup_discard(ns, req, cmd);
1015 		break;
1016 	case REQ_OP_READ:
1017 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
1018 		break;
1019 	case REQ_OP_WRITE:
1020 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
1021 		break;
1022 	case REQ_OP_ZONE_APPEND:
1023 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
1024 		break;
1025 	default:
1026 		WARN_ON_ONCE(1);
1027 		return BLK_STS_IOERR;
1028 	}
1029 
1030 	nvme_req(req)->genctr++;
1031 	cmd->common.command_id = nvme_cid(req);
1032 	trace_nvme_setup_cmd(req, cmd);
1033 	return ret;
1034 }
1035 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
1036 
1037 /*
1038  * Return values:
1039  * 0:  success
1040  * >0: nvme controller's cqe status response
1041  * <0: kernel error in lieu of controller response
1042  */
1043 static int nvme_execute_rq(struct gendisk *disk, struct request *rq,
1044 		bool at_head)
1045 {
1046 	blk_status_t status;
1047 
1048 	status = blk_execute_rq(disk, rq, at_head);
1049 	if (nvme_req(rq)->flags & NVME_REQ_CANCELLED)
1050 		return -EINTR;
1051 	if (nvme_req(rq)->status)
1052 		return nvme_req(rq)->status;
1053 	return blk_status_to_errno(status);
1054 }
1055 
1056 /*
1057  * Returns 0 on success.  If the result is negative, it's a Linux error code;
1058  * if the result is positive, it's an NVM Express status code
1059  */
1060 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1061 		union nvme_result *result, void *buffer, unsigned bufflen,
1062 		unsigned timeout, int qid, int at_head,
1063 		blk_mq_req_flags_t flags)
1064 {
1065 	struct request *req;
1066 	int ret;
1067 
1068 	if (qid == NVME_QID_ANY)
1069 		req = nvme_alloc_request(q, cmd, flags);
1070 	else
1071 		req = nvme_alloc_request_qid(q, cmd, flags, qid);
1072 	if (IS_ERR(req))
1073 		return PTR_ERR(req);
1074 
1075 	if (timeout)
1076 		req->timeout = timeout;
1077 
1078 	if (buffer && bufflen) {
1079 		ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
1080 		if (ret)
1081 			goto out;
1082 	}
1083 
1084 	ret = nvme_execute_rq(NULL, req, at_head);
1085 	if (result && ret >= 0)
1086 		*result = nvme_req(req)->result;
1087  out:
1088 	blk_mq_free_request(req);
1089 	return ret;
1090 }
1091 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
1092 
1093 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1094 		void *buffer, unsigned bufflen)
1095 {
1096 	return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
1097 			NVME_QID_ANY, 0, 0);
1098 }
1099 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
1100 
1101 static u32 nvme_known_admin_effects(u8 opcode)
1102 {
1103 	switch (opcode) {
1104 	case nvme_admin_format_nvm:
1105 		return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_NCC |
1106 			NVME_CMD_EFFECTS_CSE_MASK;
1107 	case nvme_admin_sanitize_nvm:
1108 		return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK;
1109 	default:
1110 		break;
1111 	}
1112 	return 0;
1113 }
1114 
1115 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1116 {
1117 	u32 effects = 0;
1118 
1119 	if (ns) {
1120 		if (ns->head->effects)
1121 			effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
1122 		if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1123 			dev_warn_once(ctrl->device,
1124 				"IO command:%02x has unhandled effects:%08x\n",
1125 				opcode, effects);
1126 		return 0;
1127 	}
1128 
1129 	if (ctrl->effects)
1130 		effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1131 	effects |= nvme_known_admin_effects(opcode);
1132 
1133 	return effects;
1134 }
1135 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
1136 
1137 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1138 			       u8 opcode)
1139 {
1140 	u32 effects = nvme_command_effects(ctrl, ns, opcode);
1141 
1142 	/*
1143 	 * For simplicity, IO to all namespaces is quiesced even if the command
1144 	 * effects say only one namespace is affected.
1145 	 */
1146 	if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1147 		mutex_lock(&ctrl->scan_lock);
1148 		mutex_lock(&ctrl->subsys->lock);
1149 		nvme_mpath_start_freeze(ctrl->subsys);
1150 		nvme_mpath_wait_freeze(ctrl->subsys);
1151 		nvme_start_freeze(ctrl);
1152 		nvme_wait_freeze(ctrl);
1153 	}
1154 	return effects;
1155 }
1156 
1157 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects,
1158 			      struct nvme_command *cmd, int status)
1159 {
1160 	if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1161 		nvme_unfreeze(ctrl);
1162 		nvme_mpath_unfreeze(ctrl->subsys);
1163 		mutex_unlock(&ctrl->subsys->lock);
1164 		nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1165 		mutex_unlock(&ctrl->scan_lock);
1166 	}
1167 	if (effects & NVME_CMD_EFFECTS_CCC)
1168 		nvme_init_ctrl_finish(ctrl);
1169 	if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1170 		nvme_queue_scan(ctrl);
1171 		flush_work(&ctrl->scan_work);
1172 	}
1173 
1174 	switch (cmd->common.opcode) {
1175 	case nvme_admin_set_features:
1176 		switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) {
1177 		case NVME_FEAT_KATO:
1178 			/*
1179 			 * Keep alive commands interval on the host should be
1180 			 * updated when KATO is modified by Set Features
1181 			 * commands.
1182 			 */
1183 			if (!status)
1184 				nvme_update_keep_alive(ctrl, cmd);
1185 			break;
1186 		default:
1187 			break;
1188 		}
1189 		break;
1190 	default:
1191 		break;
1192 	}
1193 }
1194 
1195 int nvme_execute_passthru_rq(struct request *rq)
1196 {
1197 	struct nvme_command *cmd = nvme_req(rq)->cmd;
1198 	struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl;
1199 	struct nvme_ns *ns = rq->q->queuedata;
1200 	struct gendisk *disk = ns ? ns->disk : NULL;
1201 	u32 effects;
1202 	int  ret;
1203 
1204 	effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode);
1205 	ret = nvme_execute_rq(disk, rq, false);
1206 	if (effects) /* nothing to be done for zero cmd effects */
1207 		nvme_passthru_end(ctrl, effects, cmd, ret);
1208 
1209 	return ret;
1210 }
1211 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU);
1212 
1213 /*
1214  * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
1215  *
1216  *   The host should send Keep Alive commands at half of the Keep Alive Timeout
1217  *   accounting for transport roundtrip times [..].
1218  */
1219 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
1220 {
1221 	queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ / 2);
1222 }
1223 
1224 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
1225 {
1226 	struct nvme_ctrl *ctrl = rq->end_io_data;
1227 	unsigned long flags;
1228 	bool startka = false;
1229 
1230 	blk_mq_free_request(rq);
1231 
1232 	if (status) {
1233 		dev_err(ctrl->device,
1234 			"failed nvme_keep_alive_end_io error=%d\n",
1235 				status);
1236 		return;
1237 	}
1238 
1239 	ctrl->comp_seen = false;
1240 	spin_lock_irqsave(&ctrl->lock, flags);
1241 	if (ctrl->state == NVME_CTRL_LIVE ||
1242 	    ctrl->state == NVME_CTRL_CONNECTING)
1243 		startka = true;
1244 	spin_unlock_irqrestore(&ctrl->lock, flags);
1245 	if (startka)
1246 		nvme_queue_keep_alive_work(ctrl);
1247 }
1248 
1249 static void nvme_keep_alive_work(struct work_struct *work)
1250 {
1251 	struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1252 			struct nvme_ctrl, ka_work);
1253 	bool comp_seen = ctrl->comp_seen;
1254 	struct request *rq;
1255 
1256 	if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1257 		dev_dbg(ctrl->device,
1258 			"reschedule traffic based keep-alive timer\n");
1259 		ctrl->comp_seen = false;
1260 		nvme_queue_keep_alive_work(ctrl);
1261 		return;
1262 	}
1263 
1264 	rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd,
1265 				BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
1266 	if (IS_ERR(rq)) {
1267 		/* allocation failure, reset the controller */
1268 		dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
1269 		nvme_reset_ctrl(ctrl);
1270 		return;
1271 	}
1272 
1273 	rq->timeout = ctrl->kato * HZ;
1274 	rq->end_io_data = ctrl;
1275 	blk_execute_rq_nowait(NULL, rq, 0, nvme_keep_alive_end_io);
1276 }
1277 
1278 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1279 {
1280 	if (unlikely(ctrl->kato == 0))
1281 		return;
1282 
1283 	nvme_queue_keep_alive_work(ctrl);
1284 }
1285 
1286 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1287 {
1288 	if (unlikely(ctrl->kato == 0))
1289 		return;
1290 
1291 	cancel_delayed_work_sync(&ctrl->ka_work);
1292 }
1293 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1294 
1295 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
1296 				   struct nvme_command *cmd)
1297 {
1298 	unsigned int new_kato =
1299 		DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000);
1300 
1301 	dev_info(ctrl->device,
1302 		 "keep alive interval updated from %u ms to %u ms\n",
1303 		 ctrl->kato * 1000 / 2, new_kato * 1000 / 2);
1304 
1305 	nvme_stop_keep_alive(ctrl);
1306 	ctrl->kato = new_kato;
1307 	nvme_start_keep_alive(ctrl);
1308 }
1309 
1310 /*
1311  * In NVMe 1.0 the CNS field was just a binary controller or namespace
1312  * flag, thus sending any new CNS opcodes has a big chance of not working.
1313  * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1314  * (but not for any later version).
1315  */
1316 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1317 {
1318 	if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1319 		return ctrl->vs < NVME_VS(1, 2, 0);
1320 	return ctrl->vs < NVME_VS(1, 1, 0);
1321 }
1322 
1323 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1324 {
1325 	struct nvme_command c = { };
1326 	int error;
1327 
1328 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1329 	c.identify.opcode = nvme_admin_identify;
1330 	c.identify.cns = NVME_ID_CNS_CTRL;
1331 
1332 	*id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1333 	if (!*id)
1334 		return -ENOMEM;
1335 
1336 	error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1337 			sizeof(struct nvme_id_ctrl));
1338 	if (error)
1339 		kfree(*id);
1340 	return error;
1341 }
1342 
1343 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1344 		struct nvme_ns_id_desc *cur, bool *csi_seen)
1345 {
1346 	const char *warn_str = "ctrl returned bogus length:";
1347 	void *data = cur;
1348 
1349 	switch (cur->nidt) {
1350 	case NVME_NIDT_EUI64:
1351 		if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1352 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1353 				 warn_str, cur->nidl);
1354 			return -1;
1355 		}
1356 		memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1357 		return NVME_NIDT_EUI64_LEN;
1358 	case NVME_NIDT_NGUID:
1359 		if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1360 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1361 				 warn_str, cur->nidl);
1362 			return -1;
1363 		}
1364 		memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1365 		return NVME_NIDT_NGUID_LEN;
1366 	case NVME_NIDT_UUID:
1367 		if (cur->nidl != NVME_NIDT_UUID_LEN) {
1368 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1369 				 warn_str, cur->nidl);
1370 			return -1;
1371 		}
1372 		uuid_copy(&ids->uuid, data + sizeof(*cur));
1373 		return NVME_NIDT_UUID_LEN;
1374 	case NVME_NIDT_CSI:
1375 		if (cur->nidl != NVME_NIDT_CSI_LEN) {
1376 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1377 				 warn_str, cur->nidl);
1378 			return -1;
1379 		}
1380 		memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1381 		*csi_seen = true;
1382 		return NVME_NIDT_CSI_LEN;
1383 	default:
1384 		/* Skip unknown types */
1385 		return cur->nidl;
1386 	}
1387 }
1388 
1389 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1390 		struct nvme_ns_ids *ids)
1391 {
1392 	struct nvme_command c = { };
1393 	bool csi_seen = false;
1394 	int status, pos, len;
1395 	void *data;
1396 
1397 	if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
1398 		return 0;
1399 	if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1400 		return 0;
1401 
1402 	c.identify.opcode = nvme_admin_identify;
1403 	c.identify.nsid = cpu_to_le32(nsid);
1404 	c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1405 
1406 	data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1407 	if (!data)
1408 		return -ENOMEM;
1409 
1410 	status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1411 				      NVME_IDENTIFY_DATA_SIZE);
1412 	if (status) {
1413 		dev_warn(ctrl->device,
1414 			"Identify Descriptors failed (nsid=%u, status=0x%x)\n",
1415 			nsid, status);
1416 		goto free_data;
1417 	}
1418 
1419 	for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1420 		struct nvme_ns_id_desc *cur = data + pos;
1421 
1422 		if (cur->nidl == 0)
1423 			break;
1424 
1425 		len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1426 		if (len < 0)
1427 			break;
1428 
1429 		len += sizeof(*cur);
1430 	}
1431 
1432 	if (nvme_multi_css(ctrl) && !csi_seen) {
1433 		dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1434 			 nsid);
1435 		status = -EINVAL;
1436 	}
1437 
1438 free_data:
1439 	kfree(data);
1440 	return status;
1441 }
1442 
1443 static int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
1444 			struct nvme_ns_ids *ids, struct nvme_id_ns **id)
1445 {
1446 	struct nvme_command c = { };
1447 	int error;
1448 
1449 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1450 	c.identify.opcode = nvme_admin_identify;
1451 	c.identify.nsid = cpu_to_le32(nsid);
1452 	c.identify.cns = NVME_ID_CNS_NS;
1453 
1454 	*id = kmalloc(sizeof(**id), GFP_KERNEL);
1455 	if (!*id)
1456 		return -ENOMEM;
1457 
1458 	error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1459 	if (error) {
1460 		dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1461 		goto out_free_id;
1462 	}
1463 
1464 	error = NVME_SC_INVALID_NS | NVME_SC_DNR;
1465 	if ((*id)->ncap == 0) /* namespace not allocated or attached */
1466 		goto out_free_id;
1467 
1468 	if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1469 	    !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
1470 		memcpy(ids->eui64, (*id)->eui64, sizeof(ids->eui64));
1471 	if (ctrl->vs >= NVME_VS(1, 2, 0) &&
1472 	    !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
1473 		memcpy(ids->nguid, (*id)->nguid, sizeof(ids->nguid));
1474 
1475 	return 0;
1476 
1477 out_free_id:
1478 	kfree(*id);
1479 	return error;
1480 }
1481 
1482 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1483 		unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1484 {
1485 	union nvme_result res = { 0 };
1486 	struct nvme_command c = { };
1487 	int ret;
1488 
1489 	c.features.opcode = op;
1490 	c.features.fid = cpu_to_le32(fid);
1491 	c.features.dword11 = cpu_to_le32(dword11);
1492 
1493 	ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1494 			buffer, buflen, 0, NVME_QID_ANY, 0, 0);
1495 	if (ret >= 0 && result)
1496 		*result = le32_to_cpu(res.u32);
1497 	return ret;
1498 }
1499 
1500 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1501 		      unsigned int dword11, void *buffer, size_t buflen,
1502 		      u32 *result)
1503 {
1504 	return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1505 			     buflen, result);
1506 }
1507 EXPORT_SYMBOL_GPL(nvme_set_features);
1508 
1509 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1510 		      unsigned int dword11, void *buffer, size_t buflen,
1511 		      u32 *result)
1512 {
1513 	return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1514 			     buflen, result);
1515 }
1516 EXPORT_SYMBOL_GPL(nvme_get_features);
1517 
1518 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1519 {
1520 	u32 q_count = (*count - 1) | ((*count - 1) << 16);
1521 	u32 result;
1522 	int status, nr_io_queues;
1523 
1524 	status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1525 			&result);
1526 	if (status < 0)
1527 		return status;
1528 
1529 	/*
1530 	 * Degraded controllers might return an error when setting the queue
1531 	 * count.  We still want to be able to bring them online and offer
1532 	 * access to the admin queue, as that might be only way to fix them up.
1533 	 */
1534 	if (status > 0) {
1535 		dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1536 		*count = 0;
1537 	} else {
1538 		nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1539 		*count = min(*count, nr_io_queues);
1540 	}
1541 
1542 	return 0;
1543 }
1544 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1545 
1546 #define NVME_AEN_SUPPORTED \
1547 	(NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1548 	 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1549 
1550 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1551 {
1552 	u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1553 	int status;
1554 
1555 	if (!supported_aens)
1556 		return;
1557 
1558 	status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1559 			NULL, 0, &result);
1560 	if (status)
1561 		dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1562 			 supported_aens);
1563 
1564 	queue_work(nvme_wq, &ctrl->async_event_work);
1565 }
1566 
1567 static int nvme_ns_open(struct nvme_ns *ns)
1568 {
1569 
1570 	/* should never be called due to GENHD_FL_HIDDEN */
1571 	if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
1572 		goto fail;
1573 	if (!nvme_get_ns(ns))
1574 		goto fail;
1575 	if (!try_module_get(ns->ctrl->ops->module))
1576 		goto fail_put_ns;
1577 
1578 	return 0;
1579 
1580 fail_put_ns:
1581 	nvme_put_ns(ns);
1582 fail:
1583 	return -ENXIO;
1584 }
1585 
1586 static void nvme_ns_release(struct nvme_ns *ns)
1587 {
1588 
1589 	module_put(ns->ctrl->ops->module);
1590 	nvme_put_ns(ns);
1591 }
1592 
1593 static int nvme_open(struct block_device *bdev, fmode_t mode)
1594 {
1595 	return nvme_ns_open(bdev->bd_disk->private_data);
1596 }
1597 
1598 static void nvme_release(struct gendisk *disk, fmode_t mode)
1599 {
1600 	nvme_ns_release(disk->private_data);
1601 }
1602 
1603 int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1604 {
1605 	/* some standard values */
1606 	geo->heads = 1 << 6;
1607 	geo->sectors = 1 << 5;
1608 	geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1609 	return 0;
1610 }
1611 
1612 #ifdef CONFIG_BLK_DEV_INTEGRITY
1613 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1614 				u32 max_integrity_segments)
1615 {
1616 	struct blk_integrity integrity = { };
1617 
1618 	switch (pi_type) {
1619 	case NVME_NS_DPS_PI_TYPE3:
1620 		integrity.profile = &t10_pi_type3_crc;
1621 		integrity.tag_size = sizeof(u16) + sizeof(u32);
1622 		integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1623 		break;
1624 	case NVME_NS_DPS_PI_TYPE1:
1625 	case NVME_NS_DPS_PI_TYPE2:
1626 		integrity.profile = &t10_pi_type1_crc;
1627 		integrity.tag_size = sizeof(u16);
1628 		integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1629 		break;
1630 	default:
1631 		integrity.profile = NULL;
1632 		break;
1633 	}
1634 	integrity.tuple_size = ms;
1635 	blk_integrity_register(disk, &integrity);
1636 	blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1637 }
1638 #else
1639 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1640 				u32 max_integrity_segments)
1641 {
1642 }
1643 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1644 
1645 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1646 {
1647 	struct nvme_ctrl *ctrl = ns->ctrl;
1648 	struct request_queue *queue = disk->queue;
1649 	u32 size = queue_logical_block_size(queue);
1650 
1651 	if (ctrl->max_discard_sectors == 0) {
1652 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1653 		return;
1654 	}
1655 
1656 	if (ctrl->nr_streams && ns->sws && ns->sgs)
1657 		size *= ns->sws * ns->sgs;
1658 
1659 	BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1660 			NVME_DSM_MAX_RANGES);
1661 
1662 	queue->limits.discard_alignment = 0;
1663 	queue->limits.discard_granularity = size;
1664 
1665 	/* If discard is already enabled, don't reset queue limits */
1666 	if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1667 		return;
1668 
1669 	blk_queue_max_discard_sectors(queue, ctrl->max_discard_sectors);
1670 	blk_queue_max_discard_segments(queue, ctrl->max_discard_segments);
1671 
1672 	if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1673 		blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1674 }
1675 
1676 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1677 {
1678 	return !uuid_is_null(&ids->uuid) ||
1679 		memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1680 		memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1681 }
1682 
1683 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1684 {
1685 	return uuid_equal(&a->uuid, &b->uuid) &&
1686 		memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1687 		memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1688 		a->csi == b->csi;
1689 }
1690 
1691 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1692 				 u32 *phys_bs, u32 *io_opt)
1693 {
1694 	struct streams_directive_params s;
1695 	int ret;
1696 
1697 	if (!ctrl->nr_streams)
1698 		return 0;
1699 
1700 	ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1701 	if (ret)
1702 		return ret;
1703 
1704 	ns->sws = le32_to_cpu(s.sws);
1705 	ns->sgs = le16_to_cpu(s.sgs);
1706 
1707 	if (ns->sws) {
1708 		*phys_bs = ns->sws * (1 << ns->lba_shift);
1709 		if (ns->sgs)
1710 			*io_opt = *phys_bs * ns->sgs;
1711 	}
1712 
1713 	return 0;
1714 }
1715 
1716 static int nvme_configure_metadata(struct nvme_ns *ns, struct nvme_id_ns *id)
1717 {
1718 	struct nvme_ctrl *ctrl = ns->ctrl;
1719 
1720 	/*
1721 	 * The PI implementation requires the metadata size to be equal to the
1722 	 * t10 pi tuple size.
1723 	 */
1724 	ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1725 	if (ns->ms == sizeof(struct t10_pi_tuple))
1726 		ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1727 	else
1728 		ns->pi_type = 0;
1729 
1730 	ns->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1731 	if (!ns->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1732 		return 0;
1733 	if (ctrl->ops->flags & NVME_F_FABRICS) {
1734 		/*
1735 		 * The NVMe over Fabrics specification only supports metadata as
1736 		 * part of the extended data LBA.  We rely on HCA/HBA support to
1737 		 * remap the separate metadata buffer from the block layer.
1738 		 */
1739 		if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
1740 			return -EINVAL;
1741 		if (ctrl->max_integrity_segments)
1742 			ns->features |=
1743 				(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1744 	} else {
1745 		/*
1746 		 * For PCIe controllers, we can't easily remap the separate
1747 		 * metadata buffer from the block layer and thus require a
1748 		 * separate metadata buffer for block layer metadata/PI support.
1749 		 * We allow extended LBAs for the passthrough interface, though.
1750 		 */
1751 		if (id->flbas & NVME_NS_FLBAS_META_EXT)
1752 			ns->features |= NVME_NS_EXT_LBAS;
1753 		else
1754 			ns->features |= NVME_NS_METADATA_SUPPORTED;
1755 	}
1756 
1757 	return 0;
1758 }
1759 
1760 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1761 		struct request_queue *q)
1762 {
1763 	bool vwc = ctrl->vwc & NVME_CTRL_VWC_PRESENT;
1764 
1765 	if (ctrl->max_hw_sectors) {
1766 		u32 max_segments =
1767 			(ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
1768 
1769 		max_segments = min_not_zero(max_segments, ctrl->max_segments);
1770 		blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1771 		blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1772 	}
1773 	blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
1774 	blk_queue_dma_alignment(q, 7);
1775 	blk_queue_write_cache(q, vwc, vwc);
1776 }
1777 
1778 static void nvme_update_disk_info(struct gendisk *disk,
1779 		struct nvme_ns *ns, struct nvme_id_ns *id)
1780 {
1781 	sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1782 	unsigned short bs = 1 << ns->lba_shift;
1783 	u32 atomic_bs, phys_bs, io_opt = 0;
1784 
1785 	/*
1786 	 * The block layer can't support LBA sizes larger than the page size
1787 	 * yet, so catch this early and don't allow block I/O.
1788 	 */
1789 	if (ns->lba_shift > PAGE_SHIFT) {
1790 		capacity = 0;
1791 		bs = (1 << 9);
1792 	}
1793 
1794 	blk_integrity_unregister(disk);
1795 
1796 	atomic_bs = phys_bs = bs;
1797 	nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1798 	if (id->nabo == 0) {
1799 		/*
1800 		 * Bit 1 indicates whether NAWUPF is defined for this namespace
1801 		 * and whether it should be used instead of AWUPF. If NAWUPF ==
1802 		 * 0 then AWUPF must be used instead.
1803 		 */
1804 		if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1805 			atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1806 		else
1807 			atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1808 	}
1809 
1810 	if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1811 		/* NPWG = Namespace Preferred Write Granularity */
1812 		phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1813 		/* NOWS = Namespace Optimal Write Size */
1814 		io_opt = bs * (1 + le16_to_cpu(id->nows));
1815 	}
1816 
1817 	blk_queue_logical_block_size(disk->queue, bs);
1818 	/*
1819 	 * Linux filesystems assume writing a single physical block is
1820 	 * an atomic operation. Hence limit the physical block size to the
1821 	 * value of the Atomic Write Unit Power Fail parameter.
1822 	 */
1823 	blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1824 	blk_queue_io_min(disk->queue, phys_bs);
1825 	blk_queue_io_opt(disk->queue, io_opt);
1826 
1827 	/*
1828 	 * Register a metadata profile for PI, or the plain non-integrity NVMe
1829 	 * metadata masquerading as Type 0 if supported, otherwise reject block
1830 	 * I/O to namespaces with metadata except when the namespace supports
1831 	 * PI, as it can strip/insert in that case.
1832 	 */
1833 	if (ns->ms) {
1834 		if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
1835 		    (ns->features & NVME_NS_METADATA_SUPPORTED))
1836 			nvme_init_integrity(disk, ns->ms, ns->pi_type,
1837 					    ns->ctrl->max_integrity_segments);
1838 		else if (!nvme_ns_has_pi(ns))
1839 			capacity = 0;
1840 	}
1841 
1842 	set_capacity_and_notify(disk, capacity);
1843 
1844 	nvme_config_discard(disk, ns);
1845 	blk_queue_max_write_zeroes_sectors(disk->queue,
1846 					   ns->ctrl->max_zeroes_sectors);
1847 
1848 	set_disk_ro(disk, (id->nsattr & NVME_NS_ATTR_RO) ||
1849 		test_bit(NVME_NS_FORCE_RO, &ns->flags));
1850 }
1851 
1852 static inline bool nvme_first_scan(struct gendisk *disk)
1853 {
1854 	/* nvme_alloc_ns() scans the disk prior to adding it */
1855 	return !disk_live(disk);
1856 }
1857 
1858 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id)
1859 {
1860 	struct nvme_ctrl *ctrl = ns->ctrl;
1861 	u32 iob;
1862 
1863 	if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1864 	    is_power_of_2(ctrl->max_hw_sectors))
1865 		iob = ctrl->max_hw_sectors;
1866 	else
1867 		iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
1868 
1869 	if (!iob)
1870 		return;
1871 
1872 	if (!is_power_of_2(iob)) {
1873 		if (nvme_first_scan(ns->disk))
1874 			pr_warn("%s: ignoring unaligned IO boundary:%u\n",
1875 				ns->disk->disk_name, iob);
1876 		return;
1877 	}
1878 
1879 	if (blk_queue_is_zoned(ns->disk->queue)) {
1880 		if (nvme_first_scan(ns->disk))
1881 			pr_warn("%s: ignoring zoned namespace IO boundary\n",
1882 				ns->disk->disk_name);
1883 		return;
1884 	}
1885 
1886 	blk_queue_chunk_sectors(ns->queue, iob);
1887 }
1888 
1889 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_id_ns *id)
1890 {
1891 	unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
1892 	int ret;
1893 
1894 	blk_mq_freeze_queue(ns->disk->queue);
1895 	ns->lba_shift = id->lbaf[lbaf].ds;
1896 	nvme_set_queue_limits(ns->ctrl, ns->queue);
1897 
1898 	ret = nvme_configure_metadata(ns, id);
1899 	if (ret)
1900 		goto out_unfreeze;
1901 	nvme_set_chunk_sectors(ns, id);
1902 	nvme_update_disk_info(ns->disk, ns, id);
1903 
1904 	if (ns->head->ids.csi == NVME_CSI_ZNS) {
1905 		ret = nvme_update_zone_info(ns, lbaf);
1906 		if (ret)
1907 			goto out_unfreeze;
1908 	}
1909 
1910 	set_bit(NVME_NS_READY, &ns->flags);
1911 	blk_mq_unfreeze_queue(ns->disk->queue);
1912 
1913 	if (blk_queue_is_zoned(ns->queue)) {
1914 		ret = nvme_revalidate_zones(ns);
1915 		if (ret && !nvme_first_scan(ns->disk))
1916 			goto out;
1917 	}
1918 
1919 	if (nvme_ns_head_multipath(ns->head)) {
1920 		blk_mq_freeze_queue(ns->head->disk->queue);
1921 		nvme_update_disk_info(ns->head->disk, ns, id);
1922 		nvme_mpath_revalidate_paths(ns);
1923 		blk_stack_limits(&ns->head->disk->queue->limits,
1924 				 &ns->queue->limits, 0);
1925 		disk_update_readahead(ns->head->disk);
1926 		blk_mq_unfreeze_queue(ns->head->disk->queue);
1927 	}
1928 	return 0;
1929 
1930 out_unfreeze:
1931 	blk_mq_unfreeze_queue(ns->disk->queue);
1932 out:
1933 	/*
1934 	 * If probing fails due an unsupported feature, hide the block device,
1935 	 * but still allow other access.
1936 	 */
1937 	if (ret == -ENODEV) {
1938 		ns->disk->flags |= GENHD_FL_HIDDEN;
1939 		ret = 0;
1940 	}
1941 	return ret;
1942 }
1943 
1944 static char nvme_pr_type(enum pr_type type)
1945 {
1946 	switch (type) {
1947 	case PR_WRITE_EXCLUSIVE:
1948 		return 1;
1949 	case PR_EXCLUSIVE_ACCESS:
1950 		return 2;
1951 	case PR_WRITE_EXCLUSIVE_REG_ONLY:
1952 		return 3;
1953 	case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1954 		return 4;
1955 	case PR_WRITE_EXCLUSIVE_ALL_REGS:
1956 		return 5;
1957 	case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1958 		return 6;
1959 	default:
1960 		return 0;
1961 	}
1962 };
1963 
1964 static int nvme_send_ns_head_pr_command(struct block_device *bdev,
1965 		struct nvme_command *c, u8 data[16])
1966 {
1967 	struct nvme_ns_head *head = bdev->bd_disk->private_data;
1968 	int srcu_idx = srcu_read_lock(&head->srcu);
1969 	struct nvme_ns *ns = nvme_find_path(head);
1970 	int ret = -EWOULDBLOCK;
1971 
1972 	if (ns) {
1973 		c->common.nsid = cpu_to_le32(ns->head->ns_id);
1974 		ret = nvme_submit_sync_cmd(ns->queue, c, data, 16);
1975 	}
1976 	srcu_read_unlock(&head->srcu, srcu_idx);
1977 	return ret;
1978 }
1979 
1980 static int nvme_send_ns_pr_command(struct nvme_ns *ns, struct nvme_command *c,
1981 		u8 data[16])
1982 {
1983 	c->common.nsid = cpu_to_le32(ns->head->ns_id);
1984 	return nvme_submit_sync_cmd(ns->queue, c, data, 16);
1985 }
1986 
1987 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1988 				u64 key, u64 sa_key, u8 op)
1989 {
1990 	struct nvme_command c = { };
1991 	u8 data[16] = { 0, };
1992 
1993 	put_unaligned_le64(key, &data[0]);
1994 	put_unaligned_le64(sa_key, &data[8]);
1995 
1996 	c.common.opcode = op;
1997 	c.common.cdw10 = cpu_to_le32(cdw10);
1998 
1999 	if (IS_ENABLED(CONFIG_NVME_MULTIPATH) &&
2000 	    bdev->bd_disk->fops == &nvme_ns_head_ops)
2001 		return nvme_send_ns_head_pr_command(bdev, &c, data);
2002 	return nvme_send_ns_pr_command(bdev->bd_disk->private_data, &c, data);
2003 }
2004 
2005 static int nvme_pr_register(struct block_device *bdev, u64 old,
2006 		u64 new, unsigned flags)
2007 {
2008 	u32 cdw10;
2009 
2010 	if (flags & ~PR_FL_IGNORE_KEY)
2011 		return -EOPNOTSUPP;
2012 
2013 	cdw10 = old ? 2 : 0;
2014 	cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2015 	cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2016 	return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2017 }
2018 
2019 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2020 		enum pr_type type, unsigned flags)
2021 {
2022 	u32 cdw10;
2023 
2024 	if (flags & ~PR_FL_IGNORE_KEY)
2025 		return -EOPNOTSUPP;
2026 
2027 	cdw10 = nvme_pr_type(type) << 8;
2028 	cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2029 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2030 }
2031 
2032 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2033 		enum pr_type type, bool abort)
2034 {
2035 	u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
2036 
2037 	return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2038 }
2039 
2040 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2041 {
2042 	u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2043 
2044 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2045 }
2046 
2047 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2048 {
2049 	u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
2050 
2051 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2052 }
2053 
2054 const struct pr_ops nvme_pr_ops = {
2055 	.pr_register	= nvme_pr_register,
2056 	.pr_reserve	= nvme_pr_reserve,
2057 	.pr_release	= nvme_pr_release,
2058 	.pr_preempt	= nvme_pr_preempt,
2059 	.pr_clear	= nvme_pr_clear,
2060 };
2061 
2062 #ifdef CONFIG_BLK_SED_OPAL
2063 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2064 		bool send)
2065 {
2066 	struct nvme_ctrl *ctrl = data;
2067 	struct nvme_command cmd = { };
2068 
2069 	if (send)
2070 		cmd.common.opcode = nvme_admin_security_send;
2071 	else
2072 		cmd.common.opcode = nvme_admin_security_recv;
2073 	cmd.common.nsid = 0;
2074 	cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2075 	cmd.common.cdw11 = cpu_to_le32(len);
2076 
2077 	return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 0,
2078 			NVME_QID_ANY, 1, 0);
2079 }
2080 EXPORT_SYMBOL_GPL(nvme_sec_submit);
2081 #endif /* CONFIG_BLK_SED_OPAL */
2082 
2083 #ifdef CONFIG_BLK_DEV_ZONED
2084 static int nvme_report_zones(struct gendisk *disk, sector_t sector,
2085 		unsigned int nr_zones, report_zones_cb cb, void *data)
2086 {
2087 	return nvme_ns_report_zones(disk->private_data, sector, nr_zones, cb,
2088 			data);
2089 }
2090 #else
2091 #define nvme_report_zones	NULL
2092 #endif /* CONFIG_BLK_DEV_ZONED */
2093 
2094 static const struct block_device_operations nvme_bdev_ops = {
2095 	.owner		= THIS_MODULE,
2096 	.ioctl		= nvme_ioctl,
2097 	.open		= nvme_open,
2098 	.release	= nvme_release,
2099 	.getgeo		= nvme_getgeo,
2100 	.report_zones	= nvme_report_zones,
2101 	.pr_ops		= &nvme_pr_ops,
2102 };
2103 
2104 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2105 {
2106 	unsigned long timeout =
2107 		((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2108 	u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2109 	int ret;
2110 
2111 	while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2112 		if (csts == ~0)
2113 			return -ENODEV;
2114 		if ((csts & NVME_CSTS_RDY) == bit)
2115 			break;
2116 
2117 		usleep_range(1000, 2000);
2118 		if (fatal_signal_pending(current))
2119 			return -EINTR;
2120 		if (time_after(jiffies, timeout)) {
2121 			dev_err(ctrl->device,
2122 				"Device not ready; aborting %s, CSTS=0x%x\n",
2123 				enabled ? "initialisation" : "reset", csts);
2124 			return -ENODEV;
2125 		}
2126 	}
2127 
2128 	return ret;
2129 }
2130 
2131 /*
2132  * If the device has been passed off to us in an enabled state, just clear
2133  * the enabled bit.  The spec says we should set the 'shutdown notification
2134  * bits', but doing so may cause the device to complete commands to the
2135  * admin queue ... and we don't know what memory that might be pointing at!
2136  */
2137 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2138 {
2139 	int ret;
2140 
2141 	ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2142 	ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2143 
2144 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2145 	if (ret)
2146 		return ret;
2147 
2148 	if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2149 		msleep(NVME_QUIRK_DELAY_AMOUNT);
2150 
2151 	return nvme_wait_ready(ctrl, ctrl->cap, false);
2152 }
2153 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2154 
2155 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2156 {
2157 	unsigned dev_page_min;
2158 	int ret;
2159 
2160 	ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2161 	if (ret) {
2162 		dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2163 		return ret;
2164 	}
2165 	dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2166 
2167 	if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2168 		dev_err(ctrl->device,
2169 			"Minimum device page size %u too large for host (%u)\n",
2170 			1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2171 		return -ENODEV;
2172 	}
2173 
2174 	if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2175 		ctrl->ctrl_config = NVME_CC_CSS_CSI;
2176 	else
2177 		ctrl->ctrl_config = NVME_CC_CSS_NVM;
2178 	ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2179 	ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2180 	ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2181 	ctrl->ctrl_config |= NVME_CC_ENABLE;
2182 
2183 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2184 	if (ret)
2185 		return ret;
2186 	return nvme_wait_ready(ctrl, ctrl->cap, true);
2187 }
2188 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2189 
2190 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2191 {
2192 	unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2193 	u32 csts;
2194 	int ret;
2195 
2196 	ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2197 	ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2198 
2199 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2200 	if (ret)
2201 		return ret;
2202 
2203 	while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2204 		if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2205 			break;
2206 
2207 		msleep(100);
2208 		if (fatal_signal_pending(current))
2209 			return -EINTR;
2210 		if (time_after(jiffies, timeout)) {
2211 			dev_err(ctrl->device,
2212 				"Device shutdown incomplete; abort shutdown\n");
2213 			return -ENODEV;
2214 		}
2215 	}
2216 
2217 	return ret;
2218 }
2219 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2220 
2221 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2222 {
2223 	__le64 ts;
2224 	int ret;
2225 
2226 	if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2227 		return 0;
2228 
2229 	ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2230 	ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2231 			NULL);
2232 	if (ret)
2233 		dev_warn_once(ctrl->device,
2234 			"could not set timestamp (%d)\n", ret);
2235 	return ret;
2236 }
2237 
2238 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2239 {
2240 	struct nvme_feat_host_behavior *host;
2241 	int ret;
2242 
2243 	/* Don't bother enabling the feature if retry delay is not reported */
2244 	if (!ctrl->crdt[0])
2245 		return 0;
2246 
2247 	host = kzalloc(sizeof(*host), GFP_KERNEL);
2248 	if (!host)
2249 		return 0;
2250 
2251 	host->acre = NVME_ENABLE_ACRE;
2252 	ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2253 				host, sizeof(*host), NULL);
2254 	kfree(host);
2255 	return ret;
2256 }
2257 
2258 /*
2259  * The function checks whether the given total (exlat + enlat) latency of
2260  * a power state allows the latter to be used as an APST transition target.
2261  * It does so by comparing the latency to the primary and secondary latency
2262  * tolerances defined by module params. If there's a match, the corresponding
2263  * timeout value is returned and the matching tolerance index (1 or 2) is
2264  * reported.
2265  */
2266 static bool nvme_apst_get_transition_time(u64 total_latency,
2267 		u64 *transition_time, unsigned *last_index)
2268 {
2269 	if (total_latency <= apst_primary_latency_tol_us) {
2270 		if (*last_index == 1)
2271 			return false;
2272 		*last_index = 1;
2273 		*transition_time = apst_primary_timeout_ms;
2274 		return true;
2275 	}
2276 	if (apst_secondary_timeout_ms &&
2277 		total_latency <= apst_secondary_latency_tol_us) {
2278 		if (*last_index <= 2)
2279 			return false;
2280 		*last_index = 2;
2281 		*transition_time = apst_secondary_timeout_ms;
2282 		return true;
2283 	}
2284 	return false;
2285 }
2286 
2287 /*
2288  * APST (Autonomous Power State Transition) lets us program a table of power
2289  * state transitions that the controller will perform automatically.
2290  *
2291  * Depending on module params, one of the two supported techniques will be used:
2292  *
2293  * - If the parameters provide explicit timeouts and tolerances, they will be
2294  *   used to build a table with up to 2 non-operational states to transition to.
2295  *   The default parameter values were selected based on the values used by
2296  *   Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic
2297  *   regeneration of the APST table in the event of switching between external
2298  *   and battery power, the timeouts and tolerances reflect a compromise
2299  *   between values used by Microsoft for AC and battery scenarios.
2300  * - If not, we'll configure the table with a simple heuristic: we are willing
2301  *   to spend at most 2% of the time transitioning between power states.
2302  *   Therefore, when running in any given state, we will enter the next
2303  *   lower-power non-operational state after waiting 50 * (enlat + exlat)
2304  *   microseconds, as long as that state's exit latency is under the requested
2305  *   maximum latency.
2306  *
2307  * We will not autonomously enter any non-operational state for which the total
2308  * latency exceeds ps_max_latency_us.
2309  *
2310  * Users can set ps_max_latency_us to zero to turn off APST.
2311  */
2312 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2313 {
2314 	struct nvme_feat_auto_pst *table;
2315 	unsigned apste = 0;
2316 	u64 max_lat_us = 0;
2317 	__le64 target = 0;
2318 	int max_ps = -1;
2319 	int state;
2320 	int ret;
2321 	unsigned last_lt_index = UINT_MAX;
2322 
2323 	/*
2324 	 * If APST isn't supported or if we haven't been initialized yet,
2325 	 * then don't do anything.
2326 	 */
2327 	if (!ctrl->apsta)
2328 		return 0;
2329 
2330 	if (ctrl->npss > 31) {
2331 		dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2332 		return 0;
2333 	}
2334 
2335 	table = kzalloc(sizeof(*table), GFP_KERNEL);
2336 	if (!table)
2337 		return 0;
2338 
2339 	if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2340 		/* Turn off APST. */
2341 		dev_dbg(ctrl->device, "APST disabled\n");
2342 		goto done;
2343 	}
2344 
2345 	/*
2346 	 * Walk through all states from lowest- to highest-power.
2347 	 * According to the spec, lower-numbered states use more power.  NPSS,
2348 	 * despite the name, is the index of the lowest-power state, not the
2349 	 * number of states.
2350 	 */
2351 	for (state = (int)ctrl->npss; state >= 0; state--) {
2352 		u64 total_latency_us, exit_latency_us, transition_ms;
2353 
2354 		if (target)
2355 			table->entries[state] = target;
2356 
2357 		/*
2358 		 * Don't allow transitions to the deepest state if it's quirked
2359 		 * off.
2360 		 */
2361 		if (state == ctrl->npss &&
2362 		    (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2363 			continue;
2364 
2365 		/*
2366 		 * Is this state a useful non-operational state for higher-power
2367 		 * states to autonomously transition to?
2368 		 */
2369 		if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
2370 			continue;
2371 
2372 		exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2373 		if (exit_latency_us > ctrl->ps_max_latency_us)
2374 			continue;
2375 
2376 		total_latency_us = exit_latency_us +
2377 			le32_to_cpu(ctrl->psd[state].entry_lat);
2378 
2379 		/*
2380 		 * This state is good. It can be used as the APST idle target
2381 		 * for higher power states.
2382 		 */
2383 		if (apst_primary_timeout_ms && apst_primary_latency_tol_us) {
2384 			if (!nvme_apst_get_transition_time(total_latency_us,
2385 					&transition_ms, &last_lt_index))
2386 				continue;
2387 		} else {
2388 			transition_ms = total_latency_us + 19;
2389 			do_div(transition_ms, 20);
2390 			if (transition_ms > (1 << 24) - 1)
2391 				transition_ms = (1 << 24) - 1;
2392 		}
2393 
2394 		target = cpu_to_le64((state << 3) | (transition_ms << 8));
2395 		if (max_ps == -1)
2396 			max_ps = state;
2397 		if (total_latency_us > max_lat_us)
2398 			max_lat_us = total_latency_us;
2399 	}
2400 
2401 	if (max_ps == -1)
2402 		dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2403 	else
2404 		dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2405 			max_ps, max_lat_us, (int)sizeof(*table), table);
2406 	apste = 1;
2407 
2408 done:
2409 	ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2410 				table, sizeof(*table), NULL);
2411 	if (ret)
2412 		dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2413 	kfree(table);
2414 	return ret;
2415 }
2416 
2417 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2418 {
2419 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2420 	u64 latency;
2421 
2422 	switch (val) {
2423 	case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2424 	case PM_QOS_LATENCY_ANY:
2425 		latency = U64_MAX;
2426 		break;
2427 
2428 	default:
2429 		latency = val;
2430 	}
2431 
2432 	if (ctrl->ps_max_latency_us != latency) {
2433 		ctrl->ps_max_latency_us = latency;
2434 		if (ctrl->state == NVME_CTRL_LIVE)
2435 			nvme_configure_apst(ctrl);
2436 	}
2437 }
2438 
2439 struct nvme_core_quirk_entry {
2440 	/*
2441 	 * NVMe model and firmware strings are padded with spaces.  For
2442 	 * simplicity, strings in the quirk table are padded with NULLs
2443 	 * instead.
2444 	 */
2445 	u16 vid;
2446 	const char *mn;
2447 	const char *fr;
2448 	unsigned long quirks;
2449 };
2450 
2451 static const struct nvme_core_quirk_entry core_quirks[] = {
2452 	{
2453 		/*
2454 		 * This Toshiba device seems to die using any APST states.  See:
2455 		 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2456 		 */
2457 		.vid = 0x1179,
2458 		.mn = "THNSF5256GPUK TOSHIBA",
2459 		.quirks = NVME_QUIRK_NO_APST,
2460 	},
2461 	{
2462 		/*
2463 		 * This LiteON CL1-3D*-Q11 firmware version has a race
2464 		 * condition associated with actions related to suspend to idle
2465 		 * LiteON has resolved the problem in future firmware
2466 		 */
2467 		.vid = 0x14a4,
2468 		.fr = "22301111",
2469 		.quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2470 	}
2471 };
2472 
2473 /* match is null-terminated but idstr is space-padded. */
2474 static bool string_matches(const char *idstr, const char *match, size_t len)
2475 {
2476 	size_t matchlen;
2477 
2478 	if (!match)
2479 		return true;
2480 
2481 	matchlen = strlen(match);
2482 	WARN_ON_ONCE(matchlen > len);
2483 
2484 	if (memcmp(idstr, match, matchlen))
2485 		return false;
2486 
2487 	for (; matchlen < len; matchlen++)
2488 		if (idstr[matchlen] != ' ')
2489 			return false;
2490 
2491 	return true;
2492 }
2493 
2494 static bool quirk_matches(const struct nvme_id_ctrl *id,
2495 			  const struct nvme_core_quirk_entry *q)
2496 {
2497 	return q->vid == le16_to_cpu(id->vid) &&
2498 		string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2499 		string_matches(id->fr, q->fr, sizeof(id->fr));
2500 }
2501 
2502 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2503 		struct nvme_id_ctrl *id)
2504 {
2505 	size_t nqnlen;
2506 	int off;
2507 
2508 	if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2509 		nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2510 		if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2511 			strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2512 			return;
2513 		}
2514 
2515 		if (ctrl->vs >= NVME_VS(1, 2, 1))
2516 			dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2517 	}
2518 
2519 	/* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2520 	off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2521 			"nqn.2014.08.org.nvmexpress:%04x%04x",
2522 			le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2523 	memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2524 	off += sizeof(id->sn);
2525 	memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2526 	off += sizeof(id->mn);
2527 	memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2528 }
2529 
2530 static void nvme_release_subsystem(struct device *dev)
2531 {
2532 	struct nvme_subsystem *subsys =
2533 		container_of(dev, struct nvme_subsystem, dev);
2534 
2535 	if (subsys->instance >= 0)
2536 		ida_simple_remove(&nvme_instance_ida, subsys->instance);
2537 	kfree(subsys);
2538 }
2539 
2540 static void nvme_destroy_subsystem(struct kref *ref)
2541 {
2542 	struct nvme_subsystem *subsys =
2543 			container_of(ref, struct nvme_subsystem, ref);
2544 
2545 	mutex_lock(&nvme_subsystems_lock);
2546 	list_del(&subsys->entry);
2547 	mutex_unlock(&nvme_subsystems_lock);
2548 
2549 	ida_destroy(&subsys->ns_ida);
2550 	device_del(&subsys->dev);
2551 	put_device(&subsys->dev);
2552 }
2553 
2554 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2555 {
2556 	kref_put(&subsys->ref, nvme_destroy_subsystem);
2557 }
2558 
2559 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2560 {
2561 	struct nvme_subsystem *subsys;
2562 
2563 	lockdep_assert_held(&nvme_subsystems_lock);
2564 
2565 	/*
2566 	 * Fail matches for discovery subsystems. This results
2567 	 * in each discovery controller bound to a unique subsystem.
2568 	 * This avoids issues with validating controller values
2569 	 * that can only be true when there is a single unique subsystem.
2570 	 * There may be multiple and completely independent entities
2571 	 * that provide discovery controllers.
2572 	 */
2573 	if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2574 		return NULL;
2575 
2576 	list_for_each_entry(subsys, &nvme_subsystems, entry) {
2577 		if (strcmp(subsys->subnqn, subsysnqn))
2578 			continue;
2579 		if (!kref_get_unless_zero(&subsys->ref))
2580 			continue;
2581 		return subsys;
2582 	}
2583 
2584 	return NULL;
2585 }
2586 
2587 #define SUBSYS_ATTR_RO(_name, _mode, _show)			\
2588 	struct device_attribute subsys_attr_##_name = \
2589 		__ATTR(_name, _mode, _show, NULL)
2590 
2591 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2592 				    struct device_attribute *attr,
2593 				    char *buf)
2594 {
2595 	struct nvme_subsystem *subsys =
2596 		container_of(dev, struct nvme_subsystem, dev);
2597 
2598 	return sysfs_emit(buf, "%s\n", subsys->subnqn);
2599 }
2600 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2601 
2602 #define nvme_subsys_show_str_function(field)				\
2603 static ssize_t subsys_##field##_show(struct device *dev,		\
2604 			    struct device_attribute *attr, char *buf)	\
2605 {									\
2606 	struct nvme_subsystem *subsys =					\
2607 		container_of(dev, struct nvme_subsystem, dev);		\
2608 	return sysfs_emit(buf, "%.*s\n",				\
2609 			   (int)sizeof(subsys->field), subsys->field);	\
2610 }									\
2611 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2612 
2613 nvme_subsys_show_str_function(model);
2614 nvme_subsys_show_str_function(serial);
2615 nvme_subsys_show_str_function(firmware_rev);
2616 
2617 static struct attribute *nvme_subsys_attrs[] = {
2618 	&subsys_attr_model.attr,
2619 	&subsys_attr_serial.attr,
2620 	&subsys_attr_firmware_rev.attr,
2621 	&subsys_attr_subsysnqn.attr,
2622 #ifdef CONFIG_NVME_MULTIPATH
2623 	&subsys_attr_iopolicy.attr,
2624 #endif
2625 	NULL,
2626 };
2627 
2628 static const struct attribute_group nvme_subsys_attrs_group = {
2629 	.attrs = nvme_subsys_attrs,
2630 };
2631 
2632 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2633 	&nvme_subsys_attrs_group,
2634 	NULL,
2635 };
2636 
2637 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
2638 {
2639 	return ctrl->opts && ctrl->opts->discovery_nqn;
2640 }
2641 
2642 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2643 		struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2644 {
2645 	struct nvme_ctrl *tmp;
2646 
2647 	lockdep_assert_held(&nvme_subsystems_lock);
2648 
2649 	list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2650 		if (nvme_state_terminal(tmp))
2651 			continue;
2652 
2653 		if (tmp->cntlid == ctrl->cntlid) {
2654 			dev_err(ctrl->device,
2655 				"Duplicate cntlid %u with %s, rejecting\n",
2656 				ctrl->cntlid, dev_name(tmp->device));
2657 			return false;
2658 		}
2659 
2660 		if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2661 		    nvme_discovery_ctrl(ctrl))
2662 			continue;
2663 
2664 		dev_err(ctrl->device,
2665 			"Subsystem does not support multiple controllers\n");
2666 		return false;
2667 	}
2668 
2669 	return true;
2670 }
2671 
2672 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2673 {
2674 	struct nvme_subsystem *subsys, *found;
2675 	int ret;
2676 
2677 	subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2678 	if (!subsys)
2679 		return -ENOMEM;
2680 
2681 	subsys->instance = -1;
2682 	mutex_init(&subsys->lock);
2683 	kref_init(&subsys->ref);
2684 	INIT_LIST_HEAD(&subsys->ctrls);
2685 	INIT_LIST_HEAD(&subsys->nsheads);
2686 	nvme_init_subnqn(subsys, ctrl, id);
2687 	memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2688 	memcpy(subsys->model, id->mn, sizeof(subsys->model));
2689 	memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2690 	subsys->vendor_id = le16_to_cpu(id->vid);
2691 	subsys->cmic = id->cmic;
2692 	subsys->awupf = le16_to_cpu(id->awupf);
2693 #ifdef CONFIG_NVME_MULTIPATH
2694 	subsys->iopolicy = NVME_IOPOLICY_NUMA;
2695 #endif
2696 
2697 	subsys->dev.class = nvme_subsys_class;
2698 	subsys->dev.release = nvme_release_subsystem;
2699 	subsys->dev.groups = nvme_subsys_attrs_groups;
2700 	dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2701 	device_initialize(&subsys->dev);
2702 
2703 	mutex_lock(&nvme_subsystems_lock);
2704 	found = __nvme_find_get_subsystem(subsys->subnqn);
2705 	if (found) {
2706 		put_device(&subsys->dev);
2707 		subsys = found;
2708 
2709 		if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2710 			ret = -EINVAL;
2711 			goto out_put_subsystem;
2712 		}
2713 	} else {
2714 		ret = device_add(&subsys->dev);
2715 		if (ret) {
2716 			dev_err(ctrl->device,
2717 				"failed to register subsystem device.\n");
2718 			put_device(&subsys->dev);
2719 			goto out_unlock;
2720 		}
2721 		ida_init(&subsys->ns_ida);
2722 		list_add_tail(&subsys->entry, &nvme_subsystems);
2723 	}
2724 
2725 	ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2726 				dev_name(ctrl->device));
2727 	if (ret) {
2728 		dev_err(ctrl->device,
2729 			"failed to create sysfs link from subsystem.\n");
2730 		goto out_put_subsystem;
2731 	}
2732 
2733 	if (!found)
2734 		subsys->instance = ctrl->instance;
2735 	ctrl->subsys = subsys;
2736 	list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2737 	mutex_unlock(&nvme_subsystems_lock);
2738 	return 0;
2739 
2740 out_put_subsystem:
2741 	nvme_put_subsystem(subsys);
2742 out_unlock:
2743 	mutex_unlock(&nvme_subsystems_lock);
2744 	return ret;
2745 }
2746 
2747 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2748 		void *log, size_t size, u64 offset)
2749 {
2750 	struct nvme_command c = { };
2751 	u32 dwlen = nvme_bytes_to_numd(size);
2752 
2753 	c.get_log_page.opcode = nvme_admin_get_log_page;
2754 	c.get_log_page.nsid = cpu_to_le32(nsid);
2755 	c.get_log_page.lid = log_page;
2756 	c.get_log_page.lsp = lsp;
2757 	c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2758 	c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2759 	c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2760 	c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2761 	c.get_log_page.csi = csi;
2762 
2763 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2764 }
2765 
2766 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
2767 				struct nvme_effects_log **log)
2768 {
2769 	struct nvme_effects_log	*cel = xa_load(&ctrl->cels, csi);
2770 	int ret;
2771 
2772 	if (cel)
2773 		goto out;
2774 
2775 	cel = kzalloc(sizeof(*cel), GFP_KERNEL);
2776 	if (!cel)
2777 		return -ENOMEM;
2778 
2779 	ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
2780 			cel, sizeof(*cel), 0);
2781 	if (ret) {
2782 		kfree(cel);
2783 		return ret;
2784 	}
2785 
2786 	xa_store(&ctrl->cels, csi, cel, GFP_KERNEL);
2787 out:
2788 	*log = cel;
2789 	return 0;
2790 }
2791 
2792 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
2793 {
2794 	u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
2795 
2796 	if (check_shl_overflow(1U, units + page_shift - 9, &val))
2797 		return UINT_MAX;
2798 	return val;
2799 }
2800 
2801 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
2802 {
2803 	struct nvme_command c = { };
2804 	struct nvme_id_ctrl_nvm *id;
2805 	int ret;
2806 
2807 	if (ctrl->oncs & NVME_CTRL_ONCS_DSM) {
2808 		ctrl->max_discard_sectors = UINT_MAX;
2809 		ctrl->max_discard_segments = NVME_DSM_MAX_RANGES;
2810 	} else {
2811 		ctrl->max_discard_sectors = 0;
2812 		ctrl->max_discard_segments = 0;
2813 	}
2814 
2815 	/*
2816 	 * Even though NVMe spec explicitly states that MDTS is not applicable
2817 	 * to the write-zeroes, we are cautious and limit the size to the
2818 	 * controllers max_hw_sectors value, which is based on the MDTS field
2819 	 * and possibly other limiting factors.
2820 	 */
2821 	if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
2822 	    !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
2823 		ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
2824 	else
2825 		ctrl->max_zeroes_sectors = 0;
2826 
2827 	if (nvme_ctrl_limited_cns(ctrl))
2828 		return 0;
2829 
2830 	id = kzalloc(sizeof(*id), GFP_KERNEL);
2831 	if (!id)
2832 		return 0;
2833 
2834 	c.identify.opcode = nvme_admin_identify;
2835 	c.identify.cns = NVME_ID_CNS_CS_CTRL;
2836 	c.identify.csi = NVME_CSI_NVM;
2837 
2838 	ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
2839 	if (ret)
2840 		goto free_data;
2841 
2842 	if (id->dmrl)
2843 		ctrl->max_discard_segments = id->dmrl;
2844 	if (id->dmrsl)
2845 		ctrl->max_discard_sectors = le32_to_cpu(id->dmrsl);
2846 	if (id->wzsl)
2847 		ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
2848 
2849 free_data:
2850 	kfree(id);
2851 	return ret;
2852 }
2853 
2854 static int nvme_init_identify(struct nvme_ctrl *ctrl)
2855 {
2856 	struct nvme_id_ctrl *id;
2857 	u32 max_hw_sectors;
2858 	bool prev_apst_enabled;
2859 	int ret;
2860 
2861 	ret = nvme_identify_ctrl(ctrl, &id);
2862 	if (ret) {
2863 		dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2864 		return -EIO;
2865 	}
2866 
2867 	if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2868 		ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
2869 		if (ret < 0)
2870 			goto out_free;
2871 	}
2872 
2873 	if (!(ctrl->ops->flags & NVME_F_FABRICS))
2874 		ctrl->cntlid = le16_to_cpu(id->cntlid);
2875 
2876 	if (!ctrl->identified) {
2877 		unsigned int i;
2878 
2879 		ret = nvme_init_subsystem(ctrl, id);
2880 		if (ret)
2881 			goto out_free;
2882 
2883 		/*
2884 		 * Check for quirks.  Quirk can depend on firmware version,
2885 		 * so, in principle, the set of quirks present can change
2886 		 * across a reset.  As a possible future enhancement, we
2887 		 * could re-scan for quirks every time we reinitialize
2888 		 * the device, but we'd have to make sure that the driver
2889 		 * behaves intelligently if the quirks change.
2890 		 */
2891 		for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2892 			if (quirk_matches(id, &core_quirks[i]))
2893 				ctrl->quirks |= core_quirks[i].quirks;
2894 		}
2895 	}
2896 
2897 	if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2898 		dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2899 		ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2900 	}
2901 
2902 	ctrl->crdt[0] = le16_to_cpu(id->crdt1);
2903 	ctrl->crdt[1] = le16_to_cpu(id->crdt2);
2904 	ctrl->crdt[2] = le16_to_cpu(id->crdt3);
2905 
2906 	ctrl->oacs = le16_to_cpu(id->oacs);
2907 	ctrl->oncs = le16_to_cpu(id->oncs);
2908 	ctrl->mtfa = le16_to_cpu(id->mtfa);
2909 	ctrl->oaes = le32_to_cpu(id->oaes);
2910 	ctrl->wctemp = le16_to_cpu(id->wctemp);
2911 	ctrl->cctemp = le16_to_cpu(id->cctemp);
2912 
2913 	atomic_set(&ctrl->abort_limit, id->acl + 1);
2914 	ctrl->vwc = id->vwc;
2915 	if (id->mdts)
2916 		max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
2917 	else
2918 		max_hw_sectors = UINT_MAX;
2919 	ctrl->max_hw_sectors =
2920 		min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2921 
2922 	nvme_set_queue_limits(ctrl, ctrl->admin_q);
2923 	ctrl->sgls = le32_to_cpu(id->sgls);
2924 	ctrl->kas = le16_to_cpu(id->kas);
2925 	ctrl->max_namespaces = le32_to_cpu(id->mnan);
2926 	ctrl->ctratt = le32_to_cpu(id->ctratt);
2927 
2928 	if (id->rtd3e) {
2929 		/* us -> s */
2930 		u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
2931 
2932 		ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2933 						 shutdown_timeout, 60);
2934 
2935 		if (ctrl->shutdown_timeout != shutdown_timeout)
2936 			dev_info(ctrl->device,
2937 				 "Shutdown timeout set to %u seconds\n",
2938 				 ctrl->shutdown_timeout);
2939 	} else
2940 		ctrl->shutdown_timeout = shutdown_timeout;
2941 
2942 	ctrl->npss = id->npss;
2943 	ctrl->apsta = id->apsta;
2944 	prev_apst_enabled = ctrl->apst_enabled;
2945 	if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2946 		if (force_apst && id->apsta) {
2947 			dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2948 			ctrl->apst_enabled = true;
2949 		} else {
2950 			ctrl->apst_enabled = false;
2951 		}
2952 	} else {
2953 		ctrl->apst_enabled = id->apsta;
2954 	}
2955 	memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2956 
2957 	if (ctrl->ops->flags & NVME_F_FABRICS) {
2958 		ctrl->icdoff = le16_to_cpu(id->icdoff);
2959 		ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2960 		ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2961 		ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2962 
2963 		/*
2964 		 * In fabrics we need to verify the cntlid matches the
2965 		 * admin connect
2966 		 */
2967 		if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2968 			dev_err(ctrl->device,
2969 				"Mismatching cntlid: Connect %u vs Identify "
2970 				"%u, rejecting\n",
2971 				ctrl->cntlid, le16_to_cpu(id->cntlid));
2972 			ret = -EINVAL;
2973 			goto out_free;
2974 		}
2975 
2976 		if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
2977 			dev_err(ctrl->device,
2978 				"keep-alive support is mandatory for fabrics\n");
2979 			ret = -EINVAL;
2980 			goto out_free;
2981 		}
2982 	} else {
2983 		ctrl->hmpre = le32_to_cpu(id->hmpre);
2984 		ctrl->hmmin = le32_to_cpu(id->hmmin);
2985 		ctrl->hmminds = le32_to_cpu(id->hmminds);
2986 		ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2987 	}
2988 
2989 	ret = nvme_mpath_init_identify(ctrl, id);
2990 	if (ret < 0)
2991 		goto out_free;
2992 
2993 	if (ctrl->apst_enabled && !prev_apst_enabled)
2994 		dev_pm_qos_expose_latency_tolerance(ctrl->device);
2995 	else if (!ctrl->apst_enabled && prev_apst_enabled)
2996 		dev_pm_qos_hide_latency_tolerance(ctrl->device);
2997 
2998 out_free:
2999 	kfree(id);
3000 	return ret;
3001 }
3002 
3003 /*
3004  * Initialize the cached copies of the Identify data and various controller
3005  * register in our nvme_ctrl structure.  This should be called as soon as
3006  * the admin queue is fully up and running.
3007  */
3008 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl)
3009 {
3010 	int ret;
3011 
3012 	ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3013 	if (ret) {
3014 		dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3015 		return ret;
3016 	}
3017 
3018 	ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3019 
3020 	if (ctrl->vs >= NVME_VS(1, 1, 0))
3021 		ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3022 
3023 	ret = nvme_init_identify(ctrl);
3024 	if (ret)
3025 		return ret;
3026 
3027 	ret = nvme_init_non_mdts_limits(ctrl);
3028 	if (ret < 0)
3029 		return ret;
3030 
3031 	ret = nvme_configure_apst(ctrl);
3032 	if (ret < 0)
3033 		return ret;
3034 
3035 	ret = nvme_configure_timestamp(ctrl);
3036 	if (ret < 0)
3037 		return ret;
3038 
3039 	ret = nvme_configure_directives(ctrl);
3040 	if (ret < 0)
3041 		return ret;
3042 
3043 	ret = nvme_configure_acre(ctrl);
3044 	if (ret < 0)
3045 		return ret;
3046 
3047 	if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
3048 		ret = nvme_hwmon_init(ctrl);
3049 		if (ret < 0)
3050 			return ret;
3051 	}
3052 
3053 	ctrl->identified = true;
3054 
3055 	return 0;
3056 }
3057 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
3058 
3059 static int nvme_dev_open(struct inode *inode, struct file *file)
3060 {
3061 	struct nvme_ctrl *ctrl =
3062 		container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3063 
3064 	switch (ctrl->state) {
3065 	case NVME_CTRL_LIVE:
3066 		break;
3067 	default:
3068 		return -EWOULDBLOCK;
3069 	}
3070 
3071 	nvme_get_ctrl(ctrl);
3072 	if (!try_module_get(ctrl->ops->module)) {
3073 		nvme_put_ctrl(ctrl);
3074 		return -EINVAL;
3075 	}
3076 
3077 	file->private_data = ctrl;
3078 	return 0;
3079 }
3080 
3081 static int nvme_dev_release(struct inode *inode, struct file *file)
3082 {
3083 	struct nvme_ctrl *ctrl =
3084 		container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3085 
3086 	module_put(ctrl->ops->module);
3087 	nvme_put_ctrl(ctrl);
3088 	return 0;
3089 }
3090 
3091 static const struct file_operations nvme_dev_fops = {
3092 	.owner		= THIS_MODULE,
3093 	.open		= nvme_dev_open,
3094 	.release	= nvme_dev_release,
3095 	.unlocked_ioctl	= nvme_dev_ioctl,
3096 	.compat_ioctl	= compat_ptr_ioctl,
3097 };
3098 
3099 static ssize_t nvme_sysfs_reset(struct device *dev,
3100 				struct device_attribute *attr, const char *buf,
3101 				size_t count)
3102 {
3103 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3104 	int ret;
3105 
3106 	ret = nvme_reset_ctrl_sync(ctrl);
3107 	if (ret < 0)
3108 		return ret;
3109 	return count;
3110 }
3111 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3112 
3113 static ssize_t nvme_sysfs_rescan(struct device *dev,
3114 				struct device_attribute *attr, const char *buf,
3115 				size_t count)
3116 {
3117 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3118 
3119 	nvme_queue_scan(ctrl);
3120 	return count;
3121 }
3122 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
3123 
3124 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
3125 {
3126 	struct gendisk *disk = dev_to_disk(dev);
3127 
3128 	if (disk->fops == &nvme_bdev_ops)
3129 		return nvme_get_ns_from_dev(dev)->head;
3130 	else
3131 		return disk->private_data;
3132 }
3133 
3134 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
3135 		char *buf)
3136 {
3137 	struct nvme_ns_head *head = dev_to_ns_head(dev);
3138 	struct nvme_ns_ids *ids = &head->ids;
3139 	struct nvme_subsystem *subsys = head->subsys;
3140 	int serial_len = sizeof(subsys->serial);
3141 	int model_len = sizeof(subsys->model);
3142 
3143 	if (!uuid_is_null(&ids->uuid))
3144 		return sysfs_emit(buf, "uuid.%pU\n", &ids->uuid);
3145 
3146 	if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3147 		return sysfs_emit(buf, "eui.%16phN\n", ids->nguid);
3148 
3149 	if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3150 		return sysfs_emit(buf, "eui.%8phN\n", ids->eui64);
3151 
3152 	while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3153 				  subsys->serial[serial_len - 1] == '\0'))
3154 		serial_len--;
3155 	while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3156 				 subsys->model[model_len - 1] == '\0'))
3157 		model_len--;
3158 
3159 	return sysfs_emit(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3160 		serial_len, subsys->serial, model_len, subsys->model,
3161 		head->ns_id);
3162 }
3163 static DEVICE_ATTR_RO(wwid);
3164 
3165 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3166 		char *buf)
3167 {
3168 	return sysfs_emit(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3169 }
3170 static DEVICE_ATTR_RO(nguid);
3171 
3172 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3173 		char *buf)
3174 {
3175 	struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3176 
3177 	/* For backward compatibility expose the NGUID to userspace if
3178 	 * we have no UUID set
3179 	 */
3180 	if (uuid_is_null(&ids->uuid)) {
3181 		printk_ratelimited(KERN_WARNING
3182 				   "No UUID available providing old NGUID\n");
3183 		return sysfs_emit(buf, "%pU\n", ids->nguid);
3184 	}
3185 	return sysfs_emit(buf, "%pU\n", &ids->uuid);
3186 }
3187 static DEVICE_ATTR_RO(uuid);
3188 
3189 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3190 		char *buf)
3191 {
3192 	return sysfs_emit(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3193 }
3194 static DEVICE_ATTR_RO(eui);
3195 
3196 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3197 		char *buf)
3198 {
3199 	return sysfs_emit(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3200 }
3201 static DEVICE_ATTR_RO(nsid);
3202 
3203 static struct attribute *nvme_ns_id_attrs[] = {
3204 	&dev_attr_wwid.attr,
3205 	&dev_attr_uuid.attr,
3206 	&dev_attr_nguid.attr,
3207 	&dev_attr_eui.attr,
3208 	&dev_attr_nsid.attr,
3209 #ifdef CONFIG_NVME_MULTIPATH
3210 	&dev_attr_ana_grpid.attr,
3211 	&dev_attr_ana_state.attr,
3212 #endif
3213 	NULL,
3214 };
3215 
3216 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3217 		struct attribute *a, int n)
3218 {
3219 	struct device *dev = container_of(kobj, struct device, kobj);
3220 	struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3221 
3222 	if (a == &dev_attr_uuid.attr) {
3223 		if (uuid_is_null(&ids->uuid) &&
3224 		    !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3225 			return 0;
3226 	}
3227 	if (a == &dev_attr_nguid.attr) {
3228 		if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3229 			return 0;
3230 	}
3231 	if (a == &dev_attr_eui.attr) {
3232 		if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3233 			return 0;
3234 	}
3235 #ifdef CONFIG_NVME_MULTIPATH
3236 	if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3237 		if (dev_to_disk(dev)->fops != &nvme_bdev_ops) /* per-path attr */
3238 			return 0;
3239 		if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3240 			return 0;
3241 	}
3242 #endif
3243 	return a->mode;
3244 }
3245 
3246 static const struct attribute_group nvme_ns_id_attr_group = {
3247 	.attrs		= nvme_ns_id_attrs,
3248 	.is_visible	= nvme_ns_id_attrs_are_visible,
3249 };
3250 
3251 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3252 	&nvme_ns_id_attr_group,
3253 	NULL,
3254 };
3255 
3256 #define nvme_show_str_function(field)						\
3257 static ssize_t  field##_show(struct device *dev,				\
3258 			    struct device_attribute *attr, char *buf)		\
3259 {										\
3260         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);				\
3261         return sysfs_emit(buf, "%.*s\n",					\
3262 		(int)sizeof(ctrl->subsys->field), ctrl->subsys->field);		\
3263 }										\
3264 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3265 
3266 nvme_show_str_function(model);
3267 nvme_show_str_function(serial);
3268 nvme_show_str_function(firmware_rev);
3269 
3270 #define nvme_show_int_function(field)						\
3271 static ssize_t  field##_show(struct device *dev,				\
3272 			    struct device_attribute *attr, char *buf)		\
3273 {										\
3274         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);				\
3275         return sysfs_emit(buf, "%d\n", ctrl->field);				\
3276 }										\
3277 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3278 
3279 nvme_show_int_function(cntlid);
3280 nvme_show_int_function(numa_node);
3281 nvme_show_int_function(queue_count);
3282 nvme_show_int_function(sqsize);
3283 nvme_show_int_function(kato);
3284 
3285 static ssize_t nvme_sysfs_delete(struct device *dev,
3286 				struct device_attribute *attr, const char *buf,
3287 				size_t count)
3288 {
3289 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3290 
3291 	if (device_remove_file_self(dev, attr))
3292 		nvme_delete_ctrl_sync(ctrl);
3293 	return count;
3294 }
3295 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3296 
3297 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3298 					 struct device_attribute *attr,
3299 					 char *buf)
3300 {
3301 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3302 
3303 	return sysfs_emit(buf, "%s\n", ctrl->ops->name);
3304 }
3305 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3306 
3307 static ssize_t nvme_sysfs_show_state(struct device *dev,
3308 				     struct device_attribute *attr,
3309 				     char *buf)
3310 {
3311 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3312 	static const char *const state_name[] = {
3313 		[NVME_CTRL_NEW]		= "new",
3314 		[NVME_CTRL_LIVE]	= "live",
3315 		[NVME_CTRL_RESETTING]	= "resetting",
3316 		[NVME_CTRL_CONNECTING]	= "connecting",
3317 		[NVME_CTRL_DELETING]	= "deleting",
3318 		[NVME_CTRL_DELETING_NOIO]= "deleting (no IO)",
3319 		[NVME_CTRL_DEAD]	= "dead",
3320 	};
3321 
3322 	if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3323 	    state_name[ctrl->state])
3324 		return sysfs_emit(buf, "%s\n", state_name[ctrl->state]);
3325 
3326 	return sysfs_emit(buf, "unknown state\n");
3327 }
3328 
3329 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3330 
3331 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3332 					 struct device_attribute *attr,
3333 					 char *buf)
3334 {
3335 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3336 
3337 	return sysfs_emit(buf, "%s\n", ctrl->subsys->subnqn);
3338 }
3339 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3340 
3341 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3342 					struct device_attribute *attr,
3343 					char *buf)
3344 {
3345 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3346 
3347 	return sysfs_emit(buf, "%s\n", ctrl->opts->host->nqn);
3348 }
3349 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3350 
3351 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3352 					struct device_attribute *attr,
3353 					char *buf)
3354 {
3355 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3356 
3357 	return sysfs_emit(buf, "%pU\n", &ctrl->opts->host->id);
3358 }
3359 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3360 
3361 static ssize_t nvme_sysfs_show_address(struct device *dev,
3362 					 struct device_attribute *attr,
3363 					 char *buf)
3364 {
3365 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3366 
3367 	return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3368 }
3369 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3370 
3371 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev,
3372 		struct device_attribute *attr, char *buf)
3373 {
3374 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3375 	struct nvmf_ctrl_options *opts = ctrl->opts;
3376 
3377 	if (ctrl->opts->max_reconnects == -1)
3378 		return sysfs_emit(buf, "off\n");
3379 	return sysfs_emit(buf, "%d\n",
3380 			  opts->max_reconnects * opts->reconnect_delay);
3381 }
3382 
3383 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev,
3384 		struct device_attribute *attr, const char *buf, size_t count)
3385 {
3386 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3387 	struct nvmf_ctrl_options *opts = ctrl->opts;
3388 	int ctrl_loss_tmo, err;
3389 
3390 	err = kstrtoint(buf, 10, &ctrl_loss_tmo);
3391 	if (err)
3392 		return -EINVAL;
3393 
3394 	if (ctrl_loss_tmo < 0)
3395 		opts->max_reconnects = -1;
3396 	else
3397 		opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
3398 						opts->reconnect_delay);
3399 	return count;
3400 }
3401 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR,
3402 	nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store);
3403 
3404 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev,
3405 		struct device_attribute *attr, char *buf)
3406 {
3407 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3408 
3409 	if (ctrl->opts->reconnect_delay == -1)
3410 		return sysfs_emit(buf, "off\n");
3411 	return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay);
3412 }
3413 
3414 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev,
3415 		struct device_attribute *attr, const char *buf, size_t count)
3416 {
3417 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3418 	unsigned int v;
3419 	int err;
3420 
3421 	err = kstrtou32(buf, 10, &v);
3422 	if (err)
3423 		return err;
3424 
3425 	ctrl->opts->reconnect_delay = v;
3426 	return count;
3427 }
3428 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR,
3429 	nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store);
3430 
3431 static ssize_t nvme_ctrl_fast_io_fail_tmo_show(struct device *dev,
3432 		struct device_attribute *attr, char *buf)
3433 {
3434 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3435 
3436 	if (ctrl->opts->fast_io_fail_tmo == -1)
3437 		return sysfs_emit(buf, "off\n");
3438 	return sysfs_emit(buf, "%d\n", ctrl->opts->fast_io_fail_tmo);
3439 }
3440 
3441 static ssize_t nvme_ctrl_fast_io_fail_tmo_store(struct device *dev,
3442 		struct device_attribute *attr, const char *buf, size_t count)
3443 {
3444 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3445 	struct nvmf_ctrl_options *opts = ctrl->opts;
3446 	int fast_io_fail_tmo, err;
3447 
3448 	err = kstrtoint(buf, 10, &fast_io_fail_tmo);
3449 	if (err)
3450 		return -EINVAL;
3451 
3452 	if (fast_io_fail_tmo < 0)
3453 		opts->fast_io_fail_tmo = -1;
3454 	else
3455 		opts->fast_io_fail_tmo = fast_io_fail_tmo;
3456 	return count;
3457 }
3458 static DEVICE_ATTR(fast_io_fail_tmo, S_IRUGO | S_IWUSR,
3459 	nvme_ctrl_fast_io_fail_tmo_show, nvme_ctrl_fast_io_fail_tmo_store);
3460 
3461 static struct attribute *nvme_dev_attrs[] = {
3462 	&dev_attr_reset_controller.attr,
3463 	&dev_attr_rescan_controller.attr,
3464 	&dev_attr_model.attr,
3465 	&dev_attr_serial.attr,
3466 	&dev_attr_firmware_rev.attr,
3467 	&dev_attr_cntlid.attr,
3468 	&dev_attr_delete_controller.attr,
3469 	&dev_attr_transport.attr,
3470 	&dev_attr_subsysnqn.attr,
3471 	&dev_attr_address.attr,
3472 	&dev_attr_state.attr,
3473 	&dev_attr_numa_node.attr,
3474 	&dev_attr_queue_count.attr,
3475 	&dev_attr_sqsize.attr,
3476 	&dev_attr_hostnqn.attr,
3477 	&dev_attr_hostid.attr,
3478 	&dev_attr_ctrl_loss_tmo.attr,
3479 	&dev_attr_reconnect_delay.attr,
3480 	&dev_attr_fast_io_fail_tmo.attr,
3481 	&dev_attr_kato.attr,
3482 	NULL
3483 };
3484 
3485 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3486 		struct attribute *a, int n)
3487 {
3488 	struct device *dev = container_of(kobj, struct device, kobj);
3489 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3490 
3491 	if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3492 		return 0;
3493 	if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3494 		return 0;
3495 	if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3496 		return 0;
3497 	if (a == &dev_attr_hostid.attr && !ctrl->opts)
3498 		return 0;
3499 	if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts)
3500 		return 0;
3501 	if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts)
3502 		return 0;
3503 	if (a == &dev_attr_fast_io_fail_tmo.attr && !ctrl->opts)
3504 		return 0;
3505 
3506 	return a->mode;
3507 }
3508 
3509 static const struct attribute_group nvme_dev_attrs_group = {
3510 	.attrs		= nvme_dev_attrs,
3511 	.is_visible	= nvme_dev_attrs_are_visible,
3512 };
3513 
3514 static const struct attribute_group *nvme_dev_attr_groups[] = {
3515 	&nvme_dev_attrs_group,
3516 	NULL,
3517 };
3518 
3519 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3520 		unsigned nsid)
3521 {
3522 	struct nvme_ns_head *h;
3523 
3524 	lockdep_assert_held(&subsys->lock);
3525 
3526 	list_for_each_entry(h, &subsys->nsheads, entry) {
3527 		if (h->ns_id != nsid)
3528 			continue;
3529 		if (!list_empty(&h->list) && nvme_tryget_ns_head(h))
3530 			return h;
3531 	}
3532 
3533 	return NULL;
3534 }
3535 
3536 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3537 		struct nvme_ns_head *new)
3538 {
3539 	struct nvme_ns_head *h;
3540 
3541 	lockdep_assert_held(&subsys->lock);
3542 
3543 	list_for_each_entry(h, &subsys->nsheads, entry) {
3544 		if (nvme_ns_ids_valid(&new->ids) &&
3545 		    nvme_ns_ids_equal(&new->ids, &h->ids))
3546 			return -EINVAL;
3547 	}
3548 
3549 	return 0;
3550 }
3551 
3552 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
3553 {
3554 	cdev_device_del(cdev, cdev_device);
3555 	ida_simple_remove(&nvme_ns_chr_minor_ida, MINOR(cdev_device->devt));
3556 }
3557 
3558 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
3559 		const struct file_operations *fops, struct module *owner)
3560 {
3561 	int minor, ret;
3562 
3563 	minor = ida_simple_get(&nvme_ns_chr_minor_ida, 0, 0, GFP_KERNEL);
3564 	if (minor < 0)
3565 		return minor;
3566 	cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
3567 	cdev_device->class = nvme_ns_chr_class;
3568 	device_initialize(cdev_device);
3569 	cdev_init(cdev, fops);
3570 	cdev->owner = owner;
3571 	ret = cdev_device_add(cdev, cdev_device);
3572 	if (ret) {
3573 		put_device(cdev_device);
3574 		ida_simple_remove(&nvme_ns_chr_minor_ida, minor);
3575 	}
3576 	return ret;
3577 }
3578 
3579 static int nvme_ns_chr_open(struct inode *inode, struct file *file)
3580 {
3581 	return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
3582 }
3583 
3584 static int nvme_ns_chr_release(struct inode *inode, struct file *file)
3585 {
3586 	nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
3587 	return 0;
3588 }
3589 
3590 static const struct file_operations nvme_ns_chr_fops = {
3591 	.owner		= THIS_MODULE,
3592 	.open		= nvme_ns_chr_open,
3593 	.release	= nvme_ns_chr_release,
3594 	.unlocked_ioctl	= nvme_ns_chr_ioctl,
3595 	.compat_ioctl	= compat_ptr_ioctl,
3596 };
3597 
3598 static int nvme_add_ns_cdev(struct nvme_ns *ns)
3599 {
3600 	int ret;
3601 
3602 	ns->cdev_device.parent = ns->ctrl->device;
3603 	ret = dev_set_name(&ns->cdev_device, "ng%dn%d",
3604 			   ns->ctrl->instance, ns->head->instance);
3605 	if (ret)
3606 		return ret;
3607 	ret = nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops,
3608 			    ns->ctrl->ops->module);
3609 	if (ret)
3610 		kfree_const(ns->cdev_device.kobj.name);
3611 	return ret;
3612 }
3613 
3614 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3615 		unsigned nsid, struct nvme_ns_ids *ids)
3616 {
3617 	struct nvme_ns_head *head;
3618 	size_t size = sizeof(*head);
3619 	int ret = -ENOMEM;
3620 
3621 #ifdef CONFIG_NVME_MULTIPATH
3622 	size += num_possible_nodes() * sizeof(struct nvme_ns *);
3623 #endif
3624 
3625 	head = kzalloc(size, GFP_KERNEL);
3626 	if (!head)
3627 		goto out;
3628 	ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3629 	if (ret < 0)
3630 		goto out_free_head;
3631 	head->instance = ret;
3632 	INIT_LIST_HEAD(&head->list);
3633 	ret = init_srcu_struct(&head->srcu);
3634 	if (ret)
3635 		goto out_ida_remove;
3636 	head->subsys = ctrl->subsys;
3637 	head->ns_id = nsid;
3638 	head->ids = *ids;
3639 	kref_init(&head->ref);
3640 
3641 	ret = __nvme_check_ids(ctrl->subsys, head);
3642 	if (ret) {
3643 		dev_err(ctrl->device,
3644 			"duplicate IDs for nsid %d\n", nsid);
3645 		goto out_cleanup_srcu;
3646 	}
3647 
3648 	if (head->ids.csi) {
3649 		ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3650 		if (ret)
3651 			goto out_cleanup_srcu;
3652 	} else
3653 		head->effects = ctrl->effects;
3654 
3655 	ret = nvme_mpath_alloc_disk(ctrl, head);
3656 	if (ret)
3657 		goto out_cleanup_srcu;
3658 
3659 	list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3660 
3661 	kref_get(&ctrl->subsys->ref);
3662 
3663 	return head;
3664 out_cleanup_srcu:
3665 	cleanup_srcu_struct(&head->srcu);
3666 out_ida_remove:
3667 	ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3668 out_free_head:
3669 	kfree(head);
3670 out:
3671 	if (ret > 0)
3672 		ret = blk_status_to_errno(nvme_error_status(ret));
3673 	return ERR_PTR(ret);
3674 }
3675 
3676 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3677 		struct nvme_ns_ids *ids, bool is_shared)
3678 {
3679 	struct nvme_ctrl *ctrl = ns->ctrl;
3680 	struct nvme_ns_head *head = NULL;
3681 	int ret = 0;
3682 
3683 	mutex_lock(&ctrl->subsys->lock);
3684 	head = nvme_find_ns_head(ctrl->subsys, nsid);
3685 	if (!head) {
3686 		head = nvme_alloc_ns_head(ctrl, nsid, ids);
3687 		if (IS_ERR(head)) {
3688 			ret = PTR_ERR(head);
3689 			goto out_unlock;
3690 		}
3691 		head->shared = is_shared;
3692 	} else {
3693 		ret = -EINVAL;
3694 		if (!is_shared || !head->shared) {
3695 			dev_err(ctrl->device,
3696 				"Duplicate unshared namespace %d\n", nsid);
3697 			goto out_put_ns_head;
3698 		}
3699 		if (!nvme_ns_ids_equal(&head->ids, ids)) {
3700 			dev_err(ctrl->device,
3701 				"IDs don't match for shared namespace %d\n",
3702 					nsid);
3703 			goto out_put_ns_head;
3704 		}
3705 	}
3706 
3707 	list_add_tail_rcu(&ns->siblings, &head->list);
3708 	ns->head = head;
3709 	mutex_unlock(&ctrl->subsys->lock);
3710 	return 0;
3711 
3712 out_put_ns_head:
3713 	nvme_put_ns_head(head);
3714 out_unlock:
3715 	mutex_unlock(&ctrl->subsys->lock);
3716 	return ret;
3717 }
3718 
3719 static int ns_cmp(void *priv, const struct list_head *a,
3720 		const struct list_head *b)
3721 {
3722 	struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3723 	struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3724 
3725 	return nsa->head->ns_id - nsb->head->ns_id;
3726 }
3727 
3728 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3729 {
3730 	struct nvme_ns *ns, *ret = NULL;
3731 
3732 	down_read(&ctrl->namespaces_rwsem);
3733 	list_for_each_entry(ns, &ctrl->namespaces, list) {
3734 		if (ns->head->ns_id == nsid) {
3735 			if (!nvme_get_ns(ns))
3736 				continue;
3737 			ret = ns;
3738 			break;
3739 		}
3740 		if (ns->head->ns_id > nsid)
3741 			break;
3742 	}
3743 	up_read(&ctrl->namespaces_rwsem);
3744 	return ret;
3745 }
3746 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3747 
3748 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid,
3749 		struct nvme_ns_ids *ids)
3750 {
3751 	struct nvme_ns *ns;
3752 	struct gendisk *disk;
3753 	struct nvme_id_ns *id;
3754 	int node = ctrl->numa_node;
3755 
3756 	if (nvme_identify_ns(ctrl, nsid, ids, &id))
3757 		return;
3758 
3759 	ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3760 	if (!ns)
3761 		goto out_free_id;
3762 
3763 	disk = blk_mq_alloc_disk(ctrl->tagset, ns);
3764 	if (IS_ERR(disk))
3765 		goto out_free_ns;
3766 	disk->fops = &nvme_bdev_ops;
3767 	disk->private_data = ns;
3768 
3769 	ns->disk = disk;
3770 	ns->queue = disk->queue;
3771 
3772 	if (ctrl->opts && ctrl->opts->data_digest)
3773 		blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, ns->queue);
3774 
3775 	blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3776 	if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3777 		blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3778 
3779 	ns->ctrl = ctrl;
3780 	kref_init(&ns->kref);
3781 
3782 	if (nvme_init_ns_head(ns, nsid, ids, id->nmic & NVME_NS_NMIC_SHARED))
3783 		goto out_cleanup_disk;
3784 
3785 	/*
3786 	 * Without the multipath code enabled, multiple controller per
3787 	 * subsystems are visible as devices and thus we cannot use the
3788 	 * subsystem instance.
3789 	 */
3790 	if (!nvme_mpath_set_disk_name(ns, disk->disk_name, &disk->flags))
3791 		sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
3792 			ns->head->instance);
3793 
3794 	if (nvme_update_ns_info(ns, id))
3795 		goto out_unlink_ns;
3796 
3797 	down_write(&ctrl->namespaces_rwsem);
3798 	list_add_tail(&ns->list, &ctrl->namespaces);
3799 	up_write(&ctrl->namespaces_rwsem);
3800 
3801 	nvme_get_ctrl(ctrl);
3802 
3803 	if (device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups))
3804 		goto out_cleanup_ns_from_list;
3805 
3806 	if (!nvme_ns_head_multipath(ns->head))
3807 		nvme_add_ns_cdev(ns);
3808 
3809 	nvme_mpath_add_disk(ns, id);
3810 	nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3811 	kfree(id);
3812 
3813 	return;
3814 
3815  out_cleanup_ns_from_list:
3816 	nvme_put_ctrl(ctrl);
3817 	down_write(&ctrl->namespaces_rwsem);
3818 	list_del_init(&ns->list);
3819 	up_write(&ctrl->namespaces_rwsem);
3820  out_unlink_ns:
3821 	mutex_lock(&ctrl->subsys->lock);
3822 	list_del_rcu(&ns->siblings);
3823 	if (list_empty(&ns->head->list))
3824 		list_del_init(&ns->head->entry);
3825 	mutex_unlock(&ctrl->subsys->lock);
3826 	nvme_put_ns_head(ns->head);
3827  out_cleanup_disk:
3828 	blk_cleanup_disk(disk);
3829  out_free_ns:
3830 	kfree(ns);
3831  out_free_id:
3832 	kfree(id);
3833 }
3834 
3835 static void nvme_ns_remove(struct nvme_ns *ns)
3836 {
3837 	bool last_path = false;
3838 
3839 	if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3840 		return;
3841 
3842 	clear_bit(NVME_NS_READY, &ns->flags);
3843 	set_capacity(ns->disk, 0);
3844 	nvme_fault_inject_fini(&ns->fault_inject);
3845 
3846 	mutex_lock(&ns->ctrl->subsys->lock);
3847 	list_del_rcu(&ns->siblings);
3848 	if (list_empty(&ns->head->list)) {
3849 		list_del_init(&ns->head->entry);
3850 		last_path = true;
3851 	}
3852 	mutex_unlock(&ns->ctrl->subsys->lock);
3853 
3854 	/* guarantee not available in head->list */
3855 	synchronize_rcu();
3856 
3857 	/* wait for concurrent submissions */
3858 	if (nvme_mpath_clear_current_path(ns))
3859 		synchronize_srcu(&ns->head->srcu);
3860 
3861 	if (!nvme_ns_head_multipath(ns->head))
3862 		nvme_cdev_del(&ns->cdev, &ns->cdev_device);
3863 	del_gendisk(ns->disk);
3864 	blk_cleanup_queue(ns->queue);
3865 
3866 	down_write(&ns->ctrl->namespaces_rwsem);
3867 	list_del_init(&ns->list);
3868 	up_write(&ns->ctrl->namespaces_rwsem);
3869 
3870 	if (last_path)
3871 		nvme_mpath_shutdown_disk(ns->head);
3872 	nvme_put_ns(ns);
3873 }
3874 
3875 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
3876 {
3877 	struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
3878 
3879 	if (ns) {
3880 		nvme_ns_remove(ns);
3881 		nvme_put_ns(ns);
3882 	}
3883 }
3884 
3885 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_ids *ids)
3886 {
3887 	struct nvme_id_ns *id;
3888 	int ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3889 
3890 	if (test_bit(NVME_NS_DEAD, &ns->flags))
3891 		goto out;
3892 
3893 	ret = nvme_identify_ns(ns->ctrl, ns->head->ns_id, ids, &id);
3894 	if (ret)
3895 		goto out;
3896 
3897 	ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3898 	if (!nvme_ns_ids_equal(&ns->head->ids, ids)) {
3899 		dev_err(ns->ctrl->device,
3900 			"identifiers changed for nsid %d\n", ns->head->ns_id);
3901 		goto out_free_id;
3902 	}
3903 
3904 	ret = nvme_update_ns_info(ns, id);
3905 
3906 out_free_id:
3907 	kfree(id);
3908 out:
3909 	/*
3910 	 * Only remove the namespace if we got a fatal error back from the
3911 	 * device, otherwise ignore the error and just move on.
3912 	 *
3913 	 * TODO: we should probably schedule a delayed retry here.
3914 	 */
3915 	if (ret > 0 && (ret & NVME_SC_DNR))
3916 		nvme_ns_remove(ns);
3917 }
3918 
3919 static void nvme_validate_or_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3920 {
3921 	struct nvme_ns_ids ids = { };
3922 	struct nvme_ns *ns;
3923 
3924 	if (nvme_identify_ns_descs(ctrl, nsid, &ids))
3925 		return;
3926 
3927 	ns = nvme_find_get_ns(ctrl, nsid);
3928 	if (ns) {
3929 		nvme_validate_ns(ns, &ids);
3930 		nvme_put_ns(ns);
3931 		return;
3932 	}
3933 
3934 	switch (ids.csi) {
3935 	case NVME_CSI_NVM:
3936 		nvme_alloc_ns(ctrl, nsid, &ids);
3937 		break;
3938 	case NVME_CSI_ZNS:
3939 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
3940 			dev_warn(ctrl->device,
3941 				"nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
3942 				nsid);
3943 			break;
3944 		}
3945 		if (!nvme_multi_css(ctrl)) {
3946 			dev_warn(ctrl->device,
3947 				"command set not reported for nsid: %d\n",
3948 				nsid);
3949 			break;
3950 		}
3951 		nvme_alloc_ns(ctrl, nsid, &ids);
3952 		break;
3953 	default:
3954 		dev_warn(ctrl->device, "unknown csi %u for nsid %u\n",
3955 			ids.csi, nsid);
3956 		break;
3957 	}
3958 }
3959 
3960 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3961 					unsigned nsid)
3962 {
3963 	struct nvme_ns *ns, *next;
3964 	LIST_HEAD(rm_list);
3965 
3966 	down_write(&ctrl->namespaces_rwsem);
3967 	list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3968 		if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
3969 			list_move_tail(&ns->list, &rm_list);
3970 	}
3971 	up_write(&ctrl->namespaces_rwsem);
3972 
3973 	list_for_each_entry_safe(ns, next, &rm_list, list)
3974 		nvme_ns_remove(ns);
3975 
3976 }
3977 
3978 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
3979 {
3980 	const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
3981 	__le32 *ns_list;
3982 	u32 prev = 0;
3983 	int ret = 0, i;
3984 
3985 	if (nvme_ctrl_limited_cns(ctrl))
3986 		return -EOPNOTSUPP;
3987 
3988 	ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3989 	if (!ns_list)
3990 		return -ENOMEM;
3991 
3992 	for (;;) {
3993 		struct nvme_command cmd = {
3994 			.identify.opcode	= nvme_admin_identify,
3995 			.identify.cns		= NVME_ID_CNS_NS_ACTIVE_LIST,
3996 			.identify.nsid		= cpu_to_le32(prev),
3997 		};
3998 
3999 		ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
4000 					    NVME_IDENTIFY_DATA_SIZE);
4001 		if (ret) {
4002 			dev_warn(ctrl->device,
4003 				"Identify NS List failed (status=0x%x)\n", ret);
4004 			goto free;
4005 		}
4006 
4007 		for (i = 0; i < nr_entries; i++) {
4008 			u32 nsid = le32_to_cpu(ns_list[i]);
4009 
4010 			if (!nsid)	/* end of the list? */
4011 				goto out;
4012 			nvme_validate_or_alloc_ns(ctrl, nsid);
4013 			while (++prev < nsid)
4014 				nvme_ns_remove_by_nsid(ctrl, prev);
4015 		}
4016 	}
4017  out:
4018 	nvme_remove_invalid_namespaces(ctrl, prev);
4019  free:
4020 	kfree(ns_list);
4021 	return ret;
4022 }
4023 
4024 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
4025 {
4026 	struct nvme_id_ctrl *id;
4027 	u32 nn, i;
4028 
4029 	if (nvme_identify_ctrl(ctrl, &id))
4030 		return;
4031 	nn = le32_to_cpu(id->nn);
4032 	kfree(id);
4033 
4034 	for (i = 1; i <= nn; i++)
4035 		nvme_validate_or_alloc_ns(ctrl, i);
4036 
4037 	nvme_remove_invalid_namespaces(ctrl, nn);
4038 }
4039 
4040 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
4041 {
4042 	size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
4043 	__le32 *log;
4044 	int error;
4045 
4046 	log = kzalloc(log_size, GFP_KERNEL);
4047 	if (!log)
4048 		return;
4049 
4050 	/*
4051 	 * We need to read the log to clear the AEN, but we don't want to rely
4052 	 * on it for the changed namespace information as userspace could have
4053 	 * raced with us in reading the log page, which could cause us to miss
4054 	 * updates.
4055 	 */
4056 	error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
4057 			NVME_CSI_NVM, log, log_size, 0);
4058 	if (error)
4059 		dev_warn(ctrl->device,
4060 			"reading changed ns log failed: %d\n", error);
4061 
4062 	kfree(log);
4063 }
4064 
4065 static void nvme_scan_work(struct work_struct *work)
4066 {
4067 	struct nvme_ctrl *ctrl =
4068 		container_of(work, struct nvme_ctrl, scan_work);
4069 
4070 	/* No tagset on a live ctrl means IO queues could not created */
4071 	if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
4072 		return;
4073 
4074 	if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
4075 		dev_info(ctrl->device, "rescanning namespaces.\n");
4076 		nvme_clear_changed_ns_log(ctrl);
4077 	}
4078 
4079 	mutex_lock(&ctrl->scan_lock);
4080 	if (nvme_scan_ns_list(ctrl) != 0)
4081 		nvme_scan_ns_sequential(ctrl);
4082 	mutex_unlock(&ctrl->scan_lock);
4083 
4084 	down_write(&ctrl->namespaces_rwsem);
4085 	list_sort(NULL, &ctrl->namespaces, ns_cmp);
4086 	up_write(&ctrl->namespaces_rwsem);
4087 }
4088 
4089 /*
4090  * This function iterates the namespace list unlocked to allow recovery from
4091  * controller failure. It is up to the caller to ensure the namespace list is
4092  * not modified by scan work while this function is executing.
4093  */
4094 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
4095 {
4096 	struct nvme_ns *ns, *next;
4097 	LIST_HEAD(ns_list);
4098 
4099 	/*
4100 	 * make sure to requeue I/O to all namespaces as these
4101 	 * might result from the scan itself and must complete
4102 	 * for the scan_work to make progress
4103 	 */
4104 	nvme_mpath_clear_ctrl_paths(ctrl);
4105 
4106 	/* prevent racing with ns scanning */
4107 	flush_work(&ctrl->scan_work);
4108 
4109 	/*
4110 	 * The dead states indicates the controller was not gracefully
4111 	 * disconnected. In that case, we won't be able to flush any data while
4112 	 * removing the namespaces' disks; fail all the queues now to avoid
4113 	 * potentially having to clean up the failed sync later.
4114 	 */
4115 	if (ctrl->state == NVME_CTRL_DEAD)
4116 		nvme_kill_queues(ctrl);
4117 
4118 	/* this is a no-op when called from the controller reset handler */
4119 	nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4120 
4121 	down_write(&ctrl->namespaces_rwsem);
4122 	list_splice_init(&ctrl->namespaces, &ns_list);
4123 	up_write(&ctrl->namespaces_rwsem);
4124 
4125 	list_for_each_entry_safe(ns, next, &ns_list, list)
4126 		nvme_ns_remove(ns);
4127 }
4128 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4129 
4130 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
4131 {
4132 	struct nvme_ctrl *ctrl =
4133 		container_of(dev, struct nvme_ctrl, ctrl_device);
4134 	struct nvmf_ctrl_options *opts = ctrl->opts;
4135 	int ret;
4136 
4137 	ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4138 	if (ret)
4139 		return ret;
4140 
4141 	if (opts) {
4142 		ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4143 		if (ret)
4144 			return ret;
4145 
4146 		ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4147 				opts->trsvcid ?: "none");
4148 		if (ret)
4149 			return ret;
4150 
4151 		ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4152 				opts->host_traddr ?: "none");
4153 		if (ret)
4154 			return ret;
4155 
4156 		ret = add_uevent_var(env, "NVME_HOST_IFACE=%s",
4157 				opts->host_iface ?: "none");
4158 	}
4159 	return ret;
4160 }
4161 
4162 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4163 {
4164 	char *envp[2] = { NULL, NULL };
4165 	u32 aen_result = ctrl->aen_result;
4166 
4167 	ctrl->aen_result = 0;
4168 	if (!aen_result)
4169 		return;
4170 
4171 	envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4172 	if (!envp[0])
4173 		return;
4174 	kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4175 	kfree(envp[0]);
4176 }
4177 
4178 static void nvme_async_event_work(struct work_struct *work)
4179 {
4180 	struct nvme_ctrl *ctrl =
4181 		container_of(work, struct nvme_ctrl, async_event_work);
4182 
4183 	nvme_aen_uevent(ctrl);
4184 	ctrl->ops->submit_async_event(ctrl);
4185 }
4186 
4187 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4188 {
4189 
4190 	u32 csts;
4191 
4192 	if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4193 		return false;
4194 
4195 	if (csts == ~0)
4196 		return false;
4197 
4198 	return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4199 }
4200 
4201 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4202 {
4203 	struct nvme_fw_slot_info_log *log;
4204 
4205 	log = kmalloc(sizeof(*log), GFP_KERNEL);
4206 	if (!log)
4207 		return;
4208 
4209 	if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4210 			log, sizeof(*log), 0))
4211 		dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4212 	kfree(log);
4213 }
4214 
4215 static void nvme_fw_act_work(struct work_struct *work)
4216 {
4217 	struct nvme_ctrl *ctrl = container_of(work,
4218 				struct nvme_ctrl, fw_act_work);
4219 	unsigned long fw_act_timeout;
4220 
4221 	if (ctrl->mtfa)
4222 		fw_act_timeout = jiffies +
4223 				msecs_to_jiffies(ctrl->mtfa * 100);
4224 	else
4225 		fw_act_timeout = jiffies +
4226 				msecs_to_jiffies(admin_timeout * 1000);
4227 
4228 	nvme_stop_queues(ctrl);
4229 	while (nvme_ctrl_pp_status(ctrl)) {
4230 		if (time_after(jiffies, fw_act_timeout)) {
4231 			dev_warn(ctrl->device,
4232 				"Fw activation timeout, reset controller\n");
4233 			nvme_try_sched_reset(ctrl);
4234 			return;
4235 		}
4236 		msleep(100);
4237 	}
4238 
4239 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4240 		return;
4241 
4242 	nvme_start_queues(ctrl);
4243 	/* read FW slot information to clear the AER */
4244 	nvme_get_fw_slot_info(ctrl);
4245 }
4246 
4247 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4248 {
4249 	u32 aer_notice_type = (result & 0xff00) >> 8;
4250 
4251 	trace_nvme_async_event(ctrl, aer_notice_type);
4252 
4253 	switch (aer_notice_type) {
4254 	case NVME_AER_NOTICE_NS_CHANGED:
4255 		set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4256 		nvme_queue_scan(ctrl);
4257 		break;
4258 	case NVME_AER_NOTICE_FW_ACT_STARTING:
4259 		/*
4260 		 * We are (ab)using the RESETTING state to prevent subsequent
4261 		 * recovery actions from interfering with the controller's
4262 		 * firmware activation.
4263 		 */
4264 		if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4265 			queue_work(nvme_wq, &ctrl->fw_act_work);
4266 		break;
4267 #ifdef CONFIG_NVME_MULTIPATH
4268 	case NVME_AER_NOTICE_ANA:
4269 		if (!ctrl->ana_log_buf)
4270 			break;
4271 		queue_work(nvme_wq, &ctrl->ana_work);
4272 		break;
4273 #endif
4274 	case NVME_AER_NOTICE_DISC_CHANGED:
4275 		ctrl->aen_result = result;
4276 		break;
4277 	default:
4278 		dev_warn(ctrl->device, "async event result %08x\n", result);
4279 	}
4280 }
4281 
4282 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4283 		volatile union nvme_result *res)
4284 {
4285 	u32 result = le32_to_cpu(res->u32);
4286 	u32 aer_type = result & 0x07;
4287 
4288 	if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4289 		return;
4290 
4291 	switch (aer_type) {
4292 	case NVME_AER_NOTICE:
4293 		nvme_handle_aen_notice(ctrl, result);
4294 		break;
4295 	case NVME_AER_ERROR:
4296 	case NVME_AER_SMART:
4297 	case NVME_AER_CSS:
4298 	case NVME_AER_VS:
4299 		trace_nvme_async_event(ctrl, aer_type);
4300 		ctrl->aen_result = result;
4301 		break;
4302 	default:
4303 		break;
4304 	}
4305 	queue_work(nvme_wq, &ctrl->async_event_work);
4306 }
4307 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4308 
4309 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4310 {
4311 	nvme_mpath_stop(ctrl);
4312 	nvme_stop_keep_alive(ctrl);
4313 	nvme_stop_failfast_work(ctrl);
4314 	flush_work(&ctrl->async_event_work);
4315 	cancel_work_sync(&ctrl->fw_act_work);
4316 }
4317 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4318 
4319 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4320 {
4321 	nvme_start_keep_alive(ctrl);
4322 
4323 	nvme_enable_aen(ctrl);
4324 
4325 	if (ctrl->queue_count > 1) {
4326 		nvme_queue_scan(ctrl);
4327 		nvme_start_queues(ctrl);
4328 	}
4329 }
4330 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4331 
4332 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4333 {
4334 	nvme_hwmon_exit(ctrl);
4335 	nvme_fault_inject_fini(&ctrl->fault_inject);
4336 	dev_pm_qos_hide_latency_tolerance(ctrl->device);
4337 	cdev_device_del(&ctrl->cdev, ctrl->device);
4338 	nvme_put_ctrl(ctrl);
4339 }
4340 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4341 
4342 static void nvme_free_cels(struct nvme_ctrl *ctrl)
4343 {
4344 	struct nvme_effects_log	*cel;
4345 	unsigned long i;
4346 
4347 	xa_for_each(&ctrl->cels, i, cel) {
4348 		xa_erase(&ctrl->cels, i);
4349 		kfree(cel);
4350 	}
4351 
4352 	xa_destroy(&ctrl->cels);
4353 }
4354 
4355 static void nvme_free_ctrl(struct device *dev)
4356 {
4357 	struct nvme_ctrl *ctrl =
4358 		container_of(dev, struct nvme_ctrl, ctrl_device);
4359 	struct nvme_subsystem *subsys = ctrl->subsys;
4360 
4361 	if (!subsys || ctrl->instance != subsys->instance)
4362 		ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4363 
4364 	nvme_free_cels(ctrl);
4365 	nvme_mpath_uninit(ctrl);
4366 	__free_page(ctrl->discard_page);
4367 
4368 	if (subsys) {
4369 		mutex_lock(&nvme_subsystems_lock);
4370 		list_del(&ctrl->subsys_entry);
4371 		sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4372 		mutex_unlock(&nvme_subsystems_lock);
4373 	}
4374 
4375 	ctrl->ops->free_ctrl(ctrl);
4376 
4377 	if (subsys)
4378 		nvme_put_subsystem(subsys);
4379 }
4380 
4381 /*
4382  * Initialize a NVMe controller structures.  This needs to be called during
4383  * earliest initialization so that we have the initialized structured around
4384  * during probing.
4385  */
4386 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4387 		const struct nvme_ctrl_ops *ops, unsigned long quirks)
4388 {
4389 	int ret;
4390 
4391 	ctrl->state = NVME_CTRL_NEW;
4392 	clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
4393 	spin_lock_init(&ctrl->lock);
4394 	mutex_init(&ctrl->scan_lock);
4395 	INIT_LIST_HEAD(&ctrl->namespaces);
4396 	xa_init(&ctrl->cels);
4397 	init_rwsem(&ctrl->namespaces_rwsem);
4398 	ctrl->dev = dev;
4399 	ctrl->ops = ops;
4400 	ctrl->quirks = quirks;
4401 	ctrl->numa_node = NUMA_NO_NODE;
4402 	INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4403 	INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4404 	INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4405 	INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4406 	init_waitqueue_head(&ctrl->state_wq);
4407 
4408 	INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4409 	INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
4410 	memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4411 	ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4412 
4413 	BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4414 			PAGE_SIZE);
4415 	ctrl->discard_page = alloc_page(GFP_KERNEL);
4416 	if (!ctrl->discard_page) {
4417 		ret = -ENOMEM;
4418 		goto out;
4419 	}
4420 
4421 	ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4422 	if (ret < 0)
4423 		goto out;
4424 	ctrl->instance = ret;
4425 
4426 	device_initialize(&ctrl->ctrl_device);
4427 	ctrl->device = &ctrl->ctrl_device;
4428 	ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
4429 			ctrl->instance);
4430 	ctrl->device->class = nvme_class;
4431 	ctrl->device->parent = ctrl->dev;
4432 	ctrl->device->groups = nvme_dev_attr_groups;
4433 	ctrl->device->release = nvme_free_ctrl;
4434 	dev_set_drvdata(ctrl->device, ctrl);
4435 	ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4436 	if (ret)
4437 		goto out_release_instance;
4438 
4439 	nvme_get_ctrl(ctrl);
4440 	cdev_init(&ctrl->cdev, &nvme_dev_fops);
4441 	ctrl->cdev.owner = ops->module;
4442 	ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4443 	if (ret)
4444 		goto out_free_name;
4445 
4446 	/*
4447 	 * Initialize latency tolerance controls.  The sysfs files won't
4448 	 * be visible to userspace unless the device actually supports APST.
4449 	 */
4450 	ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4451 	dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4452 		min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4453 
4454 	nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4455 	nvme_mpath_init_ctrl(ctrl);
4456 
4457 	return 0;
4458 out_free_name:
4459 	nvme_put_ctrl(ctrl);
4460 	kfree_const(ctrl->device->kobj.name);
4461 out_release_instance:
4462 	ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4463 out:
4464 	if (ctrl->discard_page)
4465 		__free_page(ctrl->discard_page);
4466 	return ret;
4467 }
4468 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4469 
4470 /**
4471  * nvme_kill_queues(): Ends all namespace queues
4472  * @ctrl: the dead controller that needs to end
4473  *
4474  * Call this function when the driver determines it is unable to get the
4475  * controller in a state capable of servicing IO.
4476  */
4477 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4478 {
4479 	struct nvme_ns *ns;
4480 
4481 	down_read(&ctrl->namespaces_rwsem);
4482 
4483 	/* Forcibly unquiesce queues to avoid blocking dispatch */
4484 	if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4485 		blk_mq_unquiesce_queue(ctrl->admin_q);
4486 
4487 	list_for_each_entry(ns, &ctrl->namespaces, list)
4488 		nvme_set_queue_dying(ns);
4489 
4490 	up_read(&ctrl->namespaces_rwsem);
4491 }
4492 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4493 
4494 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4495 {
4496 	struct nvme_ns *ns;
4497 
4498 	down_read(&ctrl->namespaces_rwsem);
4499 	list_for_each_entry(ns, &ctrl->namespaces, list)
4500 		blk_mq_unfreeze_queue(ns->queue);
4501 	up_read(&ctrl->namespaces_rwsem);
4502 }
4503 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4504 
4505 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4506 {
4507 	struct nvme_ns *ns;
4508 
4509 	down_read(&ctrl->namespaces_rwsem);
4510 	list_for_each_entry(ns, &ctrl->namespaces, list) {
4511 		timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4512 		if (timeout <= 0)
4513 			break;
4514 	}
4515 	up_read(&ctrl->namespaces_rwsem);
4516 	return timeout;
4517 }
4518 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4519 
4520 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4521 {
4522 	struct nvme_ns *ns;
4523 
4524 	down_read(&ctrl->namespaces_rwsem);
4525 	list_for_each_entry(ns, &ctrl->namespaces, list)
4526 		blk_mq_freeze_queue_wait(ns->queue);
4527 	up_read(&ctrl->namespaces_rwsem);
4528 }
4529 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4530 
4531 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4532 {
4533 	struct nvme_ns *ns;
4534 
4535 	down_read(&ctrl->namespaces_rwsem);
4536 	list_for_each_entry(ns, &ctrl->namespaces, list)
4537 		blk_freeze_queue_start(ns->queue);
4538 	up_read(&ctrl->namespaces_rwsem);
4539 }
4540 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4541 
4542 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4543 {
4544 	struct nvme_ns *ns;
4545 
4546 	down_read(&ctrl->namespaces_rwsem);
4547 	list_for_each_entry(ns, &ctrl->namespaces, list)
4548 		blk_mq_quiesce_queue(ns->queue);
4549 	up_read(&ctrl->namespaces_rwsem);
4550 }
4551 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4552 
4553 void nvme_start_queues(struct nvme_ctrl *ctrl)
4554 {
4555 	struct nvme_ns *ns;
4556 
4557 	down_read(&ctrl->namespaces_rwsem);
4558 	list_for_each_entry(ns, &ctrl->namespaces, list)
4559 		blk_mq_unquiesce_queue(ns->queue);
4560 	up_read(&ctrl->namespaces_rwsem);
4561 }
4562 EXPORT_SYMBOL_GPL(nvme_start_queues);
4563 
4564 void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
4565 {
4566 	struct nvme_ns *ns;
4567 
4568 	down_read(&ctrl->namespaces_rwsem);
4569 	list_for_each_entry(ns, &ctrl->namespaces, list)
4570 		blk_sync_queue(ns->queue);
4571 	up_read(&ctrl->namespaces_rwsem);
4572 }
4573 EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
4574 
4575 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4576 {
4577 	nvme_sync_io_queues(ctrl);
4578 	if (ctrl->admin_q)
4579 		blk_sync_queue(ctrl->admin_q);
4580 }
4581 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4582 
4583 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
4584 {
4585 	if (file->f_op != &nvme_dev_fops)
4586 		return NULL;
4587 	return file->private_data;
4588 }
4589 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU);
4590 
4591 /*
4592  * Check we didn't inadvertently grow the command structure sizes:
4593  */
4594 static inline void _nvme_check_size(void)
4595 {
4596 	BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4597 	BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4598 	BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4599 	BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4600 	BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4601 	BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4602 	BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4603 	BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4604 	BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4605 	BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4606 	BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4607 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4608 	BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4609 	BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4610 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4611 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
4612 	BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4613 	BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4614 	BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4615 	BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4616 }
4617 
4618 
4619 static int __init nvme_core_init(void)
4620 {
4621 	int result = -ENOMEM;
4622 
4623 	_nvme_check_size();
4624 
4625 	nvme_wq = alloc_workqueue("nvme-wq",
4626 			WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4627 	if (!nvme_wq)
4628 		goto out;
4629 
4630 	nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4631 			WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4632 	if (!nvme_reset_wq)
4633 		goto destroy_wq;
4634 
4635 	nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4636 			WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4637 	if (!nvme_delete_wq)
4638 		goto destroy_reset_wq;
4639 
4640 	result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
4641 			NVME_MINORS, "nvme");
4642 	if (result < 0)
4643 		goto destroy_delete_wq;
4644 
4645 	nvme_class = class_create(THIS_MODULE, "nvme");
4646 	if (IS_ERR(nvme_class)) {
4647 		result = PTR_ERR(nvme_class);
4648 		goto unregister_chrdev;
4649 	}
4650 	nvme_class->dev_uevent = nvme_class_uevent;
4651 
4652 	nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4653 	if (IS_ERR(nvme_subsys_class)) {
4654 		result = PTR_ERR(nvme_subsys_class);
4655 		goto destroy_class;
4656 	}
4657 
4658 	result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
4659 				     "nvme-generic");
4660 	if (result < 0)
4661 		goto destroy_subsys_class;
4662 
4663 	nvme_ns_chr_class = class_create(THIS_MODULE, "nvme-generic");
4664 	if (IS_ERR(nvme_ns_chr_class)) {
4665 		result = PTR_ERR(nvme_ns_chr_class);
4666 		goto unregister_generic_ns;
4667 	}
4668 
4669 	return 0;
4670 
4671 unregister_generic_ns:
4672 	unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4673 destroy_subsys_class:
4674 	class_destroy(nvme_subsys_class);
4675 destroy_class:
4676 	class_destroy(nvme_class);
4677 unregister_chrdev:
4678 	unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4679 destroy_delete_wq:
4680 	destroy_workqueue(nvme_delete_wq);
4681 destroy_reset_wq:
4682 	destroy_workqueue(nvme_reset_wq);
4683 destroy_wq:
4684 	destroy_workqueue(nvme_wq);
4685 out:
4686 	return result;
4687 }
4688 
4689 static void __exit nvme_core_exit(void)
4690 {
4691 	class_destroy(nvme_ns_chr_class);
4692 	class_destroy(nvme_subsys_class);
4693 	class_destroy(nvme_class);
4694 	unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4695 	unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4696 	destroy_workqueue(nvme_delete_wq);
4697 	destroy_workqueue(nvme_reset_wq);
4698 	destroy_workqueue(nvme_wq);
4699 	ida_destroy(&nvme_ns_chr_minor_ida);
4700 	ida_destroy(&nvme_instance_ida);
4701 }
4702 
4703 MODULE_LICENSE("GPL");
4704 MODULE_VERSION("1.0");
4705 module_init(nvme_core_init);
4706 module_exit(nvme_core_exit);
4707