xref: /openbmc/linux/drivers/nvme/host/core.c (revision 711aab1d)
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14 
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/pr.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <linux/pm_qos.h>
30 #include <asm/unaligned.h>
31 
32 #include "nvme.h"
33 #include "fabrics.h"
34 
35 #define NVME_MINORS		(1U << MINORBITS)
36 
37 unsigned char admin_timeout = 60;
38 module_param(admin_timeout, byte, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
41 
42 unsigned char nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
46 
47 static unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
50 
51 static u8 nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, byte, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
54 
55 static int nvme_char_major;
56 module_param(nvme_char_major, int, 0);
57 
58 static unsigned long default_ps_max_latency_us = 100000;
59 module_param(default_ps_max_latency_us, ulong, 0644);
60 MODULE_PARM_DESC(default_ps_max_latency_us,
61 		 "max power saving latency for new devices; use PM QOS to change per device");
62 
63 static bool force_apst;
64 module_param(force_apst, bool, 0644);
65 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
66 
67 static bool streams;
68 module_param(streams, bool, 0644);
69 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
70 
71 struct workqueue_struct *nvme_wq;
72 EXPORT_SYMBOL_GPL(nvme_wq);
73 
74 static LIST_HEAD(nvme_ctrl_list);
75 static DEFINE_SPINLOCK(dev_list_lock);
76 
77 static struct class *nvme_class;
78 
79 static __le32 nvme_get_log_dw10(u8 lid, size_t size)
80 {
81 	return cpu_to_le32((((size / 4) - 1) << 16) | lid);
82 }
83 
84 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
85 {
86 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
87 		return -EBUSY;
88 	if (!queue_work(nvme_wq, &ctrl->reset_work))
89 		return -EBUSY;
90 	return 0;
91 }
92 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
93 
94 static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
95 {
96 	int ret;
97 
98 	ret = nvme_reset_ctrl(ctrl);
99 	if (!ret)
100 		flush_work(&ctrl->reset_work);
101 	return ret;
102 }
103 
104 static blk_status_t nvme_error_status(struct request *req)
105 {
106 	switch (nvme_req(req)->status & 0x7ff) {
107 	case NVME_SC_SUCCESS:
108 		return BLK_STS_OK;
109 	case NVME_SC_CAP_EXCEEDED:
110 		return BLK_STS_NOSPC;
111 	case NVME_SC_ONCS_NOT_SUPPORTED:
112 		return BLK_STS_NOTSUPP;
113 	case NVME_SC_WRITE_FAULT:
114 	case NVME_SC_READ_ERROR:
115 	case NVME_SC_UNWRITTEN_BLOCK:
116 	case NVME_SC_ACCESS_DENIED:
117 	case NVME_SC_READ_ONLY:
118 		return BLK_STS_MEDIUM;
119 	case NVME_SC_GUARD_CHECK:
120 	case NVME_SC_APPTAG_CHECK:
121 	case NVME_SC_REFTAG_CHECK:
122 	case NVME_SC_INVALID_PI:
123 		return BLK_STS_PROTECTION;
124 	case NVME_SC_RESERVATION_CONFLICT:
125 		return BLK_STS_NEXUS;
126 	default:
127 		return BLK_STS_IOERR;
128 	}
129 }
130 
131 static inline bool nvme_req_needs_retry(struct request *req)
132 {
133 	if (blk_noretry_request(req))
134 		return false;
135 	if (nvme_req(req)->status & NVME_SC_DNR)
136 		return false;
137 	if (jiffies - req->start_time >= req->timeout)
138 		return false;
139 	if (nvme_req(req)->retries >= nvme_max_retries)
140 		return false;
141 	return true;
142 }
143 
144 void nvme_complete_rq(struct request *req)
145 {
146 	if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
147 		nvme_req(req)->retries++;
148 		blk_mq_requeue_request(req, true);
149 		return;
150 	}
151 
152 	blk_mq_end_request(req, nvme_error_status(req));
153 }
154 EXPORT_SYMBOL_GPL(nvme_complete_rq);
155 
156 void nvme_cancel_request(struct request *req, void *data, bool reserved)
157 {
158 	int status;
159 
160 	if (!blk_mq_request_started(req))
161 		return;
162 
163 	dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
164 				"Cancelling I/O %d", req->tag);
165 
166 	status = NVME_SC_ABORT_REQ;
167 	if (blk_queue_dying(req->q))
168 		status |= NVME_SC_DNR;
169 	nvme_req(req)->status = status;
170 	blk_mq_complete_request(req);
171 
172 }
173 EXPORT_SYMBOL_GPL(nvme_cancel_request);
174 
175 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
176 		enum nvme_ctrl_state new_state)
177 {
178 	enum nvme_ctrl_state old_state;
179 	unsigned long flags;
180 	bool changed = false;
181 
182 	spin_lock_irqsave(&ctrl->lock, flags);
183 
184 	old_state = ctrl->state;
185 	switch (new_state) {
186 	case NVME_CTRL_LIVE:
187 		switch (old_state) {
188 		case NVME_CTRL_NEW:
189 		case NVME_CTRL_RESETTING:
190 		case NVME_CTRL_RECONNECTING:
191 			changed = true;
192 			/* FALLTHRU */
193 		default:
194 			break;
195 		}
196 		break;
197 	case NVME_CTRL_RESETTING:
198 		switch (old_state) {
199 		case NVME_CTRL_NEW:
200 		case NVME_CTRL_LIVE:
201 			changed = true;
202 			/* FALLTHRU */
203 		default:
204 			break;
205 		}
206 		break;
207 	case NVME_CTRL_RECONNECTING:
208 		switch (old_state) {
209 		case NVME_CTRL_LIVE:
210 			changed = true;
211 			/* FALLTHRU */
212 		default:
213 			break;
214 		}
215 		break;
216 	case NVME_CTRL_DELETING:
217 		switch (old_state) {
218 		case NVME_CTRL_LIVE:
219 		case NVME_CTRL_RESETTING:
220 		case NVME_CTRL_RECONNECTING:
221 			changed = true;
222 			/* FALLTHRU */
223 		default:
224 			break;
225 		}
226 		break;
227 	case NVME_CTRL_DEAD:
228 		switch (old_state) {
229 		case NVME_CTRL_DELETING:
230 			changed = true;
231 			/* FALLTHRU */
232 		default:
233 			break;
234 		}
235 		break;
236 	default:
237 		break;
238 	}
239 
240 	if (changed)
241 		ctrl->state = new_state;
242 
243 	spin_unlock_irqrestore(&ctrl->lock, flags);
244 
245 	return changed;
246 }
247 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
248 
249 static void nvme_free_ns(struct kref *kref)
250 {
251 	struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
252 
253 	if (ns->ndev)
254 		nvme_nvm_unregister(ns);
255 
256 	if (ns->disk) {
257 		spin_lock(&dev_list_lock);
258 		ns->disk->private_data = NULL;
259 		spin_unlock(&dev_list_lock);
260 	}
261 
262 	put_disk(ns->disk);
263 	ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
264 	nvme_put_ctrl(ns->ctrl);
265 	kfree(ns);
266 }
267 
268 static void nvme_put_ns(struct nvme_ns *ns)
269 {
270 	kref_put(&ns->kref, nvme_free_ns);
271 }
272 
273 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
274 {
275 	struct nvme_ns *ns;
276 
277 	spin_lock(&dev_list_lock);
278 	ns = disk->private_data;
279 	if (ns) {
280 		if (!kref_get_unless_zero(&ns->kref))
281 			goto fail;
282 		if (!try_module_get(ns->ctrl->ops->module))
283 			goto fail_put_ns;
284 	}
285 	spin_unlock(&dev_list_lock);
286 
287 	return ns;
288 
289 fail_put_ns:
290 	kref_put(&ns->kref, nvme_free_ns);
291 fail:
292 	spin_unlock(&dev_list_lock);
293 	return NULL;
294 }
295 
296 struct request *nvme_alloc_request(struct request_queue *q,
297 		struct nvme_command *cmd, unsigned int flags, int qid)
298 {
299 	unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
300 	struct request *req;
301 
302 	if (qid == NVME_QID_ANY) {
303 		req = blk_mq_alloc_request(q, op, flags);
304 	} else {
305 		req = blk_mq_alloc_request_hctx(q, op, flags,
306 				qid ? qid - 1 : 0);
307 	}
308 	if (IS_ERR(req))
309 		return req;
310 
311 	req->cmd_flags |= REQ_FAILFAST_DRIVER;
312 	nvme_req(req)->cmd = cmd;
313 
314 	return req;
315 }
316 EXPORT_SYMBOL_GPL(nvme_alloc_request);
317 
318 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
319 {
320 	struct nvme_command c;
321 
322 	memset(&c, 0, sizeof(c));
323 
324 	c.directive.opcode = nvme_admin_directive_send;
325 	c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
326 	c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
327 	c.directive.dtype = NVME_DIR_IDENTIFY;
328 	c.directive.tdtype = NVME_DIR_STREAMS;
329 	c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
330 
331 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
332 }
333 
334 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
335 {
336 	return nvme_toggle_streams(ctrl, false);
337 }
338 
339 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
340 {
341 	return nvme_toggle_streams(ctrl, true);
342 }
343 
344 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
345 				  struct streams_directive_params *s, u32 nsid)
346 {
347 	struct nvme_command c;
348 
349 	memset(&c, 0, sizeof(c));
350 	memset(s, 0, sizeof(*s));
351 
352 	c.directive.opcode = nvme_admin_directive_recv;
353 	c.directive.nsid = cpu_to_le32(nsid);
354 	c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
355 	c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
356 	c.directive.dtype = NVME_DIR_STREAMS;
357 
358 	return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
359 }
360 
361 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
362 {
363 	struct streams_directive_params s;
364 	int ret;
365 
366 	if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
367 		return 0;
368 	if (!streams)
369 		return 0;
370 
371 	ret = nvme_enable_streams(ctrl);
372 	if (ret)
373 		return ret;
374 
375 	ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
376 	if (ret)
377 		return ret;
378 
379 	ctrl->nssa = le16_to_cpu(s.nssa);
380 	if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
381 		dev_info(ctrl->device, "too few streams (%u) available\n",
382 					ctrl->nssa);
383 		nvme_disable_streams(ctrl);
384 		return 0;
385 	}
386 
387 	ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
388 	dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
389 	return 0;
390 }
391 
392 /*
393  * Check if 'req' has a write hint associated with it. If it does, assign
394  * a valid namespace stream to the write.
395  */
396 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
397 				     struct request *req, u16 *control,
398 				     u32 *dsmgmt)
399 {
400 	enum rw_hint streamid = req->write_hint;
401 
402 	if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
403 		streamid = 0;
404 	else {
405 		streamid--;
406 		if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
407 			return;
408 
409 		*control |= NVME_RW_DTYPE_STREAMS;
410 		*dsmgmt |= streamid << 16;
411 	}
412 
413 	if (streamid < ARRAY_SIZE(req->q->write_hints))
414 		req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
415 }
416 
417 static inline void nvme_setup_flush(struct nvme_ns *ns,
418 		struct nvme_command *cmnd)
419 {
420 	memset(cmnd, 0, sizeof(*cmnd));
421 	cmnd->common.opcode = nvme_cmd_flush;
422 	cmnd->common.nsid = cpu_to_le32(ns->ns_id);
423 }
424 
425 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
426 		struct nvme_command *cmnd)
427 {
428 	unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
429 	struct nvme_dsm_range *range;
430 	struct bio *bio;
431 
432 	range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
433 	if (!range)
434 		return BLK_STS_RESOURCE;
435 
436 	__rq_for_each_bio(bio, req) {
437 		u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
438 		u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
439 
440 		range[n].cattr = cpu_to_le32(0);
441 		range[n].nlb = cpu_to_le32(nlb);
442 		range[n].slba = cpu_to_le64(slba);
443 		n++;
444 	}
445 
446 	if (WARN_ON_ONCE(n != segments)) {
447 		kfree(range);
448 		return BLK_STS_IOERR;
449 	}
450 
451 	memset(cmnd, 0, sizeof(*cmnd));
452 	cmnd->dsm.opcode = nvme_cmd_dsm;
453 	cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
454 	cmnd->dsm.nr = cpu_to_le32(segments - 1);
455 	cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
456 
457 	req->special_vec.bv_page = virt_to_page(range);
458 	req->special_vec.bv_offset = offset_in_page(range);
459 	req->special_vec.bv_len = sizeof(*range) * segments;
460 	req->rq_flags |= RQF_SPECIAL_PAYLOAD;
461 
462 	return BLK_STS_OK;
463 }
464 
465 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
466 		struct request *req, struct nvme_command *cmnd)
467 {
468 	struct nvme_ctrl *ctrl = ns->ctrl;
469 	u16 control = 0;
470 	u32 dsmgmt = 0;
471 
472 	/*
473 	 * If formated with metadata, require the block layer provide a buffer
474 	 * unless this namespace is formated such that the metadata can be
475 	 * stripped/generated by the controller with PRACT=1.
476 	 */
477 	if (ns && ns->ms &&
478 	    (!ns->pi_type || ns->ms != sizeof(struct t10_pi_tuple)) &&
479 	    !blk_integrity_rq(req) && !blk_rq_is_passthrough(req))
480 		return BLK_STS_NOTSUPP;
481 
482 	if (req->cmd_flags & REQ_FUA)
483 		control |= NVME_RW_FUA;
484 	if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
485 		control |= NVME_RW_LR;
486 
487 	if (req->cmd_flags & REQ_RAHEAD)
488 		dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
489 
490 	memset(cmnd, 0, sizeof(*cmnd));
491 	cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
492 	cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
493 	cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
494 	cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
495 
496 	if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
497 		nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
498 
499 	if (ns->ms) {
500 		switch (ns->pi_type) {
501 		case NVME_NS_DPS_PI_TYPE3:
502 			control |= NVME_RW_PRINFO_PRCHK_GUARD;
503 			break;
504 		case NVME_NS_DPS_PI_TYPE1:
505 		case NVME_NS_DPS_PI_TYPE2:
506 			control |= NVME_RW_PRINFO_PRCHK_GUARD |
507 					NVME_RW_PRINFO_PRCHK_REF;
508 			cmnd->rw.reftag = cpu_to_le32(
509 					nvme_block_nr(ns, blk_rq_pos(req)));
510 			break;
511 		}
512 		if (!blk_integrity_rq(req))
513 			control |= NVME_RW_PRINFO_PRACT;
514 	}
515 
516 	cmnd->rw.control = cpu_to_le16(control);
517 	cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
518 	return 0;
519 }
520 
521 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
522 		struct nvme_command *cmd)
523 {
524 	blk_status_t ret = BLK_STS_OK;
525 
526 	if (!(req->rq_flags & RQF_DONTPREP)) {
527 		nvme_req(req)->retries = 0;
528 		nvme_req(req)->flags = 0;
529 		req->rq_flags |= RQF_DONTPREP;
530 	}
531 
532 	switch (req_op(req)) {
533 	case REQ_OP_DRV_IN:
534 	case REQ_OP_DRV_OUT:
535 		memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
536 		break;
537 	case REQ_OP_FLUSH:
538 		nvme_setup_flush(ns, cmd);
539 		break;
540 	case REQ_OP_WRITE_ZEROES:
541 		/* currently only aliased to deallocate for a few ctrls: */
542 	case REQ_OP_DISCARD:
543 		ret = nvme_setup_discard(ns, req, cmd);
544 		break;
545 	case REQ_OP_READ:
546 	case REQ_OP_WRITE:
547 		ret = nvme_setup_rw(ns, req, cmd);
548 		break;
549 	default:
550 		WARN_ON_ONCE(1);
551 		return BLK_STS_IOERR;
552 	}
553 
554 	cmd->common.command_id = req->tag;
555 	return ret;
556 }
557 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
558 
559 /*
560  * Returns 0 on success.  If the result is negative, it's a Linux error code;
561  * if the result is positive, it's an NVM Express status code
562  */
563 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
564 		union nvme_result *result, void *buffer, unsigned bufflen,
565 		unsigned timeout, int qid, int at_head, int flags)
566 {
567 	struct request *req;
568 	int ret;
569 
570 	req = nvme_alloc_request(q, cmd, flags, qid);
571 	if (IS_ERR(req))
572 		return PTR_ERR(req);
573 
574 	req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
575 
576 	if (buffer && bufflen) {
577 		ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
578 		if (ret)
579 			goto out;
580 	}
581 
582 	blk_execute_rq(req->q, NULL, req, at_head);
583 	if (result)
584 		*result = nvme_req(req)->result;
585 	if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
586 		ret = -EINTR;
587 	else
588 		ret = nvme_req(req)->status;
589  out:
590 	blk_mq_free_request(req);
591 	return ret;
592 }
593 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
594 
595 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
596 		void *buffer, unsigned bufflen)
597 {
598 	return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
599 			NVME_QID_ANY, 0, 0);
600 }
601 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
602 
603 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
604 		unsigned len, u32 seed, bool write)
605 {
606 	struct bio_integrity_payload *bip;
607 	int ret = -ENOMEM;
608 	void *buf;
609 
610 	buf = kmalloc(len, GFP_KERNEL);
611 	if (!buf)
612 		goto out;
613 
614 	ret = -EFAULT;
615 	if (write && copy_from_user(buf, ubuf, len))
616 		goto out_free_meta;
617 
618 	bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
619 	if (IS_ERR(bip)) {
620 		ret = PTR_ERR(bip);
621 		goto out_free_meta;
622 	}
623 
624 	bip->bip_iter.bi_size = len;
625 	bip->bip_iter.bi_sector = seed;
626 	ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
627 			offset_in_page(buf));
628 	if (ret == len)
629 		return buf;
630 	ret = -ENOMEM;
631 out_free_meta:
632 	kfree(buf);
633 out:
634 	return ERR_PTR(ret);
635 }
636 
637 static int nvme_submit_user_cmd(struct request_queue *q,
638 		struct nvme_command *cmd, void __user *ubuffer,
639 		unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
640 		u32 meta_seed, u32 *result, unsigned timeout)
641 {
642 	bool write = nvme_is_write(cmd);
643 	struct nvme_ns *ns = q->queuedata;
644 	struct gendisk *disk = ns ? ns->disk : NULL;
645 	struct request *req;
646 	struct bio *bio = NULL;
647 	void *meta = NULL;
648 	int ret;
649 
650 	req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
651 	if (IS_ERR(req))
652 		return PTR_ERR(req);
653 
654 	req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
655 
656 	if (ubuffer && bufflen) {
657 		ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
658 				GFP_KERNEL);
659 		if (ret)
660 			goto out;
661 		bio = req->bio;
662 		bio->bi_disk = disk;
663 		if (disk && meta_buffer && meta_len) {
664 			meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
665 					meta_seed, write);
666 			if (IS_ERR(meta)) {
667 				ret = PTR_ERR(meta);
668 				goto out_unmap;
669 			}
670 		}
671 	}
672 
673 	blk_execute_rq(req->q, disk, req, 0);
674 	if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
675 		ret = -EINTR;
676 	else
677 		ret = nvme_req(req)->status;
678 	if (result)
679 		*result = le32_to_cpu(nvme_req(req)->result.u32);
680 	if (meta && !ret && !write) {
681 		if (copy_to_user(meta_buffer, meta, meta_len))
682 			ret = -EFAULT;
683 	}
684 	kfree(meta);
685  out_unmap:
686 	if (bio)
687 		blk_rq_unmap_user(bio);
688  out:
689 	blk_mq_free_request(req);
690 	return ret;
691 }
692 
693 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
694 {
695 	struct nvme_ctrl *ctrl = rq->end_io_data;
696 
697 	blk_mq_free_request(rq);
698 
699 	if (status) {
700 		dev_err(ctrl->device,
701 			"failed nvme_keep_alive_end_io error=%d\n",
702 				status);
703 		return;
704 	}
705 
706 	schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
707 }
708 
709 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
710 {
711 	struct nvme_command c;
712 	struct request *rq;
713 
714 	memset(&c, 0, sizeof(c));
715 	c.common.opcode = nvme_admin_keep_alive;
716 
717 	rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
718 			NVME_QID_ANY);
719 	if (IS_ERR(rq))
720 		return PTR_ERR(rq);
721 
722 	rq->timeout = ctrl->kato * HZ;
723 	rq->end_io_data = ctrl;
724 
725 	blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
726 
727 	return 0;
728 }
729 
730 static void nvme_keep_alive_work(struct work_struct *work)
731 {
732 	struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
733 			struct nvme_ctrl, ka_work);
734 
735 	if (nvme_keep_alive(ctrl)) {
736 		/* allocation failure, reset the controller */
737 		dev_err(ctrl->device, "keep-alive failed\n");
738 		nvme_reset_ctrl(ctrl);
739 		return;
740 	}
741 }
742 
743 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
744 {
745 	if (unlikely(ctrl->kato == 0))
746 		return;
747 
748 	INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
749 	schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
750 }
751 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
752 
753 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
754 {
755 	if (unlikely(ctrl->kato == 0))
756 		return;
757 
758 	cancel_delayed_work_sync(&ctrl->ka_work);
759 }
760 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
761 
762 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
763 {
764 	struct nvme_command c = { };
765 	int error;
766 
767 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
768 	c.identify.opcode = nvme_admin_identify;
769 	c.identify.cns = NVME_ID_CNS_CTRL;
770 
771 	*id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
772 	if (!*id)
773 		return -ENOMEM;
774 
775 	error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
776 			sizeof(struct nvme_id_ctrl));
777 	if (error)
778 		kfree(*id);
779 	return error;
780 }
781 
782 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
783 		u8 *eui64, u8 *nguid, uuid_t *uuid)
784 {
785 	struct nvme_command c = { };
786 	int status;
787 	void *data;
788 	int pos;
789 	int len;
790 
791 	c.identify.opcode = nvme_admin_identify;
792 	c.identify.nsid = cpu_to_le32(nsid);
793 	c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
794 
795 	data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
796 	if (!data)
797 		return -ENOMEM;
798 
799 	status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
800 				      NVME_IDENTIFY_DATA_SIZE);
801 	if (status)
802 		goto free_data;
803 
804 	for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
805 		struct nvme_ns_id_desc *cur = data + pos;
806 
807 		if (cur->nidl == 0)
808 			break;
809 
810 		switch (cur->nidt) {
811 		case NVME_NIDT_EUI64:
812 			if (cur->nidl != NVME_NIDT_EUI64_LEN) {
813 				dev_warn(ctrl->device,
814 					 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
815 					 cur->nidl);
816 				goto free_data;
817 			}
818 			len = NVME_NIDT_EUI64_LEN;
819 			memcpy(eui64, data + pos + sizeof(*cur), len);
820 			break;
821 		case NVME_NIDT_NGUID:
822 			if (cur->nidl != NVME_NIDT_NGUID_LEN) {
823 				dev_warn(ctrl->device,
824 					 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
825 					 cur->nidl);
826 				goto free_data;
827 			}
828 			len = NVME_NIDT_NGUID_LEN;
829 			memcpy(nguid, data + pos + sizeof(*cur), len);
830 			break;
831 		case NVME_NIDT_UUID:
832 			if (cur->nidl != NVME_NIDT_UUID_LEN) {
833 				dev_warn(ctrl->device,
834 					 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
835 					 cur->nidl);
836 				goto free_data;
837 			}
838 			len = NVME_NIDT_UUID_LEN;
839 			uuid_copy(uuid, data + pos + sizeof(*cur));
840 			break;
841 		default:
842 			/* Skip unnkown types */
843 			len = cur->nidl;
844 			break;
845 		}
846 
847 		len += sizeof(*cur);
848 	}
849 free_data:
850 	kfree(data);
851 	return status;
852 }
853 
854 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
855 {
856 	struct nvme_command c = { };
857 
858 	c.identify.opcode = nvme_admin_identify;
859 	c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
860 	c.identify.nsid = cpu_to_le32(nsid);
861 	return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
862 }
863 
864 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
865 		unsigned nsid)
866 {
867 	struct nvme_id_ns *id;
868 	struct nvme_command c = { };
869 	int error;
870 
871 	/* gcc-4.4.4 (at least) has issues with initializers and anon unions */
872 	c.identify.opcode = nvme_admin_identify;
873 	c.identify.nsid = cpu_to_le32(nsid);
874 	c.identify.cns = NVME_ID_CNS_NS;
875 
876 	id = kmalloc(sizeof(*id), GFP_KERNEL);
877 	if (!id)
878 		return NULL;
879 
880 	error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
881 	if (error) {
882 		dev_warn(ctrl->device, "Identify namespace failed\n");
883 		kfree(id);
884 		return NULL;
885 	}
886 
887 	return id;
888 }
889 
890 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
891 		      void *buffer, size_t buflen, u32 *result)
892 {
893 	struct nvme_command c;
894 	union nvme_result res;
895 	int ret;
896 
897 	memset(&c, 0, sizeof(c));
898 	c.features.opcode = nvme_admin_set_features;
899 	c.features.fid = cpu_to_le32(fid);
900 	c.features.dword11 = cpu_to_le32(dword11);
901 
902 	ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
903 			buffer, buflen, 0, NVME_QID_ANY, 0, 0);
904 	if (ret >= 0 && result)
905 		*result = le32_to_cpu(res.u32);
906 	return ret;
907 }
908 
909 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
910 {
911 	u32 q_count = (*count - 1) | ((*count - 1) << 16);
912 	u32 result;
913 	int status, nr_io_queues;
914 
915 	status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
916 			&result);
917 	if (status < 0)
918 		return status;
919 
920 	/*
921 	 * Degraded controllers might return an error when setting the queue
922 	 * count.  We still want to be able to bring them online and offer
923 	 * access to the admin queue, as that might be only way to fix them up.
924 	 */
925 	if (status > 0) {
926 		dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
927 		*count = 0;
928 	} else {
929 		nr_io_queues = min(result & 0xffff, result >> 16) + 1;
930 		*count = min(*count, nr_io_queues);
931 	}
932 
933 	return 0;
934 }
935 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
936 
937 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
938 {
939 	struct nvme_user_io io;
940 	struct nvme_command c;
941 	unsigned length, meta_len;
942 	void __user *metadata;
943 
944 	if (copy_from_user(&io, uio, sizeof(io)))
945 		return -EFAULT;
946 	if (io.flags)
947 		return -EINVAL;
948 
949 	switch (io.opcode) {
950 	case nvme_cmd_write:
951 	case nvme_cmd_read:
952 	case nvme_cmd_compare:
953 		break;
954 	default:
955 		return -EINVAL;
956 	}
957 
958 	length = (io.nblocks + 1) << ns->lba_shift;
959 	meta_len = (io.nblocks + 1) * ns->ms;
960 	metadata = (void __user *)(uintptr_t)io.metadata;
961 
962 	if (ns->ext) {
963 		length += meta_len;
964 		meta_len = 0;
965 	} else if (meta_len) {
966 		if ((io.metadata & 3) || !io.metadata)
967 			return -EINVAL;
968 	}
969 
970 	memset(&c, 0, sizeof(c));
971 	c.rw.opcode = io.opcode;
972 	c.rw.flags = io.flags;
973 	c.rw.nsid = cpu_to_le32(ns->ns_id);
974 	c.rw.slba = cpu_to_le64(io.slba);
975 	c.rw.length = cpu_to_le16(io.nblocks);
976 	c.rw.control = cpu_to_le16(io.control);
977 	c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
978 	c.rw.reftag = cpu_to_le32(io.reftag);
979 	c.rw.apptag = cpu_to_le16(io.apptag);
980 	c.rw.appmask = cpu_to_le16(io.appmask);
981 
982 	return nvme_submit_user_cmd(ns->queue, &c,
983 			(void __user *)(uintptr_t)io.addr, length,
984 			metadata, meta_len, io.slba, NULL, 0);
985 }
986 
987 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
988 			struct nvme_passthru_cmd __user *ucmd)
989 {
990 	struct nvme_passthru_cmd cmd;
991 	struct nvme_command c;
992 	unsigned timeout = 0;
993 	int status;
994 
995 	if (!capable(CAP_SYS_ADMIN))
996 		return -EACCES;
997 	if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
998 		return -EFAULT;
999 	if (cmd.flags)
1000 		return -EINVAL;
1001 
1002 	memset(&c, 0, sizeof(c));
1003 	c.common.opcode = cmd.opcode;
1004 	c.common.flags = cmd.flags;
1005 	c.common.nsid = cpu_to_le32(cmd.nsid);
1006 	c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1007 	c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1008 	c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1009 	c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1010 	c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1011 	c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1012 	c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1013 	c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1014 
1015 	if (cmd.timeout_ms)
1016 		timeout = msecs_to_jiffies(cmd.timeout_ms);
1017 
1018 	status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1019 			(void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1020 			(void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1021 			0, &cmd.result, timeout);
1022 	if (status >= 0) {
1023 		if (put_user(cmd.result, &ucmd->result))
1024 			return -EFAULT;
1025 	}
1026 
1027 	return status;
1028 }
1029 
1030 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1031 		unsigned int cmd, unsigned long arg)
1032 {
1033 	struct nvme_ns *ns = bdev->bd_disk->private_data;
1034 
1035 	switch (cmd) {
1036 	case NVME_IOCTL_ID:
1037 		force_successful_syscall_return();
1038 		return ns->ns_id;
1039 	case NVME_IOCTL_ADMIN_CMD:
1040 		return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1041 	case NVME_IOCTL_IO_CMD:
1042 		return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1043 	case NVME_IOCTL_SUBMIT_IO:
1044 		return nvme_submit_io(ns, (void __user *)arg);
1045 	default:
1046 #ifdef CONFIG_NVM
1047 		if (ns->ndev)
1048 			return nvme_nvm_ioctl(ns, cmd, arg);
1049 #endif
1050 		if (is_sed_ioctl(cmd))
1051 			return sed_ioctl(ns->ctrl->opal_dev, cmd,
1052 					 (void __user *) arg);
1053 		return -ENOTTY;
1054 	}
1055 }
1056 
1057 #ifdef CONFIG_COMPAT
1058 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1059 			unsigned int cmd, unsigned long arg)
1060 {
1061 	return nvme_ioctl(bdev, mode, cmd, arg);
1062 }
1063 #else
1064 #define nvme_compat_ioctl	NULL
1065 #endif
1066 
1067 static int nvme_open(struct block_device *bdev, fmode_t mode)
1068 {
1069 	return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
1070 }
1071 
1072 static void nvme_release(struct gendisk *disk, fmode_t mode)
1073 {
1074 	struct nvme_ns *ns = disk->private_data;
1075 
1076 	module_put(ns->ctrl->ops->module);
1077 	nvme_put_ns(ns);
1078 }
1079 
1080 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1081 {
1082 	/* some standard values */
1083 	geo->heads = 1 << 6;
1084 	geo->sectors = 1 << 5;
1085 	geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1086 	return 0;
1087 }
1088 
1089 #ifdef CONFIG_BLK_DEV_INTEGRITY
1090 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1091 		u16 bs)
1092 {
1093 	struct nvme_ns *ns = disk->private_data;
1094 	u16 old_ms = ns->ms;
1095 	u8 pi_type = 0;
1096 
1097 	ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1098 	ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1099 
1100 	/* PI implementation requires metadata equal t10 pi tuple size */
1101 	if (ns->ms == sizeof(struct t10_pi_tuple))
1102 		pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1103 
1104 	if (blk_get_integrity(disk) &&
1105 	    (ns->pi_type != pi_type || ns->ms != old_ms ||
1106 	     bs != queue_logical_block_size(disk->queue) ||
1107 	     (ns->ms && ns->ext)))
1108 		blk_integrity_unregister(disk);
1109 
1110 	ns->pi_type = pi_type;
1111 }
1112 
1113 static void nvme_init_integrity(struct nvme_ns *ns)
1114 {
1115 	struct blk_integrity integrity;
1116 
1117 	memset(&integrity, 0, sizeof(integrity));
1118 	switch (ns->pi_type) {
1119 	case NVME_NS_DPS_PI_TYPE3:
1120 		integrity.profile = &t10_pi_type3_crc;
1121 		integrity.tag_size = sizeof(u16) + sizeof(u32);
1122 		integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1123 		break;
1124 	case NVME_NS_DPS_PI_TYPE1:
1125 	case NVME_NS_DPS_PI_TYPE2:
1126 		integrity.profile = &t10_pi_type1_crc;
1127 		integrity.tag_size = sizeof(u16);
1128 		integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1129 		break;
1130 	default:
1131 		integrity.profile = NULL;
1132 		break;
1133 	}
1134 	integrity.tuple_size = ns->ms;
1135 	blk_integrity_register(ns->disk, &integrity);
1136 	blk_queue_max_integrity_segments(ns->queue, 1);
1137 }
1138 #else
1139 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1140 		u16 bs)
1141 {
1142 }
1143 static void nvme_init_integrity(struct nvme_ns *ns)
1144 {
1145 }
1146 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1147 
1148 static void nvme_set_chunk_size(struct nvme_ns *ns)
1149 {
1150 	u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1151 	blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1152 }
1153 
1154 static void nvme_config_discard(struct nvme_ns *ns)
1155 {
1156 	struct nvme_ctrl *ctrl = ns->ctrl;
1157 	u32 logical_block_size = queue_logical_block_size(ns->queue);
1158 
1159 	BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1160 			NVME_DSM_MAX_RANGES);
1161 
1162 	if (ctrl->nr_streams && ns->sws && ns->sgs) {
1163 		unsigned int sz = logical_block_size * ns->sws * ns->sgs;
1164 
1165 		ns->queue->limits.discard_alignment = sz;
1166 		ns->queue->limits.discard_granularity = sz;
1167 	} else {
1168 		ns->queue->limits.discard_alignment = logical_block_size;
1169 		ns->queue->limits.discard_granularity = logical_block_size;
1170 	}
1171 	blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
1172 	blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1173 	queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1174 
1175 	if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1176 		blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1177 }
1178 
1179 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1180 		struct nvme_id_ns *id, u8 *eui64, u8 *nguid, uuid_t *uuid)
1181 {
1182 	if (ctrl->vs >= NVME_VS(1, 1, 0))
1183 		memcpy(eui64, id->eui64, sizeof(id->eui64));
1184 	if (ctrl->vs >= NVME_VS(1, 2, 0))
1185 		memcpy(nguid, id->nguid, sizeof(id->nguid));
1186 	if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1187 		 /* Don't treat error as fatal we potentially
1188 		  * already have a NGUID or EUI-64
1189 		  */
1190 		if (nvme_identify_ns_descs(ctrl, nsid, eui64, nguid, uuid))
1191 			dev_warn(ctrl->device,
1192 				 "%s: Identify Descriptors failed\n", __func__);
1193 	}
1194 }
1195 
1196 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1197 {
1198 	struct nvme_ns *ns = disk->private_data;
1199 	struct nvme_ctrl *ctrl = ns->ctrl;
1200 	u16 bs;
1201 
1202 	/*
1203 	 * If identify namespace failed, use default 512 byte block size so
1204 	 * block layer can use before failing read/write for 0 capacity.
1205 	 */
1206 	ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1207 	if (ns->lba_shift == 0)
1208 		ns->lba_shift = 9;
1209 	bs = 1 << ns->lba_shift;
1210 	ns->noiob = le16_to_cpu(id->noiob);
1211 
1212 	blk_mq_freeze_queue(disk->queue);
1213 
1214 	if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
1215 		nvme_prep_integrity(disk, id, bs);
1216 	blk_queue_logical_block_size(ns->queue, bs);
1217 	if (ns->noiob)
1218 		nvme_set_chunk_size(ns);
1219 	if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1220 		nvme_init_integrity(ns);
1221 	if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1222 		set_capacity(disk, 0);
1223 	else
1224 		set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1225 
1226 	if (ctrl->oncs & NVME_CTRL_ONCS_DSM)
1227 		nvme_config_discard(ns);
1228 	blk_mq_unfreeze_queue(disk->queue);
1229 }
1230 
1231 static int nvme_revalidate_disk(struct gendisk *disk)
1232 {
1233 	struct nvme_ns *ns = disk->private_data;
1234 	struct nvme_ctrl *ctrl = ns->ctrl;
1235 	struct nvme_id_ns *id;
1236 	u8 eui64[8] = { 0 }, nguid[16] = { 0 };
1237 	uuid_t uuid = uuid_null;
1238 	int ret = 0;
1239 
1240 	if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1241 		set_capacity(disk, 0);
1242 		return -ENODEV;
1243 	}
1244 
1245 	id = nvme_identify_ns(ctrl, ns->ns_id);
1246 	if (!id)
1247 		return -ENODEV;
1248 
1249 	if (id->ncap == 0) {
1250 		ret = -ENODEV;
1251 		goto out;
1252 	}
1253 
1254 	nvme_report_ns_ids(ctrl, ns->ns_id, id, eui64, nguid, &uuid);
1255 	if (!uuid_equal(&ns->uuid, &uuid) ||
1256 	    memcmp(&ns->nguid, &nguid, sizeof(ns->nguid)) ||
1257 	    memcmp(&ns->eui, &eui64, sizeof(ns->eui))) {
1258 		dev_err(ctrl->device,
1259 			"identifiers changed for nsid %d\n", ns->ns_id);
1260 		ret = -ENODEV;
1261 	}
1262 
1263 out:
1264 	kfree(id);
1265 	return ret;
1266 }
1267 
1268 static char nvme_pr_type(enum pr_type type)
1269 {
1270 	switch (type) {
1271 	case PR_WRITE_EXCLUSIVE:
1272 		return 1;
1273 	case PR_EXCLUSIVE_ACCESS:
1274 		return 2;
1275 	case PR_WRITE_EXCLUSIVE_REG_ONLY:
1276 		return 3;
1277 	case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1278 		return 4;
1279 	case PR_WRITE_EXCLUSIVE_ALL_REGS:
1280 		return 5;
1281 	case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1282 		return 6;
1283 	default:
1284 		return 0;
1285 	}
1286 };
1287 
1288 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1289 				u64 key, u64 sa_key, u8 op)
1290 {
1291 	struct nvme_ns *ns = bdev->bd_disk->private_data;
1292 	struct nvme_command c;
1293 	u8 data[16] = { 0, };
1294 
1295 	put_unaligned_le64(key, &data[0]);
1296 	put_unaligned_le64(sa_key, &data[8]);
1297 
1298 	memset(&c, 0, sizeof(c));
1299 	c.common.opcode = op;
1300 	c.common.nsid = cpu_to_le32(ns->ns_id);
1301 	c.common.cdw10[0] = cpu_to_le32(cdw10);
1302 
1303 	return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1304 }
1305 
1306 static int nvme_pr_register(struct block_device *bdev, u64 old,
1307 		u64 new, unsigned flags)
1308 {
1309 	u32 cdw10;
1310 
1311 	if (flags & ~PR_FL_IGNORE_KEY)
1312 		return -EOPNOTSUPP;
1313 
1314 	cdw10 = old ? 2 : 0;
1315 	cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1316 	cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1317 	return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1318 }
1319 
1320 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1321 		enum pr_type type, unsigned flags)
1322 {
1323 	u32 cdw10;
1324 
1325 	if (flags & ~PR_FL_IGNORE_KEY)
1326 		return -EOPNOTSUPP;
1327 
1328 	cdw10 = nvme_pr_type(type) << 8;
1329 	cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1330 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1331 }
1332 
1333 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1334 		enum pr_type type, bool abort)
1335 {
1336 	u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1337 	return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1338 }
1339 
1340 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1341 {
1342 	u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1343 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1344 }
1345 
1346 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1347 {
1348 	u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1349 	return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1350 }
1351 
1352 static const struct pr_ops nvme_pr_ops = {
1353 	.pr_register	= nvme_pr_register,
1354 	.pr_reserve	= nvme_pr_reserve,
1355 	.pr_release	= nvme_pr_release,
1356 	.pr_preempt	= nvme_pr_preempt,
1357 	.pr_clear	= nvme_pr_clear,
1358 };
1359 
1360 #ifdef CONFIG_BLK_SED_OPAL
1361 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1362 		bool send)
1363 {
1364 	struct nvme_ctrl *ctrl = data;
1365 	struct nvme_command cmd;
1366 
1367 	memset(&cmd, 0, sizeof(cmd));
1368 	if (send)
1369 		cmd.common.opcode = nvme_admin_security_send;
1370 	else
1371 		cmd.common.opcode = nvme_admin_security_recv;
1372 	cmd.common.nsid = 0;
1373 	cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1374 	cmd.common.cdw10[1] = cpu_to_le32(len);
1375 
1376 	return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1377 				      ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1378 }
1379 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1380 #endif /* CONFIG_BLK_SED_OPAL */
1381 
1382 static const struct block_device_operations nvme_fops = {
1383 	.owner		= THIS_MODULE,
1384 	.ioctl		= nvme_ioctl,
1385 	.compat_ioctl	= nvme_compat_ioctl,
1386 	.open		= nvme_open,
1387 	.release	= nvme_release,
1388 	.getgeo		= nvme_getgeo,
1389 	.revalidate_disk= nvme_revalidate_disk,
1390 	.pr_ops		= &nvme_pr_ops,
1391 };
1392 
1393 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1394 {
1395 	unsigned long timeout =
1396 		((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1397 	u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1398 	int ret;
1399 
1400 	while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1401 		if (csts == ~0)
1402 			return -ENODEV;
1403 		if ((csts & NVME_CSTS_RDY) == bit)
1404 			break;
1405 
1406 		msleep(100);
1407 		if (fatal_signal_pending(current))
1408 			return -EINTR;
1409 		if (time_after(jiffies, timeout)) {
1410 			dev_err(ctrl->device,
1411 				"Device not ready; aborting %s\n", enabled ?
1412 						"initialisation" : "reset");
1413 			return -ENODEV;
1414 		}
1415 	}
1416 
1417 	return ret;
1418 }
1419 
1420 /*
1421  * If the device has been passed off to us in an enabled state, just clear
1422  * the enabled bit.  The spec says we should set the 'shutdown notification
1423  * bits', but doing so may cause the device to complete commands to the
1424  * admin queue ... and we don't know what memory that might be pointing at!
1425  */
1426 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1427 {
1428 	int ret;
1429 
1430 	ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1431 	ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1432 
1433 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1434 	if (ret)
1435 		return ret;
1436 
1437 	if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1438 		msleep(NVME_QUIRK_DELAY_AMOUNT);
1439 
1440 	return nvme_wait_ready(ctrl, cap, false);
1441 }
1442 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1443 
1444 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1445 {
1446 	/*
1447 	 * Default to a 4K page size, with the intention to update this
1448 	 * path in the future to accomodate architectures with differing
1449 	 * kernel and IO page sizes.
1450 	 */
1451 	unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1452 	int ret;
1453 
1454 	if (page_shift < dev_page_min) {
1455 		dev_err(ctrl->device,
1456 			"Minimum device page size %u too large for host (%u)\n",
1457 			1 << dev_page_min, 1 << page_shift);
1458 		return -ENODEV;
1459 	}
1460 
1461 	ctrl->page_size = 1 << page_shift;
1462 
1463 	ctrl->ctrl_config = NVME_CC_CSS_NVM;
1464 	ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1465 	ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1466 	ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1467 	ctrl->ctrl_config |= NVME_CC_ENABLE;
1468 
1469 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1470 	if (ret)
1471 		return ret;
1472 	return nvme_wait_ready(ctrl, cap, true);
1473 }
1474 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1475 
1476 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1477 {
1478 	unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1479 	u32 csts;
1480 	int ret;
1481 
1482 	ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1483 	ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1484 
1485 	ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1486 	if (ret)
1487 		return ret;
1488 
1489 	while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1490 		if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1491 			break;
1492 
1493 		msleep(100);
1494 		if (fatal_signal_pending(current))
1495 			return -EINTR;
1496 		if (time_after(jiffies, timeout)) {
1497 			dev_err(ctrl->device,
1498 				"Device shutdown incomplete; abort shutdown\n");
1499 			return -ENODEV;
1500 		}
1501 	}
1502 
1503 	return ret;
1504 }
1505 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1506 
1507 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1508 		struct request_queue *q)
1509 {
1510 	bool vwc = false;
1511 
1512 	if (ctrl->max_hw_sectors) {
1513 		u32 max_segments =
1514 			(ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1515 
1516 		blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1517 		blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1518 	}
1519 	if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1520 		blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1521 	blk_queue_virt_boundary(q, ctrl->page_size - 1);
1522 	if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1523 		vwc = true;
1524 	blk_queue_write_cache(q, vwc, vwc);
1525 }
1526 
1527 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1528 {
1529 	__le64 ts;
1530 	int ret;
1531 
1532 	if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1533 		return 0;
1534 
1535 	ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1536 	ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1537 			NULL);
1538 	if (ret)
1539 		dev_warn_once(ctrl->device,
1540 			"could not set timestamp (%d)\n", ret);
1541 	return ret;
1542 }
1543 
1544 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1545 {
1546 	/*
1547 	 * APST (Autonomous Power State Transition) lets us program a
1548 	 * table of power state transitions that the controller will
1549 	 * perform automatically.  We configure it with a simple
1550 	 * heuristic: we are willing to spend at most 2% of the time
1551 	 * transitioning between power states.  Therefore, when running
1552 	 * in any given state, we will enter the next lower-power
1553 	 * non-operational state after waiting 50 * (enlat + exlat)
1554 	 * microseconds, as long as that state's exit latency is under
1555 	 * the requested maximum latency.
1556 	 *
1557 	 * We will not autonomously enter any non-operational state for
1558 	 * which the total latency exceeds ps_max_latency_us.  Users
1559 	 * can set ps_max_latency_us to zero to turn off APST.
1560 	 */
1561 
1562 	unsigned apste;
1563 	struct nvme_feat_auto_pst *table;
1564 	u64 max_lat_us = 0;
1565 	int max_ps = -1;
1566 	int ret;
1567 
1568 	/*
1569 	 * If APST isn't supported or if we haven't been initialized yet,
1570 	 * then don't do anything.
1571 	 */
1572 	if (!ctrl->apsta)
1573 		return 0;
1574 
1575 	if (ctrl->npss > 31) {
1576 		dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1577 		return 0;
1578 	}
1579 
1580 	table = kzalloc(sizeof(*table), GFP_KERNEL);
1581 	if (!table)
1582 		return 0;
1583 
1584 	if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1585 		/* Turn off APST. */
1586 		apste = 0;
1587 		dev_dbg(ctrl->device, "APST disabled\n");
1588 	} else {
1589 		__le64 target = cpu_to_le64(0);
1590 		int state;
1591 
1592 		/*
1593 		 * Walk through all states from lowest- to highest-power.
1594 		 * According to the spec, lower-numbered states use more
1595 		 * power.  NPSS, despite the name, is the index of the
1596 		 * lowest-power state, not the number of states.
1597 		 */
1598 		for (state = (int)ctrl->npss; state >= 0; state--) {
1599 			u64 total_latency_us, exit_latency_us, transition_ms;
1600 
1601 			if (target)
1602 				table->entries[state] = target;
1603 
1604 			/*
1605 			 * Don't allow transitions to the deepest state
1606 			 * if it's quirked off.
1607 			 */
1608 			if (state == ctrl->npss &&
1609 			    (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1610 				continue;
1611 
1612 			/*
1613 			 * Is this state a useful non-operational state for
1614 			 * higher-power states to autonomously transition to?
1615 			 */
1616 			if (!(ctrl->psd[state].flags &
1617 			      NVME_PS_FLAGS_NON_OP_STATE))
1618 				continue;
1619 
1620 			exit_latency_us =
1621 				(u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1622 			if (exit_latency_us > ctrl->ps_max_latency_us)
1623 				continue;
1624 
1625 			total_latency_us =
1626 				exit_latency_us +
1627 				le32_to_cpu(ctrl->psd[state].entry_lat);
1628 
1629 			/*
1630 			 * This state is good.  Use it as the APST idle
1631 			 * target for higher power states.
1632 			 */
1633 			transition_ms = total_latency_us + 19;
1634 			do_div(transition_ms, 20);
1635 			if (transition_ms > (1 << 24) - 1)
1636 				transition_ms = (1 << 24) - 1;
1637 
1638 			target = cpu_to_le64((state << 3) |
1639 					     (transition_ms << 8));
1640 
1641 			if (max_ps == -1)
1642 				max_ps = state;
1643 
1644 			if (total_latency_us > max_lat_us)
1645 				max_lat_us = total_latency_us;
1646 		}
1647 
1648 		apste = 1;
1649 
1650 		if (max_ps == -1) {
1651 			dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1652 		} else {
1653 			dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1654 				max_ps, max_lat_us, (int)sizeof(*table), table);
1655 		}
1656 	}
1657 
1658 	ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1659 				table, sizeof(*table), NULL);
1660 	if (ret)
1661 		dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1662 
1663 	kfree(table);
1664 	return ret;
1665 }
1666 
1667 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1668 {
1669 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1670 	u64 latency;
1671 
1672 	switch (val) {
1673 	case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1674 	case PM_QOS_LATENCY_ANY:
1675 		latency = U64_MAX;
1676 		break;
1677 
1678 	default:
1679 		latency = val;
1680 	}
1681 
1682 	if (ctrl->ps_max_latency_us != latency) {
1683 		ctrl->ps_max_latency_us = latency;
1684 		nvme_configure_apst(ctrl);
1685 	}
1686 }
1687 
1688 struct nvme_core_quirk_entry {
1689 	/*
1690 	 * NVMe model and firmware strings are padded with spaces.  For
1691 	 * simplicity, strings in the quirk table are padded with NULLs
1692 	 * instead.
1693 	 */
1694 	u16 vid;
1695 	const char *mn;
1696 	const char *fr;
1697 	unsigned long quirks;
1698 };
1699 
1700 static const struct nvme_core_quirk_entry core_quirks[] = {
1701 	{
1702 		/*
1703 		 * This Toshiba device seems to die using any APST states.  See:
1704 		 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1705 		 */
1706 		.vid = 0x1179,
1707 		.mn = "THNSF5256GPUK TOSHIBA",
1708 		.quirks = NVME_QUIRK_NO_APST,
1709 	}
1710 };
1711 
1712 /* match is null-terminated but idstr is space-padded. */
1713 static bool string_matches(const char *idstr, const char *match, size_t len)
1714 {
1715 	size_t matchlen;
1716 
1717 	if (!match)
1718 		return true;
1719 
1720 	matchlen = strlen(match);
1721 	WARN_ON_ONCE(matchlen > len);
1722 
1723 	if (memcmp(idstr, match, matchlen))
1724 		return false;
1725 
1726 	for (; matchlen < len; matchlen++)
1727 		if (idstr[matchlen] != ' ')
1728 			return false;
1729 
1730 	return true;
1731 }
1732 
1733 static bool quirk_matches(const struct nvme_id_ctrl *id,
1734 			  const struct nvme_core_quirk_entry *q)
1735 {
1736 	return q->vid == le16_to_cpu(id->vid) &&
1737 		string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1738 		string_matches(id->fr, q->fr, sizeof(id->fr));
1739 }
1740 
1741 static void nvme_init_subnqn(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1742 {
1743 	size_t nqnlen;
1744 	int off;
1745 
1746 	nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
1747 	if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
1748 		strcpy(ctrl->subnqn, id->subnqn);
1749 		return;
1750 	}
1751 
1752 	if (ctrl->vs >= NVME_VS(1, 2, 1))
1753 		dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
1754 
1755 	/* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
1756 	off = snprintf(ctrl->subnqn, NVMF_NQN_SIZE,
1757 			"nqn.2014.08.org.nvmexpress:%4x%4x",
1758 			le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
1759 	memcpy(ctrl->subnqn + off, id->sn, sizeof(id->sn));
1760 	off += sizeof(id->sn);
1761 	memcpy(ctrl->subnqn + off, id->mn, sizeof(id->mn));
1762 	off += sizeof(id->mn);
1763 	memset(ctrl->subnqn + off, 0, sizeof(ctrl->subnqn) - off);
1764 }
1765 
1766 /*
1767  * Initialize the cached copies of the Identify data and various controller
1768  * register in our nvme_ctrl structure.  This should be called as soon as
1769  * the admin queue is fully up and running.
1770  */
1771 int nvme_init_identify(struct nvme_ctrl *ctrl)
1772 {
1773 	struct nvme_id_ctrl *id;
1774 	u64 cap;
1775 	int ret, page_shift;
1776 	u32 max_hw_sectors;
1777 	bool prev_apst_enabled;
1778 
1779 	ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1780 	if (ret) {
1781 		dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1782 		return ret;
1783 	}
1784 
1785 	ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1786 	if (ret) {
1787 		dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1788 		return ret;
1789 	}
1790 	page_shift = NVME_CAP_MPSMIN(cap) + 12;
1791 
1792 	if (ctrl->vs >= NVME_VS(1, 1, 0))
1793 		ctrl->subsystem = NVME_CAP_NSSRC(cap);
1794 
1795 	ret = nvme_identify_ctrl(ctrl, &id);
1796 	if (ret) {
1797 		dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1798 		return -EIO;
1799 	}
1800 
1801 	nvme_init_subnqn(ctrl, id);
1802 
1803 	if (!ctrl->identified) {
1804 		/*
1805 		 * Check for quirks.  Quirk can depend on firmware version,
1806 		 * so, in principle, the set of quirks present can change
1807 		 * across a reset.  As a possible future enhancement, we
1808 		 * could re-scan for quirks every time we reinitialize
1809 		 * the device, but we'd have to make sure that the driver
1810 		 * behaves intelligently if the quirks change.
1811 		 */
1812 
1813 		int i;
1814 
1815 		for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1816 			if (quirk_matches(id, &core_quirks[i]))
1817 				ctrl->quirks |= core_quirks[i].quirks;
1818 		}
1819 	}
1820 
1821 	if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1822 		dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1823 		ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1824 	}
1825 
1826 	ctrl->oacs = le16_to_cpu(id->oacs);
1827 	ctrl->vid = le16_to_cpu(id->vid);
1828 	ctrl->oncs = le16_to_cpup(&id->oncs);
1829 	atomic_set(&ctrl->abort_limit, id->acl + 1);
1830 	ctrl->vwc = id->vwc;
1831 	ctrl->cntlid = le16_to_cpup(&id->cntlid);
1832 	memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1833 	memcpy(ctrl->model, id->mn, sizeof(id->mn));
1834 	memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1835 	if (id->mdts)
1836 		max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1837 	else
1838 		max_hw_sectors = UINT_MAX;
1839 	ctrl->max_hw_sectors =
1840 		min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1841 
1842 	nvme_set_queue_limits(ctrl, ctrl->admin_q);
1843 	ctrl->sgls = le32_to_cpu(id->sgls);
1844 	ctrl->kas = le16_to_cpu(id->kas);
1845 
1846 	if (id->rtd3e) {
1847 		/* us -> s */
1848 		u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
1849 
1850 		ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
1851 						 shutdown_timeout, 60);
1852 
1853 		if (ctrl->shutdown_timeout != shutdown_timeout)
1854 			dev_warn(ctrl->device,
1855 				 "Shutdown timeout set to %u seconds\n",
1856 				 ctrl->shutdown_timeout);
1857 	} else
1858 		ctrl->shutdown_timeout = shutdown_timeout;
1859 
1860 	ctrl->npss = id->npss;
1861 	ctrl->apsta = id->apsta;
1862 	prev_apst_enabled = ctrl->apst_enabled;
1863 	if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1864 		if (force_apst && id->apsta) {
1865 			dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1866 			ctrl->apst_enabled = true;
1867 		} else {
1868 			ctrl->apst_enabled = false;
1869 		}
1870 	} else {
1871 		ctrl->apst_enabled = id->apsta;
1872 	}
1873 	memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1874 
1875 	if (ctrl->ops->flags & NVME_F_FABRICS) {
1876 		ctrl->icdoff = le16_to_cpu(id->icdoff);
1877 		ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1878 		ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1879 		ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1880 
1881 		/*
1882 		 * In fabrics we need to verify the cntlid matches the
1883 		 * admin connect
1884 		 */
1885 		if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
1886 			ret = -EINVAL;
1887 			goto out_free;
1888 		}
1889 
1890 		if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1891 			dev_err(ctrl->device,
1892 				"keep-alive support is mandatory for fabrics\n");
1893 			ret = -EINVAL;
1894 			goto out_free;
1895 		}
1896 	} else {
1897 		ctrl->cntlid = le16_to_cpu(id->cntlid);
1898 		ctrl->hmpre = le32_to_cpu(id->hmpre);
1899 		ctrl->hmmin = le32_to_cpu(id->hmmin);
1900 		ctrl->hmminds = le32_to_cpu(id->hmminds);
1901 		ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
1902 	}
1903 
1904 	kfree(id);
1905 
1906 	if (ctrl->apst_enabled && !prev_apst_enabled)
1907 		dev_pm_qos_expose_latency_tolerance(ctrl->device);
1908 	else if (!ctrl->apst_enabled && prev_apst_enabled)
1909 		dev_pm_qos_hide_latency_tolerance(ctrl->device);
1910 
1911 	ret = nvme_configure_apst(ctrl);
1912 	if (ret < 0)
1913 		return ret;
1914 
1915 	ret = nvme_configure_timestamp(ctrl);
1916 	if (ret < 0)
1917 		return ret;
1918 
1919 	ret = nvme_configure_directives(ctrl);
1920 	if (ret < 0)
1921 		return ret;
1922 
1923 	ctrl->identified = true;
1924 
1925 	return 0;
1926 
1927 out_free:
1928 	kfree(id);
1929 	return ret;
1930 }
1931 EXPORT_SYMBOL_GPL(nvme_init_identify);
1932 
1933 static int nvme_dev_open(struct inode *inode, struct file *file)
1934 {
1935 	struct nvme_ctrl *ctrl;
1936 	int instance = iminor(inode);
1937 	int ret = -ENODEV;
1938 
1939 	spin_lock(&dev_list_lock);
1940 	list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1941 		if (ctrl->instance != instance)
1942 			continue;
1943 
1944 		if (!ctrl->admin_q) {
1945 			ret = -EWOULDBLOCK;
1946 			break;
1947 		}
1948 		if (!kref_get_unless_zero(&ctrl->kref))
1949 			break;
1950 		file->private_data = ctrl;
1951 		ret = 0;
1952 		break;
1953 	}
1954 	spin_unlock(&dev_list_lock);
1955 
1956 	return ret;
1957 }
1958 
1959 static int nvme_dev_release(struct inode *inode, struct file *file)
1960 {
1961 	nvme_put_ctrl(file->private_data);
1962 	return 0;
1963 }
1964 
1965 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1966 {
1967 	struct nvme_ns *ns;
1968 	int ret;
1969 
1970 	mutex_lock(&ctrl->namespaces_mutex);
1971 	if (list_empty(&ctrl->namespaces)) {
1972 		ret = -ENOTTY;
1973 		goto out_unlock;
1974 	}
1975 
1976 	ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1977 	if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1978 		dev_warn(ctrl->device,
1979 			"NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1980 		ret = -EINVAL;
1981 		goto out_unlock;
1982 	}
1983 
1984 	dev_warn(ctrl->device,
1985 		"using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1986 	kref_get(&ns->kref);
1987 	mutex_unlock(&ctrl->namespaces_mutex);
1988 
1989 	ret = nvme_user_cmd(ctrl, ns, argp);
1990 	nvme_put_ns(ns);
1991 	return ret;
1992 
1993 out_unlock:
1994 	mutex_unlock(&ctrl->namespaces_mutex);
1995 	return ret;
1996 }
1997 
1998 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1999 		unsigned long arg)
2000 {
2001 	struct nvme_ctrl *ctrl = file->private_data;
2002 	void __user *argp = (void __user *)arg;
2003 
2004 	switch (cmd) {
2005 	case NVME_IOCTL_ADMIN_CMD:
2006 		return nvme_user_cmd(ctrl, NULL, argp);
2007 	case NVME_IOCTL_IO_CMD:
2008 		return nvme_dev_user_cmd(ctrl, argp);
2009 	case NVME_IOCTL_RESET:
2010 		dev_warn(ctrl->device, "resetting controller\n");
2011 		return nvme_reset_ctrl_sync(ctrl);
2012 	case NVME_IOCTL_SUBSYS_RESET:
2013 		return nvme_reset_subsystem(ctrl);
2014 	case NVME_IOCTL_RESCAN:
2015 		nvme_queue_scan(ctrl);
2016 		return 0;
2017 	default:
2018 		return -ENOTTY;
2019 	}
2020 }
2021 
2022 static const struct file_operations nvme_dev_fops = {
2023 	.owner		= THIS_MODULE,
2024 	.open		= nvme_dev_open,
2025 	.release	= nvme_dev_release,
2026 	.unlocked_ioctl	= nvme_dev_ioctl,
2027 	.compat_ioctl	= nvme_dev_ioctl,
2028 };
2029 
2030 static ssize_t nvme_sysfs_reset(struct device *dev,
2031 				struct device_attribute *attr, const char *buf,
2032 				size_t count)
2033 {
2034 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2035 	int ret;
2036 
2037 	ret = nvme_reset_ctrl_sync(ctrl);
2038 	if (ret < 0)
2039 		return ret;
2040 	return count;
2041 }
2042 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2043 
2044 static ssize_t nvme_sysfs_rescan(struct device *dev,
2045 				struct device_attribute *attr, const char *buf,
2046 				size_t count)
2047 {
2048 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2049 
2050 	nvme_queue_scan(ctrl);
2051 	return count;
2052 }
2053 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2054 
2055 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2056 								char *buf)
2057 {
2058 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2059 	struct nvme_ctrl *ctrl = ns->ctrl;
2060 	int serial_len = sizeof(ctrl->serial);
2061 	int model_len = sizeof(ctrl->model);
2062 
2063 	if (!uuid_is_null(&ns->uuid))
2064 		return sprintf(buf, "uuid.%pU\n", &ns->uuid);
2065 
2066 	if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2067 		return sprintf(buf, "eui.%16phN\n", ns->nguid);
2068 
2069 	if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2070 		return sprintf(buf, "eui.%8phN\n", ns->eui);
2071 
2072 	while (serial_len > 0 && (ctrl->serial[serial_len - 1] == ' ' ||
2073 				  ctrl->serial[serial_len - 1] == '\0'))
2074 		serial_len--;
2075 	while (model_len > 0 && (ctrl->model[model_len - 1] == ' ' ||
2076 				 ctrl->model[model_len - 1] == '\0'))
2077 		model_len--;
2078 
2079 	return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
2080 		serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
2081 }
2082 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
2083 
2084 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2085 			  char *buf)
2086 {
2087 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2088 	return sprintf(buf, "%pU\n", ns->nguid);
2089 }
2090 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
2091 
2092 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2093 								char *buf)
2094 {
2095 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2096 
2097 	/* For backward compatibility expose the NGUID to userspace if
2098 	 * we have no UUID set
2099 	 */
2100 	if (uuid_is_null(&ns->uuid)) {
2101 		printk_ratelimited(KERN_WARNING
2102 				   "No UUID available providing old NGUID\n");
2103 		return sprintf(buf, "%pU\n", ns->nguid);
2104 	}
2105 	return sprintf(buf, "%pU\n", &ns->uuid);
2106 }
2107 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
2108 
2109 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2110 								char *buf)
2111 {
2112 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2113 	return sprintf(buf, "%8phd\n", ns->eui);
2114 }
2115 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
2116 
2117 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2118 								char *buf)
2119 {
2120 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2121 	return sprintf(buf, "%d\n", ns->ns_id);
2122 }
2123 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
2124 
2125 static struct attribute *nvme_ns_attrs[] = {
2126 	&dev_attr_wwid.attr,
2127 	&dev_attr_uuid.attr,
2128 	&dev_attr_nguid.attr,
2129 	&dev_attr_eui.attr,
2130 	&dev_attr_nsid.attr,
2131 	NULL,
2132 };
2133 
2134 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2135 		struct attribute *a, int n)
2136 {
2137 	struct device *dev = container_of(kobj, struct device, kobj);
2138 	struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2139 
2140 	if (a == &dev_attr_uuid.attr) {
2141 		if (uuid_is_null(&ns->uuid) ||
2142 		    !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2143 			return 0;
2144 	}
2145 	if (a == &dev_attr_nguid.attr) {
2146 		if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2147 			return 0;
2148 	}
2149 	if (a == &dev_attr_eui.attr) {
2150 		if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2151 			return 0;
2152 	}
2153 	return a->mode;
2154 }
2155 
2156 static const struct attribute_group nvme_ns_attr_group = {
2157 	.attrs		= nvme_ns_attrs,
2158 	.is_visible	= nvme_ns_attrs_are_visible,
2159 };
2160 
2161 #define nvme_show_str_function(field)						\
2162 static ssize_t  field##_show(struct device *dev,				\
2163 			    struct device_attribute *attr, char *buf)		\
2164 {										\
2165         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);				\
2166         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);	\
2167 }										\
2168 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2169 
2170 #define nvme_show_int_function(field)						\
2171 static ssize_t  field##_show(struct device *dev,				\
2172 			    struct device_attribute *attr, char *buf)		\
2173 {										\
2174         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);				\
2175         return sprintf(buf, "%d\n", ctrl->field);	\
2176 }										\
2177 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2178 
2179 nvme_show_str_function(model);
2180 nvme_show_str_function(serial);
2181 nvme_show_str_function(firmware_rev);
2182 nvme_show_int_function(cntlid);
2183 
2184 static ssize_t nvme_sysfs_delete(struct device *dev,
2185 				struct device_attribute *attr, const char *buf,
2186 				size_t count)
2187 {
2188 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2189 
2190 	if (device_remove_file_self(dev, attr))
2191 		ctrl->ops->delete_ctrl(ctrl);
2192 	return count;
2193 }
2194 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2195 
2196 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2197 					 struct device_attribute *attr,
2198 					 char *buf)
2199 {
2200 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2201 
2202 	return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2203 }
2204 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2205 
2206 static ssize_t nvme_sysfs_show_state(struct device *dev,
2207 				     struct device_attribute *attr,
2208 				     char *buf)
2209 {
2210 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2211 	static const char *const state_name[] = {
2212 		[NVME_CTRL_NEW]		= "new",
2213 		[NVME_CTRL_LIVE]	= "live",
2214 		[NVME_CTRL_RESETTING]	= "resetting",
2215 		[NVME_CTRL_RECONNECTING]= "reconnecting",
2216 		[NVME_CTRL_DELETING]	= "deleting",
2217 		[NVME_CTRL_DEAD]	= "dead",
2218 	};
2219 
2220 	if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2221 	    state_name[ctrl->state])
2222 		return sprintf(buf, "%s\n", state_name[ctrl->state]);
2223 
2224 	return sprintf(buf, "unknown state\n");
2225 }
2226 
2227 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2228 
2229 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2230 					 struct device_attribute *attr,
2231 					 char *buf)
2232 {
2233 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2234 
2235 	return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subnqn);
2236 }
2237 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2238 
2239 static ssize_t nvme_sysfs_show_address(struct device *dev,
2240 					 struct device_attribute *attr,
2241 					 char *buf)
2242 {
2243 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2244 
2245 	return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2246 }
2247 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2248 
2249 static struct attribute *nvme_dev_attrs[] = {
2250 	&dev_attr_reset_controller.attr,
2251 	&dev_attr_rescan_controller.attr,
2252 	&dev_attr_model.attr,
2253 	&dev_attr_serial.attr,
2254 	&dev_attr_firmware_rev.attr,
2255 	&dev_attr_cntlid.attr,
2256 	&dev_attr_delete_controller.attr,
2257 	&dev_attr_transport.attr,
2258 	&dev_attr_subsysnqn.attr,
2259 	&dev_attr_address.attr,
2260 	&dev_attr_state.attr,
2261 	NULL
2262 };
2263 
2264 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2265 		struct attribute *a, int n)
2266 {
2267 	struct device *dev = container_of(kobj, struct device, kobj);
2268 	struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2269 
2270 	if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2271 		return 0;
2272 	if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2273 		return 0;
2274 
2275 	return a->mode;
2276 }
2277 
2278 static struct attribute_group nvme_dev_attrs_group = {
2279 	.attrs		= nvme_dev_attrs,
2280 	.is_visible	= nvme_dev_attrs_are_visible,
2281 };
2282 
2283 static const struct attribute_group *nvme_dev_attr_groups[] = {
2284 	&nvme_dev_attrs_group,
2285 	NULL,
2286 };
2287 
2288 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2289 {
2290 	struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2291 	struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2292 
2293 	return nsa->ns_id - nsb->ns_id;
2294 }
2295 
2296 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2297 {
2298 	struct nvme_ns *ns, *ret = NULL;
2299 
2300 	mutex_lock(&ctrl->namespaces_mutex);
2301 	list_for_each_entry(ns, &ctrl->namespaces, list) {
2302 		if (ns->ns_id == nsid) {
2303 			kref_get(&ns->kref);
2304 			ret = ns;
2305 			break;
2306 		}
2307 		if (ns->ns_id > nsid)
2308 			break;
2309 	}
2310 	mutex_unlock(&ctrl->namespaces_mutex);
2311 	return ret;
2312 }
2313 
2314 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2315 {
2316 	struct streams_directive_params s;
2317 	int ret;
2318 
2319 	if (!ctrl->nr_streams)
2320 		return 0;
2321 
2322 	ret = nvme_get_stream_params(ctrl, &s, ns->ns_id);
2323 	if (ret)
2324 		return ret;
2325 
2326 	ns->sws = le32_to_cpu(s.sws);
2327 	ns->sgs = le16_to_cpu(s.sgs);
2328 
2329 	if (ns->sws) {
2330 		unsigned int bs = 1 << ns->lba_shift;
2331 
2332 		blk_queue_io_min(ns->queue, bs * ns->sws);
2333 		if (ns->sgs)
2334 			blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2335 	}
2336 
2337 	return 0;
2338 }
2339 
2340 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2341 {
2342 	struct nvme_ns *ns;
2343 	struct gendisk *disk;
2344 	struct nvme_id_ns *id;
2345 	char disk_name[DISK_NAME_LEN];
2346 	int node = dev_to_node(ctrl->dev);
2347 
2348 	ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2349 	if (!ns)
2350 		return;
2351 
2352 	ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2353 	if (ns->instance < 0)
2354 		goto out_free_ns;
2355 
2356 	ns->queue = blk_mq_init_queue(ctrl->tagset);
2357 	if (IS_ERR(ns->queue))
2358 		goto out_release_instance;
2359 	queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2360 	ns->queue->queuedata = ns;
2361 	ns->ctrl = ctrl;
2362 
2363 	kref_init(&ns->kref);
2364 	ns->ns_id = nsid;
2365 	ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2366 
2367 	blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2368 	nvme_set_queue_limits(ctrl, ns->queue);
2369 	nvme_setup_streams_ns(ctrl, ns);
2370 
2371 	sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2372 
2373 	id = nvme_identify_ns(ctrl, nsid);
2374 	if (!id)
2375 		goto out_free_queue;
2376 
2377 	if (id->ncap == 0)
2378 		goto out_free_id;
2379 
2380 	nvme_report_ns_ids(ctrl, ns->ns_id, id, ns->eui, ns->nguid, &ns->uuid);
2381 
2382 	if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
2383 		if (nvme_nvm_register(ns, disk_name, node)) {
2384 			dev_warn(ctrl->device, "LightNVM init failure\n");
2385 			goto out_free_id;
2386 		}
2387 	}
2388 
2389 	disk = alloc_disk_node(0, node);
2390 	if (!disk)
2391 		goto out_free_id;
2392 
2393 	disk->fops = &nvme_fops;
2394 	disk->private_data = ns;
2395 	disk->queue = ns->queue;
2396 	disk->flags = GENHD_FL_EXT_DEVT;
2397 	memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2398 	ns->disk = disk;
2399 
2400 	__nvme_revalidate_disk(disk, id);
2401 
2402 	mutex_lock(&ctrl->namespaces_mutex);
2403 	list_add_tail(&ns->list, &ctrl->namespaces);
2404 	mutex_unlock(&ctrl->namespaces_mutex);
2405 
2406 	kref_get(&ctrl->kref);
2407 
2408 	kfree(id);
2409 
2410 	device_add_disk(ctrl->device, ns->disk);
2411 	if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2412 					&nvme_ns_attr_group))
2413 		pr_warn("%s: failed to create sysfs group for identification\n",
2414 			ns->disk->disk_name);
2415 	if (ns->ndev && nvme_nvm_register_sysfs(ns))
2416 		pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2417 			ns->disk->disk_name);
2418 	return;
2419  out_free_id:
2420 	kfree(id);
2421  out_free_queue:
2422 	blk_cleanup_queue(ns->queue);
2423  out_release_instance:
2424 	ida_simple_remove(&ctrl->ns_ida, ns->instance);
2425  out_free_ns:
2426 	kfree(ns);
2427 }
2428 
2429 static void nvme_ns_remove(struct nvme_ns *ns)
2430 {
2431 	if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2432 		return;
2433 
2434 	if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2435 		if (blk_get_integrity(ns->disk))
2436 			blk_integrity_unregister(ns->disk);
2437 		sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2438 					&nvme_ns_attr_group);
2439 		if (ns->ndev)
2440 			nvme_nvm_unregister_sysfs(ns);
2441 		del_gendisk(ns->disk);
2442 		blk_cleanup_queue(ns->queue);
2443 	}
2444 
2445 	mutex_lock(&ns->ctrl->namespaces_mutex);
2446 	list_del_init(&ns->list);
2447 	mutex_unlock(&ns->ctrl->namespaces_mutex);
2448 
2449 	nvme_put_ns(ns);
2450 }
2451 
2452 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2453 {
2454 	struct nvme_ns *ns;
2455 
2456 	ns = nvme_find_get_ns(ctrl, nsid);
2457 	if (ns) {
2458 		if (ns->disk && revalidate_disk(ns->disk))
2459 			nvme_ns_remove(ns);
2460 		nvme_put_ns(ns);
2461 	} else
2462 		nvme_alloc_ns(ctrl, nsid);
2463 }
2464 
2465 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2466 					unsigned nsid)
2467 {
2468 	struct nvme_ns *ns, *next;
2469 
2470 	list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2471 		if (ns->ns_id > nsid)
2472 			nvme_ns_remove(ns);
2473 	}
2474 }
2475 
2476 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2477 {
2478 	struct nvme_ns *ns;
2479 	__le32 *ns_list;
2480 	unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2481 	int ret = 0;
2482 
2483 	ns_list = kzalloc(0x1000, GFP_KERNEL);
2484 	if (!ns_list)
2485 		return -ENOMEM;
2486 
2487 	for (i = 0; i < num_lists; i++) {
2488 		ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2489 		if (ret)
2490 			goto free;
2491 
2492 		for (j = 0; j < min(nn, 1024U); j++) {
2493 			nsid = le32_to_cpu(ns_list[j]);
2494 			if (!nsid)
2495 				goto out;
2496 
2497 			nvme_validate_ns(ctrl, nsid);
2498 
2499 			while (++prev < nsid) {
2500 				ns = nvme_find_get_ns(ctrl, prev);
2501 				if (ns) {
2502 					nvme_ns_remove(ns);
2503 					nvme_put_ns(ns);
2504 				}
2505 			}
2506 		}
2507 		nn -= j;
2508 	}
2509  out:
2510 	nvme_remove_invalid_namespaces(ctrl, prev);
2511  free:
2512 	kfree(ns_list);
2513 	return ret;
2514 }
2515 
2516 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2517 {
2518 	unsigned i;
2519 
2520 	for (i = 1; i <= nn; i++)
2521 		nvme_validate_ns(ctrl, i);
2522 
2523 	nvme_remove_invalid_namespaces(ctrl, nn);
2524 }
2525 
2526 static void nvme_scan_work(struct work_struct *work)
2527 {
2528 	struct nvme_ctrl *ctrl =
2529 		container_of(work, struct nvme_ctrl, scan_work);
2530 	struct nvme_id_ctrl *id;
2531 	unsigned nn;
2532 
2533 	if (ctrl->state != NVME_CTRL_LIVE)
2534 		return;
2535 
2536 	if (nvme_identify_ctrl(ctrl, &id))
2537 		return;
2538 
2539 	nn = le32_to_cpu(id->nn);
2540 	if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2541 	    !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2542 		if (!nvme_scan_ns_list(ctrl, nn))
2543 			goto done;
2544 	}
2545 	nvme_scan_ns_sequential(ctrl, nn);
2546  done:
2547 	mutex_lock(&ctrl->namespaces_mutex);
2548 	list_sort(NULL, &ctrl->namespaces, ns_cmp);
2549 	mutex_unlock(&ctrl->namespaces_mutex);
2550 	kfree(id);
2551 }
2552 
2553 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2554 {
2555 	/*
2556 	 * Do not queue new scan work when a controller is reset during
2557 	 * removal.
2558 	 */
2559 	if (ctrl->state == NVME_CTRL_LIVE)
2560 		queue_work(nvme_wq, &ctrl->scan_work);
2561 }
2562 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2563 
2564 /*
2565  * This function iterates the namespace list unlocked to allow recovery from
2566  * controller failure. It is up to the caller to ensure the namespace list is
2567  * not modified by scan work while this function is executing.
2568  */
2569 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2570 {
2571 	struct nvme_ns *ns, *next;
2572 
2573 	/*
2574 	 * The dead states indicates the controller was not gracefully
2575 	 * disconnected. In that case, we won't be able to flush any data while
2576 	 * removing the namespaces' disks; fail all the queues now to avoid
2577 	 * potentially having to clean up the failed sync later.
2578 	 */
2579 	if (ctrl->state == NVME_CTRL_DEAD)
2580 		nvme_kill_queues(ctrl);
2581 
2582 	list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2583 		nvme_ns_remove(ns);
2584 }
2585 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2586 
2587 static void nvme_async_event_work(struct work_struct *work)
2588 {
2589 	struct nvme_ctrl *ctrl =
2590 		container_of(work, struct nvme_ctrl, async_event_work);
2591 
2592 	spin_lock_irq(&ctrl->lock);
2593 	while (ctrl->event_limit > 0) {
2594 		int aer_idx = --ctrl->event_limit;
2595 
2596 		spin_unlock_irq(&ctrl->lock);
2597 		ctrl->ops->submit_async_event(ctrl, aer_idx);
2598 		spin_lock_irq(&ctrl->lock);
2599 	}
2600 	spin_unlock_irq(&ctrl->lock);
2601 }
2602 
2603 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
2604 {
2605 
2606 	u32 csts;
2607 
2608 	if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
2609 		return false;
2610 
2611 	if (csts == ~0)
2612 		return false;
2613 
2614 	return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
2615 }
2616 
2617 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
2618 {
2619 	struct nvme_command c = { };
2620 	struct nvme_fw_slot_info_log *log;
2621 
2622 	log = kmalloc(sizeof(*log), GFP_KERNEL);
2623 	if (!log)
2624 		return;
2625 
2626 	c.common.opcode = nvme_admin_get_log_page;
2627 	c.common.nsid = cpu_to_le32(NVME_NSID_ALL);
2628 	c.common.cdw10[0] = nvme_get_log_dw10(NVME_LOG_FW_SLOT, sizeof(*log));
2629 
2630 	if (!nvme_submit_sync_cmd(ctrl->admin_q, &c, log, sizeof(*log)))
2631 		dev_warn(ctrl->device,
2632 				"Get FW SLOT INFO log error\n");
2633 	kfree(log);
2634 }
2635 
2636 static void nvme_fw_act_work(struct work_struct *work)
2637 {
2638 	struct nvme_ctrl *ctrl = container_of(work,
2639 				struct nvme_ctrl, fw_act_work);
2640 	unsigned long fw_act_timeout;
2641 
2642 	if (ctrl->mtfa)
2643 		fw_act_timeout = jiffies +
2644 				msecs_to_jiffies(ctrl->mtfa * 100);
2645 	else
2646 		fw_act_timeout = jiffies +
2647 				msecs_to_jiffies(admin_timeout * 1000);
2648 
2649 	nvme_stop_queues(ctrl);
2650 	while (nvme_ctrl_pp_status(ctrl)) {
2651 		if (time_after(jiffies, fw_act_timeout)) {
2652 			dev_warn(ctrl->device,
2653 				"Fw activation timeout, reset controller\n");
2654 			nvme_reset_ctrl(ctrl);
2655 			break;
2656 		}
2657 		msleep(100);
2658 	}
2659 
2660 	if (ctrl->state != NVME_CTRL_LIVE)
2661 		return;
2662 
2663 	nvme_start_queues(ctrl);
2664 	/* read FW slot informationi to clear the AER*/
2665 	nvme_get_fw_slot_info(ctrl);
2666 }
2667 
2668 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2669 		union nvme_result *res)
2670 {
2671 	u32 result = le32_to_cpu(res->u32);
2672 	bool done = true;
2673 
2674 	switch (le16_to_cpu(status) >> 1) {
2675 	case NVME_SC_SUCCESS:
2676 		done = false;
2677 		/*FALLTHRU*/
2678 	case NVME_SC_ABORT_REQ:
2679 		++ctrl->event_limit;
2680 		queue_work(nvme_wq, &ctrl->async_event_work);
2681 		break;
2682 	default:
2683 		break;
2684 	}
2685 
2686 	if (done)
2687 		return;
2688 
2689 	switch (result & 0xff07) {
2690 	case NVME_AER_NOTICE_NS_CHANGED:
2691 		dev_info(ctrl->device, "rescanning\n");
2692 		nvme_queue_scan(ctrl);
2693 		break;
2694 	case NVME_AER_NOTICE_FW_ACT_STARTING:
2695 		schedule_work(&ctrl->fw_act_work);
2696 		break;
2697 	default:
2698 		dev_warn(ctrl->device, "async event result %08x\n", result);
2699 	}
2700 }
2701 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2702 
2703 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2704 {
2705 	ctrl->event_limit = NVME_NR_AERS;
2706 	queue_work(nvme_wq, &ctrl->async_event_work);
2707 }
2708 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2709 
2710 static DEFINE_IDA(nvme_instance_ida);
2711 
2712 static int nvme_set_instance(struct nvme_ctrl *ctrl)
2713 {
2714 	int instance, error;
2715 
2716 	do {
2717 		if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2718 			return -ENODEV;
2719 
2720 		spin_lock(&dev_list_lock);
2721 		error = ida_get_new(&nvme_instance_ida, &instance);
2722 		spin_unlock(&dev_list_lock);
2723 	} while (error == -EAGAIN);
2724 
2725 	if (error)
2726 		return -ENODEV;
2727 
2728 	ctrl->instance = instance;
2729 	return 0;
2730 }
2731 
2732 static void nvme_release_instance(struct nvme_ctrl *ctrl)
2733 {
2734 	spin_lock(&dev_list_lock);
2735 	ida_remove(&nvme_instance_ida, ctrl->instance);
2736 	spin_unlock(&dev_list_lock);
2737 }
2738 
2739 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
2740 {
2741 	nvme_stop_keep_alive(ctrl);
2742 	flush_work(&ctrl->async_event_work);
2743 	flush_work(&ctrl->scan_work);
2744 	cancel_work_sync(&ctrl->fw_act_work);
2745 }
2746 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
2747 
2748 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
2749 {
2750 	if (ctrl->kato)
2751 		nvme_start_keep_alive(ctrl);
2752 
2753 	if (ctrl->queue_count > 1) {
2754 		nvme_queue_scan(ctrl);
2755 		nvme_queue_async_events(ctrl);
2756 		nvme_start_queues(ctrl);
2757 	}
2758 }
2759 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
2760 
2761 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2762 {
2763 	device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
2764 
2765 	spin_lock(&dev_list_lock);
2766 	list_del(&ctrl->node);
2767 	spin_unlock(&dev_list_lock);
2768 }
2769 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2770 
2771 static void nvme_free_ctrl(struct kref *kref)
2772 {
2773 	struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
2774 
2775 	put_device(ctrl->device);
2776 	nvme_release_instance(ctrl);
2777 	ida_destroy(&ctrl->ns_ida);
2778 
2779 	ctrl->ops->free_ctrl(ctrl);
2780 }
2781 
2782 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2783 {
2784 	kref_put(&ctrl->kref, nvme_free_ctrl);
2785 }
2786 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
2787 
2788 /*
2789  * Initialize a NVMe controller structures.  This needs to be called during
2790  * earliest initialization so that we have the initialized structured around
2791  * during probing.
2792  */
2793 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2794 		const struct nvme_ctrl_ops *ops, unsigned long quirks)
2795 {
2796 	int ret;
2797 
2798 	ctrl->state = NVME_CTRL_NEW;
2799 	spin_lock_init(&ctrl->lock);
2800 	INIT_LIST_HEAD(&ctrl->namespaces);
2801 	mutex_init(&ctrl->namespaces_mutex);
2802 	kref_init(&ctrl->kref);
2803 	ctrl->dev = dev;
2804 	ctrl->ops = ops;
2805 	ctrl->quirks = quirks;
2806 	INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2807 	INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2808 	INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
2809 
2810 	ret = nvme_set_instance(ctrl);
2811 	if (ret)
2812 		goto out;
2813 
2814 	ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2815 				MKDEV(nvme_char_major, ctrl->instance),
2816 				ctrl, nvme_dev_attr_groups,
2817 				"nvme%d", ctrl->instance);
2818 	if (IS_ERR(ctrl->device)) {
2819 		ret = PTR_ERR(ctrl->device);
2820 		goto out_release_instance;
2821 	}
2822 	get_device(ctrl->device);
2823 	ida_init(&ctrl->ns_ida);
2824 
2825 	spin_lock(&dev_list_lock);
2826 	list_add_tail(&ctrl->node, &nvme_ctrl_list);
2827 	spin_unlock(&dev_list_lock);
2828 
2829 	/*
2830 	 * Initialize latency tolerance controls.  The sysfs files won't
2831 	 * be visible to userspace unless the device actually supports APST.
2832 	 */
2833 	ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2834 	dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2835 		min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2836 
2837 	return 0;
2838 out_release_instance:
2839 	nvme_release_instance(ctrl);
2840 out:
2841 	return ret;
2842 }
2843 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2844 
2845 /**
2846  * nvme_kill_queues(): Ends all namespace queues
2847  * @ctrl: the dead controller that needs to end
2848  *
2849  * Call this function when the driver determines it is unable to get the
2850  * controller in a state capable of servicing IO.
2851  */
2852 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2853 {
2854 	struct nvme_ns *ns;
2855 
2856 	mutex_lock(&ctrl->namespaces_mutex);
2857 
2858 	/* Forcibly unquiesce queues to avoid blocking dispatch */
2859 	if (ctrl->admin_q)
2860 		blk_mq_unquiesce_queue(ctrl->admin_q);
2861 
2862 	list_for_each_entry(ns, &ctrl->namespaces, list) {
2863 		/*
2864 		 * Revalidating a dead namespace sets capacity to 0. This will
2865 		 * end buffered writers dirtying pages that can't be synced.
2866 		 */
2867 		if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2868 			continue;
2869 		revalidate_disk(ns->disk);
2870 		blk_set_queue_dying(ns->queue);
2871 
2872 		/* Forcibly unquiesce queues to avoid blocking dispatch */
2873 		blk_mq_unquiesce_queue(ns->queue);
2874 	}
2875 	mutex_unlock(&ctrl->namespaces_mutex);
2876 }
2877 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2878 
2879 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2880 {
2881 	struct nvme_ns *ns;
2882 
2883 	mutex_lock(&ctrl->namespaces_mutex);
2884 	list_for_each_entry(ns, &ctrl->namespaces, list)
2885 		blk_mq_unfreeze_queue(ns->queue);
2886 	mutex_unlock(&ctrl->namespaces_mutex);
2887 }
2888 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2889 
2890 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2891 {
2892 	struct nvme_ns *ns;
2893 
2894 	mutex_lock(&ctrl->namespaces_mutex);
2895 	list_for_each_entry(ns, &ctrl->namespaces, list) {
2896 		timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2897 		if (timeout <= 0)
2898 			break;
2899 	}
2900 	mutex_unlock(&ctrl->namespaces_mutex);
2901 }
2902 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2903 
2904 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2905 {
2906 	struct nvme_ns *ns;
2907 
2908 	mutex_lock(&ctrl->namespaces_mutex);
2909 	list_for_each_entry(ns, &ctrl->namespaces, list)
2910 		blk_mq_freeze_queue_wait(ns->queue);
2911 	mutex_unlock(&ctrl->namespaces_mutex);
2912 }
2913 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2914 
2915 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2916 {
2917 	struct nvme_ns *ns;
2918 
2919 	mutex_lock(&ctrl->namespaces_mutex);
2920 	list_for_each_entry(ns, &ctrl->namespaces, list)
2921 		blk_freeze_queue_start(ns->queue);
2922 	mutex_unlock(&ctrl->namespaces_mutex);
2923 }
2924 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2925 
2926 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2927 {
2928 	struct nvme_ns *ns;
2929 
2930 	mutex_lock(&ctrl->namespaces_mutex);
2931 	list_for_each_entry(ns, &ctrl->namespaces, list)
2932 		blk_mq_quiesce_queue(ns->queue);
2933 	mutex_unlock(&ctrl->namespaces_mutex);
2934 }
2935 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2936 
2937 void nvme_start_queues(struct nvme_ctrl *ctrl)
2938 {
2939 	struct nvme_ns *ns;
2940 
2941 	mutex_lock(&ctrl->namespaces_mutex);
2942 	list_for_each_entry(ns, &ctrl->namespaces, list)
2943 		blk_mq_unquiesce_queue(ns->queue);
2944 	mutex_unlock(&ctrl->namespaces_mutex);
2945 }
2946 EXPORT_SYMBOL_GPL(nvme_start_queues);
2947 
2948 int __init nvme_core_init(void)
2949 {
2950 	int result;
2951 
2952 	nvme_wq = alloc_workqueue("nvme-wq",
2953 			WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2954 	if (!nvme_wq)
2955 		return -ENOMEM;
2956 
2957 	result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2958 							&nvme_dev_fops);
2959 	if (result < 0)
2960 		goto destroy_wq;
2961 	else if (result > 0)
2962 		nvme_char_major = result;
2963 
2964 	nvme_class = class_create(THIS_MODULE, "nvme");
2965 	if (IS_ERR(nvme_class)) {
2966 		result = PTR_ERR(nvme_class);
2967 		goto unregister_chrdev;
2968 	}
2969 
2970 	return 0;
2971 
2972 unregister_chrdev:
2973 	__unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2974 destroy_wq:
2975 	destroy_workqueue(nvme_wq);
2976 	return result;
2977 }
2978 
2979 void nvme_core_exit(void)
2980 {
2981 	class_destroy(nvme_class);
2982 	__unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2983 	destroy_workqueue(nvme_wq);
2984 }
2985 
2986 MODULE_LICENSE("GPL");
2987 MODULE_VERSION("1.0");
2988 module_init(nvme_core_init);
2989 module_exit(nvme_core_exit);
2990