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