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