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