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