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