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