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