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