xref: /linux/drivers/nvme/host/core.c (revision 3b7cab693ba2bab63774bf5b988e8a61b2ef0f32)
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/async.h>
8 #include <linux/blkdev.h>
9 #include <linux/blk-mq.h>
10 #include <linux/blk-integrity.h>
11 #include <linux/compat.h>
12 #include <linux/delay.h>
13 #include <linux/errno.h>
14 #include <linux/hdreg.h>
15 #include <linux/kernel.h>
16 #include <linux/module.h>
17 #include <linux/backing-dev.h>
18 #include <linux/slab.h>
19 #include <linux/types.h>
20 #include <linux/pr.h>
21 #include <linux/ptrace.h>
22 #include <linux/nvme_ioctl.h>
23 #include <linux/pm_qos.h>
24 #include <linux/ratelimit.h>
25 #include <linux/unaligned.h>
26 
27 #include "nvme.h"
28 #include "fabrics.h"
29 #include <linux/nvme-auth.h>
30 
31 #define CREATE_TRACE_POINTS
32 #include "trace.h"
33 
34 #define NVME_MINORS		(1U << MINORBITS)
35 
36 /*
37  * Write hints (bio->bi_write_stream) are u8, so FDP placement handles beyond
38  * U8_MAX can never be selected. Cap the handle count to bound both the RUH
39  * status buffer and the per-head plids array.
40  */
41 #define NVME_MAX_PLIDS		U8_MAX
42 
43 struct nvme_ns_info {
44 	struct nvme_ns_ids ids;
45 	u32 nsid;
46 	__le32 anagrpid;
47 	u8 pi_offset;
48 	u16 endgid;
49 	u64 runs;
50 	bool is_shared;
51 	bool is_readonly;
52 	bool is_ready;
53 	bool is_removed;
54 	bool is_rotational;
55 	bool no_vwc;
56 };
57 
58 unsigned int admin_timeout = 60;
59 module_param(admin_timeout, uint, 0644);
60 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
61 EXPORT_SYMBOL_GPL(admin_timeout);
62 
63 unsigned int nvme_io_timeout = 30;
64 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
65 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
66 EXPORT_SYMBOL_GPL(nvme_io_timeout);
67 
68 static unsigned char shutdown_timeout = 5;
69 module_param(shutdown_timeout, byte, 0644);
70 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
71 
72 static u8 nvme_max_retries = 5;
73 module_param_named(max_retries, nvme_max_retries, byte, 0644);
74 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
75 
76 static unsigned long default_ps_max_latency_us = 100000;
77 module_param(default_ps_max_latency_us, ulong, 0644);
78 MODULE_PARM_DESC(default_ps_max_latency_us,
79 		 "max power saving latency for new devices; use PM QOS to change per device");
80 
81 static bool force_apst;
82 module_param(force_apst, bool, 0644);
83 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
84 
85 static unsigned long apst_primary_timeout_ms = 100;
86 module_param(apst_primary_timeout_ms, ulong, 0644);
87 MODULE_PARM_DESC(apst_primary_timeout_ms,
88 	"primary APST timeout in ms");
89 
90 static unsigned long apst_secondary_timeout_ms = 2000;
91 module_param(apst_secondary_timeout_ms, ulong, 0644);
92 MODULE_PARM_DESC(apst_secondary_timeout_ms,
93 	"secondary APST timeout in ms");
94 
95 static unsigned long apst_primary_latency_tol_us = 15000;
96 module_param(apst_primary_latency_tol_us, ulong, 0644);
97 MODULE_PARM_DESC(apst_primary_latency_tol_us,
98 	"primary APST latency tolerance in us");
99 
100 static unsigned long apst_secondary_latency_tol_us = 100000;
101 module_param(apst_secondary_latency_tol_us, ulong, 0644);
102 MODULE_PARM_DESC(apst_secondary_latency_tol_us,
103 	"secondary APST latency tolerance in us");
104 
105 /*
106  * Older kernels didn't enable protection information if it was at an offset.
107  * Newer kernels do, so it breaks reads on the upgrade if such formats were
108  * used in prior kernels since the metadata written did not contain a valid
109  * checksum.
110  */
111 static bool disable_pi_offsets = false;
112 module_param(disable_pi_offsets, bool, 0444);
113 MODULE_PARM_DESC(disable_pi_offsets,
114 	"disable protection information if it has an offset");
115 
116 /*
117  * nvme_wq - hosts nvme related works that are not reset or delete
118  * nvme_reset_wq - hosts nvme reset works
119  * nvme_delete_wq - hosts nvme delete works
120  *
121  * nvme_wq will host works such as scan, aen handling, fw activation,
122  * keep-alive, periodic reconnects etc. nvme_reset_wq
123  * runs reset works which also flush works hosted on nvme_wq for
124  * serialization purposes. nvme_delete_wq host controller deletion
125  * works which flush reset works for serialization.
126  */
127 struct workqueue_struct *nvme_wq;
128 EXPORT_SYMBOL_GPL(nvme_wq);
129 
130 struct workqueue_struct *nvme_reset_wq;
131 EXPORT_SYMBOL_GPL(nvme_reset_wq);
132 
133 struct workqueue_struct *nvme_delete_wq;
134 EXPORT_SYMBOL_GPL(nvme_delete_wq);
135 
136 DEFINE_MUTEX(nvme_subsystems_lock);
137 static LIST_HEAD_GUARDED(nvme_subsystems, nvme_subsystems_lock);
138 
139 static DEFINE_IDA(nvme_instance_ida);
140 static dev_t nvme_ctrl_base_chr_devt;
141 static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env);
142 static const struct class nvme_class = {
143 	.name = "nvme",
144 	.dev_uevent = nvme_class_uevent,
145 };
146 
147 static const struct class nvme_subsys_class = {
148 	.name = "nvme-subsystem",
149 };
150 
151 static DEFINE_IDA(nvme_ns_chr_minor_ida);
152 static dev_t nvme_ns_chr_devt;
153 static const struct class nvme_ns_chr_class = {
154 	.name = "nvme-generic",
155 };
156 
157 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
158 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
159 				   struct nvme_command *cmd);
160 static int nvme_get_log_lsi(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page,
161 		u8 lsp, u8 csi, void *log, size_t size, u64 offset, u16 lsi);
162 
163 void nvme_queue_scan(struct nvme_ctrl *ctrl)
164 {
165 	/*
166 	 * Only new queue scan work when admin and IO queues are both alive
167 	 */
168 	if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE && ctrl->tagset)
169 		queue_work(nvme_wq, &ctrl->scan_work);
170 }
171 
172 /*
173  * Use this function to proceed with scheduling reset_work for a controller
174  * that had previously been set to the resetting state. This is intended for
175  * code paths that can't be interrupted by other reset attempts. A hot removal
176  * may prevent this from succeeding.
177  */
178 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
179 {
180 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_RESETTING)
181 		return -EBUSY;
182 	if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
183 		return -EBUSY;
184 	return 0;
185 }
186 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
187 
188 static void nvme_failfast_work(struct work_struct *work)
189 {
190 	struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
191 			struct nvme_ctrl, failfast_work);
192 
193 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_CONNECTING)
194 		return;
195 
196 	set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
197 	dev_info(ctrl->device, "failfast expired\n");
198 	nvme_kick_requeue_lists(ctrl);
199 }
200 
201 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
202 {
203 	if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
204 		return;
205 
206 	schedule_delayed_work(&ctrl->failfast_work,
207 			      ctrl->opts->fast_io_fail_tmo * HZ);
208 }
209 
210 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
211 {
212 	if (!ctrl->opts)
213 		return;
214 
215 	cancel_delayed_work_sync(&ctrl->failfast_work);
216 	clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
217 }
218 
219 
220 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
221 {
222 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
223 		return -EBUSY;
224 	if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
225 		return -EBUSY;
226 	return 0;
227 }
228 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
229 
230 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
231 {
232 	int ret;
233 
234 	ret = nvme_reset_ctrl(ctrl);
235 	if (!ret) {
236 		flush_work(&ctrl->reset_work);
237 		if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE)
238 			ret = -ENETRESET;
239 	}
240 
241 	return ret;
242 }
243 
244 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
245 {
246 	dev_info(ctrl->device,
247 		 "Removing ctrl: NQN \"%s\"\n", nvmf_ctrl_subsysnqn(ctrl));
248 
249 	flush_work(&ctrl->reset_work);
250 	nvme_stop_ctrl(ctrl);
251 	nvme_remove_namespaces(ctrl);
252 	ctrl->ops->delete_ctrl(ctrl);
253 	nvme_uninit_ctrl(ctrl);
254 }
255 
256 static void nvme_delete_ctrl_work(struct work_struct *work)
257 {
258 	struct nvme_ctrl *ctrl =
259 		container_of(work, struct nvme_ctrl, delete_work);
260 
261 	nvme_do_delete_ctrl(ctrl);
262 }
263 
264 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
265 {
266 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
267 		return -EBUSY;
268 	if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
269 		return -EBUSY;
270 	return 0;
271 }
272 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
273 
274 void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
275 {
276 	/*
277 	 * Keep a reference until nvme_do_delete_ctrl() complete,
278 	 * since ->delete_ctrl can free the controller.
279 	 */
280 	nvme_get_ctrl(ctrl);
281 	if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
282 		nvme_do_delete_ctrl(ctrl);
283 	nvme_put_ctrl(ctrl);
284 }
285 
286 static blk_status_t nvme_error_status(u16 status)
287 {
288 	switch (status & NVME_SCT_SC_MASK) {
289 	case NVME_SC_SUCCESS:
290 		return BLK_STS_OK;
291 	case NVME_SC_CAP_EXCEEDED:
292 		return BLK_STS_NOSPC;
293 	case NVME_SC_LBA_RANGE:
294 	case NVME_SC_CMD_INTERRUPTED:
295 	case NVME_SC_NS_NOT_READY:
296 		return BLK_STS_TARGET;
297 	case NVME_SC_BAD_ATTRIBUTES:
298 	case NVME_SC_INVALID_OPCODE:
299 	case NVME_SC_INVALID_FIELD:
300 	case NVME_SC_INVALID_NS:
301 		return BLK_STS_NOTSUPP;
302 	case NVME_SC_WRITE_FAULT:
303 	case NVME_SC_READ_ERROR:
304 	case NVME_SC_UNWRITTEN_BLOCK:
305 	case NVME_SC_ACCESS_DENIED:
306 	case NVME_SC_READ_ONLY:
307 	case NVME_SC_COMPARE_FAILED:
308 		return BLK_STS_MEDIUM;
309 	case NVME_SC_GUARD_CHECK:
310 	case NVME_SC_APPTAG_CHECK:
311 	case NVME_SC_REFTAG_CHECK:
312 	case NVME_SC_INVALID_PI:
313 		return BLK_STS_PROTECTION;
314 	case NVME_SC_RESERVATION_CONFLICT:
315 		return BLK_STS_RESV_CONFLICT;
316 	case NVME_SC_HOST_PATH_ERROR:
317 		return BLK_STS_TRANSPORT;
318 	case NVME_SC_ZONE_TOO_MANY_ACTIVE:
319 		return BLK_STS_ZONE_ACTIVE_RESOURCE;
320 	case NVME_SC_ZONE_TOO_MANY_OPEN:
321 		return BLK_STS_ZONE_OPEN_RESOURCE;
322 	default:
323 		return BLK_STS_IOERR;
324 	}
325 }
326 
327 static void nvme_retry_req(struct request *req)
328 {
329 	unsigned long delay = 0;
330 	u16 crd;
331 	struct nvme_ns *ns = req->q->queuedata;
332 
333 	/* The mask and shift result must be <= 3 */
334 	crd = (nvme_req(req)->status & NVME_STATUS_CRD) >> 11;
335 	if (crd)
336 		delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
337 
338 	nvme_req(req)->retries++;
339 	if (ns)
340 		atomic_long_inc(&ns->retries);
341 
342 	blk_mq_requeue_request(req, false);
343 	blk_mq_delay_kick_requeue_list(req->q, delay);
344 }
345 
346 static void nvme_log_error(struct request *req)
347 {
348 	struct nvme_ns *ns = req->q->queuedata;
349 	struct nvme_request *nr = nvme_req(req);
350 
351 	if (ns) {
352 		pr_err_ratelimited("%s: %s(0x%x) @ LBA %llu, %u blocks, %s (sct 0x%x / sc 0x%x) %s%s\n",
353 		       ns->disk ? ns->disk->disk_name : "?",
354 		       nvme_get_opcode_str(nr->cmd->common.opcode),
355 		       nr->cmd->common.opcode,
356 		       nvme_sect_to_lba(ns->head, blk_rq_pos(req)),
357 		       blk_rq_bytes(req) >> ns->head->lba_shift,
358 		       nvme_get_error_status_str(nr->status),
359 		       NVME_SCT(nr->status),		/* Status Code Type */
360 		       nr->status & NVME_SC_MASK,	/* Status Code */
361 		       nr->status & NVME_STATUS_MORE ? "MORE " : "",
362 		       nr->status & NVME_STATUS_DNR  ? "DNR "  : "");
363 		return;
364 	}
365 
366 	pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s\n",
367 			   dev_name(nr->ctrl->device),
368 			   nvme_get_admin_opcode_str(nr->cmd->common.opcode),
369 			   nr->cmd->common.opcode,
370 			   nvme_get_error_status_str(nr->status),
371 			   NVME_SCT(nr->status),	/* Status Code Type */
372 			   nr->status & NVME_SC_MASK,	/* Status Code */
373 			   nr->status & NVME_STATUS_MORE ? "MORE " : "",
374 			   nr->status & NVME_STATUS_DNR  ? "DNR "  : "");
375 }
376 
377 static void nvme_log_err_passthru(struct request *req)
378 {
379 	struct nvme_ns *ns = req->q->queuedata;
380 	struct nvme_request *nr = nvme_req(req);
381 
382 	pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s"
383 		"cdw10=0x%x cdw11=0x%x cdw12=0x%x cdw13=0x%x cdw14=0x%x cdw15=0x%x\n",
384 		ns ? ns->disk->disk_name : dev_name(nr->ctrl->device),
385 		ns ? nvme_get_opcode_str(nr->cmd->common.opcode) :
386 		     nvme_get_admin_opcode_str(nr->cmd->common.opcode),
387 		nr->cmd->common.opcode,
388 		nvme_get_error_status_str(nr->status),
389 		NVME_SCT(nr->status),		/* Status Code Type */
390 		nr->status & NVME_SC_MASK,	/* Status Code */
391 		nr->status & NVME_STATUS_MORE ? "MORE " : "",
392 		nr->status & NVME_STATUS_DNR  ? "DNR "  : "",
393 		le32_to_cpu(nr->cmd->common.cdw10),
394 		le32_to_cpu(nr->cmd->common.cdw11),
395 		le32_to_cpu(nr->cmd->common.cdw12),
396 		le32_to_cpu(nr->cmd->common.cdw13),
397 		le32_to_cpu(nr->cmd->common.cdw14),
398 		le32_to_cpu(nr->cmd->common.cdw15));
399 }
400 
401 enum nvme_disposition {
402 	COMPLETE,
403 	RETRY,
404 	FAILOVER,
405 	AUTHENTICATE,
406 };
407 
408 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
409 {
410 	if (likely(nvme_req(req)->status == 0))
411 		return COMPLETE;
412 
413 	if (blk_noretry_request(req) ||
414 	    (nvme_req(req)->status & NVME_STATUS_DNR) ||
415 	    nvme_req(req)->retries >= nvme_max_retries)
416 		return COMPLETE;
417 
418 	if ((nvme_req(req)->status & NVME_SCT_SC_MASK) == NVME_SC_AUTH_REQUIRED)
419 		return AUTHENTICATE;
420 
421 	if (req->cmd_flags & REQ_NVME_MPATH) {
422 		if (nvme_is_path_error(nvme_req(req)->status) ||
423 		    blk_queue_dying(req->q))
424 			return FAILOVER;
425 	} else {
426 		if (blk_queue_dying(req->q))
427 			return COMPLETE;
428 	}
429 
430 	return RETRY;
431 }
432 
433 static inline void nvme_end_req_zoned(struct request *req)
434 {
435 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
436 	    req_op(req) == REQ_OP_ZONE_APPEND) {
437 		struct nvme_ns *ns = req->q->queuedata;
438 
439 		req->__sector = nvme_lba_to_sect(ns->head,
440 			le64_to_cpu(nvme_req(req)->result.u64));
441 	}
442 }
443 
444 static inline void __nvme_end_req(struct request *req)
445 {
446 	struct nvme_ns *ns = req->q->queuedata;
447 	struct nvme_request *nr = nvme_req(req);
448 
449 	if (unlikely(nr->status && !(req->rq_flags & RQF_QUIET))) {
450 		if (blk_rq_is_passthrough(req))
451 			nvme_log_err_passthru(req);
452 		else
453 			nvme_log_error(req);
454 
455 		if (ns)
456 			atomic_long_inc(&ns->errors);
457 		else
458 			atomic_long_inc(&nr->ctrl->errors);
459 	}
460 	nvme_end_req_zoned(req);
461 	nvme_trace_bio_complete(req);
462 	if (req->cmd_flags & REQ_NVME_MPATH)
463 		nvme_mpath_end_request(req);
464 }
465 
466 void nvme_end_req(struct request *req)
467 {
468 	blk_status_t status = nvme_error_status(nvme_req(req)->status);
469 
470 	__nvme_end_req(req);
471 	blk_mq_end_request(req, status);
472 }
473 
474 static void __nvme_complete_rq(struct request *req)
475 {
476 	struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
477 
478 	nvme_cleanup_cmd(req);
479 
480 	/*
481 	 * Completions of long-running commands should not be able to
482 	 * defer sending of periodic keep alives, since the controller
483 	 * may have completed processing such commands a long time ago
484 	 * (arbitrarily close to command submission time).
485 	 * req->deadline - req->timeout is the command submission time
486 	 * in jiffies.
487 	 */
488 	if (ctrl->kas &&
489 	    req->deadline - req->timeout >= ctrl->ka_last_check_time)
490 		ctrl->comp_seen = true;
491 
492 	switch (nvme_decide_disposition(req)) {
493 	case COMPLETE:
494 		nvme_end_req(req);
495 		return;
496 	case RETRY:
497 		nvme_retry_req(req);
498 		return;
499 	case FAILOVER:
500 		nvme_failover_req(req);
501 		return;
502 	case AUTHENTICATE:
503 #ifdef CONFIG_NVME_HOST_AUTH
504 		queue_work(nvme_wq, &ctrl->dhchap_auth_work);
505 		nvme_retry_req(req);
506 #else
507 		nvme_end_req(req);
508 #endif
509 		return;
510 	}
511 }
512 
513 void nvme_complete_rq(struct request *req)
514 {
515 	trace_nvme_complete_rq(req);
516 	__nvme_complete_rq(req);
517 }
518 EXPORT_SYMBOL_GPL(nvme_complete_rq);
519 
520 void nvme_complete_batch_req(struct request *req)
521 {
522 	trace_nvme_complete_rq(req);
523 	nvme_cleanup_cmd(req);
524 	__nvme_end_req(req);
525 }
526 EXPORT_SYMBOL_GPL(nvme_complete_batch_req);
527 
528 /*
529  * Called to unwind from ->queue_rq on a failed command submission so that the
530  * multipathing code gets called to potentially failover to another path.
531  * The caller needs to unwind all transport specific resource allocations and
532  * must return propagate the return value.
533  */
534 blk_status_t nvme_host_path_error(struct request *req)
535 {
536 	nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
537 	blk_mq_set_request_complete(req);
538 	__nvme_complete_rq(req);
539 	return BLK_STS_OK;
540 }
541 EXPORT_SYMBOL_GPL(nvme_host_path_error);
542 
543 bool nvme_cancel_request(struct request *req, void *data)
544 {
545 	dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
546 				"Cancelling I/O %d", req->tag);
547 
548 	/* don't abort one completed or idle request */
549 	if (blk_mq_rq_state(req) != MQ_RQ_IN_FLIGHT)
550 		return true;
551 
552 	nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
553 	nvme_req(req)->flags |= NVME_REQ_CANCELLED;
554 	blk_mq_complete_request(req);
555 	return true;
556 }
557 EXPORT_SYMBOL_GPL(nvme_cancel_request);
558 
559 void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
560 {
561 	if (ctrl->tagset) {
562 		blk_mq_tagset_busy_iter(ctrl->tagset,
563 				nvme_cancel_request, ctrl);
564 		blk_mq_tagset_wait_completed_request(ctrl->tagset);
565 	}
566 }
567 EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
568 
569 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
570 {
571 	if (ctrl->admin_tagset) {
572 		blk_mq_tagset_busy_iter(ctrl->admin_tagset,
573 				nvme_cancel_request, ctrl);
574 		blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
575 	}
576 }
577 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
578 
579 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
580 		enum nvme_ctrl_state new_state)
581 {
582 	enum nvme_ctrl_state old_state;
583 	unsigned long flags;
584 	bool changed = false;
585 
586 	spin_lock_irqsave(&ctrl->lock, flags);
587 
588 	old_state = nvme_ctrl_state(ctrl);
589 	switch (new_state) {
590 	case NVME_CTRL_LIVE:
591 		switch (old_state) {
592 		case NVME_CTRL_CONNECTING:
593 			changed = true;
594 			fallthrough;
595 		default:
596 			break;
597 		}
598 		break;
599 	case NVME_CTRL_RESETTING:
600 		switch (old_state) {
601 		case NVME_CTRL_LIVE:
602 			changed = true;
603 			atomic_long_inc(&ctrl->nr_reset);
604 			fallthrough;
605 		default:
606 			break;
607 		}
608 		break;
609 	case NVME_CTRL_CONNECTING:
610 		switch (old_state) {
611 		case NVME_CTRL_NEW:
612 		case NVME_CTRL_RESETTING:
613 			changed = true;
614 			fallthrough;
615 		default:
616 			break;
617 		}
618 		break;
619 	case NVME_CTRL_DELETING:
620 		switch (old_state) {
621 		case NVME_CTRL_LIVE:
622 		case NVME_CTRL_RESETTING:
623 		case NVME_CTRL_CONNECTING:
624 			changed = true;
625 			fallthrough;
626 		default:
627 			break;
628 		}
629 		break;
630 	case NVME_CTRL_DELETING_NOIO:
631 		switch (old_state) {
632 		case NVME_CTRL_DELETING:
633 		case NVME_CTRL_DEAD:
634 			changed = true;
635 			fallthrough;
636 		default:
637 			break;
638 		}
639 		break;
640 	case NVME_CTRL_DEAD:
641 		switch (old_state) {
642 		case NVME_CTRL_DELETING:
643 			changed = true;
644 			fallthrough;
645 		default:
646 			break;
647 		}
648 		break;
649 	default:
650 		break;
651 	}
652 
653 	if (changed) {
654 		WRITE_ONCE(ctrl->state, new_state);
655 		wake_up_all(&ctrl->state_wq);
656 	}
657 
658 	spin_unlock_irqrestore(&ctrl->lock, flags);
659 	if (!changed)
660 		return false;
661 
662 	if (new_state == NVME_CTRL_LIVE) {
663 		if (old_state == NVME_CTRL_CONNECTING)
664 			nvme_stop_failfast_work(ctrl);
665 		nvme_kick_requeue_lists(ctrl);
666 	} else if (new_state == NVME_CTRL_CONNECTING &&
667 		old_state == NVME_CTRL_RESETTING) {
668 		nvme_start_failfast_work(ctrl);
669 	}
670 	return changed;
671 }
672 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
673 
674 /*
675  * Waits for the controller state to be resetting, or returns false if it is
676  * not possible to ever transition to that state.
677  */
678 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
679 {
680 	wait_event(ctrl->state_wq,
681 		   nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
682 		   nvme_state_terminal(ctrl));
683 	return nvme_ctrl_state(ctrl) == NVME_CTRL_RESETTING;
684 }
685 EXPORT_SYMBOL_GPL(nvme_wait_reset);
686 
687 static void nvme_free_ns_head(struct kref *ref)
688 {
689 	struct nvme_ns_head *head =
690 		container_of(ref, struct nvme_ns_head, ref);
691 
692 	nvme_mpath_put_disk(head);
693 	ida_free(&head->subsys->ns_ida, head->instance);
694 	cleanup_srcu_struct(&head->srcu);
695 	nvme_put_subsystem(head->subsys);
696 	kfree(head->plids);
697 	kfree(head);
698 }
699 
700 void nvme_get_ns_head(struct nvme_ns_head *head)
701 {
702 	kref_get(&head->ref);
703 }
704 
705 bool nvme_tryget_ns_head(struct nvme_ns_head *head)
706 {
707 	return kref_get_unless_zero(&head->ref);
708 }
709 
710 void nvme_put_ns_head(struct nvme_ns_head *head)
711 {
712 	kref_put(&head->ref, nvme_free_ns_head);
713 }
714 
715 static void nvme_free_ns(struct kref *kref)
716 {
717 	struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
718 
719 	put_disk(ns->disk);
720 	nvme_put_ns_head(ns->head);
721 	nvme_put_ctrl(ns->ctrl);
722 	kfree(ns);
723 }
724 
725 bool nvme_get_ns(struct nvme_ns *ns)
726 {
727 	return kref_get_unless_zero(&ns->kref);
728 }
729 
730 void nvme_put_ns(struct nvme_ns *ns)
731 {
732 	kref_put(&ns->kref, nvme_free_ns);
733 }
734 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, "NVME_TARGET_PASSTHRU");
735 
736 static inline void nvme_clear_nvme_request(struct request *req)
737 {
738 	nvme_req(req)->status = 0;
739 	nvme_req(req)->retries = 0;
740 	nvme_req(req)->flags = 0;
741 	req->rq_flags |= RQF_DONTPREP;
742 }
743 
744 /* initialize a passthrough request */
745 void nvme_init_request(struct request *req, struct nvme_command *cmd)
746 {
747 	struct nvme_request *nr = nvme_req(req);
748 	bool logging_enabled;
749 
750 	if (req->q->queuedata) {
751 		struct nvme_ns *ns = req->q->disk->private_data;
752 
753 		logging_enabled = ns->head->passthru_err_log_enabled;
754 	} else { /* no queuedata implies admin queue */
755 		logging_enabled = nr->ctrl->passthru_err_log_enabled;
756 	}
757 
758 	if (!logging_enabled)
759 		req->rq_flags |= RQF_QUIET;
760 
761 	/* passthru commands should let the driver set the SGL flags */
762 	cmd->common.flags &= ~NVME_CMD_SGL_ALL;
763 
764 	req->cmd_flags |= REQ_FAILFAST_DRIVER;
765 	if (req->mq_hctx->type == HCTX_TYPE_POLL)
766 		req->cmd_flags |= REQ_POLLED;
767 	nvme_clear_nvme_request(req);
768 	memcpy(nr->cmd, cmd, sizeof(*cmd));
769 }
770 EXPORT_SYMBOL_GPL(nvme_init_request);
771 
772 /*
773  * For something we're not in a state to send to the device the default action
774  * is to busy it and retry it after the controller state is recovered.  However,
775  * if the controller is deleting or if anything is marked for failfast or
776  * nvme multipath it is immediately failed.
777  *
778  * Note: commands used to initialize the controller will be marked for failfast.
779  * Note: nvme cli/ioctl commands are marked for failfast.
780  */
781 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl,
782 		struct request *rq)
783 {
784 	enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
785 
786 	if (state != NVME_CTRL_DELETING_NOIO &&
787 	    state != NVME_CTRL_DELETING &&
788 	    state != NVME_CTRL_DEAD &&
789 	    !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) &&
790 	    !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
791 		return BLK_STS_RESOURCE;
792 
793 	if (!(rq->rq_flags & RQF_DONTPREP))
794 		nvme_clear_nvme_request(rq);
795 
796 	return nvme_host_path_error(rq);
797 }
798 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command);
799 
800 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
801 		bool queue_live, enum nvme_ctrl_state state)
802 {
803 	struct nvme_request *req = nvme_req(rq);
804 
805 	/*
806 	 * currently we have a problem sending passthru commands
807 	 * on the admin_q if the controller is not LIVE because we can't
808 	 * make sure that they are going out after the admin connect,
809 	 * controller enable and/or other commands in the initialization
810 	 * sequence. until the controller will be LIVE, fail with
811 	 * BLK_STS_RESOURCE so that they will be rescheduled.
812 	 */
813 	if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD))
814 		return false;
815 
816 	if (ctrl->ops->flags & NVME_F_FABRICS) {
817 		/*
818 		 * Only allow commands on a live queue, except for the connect
819 		 * command, which is require to set the queue live in the
820 		 * appropinquate states.
821 		 */
822 		switch (state) {
823 		case NVME_CTRL_CONNECTING:
824 			if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) &&
825 			    (req->cmd->fabrics.fctype == nvme_fabrics_type_connect ||
826 			     req->cmd->fabrics.fctype == nvme_fabrics_type_auth_send ||
827 			     req->cmd->fabrics.fctype == nvme_fabrics_type_auth_receive))
828 				return true;
829 			break;
830 		default:
831 			break;
832 		case NVME_CTRL_DEAD:
833 			return false;
834 		}
835 	}
836 
837 	return queue_live;
838 }
839 EXPORT_SYMBOL_GPL(__nvme_check_ready);
840 
841 static inline void nvme_setup_flush(struct nvme_ns *ns,
842 		struct nvme_command *cmnd)
843 {
844 	memset(cmnd, 0, sizeof(*cmnd));
845 	cmnd->common.opcode = nvme_cmd_flush;
846 	cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
847 }
848 
849 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
850 		struct nvme_command *cmnd)
851 {
852 	unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
853 	struct nvme_dsm_range *range;
854 	struct bio *bio;
855 
856 	/*
857 	 * Some devices do not consider the DSM 'Number of Ranges' field when
858 	 * determining how much data to DMA. Always allocate memory for maximum
859 	 * number of segments to prevent device reading beyond end of buffer.
860 	 */
861 	static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
862 
863 	range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
864 	if (!range) {
865 		/*
866 		 * If we fail allocation our range, fallback to the controller
867 		 * discard page. If that's also busy, it's safe to return
868 		 * busy, as we know we can make progress once that's freed.
869 		 */
870 		if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
871 			return BLK_STS_RESOURCE;
872 
873 		range = page_address(ns->ctrl->discard_page);
874 	}
875 
876 	if (queue_max_discard_segments(req->q) == 1) {
877 		u64 slba = nvme_sect_to_lba(ns->head, blk_rq_pos(req));
878 		u32 nlb = blk_rq_sectors(req) >> (ns->head->lba_shift - 9);
879 
880 		range[0].cattr = cpu_to_le32(0);
881 		range[0].nlb = cpu_to_le32(nlb);
882 		range[0].slba = cpu_to_le64(slba);
883 		n = 1;
884 	} else {
885 		__rq_for_each_bio(bio, req) {
886 			u64 slba = nvme_sect_to_lba(ns->head,
887 						    bio->bi_iter.bi_sector);
888 			u32 nlb = bio->bi_iter.bi_size >> ns->head->lba_shift;
889 
890 			if (n < segments) {
891 				range[n].cattr = cpu_to_le32(0);
892 				range[n].nlb = cpu_to_le32(nlb);
893 				range[n].slba = cpu_to_le64(slba);
894 			}
895 			n++;
896 		}
897 	}
898 
899 	if (WARN_ON_ONCE(n != segments)) {
900 		if (virt_to_page(range) == ns->ctrl->discard_page)
901 			clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
902 		else
903 			kfree(range);
904 		return BLK_STS_IOERR;
905 	}
906 
907 	memset(cmnd, 0, sizeof(*cmnd));
908 	cmnd->dsm.opcode = nvme_cmd_dsm;
909 	cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
910 	cmnd->dsm.nr = cpu_to_le32(segments - 1);
911 	cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
912 
913 	bvec_set_virt(&req->special_vec, range, alloc_size);
914 	req->rq_flags |= RQF_SPECIAL_PAYLOAD;
915 
916 	return BLK_STS_OK;
917 }
918 
919 static void nvme_set_app_tag(struct request *req, struct nvme_command *cmnd)
920 {
921 	cmnd->rw.lbat = cpu_to_le16(bio_integrity(req->bio)->app_tag);
922 	cmnd->rw.lbatm = cpu_to_le16(0xffff);
923 }
924 
925 static void nvme_set_ref_tag(struct nvme_ns *ns, struct nvme_command *cmnd,
926 			      struct request *req)
927 {
928 	u32 upper, lower;
929 	u64 ref48;
930 
931 	/* only type1 and type 2 PI formats have a reftag */
932 	switch (ns->head->pi_type) {
933 	case NVME_NS_DPS_PI_TYPE1:
934 	case NVME_NS_DPS_PI_TYPE2:
935 		break;
936 	default:
937 		return;
938 	}
939 
940 	/* both rw and write zeroes share the same reftag format */
941 	switch (ns->head->guard_type) {
942 	case NVME_NVM_NS_16B_GUARD:
943 		cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
944 		break;
945 	case NVME_NVM_NS_64B_GUARD:
946 		ref48 = ext_pi_ref_tag(req);
947 		lower = lower_32_bits(ref48);
948 		upper = upper_32_bits(ref48);
949 
950 		cmnd->rw.reftag = cpu_to_le32(lower);
951 		cmnd->rw.cdw3 = cpu_to_le32(upper);
952 		break;
953 	default:
954 		break;
955 	}
956 }
957 
958 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
959 		struct request *req, struct nvme_command *cmnd)
960 {
961 	memset(cmnd, 0, sizeof(*cmnd));
962 
963 	if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
964 		return nvme_setup_discard(ns, req, cmnd);
965 
966 	cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
967 	cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
968 	cmnd->write_zeroes.slba =
969 		cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req)));
970 	cmnd->write_zeroes.length =
971 		cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1);
972 
973 	if (!(req->cmd_flags & REQ_NOUNMAP) &&
974 	    (ns->head->features & NVME_NS_DEAC))
975 		cmnd->write_zeroes.control |= cpu_to_le16(NVME_WZ_DEAC);
976 
977 	if (nvme_ns_has_pi(ns->head)) {
978 		cmnd->write_zeroes.control |= cpu_to_le16(NVME_RW_PRINFO_PRACT);
979 		nvme_set_ref_tag(ns, cmnd, req);
980 	}
981 
982 	return BLK_STS_OK;
983 }
984 
985 /*
986  * NVMe does not support a dedicated command to issue an atomic write. A write
987  * which does adhere to the device atomic limits will silently be executed
988  * non-atomically. The request issuer should ensure that the write is within
989  * the queue atomic writes limits, but just validate this in case it is not.
990  */
991 static bool nvme_valid_atomic_write(struct request *req)
992 {
993 	struct request_queue *q = req->q;
994 	u32 boundary_bytes = queue_atomic_write_boundary_bytes(q);
995 
996 	if (blk_rq_bytes(req) > queue_atomic_write_unit_max_bytes(q))
997 		return false;
998 
999 	if (boundary_bytes) {
1000 		u64 mask = boundary_bytes - 1, imask = ~mask;
1001 		u64 start = blk_rq_pos(req) << SECTOR_SHIFT;
1002 		u64 end = start + blk_rq_bytes(req) - 1;
1003 
1004 		/* If greater then must be crossing a boundary */
1005 		if (blk_rq_bytes(req) > boundary_bytes)
1006 			return false;
1007 
1008 		if ((start & imask) != (end & imask))
1009 			return false;
1010 	}
1011 
1012 	return true;
1013 }
1014 
1015 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
1016 		struct request *req, struct nvme_command *cmnd,
1017 		enum nvme_opcode op)
1018 {
1019 	u16 control = 0;
1020 	u32 dsmgmt = 0;
1021 
1022 	if (req->cmd_flags & REQ_FUA)
1023 		control |= NVME_RW_FUA;
1024 	if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
1025 		control |= NVME_RW_LR;
1026 
1027 	if (req->cmd_flags & REQ_RAHEAD)
1028 		dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
1029 
1030 	if (op == nvme_cmd_write && ns->head->nr_plids) {
1031 		u16 write_stream = req->bio->bi_write_stream;
1032 
1033 		if (WARN_ON_ONCE(write_stream > ns->head->nr_plids))
1034 			return BLK_STS_INVAL;
1035 
1036 		if (write_stream) {
1037 			dsmgmt |= ns->head->plids[write_stream - 1] << 16;
1038 			control |= NVME_RW_DTYPE_DPLCMT;
1039 		}
1040 	}
1041 
1042 	if (req->cmd_flags & REQ_ATOMIC && !nvme_valid_atomic_write(req))
1043 		return BLK_STS_INVAL;
1044 
1045 	cmnd->rw.opcode = op;
1046 	cmnd->rw.flags = 0;
1047 	cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
1048 	cmnd->rw.cdw2 = 0;
1049 	cmnd->rw.cdw3 = 0;
1050 	cmnd->rw.metadata = 0;
1051 	cmnd->rw.slba =
1052 		cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req)));
1053 	cmnd->rw.length =
1054 		cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1);
1055 	cmnd->rw.reftag = 0;
1056 	cmnd->rw.lbat = 0;
1057 	cmnd->rw.lbatm = 0;
1058 
1059 	if (ns->head->ms) {
1060 		/*
1061 		 * If formatted with metadata, the block layer always provides a
1062 		 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled.  Else
1063 		 * we enable the PRACT bit for protection information or set the
1064 		 * namespace capacity to zero to prevent any I/O.
1065 		 */
1066 		if (!blk_integrity_rq(req)) {
1067 			if (WARN_ON_ONCE(!nvme_ns_has_pi(ns->head)))
1068 				return BLK_STS_NOTSUPP;
1069 			control |= NVME_RW_PRINFO_PRACT;
1070 			nvme_set_ref_tag(ns, cmnd, req);
1071 		}
1072 
1073 		if (bio_integrity_flagged(req->bio, BIP_CHECK_GUARD))
1074 			control |= NVME_RW_PRINFO_PRCHK_GUARD;
1075 		if (bio_integrity_flagged(req->bio, BIP_CHECK_REFTAG)) {
1076 			control |= NVME_RW_PRINFO_PRCHK_REF;
1077 			if (op == nvme_cmd_zone_append)
1078 				control |= NVME_RW_APPEND_PIREMAP;
1079 			nvme_set_ref_tag(ns, cmnd, req);
1080 		}
1081 		if (bio_integrity_flagged(req->bio, BIP_CHECK_APPTAG)) {
1082 			control |= NVME_RW_PRINFO_PRCHK_APP;
1083 			nvme_set_app_tag(req, cmnd);
1084 		}
1085 	}
1086 
1087 	cmnd->rw.control = cpu_to_le16(control);
1088 	cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
1089 	return 0;
1090 }
1091 
1092 void nvme_cleanup_cmd(struct request *req)
1093 {
1094 	if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
1095 		struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
1096 
1097 		if (req->special_vec.bv_page == ctrl->discard_page)
1098 			clear_bit_unlock(0, &ctrl->discard_page_busy);
1099 		else
1100 			kfree(bvec_virt(&req->special_vec));
1101 		req->rq_flags &= ~RQF_SPECIAL_PAYLOAD;
1102 	}
1103 }
1104 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
1105 
1106 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
1107 {
1108 	struct nvme_command *cmd = nvme_req(req)->cmd;
1109 	blk_status_t ret = BLK_STS_OK;
1110 
1111 	if (!(req->rq_flags & RQF_DONTPREP))
1112 		nvme_clear_nvme_request(req);
1113 
1114 	switch (req_op(req)) {
1115 	case REQ_OP_DRV_IN:
1116 	case REQ_OP_DRV_OUT:
1117 		/* these are setup prior to execution in nvme_init_request() */
1118 		break;
1119 	case REQ_OP_FLUSH:
1120 		nvme_setup_flush(ns, cmd);
1121 		break;
1122 	case REQ_OP_ZONE_RESET_ALL:
1123 	case REQ_OP_ZONE_RESET:
1124 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
1125 		break;
1126 	case REQ_OP_ZONE_OPEN:
1127 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
1128 		break;
1129 	case REQ_OP_ZONE_CLOSE:
1130 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
1131 		break;
1132 	case REQ_OP_ZONE_FINISH:
1133 		ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
1134 		break;
1135 	case REQ_OP_WRITE_ZEROES:
1136 		ret = nvme_setup_write_zeroes(ns, req, cmd);
1137 		break;
1138 	case REQ_OP_DISCARD:
1139 		ret = nvme_setup_discard(ns, req, cmd);
1140 		break;
1141 	case REQ_OP_READ:
1142 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
1143 		break;
1144 	case REQ_OP_WRITE:
1145 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
1146 		break;
1147 	case REQ_OP_ZONE_APPEND:
1148 		ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
1149 		break;
1150 	default:
1151 		WARN_ON_ONCE(1);
1152 		return BLK_STS_IOERR;
1153 	}
1154 
1155 	cmd->common.command_id = nvme_cid(req);
1156 	trace_nvme_setup_cmd(req, cmd);
1157 	return ret;
1158 }
1159 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
1160 
1161 /*
1162  * Return values:
1163  * 0:  success
1164  * >0: nvme controller's cqe status response
1165  * <0: kernel error in lieu of controller response
1166  */
1167 int nvme_execute_rq(struct request *rq, bool at_head)
1168 {
1169 	blk_status_t status;
1170 
1171 	status = blk_execute_rq(rq, at_head);
1172 	if (nvme_req(rq)->flags & NVME_REQ_CANCELLED)
1173 		return -EINTR;
1174 	if (nvme_req(rq)->status)
1175 		return nvme_req(rq)->status;
1176 	return blk_status_to_errno(status);
1177 }
1178 EXPORT_SYMBOL_NS_GPL(nvme_execute_rq, "NVME_TARGET_PASSTHRU");
1179 
1180 /*
1181  * Returns 0 on success.  If the result is negative, it's a Linux error code;
1182  * if the result is positive, it's an NVM Express status code
1183  */
1184 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1185 		union nvme_result *result, void *buffer, unsigned bufflen,
1186 		int qid, nvme_submit_flags_t flags)
1187 {
1188 	struct request *req;
1189 	int ret;
1190 	blk_mq_req_flags_t blk_flags = 0;
1191 
1192 	if (flags & NVME_SUBMIT_NOWAIT)
1193 		blk_flags |= BLK_MQ_REQ_NOWAIT;
1194 	if (flags & NVME_SUBMIT_RESERVED)
1195 		blk_flags |= BLK_MQ_REQ_RESERVED;
1196 	if (qid == NVME_QID_ANY)
1197 		req = blk_mq_alloc_request(q, nvme_req_op(cmd), blk_flags);
1198 	else
1199 		req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), blk_flags,
1200 						qid - 1);
1201 
1202 	if (IS_ERR(req))
1203 		return PTR_ERR(req);
1204 	nvme_init_request(req, cmd);
1205 	if (flags & NVME_SUBMIT_RETRY)
1206 		req->cmd_flags &= ~REQ_FAILFAST_DRIVER;
1207 
1208 	if (buffer && bufflen) {
1209 		ret = blk_rq_map_kern(req, buffer, bufflen, GFP_KERNEL);
1210 		if (ret)
1211 			goto out;
1212 	}
1213 
1214 	ret = nvme_execute_rq(req, flags & NVME_SUBMIT_AT_HEAD);
1215 	if (result && ret >= 0)
1216 		*result = nvme_req(req)->result;
1217  out:
1218 	blk_mq_free_request(req);
1219 	return ret;
1220 }
1221 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
1222 
1223 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1224 		void *buffer, unsigned bufflen)
1225 {
1226 	return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen,
1227 			NVME_QID_ANY, 0);
1228 }
1229 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
1230 
1231 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1232 {
1233 	u32 effects = 0;
1234 
1235 	if (ns) {
1236 		effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
1237 		if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1238 			dev_warn_once(ctrl->device,
1239 				"IO command:%02x has unusual effects:%08x\n",
1240 				opcode, effects);
1241 
1242 		/*
1243 		 * NVME_CMD_EFFECTS_CSE_MASK causes a freeze all I/O queues,
1244 		 * which would deadlock when done on an I/O command.  Note that
1245 		 * We already warn about an unusual effect above.
1246 		 */
1247 		effects &= ~NVME_CMD_EFFECTS_CSE_MASK;
1248 	} else {
1249 		effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1250 
1251 		/* Ignore execution restrictions if any relaxation bits are set */
1252 		if (effects & NVME_CMD_EFFECTS_CSER_MASK)
1253 			effects &= ~NVME_CMD_EFFECTS_CSE_MASK;
1254 	}
1255 
1256 	return effects;
1257 }
1258 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, "NVME_TARGET_PASSTHRU");
1259 
1260 u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1261 {
1262 	u32 effects = nvme_command_effects(ctrl, ns, opcode);
1263 
1264 	/*
1265 	 * For simplicity, IO to all namespaces is quiesced even if the command
1266 	 * effects say only one namespace is affected.
1267 	 */
1268 	if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1269 		mutex_lock(&ctrl->scan_lock);
1270 		mutex_lock(&ctrl->subsys->lock);
1271 		nvme_mpath_start_freeze(ctrl->subsys);
1272 		nvme_mpath_wait_freeze(ctrl->subsys);
1273 		nvme_start_freeze(ctrl);
1274 		nvme_wait_freeze(ctrl);
1275 	}
1276 	return effects;
1277 }
1278 EXPORT_SYMBOL_NS_GPL(nvme_passthru_start, "NVME_TARGET_PASSTHRU");
1279 
1280 u32 nvme_passthru_end(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u32 effects,
1281 		       struct nvme_command *cmd, int status)
1282 {
1283 	if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1284 		nvme_unfreeze(ctrl);
1285 		nvme_mpath_unfreeze(ctrl->subsys);
1286 		mutex_unlock(&ctrl->subsys->lock);
1287 		mutex_unlock(&ctrl->scan_lock);
1288 	}
1289 	if (effects & NVME_CMD_EFFECTS_CCC) {
1290 		if (!test_and_set_bit(NVME_CTRL_DIRTY_CAPABILITY,
1291 				      &ctrl->flags)) {
1292 			dev_info(ctrl->device,
1293 "controller capabilities changed, reset may be required to take effect.\n");
1294 		}
1295 	}
1296 	if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1297 		nvme_queue_scan(ctrl);
1298 		flush_work(&ctrl->scan_work);
1299 	}
1300 	if (ns)
1301 		return effects;
1302 
1303 	switch (cmd->common.opcode) {
1304 	case nvme_admin_set_features:
1305 		switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) {
1306 		case NVME_FEAT_KATO:
1307 			/*
1308 			 * Keep alive commands interval on the host should be
1309 			 * updated when KATO is modified by Set Features
1310 			 * commands.
1311 			 */
1312 			if (!status)
1313 				nvme_update_keep_alive(ctrl, cmd);
1314 			break;
1315 		default:
1316 			break;
1317 		}
1318 		break;
1319 	default:
1320 		break;
1321 	}
1322 
1323 	return effects;
1324 }
1325 EXPORT_SYMBOL_NS_GPL(nvme_passthru_end, "NVME_TARGET_PASSTHRU");
1326 
1327 /*
1328  * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
1329  *
1330  *   The host should send Keep Alive commands at half of the Keep Alive Timeout
1331  *   accounting for transport roundtrip times [..].
1332  */
1333 static unsigned long nvme_keep_alive_work_period(struct nvme_ctrl *ctrl)
1334 {
1335 	unsigned long delay = ctrl->kato * HZ / 2;
1336 
1337 	/*
1338 	 * When using Traffic Based Keep Alive, we need to run
1339 	 * nvme_keep_alive_work at twice the normal frequency, as one
1340 	 * command completion can postpone sending a keep alive command
1341 	 * by up to twice the delay between runs.
1342 	 */
1343 	if (ctrl->ctratt & NVME_CTRL_ATTR_TBKAS)
1344 		delay /= 2;
1345 	return delay;
1346 }
1347 
1348 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
1349 {
1350 	unsigned long now = jiffies;
1351 	unsigned long delay = nvme_keep_alive_work_period(ctrl);
1352 	unsigned long ka_next_check_tm = ctrl->ka_last_check_time + delay;
1353 
1354 	if (time_after(now, ka_next_check_tm))
1355 		delay = 0;
1356 	else
1357 		delay = ka_next_check_tm - now;
1358 
1359 	queue_delayed_work(nvme_wq, &ctrl->ka_work, delay);
1360 }
1361 
1362 static enum rq_end_io_ret nvme_keep_alive_end_io(struct request *rq,
1363 						 blk_status_t status,
1364 						 const struct io_comp_batch *iob)
1365 {
1366 	struct nvme_ctrl *ctrl = rq->end_io_data;
1367 	unsigned long rtt = jiffies - (rq->deadline - rq->timeout);
1368 	unsigned long delay = nvme_keep_alive_work_period(ctrl);
1369 	enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
1370 
1371 	/*
1372 	 * Subtract off the keepalive RTT so nvme_keep_alive_work runs
1373 	 * at the desired frequency.
1374 	 */
1375 	if (rtt <= delay) {
1376 		delay -= rtt;
1377 	} else {
1378 		dev_warn(ctrl->device, "long keepalive RTT (%u ms)\n",
1379 			 jiffies_to_msecs(rtt));
1380 		delay = 0;
1381 	}
1382 
1383 	blk_mq_free_request(rq);
1384 
1385 	if (status) {
1386 		dev_err(ctrl->device,
1387 			"failed nvme_keep_alive_end_io error=%d\n",
1388 				status);
1389 		return RQ_END_IO_NONE;
1390 	}
1391 
1392 	ctrl->ka_last_check_time = jiffies;
1393 	ctrl->comp_seen = false;
1394 	if (state == NVME_CTRL_LIVE || state == NVME_CTRL_CONNECTING)
1395 		queue_delayed_work(nvme_wq, &ctrl->ka_work, delay);
1396 	return RQ_END_IO_NONE;
1397 }
1398 
1399 static void nvme_keep_alive_work(struct work_struct *work)
1400 {
1401 	struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1402 			struct nvme_ctrl, ka_work);
1403 	bool comp_seen = ctrl->comp_seen;
1404 	struct request *rq;
1405 
1406 	ctrl->ka_last_check_time = jiffies;
1407 
1408 	if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1409 		dev_dbg(ctrl->device,
1410 			"reschedule traffic based keep-alive timer\n");
1411 		ctrl->comp_seen = false;
1412 		nvme_queue_keep_alive_work(ctrl);
1413 		return;
1414 	}
1415 
1416 	rq = blk_mq_alloc_request(ctrl->admin_q, nvme_req_op(&ctrl->ka_cmd),
1417 				  BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
1418 	if (IS_ERR(rq)) {
1419 		/* allocation failure, reset the controller */
1420 		dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
1421 		nvme_reset_ctrl(ctrl);
1422 		return;
1423 	}
1424 	nvme_init_request(rq, &ctrl->ka_cmd);
1425 
1426 	rq->timeout = ctrl->kato * HZ;
1427 	rq->end_io = nvme_keep_alive_end_io;
1428 	rq->end_io_data = ctrl;
1429 	blk_execute_rq_nowait(rq, false);
1430 }
1431 
1432 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1433 {
1434 	if (unlikely(ctrl->kato == 0))
1435 		return;
1436 
1437 	nvme_queue_keep_alive_work(ctrl);
1438 }
1439 
1440 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1441 {
1442 	if (unlikely(ctrl->kato == 0))
1443 		return;
1444 
1445 	cancel_delayed_work_sync(&ctrl->ka_work);
1446 }
1447 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1448 
1449 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
1450 				   struct nvme_command *cmd)
1451 {
1452 	unsigned int new_kato =
1453 		DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000);
1454 
1455 	dev_info(ctrl->device,
1456 		 "keep alive interval updated from %u ms to %u ms\n",
1457 		 ctrl->kato * 1000 / 2, new_kato * 1000 / 2);
1458 
1459 	nvme_stop_keep_alive(ctrl);
1460 	ctrl->kato = new_kato;
1461 	nvme_start_keep_alive(ctrl);
1462 }
1463 
1464 static bool nvme_id_cns_ok(struct nvme_ctrl *ctrl, u8 cns)
1465 {
1466 	/*
1467 	 * The CNS field occupies a full byte starting with NVMe 1.2
1468 	 */
1469 	if (ctrl->vs >= NVME_VS(1, 2, 0))
1470 		return true;
1471 
1472 	/*
1473 	 * NVMe 1.1 expanded the CNS value to two bits, which means values
1474 	 * larger than that could get truncated and treated as an incorrect
1475 	 * value.
1476 	 *
1477 	 * Qemu implemented 1.0 behavior for controllers claiming 1.1
1478 	 * compliance, so they need to be quirked here.
1479 	 */
1480 	if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1481 	    !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS))
1482 		return cns <= 3;
1483 
1484 	/*
1485 	 * NVMe 1.0 used a single bit for the CNS value.
1486 	 */
1487 	return cns <= 1;
1488 }
1489 
1490 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1491 {
1492 	struct nvme_command c = { };
1493 	int error;
1494 
1495 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1496 	c.identify.opcode = nvme_admin_identify;
1497 	c.identify.cns = NVME_ID_CNS_CTRL;
1498 
1499 	*id = kmalloc_obj(struct nvme_id_ctrl);
1500 	if (!*id)
1501 		return -ENOMEM;
1502 
1503 	error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1504 			sizeof(struct nvme_id_ctrl));
1505 	if (error) {
1506 		kfree(*id);
1507 		*id = NULL;
1508 	}
1509 	return error;
1510 }
1511 
1512 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1513 		struct nvme_ns_id_desc *cur, bool *csi_seen)
1514 {
1515 	const char *warn_str = "ctrl returned bogus length:";
1516 	void *data = cur;
1517 
1518 	switch (cur->nidt) {
1519 	case NVME_NIDT_EUI64:
1520 		if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1521 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1522 				 warn_str, cur->nidl);
1523 			return -1;
1524 		}
1525 		if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1526 			return NVME_NIDT_EUI64_LEN;
1527 		memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1528 		return NVME_NIDT_EUI64_LEN;
1529 	case NVME_NIDT_NGUID:
1530 		if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1531 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1532 				 warn_str, cur->nidl);
1533 			return -1;
1534 		}
1535 		if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1536 			return NVME_NIDT_NGUID_LEN;
1537 		memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1538 		return NVME_NIDT_NGUID_LEN;
1539 	case NVME_NIDT_UUID:
1540 		if (cur->nidl != NVME_NIDT_UUID_LEN) {
1541 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1542 				 warn_str, cur->nidl);
1543 			return -1;
1544 		}
1545 		if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1546 			return NVME_NIDT_UUID_LEN;
1547 		uuid_copy(&ids->uuid, data + sizeof(*cur));
1548 		return NVME_NIDT_UUID_LEN;
1549 	case NVME_NIDT_CSI:
1550 		if (cur->nidl != NVME_NIDT_CSI_LEN) {
1551 			dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1552 				 warn_str, cur->nidl);
1553 			return -1;
1554 		}
1555 		memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1556 		*csi_seen = true;
1557 		return NVME_NIDT_CSI_LEN;
1558 	default:
1559 		/* Skip unknown types */
1560 		return cur->nidl;
1561 	}
1562 }
1563 
1564 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl,
1565 		struct nvme_ns_info *info)
1566 {
1567 	struct nvme_command c = { };
1568 	bool csi_seen = false;
1569 	int status, pos, len;
1570 	void *data;
1571 
1572 	if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
1573 		return 0;
1574 	if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1575 		return 0;
1576 
1577 	c.identify.opcode = nvme_admin_identify;
1578 	c.identify.nsid = cpu_to_le32(info->nsid);
1579 	c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1580 
1581 	data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1582 	if (!data)
1583 		return -ENOMEM;
1584 
1585 	status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1586 				      NVME_IDENTIFY_DATA_SIZE);
1587 	if (status) {
1588 		dev_warn(ctrl->device,
1589 			"Identify Descriptors failed (nsid=%u, status=0x%x)\n",
1590 			info->nsid, status);
1591 		goto free_data;
1592 	}
1593 
1594 	for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1595 		struct nvme_ns_id_desc *cur = data + pos;
1596 
1597 		if (pos + sizeof(*cur) > NVME_IDENTIFY_DATA_SIZE)
1598 			break;
1599 		if (cur->nidl == 0)
1600 			break;
1601 		if (pos + sizeof(*cur) + cur->nidl > NVME_IDENTIFY_DATA_SIZE)
1602 			break;
1603 
1604 		len = nvme_process_ns_desc(ctrl, &info->ids, cur, &csi_seen);
1605 		if (len < 0)
1606 			break;
1607 
1608 		len += sizeof(*cur);
1609 	}
1610 
1611 	if (nvme_multi_css(ctrl) && !csi_seen) {
1612 		dev_warn(ctrl->device, "Command set not reported for nsid:%u\n",
1613 			 info->nsid);
1614 		status = -EINVAL;
1615 	}
1616 
1617 free_data:
1618 	kfree(data);
1619 	return status;
1620 }
1621 
1622 int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
1623 			struct nvme_id_ns **id)
1624 {
1625 	struct nvme_command c = { };
1626 	int error;
1627 
1628 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1629 	c.identify.opcode = nvme_admin_identify;
1630 	c.identify.nsid = cpu_to_le32(nsid);
1631 	c.identify.cns = NVME_ID_CNS_NS;
1632 
1633 	*id = kmalloc_obj(**id);
1634 	if (!*id)
1635 		return -ENOMEM;
1636 
1637 	error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1638 	if (error) {
1639 		dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1640 		kfree(*id);
1641 		*id = NULL;
1642 	}
1643 	return error;
1644 }
1645 
1646 static int nvme_ns_info_from_identify(struct nvme_ctrl *ctrl,
1647 		struct nvme_ns_info *info)
1648 {
1649 	struct nvme_ns_ids *ids = &info->ids;
1650 	struct nvme_id_ns *id;
1651 	int ret;
1652 
1653 	ret = nvme_identify_ns(ctrl, info->nsid, &id);
1654 	if (ret)
1655 		return ret;
1656 
1657 	if (id->ncap == 0) {
1658 		/* namespace not allocated or attached */
1659 		info->is_removed = true;
1660 		ret = -ENODEV;
1661 		goto error;
1662 	}
1663 
1664 	info->anagrpid = id->anagrpid;
1665 	info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
1666 	info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
1667 	info->is_ready = true;
1668 	info->endgid = le16_to_cpu(id->endgid);
1669 	if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) {
1670 		dev_info(ctrl->device,
1671 			 "Ignoring bogus Namespace Identifiers\n");
1672 	} else {
1673 		if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1674 		    !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
1675 			memcpy(ids->eui64, id->eui64, sizeof(ids->eui64));
1676 		if (ctrl->vs >= NVME_VS(1, 2, 0) &&
1677 		    !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
1678 			memcpy(ids->nguid, id->nguid, sizeof(ids->nguid));
1679 	}
1680 
1681 error:
1682 	kfree(id);
1683 	return ret;
1684 }
1685 
1686 static int nvme_ns_info_from_id_cs_indep(struct nvme_ctrl *ctrl,
1687 		struct nvme_ns_info *info)
1688 {
1689 	struct nvme_id_ns_cs_indep *id;
1690 	struct nvme_command c = {
1691 		.identify.opcode	= nvme_admin_identify,
1692 		.identify.nsid		= cpu_to_le32(info->nsid),
1693 		.identify.cns		= NVME_ID_CNS_NS_CS_INDEP,
1694 	};
1695 	int ret;
1696 
1697 	id = kmalloc_obj(*id);
1698 	if (!id)
1699 		return -ENOMEM;
1700 
1701 	ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
1702 	if (!ret) {
1703 		info->anagrpid = id->anagrpid;
1704 		info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
1705 		info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
1706 		info->is_ready = id->nstat & NVME_NSTAT_NRDY;
1707 		info->is_rotational = id->nsfeat & NVME_NS_ROTATIONAL;
1708 		info->no_vwc = id->nsfeat & NVME_NS_VWC_NOT_PRESENT;
1709 		info->endgid = le16_to_cpu(id->endgid);
1710 	}
1711 	kfree(id);
1712 	return ret;
1713 }
1714 
1715 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1716 		unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1717 {
1718 	union nvme_result res = { 0 };
1719 	struct nvme_command c = { };
1720 	int ret;
1721 
1722 	c.features.opcode = op;
1723 	c.features.fid = cpu_to_le32(fid);
1724 	c.features.dword11 = cpu_to_le32(dword11);
1725 
1726 	ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1727 			buffer, buflen, NVME_QID_ANY, 0);
1728 	if (ret >= 0 && result)
1729 		*result = le32_to_cpu(res.u32);
1730 	return ret;
1731 }
1732 
1733 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1734 		      unsigned int dword11, void *buffer, size_t buflen,
1735 		      void *result)
1736 {
1737 	return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1738 			     buflen, result);
1739 }
1740 EXPORT_SYMBOL_GPL(nvme_set_features);
1741 
1742 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1743 		      unsigned int dword11, void *buffer, size_t buflen,
1744 		      void *result)
1745 {
1746 	return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1747 			     buflen, result);
1748 }
1749 EXPORT_SYMBOL_GPL(nvme_get_features);
1750 
1751 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1752 {
1753 	u32 q_count = (*count - 1) | ((*count - 1) << 16);
1754 	u32 result;
1755 	int status, nr_io_queues;
1756 
1757 	status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1758 			&result);
1759 
1760 	/*
1761 	 * It's either a kernel error or the host observed a connection
1762 	 * lost. In either case it's not possible communicate with the
1763 	 * controller and thus enter the error code path.
1764 	 */
1765 	if (status < 0 || status == NVME_SC_HOST_PATH_ERROR)
1766 		return status;
1767 
1768 	/*
1769 	 * Degraded controllers might return an error when setting the queue
1770 	 * count.  We still want to be able to bring them online and offer
1771 	 * access to the admin queue, as that might be only way to fix them up.
1772 	 */
1773 	if (status > 0) {
1774 		dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1775 		*count = 0;
1776 	} else {
1777 		nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1778 		*count = min(*count, nr_io_queues);
1779 	}
1780 
1781 	return 0;
1782 }
1783 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1784 
1785 #define NVME_AEN_SUPPORTED \
1786 	(NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1787 	 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1788 
1789 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1790 {
1791 	u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1792 	int status;
1793 
1794 	if (!supported_aens)
1795 		return;
1796 
1797 	status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1798 			NULL, 0, &result);
1799 	if (status)
1800 		dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1801 			 supported_aens);
1802 
1803 	queue_work(nvme_wq, &ctrl->async_event_work);
1804 }
1805 
1806 static int nvme_ns_open(struct nvme_ns *ns)
1807 {
1808 
1809 	/* should never be called due to GENHD_FL_HIDDEN */
1810 	if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
1811 		goto fail;
1812 	if (!nvme_get_ns(ns))
1813 		goto fail;
1814 	if (!try_module_get(ns->ctrl->ops->module))
1815 		goto fail_put_ns;
1816 
1817 	return 0;
1818 
1819 fail_put_ns:
1820 	nvme_put_ns(ns);
1821 fail:
1822 	return -ENXIO;
1823 }
1824 
1825 static void nvme_ns_release(struct nvme_ns *ns)
1826 {
1827 
1828 	module_put(ns->ctrl->ops->module);
1829 	nvme_put_ns(ns);
1830 }
1831 
1832 static int nvme_open(struct gendisk *disk, blk_mode_t mode)
1833 {
1834 	return nvme_ns_open(disk->private_data);
1835 }
1836 
1837 static void nvme_release(struct gendisk *disk)
1838 {
1839 	nvme_ns_release(disk->private_data);
1840 }
1841 
1842 int nvme_getgeo(struct gendisk *disk, struct hd_geometry *geo)
1843 {
1844 	/* some standard values */
1845 	geo->heads = 1 << 6;
1846 	geo->sectors = 1 << 5;
1847 	geo->cylinders = get_capacity(disk) >> 11;
1848 	return 0;
1849 }
1850 
1851 static bool nvme_init_integrity(struct nvme_ns_head *head,
1852 		struct queue_limits *lim, struct nvme_ns_info *info)
1853 {
1854 	struct blk_integrity *bi = &lim->integrity;
1855 
1856 	memset(bi, 0, sizeof(*bi));
1857 
1858 	if (!head->ms)
1859 		return true;
1860 
1861 	/*
1862 	 * PI can always be supported as we can ask the controller to simply
1863 	 * insert/strip it, which is not possible for other kinds of metadata.
1864 	 */
1865 	if (!IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) ||
1866 	    !(head->features & NVME_NS_METADATA_SUPPORTED))
1867 		return nvme_ns_has_pi(head);
1868 
1869 	switch (head->pi_type) {
1870 	case NVME_NS_DPS_PI_TYPE3:
1871 		switch (head->guard_type) {
1872 		case NVME_NVM_NS_16B_GUARD:
1873 			bi->csum_type = BLK_INTEGRITY_CSUM_CRC;
1874 			bi->tag_size = sizeof(u16) + sizeof(u32);
1875 			bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1876 			break;
1877 		case NVME_NVM_NS_64B_GUARD:
1878 			bi->csum_type = BLK_INTEGRITY_CSUM_CRC64;
1879 			bi->tag_size = sizeof(u16) + 6;
1880 			bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1881 			break;
1882 		default:
1883 			break;
1884 		}
1885 		break;
1886 	case NVME_NS_DPS_PI_TYPE1:
1887 	case NVME_NS_DPS_PI_TYPE2:
1888 		switch (head->guard_type) {
1889 		case NVME_NVM_NS_16B_GUARD:
1890 			bi->csum_type = BLK_INTEGRITY_CSUM_CRC;
1891 			bi->tag_size = sizeof(u16);
1892 			bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE |
1893 				     BLK_INTEGRITY_REF_TAG;
1894 			break;
1895 		case NVME_NVM_NS_64B_GUARD:
1896 			bi->csum_type = BLK_INTEGRITY_CSUM_CRC64;
1897 			bi->tag_size = sizeof(u16);
1898 			bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE |
1899 				     BLK_INTEGRITY_REF_TAG;
1900 			break;
1901 		default:
1902 			break;
1903 		}
1904 		break;
1905 	default:
1906 		break;
1907 	}
1908 
1909 	bi->flags |= BLK_SPLIT_INTERVAL_CAPABLE;
1910 	bi->metadata_size = head->ms;
1911 	if (bi->csum_type) {
1912 		bi->pi_tuple_size = head->pi_size;
1913 		bi->pi_offset = info->pi_offset;
1914 	}
1915 	return true;
1916 }
1917 
1918 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1919 {
1920 	return uuid_equal(&a->uuid, &b->uuid) &&
1921 		memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1922 		memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1923 		a->csi == b->csi;
1924 }
1925 
1926 static int nvme_identify_ns_nvm(struct nvme_ctrl *ctrl, unsigned int nsid,
1927 		struct nvme_id_ns_nvm **nvmp)
1928 {
1929 	struct nvme_command c = {
1930 		.identify.opcode	= nvme_admin_identify,
1931 		.identify.nsid		= cpu_to_le32(nsid),
1932 		.identify.cns		= NVME_ID_CNS_CS_NS,
1933 		.identify.csi		= NVME_CSI_NVM,
1934 	};
1935 	struct nvme_id_ns_nvm *nvm;
1936 	int ret;
1937 
1938 	nvm = kzalloc_obj(*nvm);
1939 	if (!nvm)
1940 		return -ENOMEM;
1941 
1942 	ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, nvm, sizeof(*nvm));
1943 	if (ret)
1944 		kfree(nvm);
1945 	else
1946 		*nvmp = nvm;
1947 	return ret;
1948 }
1949 
1950 static void nvme_configure_pi_elbas(struct nvme_ns_head *head,
1951 		struct nvme_id_ns *id, struct nvme_id_ns_nvm *nvm)
1952 {
1953 	u32 elbaf = le32_to_cpu(nvm->elbaf[nvme_lbaf_index(id->flbas)]);
1954 	u8 guard_type;
1955 
1956 	/* no support for storage tag formats right now */
1957 	if (nvme_elbaf_sts(elbaf))
1958 		return;
1959 
1960 	guard_type = nvme_elbaf_guard_type(elbaf);
1961 	if ((nvm->pic & NVME_ID_NS_NVM_QPIFS) &&
1962 	     guard_type == NVME_NVM_NS_QTYPE_GUARD)
1963 		guard_type = nvme_elbaf_qualified_guard_type(elbaf);
1964 
1965 	head->guard_type = guard_type;
1966 	switch (head->guard_type) {
1967 	case NVME_NVM_NS_64B_GUARD:
1968 		head->pi_size = sizeof(struct crc64_pi_tuple);
1969 		break;
1970 	case NVME_NVM_NS_16B_GUARD:
1971 		head->pi_size = sizeof(struct t10_pi_tuple);
1972 		break;
1973 	default:
1974 		break;
1975 	}
1976 }
1977 
1978 static void nvme_configure_metadata(struct nvme_ctrl *ctrl,
1979 		struct nvme_ns_head *head, struct nvme_id_ns *id,
1980 		struct nvme_id_ns_nvm *nvm, struct nvme_ns_info *info)
1981 {
1982 	head->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1983 	head->pi_type = 0;
1984 	head->pi_size = 0;
1985 	head->ms = le16_to_cpu(id->lbaf[nvme_lbaf_index(id->flbas)].ms);
1986 	if (!head->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1987 		return;
1988 
1989 	if (nvm && (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)) {
1990 		nvme_configure_pi_elbas(head, id, nvm);
1991 	} else {
1992 		head->pi_size = sizeof(struct t10_pi_tuple);
1993 		head->guard_type = NVME_NVM_NS_16B_GUARD;
1994 	}
1995 
1996 	if (head->pi_size && head->ms >= head->pi_size)
1997 		head->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1998 	if (!(id->dps & NVME_NS_DPS_PI_FIRST)) {
1999 		if (disable_pi_offsets)
2000 			head->pi_type = 0;
2001 		else
2002 			info->pi_offset = head->ms - head->pi_size;
2003 	}
2004 
2005 	if (ctrl->ops->flags & NVME_F_FABRICS) {
2006 		/*
2007 		 * The NVMe over Fabrics specification only supports metadata as
2008 		 * part of the extended data LBA.  We rely on HCA/HBA support to
2009 		 * remap the separate metadata buffer from the block layer.
2010 		 */
2011 		if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
2012 			return;
2013 
2014 		head->features |= NVME_NS_EXT_LBAS;
2015 
2016 		/*
2017 		 * The current fabrics transport drivers support namespace
2018 		 * metadata formats only if nvme_ns_has_pi() returns true.
2019 		 * Suppress support for all other formats so the namespace will
2020 		 * have a 0 capacity and not be usable through the block stack.
2021 		 *
2022 		 * Note, this check will need to be modified if any drivers
2023 		 * gain the ability to use other metadata formats.
2024 		 */
2025 		if (ctrl->max_integrity_segments && nvme_ns_has_pi(head))
2026 			head->features |= NVME_NS_METADATA_SUPPORTED;
2027 	} else {
2028 		/*
2029 		 * For PCIe controllers, we can't easily remap the separate
2030 		 * metadata buffer from the block layer and thus require a
2031 		 * separate metadata buffer for block layer metadata/PI support.
2032 		 * We allow extended LBAs for the passthrough interface, though.
2033 		 */
2034 		if (id->flbas & NVME_NS_FLBAS_META_EXT)
2035 			head->features |= NVME_NS_EXT_LBAS;
2036 		else
2037 			head->features |= NVME_NS_METADATA_SUPPORTED;
2038 	}
2039 }
2040 
2041 
2042 static u32 nvme_configure_atomic_write(struct nvme_ns *ns,
2043 		struct nvme_id_ns *id, struct queue_limits *lim, u32 bs)
2044 {
2045 	u32 atomic_bs, boundary = 0;
2046 
2047 	/*
2048 	 * We do not support an offset for the atomic boundaries.
2049 	 */
2050 	if (id->nabo)
2051 		return bs;
2052 
2053 	if ((id->nsfeat & NVME_NS_FEAT_ATOMICS) && id->nawupf) {
2054 		/*
2055 		 * Use the per-namespace atomic write unit when available.
2056 		 */
2057 		atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
2058 		if (id->nabspf)
2059 			boundary = (le16_to_cpu(id->nabspf) + 1) * bs;
2060 	} else {
2061 		if (ns->ctrl->awupf)
2062 			dev_info_once(ns->ctrl->device,
2063 				"AWUPF ignored, only NAWUPF accepted\n");
2064 		atomic_bs = bs;
2065 	}
2066 
2067 	lim->atomic_write_hw_max = atomic_bs;
2068 	lim->atomic_write_hw_boundary = boundary;
2069 	lim->atomic_write_hw_unit_min = bs;
2070 	lim->atomic_write_hw_unit_max = rounddown_pow_of_two(atomic_bs);
2071 	lim->features |= BLK_FEAT_ATOMIC_WRITES;
2072 	return atomic_bs;
2073 }
2074 
2075 static u32 nvme_max_drv_segments(struct nvme_ctrl *ctrl)
2076 {
2077 	return ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> SECTOR_SHIFT) + 1;
2078 }
2079 
2080 static void nvme_set_ctrl_limits(struct nvme_ctrl *ctrl,
2081 		struct queue_limits *lim, bool is_admin)
2082 {
2083 	lim->max_hw_sectors = ctrl->max_hw_sectors;
2084 	lim->max_segments = min_t(u32, USHRT_MAX,
2085 		min_not_zero(nvme_max_drv_segments(ctrl), ctrl->max_segments));
2086 	lim->max_integrity_segments = ctrl->max_integrity_segments;
2087 	lim->virt_boundary_mask = ctrl->ops->get_virt_boundary(ctrl, is_admin);
2088 	lim->max_segment_size = UINT_MAX;
2089 	if (is_admin && (ctrl->quirks & NVME_QUIRK_ADMIN_PAGE_ALIGN))
2090 		lim->dma_alignment = NVME_CTRL_PAGE_SIZE - 1;
2091 	else
2092 		lim->dma_alignment = 3;
2093 }
2094 
2095 static bool nvme_update_disk_info(struct nvme_ns *ns, struct nvme_id_ns *id,
2096 		struct nvme_id_ns_nvm *nvm, struct queue_limits *lim)
2097 {
2098 	struct nvme_ns_head *head = ns->head;
2099 	struct nvme_ctrl *ctrl = ns->ctrl;
2100 	u32 bs = 1U << head->lba_shift;
2101 	u32 atomic_bs, phys_bs, io_opt = 0;
2102 	u32 npdg = 1, npda = 1;
2103 	bool valid = true;
2104 	u8 optperf;
2105 
2106 	/*
2107 	 * The block layer can't support LBA sizes larger than the page size
2108 	 * or smaller than a sector size yet, so catch this early and don't
2109 	 * allow block I/O.
2110 	 */
2111 	if (blk_validate_block_size(bs)) {
2112 		bs = (1 << 9);
2113 		valid = false;
2114 	}
2115 
2116 	phys_bs = bs;
2117 	atomic_bs = nvme_configure_atomic_write(ns, id, lim, bs);
2118 
2119 	optperf = id->nsfeat >> NVME_NS_FEAT_OPTPERF_SHIFT;
2120 	if (ctrl->vs >= NVME_VS(2, 1, 0))
2121 		optperf &= NVME_NS_FEAT_OPTPERF_MASK_2_1;
2122 	else
2123 		optperf &= NVME_NS_FEAT_OPTPERF_MASK;
2124 	if (optperf) {
2125 		/* NPWG = Namespace Preferred Write Granularity */
2126 		phys_bs = bs * (1 + le16_to_cpu(id->npwg));
2127 		/* NOWS = Namespace Optimal Write Size */
2128 		if (id->nows)
2129 			io_opt = bs * (1 + le16_to_cpu(id->nows));
2130 	}
2131 
2132 	/*
2133 	 * Linux filesystems assume writing a single physical block is
2134 	 * an atomic operation. Hence limit the physical block size to the
2135 	 * value of the Atomic Write Unit Power Fail parameter.
2136 	 */
2137 	lim->logical_block_size = bs;
2138 	lim->physical_block_size = min(phys_bs, atomic_bs);
2139 	lim->io_min = phys_bs;
2140 	lim->io_opt = io_opt;
2141 	if ((ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) &&
2142 	    (ctrl->oncs & NVME_CTRL_ONCS_DSM))
2143 		lim->max_write_zeroes_sectors = UINT_MAX;
2144 	else
2145 		lim->max_write_zeroes_sectors = ctrl->max_zeroes_sectors;
2146 
2147 	if (ctrl->dmrsl && ctrl->dmrsl <= nvme_sect_to_lba(ns->head, UINT_MAX))
2148 		lim->max_hw_discard_sectors =
2149 			nvme_lba_to_sect(ns->head, ctrl->dmrsl);
2150 	else if (ctrl->oncs & NVME_CTRL_ONCS_DSM)
2151 		lim->max_hw_discard_sectors = UINT_MAX;
2152 	else
2153 		lim->max_hw_discard_sectors = 0;
2154 
2155 	/*
2156 	 * NVMe namespaces advertise both a preferred deallocate granularity
2157 	 * (for a discard length) and alignment (for a discard starting offset).
2158 	 * However, Linux block devices advertise a single discard_granularity.
2159 	 * From NVM Command Set specification 1.1 section 5.2.2, the NPDGL/NPDAL
2160 	 * fields in the NVM Command Set Specific Identify Namespace structure
2161 	 * are preferred to NPDG/NPDA in the Identify Namespace structure since
2162 	 * they can represent larger values. However, NPDGL or NPDAL may be 0 if
2163 	 * unsupported. NPDG and NPDA are 0's based.
2164 	 * From Figure 115 of NVM Command Set specification 1.1, NPDGL and NPDAL
2165 	 * are supported if the high bit of OPTPERF is set. NPDG is supported if
2166 	 * the low bit of OPTPERF is set. NPDA is supported if either is set.
2167 	 * NPDG should be a multiple of NPDA, and likewise NPDGL should be a
2168 	 * multiple of NPDAL, but the spec doesn't say anything about NPDG vs.
2169 	 * NPDAL or NPDGL vs. NPDA. So compute the maximum instead of assuming
2170 	 * NPDG(L) is the larger. If neither NPDG, NPDGL, NPDA, nor NPDAL are
2171 	 * supported, default the discard_granularity to the logical block size.
2172 	 */
2173 	if (optperf & 0x2 && nvm && nvm->npdgl)
2174 		npdg = le32_to_cpu(nvm->npdgl);
2175 	else if (optperf & 0x1)
2176 		npdg = from0based(id->npdg);
2177 	if (optperf & 0x2 && nvm && nvm->npdal)
2178 		npda = le32_to_cpu(nvm->npdal);
2179 	else if (optperf)
2180 		npda = from0based(id->npda);
2181 	if (check_mul_overflow(max(npdg, npda), lim->logical_block_size,
2182 			       &lim->discard_granularity))
2183 		lim->discard_granularity = lim->logical_block_size;
2184 
2185 	if (ctrl->dmrl)
2186 		lim->max_discard_segments = ctrl->dmrl;
2187 	else
2188 		lim->max_discard_segments = NVME_DSM_MAX_RANGES;
2189 	return valid;
2190 }
2191 
2192 static bool nvme_ns_is_readonly(struct nvme_ns *ns, struct nvme_ns_info *info)
2193 {
2194 	return info->is_readonly || test_bit(NVME_NS_FORCE_RO, &ns->flags);
2195 }
2196 
2197 static inline bool nvme_first_scan(struct gendisk *disk)
2198 {
2199 	/* nvme_alloc_ns() scans the disk prior to adding it */
2200 	return !disk_live(disk);
2201 }
2202 
2203 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id,
2204 		struct queue_limits *lim)
2205 {
2206 	struct nvme_ctrl *ctrl = ns->ctrl;
2207 	u32 iob;
2208 
2209 	if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
2210 	    is_power_of_2(ctrl->max_hw_sectors))
2211 		iob = ctrl->max_hw_sectors;
2212 	else
2213 		iob = nvme_lba_to_sect(ns->head, le16_to_cpu(id->noiob));
2214 
2215 	if (!iob)
2216 		return;
2217 
2218 	if (!is_power_of_2(iob)) {
2219 		if (nvme_first_scan(ns->disk))
2220 			pr_warn("%s: ignoring unaligned IO boundary:%u\n",
2221 				ns->disk->disk_name, iob);
2222 		return;
2223 	}
2224 
2225 	if (blk_queue_is_zoned(ns->disk->queue)) {
2226 		if (nvme_first_scan(ns->disk))
2227 			pr_warn("%s: ignoring zoned namespace IO boundary\n",
2228 				ns->disk->disk_name);
2229 		return;
2230 	}
2231 
2232 	lim->chunk_sectors = iob;
2233 }
2234 
2235 static int nvme_update_ns_info_generic(struct nvme_ns *ns,
2236 		struct nvme_ns_info *info)
2237 {
2238 	struct queue_limits lim;
2239 	unsigned int memflags;
2240 	int ret;
2241 
2242 	lim = queue_limits_start_update(ns->disk->queue);
2243 	nvme_set_ctrl_limits(ns->ctrl, &lim, false);
2244 
2245 	memflags = blk_mq_freeze_queue(ns->disk->queue);
2246 	ret = queue_limits_commit_update(ns->disk->queue, &lim);
2247 	set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
2248 	blk_mq_unfreeze_queue(ns->disk->queue, memflags);
2249 
2250 	/* Hide the block-interface for these devices */
2251 	if (!ret)
2252 		ret = -ENODEV;
2253 	return ret;
2254 }
2255 
2256 static int nvme_query_fdp_granularity(struct nvme_ctrl *ctrl,
2257 				      struct nvme_ns_info *info, u8 fdp_idx)
2258 {
2259 	struct nvme_fdp_config_log hdr, *h;
2260 	struct nvme_fdp_config_desc *desc;
2261 	size_t size = sizeof(hdr);
2262 	void *log, *end;
2263 	int i, n, ret;
2264 
2265 	ret = nvme_get_log_lsi(ctrl, 0, NVME_LOG_FDP_CONFIGS, 0,
2266 			       NVME_CSI_NVM, &hdr, size, 0, info->endgid);
2267 	if (ret) {
2268 		dev_warn(ctrl->device,
2269 			 "FDP configs log header status:0x%x endgid:%d\n", ret,
2270 			 info->endgid);
2271 		return ret;
2272 	}
2273 
2274 	size = le32_to_cpu(hdr.sze);
2275 	if (size > PAGE_SIZE * MAX_ORDER_NR_PAGES) {
2276 		dev_warn(ctrl->device, "FDP config size too large:%zu\n",
2277 			 size);
2278 		return 0;
2279 	}
2280 
2281 	h = kvmalloc(size, GFP_KERNEL);
2282 	if (!h)
2283 		return -ENOMEM;
2284 
2285 	ret = nvme_get_log_lsi(ctrl, 0, NVME_LOG_FDP_CONFIGS, 0,
2286 			       NVME_CSI_NVM, h, size, 0, info->endgid);
2287 	if (ret) {
2288 		dev_warn(ctrl->device,
2289 			 "FDP configs log status:0x%x endgid:%d\n", ret,
2290 			 info->endgid);
2291 		goto out;
2292 	}
2293 
2294 	n = le16_to_cpu(h->numfdpc) + 1;
2295 	if (fdp_idx >= n) {
2296 		dev_warn(ctrl->device, "FDP index:%d out of range:%d\n",
2297 			 fdp_idx, n);
2298 		/* Proceed without registering FDP streams */
2299 		ret = 0;
2300 		goto out;
2301 	}
2302 
2303 	log = h + 1;
2304 	desc = log;
2305 	end = log + size - sizeof(*h);
2306 	for (i = 0; i < fdp_idx; i++) {
2307 		u16 dsze = le16_to_cpu(desc->dsze);
2308 
2309 		if (!dsze || log + dsze > end) {
2310 			dev_warn(ctrl->device,
2311 				 "FDP invalid config descriptor at index %d\n", i);
2312 			ret = 0;
2313 			goto out;
2314 		}
2315 		log += dsze;
2316 		desc = log;
2317 	}
2318 
2319 	if (le32_to_cpu(desc->nrg) > 1) {
2320 		dev_warn(ctrl->device, "FDP NRG > 1 not supported\n");
2321 		ret = 0;
2322 		goto out;
2323 	}
2324 
2325 	info->runs = le64_to_cpu(desc->runs);
2326 out:
2327 	kvfree(h);
2328 	return ret;
2329 }
2330 
2331 static int nvme_query_fdp_info(struct nvme_ns *ns, struct nvme_ns_info *info)
2332 {
2333 	struct nvme_ns_head *head = ns->head;
2334 	struct nvme_ctrl *ctrl = ns->ctrl;
2335 	struct nvme_fdp_ruh_status *ruhs;
2336 	struct nvme_fdp_config fdp;
2337 	struct nvme_command c = {};
2338 	size_t size;
2339 	int i, ret;
2340 
2341 	ret = nvme_get_features(ctrl, NVME_FEAT_FDP, info->endgid, NULL, 0,
2342 				&fdp);
2343 	if (ret) {
2344 		dev_warn(ctrl->device, "FDP get feature status:0x%x\n", ret);
2345 		return ret;
2346 	}
2347 
2348 	if (!(fdp.flags & FDPCFG_FDPE))
2349 		return 0;
2350 
2351 	ret = nvme_query_fdp_granularity(ctrl, info, fdp.fdpcidx);
2352 	if (!info->runs)
2353 		return ret;
2354 
2355 	size = struct_size(ruhs, ruhsd, NVME_MAX_PLIDS);
2356 	ruhs = kzalloc(size, GFP_KERNEL);
2357 	if (!ruhs)
2358 		return -ENOMEM;
2359 
2360 	c.imr.opcode = nvme_cmd_io_mgmt_recv;
2361 	c.imr.nsid = cpu_to_le32(head->ns_id);
2362 	c.imr.mo = NVME_IO_MGMT_RECV_MO_RUHS;
2363 	c.imr.numd = cpu_to_le32(nvme_bytes_to_numd(size));
2364 	ret = nvme_submit_sync_cmd(ns->queue, &c, ruhs, size);
2365 	if (ret) {
2366 		dev_warn(ctrl->device, "FDP io-mgmt status:0x%x\n", ret);
2367 		goto free;
2368 	}
2369 
2370 	head->nr_plids = min(le16_to_cpu(ruhs->nruhsd), NVME_MAX_PLIDS);
2371 	if (!head->nr_plids)
2372 		goto free;
2373 
2374 	head->plids = kzalloc_objs(*head->plids, head->nr_plids);
2375 	if (!head->plids) {
2376 		dev_warn(ctrl->device,
2377 			 "failed to allocate %u FDP placement IDs\n",
2378 			 head->nr_plids);
2379 		head->nr_plids = 0;
2380 		ret = -ENOMEM;
2381 		goto free;
2382 	}
2383 
2384 	for (i = 0; i < head->nr_plids; i++)
2385 		head->plids[i] = le16_to_cpu(ruhs->ruhsd[i].pid);
2386 	head->write_stream_granularity = min(info->runs, U32_MAX);
2387 free:
2388 	kfree(ruhs);
2389 	return ret;
2390 }
2391 
2392 static bool nvme_invalid_lba_sz(u64 nsze, signed int shift, sector_t *capacity)
2393 {
2394 	return check_shl_overflow(nsze, shift, capacity);
2395 }
2396 
2397 static int nvme_update_ns_info_block(struct nvme_ns *ns,
2398 		struct nvme_ns_info *info)
2399 {
2400 	struct queue_limits lim;
2401 	struct nvme_id_ns_nvm *nvm = NULL;
2402 	struct nvme_zone_info zi = {};
2403 	struct nvme_id_ns *id;
2404 	unsigned int memflags;
2405 	sector_t capacity;
2406 	unsigned lbaf;
2407 	int ret;
2408 
2409 	ret = nvme_identify_ns(ns->ctrl, info->nsid, &id);
2410 	if (ret)
2411 		return ret;
2412 
2413 	if (id->ncap == 0) {
2414 		/* namespace not allocated or attached */
2415 		info->is_removed = true;
2416 		ret = -ENXIO;
2417 		goto out;
2418 	}
2419 	lbaf = nvme_lbaf_index(id->flbas);
2420 
2421 	if (nvme_id_cns_ok(ns->ctrl, NVME_ID_CNS_CS_NS)) {
2422 		ret = nvme_identify_ns_nvm(ns->ctrl, info->nsid, &nvm);
2423 		if (ret < 0)
2424 			goto out;
2425 	}
2426 
2427 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
2428 	    ns->head->ids.csi == NVME_CSI_ZNS) {
2429 		ret = nvme_query_zone_info(ns, lbaf, &zi);
2430 		if (ret < 0)
2431 			goto out;
2432 	}
2433 
2434 	if (nvme_invalid_lba_sz(le64_to_cpu(id->nsze),
2435 			id->lbaf[lbaf].ds - SECTOR_SHIFT, &capacity)) {
2436 		dev_warn_once(ns->ctrl->device,
2437 			"invalid LBA data size %u, skipping namespace\n",
2438 			id->lbaf[lbaf].ds);
2439 		ret = -ENODEV;
2440 		goto out;
2441 	}
2442 
2443 	lim = queue_limits_start_update(ns->disk->queue);
2444 
2445 	memflags = blk_mq_freeze_queue(ns->disk->queue);
2446 	ns->head->lba_shift = id->lbaf[lbaf].ds;
2447 	ns->head->nuse = le64_to_cpu(id->nuse);
2448 	nvme_set_ctrl_limits(ns->ctrl, &lim, false);
2449 	nvme_configure_metadata(ns->ctrl, ns->head, id, nvm, info);
2450 	nvme_set_chunk_sectors(ns, id, &lim);
2451 	if (!nvme_update_disk_info(ns, id, nvm, &lim))
2452 		capacity = 0;
2453 
2454 	/*
2455 	 * A failed zone info query leaves zi zero-initialized, so skip the
2456 	 * zoned limits update instead of configuring the queue from it.
2457 	 * During a revalidation that keeps the zone geometry the queue was
2458 	 * last validated with; on a first scan the namespace is registered
2459 	 * without zoned limits, so that it is still available as a handle
2460 	 * for admin commands.
2461 	 */
2462 	if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
2463 	    ns->head->ids.csi == NVME_CSI_ZNS) {
2464 		if (zi.zone_size)
2465 			nvme_update_zone_info(ns, &lim, &zi);
2466 		else
2467 			dev_warn(ns->ctrl->device,
2468 				 "zone info query failed for nsid %u, %s\n",
2469 				 ns->head->ns_id,
2470 				 blk_queue_is_zoned(ns->disk->queue) ?
2471 				 "keeping the previous zone limits" :
2472 				 "not enabling zoned mode");
2473 	}
2474 
2475 	if ((ns->ctrl->vwc & NVME_CTRL_VWC_PRESENT) && !info->no_vwc)
2476 		lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA;
2477 	else
2478 		lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA);
2479 
2480 	if (info->is_rotational)
2481 		lim.features |= BLK_FEAT_ROTATIONAL;
2482 
2483 	/*
2484 	 * Register a metadata profile for PI, or the plain non-integrity NVMe
2485 	 * metadata masquerading as Type 0 if supported, otherwise reject block
2486 	 * I/O to namespaces with metadata except when the namespace supports
2487 	 * PI, as it can strip/insert in that case.
2488 	 */
2489 	if (!nvme_init_integrity(ns->head, &lim, info))
2490 		capacity = 0;
2491 
2492 	lim.max_write_streams = ns->head->nr_plids;
2493 	lim.write_stream_granularity = ns->head->write_stream_granularity;
2494 
2495 	/*
2496 	 * Only set the DEAC bit if the device guarantees that reads from
2497 	 * deallocated data return zeroes.  While the DEAC bit does not
2498 	 * require that, it must be a no-op if reads from deallocated data
2499 	 * do not return zeroes.
2500 	 */
2501 	if ((id->dlfeat & 0x7) == 0x1 && (id->dlfeat & (1 << 3))) {
2502 		ns->head->features |= NVME_NS_DEAC;
2503 		lim.max_hw_wzeroes_unmap_sectors = lim.max_write_zeroes_sectors;
2504 	}
2505 
2506 	ret = queue_limits_commit_update(ns->disk->queue, &lim);
2507 	if (ret) {
2508 		blk_mq_unfreeze_queue(ns->disk->queue, memflags);
2509 		goto out;
2510 	}
2511 
2512 	set_capacity_and_notify(ns->disk, capacity);
2513 	set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
2514 	set_bit(NVME_NS_READY, &ns->flags);
2515 	blk_mq_unfreeze_queue(ns->disk->queue, memflags);
2516 
2517 	if (blk_queue_is_zoned(ns->queue)) {
2518 		ret = blk_revalidate_disk_zones(ns->disk);
2519 		if (ret && !nvme_first_scan(ns->disk))
2520 			goto out;
2521 	}
2522 
2523 	ret = 0;
2524 out:
2525 	kfree(nvm);
2526 	kfree(id);
2527 	return ret;
2528 }
2529 
2530 static void nvme_stack_zone_resources(struct queue_limits *t,
2531 				      const struct queue_limits *b)
2532 {
2533 	t->max_open_zones = min_not_zero(t->max_open_zones, b->max_open_zones);
2534 	t->max_active_zones =
2535 		min_not_zero(t->max_active_zones, b->max_active_zones);
2536 }
2537 
2538 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_ns_info *info)
2539 {
2540 	bool unsupported = false;
2541 	int ret;
2542 
2543 	switch (info->ids.csi) {
2544 	case NVME_CSI_ZNS:
2545 		if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
2546 			dev_info(ns->ctrl->device,
2547 	"block device for nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
2548 				info->nsid);
2549 			ret = nvme_update_ns_info_generic(ns, info);
2550 			break;
2551 		}
2552 		ret = nvme_update_ns_info_block(ns, info);
2553 		break;
2554 	case NVME_CSI_NVM:
2555 		ret = nvme_update_ns_info_block(ns, info);
2556 		break;
2557 	default:
2558 		dev_info(ns->ctrl->device,
2559 			"block device for nsid %u not supported (csi %u)\n",
2560 			info->nsid, info->ids.csi);
2561 		ret = nvme_update_ns_info_generic(ns, info);
2562 		break;
2563 	}
2564 
2565 	/*
2566 	 * If probing fails due an unsupported feature, hide the block device,
2567 	 * but still allow other access.
2568 	 */
2569 	if (ret == -ENODEV) {
2570 		ns->disk->flags |= GENHD_FL_HIDDEN;
2571 		set_bit(NVME_NS_READY, &ns->flags);
2572 		unsupported = true;
2573 		ret = 0;
2574 	}
2575 
2576 	if (!ret && nvme_ns_head_multipath(ns->head)) {
2577 		struct queue_limits *ns_lim = &ns->disk->queue->limits;
2578 		struct queue_limits lim;
2579 		unsigned int memflags;
2580 
2581 		lim = queue_limits_start_update(ns->head->disk->queue);
2582 		memflags = blk_mq_freeze_queue(ns->head->disk->queue);
2583 		/*
2584 		 * queue_limits mixes values that are the hardware limitations
2585 		 * for bio splitting with what is the device configuration.
2586 		 *
2587 		 * For NVMe the device configuration can change after e.g. a
2588 		 * Format command, and we really want to pick up the new format
2589 		 * value here.  But we must still stack the queue limits to the
2590 		 * least common denominator for multipathing to split the bios
2591 		 * properly.
2592 		 *
2593 		 * To work around this, we explicitly set the device
2594 		 * configuration to those that we just queried, but only stack
2595 		 * the splitting limits in to make sure we still obey possibly
2596 		 * lower limitations of other controllers.
2597 		 */
2598 		lim.logical_block_size = ns_lim->logical_block_size;
2599 		lim.physical_block_size = ns_lim->physical_block_size;
2600 		lim.io_min = ns_lim->io_min;
2601 		lim.io_opt = ns_lim->io_opt;
2602 		queue_limits_stack_bdev(&lim, ns->disk->part0, 0,
2603 					ns->head->disk->disk_name);
2604 		if (lim.features & BLK_FEAT_ZONED)
2605 			nvme_stack_zone_resources(&lim, ns_lim);
2606 		if (unsupported)
2607 			ns->head->disk->flags |= GENHD_FL_HIDDEN;
2608 		else
2609 			nvme_init_integrity(ns->head, &lim, info);
2610 		lim.max_write_streams = ns_lim->max_write_streams;
2611 		lim.write_stream_granularity = ns_lim->write_stream_granularity;
2612 		ret = queue_limits_commit_update(ns->head->disk->queue, &lim);
2613 		if (ret)
2614 			goto unfreeze_head_queue;
2615 
2616 		set_capacity_and_notify(ns->head->disk, get_capacity(ns->disk));
2617 		set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info));
2618 		nvme_mpath_revalidate_paths(ns->head);
2619 		ret = nvme_mpath_revalidate_zones(ns->head);
2620 
2621 unfreeze_head_queue:
2622 		blk_mq_unfreeze_queue(ns->head->disk->queue, memflags);
2623 	}
2624 
2625 	return ret;
2626 }
2627 
2628 int nvme_ns_get_unique_id(struct nvme_ns *ns, u8 id[16],
2629 		enum blk_unique_id type)
2630 {
2631 	struct nvme_ns_ids *ids = &ns->head->ids;
2632 
2633 	if (type != BLK_UID_EUI64)
2634 		return -EINVAL;
2635 
2636 	if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) {
2637 		memcpy(id, &ids->nguid, sizeof(ids->nguid));
2638 		return sizeof(ids->nguid);
2639 	}
2640 	if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) {
2641 		memcpy(id, &ids->eui64, sizeof(ids->eui64));
2642 		return sizeof(ids->eui64);
2643 	}
2644 
2645 	return -EINVAL;
2646 }
2647 
2648 static int nvme_get_unique_id(struct gendisk *disk, u8 id[16],
2649 		enum blk_unique_id type)
2650 {
2651 	return nvme_ns_get_unique_id(disk->private_data, id, type);
2652 }
2653 
2654 #ifdef CONFIG_BLK_SED_OPAL
2655 static int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2656 		bool send)
2657 {
2658 	struct nvme_ctrl *ctrl = data;
2659 	struct nvme_command cmd = { };
2660 
2661 	if (send)
2662 		cmd.common.opcode = nvme_admin_security_send;
2663 	else
2664 		cmd.common.opcode = nvme_admin_security_recv;
2665 	cmd.common.nsid = 0;
2666 	cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2667 	cmd.common.cdw11 = cpu_to_le32(len);
2668 
2669 	return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
2670 			NVME_QID_ANY, NVME_SUBMIT_AT_HEAD);
2671 }
2672 
2673 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
2674 {
2675 	if (ctrl->oacs & NVME_CTRL_OACS_SEC_SUPP) {
2676 		if (!ctrl->opal_dev)
2677 			ctrl->opal_dev = init_opal_dev(ctrl, &nvme_sec_submit);
2678 		else if (was_suspended)
2679 			opal_unlock_from_suspend(ctrl->opal_dev);
2680 	} else {
2681 		free_opal_dev(ctrl->opal_dev);
2682 		ctrl->opal_dev = NULL;
2683 	}
2684 }
2685 #else
2686 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
2687 {
2688 }
2689 #endif /* CONFIG_BLK_SED_OPAL */
2690 
2691 #ifdef CONFIG_BLK_DEV_ZONED
2692 static int nvme_report_zones(struct gendisk *disk, sector_t sector,
2693 		unsigned int nr_zones, struct blk_report_zones_args *args)
2694 {
2695 	return nvme_ns_report_zones(disk->private_data, sector, nr_zones, args);
2696 }
2697 #else
2698 #define nvme_report_zones	NULL
2699 #endif /* CONFIG_BLK_DEV_ZONED */
2700 
2701 const struct block_device_operations nvme_bdev_ops = {
2702 	.owner		= THIS_MODULE,
2703 	.ioctl		= nvme_ioctl,
2704 	.compat_ioctl	= blkdev_compat_ptr_ioctl,
2705 	.open		= nvme_open,
2706 	.release	= nvme_release,
2707 	.getgeo		= nvme_getgeo,
2708 	.get_unique_id	= nvme_get_unique_id,
2709 	.report_zones	= nvme_report_zones,
2710 	.pr_ops		= &nvme_pr_ops,
2711 };
2712 
2713 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u32 mask, u32 val,
2714 		u32 timeout, const char *op)
2715 {
2716 	unsigned long timeout_jiffies = jiffies + timeout * HZ;
2717 	u32 csts;
2718 	int ret;
2719 
2720 	while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2721 		if (csts == ~0)
2722 			return -ENODEV;
2723 		if ((csts & mask) == val)
2724 			break;
2725 
2726 		usleep_range(1000, 2000);
2727 		if (fatal_signal_pending(current))
2728 			return -EINTR;
2729 		if (time_after(jiffies, timeout_jiffies)) {
2730 			dev_err(ctrl->device,
2731 				"Device not ready; aborting %s, CSTS=0x%x\n",
2732 				op, csts);
2733 			return -ENODEV;
2734 		}
2735 	}
2736 
2737 	return ret;
2738 }
2739 
2740 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, bool shutdown)
2741 {
2742 	int ret;
2743 
2744 	ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2745 	if (shutdown)
2746 		ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2747 	else
2748 		ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2749 
2750 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2751 	if (ret)
2752 		return ret;
2753 
2754 	if (shutdown) {
2755 		return nvme_wait_ready(ctrl, NVME_CSTS_SHST_MASK,
2756 				       NVME_CSTS_SHST_CMPLT,
2757 				       ctrl->shutdown_timeout, "shutdown");
2758 	}
2759 	if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2760 		msleep(NVME_QUIRK_DELAY_AMOUNT);
2761 	return nvme_wait_ready(ctrl, NVME_CSTS_RDY, 0,
2762 			       (NVME_CAP_TIMEOUT(ctrl->cap) + 1) / 2, "reset");
2763 }
2764 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2765 
2766 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2767 {
2768 	unsigned dev_page_min;
2769 	u32 timeout;
2770 	int ret;
2771 
2772 	ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2773 	if (ret) {
2774 		dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2775 		return ret;
2776 	}
2777 	dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2778 
2779 	if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2780 		dev_err(ctrl->device,
2781 			"Minimum device page size %u too large for host (%u)\n",
2782 			1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2783 		return -ENODEV;
2784 	}
2785 
2786 	if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2787 		ctrl->ctrl_config = NVME_CC_CSS_CSI;
2788 	else
2789 		ctrl->ctrl_config = NVME_CC_CSS_NVM;
2790 
2791 	/*
2792 	 * Setting CRIME results in CSTS.RDY before the media is ready. This
2793 	 * makes it possible for media related commands to return the error
2794 	 * NVME_SC_ADMIN_COMMAND_MEDIA_NOT_READY. Until the driver is
2795 	 * restructured to handle retries, disable CC.CRIME.
2796 	 */
2797 	ctrl->ctrl_config &= ~NVME_CC_CRIME;
2798 
2799 	ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2800 	ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2801 	ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2802 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2803 	if (ret)
2804 		return ret;
2805 
2806 	/* CAP value may change after initial CC write */
2807 	ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2808 	if (ret)
2809 		return ret;
2810 
2811 	timeout = NVME_CAP_TIMEOUT(ctrl->cap);
2812 	if (ctrl->cap & NVME_CAP_CRMS_CRWMS) {
2813 		u32 crto, ready_timeout;
2814 
2815 		ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CRTO, &crto);
2816 		if (ret) {
2817 			dev_err(ctrl->device, "Reading CRTO failed (%d)\n",
2818 				ret);
2819 			return ret;
2820 		}
2821 
2822 		/*
2823 		 * CRTO should always be greater or equal to CAP.TO, but some
2824 		 * devices are known to get this wrong. Use the larger of the
2825 		 * two values.
2826 		 */
2827 		ready_timeout = NVME_CRTO_CRWMT(crto);
2828 
2829 		if (ready_timeout < timeout)
2830 			dev_warn_once(ctrl->device, "bad crto:%x cap:%llx\n",
2831 				      crto, ctrl->cap);
2832 		else
2833 			timeout = ready_timeout;
2834 	}
2835 
2836 	ctrl->ctrl_config |= NVME_CC_ENABLE;
2837 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2838 	if (ret)
2839 		return ret;
2840 	return nvme_wait_ready(ctrl, NVME_CSTS_RDY, NVME_CSTS_RDY,
2841 			       (timeout + 1) / 2, "initialisation");
2842 }
2843 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2844 
2845 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2846 {
2847 	__le64 ts;
2848 	int ret;
2849 
2850 	if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2851 		return 0;
2852 
2853 	ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2854 	ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2855 			NULL);
2856 	if (ret)
2857 		dev_warn_once(ctrl->device,
2858 			"could not set timestamp (%d)\n", ret);
2859 	return ret;
2860 }
2861 
2862 static int nvme_configure_host_options(struct nvme_ctrl *ctrl)
2863 {
2864 	struct nvme_feat_host_behavior *host;
2865 	u8 acre = 0, lbafee = 0;
2866 	int ret;
2867 
2868 	/* Don't bother enabling the feature if retry delay is not reported */
2869 	if (ctrl->crdt[0])
2870 		acre = NVME_ENABLE_ACRE;
2871 	if (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)
2872 		lbafee = NVME_ENABLE_LBAFEE;
2873 
2874 	if (!acre && !lbafee)
2875 		return 0;
2876 
2877 	host = kzalloc_obj(*host);
2878 	if (!host)
2879 		return 0;
2880 
2881 	host->acre = acre;
2882 	host->lbafee = lbafee;
2883 	ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2884 				host, sizeof(*host), NULL);
2885 	kfree(host);
2886 	return ret;
2887 }
2888 
2889 /*
2890  * The function checks whether the given total (exlat + enlat) latency of
2891  * a power state allows the latter to be used as an APST transition target.
2892  * It does so by comparing the latency to the primary and secondary latency
2893  * tolerances defined by module params. If there's a match, the corresponding
2894  * timeout value is returned and the matching tolerance index (1 or 2) is
2895  * reported.
2896  */
2897 static bool nvme_apst_get_transition_time(u64 total_latency,
2898 		u64 *transition_time, unsigned *last_index)
2899 {
2900 	if (total_latency <= apst_primary_latency_tol_us) {
2901 		if (*last_index == 1)
2902 			return false;
2903 		*last_index = 1;
2904 		*transition_time = apst_primary_timeout_ms;
2905 		return true;
2906 	}
2907 	if (apst_secondary_timeout_ms &&
2908 		total_latency <= apst_secondary_latency_tol_us) {
2909 		if (*last_index <= 2)
2910 			return false;
2911 		*last_index = 2;
2912 		*transition_time = apst_secondary_timeout_ms;
2913 		return true;
2914 	}
2915 	return false;
2916 }
2917 
2918 /*
2919  * APST (Autonomous Power State Transition) lets us program a table of power
2920  * state transitions that the controller will perform automatically.
2921  *
2922  * Depending on module params, one of the two supported techniques will be used:
2923  *
2924  * - If the parameters provide explicit timeouts and tolerances, they will be
2925  *   used to build a table with up to 2 non-operational states to transition to.
2926  *   The default parameter values were selected based on the values used by
2927  *   Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic
2928  *   regeneration of the APST table in the event of switching between external
2929  *   and battery power, the timeouts and tolerances reflect a compromise
2930  *   between values used by Microsoft for AC and battery scenarios.
2931  * - If not, we'll configure the table with a simple heuristic: we are willing
2932  *   to spend at most 2% of the time transitioning between power states.
2933  *   Therefore, when running in any given state, we will enter the next
2934  *   lower-power non-operational state after waiting 50 * (enlat + exlat)
2935  *   microseconds, as long as that state's exit latency is under the requested
2936  *   maximum latency.
2937  *
2938  * We will not autonomously enter any non-operational state for which the total
2939  * latency exceeds ps_max_latency_us.
2940  *
2941  * Users can set ps_max_latency_us to zero to turn off APST.
2942  */
2943 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2944 {
2945 	struct nvme_feat_auto_pst *table;
2946 	unsigned apste = 0;
2947 	u64 max_lat_us = 0;
2948 	__le64 target = 0;
2949 	int max_ps = -1;
2950 	int state;
2951 	int ret;
2952 	unsigned last_lt_index = UINT_MAX;
2953 
2954 	/*
2955 	 * If APST isn't supported or if we haven't been initialized yet,
2956 	 * then don't do anything.
2957 	 */
2958 	if (!ctrl->apsta)
2959 		return 0;
2960 
2961 	if (ctrl->npss > 31) {
2962 		dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2963 		return 0;
2964 	}
2965 
2966 	table = kzalloc_obj(*table);
2967 	if (!table)
2968 		return 0;
2969 
2970 	if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2971 		/* Turn off APST. */
2972 		dev_dbg(ctrl->device, "APST disabled\n");
2973 		goto done;
2974 	}
2975 
2976 	/*
2977 	 * Walk through all states from lowest- to highest-power.
2978 	 * According to the spec, lower-numbered states use more power.  NPSS,
2979 	 * despite the name, is the index of the lowest-power state, not the
2980 	 * number of states.
2981 	 */
2982 	for (state = (int)ctrl->npss; state >= 0; state--) {
2983 		u64 total_latency_us, exit_latency_us, transition_ms;
2984 
2985 		if (target)
2986 			table->entries[state] = target;
2987 
2988 		/*
2989 		 * Don't allow transitions to the deepest state if it's quirked
2990 		 * off.
2991 		 */
2992 		if (state == ctrl->npss &&
2993 		    (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2994 			continue;
2995 
2996 		/*
2997 		 * Is this state a useful non-operational state for higher-power
2998 		 * states to autonomously transition to?
2999 		 */
3000 		if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
3001 			continue;
3002 
3003 		exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
3004 		if (exit_latency_us > ctrl->ps_max_latency_us)
3005 			continue;
3006 
3007 		total_latency_us = exit_latency_us +
3008 			le32_to_cpu(ctrl->psd[state].entry_lat);
3009 
3010 		/*
3011 		 * This state is good. It can be used as the APST idle target
3012 		 * for higher power states.
3013 		 */
3014 		if (apst_primary_timeout_ms && apst_primary_latency_tol_us) {
3015 			if (!nvme_apst_get_transition_time(total_latency_us,
3016 					&transition_ms, &last_lt_index))
3017 				continue;
3018 		} else {
3019 			transition_ms = total_latency_us + 19;
3020 			do_div(transition_ms, 20);
3021 			if (transition_ms > (1 << 24) - 1)
3022 				transition_ms = (1 << 24) - 1;
3023 		}
3024 
3025 		target = cpu_to_le64((state << 3) | (transition_ms << 8));
3026 		if (max_ps == -1)
3027 			max_ps = state;
3028 		if (total_latency_us > max_lat_us)
3029 			max_lat_us = total_latency_us;
3030 	}
3031 
3032 	if (max_ps == -1)
3033 		dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
3034 	else
3035 		dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
3036 			max_ps, max_lat_us, (int)sizeof(*table), table);
3037 	apste = 1;
3038 
3039 done:
3040 	ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
3041 				table, sizeof(*table), NULL);
3042 	if (ret)
3043 		dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
3044 	kfree(table);
3045 	return ret;
3046 }
3047 
3048 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
3049 {
3050 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3051 	u64 latency;
3052 
3053 	switch (val) {
3054 	case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
3055 	case PM_QOS_LATENCY_ANY:
3056 		latency = U64_MAX;
3057 		break;
3058 
3059 	default:
3060 		latency = val;
3061 	}
3062 
3063 	if (ctrl->ps_max_latency_us != latency) {
3064 		ctrl->ps_max_latency_us = latency;
3065 		if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
3066 			nvme_configure_apst(ctrl);
3067 	}
3068 }
3069 
3070 struct nvme_core_quirk_entry {
3071 	/*
3072 	 * NVMe model and firmware strings are padded with spaces.  For
3073 	 * simplicity, strings in the quirk table are padded with NULLs
3074 	 * instead.
3075 	 */
3076 	u16 vid;
3077 	const char *mn;
3078 	const char *fr;
3079 	unsigned long quirks;
3080 };
3081 
3082 static const struct nvme_core_quirk_entry core_quirks[] = {
3083 	{
3084 		/*
3085 		 * This Toshiba device seems to die using any APST states.  See:
3086 		 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
3087 		 */
3088 		.vid = 0x1179,
3089 		.mn = "THNSF5256GPUK TOSHIBA",
3090 		.quirks = NVME_QUIRK_NO_APST,
3091 	},
3092 	{
3093 		/*
3094 		 * This LiteON CL1-3D*-Q11 firmware version has a race
3095 		 * condition associated with actions related to suspend to idle
3096 		 * LiteON has resolved the problem in future firmware
3097 		 */
3098 		.vid = 0x14a4,
3099 		.fr = "22301111",
3100 		.quirks = NVME_QUIRK_SIMPLE_SUSPEND,
3101 	},
3102 	{
3103 		/*
3104 		 * This Kioxia CD6-V Series / HPE PE8030 device times out and
3105 		 * aborts I/O during any load, but more easily reproducible
3106 		 * with discards (fstrim).
3107 		 *
3108 		 * The device is left in a state where it is also not possible
3109 		 * to use "nvme set-feature" to disable APST, but booting with
3110 		 * nvme_core.default_ps_max_latency_us=0 works.
3111 		 */
3112 		.vid = 0x1e0f,
3113 		.mn = "KCD6XVUL6T40",
3114 		.quirks = NVME_QUIRK_NO_APST,
3115 	},
3116 	{
3117 		/*
3118 		 * The external Samsung X5 SSD fails initialization without a
3119 		 * delay before checking if it is ready and has a whole set of
3120 		 * other problems.  To make this even more interesting, it
3121 		 * shares the PCI ID with internal Samsung 970 Evo Plus that
3122 		 * does not need or want these quirks.
3123 		 */
3124 		.vid = 0x144d,
3125 		.mn = "Samsung Portable SSD X5",
3126 		.quirks = NVME_QUIRK_DELAY_BEFORE_CHK_RDY |
3127 			  NVME_QUIRK_NO_DEEPEST_PS |
3128 			  NVME_QUIRK_IGNORE_DEV_SUBNQN,
3129 	}
3130 };
3131 
3132 /* match is null-terminated but idstr is space-padded. */
3133 static bool string_matches(const char *idstr, const char *match, size_t len)
3134 {
3135 	size_t matchlen;
3136 
3137 	if (!match)
3138 		return true;
3139 
3140 	matchlen = strlen(match);
3141 	WARN_ON_ONCE(matchlen > len);
3142 
3143 	if (memcmp(idstr, match, matchlen))
3144 		return false;
3145 
3146 	for (; matchlen < len; matchlen++)
3147 		if (idstr[matchlen] != ' ')
3148 			return false;
3149 
3150 	return true;
3151 }
3152 
3153 static bool quirk_matches(const struct nvme_id_ctrl *id,
3154 			  const struct nvme_core_quirk_entry *q)
3155 {
3156 	return q->vid == le16_to_cpu(id->vid) &&
3157 		string_matches(id->mn, q->mn, sizeof(id->mn)) &&
3158 		string_matches(id->fr, q->fr, sizeof(id->fr));
3159 }
3160 
3161 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
3162 		struct nvme_id_ctrl *id)
3163 {
3164 	size_t nqnlen;
3165 	int off;
3166 
3167 	if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
3168 		nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
3169 		if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
3170 			strscpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
3171 			return;
3172 		}
3173 
3174 		if (ctrl->vs >= NVME_VS(1, 2, 1))
3175 			dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
3176 	}
3177 
3178 	/*
3179 	 * Generate a "fake" NQN similar to the one in Section 4.5 of the NVMe
3180 	 * Base Specification 2.0.  It is slightly different from the format
3181 	 * specified there due to historic reasons, and we can't change it now.
3182 	 */
3183 	off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
3184 			"nqn.2014.08.org.nvmexpress:%04x%04x",
3185 			le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
3186 	memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
3187 	off += sizeof(id->sn);
3188 	memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
3189 	off += sizeof(id->mn);
3190 	memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
3191 }
3192 
3193 static void nvme_release_subsystem(struct device *dev)
3194 {
3195 	struct nvme_subsystem *subsys =
3196 		container_of(dev, struct nvme_subsystem, dev);
3197 	struct nvme_effects_log *cel;
3198 	unsigned long i;
3199 
3200 	if (subsys->instance >= 0)
3201 		ida_free(&nvme_instance_ida, subsys->instance);
3202 	xa_for_each(&subsys->cels, i, cel) {
3203 		xa_erase(&subsys->cels, i);
3204 		kfree(cel);
3205 	}
3206 	xa_destroy(&subsys->cels);
3207 	kfree(subsys);
3208 }
3209 
3210 static void nvme_destroy_subsystem(struct kref *ref)
3211 {
3212 	struct nvme_subsystem *subsys =
3213 			container_of(ref, struct nvme_subsystem, ref);
3214 
3215 	mutex_lock(&nvme_subsystems_lock);
3216 	list_del(&subsys->entry);
3217 	mutex_unlock(&nvme_subsystems_lock);
3218 
3219 	ida_destroy(&subsys->ns_ida);
3220 	device_del(&subsys->dev);
3221 	put_device(&subsys->dev);
3222 }
3223 
3224 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
3225 {
3226 	kref_put(&subsys->ref, nvme_destroy_subsystem);
3227 }
3228 
3229 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
3230 	__must_hold(&nvme_subsystems_lock)
3231 {
3232 	struct nvme_subsystem *subsys;
3233 
3234 	lockdep_assert_held(&nvme_subsystems_lock);
3235 
3236 	/*
3237 	 * Fail matches for discovery subsystems. This results
3238 	 * in each discovery controller bound to a unique subsystem.
3239 	 * This avoids issues with validating controller values
3240 	 * that can only be true when there is a single unique subsystem.
3241 	 * There may be multiple and completely independent entities
3242 	 * that provide discovery controllers.
3243 	 */
3244 	if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
3245 		return NULL;
3246 
3247 	list_for_each_entry(subsys, &nvme_subsystems, entry) {
3248 		if (strcmp(subsys->subnqn, subsysnqn))
3249 			continue;
3250 		if (!kref_get_unless_zero(&subsys->ref))
3251 			continue;
3252 		return subsys;
3253 	}
3254 
3255 	return NULL;
3256 }
3257 
3258 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
3259 {
3260 	return ctrl->opts && ctrl->opts->discovery_nqn;
3261 }
3262 
3263 static inline bool nvme_admin_ctrl(struct nvme_ctrl *ctrl)
3264 {
3265 	return ctrl->cntrltype == NVME_CTRL_ADMIN;
3266 }
3267 
3268 static inline bool nvme_is_io_ctrl(struct nvme_ctrl *ctrl)
3269 {
3270 	return !nvme_discovery_ctrl(ctrl) && !nvme_admin_ctrl(ctrl);
3271 }
3272 
3273 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
3274 		struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
3275 	__must_hold(&nvme_subsystems_lock)
3276 {
3277 	struct nvme_ctrl *tmp;
3278 
3279 	lockdep_assert_held(&nvme_subsystems_lock);
3280 
3281 	list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
3282 		if (nvme_state_terminal(tmp))
3283 			continue;
3284 
3285 		if (tmp->cntlid == ctrl->cntlid) {
3286 			dev_err(ctrl->device,
3287 				"Duplicate cntlid %u with %s, subsys %s, rejecting\n",
3288 				ctrl->cntlid, dev_name(tmp->device),
3289 				subsys->subnqn);
3290 			return false;
3291 		}
3292 
3293 		if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
3294 		    nvme_discovery_ctrl(ctrl))
3295 			continue;
3296 
3297 		dev_err(ctrl->device,
3298 			"Subsystem does not support multiple controllers\n");
3299 		return false;
3300 	}
3301 
3302 	return true;
3303 }
3304 
3305 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
3306 	__context_unsafe(/* initialize unpublished/lock-guarded variables */)
3307 {
3308 	struct nvme_subsystem *subsys, *found;
3309 	int ret;
3310 
3311 	subsys = kzalloc_obj(*subsys);
3312 	if (!subsys)
3313 		return -ENOMEM;
3314 
3315 	subsys->instance = -1;
3316 	mutex_init(&subsys->lock);
3317 	kref_init(&subsys->ref);
3318 	INIT_LIST_HEAD(&subsys->ctrls);
3319 	INIT_LIST_HEAD(&subsys->nsheads);
3320 	xa_init(&subsys->cels);
3321 	nvme_init_subnqn(subsys, ctrl, id);
3322 	memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
3323 	memcpy(subsys->model, id->mn, sizeof(subsys->model));
3324 	subsys->vendor_id = le16_to_cpu(id->vid);
3325 	subsys->cmic = id->cmic;
3326 
3327 	/* Versions prior to 1.4 don't necessarily report a valid type */
3328 	if (id->cntrltype == NVME_CTRL_DISC ||
3329 	    !strcmp(subsys->subnqn, NVME_DISC_SUBSYS_NAME))
3330 		subsys->subtype = NVME_NQN_DISC;
3331 	else
3332 		subsys->subtype = NVME_NQN_NVME;
3333 
3334 	if (nvme_discovery_ctrl(ctrl) && subsys->subtype != NVME_NQN_DISC) {
3335 		dev_err(ctrl->device,
3336 			"Subsystem %s is not a discovery controller",
3337 			subsys->subnqn);
3338 		kfree(subsys);
3339 		return -EINVAL;
3340 	}
3341 	nvme_mpath_default_iopolicy(subsys);
3342 
3343 	subsys->dev.class = &nvme_subsys_class;
3344 	subsys->dev.release = nvme_release_subsystem;
3345 	subsys->dev.groups = nvme_subsys_attrs_groups;
3346 	dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
3347 	device_initialize(&subsys->dev);
3348 
3349 	mutex_lock(&nvme_subsystems_lock);
3350 	found = __nvme_find_get_subsystem(subsys->subnqn);
3351 	if (found) {
3352 		put_device(&subsys->dev);
3353 		subsys = found;
3354 
3355 		if (!nvme_validate_cntlid(subsys, ctrl, id)) {
3356 			ret = -EINVAL;
3357 			goto out_put_subsystem;
3358 		}
3359 	} else {
3360 		ret = device_add(&subsys->dev);
3361 		if (ret) {
3362 			dev_err(ctrl->device,
3363 				"failed to register subsystem device.\n");
3364 			put_device(&subsys->dev);
3365 			goto out_unlock;
3366 		}
3367 		ida_init(&subsys->ns_ida);
3368 		list_add_tail(&subsys->entry, &nvme_subsystems);
3369 	}
3370 
3371 	ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
3372 				dev_name(ctrl->device));
3373 	if (ret) {
3374 		dev_err(ctrl->device,
3375 			"failed to create sysfs link from subsystem.\n");
3376 		goto out_put_subsystem;
3377 	}
3378 
3379 	if (!found)
3380 		subsys->instance = ctrl->instance;
3381 	ctrl->subsys = subsys;
3382 	list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
3383 	mutex_unlock(&nvme_subsystems_lock);
3384 	return 0;
3385 
3386 out_put_subsystem:
3387 	nvme_put_subsystem(subsys);
3388 out_unlock:
3389 	mutex_unlock(&nvme_subsystems_lock);
3390 	return ret;
3391 }
3392 
3393 static int nvme_get_log_lsi(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page,
3394 		u8 lsp, u8 csi, void *log, size_t size, u64 offset, u16 lsi)
3395 {
3396 	struct nvme_command c = { };
3397 	u32 dwlen = nvme_bytes_to_numd(size);
3398 
3399 	c.get_log_page.opcode = nvme_admin_get_log_page;
3400 	c.get_log_page.nsid = cpu_to_le32(nsid);
3401 	c.get_log_page.lid = log_page;
3402 	c.get_log_page.lsp = lsp;
3403 	c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
3404 	c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
3405 	c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
3406 	c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
3407 	c.get_log_page.csi = csi;
3408 	c.get_log_page.lsi = cpu_to_le16(lsi);
3409 
3410 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
3411 }
3412 
3413 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
3414 		void *log, size_t size, u64 offset)
3415 {
3416 	return nvme_get_log_lsi(ctrl, nsid, log_page, lsp, csi, log, size,
3417 			offset, 0);
3418 }
3419 
3420 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
3421 				struct nvme_effects_log **log)
3422 {
3423 	struct nvme_effects_log *old, *cel = xa_load(&ctrl->subsys->cels, csi);
3424 	int ret;
3425 
3426 	if (cel)
3427 		goto out;
3428 
3429 	cel = kzalloc_obj(*cel);
3430 	if (!cel)
3431 		return -ENOMEM;
3432 
3433 	ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
3434 			cel, sizeof(*cel), 0);
3435 	if (ret) {
3436 		kfree(cel);
3437 		return ret;
3438 	}
3439 
3440 	old = xa_store(&ctrl->subsys->cels, csi, cel, GFP_KERNEL);
3441 	if (xa_is_err(old)) {
3442 		kfree(cel);
3443 		return xa_err(old);
3444 	}
3445 out:
3446 	*log = cel;
3447 	return 0;
3448 }
3449 
3450 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
3451 {
3452 	u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
3453 
3454 	if (check_shl_overflow(1U, units + page_shift - 9, &val))
3455 		return UINT_MAX;
3456 	return val;
3457 }
3458 
3459 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
3460 {
3461 	struct nvme_command c = { };
3462 	struct nvme_id_ctrl_nvm *id;
3463 	int ret;
3464 
3465 	/*
3466 	 * Even though NVMe spec explicitly states that MDTS is not applicable
3467 	 * to the write-zeroes, we are cautious and limit the size to the
3468 	 * controllers max_hw_sectors value, which is based on the MDTS field
3469 	 * and possibly other limiting factors.
3470 	 */
3471 	if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
3472 	    !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
3473 		ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
3474 	else
3475 		ctrl->max_zeroes_sectors = 0;
3476 
3477 	if (!nvme_is_io_ctrl(ctrl) ||
3478 	    !nvme_id_cns_ok(ctrl, NVME_ID_CNS_CS_CTRL) ||
3479 	    test_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags))
3480 		return 0;
3481 
3482 	id = kzalloc_obj(*id);
3483 	if (!id)
3484 		return -ENOMEM;
3485 
3486 	c.identify.opcode = nvme_admin_identify;
3487 	c.identify.cns = NVME_ID_CNS_CS_CTRL;
3488 	c.identify.csi = NVME_CSI_NVM;
3489 
3490 	ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
3491 	if (ret)
3492 		goto free_data;
3493 
3494 	ctrl->dmrl = id->dmrl;
3495 	ctrl->dmrsl = le32_to_cpu(id->dmrsl);
3496 	if (id->wzsl && !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
3497 		ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
3498 
3499 free_data:
3500 	if (ret > 0)
3501 		set_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags);
3502 	kfree(id);
3503 	return ret;
3504 }
3505 
3506 static int nvme_init_effects_log(struct nvme_ctrl *ctrl,
3507 		u8 csi, struct nvme_effects_log **log)
3508 {
3509 	struct nvme_effects_log *effects, *old;
3510 
3511 	effects = kzalloc_obj(*effects);
3512 	if (!effects)
3513 		return -ENOMEM;
3514 
3515 	old = xa_store(&ctrl->subsys->cels, csi, effects, GFP_KERNEL);
3516 	if (xa_is_err(old)) {
3517 		kfree(effects);
3518 		return xa_err(old);
3519 	}
3520 
3521 	*log = effects;
3522 	return 0;
3523 }
3524 
3525 static void nvme_init_known_nvm_effects(struct nvme_ctrl *ctrl)
3526 {
3527 	struct nvme_effects_log	*log = ctrl->effects;
3528 
3529 	log->acs[nvme_admin_format_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
3530 						NVME_CMD_EFFECTS_NCC |
3531 						NVME_CMD_EFFECTS_CSE_MASK);
3532 	log->acs[nvme_admin_sanitize_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
3533 						NVME_CMD_EFFECTS_CSE_MASK);
3534 
3535 	/*
3536 	 * The spec says the result of a security receive command depends on
3537 	 * the previous security send command. As such, many vendors log this
3538 	 * command as one to submitted only when no other commands to the same
3539 	 * namespace are outstanding. The intention is to tell the host to
3540 	 * prevent mixing security send and receive.
3541 	 *
3542 	 * This driver can only enforce such exclusive access against IO
3543 	 * queues, though. We are not readily able to enforce such a rule for
3544 	 * two commands to the admin queue, which is the only queue that
3545 	 * matters for this command.
3546 	 *
3547 	 * Rather than blindly freezing the IO queues for this effect that
3548 	 * doesn't even apply to IO, mask it off.
3549 	 */
3550 	log->acs[nvme_admin_security_recv] &= cpu_to_le32(~NVME_CMD_EFFECTS_CSE_MASK);
3551 
3552 	log->iocs[nvme_cmd_write] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3553 	log->iocs[nvme_cmd_write_zeroes] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3554 	log->iocs[nvme_cmd_write_uncor] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3555 }
3556 
3557 static int nvme_init_effects(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
3558 {
3559 	int ret = 0;
3560 
3561 	mutex_lock(&ctrl->subsys->lock);
3562 	ctrl->effects = xa_load(&ctrl->subsys->cels, NVME_CSI_NVM);
3563 	if (ctrl->effects)
3564 		goto out_unlock;
3565 
3566 	if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
3567 		ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3568 		if (ret < 0)
3569 			goto out_unlock;
3570 	}
3571 
3572 	if (!ctrl->effects) {
3573 		ret = nvme_init_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3574 		if (ret < 0)
3575 			goto out_unlock;
3576 	}
3577 
3578 	nvme_init_known_nvm_effects(ctrl);
3579 out_unlock:
3580 	mutex_unlock(&ctrl->subsys->lock);
3581 	return ret;
3582 }
3583 
3584 static int nvme_check_ctrl_fabric_info(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
3585 {
3586 	/*
3587 	 * In fabrics we need to verify the cntlid matches the
3588 	 * admin connect
3589 	 */
3590 	if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
3591 		dev_err(ctrl->device,
3592 			"Mismatching cntlid: Connect %u vs Identify %u, rejecting\n",
3593 			ctrl->cntlid, le16_to_cpu(id->cntlid));
3594 		return -EINVAL;
3595 	}
3596 
3597 	if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
3598 		dev_err(ctrl->device,
3599 			"keep-alive support is mandatory for fabrics\n");
3600 		return -EINVAL;
3601 	}
3602 
3603 	if (nvme_is_io_ctrl(ctrl) && ctrl->ioccsz < 4) {
3604 		dev_err(ctrl->device,
3605 			"I/O queue command capsule supported size %d < 4\n",
3606 			ctrl->ioccsz);
3607 		return -EINVAL;
3608 	}
3609 
3610 	if (nvme_is_io_ctrl(ctrl) && ctrl->iorcsz < 1) {
3611 		dev_err(ctrl->device,
3612 			"I/O queue response capsule supported size %d < 1\n",
3613 			ctrl->iorcsz);
3614 		return -EINVAL;
3615 	}
3616 
3617 	if (!ctrl->maxcmd) {
3618 		dev_warn(ctrl->device,
3619 			"Firmware bug: maximum outstanding commands is 0\n");
3620 		ctrl->maxcmd = ctrl->sqsize + 1;
3621 	}
3622 
3623 	return 0;
3624 }
3625 
3626 static int nvme_init_identify(struct nvme_ctrl *ctrl)
3627 {
3628 	struct queue_limits lim;
3629 	struct nvme_id_ctrl *id;
3630 	u32 max_hw_sectors;
3631 	bool prev_apst_enabled;
3632 	int ret;
3633 
3634 	ret = nvme_identify_ctrl(ctrl, &id);
3635 	if (ret) {
3636 		dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
3637 		return -EIO;
3638 	}
3639 
3640 	if (!(ctrl->ops->flags & NVME_F_FABRICS))
3641 		ctrl->cntlid = le16_to_cpu(id->cntlid);
3642 
3643 	if (!ctrl->identified) {
3644 		unsigned int i;
3645 
3646 		/*
3647 		 * Check for quirks.  Quirk can depend on firmware version,
3648 		 * so, in principle, the set of quirks present can change
3649 		 * across a reset.  As a possible future enhancement, we
3650 		 * could re-scan for quirks every time we reinitialize
3651 		 * the device, but we'd have to make sure that the driver
3652 		 * behaves intelligently if the quirks change.
3653 		 */
3654 		for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
3655 			if (quirk_matches(id, &core_quirks[i]))
3656 				ctrl->quirks |= core_quirks[i].quirks;
3657 		}
3658 
3659 		ret = nvme_init_subsystem(ctrl, id);
3660 		if (ret)
3661 			goto out_free;
3662 
3663 		ret = nvme_init_effects(ctrl, id);
3664 		if (ret)
3665 			goto out_free;
3666 	}
3667 	memcpy(ctrl->subsys->firmware_rev, id->fr,
3668 	       sizeof(ctrl->subsys->firmware_rev));
3669 
3670 	if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
3671 		dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
3672 		ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
3673 	}
3674 
3675 	ctrl->crdt[0] = le16_to_cpu(id->crdt1);
3676 	ctrl->crdt[1] = le16_to_cpu(id->crdt2);
3677 	ctrl->crdt[2] = le16_to_cpu(id->crdt3);
3678 
3679 	ctrl->oacs = le16_to_cpu(id->oacs);
3680 	ctrl->oncs = le16_to_cpu(id->oncs);
3681 	ctrl->mtfa = le16_to_cpu(id->mtfa);
3682 	ctrl->oaes = le32_to_cpu(id->oaes);
3683 	ctrl->wctemp = le16_to_cpu(id->wctemp);
3684 	ctrl->cctemp = le16_to_cpu(id->cctemp);
3685 
3686 	atomic_set(&ctrl->abort_limit, id->acl + 1);
3687 	ctrl->vwc = id->vwc;
3688 	if (id->mdts)
3689 		max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
3690 	else
3691 		max_hw_sectors = UINT_MAX;
3692 	ctrl->max_hw_sectors =
3693 		min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
3694 
3695 	lim = queue_limits_start_update(ctrl->admin_q);
3696 	nvme_set_ctrl_limits(ctrl, &lim, true);
3697 	ret = queue_limits_commit_update(ctrl->admin_q, &lim);
3698 	if (ret)
3699 		goto out_free;
3700 
3701 	ctrl->sgls = le32_to_cpu(id->sgls);
3702 	ctrl->kas = le16_to_cpu(id->kas);
3703 	ctrl->max_namespaces = le32_to_cpu(id->mnan);
3704 	ctrl->ctratt = le32_to_cpu(id->ctratt);
3705 
3706 	ctrl->cntrltype = id->cntrltype;
3707 	ctrl->dctype = id->dctype;
3708 
3709 	if (id->rtd3e) {
3710 		/* us -> s */
3711 		u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
3712 
3713 		ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
3714 						 shutdown_timeout, 60);
3715 
3716 		if (ctrl->shutdown_timeout != shutdown_timeout)
3717 			dev_info(ctrl->device,
3718 				 "D3 entry latency set to %u seconds\n",
3719 				 ctrl->shutdown_timeout);
3720 	} else
3721 		ctrl->shutdown_timeout = shutdown_timeout;
3722 
3723 	ctrl->npss = id->npss;
3724 	ctrl->apsta = id->apsta;
3725 	prev_apst_enabled = ctrl->apst_enabled;
3726 	if (ctrl->quirks & NVME_QUIRK_NO_APST) {
3727 		if (force_apst && id->apsta) {
3728 			dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
3729 			ctrl->apst_enabled = true;
3730 		} else {
3731 			ctrl->apst_enabled = false;
3732 		}
3733 	} else {
3734 		ctrl->apst_enabled = id->apsta;
3735 	}
3736 	memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
3737 
3738 	if (ctrl->ops->flags & NVME_F_FABRICS) {
3739 		ctrl->icdoff = le16_to_cpu(id->icdoff);
3740 		ctrl->ioccsz = le32_to_cpu(id->ioccsz);
3741 		ctrl->iorcsz = le32_to_cpu(id->iorcsz);
3742 		ctrl->maxcmd = le16_to_cpu(id->maxcmd);
3743 
3744 		ret = nvme_check_ctrl_fabric_info(ctrl, id);
3745 		if (ret)
3746 			goto out_free;
3747 	} else {
3748 		ctrl->hmpre = le32_to_cpu(id->hmpre);
3749 		ctrl->hmmin = le32_to_cpu(id->hmmin);
3750 		ctrl->hmminds = le32_to_cpu(id->hmminds);
3751 		ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
3752 	}
3753 
3754 	ret = nvme_mpath_init_identify(ctrl, id);
3755 	if (ret < 0)
3756 		goto out_free;
3757 
3758 	if (ctrl->apst_enabled && !prev_apst_enabled)
3759 		dev_pm_qos_expose_latency_tolerance(ctrl->device);
3760 	else if (!ctrl->apst_enabled && prev_apst_enabled)
3761 		dev_pm_qos_hide_latency_tolerance(ctrl->device);
3762 	ctrl->awupf = le16_to_cpu(id->awupf);
3763 out_free:
3764 	kfree(id);
3765 	return ret;
3766 }
3767 
3768 /*
3769  * Initialize the cached copies of the Identify data and various controller
3770  * register in our nvme_ctrl structure.  This should be called as soon as
3771  * the admin queue is fully up and running.
3772  */
3773 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl, bool was_suspended)
3774 {
3775 	int ret;
3776 
3777 	ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3778 	if (ret) {
3779 		dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3780 		return ret;
3781 	}
3782 
3783 	ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3784 
3785 	if (ctrl->vs >= NVME_VS(1, 1, 0))
3786 		ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3787 
3788 	ret = nvme_init_identify(ctrl);
3789 	if (ret)
3790 		return ret;
3791 
3792 	if (nvme_admin_ctrl(ctrl)) {
3793 		/*
3794 		 * An admin controller has one admin queue, but no I/O queues.
3795 		 * Override queue_count so it only creates an admin queue.
3796 		 */
3797 		dev_dbg(ctrl->device,
3798 			"Subsystem %s is an administrative controller",
3799 			ctrl->subsys->subnqn);
3800 		ctrl->queue_count = 1;
3801 	}
3802 
3803 	ret = nvme_configure_apst(ctrl);
3804 	if (ret < 0)
3805 		return ret;
3806 
3807 	ret = nvme_configure_timestamp(ctrl);
3808 	if (ret < 0)
3809 		return ret;
3810 
3811 	ret = nvme_configure_host_options(ctrl);
3812 	if (ret < 0)
3813 		return ret;
3814 
3815 	nvme_configure_opal(ctrl, was_suspended);
3816 
3817 	if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
3818 		/*
3819 		 * Do not return errors unless we are in a controller reset,
3820 		 * the controller works perfectly fine without hwmon.
3821 		 */
3822 		ret = nvme_hwmon_init(ctrl);
3823 		if (ret == -EINTR)
3824 			return ret;
3825 
3826 		if (!nvme_ctrl_sgl_supported(ctrl))
3827 			dev_info(ctrl->device,
3828 				"passthrough uses implicit buffer lengths\n");
3829 	}
3830 
3831 	clear_bit(NVME_CTRL_DIRTY_CAPABILITY, &ctrl->flags);
3832 	ctrl->identified = true;
3833 
3834 	nvme_start_keep_alive(ctrl);
3835 
3836 	return 0;
3837 }
3838 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
3839 
3840 static int nvme_dev_open(struct inode *inode, struct file *file)
3841 {
3842 	struct nvme_ctrl *ctrl =
3843 		container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3844 
3845 	switch (nvme_ctrl_state(ctrl)) {
3846 	case NVME_CTRL_LIVE:
3847 		break;
3848 	default:
3849 		return -EWOULDBLOCK;
3850 	}
3851 
3852 	nvme_get_ctrl(ctrl);
3853 	if (!try_module_get(ctrl->ops->module)) {
3854 		nvme_put_ctrl(ctrl);
3855 		return -EINVAL;
3856 	}
3857 
3858 	file->private_data = ctrl;
3859 	return 0;
3860 }
3861 
3862 static int nvme_dev_release(struct inode *inode, struct file *file)
3863 {
3864 	struct nvme_ctrl *ctrl =
3865 		container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3866 
3867 	module_put(ctrl->ops->module);
3868 	nvme_put_ctrl(ctrl);
3869 	return 0;
3870 }
3871 
3872 static const struct file_operations nvme_dev_fops = {
3873 	.owner		= THIS_MODULE,
3874 	.open		= nvme_dev_open,
3875 	.release	= nvme_dev_release,
3876 	.unlocked_ioctl	= nvme_dev_ioctl,
3877 	.compat_ioctl	= compat_ptr_ioctl,
3878 	.uring_cmd	= nvme_dev_uring_cmd,
3879 };
3880 
3881 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_ctrl *ctrl,
3882 		unsigned nsid)
3883 	__must_hold(&ctrl->subsys->lock)
3884 {
3885 	struct nvme_ns_head *h;
3886 
3887 	lockdep_assert_held(&ctrl->subsys->lock);
3888 
3889 	list_for_each_entry(h, &ctrl->subsys->nsheads, entry) {
3890 		/*
3891 		 * Private namespaces can share NSIDs under some conditions.
3892 		 * In that case we can't use the same ns_head for namespaces
3893 		 * with the same NSID.
3894 		 */
3895 		if (h->ns_id != nsid || !nvme_is_unique_nsid(ctrl, h))
3896 			continue;
3897 		if (nvme_tryget_ns_head(h))
3898 			return h;
3899 	}
3900 
3901 	return NULL;
3902 }
3903 
3904 static int nvme_subsys_check_duplicate_ids(struct nvme_subsystem *subsys,
3905 		struct nvme_ns_ids *ids)
3906 	__must_hold(&subsys->lock)
3907 {
3908 	bool has_uuid = !uuid_is_null(&ids->uuid);
3909 	bool has_nguid = memchr_inv(ids->nguid, 0, sizeof(ids->nguid));
3910 	bool has_eui64 = memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
3911 	struct nvme_ns_head *h;
3912 
3913 	lockdep_assert_held(&subsys->lock);
3914 
3915 	list_for_each_entry(h, &subsys->nsheads, entry) {
3916 		if (has_uuid && uuid_equal(&ids->uuid, &h->ids.uuid))
3917 			return -EINVAL;
3918 		if (has_nguid &&
3919 		    memcmp(&ids->nguid, &h->ids.nguid, sizeof(ids->nguid)) == 0)
3920 			return -EINVAL;
3921 		if (has_eui64 &&
3922 		    memcmp(&ids->eui64, &h->ids.eui64, sizeof(ids->eui64)) == 0)
3923 			return -EINVAL;
3924 	}
3925 
3926 	return 0;
3927 }
3928 
3929 static void nvme_cdev_rel(struct device *dev)
3930 {
3931 	ida_free(&nvme_ns_chr_minor_ida, MINOR(dev->devt));
3932 	if (dev->parent->class == &nvme_class)
3933 		nvme_put_ns(container_of(dev, struct nvme_ns, cdev_device));
3934 	else
3935 		nvme_put_ns_head(container_of(dev, struct nvme_ns_head,
3936 				cdev_device));
3937 }
3938 
3939 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
3940 {
3941 	cdev_device_del(cdev, cdev_device);
3942 	put_device(cdev_device);
3943 }
3944 
3945 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
3946 		const struct file_operations *fops, struct module *owner,
3947 		int ctrl, int head)
3948 {
3949 	int minor, ret;
3950 
3951 	minor = ida_alloc(&nvme_ns_chr_minor_ida, GFP_KERNEL);
3952 	if (minor < 0)
3953 		return minor;
3954 
3955 	ret = dev_set_name(cdev_device, "ng%dn%d", ctrl, head);
3956 	if (ret) {
3957 		ida_free(&nvme_ns_chr_minor_ida, minor);
3958 		return ret;
3959 	}
3960 	cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
3961 	cdev_device->class = &nvme_ns_chr_class;
3962 	cdev_device->release = nvme_cdev_rel;
3963 	device_initialize(cdev_device);
3964 	cdev_init(cdev, fops);
3965 	cdev->owner = owner;
3966 	ret = cdev_device_add(cdev, cdev_device);
3967 	if (ret)
3968 		put_device(cdev_device);
3969 
3970 	return ret;
3971 }
3972 
3973 static int nvme_ns_chr_open(struct inode *inode, struct file *file)
3974 {
3975 	return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
3976 }
3977 
3978 static int nvme_ns_chr_release(struct inode *inode, struct file *file)
3979 {
3980 	nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
3981 	return 0;
3982 }
3983 
3984 static const struct file_operations nvme_ns_chr_fops = {
3985 	.owner		= THIS_MODULE,
3986 	.open		= nvme_ns_chr_open,
3987 	.release	= nvme_ns_chr_release,
3988 	.unlocked_ioctl	= nvme_ns_chr_ioctl,
3989 	.compat_ioctl	= compat_ptr_ioctl,
3990 	.uring_cmd	= nvme_ns_chr_uring_cmd,
3991 	.uring_cmd_iopoll = nvme_ns_chr_uring_cmd_iopoll,
3992 };
3993 
3994 static void nvme_add_ns_cdev(struct nvme_ns *ns)
3995 {
3996 	ns->cdev_device.parent = ns->ctrl->device;
3997 
3998 	nvme_get_ns(ns); /* Undone in nvme_cdev_rel() */
3999 	if (nvme_cdev_add(&ns->cdev, &ns->cdev_device,
4000 			&nvme_ns_chr_fops, ns->ctrl->ops->module,
4001 			ns->ctrl->instance, ns->head->instance)) {
4002 		dev_err(ns->ctrl->device, "Unable to create the ng%dn%d device\n",
4003 			ns->ctrl->instance, ns->head->instance);
4004 		nvme_put_ns(ns);
4005 		return;
4006 	}
4007 	set_bit(NVME_NS_CDEV_LIVE, &ns->flags);
4008 }
4009 
4010 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ns *ns,
4011 		struct nvme_ns_info *info)
4012 	__must_hold(&ns->ctrl->subsys->lock)
4013 {
4014 	struct nvme_ctrl *ctrl = ns->ctrl;
4015 	struct nvme_ns_head *head;
4016 	size_t size = sizeof(*head);
4017 	int ret = -ENOMEM;
4018 
4019 #ifdef CONFIG_NVME_MULTIPATH
4020 	size += nr_node_ids * sizeof(struct nvme_ns *);
4021 #endif
4022 
4023 	head = kzalloc(size, GFP_KERNEL);
4024 	if (!head)
4025 		goto out;
4026 	ret = ida_alloc_min(&ctrl->subsys->ns_ida, 1, GFP_KERNEL);
4027 	if (ret < 0)
4028 		goto out_free_head;
4029 	head->instance = ret;
4030 	INIT_LIST_HEAD(&head->list);
4031 	ret = init_srcu_struct(&head->srcu);
4032 	if (ret)
4033 		goto out_ida_remove;
4034 	head->subsys = ctrl->subsys;
4035 	head->ns_id = info->nsid;
4036 	head->ids = info->ids;
4037 	head->shared = info->is_shared;
4038 	head->rotational = info->is_rotational;
4039 	ratelimit_state_init(&head->rs_nuse, 5 * HZ, 1);
4040 	ratelimit_set_flags(&head->rs_nuse, RATELIMIT_MSG_ON_RELEASE);
4041 	kref_init(&head->ref);
4042 	ns->head = head;
4043 
4044 	if (head->ids.csi) {
4045 		ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
4046 		if (ret)
4047 			goto out_cleanup_srcu;
4048 	} else
4049 		head->effects = ctrl->effects;
4050 
4051 	if (ctrl->ctratt & NVME_CTRL_ATTR_FDPS) {
4052 		ret = nvme_query_fdp_info(ns, info);
4053 		if (ret < 0)
4054 			goto out_cleanup_srcu;
4055 	}
4056 
4057 	ret = nvme_mpath_alloc_disk(ctrl, head);
4058 	if (ret)
4059 		goto out_cleanup_fdp;
4060 
4061 	list_add_tail(&head->entry, &ctrl->subsys->nsheads);
4062 
4063 	kref_get(&ctrl->subsys->ref);
4064 
4065 	return head;
4066 out_cleanup_fdp:
4067 	kfree(head->plids);
4068 out_cleanup_srcu:
4069 	cleanup_srcu_struct(&head->srcu);
4070 out_ida_remove:
4071 	ida_free(&ctrl->subsys->ns_ida, head->instance);
4072 out_free_head:
4073 	kfree(head);
4074 	ns->head = NULL;
4075 out:
4076 	if (ret > 0)
4077 		ret = blk_status_to_errno(nvme_error_status(ret));
4078 	return ERR_PTR(ret);
4079 }
4080 
4081 static int nvme_global_check_duplicate_ids(struct nvme_subsystem *this,
4082 		struct nvme_ns_ids *ids)
4083 {
4084 	struct nvme_subsystem *s;
4085 	int ret = 0;
4086 
4087 	/*
4088 	 * Note that this check is racy as we try to avoid holding the global
4089 	 * lock over the whole ns_head creation.  But it is only intended as
4090 	 * a sanity check anyway.
4091 	 */
4092 	mutex_lock(&nvme_subsystems_lock);
4093 	list_for_each_entry(s, &nvme_subsystems, entry) {
4094 		if (s == this)
4095 			continue;
4096 		mutex_lock(&s->lock);
4097 		ret = nvme_subsys_check_duplicate_ids(s, ids);
4098 		mutex_unlock(&s->lock);
4099 		if (ret)
4100 			break;
4101 	}
4102 	mutex_unlock(&nvme_subsystems_lock);
4103 
4104 	return ret;
4105 }
4106 
4107 static int nvme_init_ns_head(struct nvme_ns *ns, struct nvme_ns_info *info)
4108 {
4109 	struct nvme_ctrl *ctrl = ns->ctrl;
4110 	struct nvme_ns_head *head = NULL;
4111 	int ret;
4112 
4113 	ret = nvme_global_check_duplicate_ids(ctrl->subsys, &info->ids);
4114 	if (ret) {
4115 		/*
4116 		 * We've found two different namespaces on two different
4117 		 * subsystems that report the same ID.  This is pretty nasty
4118 		 * for anything that actually requires unique device
4119 		 * identification.  In the kernel we need this for multipathing,
4120 		 * and in user space the /dev/disk/by-id/ links rely on it.
4121 		 *
4122 		 * If the device also claims to be multi-path capable back off
4123 		 * here now and refuse the probe the second device as this is a
4124 		 * recipe for data corruption.  If not this is probably a
4125 		 * cheap consumer device if on the PCIe bus, so let the user
4126 		 * proceed and use the shiny toy, but warn that with changing
4127 		 * probing order (which due to our async probing could just be
4128 		 * device taking longer to startup) the other device could show
4129 		 * up at any time.
4130 		 */
4131 		nvme_print_device_info(ctrl);
4132 		if ((ns->ctrl->ops->flags & NVME_F_FABRICS) || /* !PCIe */
4133 		    ((ns->ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) &&
4134 		     info->is_shared)) {
4135 			dev_err(ctrl->device,
4136 				"ignoring nsid %u because of duplicate IDs\n",
4137 				info->nsid);
4138 			return ret;
4139 		}
4140 
4141 		dev_err(ctrl->device,
4142 			"clearing duplicate IDs for nsid %u\n", info->nsid);
4143 		dev_err(ctrl->device,
4144 			"use of /dev/disk/by-id/ may cause data corruption\n");
4145 		memset(&info->ids.nguid, 0, sizeof(info->ids.nguid));
4146 		memset(&info->ids.uuid, 0, sizeof(info->ids.uuid));
4147 		memset(&info->ids.eui64, 0, sizeof(info->ids.eui64));
4148 		ctrl->quirks |= NVME_QUIRK_BOGUS_NID;
4149 	}
4150 
4151 	mutex_lock(&ctrl->subsys->lock);
4152 	head = nvme_find_ns_head(ctrl, info->nsid);
4153 	if (!head) {
4154 		ret = nvme_subsys_check_duplicate_ids(ctrl->subsys, &info->ids);
4155 		if (ret) {
4156 			dev_err(ctrl->device,
4157 				"duplicate IDs in subsystem for nsid %u\n",
4158 				info->nsid);
4159 			goto out_unlock;
4160 		}
4161 		head = nvme_alloc_ns_head(ns, info);
4162 		if (IS_ERR(head)) {
4163 			ret = PTR_ERR(head);
4164 			goto out_unlock;
4165 		}
4166 	} else {
4167 		ret = -EINVAL;
4168 		if ((!info->is_shared || !head->shared) &&
4169 		    !list_empty(&head->list)) {
4170 			dev_err(ctrl->device,
4171 				"Duplicate unshared namespace %u\n",
4172 				info->nsid);
4173 			goto out_put_ns_head;
4174 		}
4175 		if (!nvme_ns_ids_equal(&head->ids, &info->ids)) {
4176 			dev_err(ctrl->device,
4177 				"IDs don't match for shared namespace %u\n",
4178 					info->nsid);
4179 			goto out_put_ns_head;
4180 		}
4181 
4182 		if (!multipath) {
4183 			dev_warn(ctrl->device,
4184 				"Found shared namespace %u, but multipathing not supported.\n",
4185 				info->nsid);
4186 			dev_warn_once(ctrl->device,
4187 				"Shared namespace support requires core_nvme.multipath=Y.\n");
4188 		}
4189 	}
4190 
4191 	list_add_tail_rcu(&ns->siblings, &head->list);
4192 	ns->head = head;
4193 	mutex_unlock(&ctrl->subsys->lock);
4194 
4195 #ifdef CONFIG_NVME_MULTIPATH
4196 	if (cancel_delayed_work(&head->remove_work))
4197 		module_put(THIS_MODULE);
4198 #endif
4199 	return 0;
4200 
4201 out_put_ns_head:
4202 	nvme_put_ns_head(head);
4203 out_unlock:
4204 	mutex_unlock(&ctrl->subsys->lock);
4205 	return ret;
4206 }
4207 
4208 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
4209 {
4210 	struct nvme_ns *ns, *ret = NULL;
4211 	int srcu_idx;
4212 
4213 	srcu_idx = srcu_read_lock(&ctrl->srcu);
4214 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4215 				 srcu_read_lock_held(&ctrl->srcu)) {
4216 		if (ns->head->ns_id == nsid) {
4217 			if (!nvme_get_ns(ns))
4218 				continue;
4219 			ret = ns;
4220 			break;
4221 		}
4222 		if (ns->head->ns_id > nsid)
4223 			break;
4224 	}
4225 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
4226 	return ret;
4227 }
4228 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, "NVME_TARGET_PASSTHRU");
4229 
4230 /*
4231  * Add the namespace to the controller list while keeping the list ordered.
4232  */
4233 static void nvme_ns_add_to_ctrl_list(struct nvme_ns *ns)
4234 {
4235 	struct nvme_ns *tmp;
4236 
4237 	list_for_each_entry_reverse(tmp, &ns->ctrl->namespaces, list) {
4238 		if (tmp->head->ns_id < ns->head->ns_id) {
4239 			list_add_rcu(&ns->list, &tmp->list);
4240 			return;
4241 		}
4242 	}
4243 	list_add_rcu(&ns->list, &ns->ctrl->namespaces);
4244 }
4245 
4246 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info)
4247 {
4248 	struct queue_limits lim = { };
4249 	struct nvme_ns *ns;
4250 	struct gendisk *disk;
4251 	int node = ctrl->numa_node;
4252 	bool last_path = false;
4253 
4254 	ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
4255 	if (!ns)
4256 		return;
4257 
4258 	if (ctrl->opts && ctrl->opts->data_digest)
4259 		lim.features |= BLK_FEAT_STABLE_WRITES;
4260 	if (ctrl->ops->supports_pci_p2pdma &&
4261 	    ctrl->ops->supports_pci_p2pdma(ctrl))
4262 		lim.features |= BLK_FEAT_PCI_P2PDMA;
4263 
4264 	disk = blk_mq_alloc_disk(ctrl->tagset, &lim, ns);
4265 	if (IS_ERR(disk))
4266 		goto out_free_ns;
4267 	disk->fops = &nvme_bdev_ops;
4268 	disk->private_data = ns;
4269 
4270 	ns->disk = disk;
4271 	ns->queue = disk->queue;
4272 	ns->ctrl = ctrl;
4273 	kref_init(&ns->kref);
4274 
4275 	if (nvme_init_ns_head(ns, info))
4276 		goto out_cleanup_disk;
4277 
4278 	/*
4279 	 * If multipathing is enabled, the device name for all disks and not
4280 	 * just those that represent shared namespaces needs to be based on the
4281 	 * subsystem instance.  Using the controller instance for private
4282 	 * namespaces could lead to naming collisions between shared and private
4283 	 * namespaces if they don't use a common numbering scheme.
4284 	 *
4285 	 * If multipathing is not enabled, disk names must use the controller
4286 	 * instance as shared namespaces will show up as multiple block
4287 	 * devices.
4288 	 */
4289 	if (nvme_ns_head_multipath(ns->head)) {
4290 		sprintf(disk->disk_name, "nvme%dc%dn%d", ctrl->subsys->instance,
4291 			ctrl->instance, ns->head->instance);
4292 		disk->flags |= GENHD_FL_HIDDEN;
4293 	} else if (multipath) {
4294 		sprintf(disk->disk_name, "nvme%dn%d", ctrl->subsys->instance,
4295 			ns->head->instance);
4296 	} else {
4297 		sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
4298 			ns->head->instance);
4299 	}
4300 
4301 	if (nvme_update_ns_info(ns, info))
4302 		goto out_unlink_ns;
4303 
4304 	mutex_lock(&ctrl->namespaces_lock);
4305 	/*
4306 	 * Ensure that no namespaces are added to the ctrl list after the queues
4307 	 * are frozen, thereby avoiding a deadlock between scan and reset.
4308 	 */
4309 	if (test_bit(NVME_CTRL_FROZEN, &ctrl->flags)) {
4310 		mutex_unlock(&ctrl->namespaces_lock);
4311 		goto out_unlink_ns;
4312 	}
4313 	blk_queue_rq_timeout(ns->queue, ctrl->io_timeout);
4314 	nvme_ns_add_to_ctrl_list(ns);
4315 	mutex_unlock(&ctrl->namespaces_lock);
4316 	synchronize_srcu(&ctrl->srcu);
4317 	nvme_get_ctrl(ctrl);
4318 
4319 	if (device_add_disk(ctrl->device, ns->disk, nvme_ns_attr_groups))
4320 		goto out_cleanup_ns_from_list;
4321 
4322 	if (!nvme_ns_head_multipath(ns->head))
4323 		nvme_add_ns_cdev(ns);
4324 
4325 	nvme_mpath_add_disk(ns, info->anagrpid);
4326 	nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
4327 
4328 	return;
4329 
4330  out_cleanup_ns_from_list:
4331 	nvme_put_ctrl(ctrl);
4332 	mutex_lock(&ctrl->namespaces_lock);
4333 	list_del_rcu(&ns->list);
4334 	mutex_unlock(&ctrl->namespaces_lock);
4335 	synchronize_srcu(&ctrl->srcu);
4336  out_unlink_ns:
4337 	mutex_lock(&ctrl->subsys->lock);
4338 	list_del_rcu(&ns->siblings);
4339 	if (list_empty(&ns->head->list)) {
4340 		list_del_init(&ns->head->entry);
4341 		/*
4342 		 * If multipath is not configured, we still create a namespace
4343 		 * head (nshead), but head->disk is not initialized in that
4344 		 * case.  As a result, only a single reference to nshead is held
4345 		 * (via kref_init()) when it is created. Therefore, ensure that
4346 		 * we do not release the reference to nshead twice if head->disk
4347 		 * is not present.
4348 		 */
4349 		if (ns->head->disk)
4350 			last_path = true;
4351 	}
4352 	mutex_unlock(&ctrl->subsys->lock);
4353 
4354 	/* guarantee not available in head->list */
4355 	synchronize_srcu(&ns->head->srcu);
4356 	if (last_path)
4357 		nvme_put_ns_head(ns->head);
4358 	nvme_put_ns_head(ns->head);
4359  out_cleanup_disk:
4360 	put_disk(disk);
4361  out_free_ns:
4362 	kfree(ns);
4363 }
4364 
4365 static void nvme_ns_remove(struct nvme_ns *ns)
4366 {
4367 	bool last_path = false;
4368 
4369 	if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
4370 		return;
4371 
4372 	clear_bit(NVME_NS_READY, &ns->flags);
4373 	set_capacity(ns->disk, 0);
4374 	nvme_fault_inject_fini(&ns->fault_inject);
4375 
4376 	/*
4377 	 * Ensure that !NVME_NS_READY is seen by other threads to prevent
4378 	 * this ns going back into current_path.
4379 	 */
4380 	synchronize_srcu(&ns->head->srcu);
4381 
4382 	/* wait for concurrent submissions */
4383 	if (nvme_mpath_clear_current_path(ns))
4384 		synchronize_srcu(&ns->head->srcu);
4385 
4386 	mutex_lock(&ns->ctrl->subsys->lock);
4387 	list_del_rcu(&ns->siblings);
4388 	if (list_empty(&ns->head->list)) {
4389 		if (!nvme_mpath_queue_if_no_path(ns->head))
4390 			list_del_init(&ns->head->entry);
4391 		last_path = true;
4392 	}
4393 	mutex_unlock(&ns->ctrl->subsys->lock);
4394 
4395 	/* guarantee not available in head->list */
4396 	synchronize_srcu(&ns->head->srcu);
4397 
4398 	if (!nvme_ns_head_multipath(ns->head)) {
4399 		if (test_and_clear_bit(NVME_NS_CDEV_LIVE, &ns->flags))
4400 			nvme_cdev_del(&ns->cdev, &ns->cdev_device);
4401 	}
4402 
4403 	nvme_mpath_remove_sysfs_link(ns);
4404 
4405 	del_gendisk(ns->disk);
4406 
4407 	mutex_lock(&ns->ctrl->namespaces_lock);
4408 	list_del_rcu(&ns->list);
4409 	mutex_unlock(&ns->ctrl->namespaces_lock);
4410 	synchronize_srcu(&ns->ctrl->srcu);
4411 
4412 	if (last_path)
4413 		nvme_mpath_remove_disk(ns->head);
4414 	nvme_put_ns(ns);
4415 }
4416 
4417 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
4418 {
4419 	struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
4420 
4421 	if (ns) {
4422 		nvme_ns_remove(ns);
4423 		nvme_put_ns(ns);
4424 	}
4425 }
4426 
4427 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_info *info)
4428 {
4429 	int ret = NVME_SC_INVALID_NS | NVME_STATUS_DNR;
4430 
4431 	if (!nvme_ns_ids_equal(&ns->head->ids, &info->ids)) {
4432 		dev_err(ns->ctrl->device,
4433 			"identifiers changed for nsid %u\n", ns->head->ns_id);
4434 		goto out;
4435 	}
4436 
4437 	ret = nvme_update_ns_info(ns, info);
4438 out:
4439 	/*
4440 	 * Only remove the namespace if we got a fatal error back from the
4441 	 * device, otherwise ignore the error and just move on.
4442 	 *
4443 	 * TODO: we should probably schedule a delayed retry here.
4444 	 */
4445 	if (ret > 0 && (ret & NVME_STATUS_DNR))
4446 		nvme_ns_remove(ns);
4447 }
4448 
4449 static void nvme_scan_ns(struct nvme_ctrl *ctrl, unsigned nsid)
4450 {
4451 	struct nvme_ns_info info = { .nsid = nsid };
4452 	struct nvme_ns *ns;
4453 	int ret = 1;
4454 
4455 	if (nvme_identify_ns_descs(ctrl, &info))
4456 		return;
4457 
4458 	if (info.ids.csi != NVME_CSI_NVM && !nvme_multi_css(ctrl)) {
4459 		dev_warn(ctrl->device,
4460 			"command set not reported for nsid: %u\n", nsid);
4461 		return;
4462 	}
4463 
4464 	/*
4465 	 * If available try to use the Command Set Independent Identify Namespace
4466 	 * data structure to find all the generic information that is needed to
4467 	 * set up a namespace.  If not fall back to the legacy version.
4468 	 */
4469 	if ((ctrl->cap & NVME_CAP_CRMS_CRIMS) ||
4470 	    (info.ids.csi != NVME_CSI_NVM && info.ids.csi != NVME_CSI_ZNS) ||
4471 	    ctrl->vs >= NVME_VS(2, 0, 0))
4472 		ret = nvme_ns_info_from_id_cs_indep(ctrl, &info);
4473 	if (ret > 0)
4474 		ret = nvme_ns_info_from_identify(ctrl, &info);
4475 
4476 	if (info.is_removed)
4477 		nvme_ns_remove_by_nsid(ctrl, nsid);
4478 
4479 	/*
4480 	 * Ignore the namespace if it is not ready. We will get an AEN once it
4481 	 * becomes ready and restart the scan.
4482 	 */
4483 	if (ret || !info.is_ready)
4484 		return;
4485 
4486 	ns = nvme_find_get_ns(ctrl, nsid);
4487 	if (ns) {
4488 		nvme_validate_ns(ns, &info);
4489 		nvme_put_ns(ns);
4490 	} else {
4491 		nvme_alloc_ns(ctrl, &info);
4492 	}
4493 }
4494 
4495 /**
4496  * struct async_scan_info - keeps track of controller & NSIDs to scan
4497  * @ctrl:	Controller on which namespaces are being scanned
4498  * @next_nsid:	Index of next NSID to scan in ns_list
4499  * @ns_list:	Pointer to list of NSIDs to scan
4500  *
4501  * Note: There is a single async_scan_info structure shared by all instances
4502  * of nvme_scan_ns_async() scanning a given controller, so the atomic
4503  * operations on next_nsid are critical to ensure each instance scans a unique
4504  * NSID.
4505  */
4506 struct async_scan_info {
4507 	struct nvme_ctrl *ctrl;
4508 	atomic_t next_nsid;
4509 	__le32 *ns_list;
4510 };
4511 
4512 static void nvme_scan_ns_async(void *data, async_cookie_t cookie)
4513 {
4514 	struct async_scan_info *scan_info = data;
4515 	int idx;
4516 	u32 nsid;
4517 
4518 	idx = (u32)atomic_fetch_inc(&scan_info->next_nsid);
4519 	nsid = le32_to_cpu(scan_info->ns_list[idx]);
4520 
4521 	nvme_scan_ns(scan_info->ctrl, nsid);
4522 }
4523 
4524 static void nvme_remove_nsid_range(struct nvme_ctrl *ctrl, u32 start, u32 end)
4525 {
4526 	struct nvme_ns *ns, *next;
4527 	LIST_HEAD(rm_list);
4528 
4529 	mutex_lock(&ctrl->namespaces_lock);
4530 	list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
4531 		if (ns->head->ns_id >= end)
4532 			break;
4533 		if (ns->head->ns_id > start) {
4534 			list_del_rcu(&ns->list);
4535 			synchronize_srcu(&ctrl->srcu);
4536 			list_add_tail_rcu(&ns->list, &rm_list);
4537 		}
4538 	}
4539 	mutex_unlock(&ctrl->namespaces_lock);
4540 
4541 	list_for_each_entry_safe(ns, next, &rm_list, list)
4542 		nvme_ns_remove(ns);
4543 }
4544 
4545 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
4546 {
4547 	const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
4548 	__le32 *ns_list;
4549 	u32 prev = 0;
4550 	int ret = 0, i;
4551 	ASYNC_DOMAIN(domain);
4552 	struct async_scan_info scan_info;
4553 
4554 	ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
4555 	if (!ns_list)
4556 		return -ENOMEM;
4557 
4558 	scan_info.ctrl = ctrl;
4559 	scan_info.ns_list = ns_list;
4560 	for (;;) {
4561 		struct nvme_command cmd = {
4562 			.identify.opcode	= nvme_admin_identify,
4563 			.identify.cns		= NVME_ID_CNS_NS_ACTIVE_LIST,
4564 			.identify.nsid		= cpu_to_le32(prev),
4565 		};
4566 
4567 		ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
4568 					    NVME_IDENTIFY_DATA_SIZE);
4569 		if (ret) {
4570 			dev_warn(ctrl->device,
4571 				"Identify NS List failed (status=0x%x)\n", ret);
4572 			goto free;
4573 		}
4574 
4575 		atomic_set(&scan_info.next_nsid, 0);
4576 		for (i = 0; i < nr_entries; i++) {
4577 			u32 nsid = le32_to_cpu(ns_list[i]);
4578 
4579 			if (!nsid)	/* end of the list? */
4580 				goto out;
4581 			async_schedule_domain(nvme_scan_ns_async, &scan_info,
4582 						&domain);
4583 			if (prev + 1 < nsid)
4584 				nvme_remove_nsid_range(ctrl, prev, nsid);
4585 			prev = max(prev + 1, nsid);
4586 		}
4587 		async_synchronize_full_domain(&domain);
4588 	}
4589  out:
4590 	nvme_remove_nsid_range(ctrl, prev, UINT_MAX);
4591  free:
4592 	async_synchronize_full_domain(&domain);
4593 	kfree(ns_list);
4594 	return ret;
4595 }
4596 
4597 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
4598 {
4599 	struct nvme_id_ctrl *id;
4600 	u32 nn, i;
4601 
4602 	if (nvme_identify_ctrl(ctrl, &id))
4603 		return;
4604 	nn = le32_to_cpu(id->nn);
4605 	kfree(id);
4606 
4607 	for (i = 1; i <= nn; i++)
4608 		nvme_scan_ns(ctrl, i);
4609 
4610 	nvme_remove_nsid_range(ctrl, nn, UINT_MAX);
4611 }
4612 
4613 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
4614 {
4615 	size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
4616 	__le32 *log;
4617 	int error;
4618 
4619 	log = kzalloc(log_size, GFP_KERNEL);
4620 	if (!log)
4621 		return;
4622 
4623 	/*
4624 	 * We need to read the log to clear the AEN, but we don't want to rely
4625 	 * on it for the changed namespace information as userspace could have
4626 	 * raced with us in reading the log page, which could cause us to miss
4627 	 * updates.
4628 	 */
4629 	error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
4630 			NVME_CSI_NVM, log, log_size, 0);
4631 	if (error)
4632 		dev_warn(ctrl->device,
4633 			"reading changed ns log failed: %d\n", error);
4634 
4635 	kfree(log);
4636 }
4637 
4638 static void nvme_scan_work(struct work_struct *work)
4639 {
4640 	struct nvme_ctrl *ctrl =
4641 		container_of(work, struct nvme_ctrl, scan_work);
4642 	int ret;
4643 
4644 	/* No tagset on a live ctrl means IO queues could not created */
4645 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE || !ctrl->tagset)
4646 		return;
4647 
4648 	/*
4649 	 * Identify controller limits can change at controller reset due to
4650 	 * new firmware download, even though it is not common we cannot ignore
4651 	 * such scenario. Controller's non-mdts limits are reported in the unit
4652 	 * of logical blocks that is dependent on the format of attached
4653 	 * namespace. Hence re-read the limits at the time of ns allocation.
4654 	 */
4655 	ret = nvme_init_non_mdts_limits(ctrl);
4656 	if (ret < 0) {
4657 		dev_warn(ctrl->device,
4658 			"reading non-mdts-limits failed: %d\n", ret);
4659 		return;
4660 	}
4661 
4662 	if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
4663 		dev_info(ctrl->device, "rescanning namespaces.\n");
4664 		nvme_clear_changed_ns_log(ctrl);
4665 	}
4666 
4667 	mutex_lock(&ctrl->scan_lock);
4668 	if (!nvme_id_cns_ok(ctrl, NVME_ID_CNS_NS_ACTIVE_LIST)) {
4669 		nvme_scan_ns_sequential(ctrl);
4670 	} else {
4671 		/*
4672 		 * Fall back to sequential scan if DNR is set to handle broken
4673 		 * devices which should support Identify NS List (as per the VS
4674 		 * they report) but don't actually support it.
4675 		 */
4676 		ret = nvme_scan_ns_list(ctrl);
4677 		if (ret > 0 && ret & NVME_STATUS_DNR)
4678 			nvme_scan_ns_sequential(ctrl);
4679 	}
4680 	mutex_unlock(&ctrl->scan_lock);
4681 
4682 	/* Requeue if we have missed AENs */
4683 	if (test_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events))
4684 		nvme_queue_scan(ctrl);
4685 #ifdef CONFIG_NVME_MULTIPATH
4686 	else if (ctrl->ana_log_buf)
4687 		/* Re-read the ANA log page to not miss updates */
4688 		queue_work(nvme_wq, &ctrl->ana_work);
4689 #endif
4690 }
4691 
4692 /*
4693  * This function iterates the namespace list unlocked to allow recovery from
4694  * controller failure. It is up to the caller to ensure the namespace list is
4695  * not modified by scan work while this function is executing.
4696  */
4697 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
4698 {
4699 	struct nvme_ns *ns, *next;
4700 	LIST_HEAD(ns_list);
4701 
4702 	/*
4703 	 * make sure to requeue I/O to all namespaces as these
4704 	 * might result from the scan itself and must complete
4705 	 * for the scan_work to make progress
4706 	 */
4707 	nvme_mpath_clear_ctrl_paths(ctrl);
4708 
4709 	/*
4710 	 * Unquiesce io queues so any pending IO won't hang, especially
4711 	 * those submitted from scan work
4712 	 */
4713 	nvme_unquiesce_io_queues(ctrl);
4714 
4715 	/* prevent racing with ns scanning */
4716 	flush_work(&ctrl->scan_work);
4717 
4718 	/*
4719 	 * The dead states indicates the controller was not gracefully
4720 	 * disconnected. In that case, we won't be able to flush any data while
4721 	 * removing the namespaces' disks; fail all the queues now to avoid
4722 	 * potentially having to clean up the failed sync later.
4723 	 */
4724 	if (nvme_ctrl_state(ctrl) == NVME_CTRL_DEAD)
4725 		nvme_mark_namespaces_dead(ctrl);
4726 
4727 	/* this is a no-op when called from the controller reset handler */
4728 	nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4729 
4730 	mutex_lock(&ctrl->namespaces_lock);
4731 	list_splice_init_rcu(&ctrl->namespaces, &ns_list, synchronize_rcu);
4732 	mutex_unlock(&ctrl->namespaces_lock);
4733 	synchronize_srcu(&ctrl->srcu);
4734 
4735 	list_for_each_entry_safe(ns, next, &ns_list, list)
4736 		nvme_ns_remove(ns);
4737 }
4738 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4739 
4740 static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env)
4741 {
4742 	const struct nvme_ctrl *ctrl =
4743 		container_of(dev, struct nvme_ctrl, ctrl_device);
4744 	struct nvmf_ctrl_options *opts = ctrl->opts;
4745 	int ret;
4746 
4747 	ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4748 	if (ret)
4749 		return ret;
4750 
4751 	if (opts) {
4752 		ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4753 		if (ret)
4754 			return ret;
4755 
4756 		ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4757 				opts->trsvcid ?: "none");
4758 		if (ret)
4759 			return ret;
4760 
4761 		ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4762 				opts->host_traddr ?: "none");
4763 		if (ret)
4764 			return ret;
4765 
4766 		ret = add_uevent_var(env, "NVME_HOST_IFACE=%s",
4767 				opts->host_iface ?: "none");
4768 	}
4769 	return ret;
4770 }
4771 
4772 static void nvme_change_uevent(struct nvme_ctrl *ctrl, char *envdata)
4773 {
4774 	char *envp[2] = { envdata, NULL };
4775 
4776 	kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4777 }
4778 
4779 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4780 {
4781 	char *envp[2] = { NULL, NULL };
4782 	u32 aen_result = ctrl->aen_result;
4783 
4784 	ctrl->aen_result = 0;
4785 	if (!aen_result)
4786 		return;
4787 
4788 	envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4789 	if (!envp[0])
4790 		return;
4791 	kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4792 	kfree(envp[0]);
4793 }
4794 
4795 static void nvme_async_event_work(struct work_struct *work)
4796 {
4797 	struct nvme_ctrl *ctrl =
4798 		container_of(work, struct nvme_ctrl, async_event_work);
4799 
4800 	nvme_aen_uevent(ctrl);
4801 
4802 	/*
4803 	 * The transport drivers must guarantee AER submission here is safe by
4804 	 * flushing ctrl async_event_work after changing the controller state
4805 	 * from LIVE and before freeing the admin queue.
4806 	*/
4807 	if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
4808 		ctrl->ops->submit_async_event(ctrl);
4809 }
4810 
4811 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4812 {
4813 
4814 	u32 csts;
4815 
4816 	if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4817 		return false;
4818 
4819 	if (csts == ~0)
4820 		return false;
4821 
4822 	return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4823 }
4824 
4825 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4826 {
4827 	struct nvme_fw_slot_info_log *log;
4828 	u8 next_fw_slot, cur_fw_slot;
4829 
4830 	log = kmalloc_obj(*log);
4831 	if (!log)
4832 		return;
4833 
4834 	if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4835 			 log, sizeof(*log), 0)) {
4836 		dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4837 		goto out_free_log;
4838 	}
4839 
4840 	cur_fw_slot = log->afi & 0x7;
4841 	next_fw_slot = (log->afi & 0x70) >> 4;
4842 	if (!cur_fw_slot || (next_fw_slot && (cur_fw_slot != next_fw_slot))) {
4843 		dev_info(ctrl->device,
4844 			 "Firmware is activated after next Controller Level Reset\n");
4845 		goto out_free_log;
4846 	}
4847 
4848 	memcpy(ctrl->subsys->firmware_rev, &log->frs[cur_fw_slot - 1],
4849 		sizeof(ctrl->subsys->firmware_rev));
4850 
4851 out_free_log:
4852 	kfree(log);
4853 }
4854 
4855 static void nvme_fw_act_work(struct work_struct *work)
4856 {
4857 	struct nvme_ctrl *ctrl = container_of(work,
4858 				struct nvme_ctrl, fw_act_work);
4859 	unsigned long fw_act_timeout;
4860 
4861 	nvme_auth_stop(ctrl);
4862 
4863 	if (ctrl->mtfa)
4864 		fw_act_timeout = jiffies + msecs_to_jiffies(ctrl->mtfa * 100);
4865 	else
4866 		fw_act_timeout = jiffies + secs_to_jiffies(admin_timeout);
4867 
4868 	nvme_quiesce_io_queues(ctrl);
4869 	while (nvme_ctrl_pp_status(ctrl)) {
4870 		if (time_after(jiffies, fw_act_timeout)) {
4871 			dev_warn(ctrl->device,
4872 				"Fw activation timeout, reset controller\n");
4873 			nvme_try_sched_reset(ctrl);
4874 			return;
4875 		}
4876 		msleep(100);
4877 	}
4878 
4879 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING) ||
4880 	    !nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4881 		return;
4882 
4883 	nvme_unquiesce_io_queues(ctrl);
4884 	/* read FW slot information to clear the AER */
4885 	nvme_get_fw_slot_info(ctrl);
4886 
4887 	queue_work(nvme_wq, &ctrl->async_event_work);
4888 }
4889 
4890 static u32 nvme_aer_type(u32 result)
4891 {
4892 	return result & 0x7;
4893 }
4894 
4895 static u32 nvme_aer_subtype(u32 result)
4896 {
4897 	return (result & 0xff00) >> 8;
4898 }
4899 
4900 static bool nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4901 {
4902 	u32 aer_notice_type = nvme_aer_subtype(result);
4903 	bool requeue = true;
4904 
4905 	switch (aer_notice_type) {
4906 	case NVME_AER_NOTICE_NS_CHANGED:
4907 		set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4908 		nvme_queue_scan(ctrl);
4909 		break;
4910 	case NVME_AER_NOTICE_FW_ACT_STARTING:
4911 		/*
4912 		 * We are (ab)using the RESETTING state to prevent subsequent
4913 		 * recovery actions from interfering with the controller's
4914 		 * firmware activation.
4915 		 */
4916 		if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) {
4917 			requeue = false;
4918 			queue_work(nvme_wq, &ctrl->fw_act_work);
4919 		}
4920 		break;
4921 #ifdef CONFIG_NVME_MULTIPATH
4922 	case NVME_AER_NOTICE_ANA:
4923 		if (!ctrl->ana_log_buf)
4924 			break;
4925 		queue_work(nvme_wq, &ctrl->ana_work);
4926 		break;
4927 #endif
4928 	case NVME_AER_NOTICE_DISC_CHANGED:
4929 		ctrl->aen_result = result;
4930 		break;
4931 	default:
4932 		dev_warn(ctrl->device, "async event result %08x\n", result);
4933 	}
4934 	return requeue;
4935 }
4936 
4937 static void nvme_handle_aer_persistent_error(struct nvme_ctrl *ctrl)
4938 {
4939 	dev_warn(ctrl->device,
4940 		"resetting controller due to persistent internal error\n");
4941 	nvme_reset_ctrl(ctrl);
4942 }
4943 
4944 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4945 		volatile union nvme_result *res)
4946 {
4947 	u32 result = le32_to_cpu(res->u32);
4948 	u32 aer_type = nvme_aer_type(result);
4949 	u32 aer_subtype = nvme_aer_subtype(result);
4950 	bool requeue = true;
4951 
4952 	if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4953 		return;
4954 
4955 	trace_nvme_async_event(ctrl, result);
4956 	switch (aer_type) {
4957 	case NVME_AER_NOTICE:
4958 		requeue = nvme_handle_aen_notice(ctrl, result);
4959 		break;
4960 	case NVME_AER_ERROR:
4961 		/*
4962 		 * For a persistent internal error, don't run async_event_work
4963 		 * to submit a new AER. The controller reset will do it.
4964 		 */
4965 		if (aer_subtype == NVME_AER_ERROR_PERSIST_INT_ERR) {
4966 			nvme_handle_aer_persistent_error(ctrl);
4967 			return;
4968 		}
4969 		fallthrough;
4970 	case NVME_AER_SMART:
4971 	case NVME_AER_CSS:
4972 	case NVME_AER_VS:
4973 		ctrl->aen_result = result;
4974 		break;
4975 	default:
4976 		break;
4977 	}
4978 
4979 	if (requeue)
4980 		queue_work(nvme_wq, &ctrl->async_event_work);
4981 }
4982 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4983 
4984 int nvme_alloc_admin_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
4985 		const struct blk_mq_ops *ops, unsigned int cmd_size)
4986 {
4987 	int ret;
4988 
4989 	memset(set, 0, sizeof(*set));
4990 	set->ops = ops;
4991 	set->queue_depth = NVME_AQ_MQ_TAG_DEPTH;
4992 	if (ctrl->ops->flags & NVME_F_FABRICS)
4993 		/* Reserved for fabric connect and keep alive */
4994 		set->reserved_tags = 2;
4995 	set->numa_node = ctrl->numa_node;
4996 	if (ctrl->ops->flags & NVME_F_BLOCKING)
4997 		set->flags |= BLK_MQ_F_BLOCKING;
4998 	set->cmd_size = cmd_size;
4999 	set->driver_data = ctrl;
5000 	set->nr_hw_queues = 1;
5001 	set->timeout = NVME_ADMIN_TIMEOUT;
5002 	ret = blk_mq_alloc_tag_set(set);
5003 	if (ret)
5004 		return ret;
5005 
5006 	WARN_ON_ONCE(ctrl->admin_q);
5007 
5008 	ctrl->admin_q = blk_mq_alloc_queue(set, NULL, NULL);
5009 	if (IS_ERR(ctrl->admin_q)) {
5010 		ret = PTR_ERR(ctrl->admin_q);
5011 		goto out_free_tagset;
5012 	}
5013 
5014 	if (ctrl->ops->flags & NVME_F_FABRICS) {
5015 		ctrl->fabrics_q = blk_mq_alloc_queue(set, NULL, NULL);
5016 		if (IS_ERR(ctrl->fabrics_q)) {
5017 			ret = PTR_ERR(ctrl->fabrics_q);
5018 			goto out_cleanup_admin_q;
5019 		}
5020 	}
5021 
5022 	ctrl->admin_tagset = set;
5023 	return 0;
5024 
5025 out_cleanup_admin_q:
5026 	blk_mq_destroy_queue(ctrl->admin_q);
5027 	blk_put_queue(ctrl->admin_q);
5028 out_free_tagset:
5029 	blk_mq_free_tag_set(set);
5030 	ctrl->admin_q = NULL;
5031 	ctrl->fabrics_q = NULL;
5032 	return ret;
5033 }
5034 EXPORT_SYMBOL_GPL(nvme_alloc_admin_tag_set);
5035 
5036 void nvme_remove_admin_tag_set(struct nvme_ctrl *ctrl)
5037 {
5038 	/*
5039 	 * As we're about to destroy the queue and free tagset
5040 	 * we can not have keep-alive work running.
5041 	 */
5042 	nvme_stop_keep_alive(ctrl);
5043 	blk_mq_destroy_queue(ctrl->admin_q);
5044 	if (ctrl->fabrics_q)
5045 		blk_mq_destroy_queue(ctrl->fabrics_q);
5046 	blk_mq_free_tag_set(ctrl->admin_tagset);
5047 }
5048 EXPORT_SYMBOL_GPL(nvme_remove_admin_tag_set);
5049 
5050 int nvme_alloc_io_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
5051 		const struct blk_mq_ops *ops, unsigned int nr_maps,
5052 		unsigned int cmd_size)
5053 {
5054 	int ret;
5055 
5056 	memset(set, 0, sizeof(*set));
5057 	set->ops = ops;
5058 	set->queue_depth = min_t(unsigned, ctrl->sqsize, BLK_MQ_MAX_DEPTH - 1);
5059 	/*
5060 	 * Some Apple controllers requires tags to be unique across admin and
5061 	 * the (only) I/O queue, so reserve the first 32 tags of the I/O queue.
5062 	 */
5063 	if (ctrl->quirks & NVME_QUIRK_SHARED_TAGS)
5064 		set->reserved_tags = NVME_AQ_DEPTH;
5065 	else if (ctrl->ops->flags & NVME_F_FABRICS)
5066 		/* Reserved for fabric connect */
5067 		set->reserved_tags = 1;
5068 	set->numa_node = ctrl->numa_node;
5069 	if (ctrl->ops->flags & NVME_F_BLOCKING)
5070 		set->flags |= BLK_MQ_F_BLOCKING;
5071 	set->cmd_size = cmd_size;
5072 	set->driver_data = ctrl;
5073 	set->nr_hw_queues = ctrl->queue_count - 1;
5074 	set->timeout = NVME_IO_TIMEOUT;
5075 	set->nr_maps = nr_maps;
5076 	ret = blk_mq_alloc_tag_set(set);
5077 	if (ret)
5078 		return ret;
5079 
5080 	if (ctrl->ops->flags & NVME_F_FABRICS) {
5081 		struct queue_limits lim = {
5082 			.features	= BLK_FEAT_SKIP_TAGSET_QUIESCE,
5083 		};
5084 
5085 		ctrl->connect_q = blk_mq_alloc_queue(set, &lim, NULL);
5086         	if (IS_ERR(ctrl->connect_q)) {
5087 			ret = PTR_ERR(ctrl->connect_q);
5088 			goto out_free_tag_set;
5089 		}
5090 	}
5091 
5092 	ctrl->tagset = set;
5093 	return 0;
5094 
5095 out_free_tag_set:
5096 	blk_mq_free_tag_set(set);
5097 	ctrl->connect_q = NULL;
5098 	return ret;
5099 }
5100 EXPORT_SYMBOL_GPL(nvme_alloc_io_tag_set);
5101 
5102 void nvme_remove_io_tag_set(struct nvme_ctrl *ctrl)
5103 {
5104 	if (ctrl->ops->flags & NVME_F_FABRICS) {
5105 		blk_mq_destroy_queue(ctrl->connect_q);
5106 		blk_put_queue(ctrl->connect_q);
5107 	}
5108 	blk_mq_free_tag_set(ctrl->tagset);
5109 }
5110 EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set);
5111 
5112 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
5113 {
5114 	nvme_mpath_stop(ctrl);
5115 	nvme_auth_stop(ctrl);
5116 	nvme_stop_failfast_work(ctrl);
5117 	flush_work(&ctrl->async_event_work);
5118 	cancel_work_sync(&ctrl->fw_act_work);
5119 	if (ctrl->ops->stop_ctrl)
5120 		ctrl->ops->stop_ctrl(ctrl);
5121 }
5122 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
5123 
5124 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
5125 {
5126 	nvme_enable_aen(ctrl);
5127 
5128 	/*
5129 	 * persistent discovery controllers need to send indication to userspace
5130 	 * to re-read the discovery log page to learn about possible changes
5131 	 * that were missed. We identify persistent discovery controllers by
5132 	 * checking that they started once before, hence are reconnecting back.
5133 	 */
5134 	if (test_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags) &&
5135 	    nvme_discovery_ctrl(ctrl)) {
5136 		if (!ctrl->kato) {
5137 			nvme_stop_keep_alive(ctrl);
5138 			ctrl->kato = NVME_DEFAULT_KATO;
5139 			nvme_start_keep_alive(ctrl);
5140 		}
5141 		nvme_change_uevent(ctrl, "NVME_EVENT=rediscover");
5142 	}
5143 
5144 	if (ctrl->queue_count > 1) {
5145 		nvme_queue_scan(ctrl);
5146 		nvme_unquiesce_io_queues(ctrl);
5147 		nvme_mpath_update(ctrl);
5148 	}
5149 
5150 	set_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags);
5151 	nvme_change_uevent(ctrl, "NVME_EVENT=connected");
5152 }
5153 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
5154 
5155 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
5156 {
5157 	nvme_stop_keep_alive(ctrl);
5158 	nvme_hwmon_exit(ctrl);
5159 	nvme_fault_inject_fini(&ctrl->fault_inject);
5160 	dev_pm_qos_hide_latency_tolerance(ctrl->device);
5161 	cdev_device_del(&ctrl->cdev, ctrl->device);
5162 	nvme_put_ctrl(ctrl);
5163 }
5164 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
5165 
5166 static void nvme_free_ctrl(struct device *dev)
5167 {
5168 	struct nvme_ctrl *ctrl =
5169 		container_of(dev, struct nvme_ctrl, ctrl_device);
5170 	struct nvme_subsystem *subsys = ctrl->subsys;
5171 
5172 	if (ctrl->admin_q)
5173 		blk_put_queue(ctrl->admin_q);
5174 	if (ctrl->fabrics_q)
5175 		blk_put_queue(ctrl->fabrics_q);
5176 	if (!subsys || ctrl->instance != subsys->instance)
5177 		ida_free(&nvme_instance_ida, ctrl->instance);
5178 	nvme_mpath_uninit(ctrl);
5179 	cleanup_srcu_struct(&ctrl->srcu);
5180 	nvme_auth_stop(ctrl);
5181 	nvme_auth_free(ctrl);
5182 	__free_page(ctrl->discard_page);
5183 	free_opal_dev(ctrl->opal_dev);
5184 
5185 	if (subsys) {
5186 		mutex_lock(&nvme_subsystems_lock);
5187 		list_del(&ctrl->subsys_entry);
5188 		sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
5189 		mutex_unlock(&nvme_subsystems_lock);
5190 	}
5191 
5192 	ctrl->ops->free_ctrl(ctrl);
5193 
5194 	if (subsys)
5195 		nvme_put_subsystem(subsys);
5196 }
5197 
5198 /*
5199  * Initialize a NVMe controller structures.  This needs to be called during
5200  * earliest initialization so that we have the initialized structured around
5201  * during probing.
5202  *
5203  * On success, the caller must use the nvme_put_ctrl() to release this when
5204  * needed, which also invokes the ops->free_ctrl() callback.
5205  */
5206 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
5207 		const struct nvme_ctrl_ops *ops, unsigned long quirks)
5208 {
5209 	int ret;
5210 
5211 	WRITE_ONCE(ctrl->state, NVME_CTRL_NEW);
5212 	ctrl->passthru_err_log_enabled = false;
5213 	clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
5214 	spin_lock_init(&ctrl->lock);
5215 	mutex_init(&ctrl->namespaces_lock);
5216 
5217 	ret = init_srcu_struct(&ctrl->srcu);
5218 	if (ret)
5219 		return ret;
5220 
5221 	mutex_init(&ctrl->scan_lock);
5222 	INIT_LIST_HEAD(&ctrl->namespaces);
5223 	ctrl->dev = dev;
5224 	ctrl->ops = ops;
5225 	ctrl->quirks = quirks;
5226 	ctrl->numa_node = NUMA_NO_NODE;
5227 	INIT_WORK(&ctrl->scan_work, nvme_scan_work);
5228 	INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
5229 	INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
5230 	INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
5231 	init_waitqueue_head(&ctrl->state_wq);
5232 
5233 	INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
5234 	INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
5235 	memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
5236 	ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
5237 	ctrl->ka_last_check_time = jiffies;
5238 	ctrl->admin_timeout = NVME_ADMIN_TIMEOUT;
5239 	ctrl->io_timeout = NVME_IO_TIMEOUT;
5240 
5241 	BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
5242 			PAGE_SIZE);
5243 	ctrl->discard_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
5244 	if (!ctrl->discard_page) {
5245 		ret = -ENOMEM;
5246 		goto out;
5247 	}
5248 
5249 	ret = ida_alloc(&nvme_instance_ida, GFP_KERNEL);
5250 	if (ret < 0)
5251 		goto out;
5252 	ctrl->instance = ret;
5253 
5254 	ret = nvme_auth_init_ctrl(ctrl);
5255 	if (ret)
5256 		goto out_release_instance;
5257 
5258 	nvme_mpath_init_ctrl(ctrl);
5259 
5260 	device_initialize(&ctrl->ctrl_device);
5261 	ctrl->device = &ctrl->ctrl_device;
5262 	ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
5263 			ctrl->instance);
5264 	ctrl->device->class = &nvme_class;
5265 	ctrl->device->parent = ctrl->dev;
5266 	if (ops->dev_attr_groups)
5267 		ctrl->device->groups = ops->dev_attr_groups;
5268 	else
5269 		ctrl->device->groups = nvme_dev_attr_groups;
5270 	ctrl->device->release = nvme_free_ctrl;
5271 	dev_set_drvdata(ctrl->device, ctrl);
5272 
5273 	return ret;
5274 
5275 out_release_instance:
5276 	ida_free(&nvme_instance_ida, ctrl->instance);
5277 out:
5278 	if (ctrl->discard_page)
5279 		__free_page(ctrl->discard_page);
5280 	cleanup_srcu_struct(&ctrl->srcu);
5281 	return ret;
5282 }
5283 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
5284 
5285 /*
5286  * On success, returns with an elevated controller reference and caller must
5287  * use nvme_uninit_ctrl() to properly free resources associated with the ctrl.
5288  */
5289 int nvme_add_ctrl(struct nvme_ctrl *ctrl)
5290 {
5291 	int ret;
5292 
5293 	ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
5294 	if (ret)
5295 		return ret;
5296 
5297 	cdev_init(&ctrl->cdev, &nvme_dev_fops);
5298 	ctrl->cdev.owner = ctrl->ops->module;
5299 	ret = cdev_device_add(&ctrl->cdev, ctrl->device);
5300 	if (ret)
5301 		return ret;
5302 
5303 	/*
5304 	 * Initialize latency tolerance controls.  The sysfs files won't
5305 	 * be visible to userspace unless the device actually supports APST.
5306 	 */
5307 	ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
5308 	dev_pm_qos_update_user_latency_tolerance(ctrl->device,
5309 		min(default_ps_max_latency_us, (unsigned long)S32_MAX));
5310 
5311 	nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
5312 	nvme_get_ctrl(ctrl);
5313 
5314 	return 0;
5315 }
5316 EXPORT_SYMBOL_GPL(nvme_add_ctrl);
5317 
5318 /* let I/O to all namespaces fail in preparation for surprise removal */
5319 void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl)
5320 {
5321 	struct nvme_ns *ns;
5322 	int srcu_idx;
5323 
5324 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5325 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5326 				 srcu_read_lock_held(&ctrl->srcu))
5327 		blk_mark_disk_dead(ns->disk);
5328 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5329 }
5330 EXPORT_SYMBOL_GPL(nvme_mark_namespaces_dead);
5331 
5332 void nvme_unfreeze(struct nvme_ctrl *ctrl)
5333 {
5334 	struct nvme_ns *ns;
5335 	int srcu_idx;
5336 
5337 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5338 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5339 				 srcu_read_lock_held(&ctrl->srcu))
5340 		blk_mq_unfreeze_queue_non_owner(ns->queue);
5341 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5342 	clear_bit(NVME_CTRL_FROZEN, &ctrl->flags);
5343 }
5344 EXPORT_SYMBOL_GPL(nvme_unfreeze);
5345 
5346 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl)
5347 {
5348 	long timeout = ctrl->io_timeout;
5349 	struct nvme_ns *ns;
5350 	int srcu_idx;
5351 
5352 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5353 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5354 				 srcu_read_lock_held(&ctrl->srcu)) {
5355 		timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
5356 		if (timeout <= 0)
5357 			break;
5358 	}
5359 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5360 	return timeout;
5361 }
5362 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
5363 
5364 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
5365 {
5366 	struct nvme_ns *ns;
5367 	int srcu_idx;
5368 
5369 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5370 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5371 				 srcu_read_lock_held(&ctrl->srcu))
5372 		blk_mq_freeze_queue_wait(ns->queue);
5373 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5374 }
5375 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
5376 
5377 void nvme_start_freeze(struct nvme_ctrl *ctrl)
5378 {
5379 	struct nvme_ns *ns;
5380 	int srcu_idx;
5381 
5382 	set_bit(NVME_CTRL_FROZEN, &ctrl->flags);
5383 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5384 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5385 				 srcu_read_lock_held(&ctrl->srcu))
5386 		/*
5387 		 * Typical non_owner use case is from pci driver, in which
5388 		 * start_freeze is called from timeout work function, but
5389 		 * unfreeze is done in reset work context
5390 		 */
5391 		blk_freeze_queue_start_non_owner(ns->queue);
5392 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5393 }
5394 EXPORT_SYMBOL_GPL(nvme_start_freeze);
5395 
5396 void nvme_quiesce_io_queues(struct nvme_ctrl *ctrl)
5397 {
5398 	if (!ctrl->tagset)
5399 		return;
5400 	if (!test_and_set_bit(NVME_CTRL_STOPPED, &ctrl->flags))
5401 		blk_mq_quiesce_tagset(ctrl->tagset);
5402 	else
5403 		blk_mq_wait_quiesce_done(ctrl->tagset);
5404 }
5405 EXPORT_SYMBOL_GPL(nvme_quiesce_io_queues);
5406 
5407 void nvme_unquiesce_io_queues(struct nvme_ctrl *ctrl)
5408 {
5409 	if (!ctrl->tagset)
5410 		return;
5411 	if (test_and_clear_bit(NVME_CTRL_STOPPED, &ctrl->flags))
5412 		blk_mq_unquiesce_tagset(ctrl->tagset);
5413 }
5414 EXPORT_SYMBOL_GPL(nvme_unquiesce_io_queues);
5415 
5416 void nvme_quiesce_admin_queue(struct nvme_ctrl *ctrl)
5417 {
5418 	if (!test_and_set_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
5419 		blk_mq_quiesce_queue(ctrl->admin_q);
5420 	else
5421 		blk_mq_wait_quiesce_done(ctrl->admin_q->tag_set);
5422 }
5423 EXPORT_SYMBOL_GPL(nvme_quiesce_admin_queue);
5424 
5425 void nvme_unquiesce_admin_queue(struct nvme_ctrl *ctrl)
5426 {
5427 	if (test_and_clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
5428 		blk_mq_unquiesce_queue(ctrl->admin_q);
5429 }
5430 EXPORT_SYMBOL_GPL(nvme_unquiesce_admin_queue);
5431 
5432 void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
5433 {
5434 	struct nvme_ns *ns;
5435 	int srcu_idx;
5436 
5437 	srcu_idx = srcu_read_lock(&ctrl->srcu);
5438 	list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
5439 				 srcu_read_lock_held(&ctrl->srcu))
5440 		blk_sync_queue(ns->queue);
5441 	srcu_read_unlock(&ctrl->srcu, srcu_idx);
5442 }
5443 EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
5444 
5445 void nvme_sync_queues(struct nvme_ctrl *ctrl)
5446 {
5447 	nvme_sync_io_queues(ctrl);
5448 	if (ctrl->admin_q)
5449 		blk_sync_queue(ctrl->admin_q);
5450 }
5451 EXPORT_SYMBOL_GPL(nvme_sync_queues);
5452 
5453 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
5454 {
5455 	if (file->f_op != &nvme_dev_fops)
5456 		return NULL;
5457 	return file->private_data;
5458 }
5459 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, "NVME_TARGET_PASSTHRU");
5460 
5461 /*
5462  * Check we didn't inadvertently grow the command structure sizes:
5463  */
5464 static inline void _nvme_check_size(void)
5465 {
5466 	BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
5467 	BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
5468 	BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
5469 	BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
5470 	BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
5471 	BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
5472 	BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
5473 	BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
5474 	BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
5475 	BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
5476 	BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
5477 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
5478 	BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
5479 	BUILD_BUG_ON(sizeof(struct nvme_id_ns_cs_indep) !=
5480 			NVME_IDENTIFY_DATA_SIZE);
5481 	BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
5482 	BUILD_BUG_ON(sizeof(struct nvme_id_ns_nvm) != NVME_IDENTIFY_DATA_SIZE);
5483 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
5484 	BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
5485 	BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
5486 	BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
5487 	BUILD_BUG_ON(sizeof(struct nvme_endurance_group_log) != 512);
5488 	BUILD_BUG_ON(sizeof(struct nvme_rotational_media_log) != 512);
5489 	BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
5490 	BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
5491 	BUILD_BUG_ON(sizeof(struct nvme_feat_host_behavior) != 512);
5492 }
5493 
5494 
5495 static int __init nvme_core_init(void)
5496 {
5497 	unsigned int wq_flags = WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS;
5498 	int result = -ENOMEM;
5499 
5500 	_nvme_check_size();
5501 
5502 	nvme_wq = alloc_workqueue("nvme-wq", wq_flags, 0);
5503 	if (!nvme_wq)
5504 		goto out;
5505 
5506 	nvme_reset_wq = alloc_workqueue("nvme-reset-wq", wq_flags, 0);
5507 	if (!nvme_reset_wq)
5508 		goto destroy_wq;
5509 
5510 	nvme_delete_wq = alloc_workqueue("nvme-delete-wq", wq_flags, 0);
5511 	if (!nvme_delete_wq)
5512 		goto destroy_reset_wq;
5513 
5514 	result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
5515 			NVME_MINORS, "nvme");
5516 	if (result < 0)
5517 		goto destroy_delete_wq;
5518 
5519 	result = class_register(&nvme_class);
5520 	if (result)
5521 		goto unregister_chrdev;
5522 
5523 	result = class_register(&nvme_subsys_class);
5524 	if (result)
5525 		goto destroy_class;
5526 
5527 	result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
5528 				     "nvme-generic");
5529 	if (result < 0)
5530 		goto destroy_subsys_class;
5531 
5532 	result = class_register(&nvme_ns_chr_class);
5533 	if (result)
5534 		goto unregister_generic_ns;
5535 
5536 	result = nvme_init_auth();
5537 	if (result)
5538 		goto destroy_ns_chr;
5539 	return 0;
5540 
5541 destroy_ns_chr:
5542 	class_unregister(&nvme_ns_chr_class);
5543 unregister_generic_ns:
5544 	unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
5545 destroy_subsys_class:
5546 	class_unregister(&nvme_subsys_class);
5547 destroy_class:
5548 	class_unregister(&nvme_class);
5549 unregister_chrdev:
5550 	unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
5551 destroy_delete_wq:
5552 	destroy_workqueue(nvme_delete_wq);
5553 destroy_reset_wq:
5554 	destroy_workqueue(nvme_reset_wq);
5555 destroy_wq:
5556 	destroy_workqueue(nvme_wq);
5557 out:
5558 	return result;
5559 }
5560 
5561 static void __exit nvme_core_exit(void)
5562 {
5563 	nvme_exit_auth();
5564 	class_unregister(&nvme_ns_chr_class);
5565 	class_unregister(&nvme_subsys_class);
5566 	class_unregister(&nvme_class);
5567 	unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
5568 	unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
5569 	destroy_workqueue(nvme_delete_wq);
5570 	destroy_workqueue(nvme_reset_wq);
5571 	destroy_workqueue(nvme_wq);
5572 	ida_destroy(&nvme_ns_chr_minor_ida);
5573 	ida_destroy(&nvme_instance_ida);
5574 }
5575 
5576 MODULE_LICENSE("GPL");
5577 MODULE_VERSION("1.0");
5578 MODULE_DESCRIPTION("NVMe host core framework");
5579 module_init(nvme_core_init);
5580 module_exit(nvme_core_exit);
5581