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