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