xref: /linux/drivers/nvme/host/pci.c (revision bd7b7ce96db4487bb77692a85ee4489fd2c395df)
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/acpi.h>
8 #include <linux/async.h>
9 #include <linux/blkdev.h>
10 #include <linux/blk-mq-dma.h>
11 #include <linux/blk-integrity.h>
12 #include <linux/dmi.h>
13 #include <linux/init.h>
14 #include <linux/interrupt.h>
15 #include <linux/io.h>
16 #include <linux/kstrtox.h>
17 #include <linux/memremap.h>
18 #include <linux/mm.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/nodemask.h>
22 #include <linux/once.h>
23 #include <linux/pci.h>
24 #include <linux/suspend.h>
25 #include <linux/t10-pi.h>
26 #include <linux/types.h>
27 #include <linux/io-64-nonatomic-lo-hi.h>
28 #include <linux/io-64-nonatomic-hi-lo.h>
29 #include <linux/sed-opal.h>
30 
31 #include "trace.h"
32 #include "nvme.h"
33 
34 #define SQ_SIZE(q)	((q)->q_depth << (q)->sqes)
35 #define CQ_SIZE(q)	((q)->q_depth * sizeof(struct nvme_completion))
36 
37 /* Optimisation for I/Os between 4k and 128k */
38 #define NVME_SMALL_POOL_SIZE	256
39 
40 /*
41  * Arbitrary upper bound.
42  */
43 #define NVME_MAX_BYTES		SZ_8M
44 #define NVME_MAX_NR_DESCRIPTORS	5
45 
46 /*
47  * For data SGLs we support a single descriptors worth of SGL entries.
48  * For PRPs, segments don't matter at all.
49  */
50 #define NVME_MAX_SEGS \
51 	(NVME_CTRL_PAGE_SIZE / sizeof(struct nvme_sgl_desc))
52 
53 /*
54  * For metadata SGLs, only the small descriptor is supported, and the first
55  * entry is the segment descriptor, which for the data pointer sits in the SQE.
56  */
57 #define NVME_MAX_META_SEGS \
58 	((NVME_SMALL_POOL_SIZE / sizeof(struct nvme_sgl_desc)) - 1)
59 
60 /*
61  * The last entry is used to link to the next descriptor.
62  */
63 #define PRPS_PER_PAGE \
64 	(((NVME_CTRL_PAGE_SIZE / sizeof(__le64))) - 1)
65 
66 /*
67  * I/O could be non-aligned both at the beginning and end.
68  */
69 #define MAX_PRP_RANGE \
70 	(NVME_MAX_BYTES + 2 * (NVME_CTRL_PAGE_SIZE - 1))
71 
72 static_assert(MAX_PRP_RANGE / NVME_CTRL_PAGE_SIZE <=
73 	(1 /* prp1 */ + NVME_MAX_NR_DESCRIPTORS * PRPS_PER_PAGE));
74 
75 struct quirk_entry {
76 	u16 vendor_id;
77 	u16 dev_id;
78 	u32 enabled_quirks;
79 	u32 disabled_quirks;
80 };
81 
82 static int use_threaded_interrupts;
83 module_param(use_threaded_interrupts, int, 0444);
84 
85 static bool use_cmb_sqes = true;
86 module_param(use_cmb_sqes, bool, 0444);
87 MODULE_PARM_DESC(use_cmb_sqes, "use controller's memory buffer for I/O SQes");
88 
89 static unsigned int max_host_mem_size_mb = 128;
90 module_param(max_host_mem_size_mb, uint, 0444);
91 MODULE_PARM_DESC(max_host_mem_size_mb,
92 	"Maximum Host Memory Buffer (HMB) size per controller (in MiB)");
93 
94 static unsigned int sgl_threshold = SZ_32K;
95 module_param(sgl_threshold, uint, 0644);
96 MODULE_PARM_DESC(sgl_threshold,
97 		"Use SGLs when average request segment size is larger or equal to "
98 		"this size. Use 0 to disable SGLs.");
99 
100 #define NVME_PCI_MIN_QUEUE_SIZE 2
101 #define NVME_PCI_MAX_QUEUE_SIZE 4095
102 static int io_queue_depth_set(const char *val, const struct kernel_param *kp);
103 static const struct kernel_param_ops io_queue_depth_ops = {
104 	.set = io_queue_depth_set,
105 	.get = param_get_uint,
106 };
107 
108 static unsigned int io_queue_depth = 1024;
109 module_param_cb(io_queue_depth, &io_queue_depth_ops, &io_queue_depth, 0644);
110 MODULE_PARM_DESC(io_queue_depth, "set io queue depth, should >= 2 and < 4096");
111 
112 static struct quirk_entry *nvme_pci_quirk_list;
113 static unsigned int nvme_pci_quirk_count;
114 
115 /* Helper to parse individual quirk names */
116 static int nvme_parse_quirk_names(char *quirk_str, struct quirk_entry *entry)
117 {
118 	int i;
119 	size_t field_len;
120 	bool disabled, found;
121 	char *p = quirk_str, *field;
122 
123 	while ((field = strsep(&p, ",")) && *field) {
124 		disabled = false;
125 		found = false;
126 
127 		if (*field == '^') {
128 			/* Skip the '^' character */
129 			disabled = true;
130 			field++;
131 		}
132 
133 		field_len = strlen(field);
134 		for (i = 0; i < 32; i++) {
135 			unsigned int bit = 1U << i;
136 			char *q_name = nvme_quirk_name(bit);
137 			size_t q_len = strlen(q_name);
138 
139 			if (!strcmp(q_name, "unknown"))
140 				break;
141 
142 			if (!strcmp(q_name, field) &&
143 				    q_len == field_len) {
144 				if (disabled)
145 					entry->disabled_quirks |= bit;
146 				else
147 					entry->enabled_quirks |= bit;
148 				found = true;
149 				break;
150 			}
151 		}
152 
153 		if (!found) {
154 			pr_err("nvme: unrecognized quirk %s\n", field);
155 			return -EINVAL;
156 		}
157 	}
158 	return 0;
159 }
160 
161 /* Helper to parse a single VID:DID:quirk_names entry */
162 static int nvme_parse_quirk_entry(char *s, struct quirk_entry *entry)
163 {
164 	char *field;
165 
166 	field = strsep(&s, ":");
167 	if (!field || kstrtou16(field, 16, &entry->vendor_id))
168 		return -EINVAL;
169 
170 	field = strsep(&s, ":");
171 	if (!field || kstrtou16(field, 16, &entry->dev_id))
172 		return -EINVAL;
173 
174 	field = strsep(&s, ":");
175 	if (!field)
176 		return -EINVAL;
177 
178 	return nvme_parse_quirk_names(field, entry);
179 }
180 
181 static int quirks_param_set(const char *value, const struct kernel_param *kp)
182 {
183 	int count, err, i;
184 	struct quirk_entry *qlist;
185 	char *field, *val, *sep_ptr;
186 
187 	err = param_set_copystring(value, kp);
188 	if (err)
189 		return err;
190 
191 	val = kstrdup(value, GFP_KERNEL);
192 	if (!val)
193 		return -ENOMEM;
194 
195 	if (!*val)
196 		goto out_free_val;
197 
198 	count = 1;
199 	for (i = 0; val[i]; i++) {
200 		if (val[i] == '-')
201 			count++;
202 	}
203 
204 	qlist = kcalloc(count, sizeof(*qlist), GFP_KERNEL);
205 	if (!qlist) {
206 		err = -ENOMEM;
207 		goto out_free_val;
208 	}
209 
210 	i = 0;
211 	sep_ptr = val;
212 	while ((field = strsep(&sep_ptr, "-"))) {
213 		if (nvme_parse_quirk_entry(field, &qlist[i])) {
214 			pr_err("nvme: failed to parse quirk string %s\n",
215 				value);
216 			goto out_free_qlist;
217 		}
218 
219 		i++;
220 	}
221 
222 	kfree(nvme_pci_quirk_list);
223 	nvme_pci_quirk_count = count;
224 	nvme_pci_quirk_list  = qlist;
225 	goto out_free_val;
226 
227 out_free_qlist:
228 	kfree(qlist);
229 out_free_val:
230 	kfree(val);
231 	return err;
232 }
233 
234 static char quirks_param[128];
235 static const struct kernel_param_ops quirks_param_ops = {
236 	.set = quirks_param_set,
237 	.get = param_get_string,
238 };
239 
240 static struct kparam_string quirks_param_string = {
241 	.maxlen = sizeof(quirks_param),
242 	.string = quirks_param,
243 };
244 
245 module_param_cb(quirks, &quirks_param_ops, &quirks_param_string, 0444);
246 MODULE_PARM_DESC(quirks, "Enable/disable NVMe quirks by specifying "
247 						"quirks=VID:DID:quirk_names");
248 
249 static int io_queue_count_set(const char *val, const struct kernel_param *kp)
250 {
251 	unsigned int n;
252 	int ret;
253 
254 	ret = kstrtouint(val, 10, &n);
255 	if (ret != 0 || n > blk_mq_num_possible_queues(0))
256 		return -EINVAL;
257 	return param_set_uint(val, kp);
258 }
259 
260 static const struct kernel_param_ops io_queue_count_ops = {
261 	.set = io_queue_count_set,
262 	.get = param_get_uint,
263 };
264 
265 static unsigned int write_queues;
266 module_param_cb(write_queues, &io_queue_count_ops, &write_queues, 0644);
267 MODULE_PARM_DESC(write_queues,
268 	"Number of queues to use for writes. If not set, reads and writes "
269 	"will share a queue set.");
270 
271 static unsigned int poll_queues;
272 module_param_cb(poll_queues, &io_queue_count_ops, &poll_queues, 0644);
273 MODULE_PARM_DESC(poll_queues, "Number of queues to use for polled IO.");
274 
275 static bool noacpi;
276 module_param(noacpi, bool, 0444);
277 MODULE_PARM_DESC(noacpi, "disable acpi bios quirks");
278 
279 struct nvme_dev;
280 struct nvme_queue;
281 
282 static void nvme_dev_disable(struct nvme_dev *dev, bool shutdown);
283 static void nvme_delete_io_queues(struct nvme_dev *dev);
284 static void nvme_update_attrs(struct nvme_dev *dev);
285 
286 struct nvme_descriptor_pools {
287 	struct dma_pool *large;
288 	struct dma_pool *small;
289 };
290 
291 /*
292  * Represents an NVM Express device.  Each nvme_dev is a PCI function.
293  */
294 struct nvme_dev {
295 	struct nvme_queue *queues;
296 	struct blk_mq_tag_set tagset;
297 	struct blk_mq_tag_set admin_tagset;
298 	u32 __iomem *dbs;
299 	struct device *dev;
300 	unsigned online_queues;
301 	unsigned max_qid;
302 	unsigned io_queues[HCTX_MAX_TYPES];
303 	unsigned int num_vecs;
304 	u32 q_depth;
305 	int io_sqes;
306 	u32 db_stride;
307 	void __iomem *bar;
308 	unsigned long bar_mapped_size;
309 	struct mutex shutdown_lock;
310 	bool subsystem;
311 	u64 cmb_size;
312 	bool cmb_use_sqes;
313 	u32 cmbsz;
314 	u32 cmbloc;
315 	struct nvme_ctrl ctrl;
316 	u32 last_ps;
317 	bool hmb;
318 	struct sg_table *hmb_sgt;
319 	mempool_t *dmavec_mempool;
320 
321 	/* shadow doorbell buffer support: */
322 	__le32 *dbbuf_dbs;
323 	dma_addr_t dbbuf_dbs_dma_addr;
324 	__le32 *dbbuf_eis;
325 	dma_addr_t dbbuf_eis_dma_addr;
326 
327 	/* host memory buffer support: */
328 	u64 host_mem_size;
329 	u32 nr_host_mem_descs;
330 	u32 host_mem_descs_size;
331 	dma_addr_t host_mem_descs_dma;
332 	struct nvme_host_mem_buf_desc *host_mem_descs;
333 	void **host_mem_desc_bufs;
334 	unsigned int nr_allocated_queues;
335 	unsigned int nr_write_queues;
336 	unsigned int nr_poll_queues;
337 	struct nvme_descriptor_pools descriptor_pools[];
338 };
339 
340 static int io_queue_depth_set(const char *val, const struct kernel_param *kp)
341 {
342 	return param_set_uint_minmax(val, kp, NVME_PCI_MIN_QUEUE_SIZE,
343 			NVME_PCI_MAX_QUEUE_SIZE);
344 }
345 
346 static inline unsigned int sq_idx(unsigned int qid, u32 stride)
347 {
348 	return qid * 2 * stride;
349 }
350 
351 static inline unsigned int cq_idx(unsigned int qid, u32 stride)
352 {
353 	return (qid * 2 + 1) * stride;
354 }
355 
356 static inline struct nvme_dev *to_nvme_dev(struct nvme_ctrl *ctrl)
357 {
358 	return container_of(ctrl, struct nvme_dev, ctrl);
359 }
360 
361 /*
362  * An NVM Express queue.  Each device has at least two (one for admin
363  * commands and one for I/O commands).
364  */
365 struct nvme_queue {
366 	struct nvme_dev *dev;
367 	struct nvme_descriptor_pools descriptor_pools;
368 	spinlock_t sq_lock;
369 	void *sq_cmds;
370 	 /* only used for poll queues: */
371 	spinlock_t cq_poll_lock ____cacheline_aligned_in_smp;
372 	struct nvme_completion *cqes;
373 	dma_addr_t sq_dma_addr;
374 	dma_addr_t cq_dma_addr;
375 	u32 __iomem *q_db;
376 	u32 q_depth;
377 	u16 cq_vector;
378 	u16 sq_tail;
379 	u16 last_sq_tail;
380 	u16 cq_head;
381 	u16 qid;
382 	u8 cq_phase;
383 	u8 sqes;
384 	unsigned long flags;
385 #define NVMEQ_ENABLED		0
386 #define NVMEQ_SQ_CMB		1
387 #define NVMEQ_DELETE_ERROR	2
388 #define NVMEQ_POLLED		3
389 	__le32 *dbbuf_sq_db;
390 	__le32 *dbbuf_cq_db;
391 	__le32 *dbbuf_sq_ei;
392 	__le32 *dbbuf_cq_ei;
393 	struct completion delete_done;
394 };
395 
396 /* bits for iod->flags */
397 enum nvme_iod_flags {
398 	/* this command has been aborted by the timeout handler */
399 	IOD_ABORTED		= 1U << 0,
400 
401 	/* uses the small descriptor pool */
402 	IOD_SMALL_DESCRIPTOR	= 1U << 1,
403 
404 	/* single segment dma mapping */
405 	IOD_SINGLE_SEGMENT	= 1U << 2,
406 
407 	/* Data payload contains p2p memory */
408 	IOD_DATA_P2P		= 1U << 3,
409 
410 	/* Metadata contains p2p memory */
411 	IOD_META_P2P		= 1U << 4,
412 
413 	/* Data payload contains MMIO memory */
414 	IOD_DATA_MMIO		= 1U << 5,
415 
416 	/* Metadata contains MMIO memory */
417 	IOD_META_MMIO		= 1U << 6,
418 
419 	/* Metadata using non-coalesced MPTR */
420 	IOD_SINGLE_META_SEGMENT	= 1U << 7,
421 };
422 
423 struct nvme_dma_vec {
424 	dma_addr_t addr;
425 	unsigned int len;
426 };
427 
428 /*
429  * The nvme_iod describes the data in an I/O.
430  */
431 struct nvme_iod {
432 	struct nvme_request req;
433 	struct nvme_command cmd;
434 	u8 flags;
435 	u8 nr_descriptors;
436 
437 	size_t total_len;
438 	struct dma_iova_state dma_state;
439 	void *descriptors[NVME_MAX_NR_DESCRIPTORS];
440 	struct nvme_dma_vec *dma_vecs;
441 	unsigned int nr_dma_vecs;
442 
443 	dma_addr_t meta_dma;
444 	size_t meta_total_len;
445 	struct dma_iova_state meta_dma_state;
446 	struct nvme_sgl_desc *meta_descriptor;
447 };
448 
449 static inline unsigned int nvme_dbbuf_size(struct nvme_dev *dev)
450 {
451 	return dev->nr_allocated_queues * 8 * dev->db_stride;
452 }
453 
454 static void nvme_dbbuf_dma_alloc(struct nvme_dev *dev)
455 {
456 	unsigned int mem_size = nvme_dbbuf_size(dev);
457 
458 	if (!(dev->ctrl.oacs & NVME_CTRL_OACS_DBBUF_SUPP))
459 		return;
460 
461 	if (dev->dbbuf_dbs) {
462 		/*
463 		 * Clear the dbbuf memory so the driver doesn't observe stale
464 		 * values from the previous instantiation.
465 		 */
466 		memset(dev->dbbuf_dbs, 0, mem_size);
467 		memset(dev->dbbuf_eis, 0, mem_size);
468 		return;
469 	}
470 
471 	dev->dbbuf_dbs = dma_alloc_coherent(dev->dev, mem_size,
472 					    &dev->dbbuf_dbs_dma_addr,
473 					    GFP_KERNEL);
474 	if (!dev->dbbuf_dbs)
475 		goto fail;
476 	dev->dbbuf_eis = dma_alloc_coherent(dev->dev, mem_size,
477 					    &dev->dbbuf_eis_dma_addr,
478 					    GFP_KERNEL);
479 	if (!dev->dbbuf_eis)
480 		goto fail_free_dbbuf_dbs;
481 	return;
482 
483 fail_free_dbbuf_dbs:
484 	dma_free_coherent(dev->dev, mem_size, dev->dbbuf_dbs,
485 			  dev->dbbuf_dbs_dma_addr);
486 	dev->dbbuf_dbs = NULL;
487 fail:
488 	dev_warn(dev->dev, "unable to allocate dma for dbbuf\n");
489 }
490 
491 static void nvme_dbbuf_dma_free(struct nvme_dev *dev)
492 {
493 	unsigned int mem_size = nvme_dbbuf_size(dev);
494 
495 	if (dev->dbbuf_dbs) {
496 		dma_free_coherent(dev->dev, mem_size,
497 				  dev->dbbuf_dbs, dev->dbbuf_dbs_dma_addr);
498 		dev->dbbuf_dbs = NULL;
499 	}
500 	if (dev->dbbuf_eis) {
501 		dma_free_coherent(dev->dev, mem_size,
502 				  dev->dbbuf_eis, dev->dbbuf_eis_dma_addr);
503 		dev->dbbuf_eis = NULL;
504 	}
505 }
506 
507 static void nvme_dbbuf_init(struct nvme_dev *dev,
508 			    struct nvme_queue *nvmeq, int qid)
509 {
510 	if (!dev->dbbuf_dbs || !qid)
511 		return;
512 
513 	nvmeq->dbbuf_sq_db = &dev->dbbuf_dbs[sq_idx(qid, dev->db_stride)];
514 	nvmeq->dbbuf_cq_db = &dev->dbbuf_dbs[cq_idx(qid, dev->db_stride)];
515 	nvmeq->dbbuf_sq_ei = &dev->dbbuf_eis[sq_idx(qid, dev->db_stride)];
516 	nvmeq->dbbuf_cq_ei = &dev->dbbuf_eis[cq_idx(qid, dev->db_stride)];
517 }
518 
519 static void nvme_dbbuf_free(struct nvme_queue *nvmeq)
520 {
521 	if (!nvmeq->qid)
522 		return;
523 
524 	nvmeq->dbbuf_sq_db = NULL;
525 	nvmeq->dbbuf_cq_db = NULL;
526 	nvmeq->dbbuf_sq_ei = NULL;
527 	nvmeq->dbbuf_cq_ei = NULL;
528 }
529 
530 static void nvme_dbbuf_set(struct nvme_dev *dev)
531 {
532 	struct nvme_command c = { };
533 	unsigned int i;
534 
535 	if (!dev->dbbuf_dbs)
536 		return;
537 
538 	c.dbbuf.opcode = nvme_admin_dbbuf;
539 	c.dbbuf.prp1 = cpu_to_le64(dev->dbbuf_dbs_dma_addr);
540 	c.dbbuf.prp2 = cpu_to_le64(dev->dbbuf_eis_dma_addr);
541 
542 	if (nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0)) {
543 		dev_warn(dev->ctrl.device, "unable to set dbbuf\n");
544 		/* Free memory and continue on */
545 		nvme_dbbuf_dma_free(dev);
546 
547 		for (i = 1; i <= dev->online_queues; i++)
548 			nvme_dbbuf_free(&dev->queues[i]);
549 	}
550 }
551 
552 static inline int nvme_dbbuf_need_event(u16 event_idx, u16 new_idx, u16 old)
553 {
554 	return (u16)(new_idx - event_idx - 1) < (u16)(new_idx - old);
555 }
556 
557 /* Update dbbuf and return true if an MMIO is required */
558 static bool nvme_dbbuf_update_and_check_event(u16 value, __le32 *dbbuf_db,
559 					      volatile __le32 *dbbuf_ei)
560 {
561 	if (dbbuf_db) {
562 		u16 old_value, event_idx;
563 
564 		/*
565 		 * Ensure that the queue is written before updating
566 		 * the doorbell in memory
567 		 */
568 		wmb();
569 
570 		old_value = le32_to_cpu(*dbbuf_db);
571 		*dbbuf_db = cpu_to_le32(value);
572 
573 		/*
574 		 * Ensure that the doorbell is updated before reading the event
575 		 * index from memory.  The controller needs to provide similar
576 		 * ordering to ensure the event index is updated before reading
577 		 * the doorbell.
578 		 */
579 		mb();
580 
581 		event_idx = le32_to_cpu(*dbbuf_ei);
582 		if (!nvme_dbbuf_need_event(event_idx, value, old_value))
583 			return false;
584 	}
585 
586 	return true;
587 }
588 
589 static struct nvme_descriptor_pools *
590 nvme_setup_descriptor_pools(struct nvme_dev *dev, unsigned numa_node)
591 {
592 	struct nvme_descriptor_pools *pools = &dev->descriptor_pools[numa_node];
593 	size_t small_align = NVME_SMALL_POOL_SIZE;
594 
595 	if (pools->small)
596 		return pools; /* already initialized */
597 
598 	pools->large = dma_pool_create_node("nvme descriptor page", dev->dev,
599 			NVME_CTRL_PAGE_SIZE, NVME_CTRL_PAGE_SIZE, 0, numa_node);
600 	if (!pools->large)
601 		return ERR_PTR(-ENOMEM);
602 
603 	if (dev->ctrl.quirks & NVME_QUIRK_DMAPOOL_ALIGN_512)
604 		small_align = 512;
605 
606 	pools->small = dma_pool_create_node("nvme descriptor small", dev->dev,
607 			NVME_SMALL_POOL_SIZE, small_align, 0, numa_node);
608 	if (!pools->small) {
609 		dma_pool_destroy(pools->large);
610 		pools->large = NULL;
611 		return ERR_PTR(-ENOMEM);
612 	}
613 
614 	return pools;
615 }
616 
617 static void nvme_release_descriptor_pools(struct nvme_dev *dev)
618 {
619 	unsigned i;
620 
621 	for (i = 0; i < nr_node_ids; i++) {
622 		struct nvme_descriptor_pools *pools = &dev->descriptor_pools[i];
623 
624 		dma_pool_destroy(pools->large);
625 		dma_pool_destroy(pools->small);
626 	}
627 }
628 
629 static int nvme_init_hctx_common(struct blk_mq_hw_ctx *hctx, void *data,
630 		unsigned qid)
631 {
632 	struct nvme_dev *dev = to_nvme_dev(data);
633 	struct nvme_queue *nvmeq = &dev->queues[qid];
634 	struct nvme_descriptor_pools *pools;
635 	struct blk_mq_tags *tags;
636 
637 	tags = qid ? dev->tagset.tags[qid - 1] : dev->admin_tagset.tags[0];
638 	WARN_ON(tags != hctx->tags);
639 	pools = nvme_setup_descriptor_pools(dev, hctx->numa_node);
640 	if (IS_ERR(pools))
641 		return PTR_ERR(pools);
642 
643 	nvmeq->descriptor_pools = *pools;
644 	hctx->driver_data = nvmeq;
645 	return 0;
646 }
647 
648 static int nvme_admin_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
649 				unsigned int hctx_idx)
650 {
651 	WARN_ON(hctx_idx != 0);
652 	return nvme_init_hctx_common(hctx, data, 0);
653 }
654 
655 static int nvme_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
656 			     unsigned int hctx_idx)
657 {
658 	return nvme_init_hctx_common(hctx, data, hctx_idx + 1);
659 }
660 
661 static int nvme_pci_init_request(struct blk_mq_tag_set *set,
662 		struct request *req, unsigned int hctx_idx,
663 		unsigned int numa_node)
664 {
665 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
666 
667 	nvme_req(req)->ctrl = set->driver_data;
668 	nvme_req(req)->cmd = &iod->cmd;
669 	return 0;
670 }
671 
672 static int queue_irq_offset(struct nvme_dev *dev)
673 {
674 	/* if we have more than 1 vec, admin queue offsets us by 1 */
675 	if (dev->num_vecs > 1)
676 		return 1;
677 
678 	return 0;
679 }
680 
681 static void nvme_pci_map_queues(struct blk_mq_tag_set *set)
682 {
683 	struct nvme_dev *dev = to_nvme_dev(set->driver_data);
684 	int i, qoff, offset;
685 
686 	offset = queue_irq_offset(dev);
687 	for (i = 0, qoff = 0; i < set->nr_maps; i++) {
688 		struct blk_mq_queue_map *map = &set->map[i];
689 
690 		map->nr_queues = dev->io_queues[i];
691 		if (!map->nr_queues) {
692 			BUG_ON(i == HCTX_TYPE_DEFAULT);
693 			continue;
694 		}
695 
696 		/*
697 		 * The poll queue(s) doesn't have an IRQ (and hence IRQ
698 		 * affinity), so use the regular blk-mq cpu mapping
699 		 */
700 		map->queue_offset = qoff;
701 		if (i != HCTX_TYPE_POLL && offset)
702 			blk_mq_map_hw_queues(map, dev->dev, offset);
703 		else
704 			blk_mq_map_queues(map);
705 		qoff += map->nr_queues;
706 		offset += map->nr_queues;
707 	}
708 }
709 
710 /*
711  * Write sq tail if we are asked to, or if the next command would wrap.
712  */
713 static inline void nvme_write_sq_db(struct nvme_queue *nvmeq, bool write_sq)
714 {
715 	if (!write_sq) {
716 		u16 next_tail = nvmeq->sq_tail + 1;
717 
718 		if (next_tail == nvmeq->q_depth)
719 			next_tail = 0;
720 		if (next_tail != nvmeq->last_sq_tail)
721 			return;
722 	}
723 
724 	if (nvme_dbbuf_update_and_check_event(nvmeq->sq_tail,
725 			nvmeq->dbbuf_sq_db, nvmeq->dbbuf_sq_ei))
726 		writel(nvmeq->sq_tail, nvmeq->q_db);
727 	nvmeq->last_sq_tail = nvmeq->sq_tail;
728 }
729 
730 static inline void nvme_sq_copy_cmd(struct nvme_queue *nvmeq,
731 				    struct nvme_command *cmd)
732 {
733 	memcpy(nvmeq->sq_cmds + (nvmeq->sq_tail << nvmeq->sqes),
734 		absolute_pointer(cmd), sizeof(*cmd));
735 	if (++nvmeq->sq_tail == nvmeq->q_depth)
736 		nvmeq->sq_tail = 0;
737 }
738 
739 static void nvme_commit_rqs(struct blk_mq_hw_ctx *hctx)
740 {
741 	struct nvme_queue *nvmeq = hctx->driver_data;
742 
743 	spin_lock(&nvmeq->sq_lock);
744 	if (nvmeq->sq_tail != nvmeq->last_sq_tail)
745 		nvme_write_sq_db(nvmeq, true);
746 	spin_unlock(&nvmeq->sq_lock);
747 }
748 
749 enum nvme_use_sgl {
750 	SGL_UNSUPPORTED,
751 	SGL_SUPPORTED,
752 	SGL_FORCED,
753 };
754 
755 static inline bool nvme_pci_metadata_use_sgls(struct request *req)
756 {
757 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
758 	struct nvme_dev *dev = nvmeq->dev;
759 
760 	if (!nvme_ctrl_meta_sgl_supported(&dev->ctrl))
761 		return false;
762 	return req->nr_integrity_segments > 1 ||
763 		nvme_req(req)->flags & NVME_REQ_USERCMD;
764 }
765 
766 static inline enum nvme_use_sgl nvme_pci_use_sgls(struct nvme_dev *dev,
767 		struct request *req)
768 {
769 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
770 
771 	if (nvmeq->qid && nvme_ctrl_sgl_supported(&dev->ctrl)) {
772 		/*
773 		 * When the controller is capable of using SGL, there are
774 		 * several conditions that we force to use it:
775 		 *
776 		 * 1. A request containing page gaps within the controller's
777 		 *    mask can not use the PRP format.
778 		 *
779 		 * 2. User commands use SGL because that lets the device
780 		 *    validate the requested transfer lengths.
781 		 *
782 		 * 3. Multiple integrity segments must use SGL as that's the
783 		 *    only way to describe such a command in NVMe.
784 		 */
785 		if (req_phys_gap_mask(req) & (NVME_CTRL_PAGE_SIZE - 1) ||
786 		    nvme_req(req)->flags & NVME_REQ_USERCMD ||
787 		    req->nr_integrity_segments > 1)
788 			return SGL_FORCED;
789 		return SGL_SUPPORTED;
790 	}
791 
792 	return SGL_UNSUPPORTED;
793 }
794 
795 static unsigned int nvme_pci_avg_seg_size(struct request *req)
796 {
797 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
798 	unsigned int nseg;
799 
800 	if (blk_rq_dma_map_coalesce(&iod->dma_state))
801 		nseg = 1;
802 	else
803 		nseg = blk_rq_nr_phys_segments(req);
804 	return DIV_ROUND_UP(blk_rq_payload_bytes(req), nseg);
805 }
806 
807 static inline struct dma_pool *nvme_dma_pool(struct nvme_queue *nvmeq,
808 		struct nvme_iod *iod)
809 {
810 	if (iod->flags & IOD_SMALL_DESCRIPTOR)
811 		return nvmeq->descriptor_pools.small;
812 	return nvmeq->descriptor_pools.large;
813 }
814 
815 static inline bool nvme_pci_cmd_use_meta_sgl(struct nvme_command *cmd)
816 {
817 	return (cmd->common.flags & NVME_CMD_SGL_ALL) == NVME_CMD_SGL_METASEG;
818 }
819 
820 static inline bool nvme_pci_cmd_use_sgl(struct nvme_command *cmd)
821 {
822 	return cmd->common.flags &
823 		(NVME_CMD_SGL_METABUF | NVME_CMD_SGL_METASEG);
824 }
825 
826 static inline dma_addr_t nvme_pci_first_desc_dma_addr(struct nvme_command *cmd)
827 {
828 	if (nvme_pci_cmd_use_sgl(cmd))
829 		return le64_to_cpu(cmd->common.dptr.sgl.addr);
830 	return le64_to_cpu(cmd->common.dptr.prp2);
831 }
832 
833 static void nvme_free_descriptors(struct request *req)
834 {
835 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
836 	const int last_prp = NVME_CTRL_PAGE_SIZE / sizeof(__le64) - 1;
837 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
838 	dma_addr_t dma_addr = nvme_pci_first_desc_dma_addr(&iod->cmd);
839 	int i;
840 
841 	if (iod->nr_descriptors == 1) {
842 		dma_pool_free(nvme_dma_pool(nvmeq, iod), iod->descriptors[0],
843 				dma_addr);
844 		return;
845 	}
846 
847 	for (i = 0; i < iod->nr_descriptors; i++) {
848 		__le64 *prp_list = iod->descriptors[i];
849 		dma_addr_t next_dma_addr = le64_to_cpu(prp_list[last_prp]);
850 
851 		dma_pool_free(nvmeq->descriptor_pools.large, prp_list,
852 				dma_addr);
853 		dma_addr = next_dma_addr;
854 	}
855 }
856 
857 static void nvme_free_prps(struct request *req, unsigned int attrs)
858 {
859 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
860 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
861 	unsigned int i;
862 
863 	for (i = 0; i < iod->nr_dma_vecs; i++)
864 		dma_unmap_phys(nvmeq->dev->dev, iod->dma_vecs[i].addr,
865 			       iod->dma_vecs[i].len, rq_dma_dir(req), attrs);
866 	mempool_free(iod->dma_vecs, nvmeq->dev->dmavec_mempool);
867 }
868 
869 static void nvme_free_sgls(struct request *req, struct nvme_sgl_desc *sge,
870 		struct nvme_sgl_desc *sg_list, unsigned int attrs)
871 {
872 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
873 	enum dma_data_direction dir = rq_dma_dir(req);
874 	unsigned int len = le32_to_cpu(sge->length);
875 	struct device *dma_dev = nvmeq->dev->dev;
876 	unsigned int i;
877 
878 	if (sge->type == (NVME_SGL_FMT_DATA_DESC << 4)) {
879 		dma_unmap_phys(dma_dev, le64_to_cpu(sge->addr), len, dir,
880 			       attrs);
881 		return;
882 	}
883 
884 	for (i = 0; i < len / sizeof(*sg_list); i++)
885 		dma_unmap_phys(dma_dev, le64_to_cpu(sg_list[i].addr),
886 			le32_to_cpu(sg_list[i].length), dir, attrs);
887 }
888 
889 static void nvme_unmap_metadata(struct request *req)
890 {
891 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
892 	enum pci_p2pdma_map_type map = PCI_P2PDMA_MAP_NONE;
893 	enum dma_data_direction dir = rq_dma_dir(req);
894 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
895 	struct device *dma_dev = nvmeq->dev->dev;
896 	struct nvme_sgl_desc *sge = iod->meta_descriptor;
897 	unsigned int attrs = 0;
898 
899 	if (iod->flags & IOD_SINGLE_META_SEGMENT) {
900 		dma_unmap_page(dma_dev, iod->meta_dma,
901 			       rq_integrity_vec(req).bv_len,
902 			       rq_dma_dir(req));
903 		return;
904 	}
905 
906 	if (iod->flags & IOD_META_P2P)
907 		map = PCI_P2PDMA_MAP_BUS_ADDR;
908 	else if (iod->flags & IOD_META_MMIO) {
909 		map = PCI_P2PDMA_MAP_THRU_HOST_BRIDGE;
910 		attrs |= DMA_ATTR_MMIO;
911 	}
912 
913 	if (!blk_rq_dma_unmap(req, dma_dev, &iod->meta_dma_state,
914 			      iod->meta_total_len, map)) {
915 		if (nvme_pci_cmd_use_meta_sgl(&iod->cmd))
916 			nvme_free_sgls(req, sge, &sge[1], attrs);
917 		else
918 			dma_unmap_phys(dma_dev, iod->meta_dma,
919 				       iod->meta_total_len, dir, attrs);
920 	}
921 
922 	if (iod->meta_descriptor)
923 		dma_pool_free(nvmeq->descriptor_pools.small,
924 			      iod->meta_descriptor, iod->meta_dma);
925 }
926 
927 static void nvme_unmap_data(struct request *req)
928 {
929 	enum pci_p2pdma_map_type map = PCI_P2PDMA_MAP_NONE;
930 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
931 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
932 	struct device *dma_dev = nvmeq->dev->dev;
933 	unsigned int attrs = 0;
934 
935 	if (iod->flags & IOD_SINGLE_SEGMENT) {
936 		static_assert(offsetof(union nvme_data_ptr, prp1) ==
937 				offsetof(union nvme_data_ptr, sgl.addr));
938 		dma_unmap_page(dma_dev, le64_to_cpu(iod->cmd.common.dptr.prp1),
939 				iod->total_len, rq_dma_dir(req));
940 		return;
941 	}
942 
943 	if (iod->flags & IOD_DATA_P2P)
944 		map = PCI_P2PDMA_MAP_BUS_ADDR;
945 	else if (iod->flags & IOD_DATA_MMIO) {
946 		map = PCI_P2PDMA_MAP_THRU_HOST_BRIDGE;
947 		attrs |= DMA_ATTR_MMIO;
948 	}
949 
950 	if (!blk_rq_dma_unmap(req, dma_dev, &iod->dma_state, iod->total_len,
951 			      map)) {
952 		if (nvme_pci_cmd_use_sgl(&iod->cmd))
953 			nvme_free_sgls(req, &iod->cmd.common.dptr.sgl,
954 			               iod->descriptors[0], attrs);
955 		else
956 			nvme_free_prps(req, attrs);
957 	}
958 
959 	if (iod->nr_descriptors)
960 		nvme_free_descriptors(req);
961 }
962 
963 static bool nvme_pci_prp_save_mapping(struct request *req,
964 				      struct device *dma_dev,
965 				      struct blk_dma_iter *iter)
966 {
967 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
968 
969 	if (dma_use_iova(&iod->dma_state) || !dma_need_unmap(dma_dev))
970 		return true;
971 
972 	if (!iod->nr_dma_vecs) {
973 		struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
974 
975 		iod->dma_vecs = mempool_alloc(nvmeq->dev->dmavec_mempool,
976 				GFP_ATOMIC);
977 		if (!iod->dma_vecs) {
978 			iter->status = BLK_STS_RESOURCE;
979 			return false;
980 		}
981 	}
982 
983 	iod->dma_vecs[iod->nr_dma_vecs].addr = iter->addr;
984 	iod->dma_vecs[iod->nr_dma_vecs].len = iter->len;
985 	iod->nr_dma_vecs++;
986 	return true;
987 }
988 
989 static bool nvme_pci_prp_iter_next(struct request *req, struct device *dma_dev,
990 		struct blk_dma_iter *iter)
991 {
992 	if (iter->len)
993 		return true;
994 	if (!blk_rq_dma_map_iter_next(req, dma_dev, iter))
995 		return false;
996 	return nvme_pci_prp_save_mapping(req, dma_dev, iter);
997 }
998 
999 static blk_status_t nvme_pci_setup_data_prp(struct request *req,
1000 		struct blk_dma_iter *iter)
1001 {
1002 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1003 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1004 	unsigned int length = blk_rq_payload_bytes(req);
1005 	dma_addr_t prp1_dma, prp2_dma = 0;
1006 	unsigned int prp_len, i;
1007 	__le64 *prp_list;
1008 
1009 	if (!nvme_pci_prp_save_mapping(req, nvmeq->dev->dev, iter))
1010 		return iter->status;
1011 
1012 	/*
1013 	 * PRP1 always points to the start of the DMA transfers.
1014 	 *
1015 	 * This is the only PRP (except for the list entries) that could be
1016 	 * non-aligned.
1017 	 */
1018 	prp1_dma = iter->addr;
1019 	prp_len = min(length, NVME_CTRL_PAGE_SIZE -
1020 			(iter->addr & (NVME_CTRL_PAGE_SIZE - 1)));
1021 	iod->total_len += prp_len;
1022 	iter->addr += prp_len;
1023 	iter->len -= prp_len;
1024 	length -= prp_len;
1025 	if (!length)
1026 		goto done;
1027 
1028 	if (!nvme_pci_prp_iter_next(req, nvmeq->dev->dev, iter)) {
1029 		if (WARN_ON_ONCE(!iter->status))
1030 			goto bad_sgl;
1031 		goto done;
1032 	}
1033 
1034 	/*
1035 	 * PRP2 is usually a list, but can point to data if all data to be
1036 	 * transferred fits into PRP1 + PRP2:
1037 	 */
1038 	if (length <= NVME_CTRL_PAGE_SIZE) {
1039 		prp2_dma = iter->addr;
1040 		iod->total_len += length;
1041 		goto done;
1042 	}
1043 
1044 	if (DIV_ROUND_UP(length, NVME_CTRL_PAGE_SIZE) <=
1045 	    NVME_SMALL_POOL_SIZE / sizeof(__le64))
1046 		iod->flags |= IOD_SMALL_DESCRIPTOR;
1047 
1048 	prp_list = dma_pool_alloc(nvme_dma_pool(nvmeq, iod), GFP_ATOMIC,
1049 			&prp2_dma);
1050 	if (!prp_list) {
1051 		iter->status = BLK_STS_RESOURCE;
1052 		goto done;
1053 	}
1054 	iod->descriptors[iod->nr_descriptors++] = prp_list;
1055 
1056 	i = 0;
1057 	for (;;) {
1058 		prp_list[i++] = cpu_to_le64(iter->addr);
1059 		prp_len = min(length, NVME_CTRL_PAGE_SIZE);
1060 		if (WARN_ON_ONCE(iter->len < prp_len))
1061 			goto bad_sgl;
1062 
1063 		iod->total_len += prp_len;
1064 		iter->addr += prp_len;
1065 		iter->len -= prp_len;
1066 		length -= prp_len;
1067 		if (!length)
1068 			break;
1069 
1070 		if (!nvme_pci_prp_iter_next(req, nvmeq->dev->dev, iter)) {
1071 			if (WARN_ON_ONCE(!iter->status))
1072 				goto bad_sgl;
1073 			goto done;
1074 		}
1075 
1076 		/*
1077 		 * If we've filled the entire descriptor, allocate a new that is
1078 		 * pointed to be the last entry in the previous PRP list.  To
1079 		 * accommodate for that move the last actual entry to the new
1080 		 * descriptor.
1081 		 */
1082 		if (i == NVME_CTRL_PAGE_SIZE >> 3) {
1083 			__le64 *old_prp_list = prp_list;
1084 			dma_addr_t prp_list_dma;
1085 
1086 			prp_list = dma_pool_alloc(nvmeq->descriptor_pools.large,
1087 					GFP_ATOMIC, &prp_list_dma);
1088 			if (!prp_list) {
1089 				iter->status = BLK_STS_RESOURCE;
1090 				goto done;
1091 			}
1092 			iod->descriptors[iod->nr_descriptors++] = prp_list;
1093 
1094 			prp_list[0] = old_prp_list[i - 1];
1095 			old_prp_list[i - 1] = cpu_to_le64(prp_list_dma);
1096 			i = 1;
1097 		}
1098 	}
1099 
1100 done:
1101 	/*
1102 	 * nvme_unmap_data uses the DPT field in the SQE to tear down the
1103 	 * mapping, so initialize it even for failures.
1104 	 */
1105 	iod->cmd.common.dptr.prp1 = cpu_to_le64(prp1_dma);
1106 	iod->cmd.common.dptr.prp2 = cpu_to_le64(prp2_dma);
1107 	if (unlikely(iter->status))
1108 		nvme_unmap_data(req);
1109 	return iter->status;
1110 
1111 bad_sgl:
1112 	dev_err_once(nvmeq->dev->dev,
1113 		"Incorrectly formed request for payload:%d nents:%d\n",
1114 		blk_rq_payload_bytes(req), blk_rq_nr_phys_segments(req));
1115 	return BLK_STS_IOERR;
1116 }
1117 
1118 static void nvme_pci_sgl_set_data(struct nvme_sgl_desc *sge,
1119 		struct blk_dma_iter *iter)
1120 {
1121 	sge->addr = cpu_to_le64(iter->addr);
1122 	sge->length = cpu_to_le32(iter->len);
1123 	sge->type = NVME_SGL_FMT_DATA_DESC << 4;
1124 }
1125 
1126 static void nvme_pci_sgl_set_seg(struct nvme_sgl_desc *sge,
1127 		dma_addr_t dma_addr, int entries)
1128 {
1129 	sge->addr = cpu_to_le64(dma_addr);
1130 	sge->length = cpu_to_le32(entries * sizeof(*sge));
1131 	sge->type = NVME_SGL_FMT_LAST_SEG_DESC << 4;
1132 }
1133 
1134 static blk_status_t nvme_pci_setup_data_sgl(struct request *req,
1135 		struct blk_dma_iter *iter)
1136 {
1137 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1138 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1139 	unsigned int entries = blk_rq_nr_phys_segments(req);
1140 	struct nvme_sgl_desc *sg_list;
1141 	dma_addr_t sgl_dma;
1142 	unsigned int mapped = 0;
1143 
1144 	/* set the transfer type as SGL */
1145 	iod->cmd.common.flags = NVME_CMD_SGL_METABUF;
1146 
1147 	if (entries == 1 || blk_rq_dma_map_coalesce(&iod->dma_state)) {
1148 		nvme_pci_sgl_set_data(&iod->cmd.common.dptr.sgl, iter);
1149 		iod->total_len += iter->len;
1150 		return BLK_STS_OK;
1151 	}
1152 
1153 	if (entries <= NVME_SMALL_POOL_SIZE / sizeof(*sg_list))
1154 		iod->flags |= IOD_SMALL_DESCRIPTOR;
1155 
1156 	sg_list = dma_pool_alloc(nvme_dma_pool(nvmeq, iod), GFP_ATOMIC,
1157 			&sgl_dma);
1158 	if (!sg_list)
1159 		return BLK_STS_RESOURCE;
1160 	iod->descriptors[iod->nr_descriptors++] = sg_list;
1161 
1162 	do {
1163 		if (WARN_ON_ONCE(mapped == entries)) {
1164 			iter->status = BLK_STS_IOERR;
1165 			break;
1166 		}
1167 		nvme_pci_sgl_set_data(&sg_list[mapped++], iter);
1168 		iod->total_len += iter->len;
1169 	} while (blk_rq_dma_map_iter_next(req, nvmeq->dev->dev, iter));
1170 
1171 	nvme_pci_sgl_set_seg(&iod->cmd.common.dptr.sgl, sgl_dma, mapped);
1172 	if (unlikely(iter->status))
1173 		nvme_unmap_data(req);
1174 	return iter->status;
1175 }
1176 
1177 static blk_status_t nvme_pci_setup_data_simple(struct request *req,
1178 		enum nvme_use_sgl use_sgl)
1179 {
1180 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1181 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1182 	struct bio_vec bv = req_bvec(req);
1183 	unsigned int prp1_offset = bv.bv_offset & (NVME_CTRL_PAGE_SIZE - 1);
1184 	bool prp_possible = prp1_offset + bv.bv_len <= NVME_CTRL_PAGE_SIZE * 2;
1185 	dma_addr_t dma_addr;
1186 
1187 	if (!use_sgl && !prp_possible)
1188 		return BLK_STS_AGAIN;
1189 	if (is_pci_p2pdma_page(bv.bv_page))
1190 		return BLK_STS_AGAIN;
1191 
1192 	dma_addr = dma_map_bvec(nvmeq->dev->dev, &bv, rq_dma_dir(req), 0);
1193 	if (dma_mapping_error(nvmeq->dev->dev, dma_addr))
1194 		return BLK_STS_RESOURCE;
1195 	iod->total_len = bv.bv_len;
1196 	iod->flags |= IOD_SINGLE_SEGMENT;
1197 
1198 	if (use_sgl == SGL_FORCED || !prp_possible) {
1199 		iod->cmd.common.flags = NVME_CMD_SGL_METABUF;
1200 		iod->cmd.common.dptr.sgl.addr = cpu_to_le64(dma_addr);
1201 		iod->cmd.common.dptr.sgl.length = cpu_to_le32(bv.bv_len);
1202 		iod->cmd.common.dptr.sgl.type = NVME_SGL_FMT_DATA_DESC << 4;
1203 	} else {
1204 		unsigned int first_prp_len = NVME_CTRL_PAGE_SIZE - prp1_offset;
1205 
1206 		iod->cmd.common.dptr.prp1 = cpu_to_le64(dma_addr);
1207 		iod->cmd.common.dptr.prp2 = 0;
1208 		if (bv.bv_len > first_prp_len)
1209 			iod->cmd.common.dptr.prp2 =
1210 				cpu_to_le64(dma_addr + first_prp_len);
1211 	}
1212 
1213 	return BLK_STS_OK;
1214 }
1215 
1216 static blk_status_t nvme_map_data(struct request *req)
1217 {
1218 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1219 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1220 	struct nvme_dev *dev = nvmeq->dev;
1221 	enum nvme_use_sgl use_sgl = nvme_pci_use_sgls(dev, req);
1222 	struct blk_dma_iter iter;
1223 	blk_status_t ret;
1224 
1225 	/*
1226 	 * Try to skip the DMA iterator for single segment requests, as that
1227 	 * significantly improves performances for small I/O sizes.
1228 	 */
1229 	if (blk_rq_nr_phys_segments(req) == 1) {
1230 		ret = nvme_pci_setup_data_simple(req, use_sgl);
1231 		if (ret != BLK_STS_AGAIN)
1232 			return ret;
1233 	}
1234 
1235 	if (!blk_rq_dma_map_iter_start(req, dev->dev, &iod->dma_state, &iter))
1236 		return iter.status;
1237 
1238 	switch (iter.p2pdma.map) {
1239 	case PCI_P2PDMA_MAP_BUS_ADDR:
1240 		iod->flags |= IOD_DATA_P2P;
1241 		break;
1242 	case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
1243 		iod->flags |= IOD_DATA_MMIO;
1244 		break;
1245 	case PCI_P2PDMA_MAP_NONE:
1246 		break;
1247 	default:
1248 		return BLK_STS_RESOURCE;
1249 	}
1250 
1251 	if (use_sgl == SGL_FORCED ||
1252 	    (use_sgl == SGL_SUPPORTED &&
1253 	     (sgl_threshold && nvme_pci_avg_seg_size(req) >= sgl_threshold)))
1254 		return nvme_pci_setup_data_sgl(req, &iter);
1255 	return nvme_pci_setup_data_prp(req, &iter);
1256 }
1257 
1258 static blk_status_t nvme_pci_setup_meta_iter(struct request *req)
1259 {
1260 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1261 	unsigned int entries = req->nr_integrity_segments;
1262 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1263 	struct nvme_dev *dev = nvmeq->dev;
1264 	struct nvme_sgl_desc *sg_list;
1265 	struct blk_dma_iter iter;
1266 	dma_addr_t sgl_dma;
1267 	int i = 0;
1268 
1269 	if (!blk_rq_integrity_dma_map_iter_start(req, dev->dev,
1270 						&iod->meta_dma_state, &iter))
1271 		return iter.status;
1272 
1273 	switch (iter.p2pdma.map) {
1274 	case PCI_P2PDMA_MAP_BUS_ADDR:
1275 		iod->flags |= IOD_META_P2P;
1276 		break;
1277 	case PCI_P2PDMA_MAP_THRU_HOST_BRIDGE:
1278 		iod->flags |= IOD_META_MMIO;
1279 		break;
1280 	case PCI_P2PDMA_MAP_NONE:
1281 		break;
1282 	default:
1283 		return BLK_STS_RESOURCE;
1284 	}
1285 
1286 	if (blk_rq_dma_map_coalesce(&iod->meta_dma_state))
1287 		entries = 1;
1288 
1289 	/*
1290 	 * The NVMe MPTR descriptor has an implicit length that the host and
1291 	 * device must agree on to avoid data/memory corruption. We trust the
1292 	 * kernel allocated correctly based on the format's parameters, so use
1293 	 * the more efficient MPTR to avoid extra dma pool allocations for the
1294 	 * SGL indirection.
1295 	 *
1296 	 * But for user commands, we don't necessarily know what they do, so
1297 	 * the driver can't validate the metadata buffer size. The SGL
1298 	 * descriptor provides an explicit length, so we're relying on that
1299 	 * mechanism to catch any misunderstandings between the application and
1300 	 * device.
1301 	 *
1302 	 * P2P DMA also needs to use the blk_dma_iter method, so mptr setup
1303 	 * leverages this routine when that happens.
1304 	 */
1305 	if (!nvme_ctrl_meta_sgl_supported(&dev->ctrl) ||
1306 	    (entries == 1 && !(nvme_req(req)->flags & NVME_REQ_USERCMD))) {
1307 		iod->cmd.common.metadata = cpu_to_le64(iter.addr);
1308 		iod->meta_total_len = iter.len;
1309 		iod->meta_dma = iter.addr;
1310 		iod->meta_descriptor = NULL;
1311 		return BLK_STS_OK;
1312 	}
1313 
1314 	sg_list = dma_pool_alloc(nvmeq->descriptor_pools.small, GFP_ATOMIC,
1315 			&sgl_dma);
1316 	if (!sg_list)
1317 		return BLK_STS_RESOURCE;
1318 
1319 	iod->meta_descriptor = sg_list;
1320 	iod->meta_dma = sgl_dma;
1321 	iod->cmd.common.flags = NVME_CMD_SGL_METASEG;
1322 	iod->cmd.common.metadata = cpu_to_le64(sgl_dma);
1323 	if (entries == 1) {
1324 		iod->meta_total_len = iter.len;
1325 		nvme_pci_sgl_set_data(sg_list, &iter);
1326 		return BLK_STS_OK;
1327 	}
1328 
1329 	sgl_dma += sizeof(*sg_list);
1330 	do {
1331 		nvme_pci_sgl_set_data(&sg_list[++i], &iter);
1332 		iod->meta_total_len += iter.len;
1333 	} while (blk_rq_integrity_dma_map_iter_next(req, dev->dev, &iter));
1334 
1335 	nvme_pci_sgl_set_seg(sg_list, sgl_dma, i);
1336 	if (unlikely(iter.status))
1337 		nvme_unmap_metadata(req);
1338 	return iter.status;
1339 }
1340 
1341 static blk_status_t nvme_pci_setup_meta_mptr(struct request *req)
1342 {
1343 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1344 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1345 	struct bio_vec bv = rq_integrity_vec(req);
1346 
1347 	if (is_pci_p2pdma_page(bv.bv_page))
1348 		return nvme_pci_setup_meta_iter(req);
1349 
1350 	iod->meta_dma = dma_map_bvec(nvmeq->dev->dev, &bv, rq_dma_dir(req), 0);
1351 	if (dma_mapping_error(nvmeq->dev->dev, iod->meta_dma))
1352 		return BLK_STS_IOERR;
1353 	iod->cmd.common.metadata = cpu_to_le64(iod->meta_dma);
1354 	iod->flags |= IOD_SINGLE_META_SEGMENT;
1355 	return BLK_STS_OK;
1356 }
1357 
1358 static blk_status_t nvme_map_metadata(struct request *req)
1359 {
1360 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1361 
1362 	if ((iod->cmd.common.flags & NVME_CMD_SGL_METABUF) &&
1363 	    nvme_pci_metadata_use_sgls(req))
1364 		return nvme_pci_setup_meta_iter(req);
1365 	return nvme_pci_setup_meta_mptr(req);
1366 }
1367 
1368 static blk_status_t nvme_prep_rq(struct request *req)
1369 {
1370 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1371 	blk_status_t ret;
1372 
1373 	iod->flags = 0;
1374 	iod->nr_descriptors = 0;
1375 	iod->total_len = 0;
1376 	iod->meta_total_len = 0;
1377 	iod->nr_dma_vecs = 0;
1378 
1379 	ret = nvme_setup_cmd(req->q->queuedata, req);
1380 	if (ret)
1381 		return ret;
1382 
1383 	if (blk_rq_nr_phys_segments(req)) {
1384 		ret = nvme_map_data(req);
1385 		if (ret)
1386 			goto out_free_cmd;
1387 	}
1388 
1389 	if (blk_integrity_rq(req)) {
1390 		ret = nvme_map_metadata(req);
1391 		if (ret)
1392 			goto out_unmap_data;
1393 	}
1394 
1395 	nvme_start_request(req);
1396 	return BLK_STS_OK;
1397 out_unmap_data:
1398 	if (blk_rq_nr_phys_segments(req))
1399 		nvme_unmap_data(req);
1400 out_free_cmd:
1401 	nvme_cleanup_cmd(req);
1402 	return ret;
1403 }
1404 
1405 static blk_status_t nvme_queue_rq(struct blk_mq_hw_ctx *hctx,
1406 			 const struct blk_mq_queue_data *bd)
1407 {
1408 	struct nvme_queue *nvmeq = hctx->driver_data;
1409 	struct nvme_dev *dev = nvmeq->dev;
1410 	struct request *req = bd->rq;
1411 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1412 	blk_status_t ret;
1413 
1414 	/*
1415 	 * We should not need to do this, but we're still using this to
1416 	 * ensure we can drain requests on a dying queue.
1417 	 */
1418 	if (unlikely(!test_bit(NVMEQ_ENABLED, &nvmeq->flags)))
1419 		return BLK_STS_IOERR;
1420 
1421 	if (unlikely(!nvme_check_ready(&dev->ctrl, req, true)))
1422 		return nvme_fail_nonready_command(&dev->ctrl, req);
1423 
1424 	ret = nvme_prep_rq(req);
1425 	if (unlikely(ret))
1426 		return ret;
1427 	spin_lock(&nvmeq->sq_lock);
1428 	nvme_sq_copy_cmd(nvmeq, &iod->cmd);
1429 	nvme_write_sq_db(nvmeq, bd->last);
1430 	spin_unlock(&nvmeq->sq_lock);
1431 	return BLK_STS_OK;
1432 }
1433 
1434 static void nvme_submit_cmds(struct nvme_queue *nvmeq, struct rq_list *rqlist)
1435 {
1436 	struct request *req;
1437 
1438 	if (rq_list_empty(rqlist))
1439 		return;
1440 
1441 	spin_lock(&nvmeq->sq_lock);
1442 	while ((req = rq_list_pop(rqlist))) {
1443 		struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1444 
1445 		nvme_sq_copy_cmd(nvmeq, &iod->cmd);
1446 	}
1447 	nvme_write_sq_db(nvmeq, true);
1448 	spin_unlock(&nvmeq->sq_lock);
1449 }
1450 
1451 static bool nvme_prep_rq_batch(struct nvme_queue *nvmeq, struct request *req)
1452 {
1453 	/*
1454 	 * We should not need to do this, but we're still using this to
1455 	 * ensure we can drain requests on a dying queue.
1456 	 */
1457 	if (unlikely(!test_bit(NVMEQ_ENABLED, &nvmeq->flags)))
1458 		return false;
1459 	if (unlikely(!nvme_check_ready(&nvmeq->dev->ctrl, req, true)))
1460 		return false;
1461 
1462 	return nvme_prep_rq(req) == BLK_STS_OK;
1463 }
1464 
1465 static void nvme_queue_rqs(struct rq_list *rqlist)
1466 {
1467 	struct rq_list submit_list = { };
1468 	struct rq_list requeue_list = { };
1469 	struct nvme_queue *nvmeq = NULL;
1470 	struct request *req;
1471 
1472 	while ((req = rq_list_pop(rqlist))) {
1473 		if (nvmeq && nvmeq != req->mq_hctx->driver_data)
1474 			nvme_submit_cmds(nvmeq, &submit_list);
1475 		nvmeq = req->mq_hctx->driver_data;
1476 
1477 		if (nvme_prep_rq_batch(nvmeq, req))
1478 			rq_list_add_tail(&submit_list, req);
1479 		else
1480 			rq_list_add_tail(&requeue_list, req);
1481 	}
1482 
1483 	if (nvmeq)
1484 		nvme_submit_cmds(nvmeq, &submit_list);
1485 	*rqlist = requeue_list;
1486 }
1487 
1488 static __always_inline void nvme_pci_unmap_rq(struct request *req)
1489 {
1490 	if (blk_integrity_rq(req))
1491 		nvme_unmap_metadata(req);
1492 	if (blk_rq_nr_phys_segments(req))
1493 		nvme_unmap_data(req);
1494 }
1495 
1496 static void nvme_pci_complete_rq(struct request *req)
1497 {
1498 	nvme_pci_unmap_rq(req);
1499 	nvme_complete_rq(req);
1500 }
1501 
1502 static void nvme_pci_complete_batch(struct io_comp_batch *iob)
1503 {
1504 	nvme_complete_batch(iob, nvme_pci_unmap_rq);
1505 }
1506 
1507 /* We read the CQE phase first to check if the rest of the entry is valid */
1508 static inline bool nvme_cqe_pending(struct nvme_queue *nvmeq)
1509 {
1510 	struct nvme_completion *hcqe = &nvmeq->cqes[nvmeq->cq_head];
1511 
1512 	return (le16_to_cpu(READ_ONCE(hcqe->status)) & 1) == nvmeq->cq_phase;
1513 }
1514 
1515 static inline void nvme_ring_cq_doorbell(struct nvme_queue *nvmeq)
1516 {
1517 	u16 head = nvmeq->cq_head;
1518 
1519 	if (nvme_dbbuf_update_and_check_event(head, nvmeq->dbbuf_cq_db,
1520 					      nvmeq->dbbuf_cq_ei))
1521 		writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
1522 }
1523 
1524 static inline struct blk_mq_tags *nvme_queue_tagset(struct nvme_queue *nvmeq)
1525 {
1526 	if (!nvmeq->qid)
1527 		return nvmeq->dev->admin_tagset.tags[0];
1528 	return nvmeq->dev->tagset.tags[nvmeq->qid - 1];
1529 }
1530 
1531 static inline void nvme_handle_cqe(struct nvme_queue *nvmeq,
1532 				   struct io_comp_batch *iob, u16 idx)
1533 {
1534 	struct nvme_completion *cqe = &nvmeq->cqes[idx];
1535 	__u16 command_id = READ_ONCE(cqe->command_id);
1536 	struct request *req;
1537 
1538 	/*
1539 	 * AEN requests are special as they don't time out and can
1540 	 * survive any kind of queue freeze and often don't respond to
1541 	 * aborts.  We don't even bother to allocate a struct request
1542 	 * for them but rather special case them here.
1543 	 */
1544 	if (unlikely(nvme_is_aen_req(nvmeq->qid, command_id))) {
1545 		nvme_complete_async_event(&nvmeq->dev->ctrl,
1546 				cqe->status, &cqe->result);
1547 		return;
1548 	}
1549 
1550 	req = nvme_find_rq(nvme_queue_tagset(nvmeq), command_id);
1551 	if (unlikely(!req)) {
1552 		dev_warn(nvmeq->dev->ctrl.device,
1553 			"invalid id %d completed on queue %d\n",
1554 			command_id, le16_to_cpu(cqe->sq_id));
1555 		return;
1556 	}
1557 
1558 	trace_nvme_sq(req, cqe->sq_head, nvmeq->sq_tail);
1559 	if (!nvme_try_complete_req(req, cqe->status, cqe->result) &&
1560 	    !blk_mq_add_to_batch(req, iob,
1561 				 nvme_req(req)->status != NVME_SC_SUCCESS,
1562 				 nvme_pci_complete_batch))
1563 		nvme_pci_complete_rq(req);
1564 }
1565 
1566 static inline void nvme_update_cq_head(struct nvme_queue *nvmeq)
1567 {
1568 	u32 tmp = nvmeq->cq_head + 1;
1569 
1570 	if (tmp == nvmeq->q_depth) {
1571 		nvmeq->cq_head = 0;
1572 		nvmeq->cq_phase ^= 1;
1573 	} else {
1574 		nvmeq->cq_head = tmp;
1575 	}
1576 }
1577 
1578 static inline bool nvme_poll_cq(struct nvme_queue *nvmeq,
1579 			        struct io_comp_batch *iob)
1580 {
1581 	bool found = false;
1582 
1583 	while (nvme_cqe_pending(nvmeq)) {
1584 		found = true;
1585 		/*
1586 		 * load-load control dependency between phase and the rest of
1587 		 * the cqe requires a full read memory barrier
1588 		 */
1589 		dma_rmb();
1590 		nvme_handle_cqe(nvmeq, iob, nvmeq->cq_head);
1591 		nvme_update_cq_head(nvmeq);
1592 	}
1593 
1594 	if (found)
1595 		nvme_ring_cq_doorbell(nvmeq);
1596 	return found;
1597 }
1598 
1599 static irqreturn_t nvme_irq(int irq, void *data)
1600 {
1601 	struct nvme_queue *nvmeq = data;
1602 	DEFINE_IO_COMP_BATCH(iob);
1603 
1604 	if (nvme_poll_cq(nvmeq, &iob)) {
1605 		if (!rq_list_empty(&iob.req_list))
1606 			nvme_pci_complete_batch(&iob);
1607 		return IRQ_HANDLED;
1608 	}
1609 	return IRQ_NONE;
1610 }
1611 
1612 static irqreturn_t nvme_irq_check(int irq, void *data)
1613 {
1614 	struct nvme_queue *nvmeq = data;
1615 
1616 	if (nvme_cqe_pending(nvmeq))
1617 		return IRQ_WAKE_THREAD;
1618 	return IRQ_NONE;
1619 }
1620 
1621 /*
1622  * Poll for completions for any interrupt driven queue
1623  * Can be called from any context.
1624  */
1625 static void nvme_poll_irqdisable(struct nvme_queue *nvmeq)
1626 {
1627 	struct pci_dev *pdev = to_pci_dev(nvmeq->dev->dev);
1628 
1629 	WARN_ON_ONCE(test_bit(NVMEQ_POLLED, &nvmeq->flags));
1630 
1631 	disable_irq(pci_irq_vector(pdev, nvmeq->cq_vector));
1632 	spin_lock(&nvmeq->cq_poll_lock);
1633 	nvme_poll_cq(nvmeq, NULL);
1634 	spin_unlock(&nvmeq->cq_poll_lock);
1635 	enable_irq(pci_irq_vector(pdev, nvmeq->cq_vector));
1636 }
1637 
1638 static int nvme_poll(struct blk_mq_hw_ctx *hctx, struct io_comp_batch *iob)
1639 {
1640 	struct nvme_queue *nvmeq = hctx->driver_data;
1641 	bool found;
1642 
1643 	if (!test_bit(NVMEQ_POLLED, &nvmeq->flags) ||
1644 	    !nvme_cqe_pending(nvmeq))
1645 		return 0;
1646 
1647 	spin_lock(&nvmeq->cq_poll_lock);
1648 	found = nvme_poll_cq(nvmeq, iob);
1649 	spin_unlock(&nvmeq->cq_poll_lock);
1650 
1651 	return found;
1652 }
1653 
1654 static void nvme_pci_submit_async_event(struct nvme_ctrl *ctrl)
1655 {
1656 	struct nvme_dev *dev = to_nvme_dev(ctrl);
1657 	struct nvme_queue *nvmeq = &dev->queues[0];
1658 	struct nvme_command c = { };
1659 
1660 	c.common.opcode = nvme_admin_async_event;
1661 	c.common.command_id = NVME_AQ_BLK_MQ_DEPTH;
1662 
1663 	spin_lock(&nvmeq->sq_lock);
1664 	nvme_sq_copy_cmd(nvmeq, &c);
1665 	nvme_write_sq_db(nvmeq, true);
1666 	spin_unlock(&nvmeq->sq_lock);
1667 }
1668 
1669 static int nvme_pci_subsystem_reset(struct nvme_ctrl *ctrl)
1670 {
1671 	struct nvme_dev *dev = to_nvme_dev(ctrl);
1672 	int ret = 0;
1673 
1674 	/*
1675 	 * Taking the shutdown_lock ensures the BAR mapping is not being
1676 	 * altered by reset_work. Holding this lock before the RESETTING state
1677 	 * change, if successful, also ensures nvme_remove won't be able to
1678 	 * proceed to iounmap until we're done.
1679 	 */
1680 	mutex_lock(&dev->shutdown_lock);
1681 	if (!dev->bar_mapped_size) {
1682 		ret = -ENODEV;
1683 		goto unlock;
1684 	}
1685 
1686 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) {
1687 		ret = -EBUSY;
1688 		goto unlock;
1689 	}
1690 
1691 	writel(NVME_SUBSYS_RESET, dev->bar + NVME_REG_NSSR);
1692 
1693 	if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING) ||
1694 	    !nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
1695 		goto unlock;
1696 
1697 	/*
1698 	 * Read controller status to flush the previous write and trigger a
1699 	 * pcie read error.
1700 	 */
1701 	readl(dev->bar + NVME_REG_CSTS);
1702 unlock:
1703 	mutex_unlock(&dev->shutdown_lock);
1704 	return ret;
1705 }
1706 
1707 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
1708 {
1709 	struct nvme_command c = { };
1710 
1711 	c.delete_queue.opcode = opcode;
1712 	c.delete_queue.qid = cpu_to_le16(id);
1713 
1714 	return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1715 }
1716 
1717 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
1718 		struct nvme_queue *nvmeq, s16 vector)
1719 {
1720 	struct nvme_command c = { };
1721 	int flags = NVME_QUEUE_PHYS_CONTIG;
1722 
1723 	if (!test_bit(NVMEQ_POLLED, &nvmeq->flags))
1724 		flags |= NVME_CQ_IRQ_ENABLED;
1725 
1726 	/*
1727 	 * Note: we (ab)use the fact that the prp fields survive if no data
1728 	 * is attached to the request.
1729 	 */
1730 	c.create_cq.opcode = nvme_admin_create_cq;
1731 	c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1732 	c.create_cq.cqid = cpu_to_le16(qid);
1733 	c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1734 	c.create_cq.cq_flags = cpu_to_le16(flags);
1735 	c.create_cq.irq_vector = cpu_to_le16(vector);
1736 
1737 	return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1738 }
1739 
1740 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1741 						struct nvme_queue *nvmeq)
1742 {
1743 	struct nvme_ctrl *ctrl = &dev->ctrl;
1744 	struct nvme_command c = { };
1745 	int flags = NVME_QUEUE_PHYS_CONTIG;
1746 
1747 	/*
1748 	 * Some drives have a bug that auto-enables WRRU if MEDIUM isn't
1749 	 * set. Since URGENT priority is zeroes, it makes all queues
1750 	 * URGENT.
1751 	 */
1752 	if (ctrl->quirks & NVME_QUIRK_MEDIUM_PRIO_SQ)
1753 		flags |= NVME_SQ_PRIO_MEDIUM;
1754 
1755 	/*
1756 	 * Note: we (ab)use the fact that the prp fields survive if no data
1757 	 * is attached to the request.
1758 	 */
1759 	c.create_sq.opcode = nvme_admin_create_sq;
1760 	c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1761 	c.create_sq.sqid = cpu_to_le16(qid);
1762 	c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1763 	c.create_sq.sq_flags = cpu_to_le16(flags);
1764 	c.create_sq.cqid = cpu_to_le16(qid);
1765 
1766 	return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1767 }
1768 
1769 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1770 {
1771 	return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1772 }
1773 
1774 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1775 {
1776 	return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1777 }
1778 
1779 static enum rq_end_io_ret abort_endio(struct request *req, blk_status_t error,
1780 				      const struct io_comp_batch *iob)
1781 {
1782 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1783 
1784 	dev_warn(nvmeq->dev->ctrl.device,
1785 		 "Abort status: 0x%x", nvme_req(req)->status);
1786 	atomic_inc(&nvmeq->dev->ctrl.abort_limit);
1787 	blk_mq_free_request(req);
1788 	return RQ_END_IO_NONE;
1789 }
1790 
1791 static bool nvme_should_reset(struct nvme_dev *dev, u32 csts)
1792 {
1793 	/* If true, indicates loss of adapter communication, possibly by a
1794 	 * NVMe Subsystem reset.
1795 	 */
1796 	bool nssro = dev->subsystem && (csts & NVME_CSTS_NSSRO);
1797 
1798 	/* If there is a reset/reinit ongoing, we shouldn't reset again. */
1799 	switch (nvme_ctrl_state(&dev->ctrl)) {
1800 	case NVME_CTRL_RESETTING:
1801 	case NVME_CTRL_CONNECTING:
1802 		return false;
1803 	default:
1804 		break;
1805 	}
1806 
1807 	/* We shouldn't reset unless the controller is on fatal error state
1808 	 * _or_ if we lost the communication with it.
1809 	 */
1810 	if (!(csts & NVME_CSTS_CFS) && !nssro)
1811 		return false;
1812 
1813 	return true;
1814 }
1815 
1816 static void nvme_warn_reset(struct nvme_dev *dev, u32 csts)
1817 {
1818 	/* Read a config register to help see what died. */
1819 	u16 pci_status;
1820 	int result;
1821 
1822 	result = pci_read_config_word(to_pci_dev(dev->dev), PCI_STATUS,
1823 				      &pci_status);
1824 	if (result == PCIBIOS_SUCCESSFUL)
1825 		dev_warn(dev->ctrl.device,
1826 			 "controller is down; will reset: CSTS=0x%x, PCI_STATUS=0x%hx\n",
1827 			 csts, pci_status);
1828 	else
1829 		dev_warn(dev->ctrl.device,
1830 			 "controller is down; will reset: CSTS=0x%x, PCI_STATUS read failed (%d)\n",
1831 			 csts, result);
1832 
1833 	if (csts != ~0)
1834 		return;
1835 
1836 	dev_warn(dev->ctrl.device,
1837 		 "Does your device have a faulty power saving mode enabled?\n");
1838 	dev_warn(dev->ctrl.device,
1839 		 "Try \"nvme_core.default_ps_max_latency_us=0 pcie_aspm=off pcie_port_pm=off\" and report a bug\n");
1840 }
1841 
1842 static enum blk_eh_timer_return nvme_timeout(struct request *req)
1843 {
1844 	struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1845 	struct nvme_queue *nvmeq = req->mq_hctx->driver_data;
1846 	struct nvme_dev *dev = nvmeq->dev;
1847 	struct request *abort_req;
1848 	struct nvme_command cmd = { };
1849 	struct pci_dev *pdev = to_pci_dev(dev->dev);
1850 	u32 csts = readl(dev->bar + NVME_REG_CSTS);
1851 	u8 opcode;
1852 
1853 	/*
1854 	 * Shutdown the device immediately if we see it is disconnected. This
1855 	 * unblocks PCIe error handling if the nvme driver is waiting in
1856 	 * error_resume for a device that has been removed. We can't unbind the
1857 	 * driver while the driver's error callback is waiting to complete, so
1858 	 * we're relying on a timeout to break that deadlock if a removal
1859 	 * occurs while reset work is running.
1860 	 */
1861 	if (pci_dev_is_disconnected(pdev))
1862 		nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
1863 	if (nvme_state_terminal(&dev->ctrl))
1864 		goto disable;
1865 
1866 	/* If PCI error recovery process is happening, we cannot reset or
1867 	 * the recovery mechanism will surely fail.
1868 	 */
1869 	mb();
1870 	if (pci_channel_offline(pdev))
1871 		return BLK_EH_RESET_TIMER;
1872 
1873 	/*
1874 	 * Reset immediately if the controller is failed
1875 	 */
1876 	if (nvme_should_reset(dev, csts)) {
1877 		nvme_warn_reset(dev, csts);
1878 		goto disable;
1879 	}
1880 
1881 	/*
1882 	 * Did we miss an interrupt?
1883 	 */
1884 	if (test_bit(NVMEQ_POLLED, &nvmeq->flags))
1885 		nvme_poll(req->mq_hctx, NULL);
1886 	else
1887 		nvme_poll_irqdisable(nvmeq);
1888 
1889 	if (blk_mq_rq_state(req) != MQ_RQ_IN_FLIGHT) {
1890 		dev_warn(dev->ctrl.device,
1891 			 "I/O tag %d (%04x) QID %d timeout, completion polled\n",
1892 			 req->tag, nvme_cid(req), nvmeq->qid);
1893 		return BLK_EH_DONE;
1894 	}
1895 
1896 	/*
1897 	 * Shutdown immediately if controller times out while starting. The
1898 	 * reset work will see the pci device disabled when it gets the forced
1899 	 * cancellation error. All outstanding requests are completed on
1900 	 * shutdown, so we return BLK_EH_DONE.
1901 	 */
1902 	switch (nvme_ctrl_state(&dev->ctrl)) {
1903 	case NVME_CTRL_CONNECTING:
1904 		nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
1905 		fallthrough;
1906 	case NVME_CTRL_DELETING:
1907 		dev_warn_ratelimited(dev->ctrl.device,
1908 			 "I/O tag %d (%04x) QID %d timeout, disable controller\n",
1909 			 req->tag, nvme_cid(req), nvmeq->qid);
1910 		nvme_req(req)->flags |= NVME_REQ_CANCELLED;
1911 		nvme_dev_disable(dev, true);
1912 		return BLK_EH_DONE;
1913 	case NVME_CTRL_RESETTING:
1914 		return BLK_EH_RESET_TIMER;
1915 	default:
1916 		break;
1917 	}
1918 
1919 	/*
1920 	 * Shutdown the controller immediately and schedule a reset if the
1921 	 * command was already aborted once before and still hasn't been
1922 	 * returned to the driver, or if this is the admin queue.
1923 	 */
1924 	opcode = nvme_req(req)->cmd->common.opcode;
1925 	if (!nvmeq->qid || (iod->flags & IOD_ABORTED)) {
1926 		dev_warn(dev->ctrl.device,
1927 			 "I/O tag %d (%04x) opcode %#x (%s) QID %d timeout, reset controller\n",
1928 			 req->tag, nvme_cid(req), opcode,
1929 			 nvme_opcode_str(nvmeq->qid, opcode), nvmeq->qid);
1930 		nvme_req(req)->flags |= NVME_REQ_CANCELLED;
1931 		goto disable;
1932 	}
1933 
1934 	if (atomic_dec_return(&dev->ctrl.abort_limit) < 0) {
1935 		atomic_inc(&dev->ctrl.abort_limit);
1936 		return BLK_EH_RESET_TIMER;
1937 	}
1938 	iod->flags |= IOD_ABORTED;
1939 
1940 	cmd.abort.opcode = nvme_admin_abort_cmd;
1941 	cmd.abort.cid = nvme_cid(req);
1942 	cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1943 
1944 	dev_warn(nvmeq->dev->ctrl.device,
1945 		 "I/O tag %d (%04x) opcode %#x (%s) QID %d timeout, aborting req_op:%s(%u) size:%u\n",
1946 		 req->tag, nvme_cid(req), opcode, nvme_get_opcode_str(opcode),
1947 		 nvmeq->qid, blk_op_str(req_op(req)), req_op(req),
1948 		 blk_rq_bytes(req));
1949 
1950 	abort_req = blk_mq_alloc_request(dev->ctrl.admin_q, nvme_req_op(&cmd),
1951 					 BLK_MQ_REQ_NOWAIT);
1952 	if (IS_ERR(abort_req)) {
1953 		atomic_inc(&dev->ctrl.abort_limit);
1954 		return BLK_EH_RESET_TIMER;
1955 	}
1956 	nvme_init_request(abort_req, &cmd);
1957 
1958 	abort_req->end_io = abort_endio;
1959 	abort_req->end_io_data = NULL;
1960 	blk_execute_rq_nowait(abort_req, false);
1961 
1962 	/*
1963 	 * The aborted req will be completed on receiving the abort req.
1964 	 * We enable the timer again. If hit twice, it'll cause a device reset,
1965 	 * as the device then is in a faulty state.
1966 	 */
1967 	return BLK_EH_RESET_TIMER;
1968 
1969 disable:
1970 	if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_RESETTING)) {
1971 		if (nvme_state_terminal(&dev->ctrl))
1972 			nvme_dev_disable(dev, true);
1973 		return BLK_EH_DONE;
1974 	}
1975 
1976 	nvme_dev_disable(dev, false);
1977 	if (nvme_try_sched_reset(&dev->ctrl))
1978 		nvme_unquiesce_io_queues(&dev->ctrl);
1979 	return BLK_EH_DONE;
1980 }
1981 
1982 static void nvme_free_queue(struct nvme_queue *nvmeq)
1983 {
1984 	dma_free_coherent(nvmeq->dev->dev, CQ_SIZE(nvmeq),
1985 				(void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1986 	if (!nvmeq->sq_cmds)
1987 		return;
1988 
1989 	if (test_and_clear_bit(NVMEQ_SQ_CMB, &nvmeq->flags)) {
1990 		pci_free_p2pmem(to_pci_dev(nvmeq->dev->dev),
1991 				nvmeq->sq_cmds, SQ_SIZE(nvmeq));
1992 	} else {
1993 		dma_free_coherent(nvmeq->dev->dev, SQ_SIZE(nvmeq),
1994 				nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1995 	}
1996 }
1997 
1998 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1999 {
2000 	int i;
2001 
2002 	for (i = dev->ctrl.queue_count - 1; i >= lowest; i--) {
2003 		dev->ctrl.queue_count--;
2004 		nvme_free_queue(&dev->queues[i]);
2005 	}
2006 }
2007 
2008 static void nvme_suspend_queue(struct nvme_dev *dev, unsigned int qid)
2009 {
2010 	struct nvme_queue *nvmeq = &dev->queues[qid];
2011 
2012 	if (!test_and_clear_bit(NVMEQ_ENABLED, &nvmeq->flags))
2013 		return;
2014 
2015 	/* ensure that nvme_queue_rq() sees NVMEQ_ENABLED cleared */
2016 	mb();
2017 
2018 	nvmeq->dev->online_queues--;
2019 	if (!nvmeq->qid && nvmeq->dev->ctrl.admin_q)
2020 		nvme_quiesce_admin_queue(&nvmeq->dev->ctrl);
2021 	if (!test_and_clear_bit(NVMEQ_POLLED, &nvmeq->flags))
2022 		pci_free_irq(to_pci_dev(dev->dev), nvmeq->cq_vector, nvmeq);
2023 }
2024 
2025 static void nvme_suspend_io_queues(struct nvme_dev *dev)
2026 {
2027 	int i;
2028 
2029 	for (i = dev->ctrl.queue_count - 1; i > 0; i--)
2030 		nvme_suspend_queue(dev, i);
2031 }
2032 
2033 /*
2034  * Called only on a device that has been disabled and after all other threads
2035  * that can check this device's completion queues have synced, except
2036  * nvme_poll(). This is the last chance for the driver to see a natural
2037  * completion before nvme_cancel_request() terminates all incomplete requests.
2038  */
2039 static void nvme_reap_pending_cqes(struct nvme_dev *dev)
2040 {
2041 	int i;
2042 
2043 	for (i = dev->ctrl.queue_count - 1; i > 0; i--) {
2044 		spin_lock(&dev->queues[i].cq_poll_lock);
2045 		nvme_poll_cq(&dev->queues[i], NULL);
2046 		spin_unlock(&dev->queues[i].cq_poll_lock);
2047 	}
2048 }
2049 
2050 static int nvme_cmb_qdepth(struct nvme_dev *dev, int nr_io_queues,
2051 				int entry_size)
2052 {
2053 	int q_depth = dev->q_depth;
2054 	unsigned q_size_aligned = roundup(q_depth * entry_size,
2055 					  NVME_CTRL_PAGE_SIZE);
2056 
2057 	if (q_size_aligned * nr_io_queues > dev->cmb_size) {
2058 		u64 mem_per_q = div_u64(dev->cmb_size, nr_io_queues);
2059 
2060 		mem_per_q = round_down(mem_per_q, NVME_CTRL_PAGE_SIZE);
2061 		q_depth = div_u64(mem_per_q, entry_size);
2062 
2063 		/*
2064 		 * Ensure the reduced q_depth is above some threshold where it
2065 		 * would be better to map queues in system memory with the
2066 		 * original depth
2067 		 */
2068 		if (q_depth < 64)
2069 			return -ENOMEM;
2070 	}
2071 
2072 	return q_depth;
2073 }
2074 
2075 static int nvme_alloc_sq_cmds(struct nvme_dev *dev, struct nvme_queue *nvmeq,
2076 				int qid)
2077 {
2078 	struct pci_dev *pdev = to_pci_dev(dev->dev);
2079 
2080 	if (qid && dev->cmb_use_sqes && (dev->cmbsz & NVME_CMBSZ_SQS)) {
2081 		nvmeq->sq_cmds = pci_alloc_p2pmem(pdev, SQ_SIZE(nvmeq));
2082 		if (nvmeq->sq_cmds) {
2083 			nvmeq->sq_dma_addr = pci_p2pmem_virt_to_bus(pdev,
2084 							nvmeq->sq_cmds);
2085 			if (nvmeq->sq_dma_addr) {
2086 				set_bit(NVMEQ_SQ_CMB, &nvmeq->flags);
2087 				return 0;
2088 			}
2089 
2090 			pci_free_p2pmem(pdev, nvmeq->sq_cmds, SQ_SIZE(nvmeq));
2091 		}
2092 	}
2093 
2094 	nvmeq->sq_cmds = dma_alloc_coherent(dev->dev, SQ_SIZE(nvmeq),
2095 				&nvmeq->sq_dma_addr, GFP_KERNEL);
2096 	if (!nvmeq->sq_cmds)
2097 		return -ENOMEM;
2098 	return 0;
2099 }
2100 
2101 static int nvme_alloc_queue(struct nvme_dev *dev, int qid, int depth)
2102 {
2103 	struct nvme_queue *nvmeq = &dev->queues[qid];
2104 
2105 	if (dev->ctrl.queue_count > qid)
2106 		return 0;
2107 
2108 	nvmeq->sqes = qid ? dev->io_sqes : NVME_ADM_SQES;
2109 	nvmeq->q_depth = depth;
2110 	nvmeq->cqes = dma_alloc_coherent(dev->dev, CQ_SIZE(nvmeq),
2111 					 &nvmeq->cq_dma_addr, GFP_KERNEL);
2112 	if (!nvmeq->cqes)
2113 		goto free_nvmeq;
2114 
2115 	if (nvme_alloc_sq_cmds(dev, nvmeq, qid))
2116 		goto free_cqdma;
2117 
2118 	nvmeq->dev = dev;
2119 	spin_lock_init(&nvmeq->sq_lock);
2120 	spin_lock_init(&nvmeq->cq_poll_lock);
2121 	nvmeq->cq_head = 0;
2122 	nvmeq->cq_phase = 1;
2123 	nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
2124 	nvmeq->qid = qid;
2125 	dev->ctrl.queue_count++;
2126 
2127 	return 0;
2128 
2129  free_cqdma:
2130 	dma_free_coherent(dev->dev, CQ_SIZE(nvmeq), (void *)nvmeq->cqes,
2131 			  nvmeq->cq_dma_addr);
2132  free_nvmeq:
2133 	return -ENOMEM;
2134 }
2135 
2136 static int queue_request_irq(struct nvme_queue *nvmeq)
2137 {
2138 	struct pci_dev *pdev = to_pci_dev(nvmeq->dev->dev);
2139 	int nr = nvmeq->dev->ctrl.instance;
2140 
2141 	if (use_threaded_interrupts) {
2142 		return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq_check,
2143 				nvme_irq, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
2144 	} else {
2145 		return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq,
2146 				NULL, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
2147 	}
2148 }
2149 
2150 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
2151 {
2152 	struct nvme_dev *dev = nvmeq->dev;
2153 
2154 	nvmeq->sq_tail = 0;
2155 	nvmeq->last_sq_tail = 0;
2156 	nvmeq->cq_head = 0;
2157 	nvmeq->cq_phase = 1;
2158 	nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
2159 	memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq));
2160 	nvme_dbbuf_init(dev, nvmeq, qid);
2161 	dev->online_queues++;
2162 	wmb(); /* ensure the first interrupt sees the initialization */
2163 }
2164 
2165 /*
2166  * Try getting shutdown_lock while setting up IO queues.
2167  */
2168 static int nvme_setup_io_queues_trylock(struct nvme_dev *dev)
2169 {
2170 	/*
2171 	 * Give up if the lock is being held by nvme_dev_disable.
2172 	 */
2173 	if (!mutex_trylock(&dev->shutdown_lock))
2174 		return -ENODEV;
2175 
2176 	/*
2177 	 * Controller is in wrong state, fail early.
2178 	 */
2179 	if (nvme_ctrl_state(&dev->ctrl) != NVME_CTRL_CONNECTING) {
2180 		mutex_unlock(&dev->shutdown_lock);
2181 		return -ENODEV;
2182 	}
2183 
2184 	return 0;
2185 }
2186 
2187 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid, bool polled)
2188 {
2189 	struct nvme_dev *dev = nvmeq->dev;
2190 	int result;
2191 	u16 vector = 0;
2192 
2193 	clear_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags);
2194 
2195 	/*
2196 	 * A queue's vector matches the queue identifier unless the controller
2197 	 * has only one vector available.
2198 	 */
2199 	if (!polled)
2200 		vector = dev->num_vecs == 1 ? 0 : qid;
2201 	else
2202 		set_bit(NVMEQ_POLLED, &nvmeq->flags);
2203 
2204 	result = adapter_alloc_cq(dev, qid, nvmeq, vector);
2205 	if (result)
2206 		return result;
2207 
2208 	result = adapter_alloc_sq(dev, qid, nvmeq);
2209 	if (result < 0)
2210 		return result;
2211 	if (result)
2212 		goto release_cq;
2213 
2214 	nvmeq->cq_vector = vector;
2215 
2216 	result = nvme_setup_io_queues_trylock(dev);
2217 	if (result)
2218 		return result;
2219 	nvme_init_queue(nvmeq, qid);
2220 	if (!polled) {
2221 		result = queue_request_irq(nvmeq);
2222 		if (result < 0)
2223 			goto release_sq;
2224 	}
2225 
2226 	set_bit(NVMEQ_ENABLED, &nvmeq->flags);
2227 	mutex_unlock(&dev->shutdown_lock);
2228 	return result;
2229 
2230 release_sq:
2231 	dev->online_queues--;
2232 	mutex_unlock(&dev->shutdown_lock);
2233 	adapter_delete_sq(dev, qid);
2234 release_cq:
2235 	adapter_delete_cq(dev, qid);
2236 	return result;
2237 }
2238 
2239 static const struct blk_mq_ops nvme_mq_admin_ops = {
2240 	.queue_rq	= nvme_queue_rq,
2241 	.complete	= nvme_pci_complete_rq,
2242 	.commit_rqs	= nvme_commit_rqs,
2243 	.init_hctx	= nvme_admin_init_hctx,
2244 	.init_request	= nvme_pci_init_request,
2245 	.timeout	= nvme_timeout,
2246 };
2247 
2248 static const struct blk_mq_ops nvme_mq_ops = {
2249 	.queue_rq	= nvme_queue_rq,
2250 	.queue_rqs	= nvme_queue_rqs,
2251 	.complete	= nvme_pci_complete_rq,
2252 	.commit_rqs	= nvme_commit_rqs,
2253 	.init_hctx	= nvme_init_hctx,
2254 	.init_request	= nvme_pci_init_request,
2255 	.map_queues	= nvme_pci_map_queues,
2256 	.timeout	= nvme_timeout,
2257 	.poll		= nvme_poll,
2258 };
2259 
2260 static void nvme_dev_remove_admin(struct nvme_dev *dev)
2261 {
2262 	if (dev->ctrl.admin_q && !blk_queue_dying(dev->ctrl.admin_q)) {
2263 		/*
2264 		 * If the controller was reset during removal, it's possible
2265 		 * user requests may be waiting on a stopped queue. Start the
2266 		 * queue to flush these to completion.
2267 		 */
2268 		nvme_unquiesce_admin_queue(&dev->ctrl);
2269 		nvme_remove_admin_tag_set(&dev->ctrl);
2270 	}
2271 }
2272 
2273 static unsigned long db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2274 {
2275 	return NVME_REG_DBS + ((nr_io_queues + 1) * 8 * dev->db_stride);
2276 }
2277 
2278 static int nvme_remap_bar(struct nvme_dev *dev, unsigned long size)
2279 {
2280 	struct pci_dev *pdev = to_pci_dev(dev->dev);
2281 
2282 	if (size <= dev->bar_mapped_size)
2283 		return 0;
2284 	if (size > pci_resource_len(pdev, 0))
2285 		return -ENOMEM;
2286 	if (dev->bar)
2287 		iounmap(dev->bar);
2288 	dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2289 	if (!dev->bar) {
2290 		dev->bar_mapped_size = 0;
2291 		return -ENOMEM;
2292 	}
2293 	dev->bar_mapped_size = size;
2294 	dev->dbs = dev->bar + NVME_REG_DBS;
2295 
2296 	return 0;
2297 }
2298 
2299 static int nvme_pci_configure_admin_queue(struct nvme_dev *dev)
2300 {
2301 	int result;
2302 	u32 aqa;
2303 	struct nvme_queue *nvmeq;
2304 
2305 	result = nvme_remap_bar(dev, db_bar_size(dev, 0));
2306 	if (result < 0)
2307 		return result;
2308 
2309 	dev->subsystem = readl(dev->bar + NVME_REG_VS) >= NVME_VS(1, 1, 0) ?
2310 				NVME_CAP_NSSRC(dev->ctrl.cap) : 0;
2311 
2312 	if (dev->subsystem &&
2313 	    (readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_NSSRO))
2314 		writel(NVME_CSTS_NSSRO, dev->bar + NVME_REG_CSTS);
2315 
2316 	/*
2317 	 * If the device has been passed off to us in an enabled state, just
2318 	 * clear the enabled bit.  The spec says we should set the 'shutdown
2319 	 * notification bits', but doing so may cause the device to complete
2320 	 * commands to the admin queue ... and we don't know what memory that
2321 	 * might be pointing at!
2322 	 */
2323 	result = nvme_disable_ctrl(&dev->ctrl, false);
2324 	if (result < 0) {
2325 		struct pci_dev *pdev = to_pci_dev(dev->dev);
2326 
2327 		/*
2328 		 * The NVMe Controller Reset method did not get an expected
2329 		 * CSTS.RDY transition, so something with the device appears to
2330 		 * be stuck. Use the lower level and bigger hammer PCIe
2331 		 * Function Level Reset to attempt restoring the device to its
2332 		 * initial state, and try again.
2333 		 */
2334 		result = pcie_reset_flr(pdev, false);
2335 		if (result < 0)
2336 			return result;
2337 
2338 		pci_restore_state(pdev);
2339 		result = nvme_disable_ctrl(&dev->ctrl, false);
2340 		if (result < 0)
2341 			return result;
2342 
2343 		dev_info(dev->ctrl.device,
2344 			"controller reset completed after pcie flr\n");
2345 	}
2346 
2347 	result = nvme_alloc_queue(dev, 0, NVME_AQ_DEPTH);
2348 	if (result)
2349 		return result;
2350 
2351 	dev->ctrl.numa_node = dev_to_node(dev->dev);
2352 
2353 	nvmeq = &dev->queues[0];
2354 	aqa = nvmeq->q_depth - 1;
2355 	aqa |= aqa << 16;
2356 
2357 	writel(aqa, dev->bar + NVME_REG_AQA);
2358 	lo_hi_writeq(nvmeq->sq_dma_addr, dev->bar + NVME_REG_ASQ);
2359 	lo_hi_writeq(nvmeq->cq_dma_addr, dev->bar + NVME_REG_ACQ);
2360 
2361 	result = nvme_enable_ctrl(&dev->ctrl);
2362 	if (result)
2363 		return result;
2364 
2365 	nvmeq->cq_vector = 0;
2366 	nvme_init_queue(nvmeq, 0);
2367 	result = queue_request_irq(nvmeq);
2368 	if (result) {
2369 		dev->online_queues--;
2370 		return result;
2371 	}
2372 
2373 	set_bit(NVMEQ_ENABLED, &nvmeq->flags);
2374 	return result;
2375 }
2376 
2377 static int nvme_create_io_queues(struct nvme_dev *dev)
2378 {
2379 	unsigned i, max, rw_queues;
2380 	int ret = 0;
2381 
2382 	for (i = dev->ctrl.queue_count; i <= dev->max_qid; i++) {
2383 		if (nvme_alloc_queue(dev, i, dev->q_depth)) {
2384 			ret = -ENOMEM;
2385 			break;
2386 		}
2387 	}
2388 
2389 	max = min(dev->max_qid, dev->ctrl.queue_count - 1);
2390 	if (max != 1 && dev->io_queues[HCTX_TYPE_POLL]) {
2391 		rw_queues = dev->io_queues[HCTX_TYPE_DEFAULT] +
2392 				dev->io_queues[HCTX_TYPE_READ];
2393 	} else {
2394 		rw_queues = max;
2395 	}
2396 
2397 	for (i = dev->online_queues; i <= max; i++) {
2398 		bool polled = i > rw_queues;
2399 
2400 		ret = nvme_create_queue(&dev->queues[i], i, polled);
2401 		if (ret)
2402 			break;
2403 	}
2404 
2405 	/*
2406 	 * Ignore failing Create SQ/CQ commands, we can continue with less
2407 	 * than the desired amount of queues, and even a controller without
2408 	 * I/O queues can still be used to issue admin commands.  This might
2409 	 * be useful to upgrade a buggy firmware for example.
2410 	 */
2411 	return ret >= 0 ? 0 : ret;
2412 }
2413 
2414 static u64 nvme_cmb_size_unit(struct nvme_dev *dev)
2415 {
2416 	u8 szu = (dev->cmbsz >> NVME_CMBSZ_SZU_SHIFT) & NVME_CMBSZ_SZU_MASK;
2417 
2418 	return 1ULL << (12 + 4 * szu);
2419 }
2420 
2421 static u32 nvme_cmb_size(struct nvme_dev *dev)
2422 {
2423 	return (dev->cmbsz >> NVME_CMBSZ_SZ_SHIFT) & NVME_CMBSZ_SZ_MASK;
2424 }
2425 
2426 static void nvme_map_cmb(struct nvme_dev *dev)
2427 {
2428 	u64 size, offset;
2429 	resource_size_t bar_size;
2430 	struct pci_dev *pdev = to_pci_dev(dev->dev);
2431 	int bar;
2432 
2433 	if (dev->cmb_size)
2434 		return;
2435 
2436 	if (NVME_CAP_CMBS(dev->ctrl.cap))
2437 		writel(NVME_CMBMSC_CRE, dev->bar + NVME_REG_CMBMSC);
2438 
2439 	dev->cmbsz = readl(dev->bar + NVME_REG_CMBSZ);
2440 	if (!dev->cmbsz)
2441 		return;
2442 	dev->cmbloc = readl(dev->bar + NVME_REG_CMBLOC);
2443 
2444 	size = nvme_cmb_size_unit(dev) * nvme_cmb_size(dev);
2445 	offset = nvme_cmb_size_unit(dev) * NVME_CMB_OFST(dev->cmbloc);
2446 	bar = NVME_CMB_BIR(dev->cmbloc);
2447 	bar_size = pci_resource_len(pdev, bar);
2448 
2449 	if (offset > bar_size)
2450 		return;
2451 
2452 	/*
2453 	 * Controllers may support a CMB size larger than their BAR, for
2454 	 * example, due to being behind a bridge. Reduce the CMB to the
2455 	 * reported size of the BAR
2456 	 */
2457 	size = min(size, bar_size - offset);
2458 
2459 	if (!IS_ALIGNED(size, memremap_compat_align()) ||
2460 	    !IS_ALIGNED(pci_resource_start(pdev, bar),
2461 			memremap_compat_align()))
2462 		return;
2463 
2464 	/*
2465 	 * Tell the controller about the host side address mapping the CMB,
2466 	 * and enable CMB decoding for the NVMe 1.4+ scheme:
2467 	 */
2468 	if (NVME_CAP_CMBS(dev->ctrl.cap)) {
2469 		hi_lo_writeq(NVME_CMBMSC_CRE | NVME_CMBMSC_CMSE |
2470 			     (pci_bus_address(pdev, bar) + offset),
2471 			     dev->bar + NVME_REG_CMBMSC);
2472 	}
2473 
2474 	if (pci_p2pdma_add_resource(pdev, bar, size, offset)) {
2475 		dev_warn(dev->ctrl.device,
2476 			 "failed to register the CMB\n");
2477 		hi_lo_writeq(0, dev->bar + NVME_REG_CMBMSC);
2478 		return;
2479 	}
2480 
2481 	dev->cmb_size = size;
2482 	dev->cmb_use_sqes = use_cmb_sqes && (dev->cmbsz & NVME_CMBSZ_SQS);
2483 
2484 	if ((dev->cmbsz & (NVME_CMBSZ_WDS | NVME_CMBSZ_RDS)) ==
2485 			(NVME_CMBSZ_WDS | NVME_CMBSZ_RDS))
2486 		pci_p2pmem_publish(pdev, true);
2487 }
2488 
2489 static int nvme_set_host_mem(struct nvme_dev *dev, u32 bits)
2490 {
2491 	u32 host_mem_size = dev->host_mem_size >> NVME_CTRL_PAGE_SHIFT;
2492 	u64 dma_addr = dev->host_mem_descs_dma;
2493 	struct nvme_command c = { };
2494 	int ret;
2495 
2496 	c.features.opcode	= nvme_admin_set_features;
2497 	c.features.fid		= cpu_to_le32(NVME_FEAT_HOST_MEM_BUF);
2498 	c.features.dword11	= cpu_to_le32(bits);
2499 	c.features.dword12	= cpu_to_le32(host_mem_size);
2500 	c.features.dword13	= cpu_to_le32(lower_32_bits(dma_addr));
2501 	c.features.dword14	= cpu_to_le32(upper_32_bits(dma_addr));
2502 	c.features.dword15	= cpu_to_le32(dev->nr_host_mem_descs);
2503 
2504 	ret = nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
2505 	if (ret) {
2506 		dev_warn(dev->ctrl.device,
2507 			 "failed to set host mem (err %d, flags %#x).\n",
2508 			 ret, bits);
2509 	} else
2510 		dev->hmb = bits & NVME_HOST_MEM_ENABLE;
2511 
2512 	return ret;
2513 }
2514 
2515 static void nvme_free_host_mem_multi(struct nvme_dev *dev)
2516 {
2517 	int i;
2518 
2519 	for (i = 0; i < dev->nr_host_mem_descs; i++) {
2520 		struct nvme_host_mem_buf_desc *desc = &dev->host_mem_descs[i];
2521 		size_t size = le32_to_cpu(desc->size) * NVME_CTRL_PAGE_SIZE;
2522 
2523 		dma_free_attrs(dev->dev, size, dev->host_mem_desc_bufs[i],
2524 			       le64_to_cpu(desc->addr),
2525 			       DMA_ATTR_NO_KERNEL_MAPPING | DMA_ATTR_NO_WARN);
2526 	}
2527 
2528 	kfree(dev->host_mem_desc_bufs);
2529 	dev->host_mem_desc_bufs = NULL;
2530 }
2531 
2532 static void nvme_free_host_mem(struct nvme_dev *dev)
2533 {
2534 	if (dev->hmb_sgt)
2535 		dma_free_noncontiguous(dev->dev, dev->host_mem_size,
2536 				dev->hmb_sgt, DMA_BIDIRECTIONAL);
2537 	else
2538 		nvme_free_host_mem_multi(dev);
2539 
2540 	dma_free_coherent(dev->dev, dev->host_mem_descs_size,
2541 			dev->host_mem_descs, dev->host_mem_descs_dma);
2542 	dev->host_mem_descs = NULL;
2543 	dev->host_mem_descs_size = 0;
2544 	dev->nr_host_mem_descs = 0;
2545 }
2546 
2547 static int nvme_alloc_host_mem_single(struct nvme_dev *dev, u64 size)
2548 {
2549 	dev->hmb_sgt = dma_alloc_noncontiguous(dev->dev, size,
2550 				DMA_BIDIRECTIONAL, GFP_KERNEL, 0);
2551 	if (!dev->hmb_sgt)
2552 		return -ENOMEM;
2553 
2554 	dev->host_mem_descs = dma_alloc_coherent(dev->dev,
2555 			sizeof(*dev->host_mem_descs), &dev->host_mem_descs_dma,
2556 			GFP_KERNEL);
2557 	if (!dev->host_mem_descs) {
2558 		dma_free_noncontiguous(dev->dev, size, dev->hmb_sgt,
2559 				DMA_BIDIRECTIONAL);
2560 		dev->hmb_sgt = NULL;
2561 		return -ENOMEM;
2562 	}
2563 	dev->host_mem_size = size;
2564 	dev->host_mem_descs_size = sizeof(*dev->host_mem_descs);
2565 	dev->nr_host_mem_descs = 1;
2566 
2567 	dev->host_mem_descs[0].addr =
2568 		cpu_to_le64(dev->hmb_sgt->sgl->dma_address);
2569 	dev->host_mem_descs[0].size = cpu_to_le32(size / NVME_CTRL_PAGE_SIZE);
2570 	return 0;
2571 }
2572 
2573 static int nvme_alloc_host_mem_multi(struct nvme_dev *dev, u64 preferred,
2574 		u32 chunk_size)
2575 {
2576 	struct nvme_host_mem_buf_desc *descs;
2577 	u32 max_entries, len, descs_size;
2578 	dma_addr_t descs_dma;
2579 	int i = 0;
2580 	void **bufs;
2581 	u64 size, tmp;
2582 
2583 	tmp = (preferred + chunk_size - 1);
2584 	do_div(tmp, chunk_size);
2585 	max_entries = tmp;
2586 
2587 	if (dev->ctrl.hmmaxd && dev->ctrl.hmmaxd < max_entries)
2588 		max_entries = dev->ctrl.hmmaxd;
2589 
2590 	descs_size = max_entries * sizeof(*descs);
2591 	descs = dma_alloc_coherent(dev->dev, descs_size, &descs_dma,
2592 			GFP_KERNEL);
2593 	if (!descs)
2594 		goto out;
2595 
2596 	bufs = kzalloc_objs(*bufs, max_entries);
2597 	if (!bufs)
2598 		goto out_free_descs;
2599 
2600 	for (size = 0; size < preferred && i < max_entries; size += len) {
2601 		dma_addr_t dma_addr;
2602 
2603 		len = min_t(u64, chunk_size, preferred - size);
2604 		bufs[i] = dma_alloc_attrs(dev->dev, len, &dma_addr, GFP_KERNEL,
2605 				DMA_ATTR_NO_KERNEL_MAPPING | DMA_ATTR_NO_WARN);
2606 		if (!bufs[i])
2607 			break;
2608 
2609 		descs[i].addr = cpu_to_le64(dma_addr);
2610 		descs[i].size = cpu_to_le32(len / NVME_CTRL_PAGE_SIZE);
2611 		i++;
2612 	}
2613 
2614 	if (!size)
2615 		goto out_free_bufs;
2616 
2617 	dev->nr_host_mem_descs = i;
2618 	dev->host_mem_size = size;
2619 	dev->host_mem_descs = descs;
2620 	dev->host_mem_descs_dma = descs_dma;
2621 	dev->host_mem_descs_size = descs_size;
2622 	dev->host_mem_desc_bufs = bufs;
2623 	return 0;
2624 
2625 out_free_bufs:
2626 	kfree(bufs);
2627 out_free_descs:
2628 	dma_free_coherent(dev->dev, descs_size, descs, descs_dma);
2629 out:
2630 	dev->host_mem_descs = NULL;
2631 	return -ENOMEM;
2632 }
2633 
2634 static int nvme_alloc_host_mem(struct nvme_dev *dev, u64 min, u64 preferred)
2635 {
2636 	unsigned long dma_merge_boundary = dma_get_merge_boundary(dev->dev);
2637 	u64 min_chunk = min_t(u64, preferred, PAGE_SIZE * MAX_ORDER_NR_PAGES);
2638 	u64 hmminds = max_t(u32, dev->ctrl.hmminds * 4096, PAGE_SIZE * 2);
2639 	u64 chunk_size;
2640 
2641 	/*
2642 	 * If there is an IOMMU that can merge pages, try a virtually
2643 	 * non-contiguous allocation for a single segment first.
2644 	 */
2645 	if (dma_merge_boundary && (PAGE_SIZE & dma_merge_boundary) == 0) {
2646 		if (!nvme_alloc_host_mem_single(dev, preferred))
2647 			return 0;
2648 	}
2649 
2650 	/* start big and work our way down */
2651 	for (chunk_size = min_chunk; chunk_size >= hmminds; chunk_size /= 2) {
2652 		if (!nvme_alloc_host_mem_multi(dev, preferred, chunk_size)) {
2653 			if (!min || dev->host_mem_size >= min)
2654 				return 0;
2655 			nvme_free_host_mem(dev);
2656 		}
2657 	}
2658 
2659 	return -ENOMEM;
2660 }
2661 
2662 static int nvme_setup_host_mem(struct nvme_dev *dev)
2663 {
2664 	u64 max = (u64)max_host_mem_size_mb * SZ_1M;
2665 	u64 preferred = (u64)dev->ctrl.hmpre * 4096;
2666 	u64 min = (u64)dev->ctrl.hmmin * 4096;
2667 	u32 enable_bits = NVME_HOST_MEM_ENABLE;
2668 	int ret;
2669 
2670 	if (!dev->ctrl.hmpre)
2671 		return 0;
2672 
2673 	preferred = min(preferred, max);
2674 	if (min > max) {
2675 		dev_warn(dev->ctrl.device,
2676 			"min host memory (%lld MiB) above limit (%d MiB).\n",
2677 			min >> ilog2(SZ_1M), max_host_mem_size_mb);
2678 		nvme_free_host_mem(dev);
2679 		return 0;
2680 	}
2681 
2682 	/*
2683 	 * If we already have a buffer allocated check if we can reuse it.
2684 	 */
2685 	if (dev->host_mem_descs) {
2686 		if (dev->host_mem_size >= min)
2687 			enable_bits |= NVME_HOST_MEM_RETURN;
2688 		else
2689 			nvme_free_host_mem(dev);
2690 	}
2691 
2692 	if (!dev->host_mem_descs) {
2693 		if (nvme_alloc_host_mem(dev, min, preferred)) {
2694 			dev_warn(dev->ctrl.device,
2695 				"failed to allocate host memory buffer.\n");
2696 			return 0; /* controller must work without HMB */
2697 		}
2698 
2699 		dev_info(dev->ctrl.device,
2700 			"allocated %lld MiB host memory buffer (%u segment%s).\n",
2701 			dev->host_mem_size >> ilog2(SZ_1M),
2702 			dev->nr_host_mem_descs,
2703 			str_plural(dev->nr_host_mem_descs));
2704 	}
2705 
2706 	ret = nvme_set_host_mem(dev, enable_bits);
2707 	if (ret)
2708 		nvme_free_host_mem(dev);
2709 	return ret;
2710 }
2711 
2712 static ssize_t cmb_show(struct device *dev, struct device_attribute *attr,
2713 		char *buf)
2714 {
2715 	struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
2716 
2717 	return sysfs_emit(buf, "cmbloc : 0x%08x\ncmbsz  : 0x%08x\n",
2718 		       ndev->cmbloc, ndev->cmbsz);
2719 }
2720 static DEVICE_ATTR_RO(cmb);
2721 
2722 static ssize_t cmbloc_show(struct device *dev, struct device_attribute *attr,
2723 		char *buf)
2724 {
2725 	struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
2726 
2727 	return sysfs_emit(buf, "%u\n", ndev->cmbloc);
2728 }
2729 static DEVICE_ATTR_RO(cmbloc);
2730 
2731 static ssize_t cmbsz_show(struct device *dev, struct device_attribute *attr,
2732 		char *buf)
2733 {
2734 	struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
2735 
2736 	return sysfs_emit(buf, "%u\n", ndev->cmbsz);
2737 }
2738 static DEVICE_ATTR_RO(cmbsz);
2739 
2740 static ssize_t hmb_show(struct device *dev, struct device_attribute *attr,
2741 			char *buf)
2742 {
2743 	struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
2744 
2745 	return sysfs_emit(buf, "%d\n", ndev->hmb);
2746 }
2747 
2748 static ssize_t hmb_store(struct device *dev, struct device_attribute *attr,
2749 			 const char *buf, size_t count)
2750 {
2751 	struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
2752 	bool new;
2753 	int ret;
2754 
2755 	if (kstrtobool(buf, &new) < 0)
2756 		return -EINVAL;
2757 
2758 	if (new == ndev->hmb)
2759 		return count;
2760 
2761 	if (new) {
2762 		ret = nvme_setup_host_mem(ndev);
2763 	} else {
2764 		ret = nvme_set_host_mem(ndev, 0);
2765 		if (!ret)
2766 			nvme_free_host_mem(ndev);
2767 	}
2768 
2769 	if (ret < 0)
2770 		return ret;
2771 
2772 	return count;
2773 }
2774 static DEVICE_ATTR_RW(hmb);
2775 
2776 static umode_t nvme_pci_attrs_are_visible(struct kobject *kobj,
2777 		struct attribute *a, int n)
2778 {
2779 	struct nvme_ctrl *ctrl =
2780 		dev_get_drvdata(container_of(kobj, struct device, kobj));
2781 	struct nvme_dev *dev = to_nvme_dev(ctrl);
2782 
2783 	if (a == &dev_attr_cmb.attr ||
2784 	    a == &dev_attr_cmbloc.attr ||
2785 	    a == &dev_attr_cmbsz.attr) {
2786 	    	if (!dev->cmbsz)
2787 			return 0;
2788 	}
2789 	if (a == &dev_attr_hmb.attr && !ctrl->hmpre)
2790 		return 0;
2791 
2792 	return a->mode;
2793 }
2794 
2795 static struct attribute *nvme_pci_attrs[] = {
2796 	&dev_attr_cmb.attr,
2797 	&dev_attr_cmbloc.attr,
2798 	&dev_attr_cmbsz.attr,
2799 	&dev_attr_hmb.attr,
2800 	NULL,
2801 };
2802 
2803 static const struct attribute_group nvme_pci_dev_attrs_group = {
2804 	.attrs		= nvme_pci_attrs,
2805 	.is_visible	= nvme_pci_attrs_are_visible,
2806 };
2807 
2808 static const struct attribute_group *nvme_pci_dev_attr_groups[] = {
2809 	&nvme_dev_attrs_group,
2810 	&nvme_pci_dev_attrs_group,
2811 	NULL,
2812 };
2813 
2814 static void nvme_update_attrs(struct nvme_dev *dev)
2815 {
2816 	sysfs_update_group(&dev->ctrl.device->kobj, &nvme_pci_dev_attrs_group);
2817 }
2818 
2819 /*
2820  * nirqs is the number of interrupts available for write and read
2821  * queues. The core already reserved an interrupt for the admin queue.
2822  */
2823 static void nvme_calc_irq_sets(struct irq_affinity *affd, unsigned int nrirqs)
2824 {
2825 	struct nvme_dev *dev = affd->priv;
2826 	unsigned int nr_read_queues, nr_write_queues = dev->nr_write_queues;
2827 
2828 	/*
2829 	 * If there is no interrupt available for queues, ensure that
2830 	 * the default queue is set to 1. The affinity set size is
2831 	 * also set to one, but the irq core ignores it for this case.
2832 	 *
2833 	 * If only one interrupt is available or 'write_queue' == 0, combine
2834 	 * write and read queues.
2835 	 *
2836 	 * If 'write_queues' > 0, ensure it leaves room for at least one read
2837 	 * queue.
2838 	 */
2839 	if (!nrirqs) {
2840 		nrirqs = 1;
2841 		nr_read_queues = 0;
2842 	} else if (nrirqs == 1 || !nr_write_queues) {
2843 		nr_read_queues = 0;
2844 	} else if (nr_write_queues >= nrirqs) {
2845 		nr_read_queues = 1;
2846 	} else {
2847 		nr_read_queues = nrirqs - nr_write_queues;
2848 	}
2849 
2850 	dev->io_queues[HCTX_TYPE_DEFAULT] = nrirqs - nr_read_queues;
2851 	affd->set_size[HCTX_TYPE_DEFAULT] = nrirqs - nr_read_queues;
2852 	dev->io_queues[HCTX_TYPE_READ] = nr_read_queues;
2853 	affd->set_size[HCTX_TYPE_READ] = nr_read_queues;
2854 	affd->nr_sets = nr_read_queues ? 2 : 1;
2855 }
2856 
2857 static int nvme_setup_irqs(struct nvme_dev *dev, unsigned int nr_io_queues)
2858 {
2859 	struct pci_dev *pdev = to_pci_dev(dev->dev);
2860 	struct irq_affinity affd = {
2861 		.pre_vectors	= 1,
2862 		.calc_sets	= nvme_calc_irq_sets,
2863 		.priv		= dev,
2864 	};
2865 	unsigned int irq_queues, poll_queues;
2866 	unsigned int flags = PCI_IRQ_ALL_TYPES | PCI_IRQ_AFFINITY;
2867 
2868 	/*
2869 	 * Poll queues don't need interrupts, but we need at least one I/O queue
2870 	 * left over for non-polled I/O.
2871 	 */
2872 	poll_queues = min(dev->nr_poll_queues, nr_io_queues - 1);
2873 	dev->io_queues[HCTX_TYPE_POLL] = poll_queues;
2874 
2875 	/*
2876 	 * Initialize for the single interrupt case, will be updated in
2877 	 * nvme_calc_irq_sets().
2878 	 */
2879 	dev->io_queues[HCTX_TYPE_DEFAULT] = 1;
2880 	dev->io_queues[HCTX_TYPE_READ] = 0;
2881 
2882 	/*
2883 	 * We need interrupts for the admin queue and each non-polled I/O queue,
2884 	 * but some Apple controllers require all queues to use the first
2885 	 * vector.
2886 	 */
2887 	irq_queues = 1;
2888 	if (!(dev->ctrl.quirks & NVME_QUIRK_SINGLE_VECTOR))
2889 		irq_queues += (nr_io_queues - poll_queues);
2890 	if (dev->ctrl.quirks & NVME_QUIRK_BROKEN_MSI)
2891 		flags &= ~PCI_IRQ_MSI;
2892 	return pci_alloc_irq_vectors_affinity(pdev, 1, irq_queues, flags,
2893 					      &affd);
2894 }
2895 
2896 static unsigned int nvme_max_io_queues(struct nvme_dev *dev)
2897 {
2898 	/*
2899 	 * If tags are shared with admin queue (Apple bug), then
2900 	 * make sure we only use one IO queue.
2901 	 */
2902 	if (dev->ctrl.quirks & NVME_QUIRK_SHARED_TAGS)
2903 		return 1;
2904 	return blk_mq_num_possible_queues(0) + dev->nr_write_queues +
2905 		dev->nr_poll_queues;
2906 }
2907 
2908 static int nvme_setup_io_queues(struct nvme_dev *dev)
2909 {
2910 	struct nvme_queue *adminq = &dev->queues[0];
2911 	struct pci_dev *pdev = to_pci_dev(dev->dev);
2912 	unsigned int nr_io_queues;
2913 	unsigned long size;
2914 	int result;
2915 
2916 	/*
2917 	 * Sample the module parameters once at reset time so that we have
2918 	 * stable values to work with.
2919 	 */
2920 	dev->nr_write_queues = write_queues;
2921 	dev->nr_poll_queues = poll_queues;
2922 
2923 	if (dev->ctrl.tagset) {
2924 		/*
2925 		 * The set's maps are allocated only once at initialization
2926 		 * time. We can't add special queues later if their mq_map
2927 		 * wasn't preallocated.
2928 		 */
2929 		if (dev->ctrl.tagset->nr_maps < 3)
2930 			dev->nr_poll_queues = 0;
2931 		if (dev->ctrl.tagset->nr_maps < 2)
2932 			dev->nr_write_queues = 0;
2933 	}
2934 
2935 	/*
2936 	 * The initial number of allocated queue slots may be too large if the
2937 	 * user reduced the special queue parameters. Cap the value to the
2938 	 * number we need for this round.
2939 	 */
2940 	nr_io_queues = min(nvme_max_io_queues(dev),
2941 			   dev->nr_allocated_queues - 1);
2942 	result = nvme_set_queue_count(&dev->ctrl, &nr_io_queues);
2943 	if (result < 0)
2944 		return result;
2945 
2946 	if (nr_io_queues == 0)
2947 		return 0;
2948 
2949 	/*
2950 	 * Free IRQ resources as soon as NVMEQ_ENABLED bit transitions
2951 	 * from set to unset. If there is a window to it is truely freed,
2952 	 * pci_free_irq_vectors() jumping into this window will crash.
2953 	 * And take lock to avoid racing with pci_free_irq_vectors() in
2954 	 * nvme_dev_disable() path.
2955 	 */
2956 	result = nvme_setup_io_queues_trylock(dev);
2957 	if (result)
2958 		return result;
2959 	if (test_and_clear_bit(NVMEQ_ENABLED, &adminq->flags))
2960 		pci_free_irq(pdev, 0, adminq);
2961 
2962 	if (dev->cmb_use_sqes) {
2963 		result = nvme_cmb_qdepth(dev, nr_io_queues,
2964 				sizeof(struct nvme_command));
2965 		if (result > 0) {
2966 			dev->q_depth = result;
2967 			dev->ctrl.sqsize = result - 1;
2968 		} else {
2969 			dev->cmb_use_sqes = false;
2970 		}
2971 	}
2972 
2973 	do {
2974 		size = db_bar_size(dev, nr_io_queues);
2975 		result = nvme_remap_bar(dev, size);
2976 		if (!result)
2977 			break;
2978 		if (!--nr_io_queues) {
2979 			result = -ENOMEM;
2980 			goto out_unlock;
2981 		}
2982 	} while (1);
2983 	adminq->q_db = dev->dbs;
2984 
2985  retry:
2986 	/* Deregister the admin queue's interrupt */
2987 	if (test_and_clear_bit(NVMEQ_ENABLED, &adminq->flags))
2988 		pci_free_irq(pdev, 0, adminq);
2989 
2990 	/*
2991 	 * If we enable msix early due to not intx, disable it again before
2992 	 * setting up the full range we need.
2993 	 */
2994 	pci_free_irq_vectors(pdev);
2995 
2996 	result = nvme_setup_irqs(dev, nr_io_queues);
2997 	if (result <= 0) {
2998 		result = -EIO;
2999 		goto out_unlock;
3000 	}
3001 
3002 	dev->num_vecs = result;
3003 	result = max(result - 1, 1);
3004 	dev->max_qid = result + dev->io_queues[HCTX_TYPE_POLL];
3005 
3006 	/*
3007 	 * Should investigate if there's a performance win from allocating
3008 	 * more queues than interrupt vectors; it might allow the submission
3009 	 * path to scale better, even if the receive path is limited by the
3010 	 * number of interrupts.
3011 	 */
3012 	result = queue_request_irq(adminq);
3013 	if (result)
3014 		goto out_unlock;
3015 	set_bit(NVMEQ_ENABLED, &adminq->flags);
3016 	mutex_unlock(&dev->shutdown_lock);
3017 
3018 	result = nvme_create_io_queues(dev);
3019 	if (result || dev->online_queues < 2)
3020 		return result;
3021 
3022 	if (dev->online_queues - 1 < dev->max_qid) {
3023 		nr_io_queues = dev->online_queues - 1;
3024 		nvme_delete_io_queues(dev);
3025 		result = nvme_setup_io_queues_trylock(dev);
3026 		if (result)
3027 			return result;
3028 		nvme_suspend_io_queues(dev);
3029 		goto retry;
3030 	}
3031 	dev_info(dev->ctrl.device, "%d/%d/%d default/read/poll queues\n",
3032 					dev->io_queues[HCTX_TYPE_DEFAULT],
3033 					dev->io_queues[HCTX_TYPE_READ],
3034 					dev->io_queues[HCTX_TYPE_POLL]);
3035 	return 0;
3036 out_unlock:
3037 	mutex_unlock(&dev->shutdown_lock);
3038 	return result;
3039 }
3040 
3041 static enum rq_end_io_ret nvme_del_queue_end(struct request *req,
3042 					     blk_status_t error,
3043 					     const struct io_comp_batch *iob)
3044 {
3045 	struct nvme_queue *nvmeq = req->end_io_data;
3046 
3047 	blk_mq_free_request(req);
3048 	complete(&nvmeq->delete_done);
3049 	return RQ_END_IO_NONE;
3050 }
3051 
3052 static enum rq_end_io_ret nvme_del_cq_end(struct request *req,
3053 					  blk_status_t error,
3054 					  const struct io_comp_batch *iob)
3055 {
3056 	struct nvme_queue *nvmeq = req->end_io_data;
3057 
3058 	if (error)
3059 		set_bit(NVMEQ_DELETE_ERROR, &nvmeq->flags);
3060 
3061 	return nvme_del_queue_end(req, error, iob);
3062 }
3063 
3064 static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode)
3065 {
3066 	struct request_queue *q = nvmeq->dev->ctrl.admin_q;
3067 	struct request *req;
3068 	struct nvme_command cmd = { };
3069 
3070 	cmd.delete_queue.opcode = opcode;
3071 	cmd.delete_queue.qid = cpu_to_le16(nvmeq->qid);
3072 
3073 	req = blk_mq_alloc_request(q, nvme_req_op(&cmd), BLK_MQ_REQ_NOWAIT);
3074 	if (IS_ERR(req))
3075 		return PTR_ERR(req);
3076 	nvme_init_request(req, &cmd);
3077 
3078 	if (opcode == nvme_admin_delete_cq)
3079 		req->end_io = nvme_del_cq_end;
3080 	else
3081 		req->end_io = nvme_del_queue_end;
3082 	req->end_io_data = nvmeq;
3083 
3084 	init_completion(&nvmeq->delete_done);
3085 	blk_execute_rq_nowait(req, false);
3086 	return 0;
3087 }
3088 
3089 static bool __nvme_delete_io_queues(struct nvme_dev *dev, u8 opcode)
3090 {
3091 	int nr_queues = dev->online_queues - 1, sent = 0;
3092 	unsigned long timeout;
3093 
3094  retry:
3095 	timeout = NVME_ADMIN_TIMEOUT;
3096 	while (nr_queues > 0) {
3097 		if (nvme_delete_queue(&dev->queues[nr_queues], opcode))
3098 			break;
3099 		nr_queues--;
3100 		sent++;
3101 	}
3102 	while (sent) {
3103 		struct nvme_queue *nvmeq = &dev->queues[nr_queues + sent];
3104 
3105 		timeout = wait_for_completion_io_timeout(&nvmeq->delete_done,
3106 				timeout);
3107 		if (timeout == 0)
3108 			return false;
3109 
3110 		sent--;
3111 		if (nr_queues)
3112 			goto retry;
3113 	}
3114 	return true;
3115 }
3116 
3117 static void nvme_delete_io_queues(struct nvme_dev *dev)
3118 {
3119 	if (__nvme_delete_io_queues(dev, nvme_admin_delete_sq))
3120 		__nvme_delete_io_queues(dev, nvme_admin_delete_cq);
3121 }
3122 
3123 static unsigned int nvme_pci_nr_maps(struct nvme_dev *dev)
3124 {
3125 	if (dev->io_queues[HCTX_TYPE_POLL])
3126 		return 3;
3127 	if (dev->io_queues[HCTX_TYPE_READ])
3128 		return 2;
3129 	return 1;
3130 }
3131 
3132 static bool nvme_pci_update_nr_queues(struct nvme_dev *dev)
3133 {
3134 	if (!dev->ctrl.tagset) {
3135 		nvme_alloc_io_tag_set(&dev->ctrl, &dev->tagset, &nvme_mq_ops,
3136 				nvme_pci_nr_maps(dev), sizeof(struct nvme_iod));
3137 		return true;
3138 	}
3139 
3140 	/* Give up if we are racing with nvme_dev_disable() */
3141 	if (!mutex_trylock(&dev->shutdown_lock))
3142 		return false;
3143 
3144 	/* Check if nvme_dev_disable() has been executed already */
3145 	if (!dev->online_queues) {
3146 		mutex_unlock(&dev->shutdown_lock);
3147 		return false;
3148 	}
3149 
3150 	blk_mq_update_nr_hw_queues(&dev->tagset, dev->online_queues - 1);
3151 	/* free previously allocated queues that are no longer usable */
3152 	nvme_free_queues(dev, dev->online_queues);
3153 	mutex_unlock(&dev->shutdown_lock);
3154 	return true;
3155 }
3156 
3157 static int nvme_pci_enable(struct nvme_dev *dev)
3158 {
3159 	int result = -ENOMEM;
3160 	struct pci_dev *pdev = to_pci_dev(dev->dev);
3161 	unsigned int flags = PCI_IRQ_ALL_TYPES;
3162 
3163 	if (pci_enable_device_mem(pdev))
3164 		return result;
3165 
3166 	pci_set_master(pdev);
3167 
3168 	if (readl(dev->bar + NVME_REG_CSTS) == -1) {
3169 		dev_dbg(dev->ctrl.device, "reading CSTS register failed\n");
3170 		result = -ENODEV;
3171 		goto disable;
3172 	}
3173 
3174 	/*
3175 	 * Some devices and/or platforms don't advertise or work with INTx
3176 	 * interrupts. Pre-enable a single MSIX or MSI vec for setup. We'll
3177 	 * adjust this later.
3178 	 */
3179 	if (dev->ctrl.quirks & NVME_QUIRK_BROKEN_MSI)
3180 		flags &= ~PCI_IRQ_MSI;
3181 	result = pci_alloc_irq_vectors(pdev, 1, 1, flags);
3182 	if (result < 0)
3183 		goto disable;
3184 
3185 	dev->ctrl.cap = lo_hi_readq(dev->bar + NVME_REG_CAP);
3186 
3187 	dev->q_depth = min_t(u32, NVME_CAP_MQES(dev->ctrl.cap) + 1,
3188 				io_queue_depth);
3189 	dev->db_stride = 1 << NVME_CAP_STRIDE(dev->ctrl.cap);
3190 	dev->dbs = dev->bar + 4096;
3191 
3192 	/*
3193 	 * Some Apple controllers require a non-standard SQE size.
3194 	 * Interestingly they also seem to ignore the CC:IOSQES register
3195 	 * so we don't bother updating it here.
3196 	 */
3197 	if (dev->ctrl.quirks & NVME_QUIRK_128_BYTES_SQES)
3198 		dev->io_sqes = 7;
3199 	else
3200 		dev->io_sqes = NVME_NVM_IOSQES;
3201 
3202 	if (dev->ctrl.quirks & NVME_QUIRK_QDEPTH_ONE) {
3203 		dev->q_depth = 2;
3204 	} else if (pdev->vendor == PCI_VENDOR_ID_SAMSUNG &&
3205 		   (pdev->device == 0xa821 || pdev->device == 0xa822) &&
3206 		   NVME_CAP_MQES(dev->ctrl.cap) == 0) {
3207 		dev->q_depth = 64;
3208 		dev_err(dev->ctrl.device, "detected PM1725 NVMe controller, "
3209                         "set queue depth=%u\n", dev->q_depth);
3210 	}
3211 
3212 	/*
3213 	 * Controllers with the shared tags quirk need the IO queue to be
3214 	 * big enough so that we get 32 tags for the admin queue
3215 	 */
3216 	if ((dev->ctrl.quirks & NVME_QUIRK_SHARED_TAGS) &&
3217 	    (dev->q_depth < (NVME_AQ_DEPTH + 2))) {
3218 		dev->q_depth = NVME_AQ_DEPTH + 2;
3219 		dev_warn(dev->ctrl.device, "IO queue depth clamped to %d\n",
3220 			 dev->q_depth);
3221 	}
3222 	dev->ctrl.sqsize = dev->q_depth - 1; /* 0's based queue depth */
3223 
3224 	nvme_map_cmb(dev);
3225 
3226 	pci_save_state(pdev);
3227 
3228 	result = nvme_pci_configure_admin_queue(dev);
3229 	if (result)
3230 		goto free_irq;
3231 	return result;
3232 
3233  free_irq:
3234 	pci_free_irq_vectors(pdev);
3235  disable:
3236 	pci_disable_device(pdev);
3237 	return result;
3238 }
3239 
3240 static void nvme_dev_unmap(struct nvme_dev *dev)
3241 {
3242 	if (dev->bar)
3243 		iounmap(dev->bar);
3244 	pci_release_mem_regions(to_pci_dev(dev->dev));
3245 }
3246 
3247 static bool nvme_pci_ctrl_is_dead(struct nvme_dev *dev)
3248 {
3249 	struct pci_dev *pdev = to_pci_dev(dev->dev);
3250 	u32 csts;
3251 
3252 	if (!pci_is_enabled(pdev) || !pci_device_is_present(pdev))
3253 		return true;
3254 	if (pdev->error_state != pci_channel_io_normal)
3255 		return true;
3256 
3257 	csts = readl(dev->bar + NVME_REG_CSTS);
3258 	return (csts & NVME_CSTS_CFS) || !(csts & NVME_CSTS_RDY);
3259 }
3260 
3261 static void nvme_dev_disable(struct nvme_dev *dev, bool shutdown)
3262 {
3263 	enum nvme_ctrl_state state = nvme_ctrl_state(&dev->ctrl);
3264 	struct pci_dev *pdev = to_pci_dev(dev->dev);
3265 	bool dead;
3266 
3267 	mutex_lock(&dev->shutdown_lock);
3268 	dead = nvme_pci_ctrl_is_dead(dev);
3269 	if (state == NVME_CTRL_LIVE || state == NVME_CTRL_RESETTING) {
3270 		if (pci_is_enabled(pdev))
3271 			nvme_start_freeze(&dev->ctrl);
3272 		/*
3273 		 * Give the controller a chance to complete all entered requests
3274 		 * if doing a safe shutdown.
3275 		 */
3276 		if (!dead && shutdown)
3277 			nvme_wait_freeze_timeout(&dev->ctrl, NVME_IO_TIMEOUT);
3278 	}
3279 
3280 	nvme_quiesce_io_queues(&dev->ctrl);
3281 
3282 	if (!dead && dev->ctrl.queue_count > 0) {
3283 		nvme_delete_io_queues(dev);
3284 		nvme_disable_ctrl(&dev->ctrl, shutdown);
3285 		nvme_poll_irqdisable(&dev->queues[0]);
3286 	}
3287 	nvme_suspend_io_queues(dev);
3288 	nvme_suspend_queue(dev, 0);
3289 	pci_free_irq_vectors(pdev);
3290 	if (pci_is_enabled(pdev))
3291 		pci_disable_device(pdev);
3292 	nvme_reap_pending_cqes(dev);
3293 
3294 	nvme_cancel_tagset(&dev->ctrl);
3295 	nvme_cancel_admin_tagset(&dev->ctrl);
3296 
3297 	/*
3298 	 * The driver will not be starting up queues again if shutting down so
3299 	 * must flush all entered requests to their failed completion to avoid
3300 	 * deadlocking blk-mq hot-cpu notifier.
3301 	 */
3302 	if (shutdown) {
3303 		nvme_unquiesce_io_queues(&dev->ctrl);
3304 		if (dev->ctrl.admin_q && !blk_queue_dying(dev->ctrl.admin_q))
3305 			nvme_unquiesce_admin_queue(&dev->ctrl);
3306 	}
3307 	mutex_unlock(&dev->shutdown_lock);
3308 }
3309 
3310 static int nvme_disable_prepare_reset(struct nvme_dev *dev, bool shutdown)
3311 {
3312 	if (!nvme_wait_reset(&dev->ctrl))
3313 		return -EBUSY;
3314 	nvme_dev_disable(dev, shutdown);
3315 	return 0;
3316 }
3317 
3318 static int nvme_pci_alloc_iod_mempool(struct nvme_dev *dev)
3319 {
3320 	size_t alloc_size = sizeof(struct nvme_dma_vec) * NVME_MAX_SEGS;
3321 
3322 	dev->dmavec_mempool = mempool_create_node(1,
3323 			mempool_kmalloc, mempool_kfree,
3324 			(void *)alloc_size, GFP_KERNEL,
3325 			dev_to_node(dev->dev));
3326 	if (!dev->dmavec_mempool)
3327 		return -ENOMEM;
3328 	return 0;
3329 }
3330 
3331 static void nvme_free_tagset(struct nvme_dev *dev)
3332 {
3333 	if (dev->tagset.tags)
3334 		nvme_remove_io_tag_set(&dev->ctrl);
3335 	dev->ctrl.tagset = NULL;
3336 }
3337 
3338 /* pairs with nvme_pci_alloc_dev */
3339 static void nvme_pci_free_ctrl(struct nvme_ctrl *ctrl)
3340 {
3341 	struct nvme_dev *dev = to_nvme_dev(ctrl);
3342 
3343 	nvme_free_tagset(dev);
3344 	put_device(dev->dev);
3345 	kfree(dev->queues);
3346 	kfree(dev);
3347 }
3348 
3349 static void nvme_reset_work(struct work_struct *work)
3350 {
3351 	struct nvme_dev *dev =
3352 		container_of(work, struct nvme_dev, ctrl.reset_work);
3353 	bool was_suspend = !!(dev->ctrl.ctrl_config & NVME_CC_SHN_NORMAL);
3354 	int result;
3355 
3356 	if (nvme_ctrl_state(&dev->ctrl) != NVME_CTRL_RESETTING) {
3357 		dev_warn(dev->ctrl.device, "ctrl state %d is not RESETTING\n",
3358 			 dev->ctrl.state);
3359 		result = -ENODEV;
3360 		goto out;
3361 	}
3362 
3363 	/*
3364 	 * If we're called to reset a live controller first shut it down before
3365 	 * moving on.
3366 	 */
3367 	if (dev->ctrl.ctrl_config & NVME_CC_ENABLE)
3368 		nvme_dev_disable(dev, false);
3369 	nvme_sync_queues(&dev->ctrl);
3370 
3371 	mutex_lock(&dev->shutdown_lock);
3372 	result = nvme_pci_enable(dev);
3373 	if (result)
3374 		goto out_unlock;
3375 	nvme_unquiesce_admin_queue(&dev->ctrl);
3376 	mutex_unlock(&dev->shutdown_lock);
3377 
3378 	/*
3379 	 * Introduce CONNECTING state from nvme-fc/rdma transports to mark the
3380 	 * initializing procedure here.
3381 	 */
3382 	if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_CONNECTING)) {
3383 		dev_warn(dev->ctrl.device,
3384 			"failed to mark controller CONNECTING\n");
3385 		result = -EBUSY;
3386 		goto out;
3387 	}
3388 
3389 	result = nvme_init_ctrl_finish(&dev->ctrl, was_suspend);
3390 	if (result)
3391 		goto out;
3392 
3393 	if (nvme_ctrl_meta_sgl_supported(&dev->ctrl))
3394 		dev->ctrl.max_integrity_segments = NVME_MAX_META_SEGS;
3395 	else
3396 		dev->ctrl.max_integrity_segments = 1;
3397 
3398 	nvme_dbbuf_dma_alloc(dev);
3399 
3400 	result = nvme_setup_host_mem(dev);
3401 	if (result < 0)
3402 		goto out;
3403 
3404 	nvme_update_attrs(dev);
3405 
3406 	result = nvme_setup_io_queues(dev);
3407 	if (result)
3408 		goto out;
3409 
3410 	/*
3411 	 * Freeze and update the number of I/O queues as those might have
3412 	 * changed.  If there are no I/O queues left after this reset, keep the
3413 	 * controller around but remove all namespaces.
3414 	 */
3415 	if (dev->online_queues > 1) {
3416 		nvme_dbbuf_set(dev);
3417 		nvme_unquiesce_io_queues(&dev->ctrl);
3418 		nvme_wait_freeze(&dev->ctrl);
3419 		if (!nvme_pci_update_nr_queues(dev))
3420 			goto out;
3421 		nvme_unfreeze(&dev->ctrl);
3422 	} else {
3423 		dev_warn(dev->ctrl.device, "IO queues lost\n");
3424 		nvme_mark_namespaces_dead(&dev->ctrl);
3425 		nvme_unquiesce_io_queues(&dev->ctrl);
3426 		nvme_remove_namespaces(&dev->ctrl);
3427 		nvme_free_tagset(dev);
3428 	}
3429 
3430 	/*
3431 	 * If only admin queue live, keep it to do further investigation or
3432 	 * recovery.
3433 	 */
3434 	if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_LIVE)) {
3435 		dev_warn(dev->ctrl.device,
3436 			"failed to mark controller live state\n");
3437 		result = -ENODEV;
3438 		goto out;
3439 	}
3440 
3441 	nvme_start_ctrl(&dev->ctrl);
3442 	return;
3443 
3444  out_unlock:
3445 	mutex_unlock(&dev->shutdown_lock);
3446  out:
3447 	/*
3448 	 * Set state to deleting now to avoid blocking nvme_wait_reset(), which
3449 	 * may be holding this pci_dev's device lock.
3450 	 */
3451 	dev_warn(dev->ctrl.device, "Disabling device after reset failure: %d\n",
3452 		 result);
3453 	nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
3454 	nvme_dev_disable(dev, true);
3455 	nvme_sync_queues(&dev->ctrl);
3456 	nvme_mark_namespaces_dead(&dev->ctrl);
3457 	nvme_unquiesce_io_queues(&dev->ctrl);
3458 	nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DEAD);
3459 }
3460 
3461 static int nvme_pci_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
3462 {
3463 	*val = readl(to_nvme_dev(ctrl)->bar + off);
3464 	return 0;
3465 }
3466 
3467 static int nvme_pci_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
3468 {
3469 	writel(val, to_nvme_dev(ctrl)->bar + off);
3470 	return 0;
3471 }
3472 
3473 static int nvme_pci_reg_read64(struct nvme_ctrl *ctrl, u32 off, u64 *val)
3474 {
3475 	*val = lo_hi_readq(to_nvme_dev(ctrl)->bar + off);
3476 	return 0;
3477 }
3478 
3479 static int nvme_pci_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
3480 {
3481 	struct pci_dev *pdev = to_pci_dev(to_nvme_dev(ctrl)->dev);
3482 
3483 	return snprintf(buf, size, "%s\n", dev_name(&pdev->dev));
3484 }
3485 
3486 static void nvme_pci_print_device_info(struct nvme_ctrl *ctrl)
3487 {
3488 	struct pci_dev *pdev = to_pci_dev(to_nvme_dev(ctrl)->dev);
3489 	struct nvme_subsystem *subsys = ctrl->subsys;
3490 
3491 	dev_err(ctrl->device,
3492 		"VID:DID %04x:%04x model:%.*s firmware:%.*s\n",
3493 		pdev->vendor, pdev->device,
3494 		nvme_strlen(subsys->model, sizeof(subsys->model)),
3495 		subsys->model, nvme_strlen(subsys->firmware_rev,
3496 					   sizeof(subsys->firmware_rev)),
3497 		subsys->firmware_rev);
3498 }
3499 
3500 static bool nvme_pci_supports_pci_p2pdma(struct nvme_ctrl *ctrl)
3501 {
3502 	struct nvme_dev *dev = to_nvme_dev(ctrl);
3503 
3504 	return dma_pci_p2pdma_supported(dev->dev);
3505 }
3506 
3507 static unsigned long nvme_pci_get_virt_boundary(struct nvme_ctrl *ctrl,
3508 						bool is_admin)
3509 {
3510 	if (!nvme_ctrl_sgl_supported(ctrl) || is_admin)
3511 		return NVME_CTRL_PAGE_SIZE - 1;
3512 	return 0;
3513 }
3514 
3515 static const struct nvme_ctrl_ops nvme_pci_ctrl_ops = {
3516 	.name			= "pcie",
3517 	.module			= THIS_MODULE,
3518 	.flags			= NVME_F_METADATA_SUPPORTED,
3519 	.dev_attr_groups	= nvme_pci_dev_attr_groups,
3520 	.reg_read32		= nvme_pci_reg_read32,
3521 	.reg_write32		= nvme_pci_reg_write32,
3522 	.reg_read64		= nvme_pci_reg_read64,
3523 	.free_ctrl		= nvme_pci_free_ctrl,
3524 	.submit_async_event	= nvme_pci_submit_async_event,
3525 	.subsystem_reset	= nvme_pci_subsystem_reset,
3526 	.get_address		= nvme_pci_get_address,
3527 	.print_device_info	= nvme_pci_print_device_info,
3528 	.supports_pci_p2pdma	= nvme_pci_supports_pci_p2pdma,
3529 	.get_virt_boundary	= nvme_pci_get_virt_boundary,
3530 };
3531 
3532 static int nvme_dev_map(struct nvme_dev *dev)
3533 {
3534 	struct pci_dev *pdev = to_pci_dev(dev->dev);
3535 
3536 	if (pci_request_mem_regions(pdev, "nvme"))
3537 		return -ENODEV;
3538 
3539 	if (nvme_remap_bar(dev, NVME_REG_DBS + 4096))
3540 		goto release;
3541 
3542 	return 0;
3543   release:
3544 	pci_release_mem_regions(pdev);
3545 	return -ENODEV;
3546 }
3547 
3548 static unsigned long check_vendor_combination_bug(struct pci_dev *pdev)
3549 {
3550 	if (pdev->vendor == 0x144d && pdev->device == 0xa802) {
3551 		/*
3552 		 * Several Samsung devices seem to drop off the PCIe bus
3553 		 * randomly when APST is on and uses the deepest sleep state.
3554 		 * This has been observed on a Samsung "SM951 NVMe SAMSUNG
3555 		 * 256GB", a "PM951 NVMe SAMSUNG 512GB", and a "Samsung SSD
3556 		 * 950 PRO 256GB", but it seems to be restricted to two Dell
3557 		 * laptops.
3558 		 */
3559 		if (dmi_match(DMI_SYS_VENDOR, "Dell Inc.") &&
3560 		    (dmi_match(DMI_PRODUCT_NAME, "XPS 15 9550") ||
3561 		     dmi_match(DMI_PRODUCT_NAME, "Precision 5510")))
3562 			return NVME_QUIRK_NO_DEEPEST_PS;
3563 	} else if (pdev->vendor == 0x144d && pdev->device == 0xa804) {
3564 		/*
3565 		 * Samsung SSD 960 EVO drops off the PCIe bus after system
3566 		 * suspend on a Ryzen board, ASUS PRIME B350M-A, as well as
3567 		 * within few minutes after bootup on a Coffee Lake board -
3568 		 * ASUS PRIME Z370-A
3569 		 */
3570 		if (dmi_match(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC.") &&
3571 		    (dmi_match(DMI_BOARD_NAME, "PRIME B350M-A") ||
3572 		     dmi_match(DMI_BOARD_NAME, "PRIME Z370-A")))
3573 			return NVME_QUIRK_NO_APST;
3574 	} else if ((pdev->vendor == 0x144d && (pdev->device == 0xa801 ||
3575 		    pdev->device == 0xa808 || pdev->device == 0xa809)) ||
3576 		   (pdev->vendor == 0x1e0f && pdev->device == 0x0001)) {
3577 		/*
3578 		 * Forcing to use host managed nvme power settings for
3579 		 * lowest idle power with quick resume latency on
3580 		 * Samsung and Toshiba SSDs based on suspend behavior
3581 		 * on Coffee Lake board for LENOVO C640
3582 		 */
3583 		if ((dmi_match(DMI_BOARD_VENDOR, "LENOVO")) &&
3584 		     dmi_match(DMI_BOARD_NAME, "LNVNB161216"))
3585 			return NVME_QUIRK_SIMPLE_SUSPEND;
3586 	} else if (pdev->vendor == 0x2646 && (pdev->device == 0x2263 ||
3587 		   pdev->device == 0x500f)) {
3588 		/*
3589 		 * Exclude some Kingston NV1 and A2000 devices from
3590 		 * NVME_QUIRK_SIMPLE_SUSPEND. Do a full suspend to save a
3591 		 * lot of energy with s2idle sleep on some TUXEDO platforms.
3592 		 */
3593 		if (dmi_match(DMI_BOARD_NAME, "NS5X_NS7XAU") ||
3594 		    dmi_match(DMI_BOARD_NAME, "NS5x_7xAU") ||
3595 		    dmi_match(DMI_BOARD_NAME, "NS5x_7xPU") ||
3596 		    dmi_match(DMI_BOARD_NAME, "PH4PRX1_PH6PRX1"))
3597 			return NVME_QUIRK_FORCE_NO_SIMPLE_SUSPEND;
3598 	} else if (pdev->vendor == 0x144d && pdev->device == 0xa80d) {
3599 		/*
3600 		 * Exclude Samsung 990 Evo from NVME_QUIRK_SIMPLE_SUSPEND
3601 		 * because of high power consumption (> 2 Watt) in s2idle
3602 		 * sleep. Only some boards with Intel CPU are affected.
3603 		 * (Note for testing: Samsung 990 Evo Plus has same PCI ID)
3604 		 */
3605 		if (dmi_match(DMI_BOARD_NAME, "DN50Z-140HC-YD") ||
3606 		    dmi_match(DMI_BOARD_NAME, "GMxPXxx") ||
3607 		    dmi_match(DMI_BOARD_NAME, "GXxMRXx") ||
3608 		    dmi_match(DMI_BOARD_NAME, "NS5X_NS7XAU") ||
3609 		    dmi_match(DMI_BOARD_NAME, "PH4PG31") ||
3610 		    dmi_match(DMI_BOARD_NAME, "PH4PRX1_PH6PRX1") ||
3611 		    dmi_match(DMI_BOARD_NAME, "PH6PG01_PH6PG71"))
3612 			return NVME_QUIRK_FORCE_NO_SIMPLE_SUSPEND;
3613 	}
3614 
3615 	/*
3616 	 * NVMe SSD drops off the PCIe bus after system idle
3617 	 * for 10 hours on a Lenovo N60z board.
3618 	 */
3619 	if (dmi_match(DMI_BOARD_NAME, "LXKT-ZXEG-N6"))
3620 		return NVME_QUIRK_NO_APST;
3621 
3622 	return 0;
3623 }
3624 
3625 static struct quirk_entry *detect_dynamic_quirks(struct pci_dev *pdev)
3626 {
3627 	int i;
3628 
3629 	for (i = 0; i < nvme_pci_quirk_count; i++)
3630 		if (pdev->vendor == nvme_pci_quirk_list[i].vendor_id &&
3631 		    pdev->device == nvme_pci_quirk_list[i].dev_id)
3632 			return &nvme_pci_quirk_list[i];
3633 
3634 	return NULL;
3635 }
3636 
3637 static struct nvme_dev *nvme_pci_alloc_dev(struct pci_dev *pdev,
3638 		const struct pci_device_id *id)
3639 {
3640 	unsigned long quirks = id->driver_data;
3641 	int node = dev_to_node(&pdev->dev);
3642 	struct nvme_dev *dev;
3643 	struct quirk_entry *qentry;
3644 	int ret = -ENOMEM;
3645 
3646 	dev = kzalloc_node(struct_size(dev, descriptor_pools, nr_node_ids),
3647 			GFP_KERNEL, node);
3648 	if (!dev)
3649 		return ERR_PTR(-ENOMEM);
3650 	INIT_WORK(&dev->ctrl.reset_work, nvme_reset_work);
3651 	mutex_init(&dev->shutdown_lock);
3652 
3653 	dev->nr_write_queues = write_queues;
3654 	dev->nr_poll_queues = poll_queues;
3655 	dev->nr_allocated_queues = nvme_max_io_queues(dev) + 1;
3656 	dev->queues = kcalloc_node(dev->nr_allocated_queues,
3657 			sizeof(struct nvme_queue), GFP_KERNEL, node);
3658 	if (!dev->queues)
3659 		goto out_free_dev;
3660 
3661 	dev->dev = get_device(&pdev->dev);
3662 
3663 	quirks |= check_vendor_combination_bug(pdev);
3664 	if (!noacpi &&
3665 	    !(quirks & NVME_QUIRK_FORCE_NO_SIMPLE_SUSPEND) &&
3666 	    acpi_storage_d3(&pdev->dev)) {
3667 		/*
3668 		 * Some systems use a bios work around to ask for D3 on
3669 		 * platforms that support kernel managed suspend.
3670 		 */
3671 		dev_info(&pdev->dev,
3672 			 "platform quirk: setting simple suspend\n");
3673 		quirks |= NVME_QUIRK_SIMPLE_SUSPEND;
3674 	}
3675 	qentry = detect_dynamic_quirks(pdev);
3676 	if (qentry) {
3677 		quirks |= qentry->enabled_quirks;
3678 		quirks &= ~qentry->disabled_quirks;
3679 	}
3680 	ret = nvme_init_ctrl(&dev->ctrl, &pdev->dev, &nvme_pci_ctrl_ops,
3681 			     quirks);
3682 	if (ret)
3683 		goto out_put_device;
3684 
3685 	if (dev->ctrl.quirks & NVME_QUIRK_DMA_ADDRESS_BITS_48)
3686 		dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(48));
3687 	else
3688 		dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
3689 	dma_set_min_align_mask(&pdev->dev, NVME_CTRL_PAGE_SIZE - 1);
3690 	dma_set_max_seg_size(&pdev->dev, 0xffffffff);
3691 
3692 	/*
3693 	 * Limit the max command size to prevent iod->sg allocations going
3694 	 * over a single page.
3695 	 */
3696 	dev->ctrl.max_hw_sectors = min_t(u32,
3697 			NVME_MAX_BYTES >> SECTOR_SHIFT,
3698 			dma_opt_mapping_size(&pdev->dev) >> 9);
3699 	dev->ctrl.max_segments = NVME_MAX_SEGS;
3700 	dev->ctrl.max_integrity_segments = 1;
3701 	return dev;
3702 
3703 out_put_device:
3704 	put_device(dev->dev);
3705 	kfree(dev->queues);
3706 out_free_dev:
3707 	kfree(dev);
3708 	return ERR_PTR(ret);
3709 }
3710 
3711 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
3712 {
3713 	struct nvme_dev *dev;
3714 	int result = -ENOMEM;
3715 
3716 	dev = nvme_pci_alloc_dev(pdev, id);
3717 	if (IS_ERR(dev))
3718 		return PTR_ERR(dev);
3719 
3720 	result = nvme_add_ctrl(&dev->ctrl);
3721 	if (result)
3722 		goto out_put_ctrl;
3723 
3724 	result = nvme_dev_map(dev);
3725 	if (result)
3726 		goto out_uninit_ctrl;
3727 
3728 	result = nvme_pci_alloc_iod_mempool(dev);
3729 	if (result)
3730 		goto out_dev_unmap;
3731 
3732 	dev_info(dev->ctrl.device, "pci function %s\n", dev_name(&pdev->dev));
3733 
3734 	result = nvme_pci_enable(dev);
3735 	if (result)
3736 		goto out_release_iod_mempool;
3737 
3738 	result = nvme_alloc_admin_tag_set(&dev->ctrl, &dev->admin_tagset,
3739 				&nvme_mq_admin_ops, sizeof(struct nvme_iod));
3740 	if (result)
3741 		goto out_disable;
3742 
3743 	/*
3744 	 * Mark the controller as connecting before sending admin commands to
3745 	 * allow the timeout handler to do the right thing.
3746 	 */
3747 	if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_CONNECTING)) {
3748 		dev_warn(dev->ctrl.device,
3749 			"failed to mark controller CONNECTING\n");
3750 		result = -EBUSY;
3751 		goto out_disable;
3752 	}
3753 
3754 	result = nvme_init_ctrl_finish(&dev->ctrl, false);
3755 	if (result)
3756 		goto out_disable;
3757 
3758 	if (nvme_ctrl_meta_sgl_supported(&dev->ctrl))
3759 		dev->ctrl.max_integrity_segments = NVME_MAX_META_SEGS;
3760 	else
3761 		dev->ctrl.max_integrity_segments = 1;
3762 
3763 	nvme_dbbuf_dma_alloc(dev);
3764 
3765 	result = nvme_setup_host_mem(dev);
3766 	if (result < 0)
3767 		goto out_disable;
3768 
3769 	nvme_update_attrs(dev);
3770 
3771 	result = nvme_setup_io_queues(dev);
3772 	if (result)
3773 		goto out_disable;
3774 
3775 	if (dev->online_queues > 1) {
3776 		nvme_alloc_io_tag_set(&dev->ctrl, &dev->tagset, &nvme_mq_ops,
3777 				nvme_pci_nr_maps(dev), sizeof(struct nvme_iod));
3778 		nvme_dbbuf_set(dev);
3779 	}
3780 
3781 	if (!dev->ctrl.tagset)
3782 		dev_warn(dev->ctrl.device, "IO queues not created\n");
3783 
3784 	if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_LIVE)) {
3785 		dev_warn(dev->ctrl.device,
3786 			"failed to mark controller live state\n");
3787 		result = -ENODEV;
3788 		goto out_disable;
3789 	}
3790 
3791 	pci_set_drvdata(pdev, dev);
3792 
3793 	nvme_start_ctrl(&dev->ctrl);
3794 	nvme_put_ctrl(&dev->ctrl);
3795 	flush_work(&dev->ctrl.scan_work);
3796 	return 0;
3797 
3798 out_disable:
3799 	nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
3800 	nvme_dev_disable(dev, true);
3801 	nvme_free_host_mem(dev);
3802 	nvme_dev_remove_admin(dev);
3803 	nvme_dbbuf_dma_free(dev);
3804 	nvme_free_queues(dev, 0);
3805 out_release_iod_mempool:
3806 	mempool_destroy(dev->dmavec_mempool);
3807 out_dev_unmap:
3808 	nvme_dev_unmap(dev);
3809 out_uninit_ctrl:
3810 	nvme_uninit_ctrl(&dev->ctrl);
3811 out_put_ctrl:
3812 	nvme_put_ctrl(&dev->ctrl);
3813 	dev_err_probe(&pdev->dev, result, "probe failed\n");
3814 	return result;
3815 }
3816 
3817 static void nvme_reset_prepare(struct pci_dev *pdev)
3818 {
3819 	struct nvme_dev *dev = pci_get_drvdata(pdev);
3820 
3821 	/*
3822 	 * We don't need to check the return value from waiting for the reset
3823 	 * state as pci_dev device lock is held, making it impossible to race
3824 	 * with ->remove().
3825 	 */
3826 	nvme_disable_prepare_reset(dev, false);
3827 	nvme_sync_queues(&dev->ctrl);
3828 }
3829 
3830 static void nvme_reset_done(struct pci_dev *pdev)
3831 {
3832 	struct nvme_dev *dev = pci_get_drvdata(pdev);
3833 
3834 	if (!nvme_try_sched_reset(&dev->ctrl))
3835 		flush_work(&dev->ctrl.reset_work);
3836 }
3837 
3838 static void nvme_shutdown(struct pci_dev *pdev)
3839 {
3840 	struct nvme_dev *dev = pci_get_drvdata(pdev);
3841 
3842 	nvme_disable_prepare_reset(dev, true);
3843 }
3844 
3845 /*
3846  * The driver's remove may be called on a device in a partially initialized
3847  * state. This function must not have any dependencies on the device state in
3848  * order to proceed.
3849  */
3850 static void nvme_remove(struct pci_dev *pdev)
3851 {
3852 	struct nvme_dev *dev = pci_get_drvdata(pdev);
3853 
3854 	nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
3855 	pci_set_drvdata(pdev, NULL);
3856 
3857 	if (!pci_device_is_present(pdev)) {
3858 		nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DEAD);
3859 		nvme_dev_disable(dev, true);
3860 	}
3861 
3862 	flush_work(&dev->ctrl.reset_work);
3863 	nvme_stop_ctrl(&dev->ctrl);
3864 	nvme_remove_namespaces(&dev->ctrl);
3865 	nvme_dev_disable(dev, true);
3866 	nvme_free_host_mem(dev);
3867 	nvme_dev_remove_admin(dev);
3868 	nvme_dbbuf_dma_free(dev);
3869 	nvme_free_queues(dev, 0);
3870 	mempool_destroy(dev->dmavec_mempool);
3871 	nvme_release_descriptor_pools(dev);
3872 	nvme_dev_unmap(dev);
3873 	nvme_uninit_ctrl(&dev->ctrl);
3874 }
3875 
3876 #ifdef CONFIG_PM_SLEEP
3877 static int nvme_get_power_state(struct nvme_ctrl *ctrl, u32 *ps)
3878 {
3879 	return nvme_get_features(ctrl, NVME_FEAT_POWER_MGMT, 0, NULL, 0, ps);
3880 }
3881 
3882 static int nvme_set_power_state(struct nvme_ctrl *ctrl, u32 ps)
3883 {
3884 	return nvme_set_features(ctrl, NVME_FEAT_POWER_MGMT, ps, NULL, 0, NULL);
3885 }
3886 
3887 static int nvme_resume(struct device *dev)
3888 {
3889 	struct nvme_dev *ndev = pci_get_drvdata(to_pci_dev(dev));
3890 	struct nvme_ctrl *ctrl = &ndev->ctrl;
3891 
3892 	if (ndev->last_ps == U32_MAX ||
3893 	    nvme_set_power_state(ctrl, ndev->last_ps) != 0)
3894 		goto reset;
3895 	if (ctrl->hmpre && nvme_setup_host_mem(ndev))
3896 		goto reset;
3897 
3898 	return 0;
3899 reset:
3900 	return nvme_try_sched_reset(ctrl);
3901 }
3902 
3903 static int nvme_suspend(struct device *dev)
3904 {
3905 	struct pci_dev *pdev = to_pci_dev(dev);
3906 	struct nvme_dev *ndev = pci_get_drvdata(pdev);
3907 	struct nvme_ctrl *ctrl = &ndev->ctrl;
3908 	int ret = -EBUSY;
3909 
3910 	ndev->last_ps = U32_MAX;
3911 
3912 	/*
3913 	 * The platform does not remove power for a kernel managed suspend so
3914 	 * use host managed nvme power settings for lowest idle power if
3915 	 * possible. This should have quicker resume latency than a full device
3916 	 * shutdown.  But if the firmware is involved after the suspend or the
3917 	 * device does not support any non-default power states, shut down the
3918 	 * device fully.
3919 	 *
3920 	 * If ASPM is not enabled for the device, shut down the device and allow
3921 	 * the PCI bus layer to put it into D3 in order to take the PCIe link
3922 	 * down, so as to allow the platform to achieve its minimum low-power
3923 	 * state (which may not be possible if the link is up).
3924 	 */
3925 	if (pm_suspend_via_firmware() || !ctrl->npss ||
3926 	    !pcie_aspm_enabled(pdev) ||
3927 	    (ndev->ctrl.quirks & NVME_QUIRK_SIMPLE_SUSPEND))
3928 		return nvme_disable_prepare_reset(ndev, true);
3929 
3930 	nvme_start_freeze(ctrl);
3931 	nvme_wait_freeze(ctrl);
3932 	nvme_sync_queues(ctrl);
3933 
3934 	if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE)
3935 		goto unfreeze;
3936 
3937 	/*
3938 	 * Host memory access may not be successful in a system suspend state,
3939 	 * but the specification allows the controller to access memory in a
3940 	 * non-operational power state.
3941 	 */
3942 	if (ndev->hmb) {
3943 		ret = nvme_set_host_mem(ndev, 0);
3944 		if (ret < 0)
3945 			goto unfreeze;
3946 	}
3947 
3948 	ret = nvme_get_power_state(ctrl, &ndev->last_ps);
3949 	if (ret < 0)
3950 		goto unfreeze;
3951 
3952 	/*
3953 	 * A saved state prevents pci pm from generically controlling the
3954 	 * device's power. If we're using protocol specific settings, we don't
3955 	 * want pci interfering.
3956 	 */
3957 	pci_save_state(pdev);
3958 
3959 	ret = nvme_set_power_state(ctrl, ctrl->npss);
3960 	if (ret < 0)
3961 		goto unfreeze;
3962 
3963 	if (ret) {
3964 		/* discard the saved state */
3965 		pci_load_saved_state(pdev, NULL);
3966 
3967 		/*
3968 		 * Clearing npss forces a controller reset on resume. The
3969 		 * correct value will be rediscovered then.
3970 		 */
3971 		ret = nvme_disable_prepare_reset(ndev, true);
3972 		ctrl->npss = 0;
3973 	}
3974 unfreeze:
3975 	nvme_unfreeze(ctrl);
3976 	return ret;
3977 }
3978 
3979 static int nvme_simple_suspend(struct device *dev)
3980 {
3981 	struct nvme_dev *ndev = pci_get_drvdata(to_pci_dev(dev));
3982 
3983 	return nvme_disable_prepare_reset(ndev, true);
3984 }
3985 
3986 static int nvme_simple_resume(struct device *dev)
3987 {
3988 	struct pci_dev *pdev = to_pci_dev(dev);
3989 	struct nvme_dev *ndev = pci_get_drvdata(pdev);
3990 
3991 	return nvme_try_sched_reset(&ndev->ctrl);
3992 }
3993 
3994 static const struct dev_pm_ops nvme_dev_pm_ops = {
3995 	.suspend	= nvme_suspend,
3996 	.resume		= nvme_resume,
3997 	.freeze		= nvme_simple_suspend,
3998 	.thaw		= nvme_simple_resume,
3999 	.poweroff	= nvme_simple_suspend,
4000 	.restore	= nvme_simple_resume,
4001 };
4002 #endif /* CONFIG_PM_SLEEP */
4003 
4004 static pci_ers_result_t nvme_error_detected(struct pci_dev *pdev,
4005 						pci_channel_state_t state)
4006 {
4007 	struct nvme_dev *dev = pci_get_drvdata(pdev);
4008 
4009 	/*
4010 	 * A frozen channel requires a reset. When detected, this method will
4011 	 * shutdown the controller to quiesce. The controller will be restarted
4012 	 * after the slot reset through driver's slot_reset callback.
4013 	 */
4014 	switch (state) {
4015 	case pci_channel_io_normal:
4016 		return PCI_ERS_RESULT_CAN_RECOVER;
4017 	case pci_channel_io_frozen:
4018 		dev_warn(dev->ctrl.device,
4019 			"frozen state error detected, reset controller\n");
4020 		if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_RESETTING)) {
4021 			nvme_dev_disable(dev, true);
4022 			return PCI_ERS_RESULT_DISCONNECT;
4023 		}
4024 		nvme_dev_disable(dev, false);
4025 		return PCI_ERS_RESULT_NEED_RESET;
4026 	case pci_channel_io_perm_failure:
4027 		dev_warn(dev->ctrl.device,
4028 			"failure state error detected, request disconnect\n");
4029 		return PCI_ERS_RESULT_DISCONNECT;
4030 	}
4031 	return PCI_ERS_RESULT_NEED_RESET;
4032 }
4033 
4034 static pci_ers_result_t nvme_slot_reset(struct pci_dev *pdev)
4035 {
4036 	struct nvme_dev *dev = pci_get_drvdata(pdev);
4037 
4038 	dev_info(dev->ctrl.device, "restart after slot reset\n");
4039 	pci_restore_state(pdev);
4040 	if (nvme_try_sched_reset(&dev->ctrl))
4041 		nvme_unquiesce_io_queues(&dev->ctrl);
4042 	return PCI_ERS_RESULT_RECOVERED;
4043 }
4044 
4045 static void nvme_error_resume(struct pci_dev *pdev)
4046 {
4047 	struct nvme_dev *dev = pci_get_drvdata(pdev);
4048 
4049 	flush_work(&dev->ctrl.reset_work);
4050 }
4051 
4052 static const struct pci_error_handlers nvme_err_handler = {
4053 	.error_detected	= nvme_error_detected,
4054 	.slot_reset	= nvme_slot_reset,
4055 	.resume		= nvme_error_resume,
4056 	.reset_prepare	= nvme_reset_prepare,
4057 	.reset_done	= nvme_reset_done,
4058 };
4059 
4060 static const struct pci_device_id nvme_id_table[] = {
4061 	{ PCI_VDEVICE(INTEL, 0x0953),	/* Intel 750/P3500/P3600/P3700 */
4062 		.driver_data = NVME_QUIRK_STRIPE_SIZE |
4063 				NVME_QUIRK_DEALLOCATE_ZEROES, },
4064 	{ PCI_VDEVICE(INTEL, 0x0a53),	/* Intel P3520 */
4065 		.driver_data = NVME_QUIRK_STRIPE_SIZE |
4066 				NVME_QUIRK_DEALLOCATE_ZEROES, },
4067 	{ PCI_VDEVICE(INTEL, 0x0a54),	/* Intel P4500/P4600 */
4068 		.driver_data = NVME_QUIRK_STRIPE_SIZE |
4069 				NVME_QUIRK_IGNORE_DEV_SUBNQN |
4070 				NVME_QUIRK_BOGUS_NID, },
4071 	{ PCI_VDEVICE(INTEL, 0x0a55),	/* Dell Express Flash P4600 */
4072 		.driver_data = NVME_QUIRK_STRIPE_SIZE, },
4073 	{ PCI_VDEVICE(INTEL, 0xf1a5),	/* Intel 600P/P3100 */
4074 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS |
4075 				NVME_QUIRK_MEDIUM_PRIO_SQ |
4076 				NVME_QUIRK_NO_TEMP_THRESH_CHANGE |
4077 				NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4078 	{ PCI_VDEVICE(INTEL, 0xf1a6),	/* Intel 760p/Pro 7600p */
4079 		.driver_data = NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4080 	{ PCI_VDEVICE(INTEL, 0x5845),	/* Qemu emulated controller */
4081 		.driver_data = NVME_QUIRK_IDENTIFY_CNS |
4082 				NVME_QUIRK_DISABLE_WRITE_ZEROES |
4083 				NVME_QUIRK_BOGUS_NID, },
4084 	{ PCI_VDEVICE(REDHAT, 0x0010),	/* Qemu emulated controller */
4085 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4086 	{ PCI_DEVICE(0x1217, 0x8760), /* O2 Micro 64GB Steam Deck */
4087 		.driver_data = NVME_QUIRK_DMAPOOL_ALIGN_512, },
4088 	{ PCI_DEVICE(0x126f, 0x1001),	/* Silicon Motion generic */
4089 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS |
4090 				NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4091 	{ PCI_DEVICE(0x126f, 0x2262),	/* Silicon Motion generic */
4092 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS |
4093 				NVME_QUIRK_BOGUS_NID, },
4094 	{ PCI_DEVICE(0x126f, 0x2263),	/* Silicon Motion unidentified */
4095 		.driver_data = NVME_QUIRK_NO_NS_DESC_LIST |
4096 				NVME_QUIRK_BOGUS_NID, },
4097 	{ PCI_DEVICE(0x1bb1, 0x0100),   /* Seagate Nytro Flash Storage */
4098 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY |
4099 				NVME_QUIRK_NO_NS_DESC_LIST, },
4100 	{ PCI_DEVICE(0x1c58, 0x0003),	/* HGST adapter */
4101 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
4102 	{ PCI_DEVICE(0x1c58, 0x0023),	/* WDC SN200 adapter */
4103 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
4104 	{ PCI_DEVICE(0x1c5f, 0x0540),	/* Memblaze Pblaze4 adapter */
4105 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
4106 	{ PCI_DEVICE(0x1c5f, 0x0555),	/* Memblaze Pblaze5 adapter */
4107 		.driver_data = NVME_QUIRK_NO_NS_DESC_LIST, },
4108 	{ PCI_DEVICE(0x144d, 0xa808),	/* Samsung PM981/983 */
4109 		.driver_data = NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4110 	{ PCI_DEVICE(0x144d, 0xa821),   /* Samsung PM1725 */
4111 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
4112 	{ PCI_DEVICE(0x144d, 0xa822),   /* Samsung PM1725a */
4113 		.driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY |
4114 				NVME_QUIRK_DISABLE_WRITE_ZEROES|
4115 				NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4116 	{ PCI_DEVICE(0x15b7, 0x5008),   /* Sandisk SN530 */
4117 		.driver_data = NVME_QUIRK_BROKEN_MSI },
4118 	{ PCI_DEVICE(0x15b7, 0x5009),   /* Sandisk SN550 */
4119 		.driver_data = NVME_QUIRK_BROKEN_MSI |
4120 				NVME_QUIRK_NO_DEEPEST_PS },
4121 	{ PCI_DEVICE(0x1987, 0x5012),	/* Phison E12 */
4122 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4123 	{ PCI_DEVICE(0x1987, 0x5016),	/* Phison E16 */
4124 		.driver_data = NVME_QUIRK_IGNORE_DEV_SUBNQN |
4125 				NVME_QUIRK_BOGUS_NID, },
4126 	{ PCI_DEVICE(0x1987, 0x5019),  /* phison E19 */
4127 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4128 	{ PCI_DEVICE(0x1987, 0x5021),   /* Phison E21 */
4129 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4130 	{ PCI_DEVICE(0x1b4b, 0x1092),	/* Lexar 256 GB SSD */
4131 		.driver_data = NVME_QUIRK_NO_NS_DESC_LIST |
4132 				NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4133 	{ PCI_DEVICE(0x1cc1, 0x33f8),   /* ADATA IM2P33F8ABR1 1 TB */
4134 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4135 	{ PCI_DEVICE(0x10ec, 0x5762),   /* ADATA SX6000LNP */
4136 		.driver_data = NVME_QUIRK_IGNORE_DEV_SUBNQN |
4137 				NVME_QUIRK_BOGUS_NID, },
4138 	{ PCI_DEVICE(0x10ec, 0x5763),  /* ADATA SX6000PNP */
4139 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4140 	{ PCI_DEVICE(0x1cc1, 0x8201),   /* ADATA SX8200PNP 512GB */
4141 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS |
4142 				NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4143 	 { PCI_DEVICE(0x1344, 0x5407), /* Micron Technology Inc NVMe SSD */
4144 		.driver_data = NVME_QUIRK_IGNORE_DEV_SUBNQN },
4145 	 { PCI_DEVICE(0x1344, 0x6001),   /* Micron Nitro NVMe */
4146 		 .driver_data = NVME_QUIRK_BOGUS_NID, },
4147 	{ PCI_DEVICE(0x1c5c, 0x1504),   /* SK Hynix PC400 */
4148 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4149 	{ PCI_DEVICE(0x1c5c, 0x174a),   /* SK Hynix P31 SSD */
4150 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4151 	{ PCI_DEVICE(0x1c5c, 0x1D59),   /* SK Hynix BC901 */
4152 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4153 	{ PCI_DEVICE(0x15b7, 0x2001),   /*  Sandisk Skyhawk */
4154 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4155 	{ PCI_DEVICE(0x1d97, 0x2263),   /* SPCC */
4156 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4157 	{ PCI_DEVICE(0x144d, 0xa80b),   /* Samsung PM9B1 256G and 512G */
4158 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES |
4159 				NVME_QUIRK_BOGUS_NID, },
4160 	{ PCI_DEVICE(0x144d, 0xa809),   /* Samsung MZALQ256HBJD 256G */
4161 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4162 	{ PCI_DEVICE(0x144d, 0xa802),   /* Samsung SM953 */
4163 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4164 	{ PCI_DEVICE(0x1cc4, 0x6303),   /* UMIS RPJTJ512MGE1QDY 512G */
4165 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4166 	{ PCI_DEVICE(0x1cc4, 0x6302),   /* UMIS RPJTJ256MGE1QDY 256G */
4167 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4168 	{ PCI_DEVICE(0x2646, 0x2262),   /* KINGSTON SKC2000 NVMe SSD */
4169 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
4170 	{ PCI_DEVICE(0x2646, 0x2263),   /* KINGSTON A2000 NVMe SSD  */
4171 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
4172 	{ PCI_DEVICE(0x2646, 0x5013),   /* Kingston KC3000, Kingston FURY Renegade */
4173 		.driver_data = NVME_QUIRK_NO_SECONDARY_TEMP_THRESH, },
4174 	{ PCI_DEVICE(0x2646, 0x5018),   /* KINGSTON OM8SFP4xxxxP OS21012 NVMe SSD */
4175 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4176 	{ PCI_DEVICE(0x2646, 0x5016),   /* KINGSTON OM3PGP4xxxxP OS21011 NVMe SSD */
4177 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4178 	{ PCI_DEVICE(0x2646, 0x501A),   /* KINGSTON OM8PGP4xxxxP OS21005 NVMe SSD */
4179 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4180 	{ PCI_DEVICE(0x2646, 0x501B),   /* KINGSTON OM8PGP4xxxxQ OS21005 NVMe SSD */
4181 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4182 	{ PCI_DEVICE(0x2646, 0x501E),   /* KINGSTON OM3PGP4xxxxQ OS21011 NVMe SSD */
4183 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4184 	{ PCI_DEVICE(0x2646, 0x502F),   /* KINGSTON OM3SGP4xxxxK NVMe SSD */
4185 		.driver_data = NVME_QUIRK_DISABLE_WRITE_ZEROES, },
4186 	{ PCI_DEVICE(0x1f40, 0x1202),   /* Netac Technologies Co. NV3000 NVMe SSD */
4187 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4188 	{ PCI_DEVICE(0x1f40, 0x5236),   /* Netac Technologies Co. NV7000 NVMe SSD */
4189 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4190 	{ PCI_DEVICE(0x1e4B, 0x1001),   /* MAXIO MAP1001 */
4191 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4192 	{ PCI_DEVICE(0x1e4B, 0x1002),   /* MAXIO MAP1002 */
4193 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4194 	{ PCI_DEVICE(0x1e4B, 0x1202),   /* MAXIO MAP1202 */
4195 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4196 	{ PCI_DEVICE(0x1e4B, 0x1602),   /* MAXIO MAP1602 */
4197 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4198 	{ PCI_DEVICE(0x1cc1, 0x5350),   /* ADATA XPG GAMMIX S50 */
4199 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4200 	{ PCI_DEVICE(0x1dbe, 0x5216),   /* Acer/INNOGRIT FA100/5216 NVMe SSD */
4201 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4202 	{ PCI_DEVICE(0x1dbe, 0x5236),   /* ADATA XPG GAMMIX S70 */
4203 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4204 	{ PCI_DEVICE(0x1e49, 0x0021),   /* ZHITAI TiPro5000 NVMe SSD */
4205 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
4206 	{ PCI_DEVICE(0x1e49, 0x0041),   /* ZHITAI TiPro7000 NVMe SSD */
4207 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
4208 	{ PCI_DEVICE(0x1fa0, 0x2283),   /* Wodposit WPBSNM8-256GTP */
4209 		.driver_data = NVME_QUIRK_NO_SECONDARY_TEMP_THRESH, },
4210 	{ PCI_DEVICE(0x025e, 0xf1ac),   /* SOLIDIGM  P44 pro SSDPFKKW020X7  */
4211 		.driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
4212 	{ PCI_DEVICE(0xc0a9, 0x540a),   /* Crucial P2 */
4213 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4214 	{ PCI_DEVICE(0x1d97, 0x2263), /* Lexar NM610 */
4215 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4216 	{ PCI_DEVICE(0x1d97, 0x1d97), /* Lexar NM620 */
4217 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4218 	{ PCI_DEVICE(0x1d97, 0x2269), /* Lexar NM760 */
4219 		.driver_data = NVME_QUIRK_BOGUS_NID |
4220 				NVME_QUIRK_IGNORE_DEV_SUBNQN, },
4221 	{ PCI_DEVICE(0x10ec, 0x5763), /* TEAMGROUP T-FORCE CARDEA ZERO Z330 SSD */
4222 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4223 	{ PCI_DEVICE(0x1e4b, 0x1602), /* HS-SSD-FUTURE 2048G  */
4224 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4225 	{ PCI_DEVICE(0x10ec, 0x5765), /* TEAMGROUP MP33 2TB SSD */
4226 		.driver_data = NVME_QUIRK_BOGUS_NID, },
4227 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0x0061),
4228 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4229 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0x0065),
4230 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4231 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0x8061),
4232 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4233 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0xcd00),
4234 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4235 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0xcd01),
4236 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4237 	{ PCI_DEVICE(PCI_VENDOR_ID_AMAZON, 0xcd02),
4238 		.driver_data = NVME_QUIRK_DMA_ADDRESS_BITS_48, },
4239 	{ PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2001),
4240 		/*
4241 		 * Fix for the Apple controller found in the MacBook8,1 and
4242 		 * some MacBook7,1 to avoid controller resets and data loss.
4243 		 */
4244 		.driver_data = NVME_QUIRK_SINGLE_VECTOR |
4245 				NVME_QUIRK_QDEPTH_ONE },
4246 	{ PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2003) },
4247 	{ PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2005),
4248 		.driver_data = NVME_QUIRK_SINGLE_VECTOR |
4249 				NVME_QUIRK_128_BYTES_SQES |
4250 				NVME_QUIRK_SHARED_TAGS |
4251 				NVME_QUIRK_SKIP_CID_GEN |
4252 				NVME_QUIRK_IDENTIFY_CNS },
4253 	{ PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
4254 	{ 0, }
4255 };
4256 MODULE_DEVICE_TABLE(pci, nvme_id_table);
4257 
4258 static struct pci_driver nvme_driver = {
4259 	.name		= "nvme",
4260 	.id_table	= nvme_id_table,
4261 	.probe		= nvme_probe,
4262 	.remove		= nvme_remove,
4263 	.shutdown	= nvme_shutdown,
4264 	.driver		= {
4265 		.probe_type	= PROBE_PREFER_ASYNCHRONOUS,
4266 #ifdef CONFIG_PM_SLEEP
4267 		.pm		= &nvme_dev_pm_ops,
4268 #endif
4269 	},
4270 	.sriov_configure = pci_sriov_configure_simple,
4271 	.err_handler	= &nvme_err_handler,
4272 };
4273 
4274 static int __init nvme_init(void)
4275 {
4276 	BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
4277 	BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
4278 	BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
4279 	BUILD_BUG_ON(IRQ_AFFINITY_MAX_SETS < 2);
4280 
4281 	return pci_register_driver(&nvme_driver);
4282 }
4283 
4284 static void __exit nvme_exit(void)
4285 {
4286 	kfree(nvme_pci_quirk_list);
4287 	pci_unregister_driver(&nvme_driver);
4288 	flush_workqueue(nvme_wq);
4289 }
4290 
4291 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
4292 MODULE_LICENSE("GPL");
4293 MODULE_VERSION("1.0");
4294 MODULE_DESCRIPTION("NVMe host PCIe transport driver");
4295 module_init(nvme_init);
4296 module_exit(nvme_exit);
4297