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