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