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