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