GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / nvme / host / pci.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14
15 #include <linux/aer.h>
16 #include <linux/async.h>
17 #include <linux/blkdev.h>
18 #include <linux/blk-mq.h>
19 #include <linux/blk-mq-pci.h>
20 #include <linux/dmi.h>
21 #include <linux/init.h>
22 #include <linux/interrupt.h>
23 #include <linux/io.h>
24 #include <linux/mm.h>
25 #include <linux/module.h>
26 #include <linux/mutex.h>
27 #include <linux/once.h>
28 #include <linux/pci.h>
29 #include <linux/t10-pi.h>
30 #include <linux/types.h>
31 #include <linux/io-64-nonatomic-lo-hi.h>
32 #include <linux/sed-opal.h>
33
34 #include "nvme.h"
35
36 #define SQ_SIZE(depth)          (depth * sizeof(struct nvme_command))
37 #define CQ_SIZE(depth)          (depth * sizeof(struct nvme_completion))
38
39 #define SGES_PER_PAGE   (PAGE_SIZE / sizeof(struct nvme_sgl_desc))
40
41 /*
42  * These can be higher, but we need to ensure that any command doesn't
43  * require an sg allocation that needs more than a page of data.
44  */
45 #define NVME_MAX_KB_SZ  4096
46 #define NVME_MAX_SEGS   127
47
48 static int use_threaded_interrupts;
49 module_param(use_threaded_interrupts, int, 0);
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 static int io_queue_depth_set(const char *val, const struct kernel_param *kp);
67 static const struct kernel_param_ops io_queue_depth_ops = {
68         .set = io_queue_depth_set,
69         .get = param_get_int,
70 };
71
72 static int io_queue_depth = 1024;
73 module_param_cb(io_queue_depth, &io_queue_depth_ops, &io_queue_depth, 0644);
74 MODULE_PARM_DESC(io_queue_depth, "set io queue depth, should >= 2");
75
76 struct nvme_dev;
77 struct nvme_queue;
78
79 static void nvme_dev_disable(struct nvme_dev *dev, bool shutdown);
80
81 /*
82  * Represents an NVM Express device.  Each nvme_dev is a PCI function.
83  */
84 struct nvme_dev {
85         struct nvme_queue *queues;
86         struct blk_mq_tag_set tagset;
87         struct blk_mq_tag_set admin_tagset;
88         u32 __iomem *dbs;
89         struct device *dev;
90         struct dma_pool *prp_page_pool;
91         struct dma_pool *prp_small_pool;
92         unsigned online_queues;
93         unsigned max_qid;
94         unsigned int num_vecs;
95         int q_depth;
96         u32 db_stride;
97         void __iomem *bar;
98         unsigned long bar_mapped_size;
99         struct work_struct remove_work;
100         struct mutex shutdown_lock;
101         bool subsystem;
102         void __iomem *cmb;
103         pci_bus_addr_t cmb_bus_addr;
104         u64 cmb_size;
105         u32 cmbsz;
106         u32 cmbloc;
107         struct nvme_ctrl ctrl;
108         struct completion ioq_wait;
109
110         mempool_t *iod_mempool;
111
112         /* shadow doorbell buffer support: */
113         u32 *dbbuf_dbs;
114         dma_addr_t dbbuf_dbs_dma_addr;
115         u32 *dbbuf_eis;
116         dma_addr_t dbbuf_eis_dma_addr;
117
118         /* host memory buffer support: */
119         u64 host_mem_size;
120         u32 nr_host_mem_descs;
121         dma_addr_t host_mem_descs_dma;
122         struct nvme_host_mem_buf_desc *host_mem_descs;
123         void **host_mem_desc_bufs;
124 };
125
126 static int io_queue_depth_set(const char *val, const struct kernel_param *kp)
127 {
128         int n = 0, ret;
129
130         ret = kstrtoint(val, 10, &n);
131         if (ret != 0 || n < 2)
132                 return -EINVAL;
133
134         return param_set_int(val, kp);
135 }
136
137 static inline unsigned int sq_idx(unsigned int qid, u32 stride)
138 {
139         return qid * 2 * stride;
140 }
141
142 static inline unsigned int cq_idx(unsigned int qid, u32 stride)
143 {
144         return (qid * 2 + 1) * stride;
145 }
146
147 static inline struct nvme_dev *to_nvme_dev(struct nvme_ctrl *ctrl)
148 {
149         return container_of(ctrl, struct nvme_dev, ctrl);
150 }
151
152 /*
153  * An NVM Express queue.  Each device has at least two (one for admin
154  * commands and one for I/O commands).
155  */
156 struct nvme_queue {
157         struct device *q_dmadev;
158         struct nvme_dev *dev;
159         spinlock_t sq_lock;
160         struct nvme_command *sq_cmds;
161         struct nvme_command __iomem *sq_cmds_io;
162         spinlock_t cq_lock ____cacheline_aligned_in_smp;
163         volatile struct nvme_completion *cqes;
164         struct blk_mq_tags **tags;
165         dma_addr_t sq_dma_addr;
166         dma_addr_t cq_dma_addr;
167         u32 __iomem *q_db;
168         u16 q_depth;
169         s16 cq_vector;
170         u16 sq_tail;
171         u16 cq_head;
172         u16 last_cq_head;
173         u16 qid;
174         u8 cq_phase;
175         u32 *dbbuf_sq_db;
176         u32 *dbbuf_cq_db;
177         u32 *dbbuf_sq_ei;
178         u32 *dbbuf_cq_ei;
179 };
180
181 /*
182  * The nvme_iod describes the data in an I/O, including the list of PRP
183  * entries.  You can't see it in this data structure because C doesn't let
184  * me express that.  Use nvme_init_iod to ensure there's enough space
185  * allocated to store the PRP list.
186  */
187 struct nvme_iod {
188         struct nvme_request req;
189         struct nvme_queue *nvmeq;
190         bool use_sgl;
191         int aborted;
192         int npages;             /* In the PRP list. 0 means small pool in use */
193         int nents;              /* Used in scatterlist */
194         int length;             /* Of data, in bytes */
195         dma_addr_t first_dma;
196         struct scatterlist meta_sg; /* metadata requires single contiguous buffer */
197         struct scatterlist *sg;
198         struct scatterlist inline_sg[0];
199 };
200
201 /*
202  * Check we didin't inadvertently grow the command struct
203  */
204 static inline void _nvme_check_size(void)
205 {
206         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
207         BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
208         BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
209         BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
210         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
211         BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
212         BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
213         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
214         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
215         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
216         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
217         BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
218         BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
219 }
220
221 static inline unsigned int nvme_dbbuf_size(u32 stride)
222 {
223         return ((num_possible_cpus() + 1) * 8 * stride);
224 }
225
226 static int nvme_dbbuf_dma_alloc(struct nvme_dev *dev)
227 {
228         unsigned int mem_size = nvme_dbbuf_size(dev->db_stride);
229
230         if (dev->dbbuf_dbs)
231                 return 0;
232
233         dev->dbbuf_dbs = dma_alloc_coherent(dev->dev, mem_size,
234                                             &dev->dbbuf_dbs_dma_addr,
235                                             GFP_KERNEL);
236         if (!dev->dbbuf_dbs)
237                 return -ENOMEM;
238         dev->dbbuf_eis = dma_alloc_coherent(dev->dev, mem_size,
239                                             &dev->dbbuf_eis_dma_addr,
240                                             GFP_KERNEL);
241         if (!dev->dbbuf_eis) {
242                 dma_free_coherent(dev->dev, mem_size,
243                                   dev->dbbuf_dbs, dev->dbbuf_dbs_dma_addr);
244                 dev->dbbuf_dbs = NULL;
245                 return -ENOMEM;
246         }
247
248         return 0;
249 }
250
251 static void nvme_dbbuf_dma_free(struct nvme_dev *dev)
252 {
253         unsigned int mem_size = nvme_dbbuf_size(dev->db_stride);
254
255         if (dev->dbbuf_dbs) {
256                 dma_free_coherent(dev->dev, mem_size,
257                                   dev->dbbuf_dbs, dev->dbbuf_dbs_dma_addr);
258                 dev->dbbuf_dbs = NULL;
259         }
260         if (dev->dbbuf_eis) {
261                 dma_free_coherent(dev->dev, mem_size,
262                                   dev->dbbuf_eis, dev->dbbuf_eis_dma_addr);
263                 dev->dbbuf_eis = NULL;
264         }
265 }
266
267 static void nvme_dbbuf_init(struct nvme_dev *dev,
268                             struct nvme_queue *nvmeq, int qid)
269 {
270         if (!dev->dbbuf_dbs || !qid)
271                 return;
272
273         nvmeq->dbbuf_sq_db = &dev->dbbuf_dbs[sq_idx(qid, dev->db_stride)];
274         nvmeq->dbbuf_cq_db = &dev->dbbuf_dbs[cq_idx(qid, dev->db_stride)];
275         nvmeq->dbbuf_sq_ei = &dev->dbbuf_eis[sq_idx(qid, dev->db_stride)];
276         nvmeq->dbbuf_cq_ei = &dev->dbbuf_eis[cq_idx(qid, dev->db_stride)];
277 }
278
279 static void nvme_dbbuf_free(struct nvme_queue *nvmeq)
280 {
281         if (!nvmeq->qid)
282                 return;
283
284         nvmeq->dbbuf_sq_db = NULL;
285         nvmeq->dbbuf_cq_db = NULL;
286         nvmeq->dbbuf_sq_ei = NULL;
287         nvmeq->dbbuf_cq_ei = NULL;
288 }
289
290 static void nvme_dbbuf_set(struct nvme_dev *dev)
291 {
292         struct nvme_command c;
293         unsigned int i;
294
295         if (!dev->dbbuf_dbs)
296                 return;
297
298         memset(&c, 0, sizeof(c));
299         c.dbbuf.opcode = nvme_admin_dbbuf;
300         c.dbbuf.prp1 = cpu_to_le64(dev->dbbuf_dbs_dma_addr);
301         c.dbbuf.prp2 = cpu_to_le64(dev->dbbuf_eis_dma_addr);
302
303         if (nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0)) {
304                 dev_warn(dev->ctrl.device, "unable to set dbbuf\n");
305                 /* Free memory and continue on */
306                 nvme_dbbuf_dma_free(dev);
307
308                 for (i = 1; i <= dev->online_queues; i++)
309                         nvme_dbbuf_free(&dev->queues[i]);
310         }
311 }
312
313 static inline int nvme_dbbuf_need_event(u16 event_idx, u16 new_idx, u16 old)
314 {
315         return (u16)(new_idx - event_idx - 1) < (u16)(new_idx - old);
316 }
317
318 /* Update dbbuf and return true if an MMIO is required */
319 static bool nvme_dbbuf_update_and_check_event(u16 value, u32 *dbbuf_db,
320                                               volatile u32 *dbbuf_ei)
321 {
322         if (dbbuf_db) {
323                 u16 old_value;
324
325                 /*
326                  * Ensure that the queue is written before updating
327                  * the doorbell in memory
328                  */
329                 wmb();
330
331                 old_value = *dbbuf_db;
332                 *dbbuf_db = value;
333
334                 /*
335                  * Ensure that the doorbell is updated before reading the event
336                  * index from memory.  The controller needs to provide similar
337                  * ordering to ensure the envent index is updated before reading
338                  * the doorbell.
339                  */
340                 mb();
341
342                 if (!nvme_dbbuf_need_event(*dbbuf_ei, value, old_value))
343                         return false;
344         }
345
346         return true;
347 }
348
349 /*
350  * Max size of iod being embedded in the request payload
351  */
352 #define NVME_INT_PAGES          2
353 #define NVME_INT_BYTES(dev)     (NVME_INT_PAGES * (dev)->ctrl.page_size)
354
355 /*
356  * Will slightly overestimate the number of pages needed.  This is OK
357  * as it only leads to a small amount of wasted memory for the lifetime of
358  * the I/O.
359  */
360 static int nvme_npages(unsigned size, struct nvme_dev *dev)
361 {
362         unsigned nprps = DIV_ROUND_UP(size + dev->ctrl.page_size,
363                                       dev->ctrl.page_size);
364         return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
365 }
366
367 /*
368  * Calculates the number of pages needed for the SGL segments. For example a 4k
369  * page can accommodate 256 SGL descriptors.
370  */
371 static int nvme_pci_npages_sgl(unsigned int num_seg)
372 {
373         return DIV_ROUND_UP(num_seg * sizeof(struct nvme_sgl_desc), PAGE_SIZE);
374 }
375
376 static unsigned int nvme_pci_iod_alloc_size(struct nvme_dev *dev,
377                 unsigned int size, unsigned int nseg, bool use_sgl)
378 {
379         size_t alloc_size;
380
381         if (use_sgl)
382                 alloc_size = sizeof(__le64 *) * nvme_pci_npages_sgl(nseg);
383         else
384                 alloc_size = sizeof(__le64 *) * nvme_npages(size, dev);
385
386         return alloc_size + sizeof(struct scatterlist) * nseg;
387 }
388
389 static unsigned int nvme_pci_cmd_size(struct nvme_dev *dev, bool use_sgl)
390 {
391         unsigned int alloc_size = nvme_pci_iod_alloc_size(dev,
392                                     NVME_INT_BYTES(dev), NVME_INT_PAGES,
393                                     use_sgl);
394
395         return sizeof(struct nvme_iod) + alloc_size;
396 }
397
398 static int nvme_admin_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
399                                 unsigned int hctx_idx)
400 {
401         struct nvme_dev *dev = data;
402         struct nvme_queue *nvmeq = &dev->queues[0];
403
404         WARN_ON(hctx_idx != 0);
405         WARN_ON(dev->admin_tagset.tags[0] != hctx->tags);
406         WARN_ON(nvmeq->tags);
407
408         hctx->driver_data = nvmeq;
409         nvmeq->tags = &dev->admin_tagset.tags[0];
410         return 0;
411 }
412
413 static void nvme_admin_exit_hctx(struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
414 {
415         struct nvme_queue *nvmeq = hctx->driver_data;
416
417         nvmeq->tags = NULL;
418 }
419
420 static int nvme_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
421                           unsigned int hctx_idx)
422 {
423         struct nvme_dev *dev = data;
424         struct nvme_queue *nvmeq = &dev->queues[hctx_idx + 1];
425
426         if (!nvmeq->tags)
427                 nvmeq->tags = &dev->tagset.tags[hctx_idx];
428
429         WARN_ON(dev->tagset.tags[hctx_idx] != hctx->tags);
430         hctx->driver_data = nvmeq;
431         return 0;
432 }
433
434 static int nvme_init_request(struct blk_mq_tag_set *set, struct request *req,
435                 unsigned int hctx_idx, unsigned int numa_node)
436 {
437         struct nvme_dev *dev = set->driver_data;
438         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
439         int queue_idx = (set == &dev->tagset) ? hctx_idx + 1 : 0;
440         struct nvme_queue *nvmeq = &dev->queues[queue_idx];
441
442         BUG_ON(!nvmeq);
443         iod->nvmeq = nvmeq;
444
445         nvme_req(req)->ctrl = &dev->ctrl;
446         return 0;
447 }
448
449 static int nvme_pci_map_queues(struct blk_mq_tag_set *set)
450 {
451         struct nvme_dev *dev = set->driver_data;
452
453         return blk_mq_pci_map_queues(set, to_pci_dev(dev->dev),
454                         dev->num_vecs > 1 ? 1 /* admin queue */ : 0);
455 }
456
457 /**
458  * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
459  * @nvmeq: The queue to use
460  * @cmd: The command to send
461  */
462 static void nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
463 {
464         spin_lock(&nvmeq->sq_lock);
465         if (nvmeq->sq_cmds_io)
466                 memcpy_toio(&nvmeq->sq_cmds_io[nvmeq->sq_tail], cmd,
467                                 sizeof(*cmd));
468         else
469                 memcpy(&nvmeq->sq_cmds[nvmeq->sq_tail], cmd, sizeof(*cmd));
470
471         if (++nvmeq->sq_tail == nvmeq->q_depth)
472                 nvmeq->sq_tail = 0;
473         if (nvme_dbbuf_update_and_check_event(nvmeq->sq_tail,
474                         nvmeq->dbbuf_sq_db, nvmeq->dbbuf_sq_ei))
475                 writel(nvmeq->sq_tail, nvmeq->q_db);
476         spin_unlock(&nvmeq->sq_lock);
477 }
478
479 static void **nvme_pci_iod_list(struct request *req)
480 {
481         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
482         return (void **)(iod->sg + blk_rq_nr_phys_segments(req));
483 }
484
485 static inline bool nvme_pci_use_sgls(struct nvme_dev *dev, struct request *req)
486 {
487         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
488         int nseg = blk_rq_nr_phys_segments(req);
489         unsigned int avg_seg_size;
490
491         if (nseg == 0)
492                 return false;
493
494         avg_seg_size = DIV_ROUND_UP(blk_rq_payload_bytes(req), nseg);
495
496         if (!(dev->ctrl.sgls & ((1 << 0) | (1 << 1))))
497                 return false;
498         if (!iod->nvmeq->qid)
499                 return false;
500         if (!sgl_threshold || avg_seg_size < sgl_threshold)
501                 return false;
502         return true;
503 }
504
505 static blk_status_t nvme_init_iod(struct request *rq, struct nvme_dev *dev)
506 {
507         struct nvme_iod *iod = blk_mq_rq_to_pdu(rq);
508         int nseg = blk_rq_nr_phys_segments(rq);
509         unsigned int size = blk_rq_payload_bytes(rq);
510
511         iod->use_sgl = nvme_pci_use_sgls(dev, rq);
512
513         if (nseg > NVME_INT_PAGES || size > NVME_INT_BYTES(dev)) {
514                 iod->sg = mempool_alloc(dev->iod_mempool, GFP_ATOMIC);
515                 if (!iod->sg)
516                         return BLK_STS_RESOURCE;
517         } else {
518                 iod->sg = iod->inline_sg;
519         }
520
521         iod->aborted = 0;
522         iod->npages = -1;
523         iod->nents = 0;
524         iod->length = size;
525
526         return BLK_STS_OK;
527 }
528
529 static void nvme_free_iod(struct nvme_dev *dev, struct request *req)
530 {
531         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
532         const int last_prp = dev->ctrl.page_size / sizeof(__le64) - 1;
533         dma_addr_t dma_addr = iod->first_dma, next_dma_addr;
534
535         int i;
536
537         if (iod->npages == 0)
538                 dma_pool_free(dev->prp_small_pool, nvme_pci_iod_list(req)[0],
539                         dma_addr);
540
541         for (i = 0; i < iod->npages; i++) {
542                 void *addr = nvme_pci_iod_list(req)[i];
543
544                 if (iod->use_sgl) {
545                         struct nvme_sgl_desc *sg_list = addr;
546
547                         next_dma_addr =
548                             le64_to_cpu((sg_list[SGES_PER_PAGE - 1]).addr);
549                 } else {
550                         __le64 *prp_list = addr;
551
552                         next_dma_addr = le64_to_cpu(prp_list[last_prp]);
553                 }
554
555                 dma_pool_free(dev->prp_page_pool, addr, dma_addr);
556                 dma_addr = next_dma_addr;
557         }
558
559         if (iod->sg != iod->inline_sg)
560                 mempool_free(iod->sg, dev->iod_mempool);
561 }
562
563 static void nvme_print_sgl(struct scatterlist *sgl, int nents)
564 {
565         int i;
566         struct scatterlist *sg;
567
568         for_each_sg(sgl, sg, nents, i) {
569                 dma_addr_t phys = sg_phys(sg);
570                 pr_warn("sg[%d] phys_addr:%pad offset:%d length:%d "
571                         "dma_address:%pad dma_length:%d\n",
572                         i, &phys, sg->offset, sg->length, &sg_dma_address(sg),
573                         sg_dma_len(sg));
574         }
575 }
576
577 static blk_status_t nvme_pci_setup_prps(struct nvme_dev *dev,
578                 struct request *req, struct nvme_rw_command *cmnd)
579 {
580         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
581         struct dma_pool *pool;
582         int length = blk_rq_payload_bytes(req);
583         struct scatterlist *sg = iod->sg;
584         int dma_len = sg_dma_len(sg);
585         u64 dma_addr = sg_dma_address(sg);
586         u32 page_size = dev->ctrl.page_size;
587         int offset = dma_addr & (page_size - 1);
588         __le64 *prp_list;
589         void **list = nvme_pci_iod_list(req);
590         dma_addr_t prp_dma;
591         int nprps, i;
592
593         length -= (page_size - offset);
594         if (length <= 0) {
595                 iod->first_dma = 0;
596                 goto done;
597         }
598
599         dma_len -= (page_size - offset);
600         if (dma_len) {
601                 dma_addr += (page_size - offset);
602         } else {
603                 sg = sg_next(sg);
604                 dma_addr = sg_dma_address(sg);
605                 dma_len = sg_dma_len(sg);
606         }
607
608         if (length <= page_size) {
609                 iod->first_dma = dma_addr;
610                 goto done;
611         }
612
613         nprps = DIV_ROUND_UP(length, page_size);
614         if (nprps <= (256 / 8)) {
615                 pool = dev->prp_small_pool;
616                 iod->npages = 0;
617         } else {
618                 pool = dev->prp_page_pool;
619                 iod->npages = 1;
620         }
621
622         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
623         if (!prp_list) {
624                 iod->first_dma = dma_addr;
625                 iod->npages = -1;
626                 return BLK_STS_RESOURCE;
627         }
628         list[0] = prp_list;
629         iod->first_dma = prp_dma;
630         i = 0;
631         for (;;) {
632                 if (i == page_size >> 3) {
633                         __le64 *old_prp_list = prp_list;
634                         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
635                         if (!prp_list)
636                                 return BLK_STS_RESOURCE;
637                         list[iod->npages++] = prp_list;
638                         prp_list[0] = old_prp_list[i - 1];
639                         old_prp_list[i - 1] = cpu_to_le64(prp_dma);
640                         i = 1;
641                 }
642                 prp_list[i++] = cpu_to_le64(dma_addr);
643                 dma_len -= page_size;
644                 dma_addr += page_size;
645                 length -= page_size;
646                 if (length <= 0)
647                         break;
648                 if (dma_len > 0)
649                         continue;
650                 if (unlikely(dma_len < 0))
651                         goto bad_sgl;
652                 sg = sg_next(sg);
653                 dma_addr = sg_dma_address(sg);
654                 dma_len = sg_dma_len(sg);
655         }
656
657 done:
658         cmnd->dptr.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
659         cmnd->dptr.prp2 = cpu_to_le64(iod->first_dma);
660
661         return BLK_STS_OK;
662
663  bad_sgl:
664         WARN(DO_ONCE(nvme_print_sgl, iod->sg, iod->nents),
665                         "Invalid SGL for payload:%d nents:%d\n",
666                         blk_rq_payload_bytes(req), iod->nents);
667         return BLK_STS_IOERR;
668 }
669
670 static void nvme_pci_sgl_set_data(struct nvme_sgl_desc *sge,
671                 struct scatterlist *sg)
672 {
673         sge->addr = cpu_to_le64(sg_dma_address(sg));
674         sge->length = cpu_to_le32(sg_dma_len(sg));
675         sge->type = NVME_SGL_FMT_DATA_DESC << 4;
676 }
677
678 static void nvme_pci_sgl_set_seg(struct nvme_sgl_desc *sge,
679                 dma_addr_t dma_addr, int entries)
680 {
681         sge->addr = cpu_to_le64(dma_addr);
682         if (entries < SGES_PER_PAGE) {
683                 sge->length = cpu_to_le32(entries * sizeof(*sge));
684                 sge->type = NVME_SGL_FMT_LAST_SEG_DESC << 4;
685         } else {
686                 sge->length = cpu_to_le32(PAGE_SIZE);
687                 sge->type = NVME_SGL_FMT_SEG_DESC << 4;
688         }
689 }
690
691 static blk_status_t nvme_pci_setup_sgls(struct nvme_dev *dev,
692                 struct request *req, struct nvme_rw_command *cmd, int entries)
693 {
694         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
695         struct dma_pool *pool;
696         struct nvme_sgl_desc *sg_list;
697         struct scatterlist *sg = iod->sg;
698         dma_addr_t sgl_dma;
699         int i = 0;
700
701         /* setting the transfer type as SGL */
702         cmd->flags = NVME_CMD_SGL_METABUF;
703
704         if (entries == 1) {
705                 nvme_pci_sgl_set_data(&cmd->dptr.sgl, sg);
706                 return BLK_STS_OK;
707         }
708
709         if (entries <= (256 / sizeof(struct nvme_sgl_desc))) {
710                 pool = dev->prp_small_pool;
711                 iod->npages = 0;
712         } else {
713                 pool = dev->prp_page_pool;
714                 iod->npages = 1;
715         }
716
717         sg_list = dma_pool_alloc(pool, GFP_ATOMIC, &sgl_dma);
718         if (!sg_list) {
719                 iod->npages = -1;
720                 return BLK_STS_RESOURCE;
721         }
722
723         nvme_pci_iod_list(req)[0] = sg_list;
724         iod->first_dma = sgl_dma;
725
726         nvme_pci_sgl_set_seg(&cmd->dptr.sgl, sgl_dma, entries);
727
728         do {
729                 if (i == SGES_PER_PAGE) {
730                         struct nvme_sgl_desc *old_sg_desc = sg_list;
731                         struct nvme_sgl_desc *link = &old_sg_desc[i - 1];
732
733                         sg_list = dma_pool_alloc(pool, GFP_ATOMIC, &sgl_dma);
734                         if (!sg_list)
735                                 return BLK_STS_RESOURCE;
736
737                         i = 0;
738                         nvme_pci_iod_list(req)[iod->npages++] = sg_list;
739                         sg_list[i++] = *link;
740                         nvme_pci_sgl_set_seg(link, sgl_dma, entries);
741                 }
742
743                 nvme_pci_sgl_set_data(&sg_list[i++], sg);
744                 sg = sg_next(sg);
745         } while (--entries > 0);
746
747         return BLK_STS_OK;
748 }
749
750 static blk_status_t nvme_map_data(struct nvme_dev *dev, struct request *req,
751                 struct nvme_command *cmnd)
752 {
753         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
754         struct request_queue *q = req->q;
755         enum dma_data_direction dma_dir = rq_data_dir(req) ?
756                         DMA_TO_DEVICE : DMA_FROM_DEVICE;
757         blk_status_t ret = BLK_STS_IOERR;
758         int nr_mapped;
759
760         sg_init_table(iod->sg, blk_rq_nr_phys_segments(req));
761         iod->nents = blk_rq_map_sg(q, req, iod->sg);
762         if (!iod->nents)
763                 goto out;
764
765         ret = BLK_STS_RESOURCE;
766         nr_mapped = dma_map_sg_attrs(dev->dev, iod->sg, iod->nents, dma_dir,
767                         DMA_ATTR_NO_WARN);
768         if (!nr_mapped)
769                 goto out;
770
771         if (iod->use_sgl)
772                 ret = nvme_pci_setup_sgls(dev, req, &cmnd->rw, nr_mapped);
773         else
774                 ret = nvme_pci_setup_prps(dev, req, &cmnd->rw);
775
776         if (ret != BLK_STS_OK)
777                 goto out_unmap;
778
779         ret = BLK_STS_IOERR;
780         if (blk_integrity_rq(req)) {
781                 if (blk_rq_count_integrity_sg(q, req->bio) != 1)
782                         goto out_unmap;
783
784                 sg_init_table(&iod->meta_sg, 1);
785                 if (blk_rq_map_integrity_sg(q, req->bio, &iod->meta_sg) != 1)
786                         goto out_unmap;
787
788                 if (!dma_map_sg(dev->dev, &iod->meta_sg, 1, dma_dir))
789                         goto out_unmap;
790         }
791
792         if (blk_integrity_rq(req))
793                 cmnd->rw.metadata = cpu_to_le64(sg_dma_address(&iod->meta_sg));
794         return BLK_STS_OK;
795
796 out_unmap:
797         dma_unmap_sg(dev->dev, iod->sg, iod->nents, dma_dir);
798 out:
799         return ret;
800 }
801
802 static void nvme_unmap_data(struct nvme_dev *dev, struct request *req)
803 {
804         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
805         enum dma_data_direction dma_dir = rq_data_dir(req) ?
806                         DMA_TO_DEVICE : DMA_FROM_DEVICE;
807
808         if (iod->nents) {
809                 dma_unmap_sg(dev->dev, iod->sg, iod->nents, dma_dir);
810                 if (blk_integrity_rq(req))
811                         dma_unmap_sg(dev->dev, &iod->meta_sg, 1, dma_dir);
812         }
813
814         nvme_cleanup_cmd(req);
815         nvme_free_iod(dev, req);
816 }
817
818 /*
819  * NOTE: ns is NULL when called on the admin queue.
820  */
821 static blk_status_t nvme_queue_rq(struct blk_mq_hw_ctx *hctx,
822                          const struct blk_mq_queue_data *bd)
823 {
824         struct nvme_ns *ns = hctx->queue->queuedata;
825         struct nvme_queue *nvmeq = hctx->driver_data;
826         struct nvme_dev *dev = nvmeq->dev;
827         struct request *req = bd->rq;
828         struct nvme_command cmnd;
829         blk_status_t ret;
830
831         /*
832          * We should not need to do this, but we're still using this to
833          * ensure we can drain requests on a dying queue.
834          */
835         if (unlikely(nvmeq->cq_vector < 0))
836                 return BLK_STS_IOERR;
837
838         ret = nvme_setup_cmd(ns, req, &cmnd);
839         if (ret)
840                 return ret;
841
842         ret = nvme_init_iod(req, dev);
843         if (ret)
844                 goto out_free_cmd;
845
846         if (blk_rq_nr_phys_segments(req)) {
847                 ret = nvme_map_data(dev, req, &cmnd);
848                 if (ret)
849                         goto out_cleanup_iod;
850         }
851
852         blk_mq_start_request(req);
853         nvme_submit_cmd(nvmeq, &cmnd);
854         return BLK_STS_OK;
855 out_cleanup_iod:
856         nvme_free_iod(dev, req);
857 out_free_cmd:
858         nvme_cleanup_cmd(req);
859         return ret;
860 }
861
862 static void nvme_pci_complete_rq(struct request *req)
863 {
864         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
865
866         nvme_unmap_data(iod->nvmeq->dev, req);
867         nvme_complete_rq(req);
868 }
869
870 /* We read the CQE phase first to check if the rest of the entry is valid */
871 static inline bool nvme_cqe_pending(struct nvme_queue *nvmeq)
872 {
873         return (le16_to_cpu(nvmeq->cqes[nvmeq->cq_head].status) & 1) ==
874                         nvmeq->cq_phase;
875 }
876
877 static inline void nvme_ring_cq_doorbell(struct nvme_queue *nvmeq)
878 {
879         u16 head = nvmeq->cq_head;
880
881         if (nvme_dbbuf_update_and_check_event(head, nvmeq->dbbuf_cq_db,
882                                               nvmeq->dbbuf_cq_ei))
883                 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
884 }
885
886 static inline void nvme_handle_cqe(struct nvme_queue *nvmeq, u16 idx)
887 {
888         volatile struct nvme_completion *cqe = &nvmeq->cqes[idx];
889         struct request *req;
890
891         if (unlikely(cqe->command_id >= nvmeq->q_depth)) {
892                 dev_warn(nvmeq->dev->ctrl.device,
893                         "invalid id %d completed on queue %d\n",
894                         cqe->command_id, le16_to_cpu(cqe->sq_id));
895                 return;
896         }
897
898         /*
899          * AEN requests are special as they don't time out and can
900          * survive any kind of queue freeze and often don't respond to
901          * aborts.  We don't even bother to allocate a struct request
902          * for them but rather special case them here.
903          */
904         if (unlikely(nvmeq->qid == 0 &&
905                         cqe->command_id >= NVME_AQ_BLK_MQ_DEPTH)) {
906                 nvme_complete_async_event(&nvmeq->dev->ctrl,
907                                 cqe->status, &cqe->result);
908                 return;
909         }
910
911         req = blk_mq_tag_to_rq(*nvmeq->tags, cqe->command_id);
912         nvme_end_request(req, cqe->status, cqe->result);
913 }
914
915 static void nvme_complete_cqes(struct nvme_queue *nvmeq, u16 start, u16 end)
916 {
917         while (start != end) {
918                 nvme_handle_cqe(nvmeq, start);
919                 if (++start == nvmeq->q_depth)
920                         start = 0;
921         }
922 }
923
924 static inline void nvme_update_cq_head(struct nvme_queue *nvmeq)
925 {
926         if (nvmeq->cq_head == nvmeq->q_depth - 1) {
927                 nvmeq->cq_head = 0;
928                 nvmeq->cq_phase = !nvmeq->cq_phase;
929         } else {
930                 nvmeq->cq_head++;
931         }
932 }
933
934 static inline bool nvme_process_cq(struct nvme_queue *nvmeq, u16 *start,
935                 u16 *end, int tag)
936 {
937         bool found = false;
938
939         *start = nvmeq->cq_head;
940         while (!found && nvme_cqe_pending(nvmeq)) {
941                 if (nvmeq->cqes[nvmeq->cq_head].command_id == tag)
942                         found = true;
943                 nvme_update_cq_head(nvmeq);
944         }
945         *end = nvmeq->cq_head;
946
947         if (*start != *end)
948                 nvme_ring_cq_doorbell(nvmeq);
949         return found;
950 }
951
952 static irqreturn_t nvme_irq(int irq, void *data)
953 {
954         struct nvme_queue *nvmeq = data;
955         irqreturn_t ret = IRQ_NONE;
956         u16 start, end;
957
958         spin_lock(&nvmeq->cq_lock);
959         if (nvmeq->cq_head != nvmeq->last_cq_head)
960                 ret = IRQ_HANDLED;
961         nvme_process_cq(nvmeq, &start, &end, -1);
962         nvmeq->last_cq_head = nvmeq->cq_head;
963         spin_unlock(&nvmeq->cq_lock);
964
965         if (start != end) {
966                 nvme_complete_cqes(nvmeq, start, end);
967                 return IRQ_HANDLED;
968         }
969
970         return ret;
971 }
972
973 static irqreturn_t nvme_irq_check(int irq, void *data)
974 {
975         struct nvme_queue *nvmeq = data;
976         if (nvme_cqe_pending(nvmeq))
977                 return IRQ_WAKE_THREAD;
978         return IRQ_NONE;
979 }
980
981 static int __nvme_poll(struct nvme_queue *nvmeq, unsigned int tag)
982 {
983         u16 start, end;
984         bool found;
985
986         if (!nvme_cqe_pending(nvmeq))
987                 return 0;
988
989         spin_lock_irq(&nvmeq->cq_lock);
990         found = nvme_process_cq(nvmeq, &start, &end, tag);
991         spin_unlock_irq(&nvmeq->cq_lock);
992
993         nvme_complete_cqes(nvmeq, start, end);
994         return found;
995 }
996
997 static int nvme_poll(struct blk_mq_hw_ctx *hctx, unsigned int tag)
998 {
999         struct nvme_queue *nvmeq = hctx->driver_data;
1000
1001         return __nvme_poll(nvmeq, tag);
1002 }
1003
1004 static void nvme_pci_submit_async_event(struct nvme_ctrl *ctrl)
1005 {
1006         struct nvme_dev *dev = to_nvme_dev(ctrl);
1007         struct nvme_queue *nvmeq = &dev->queues[0];
1008         struct nvme_command c;
1009
1010         memset(&c, 0, sizeof(c));
1011         c.common.opcode = nvme_admin_async_event;
1012         c.common.command_id = NVME_AQ_BLK_MQ_DEPTH;
1013         nvme_submit_cmd(nvmeq, &c);
1014 }
1015
1016 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
1017 {
1018         struct nvme_command c;
1019
1020         memset(&c, 0, sizeof(c));
1021         c.delete_queue.opcode = opcode;
1022         c.delete_queue.qid = cpu_to_le16(id);
1023
1024         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1025 }
1026
1027 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
1028                 struct nvme_queue *nvmeq, s16 vector)
1029 {
1030         struct nvme_command c;
1031         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
1032
1033         /*
1034          * Note: we (ab)use the fact that the prp fields survive if no data
1035          * is attached to the request.
1036          */
1037         memset(&c, 0, sizeof(c));
1038         c.create_cq.opcode = nvme_admin_create_cq;
1039         c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1040         c.create_cq.cqid = cpu_to_le16(qid);
1041         c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1042         c.create_cq.cq_flags = cpu_to_le16(flags);
1043         c.create_cq.irq_vector = cpu_to_le16(vector);
1044
1045         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1046 }
1047
1048 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1049                                                 struct nvme_queue *nvmeq)
1050 {
1051         struct nvme_ctrl *ctrl = &dev->ctrl;
1052         struct nvme_command c;
1053         int flags = NVME_QUEUE_PHYS_CONTIG;
1054
1055         /*
1056          * Some drives have a bug that auto-enables WRRU if MEDIUM isn't
1057          * set. Since URGENT priority is zeroes, it makes all queues
1058          * URGENT.
1059          */
1060         if (ctrl->quirks & NVME_QUIRK_MEDIUM_PRIO_SQ)
1061                 flags |= NVME_SQ_PRIO_MEDIUM;
1062
1063         /*
1064          * Note: we (ab)use the fact that the prp fields survive if no data
1065          * is attached to the request.
1066          */
1067         memset(&c, 0, sizeof(c));
1068         c.create_sq.opcode = nvme_admin_create_sq;
1069         c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1070         c.create_sq.sqid = cpu_to_le16(qid);
1071         c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1072         c.create_sq.sq_flags = cpu_to_le16(flags);
1073         c.create_sq.cqid = cpu_to_le16(qid);
1074
1075         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1076 }
1077
1078 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1079 {
1080         return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1081 }
1082
1083 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1084 {
1085         return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1086 }
1087
1088 static void abort_endio(struct request *req, blk_status_t error)
1089 {
1090         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1091         struct nvme_queue *nvmeq = iod->nvmeq;
1092
1093         dev_warn(nvmeq->dev->ctrl.device,
1094                  "Abort status: 0x%x", nvme_req(req)->status);
1095         atomic_inc(&nvmeq->dev->ctrl.abort_limit);
1096         blk_mq_free_request(req);
1097 }
1098
1099 static bool nvme_should_reset(struct nvme_dev *dev, u32 csts)
1100 {
1101
1102         /* If true, indicates loss of adapter communication, possibly by a
1103          * NVMe Subsystem reset.
1104          */
1105         bool nssro = dev->subsystem && (csts & NVME_CSTS_NSSRO);
1106
1107         /* If there is a reset/reinit ongoing, we shouldn't reset again. */
1108         switch (dev->ctrl.state) {
1109         case NVME_CTRL_RESETTING:
1110         case NVME_CTRL_CONNECTING:
1111                 return false;
1112         default:
1113                 break;
1114         }
1115
1116         /* We shouldn't reset unless the controller is on fatal error state
1117          * _or_ if we lost the communication with it.
1118          */
1119         if (!(csts & NVME_CSTS_CFS) && !nssro)
1120                 return false;
1121
1122         return true;
1123 }
1124
1125 static void nvme_warn_reset(struct nvme_dev *dev, u32 csts)
1126 {
1127         /* Read a config register to help see what died. */
1128         u16 pci_status;
1129         int result;
1130
1131         result = pci_read_config_word(to_pci_dev(dev->dev), PCI_STATUS,
1132                                       &pci_status);
1133         if (result == PCIBIOS_SUCCESSFUL)
1134                 dev_warn(dev->ctrl.device,
1135                          "controller is down; will reset: CSTS=0x%x, PCI_STATUS=0x%hx\n",
1136                          csts, pci_status);
1137         else
1138                 dev_warn(dev->ctrl.device,
1139                          "controller is down; will reset: CSTS=0x%x, PCI_STATUS read failed (%d)\n",
1140                          csts, result);
1141 }
1142
1143 static enum blk_eh_timer_return nvme_timeout(struct request *req, bool reserved)
1144 {
1145         struct nvme_iod *iod = blk_mq_rq_to_pdu(req);
1146         struct nvme_queue *nvmeq = iod->nvmeq;
1147         struct nvme_dev *dev = nvmeq->dev;
1148         struct request *abort_req;
1149         struct nvme_command cmd;
1150         bool shutdown = false;
1151         u32 csts = readl(dev->bar + NVME_REG_CSTS);
1152
1153         /* If PCI error recovery process is happening, we cannot reset or
1154          * the recovery mechanism will surely fail.
1155          */
1156         mb();
1157         if (pci_channel_offline(to_pci_dev(dev->dev)))
1158                 return BLK_EH_RESET_TIMER;
1159
1160         /*
1161          * Reset immediately if the controller is failed
1162          */
1163         if (nvme_should_reset(dev, csts)) {
1164                 nvme_warn_reset(dev, csts);
1165                 nvme_dev_disable(dev, false);
1166                 nvme_reset_ctrl(&dev->ctrl);
1167                 return BLK_EH_DONE;
1168         }
1169
1170         /*
1171          * Did we miss an interrupt?
1172          */
1173         if (__nvme_poll(nvmeq, req->tag)) {
1174                 dev_warn(dev->ctrl.device,
1175                          "I/O %d QID %d timeout, completion polled\n",
1176                          req->tag, nvmeq->qid);
1177                 return BLK_EH_DONE;
1178         }
1179
1180         /*
1181          * Shutdown immediately if controller times out while starting. The
1182          * reset work will see the pci device disabled when it gets the forced
1183          * cancellation error. All outstanding requests are completed on
1184          * shutdown, so we return BLK_EH_DONE.
1185          */
1186         switch (dev->ctrl.state) {
1187         case NVME_CTRL_DELETING:
1188                 shutdown = true;
1189         case NVME_CTRL_CONNECTING:
1190         case NVME_CTRL_RESETTING:
1191                 dev_warn_ratelimited(dev->ctrl.device,
1192                          "I/O %d QID %d timeout, disable controller\n",
1193                          req->tag, nvmeq->qid);
1194                 nvme_dev_disable(dev, shutdown);
1195                 nvme_req(req)->flags |= NVME_REQ_CANCELLED;
1196                 return BLK_EH_DONE;
1197         default:
1198                 break;
1199         }
1200
1201         /*
1202          * Shutdown the controller immediately and schedule a reset if the
1203          * command was already aborted once before and still hasn't been
1204          * returned to the driver, or if this is the admin queue.
1205          */
1206         if (!nvmeq->qid || iod->aborted) {
1207                 dev_warn(dev->ctrl.device,
1208                          "I/O %d QID %d timeout, reset controller\n",
1209                          req->tag, nvmeq->qid);
1210                 nvme_dev_disable(dev, false);
1211                 nvme_reset_ctrl(&dev->ctrl);
1212
1213                 nvme_req(req)->flags |= NVME_REQ_CANCELLED;
1214                 return BLK_EH_DONE;
1215         }
1216
1217         if (atomic_dec_return(&dev->ctrl.abort_limit) < 0) {
1218                 atomic_inc(&dev->ctrl.abort_limit);
1219                 return BLK_EH_RESET_TIMER;
1220         }
1221         iod->aborted = 1;
1222
1223         memset(&cmd, 0, sizeof(cmd));
1224         cmd.abort.opcode = nvme_admin_abort_cmd;
1225         cmd.abort.cid = req->tag;
1226         cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1227
1228         dev_warn(nvmeq->dev->ctrl.device,
1229                 "I/O %d QID %d timeout, aborting\n",
1230                  req->tag, nvmeq->qid);
1231
1232         abort_req = nvme_alloc_request(dev->ctrl.admin_q, &cmd,
1233                         BLK_MQ_REQ_NOWAIT, NVME_QID_ANY);
1234         if (IS_ERR(abort_req)) {
1235                 atomic_inc(&dev->ctrl.abort_limit);
1236                 return BLK_EH_RESET_TIMER;
1237         }
1238
1239         abort_req->timeout = ADMIN_TIMEOUT;
1240         abort_req->end_io_data = NULL;
1241         blk_execute_rq_nowait(abort_req->q, NULL, abort_req, 0, abort_endio);
1242
1243         /*
1244          * The aborted req will be completed on receiving the abort req.
1245          * We enable the timer again. If hit twice, it'll cause a device reset,
1246          * as the device then is in a faulty state.
1247          */
1248         return BLK_EH_RESET_TIMER;
1249 }
1250
1251 static void nvme_free_queue(struct nvme_queue *nvmeq)
1252 {
1253         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1254                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1255         if (nvmeq->sq_cmds)
1256                 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1257                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1258 }
1259
1260 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1261 {
1262         int i;
1263
1264         for (i = dev->ctrl.queue_count - 1; i >= lowest; i--) {
1265                 dev->ctrl.queue_count--;
1266                 nvme_free_queue(&dev->queues[i]);
1267         }
1268 }
1269
1270 /**
1271  * nvme_suspend_queue - put queue into suspended state
1272  * @nvmeq - queue to suspend
1273  */
1274 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1275 {
1276         int vector;
1277
1278         spin_lock_irq(&nvmeq->cq_lock);
1279         if (nvmeq->cq_vector == -1) {
1280                 spin_unlock_irq(&nvmeq->cq_lock);
1281                 return 1;
1282         }
1283         vector = nvmeq->cq_vector;
1284         nvmeq->dev->online_queues--;
1285         nvmeq->cq_vector = -1;
1286         spin_unlock_irq(&nvmeq->cq_lock);
1287
1288         /*
1289          * Ensure that nvme_queue_rq() sees it ->cq_vector == -1 without
1290          * having to grab the lock.
1291          */
1292         mb();
1293
1294         if (!nvmeq->qid && nvmeq->dev->ctrl.admin_q)
1295                 blk_mq_quiesce_queue(nvmeq->dev->ctrl.admin_q);
1296
1297         pci_free_irq(to_pci_dev(nvmeq->dev->dev), vector, nvmeq);
1298
1299         return 0;
1300 }
1301
1302 static void nvme_disable_admin_queue(struct nvme_dev *dev, bool shutdown)
1303 {
1304         struct nvme_queue *nvmeq = &dev->queues[0];
1305         u16 start, end;
1306
1307         if (shutdown)
1308                 nvme_shutdown_ctrl(&dev->ctrl);
1309         else
1310                 nvme_disable_ctrl(&dev->ctrl, dev->ctrl.cap);
1311
1312         spin_lock_irq(&nvmeq->cq_lock);
1313         nvme_process_cq(nvmeq, &start, &end, -1);
1314         spin_unlock_irq(&nvmeq->cq_lock);
1315
1316         nvme_complete_cqes(nvmeq, start, end);
1317 }
1318
1319 static int nvme_cmb_qdepth(struct nvme_dev *dev, int nr_io_queues,
1320                                 int entry_size)
1321 {
1322         int q_depth = dev->q_depth;
1323         unsigned q_size_aligned = roundup(q_depth * entry_size,
1324                                           dev->ctrl.page_size);
1325
1326         if (q_size_aligned * nr_io_queues > dev->cmb_size) {
1327                 u64 mem_per_q = div_u64(dev->cmb_size, nr_io_queues);
1328                 mem_per_q = round_down(mem_per_q, dev->ctrl.page_size);
1329                 q_depth = div_u64(mem_per_q, entry_size);
1330
1331                 /*
1332                  * Ensure the reduced q_depth is above some threshold where it
1333                  * would be better to map queues in system memory with the
1334                  * original depth
1335                  */
1336                 if (q_depth < 64)
1337                         return -ENOMEM;
1338         }
1339
1340         return q_depth;
1341 }
1342
1343 static int nvme_alloc_sq_cmds(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1344                                 int qid, int depth)
1345 {
1346         /* CMB SQEs will be mapped before creation */
1347         if (qid && dev->cmb && use_cmb_sqes && (dev->cmbsz & NVME_CMBSZ_SQS))
1348                 return 0;
1349
1350         nvmeq->sq_cmds = dma_alloc_coherent(dev->dev, SQ_SIZE(depth),
1351                                             &nvmeq->sq_dma_addr, GFP_KERNEL);
1352         if (!nvmeq->sq_cmds)
1353                 return -ENOMEM;
1354         return 0;
1355 }
1356
1357 static int nvme_alloc_queue(struct nvme_dev *dev, int qid, int depth)
1358 {
1359         struct nvme_queue *nvmeq = &dev->queues[qid];
1360
1361         if (dev->ctrl.queue_count > qid)
1362                 return 0;
1363
1364         nvmeq->cqes = dma_zalloc_coherent(dev->dev, CQ_SIZE(depth),
1365                                           &nvmeq->cq_dma_addr, GFP_KERNEL);
1366         if (!nvmeq->cqes)
1367                 goto free_nvmeq;
1368
1369         if (nvme_alloc_sq_cmds(dev, nvmeq, qid, depth))
1370                 goto free_cqdma;
1371
1372         nvmeq->q_dmadev = dev->dev;
1373         nvmeq->dev = dev;
1374         spin_lock_init(&nvmeq->sq_lock);
1375         spin_lock_init(&nvmeq->cq_lock);
1376         nvmeq->cq_head = 0;
1377         nvmeq->cq_phase = 1;
1378         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1379         nvmeq->q_depth = depth;
1380         nvmeq->qid = qid;
1381         nvmeq->cq_vector = -1;
1382         dev->ctrl.queue_count++;
1383
1384         return 0;
1385
1386  free_cqdma:
1387         dma_free_coherent(dev->dev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1388                                                         nvmeq->cq_dma_addr);
1389  free_nvmeq:
1390         return -ENOMEM;
1391 }
1392
1393 static int queue_request_irq(struct nvme_queue *nvmeq)
1394 {
1395         struct pci_dev *pdev = to_pci_dev(nvmeq->dev->dev);
1396         int nr = nvmeq->dev->ctrl.instance;
1397
1398         if (use_threaded_interrupts) {
1399                 return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq_check,
1400                                 nvme_irq, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
1401         } else {
1402                 return pci_request_irq(pdev, nvmeq->cq_vector, nvme_irq,
1403                                 NULL, nvmeq, "nvme%dq%d", nr, nvmeq->qid);
1404         }
1405 }
1406
1407 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1408 {
1409         struct nvme_dev *dev = nvmeq->dev;
1410
1411         spin_lock_irq(&nvmeq->cq_lock);
1412         nvmeq->sq_tail = 0;
1413         nvmeq->cq_head = 0;
1414         nvmeq->cq_phase = 1;
1415         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1416         memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1417         nvme_dbbuf_init(dev, nvmeq, qid);
1418         dev->online_queues++;
1419         spin_unlock_irq(&nvmeq->cq_lock);
1420 }
1421
1422 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1423 {
1424         struct nvme_dev *dev = nvmeq->dev;
1425         int result;
1426         s16 vector;
1427
1428         if (dev->cmb && use_cmb_sqes && (dev->cmbsz & NVME_CMBSZ_SQS)) {
1429                 unsigned offset = (qid - 1) * roundup(SQ_SIZE(nvmeq->q_depth),
1430                                                       dev->ctrl.page_size);
1431                 nvmeq->sq_dma_addr = dev->cmb_bus_addr + offset;
1432                 nvmeq->sq_cmds_io = dev->cmb + offset;
1433         }
1434
1435         /*
1436          * A queue's vector matches the queue identifier unless the controller
1437          * has only one vector available.
1438          */
1439         vector = dev->num_vecs == 1 ? 0 : qid;
1440         result = adapter_alloc_cq(dev, qid, nvmeq, vector);
1441         if (result)
1442                 return result;
1443
1444         result = adapter_alloc_sq(dev, qid, nvmeq);
1445         if (result < 0)
1446                 return result;
1447         else if (result)
1448                 goto release_cq;
1449
1450         /*
1451          * Set cq_vector after alloc cq/sq, otherwise nvme_suspend_queue will
1452          * invoke free_irq for it and cause a 'Trying to free already-free IRQ
1453          * xxx' warning if the create CQ/SQ command times out.
1454          */
1455         nvmeq->cq_vector = vector;
1456         nvme_init_queue(nvmeq, qid);
1457         result = queue_request_irq(nvmeq);
1458         if (result < 0)
1459                 goto release_sq;
1460
1461         return result;
1462
1463 release_sq:
1464         nvmeq->cq_vector = -1;
1465         dev->online_queues--;
1466         adapter_delete_sq(dev, qid);
1467 release_cq:
1468         adapter_delete_cq(dev, qid);
1469         return result;
1470 }
1471
1472 static const struct blk_mq_ops nvme_mq_admin_ops = {
1473         .queue_rq       = nvme_queue_rq,
1474         .complete       = nvme_pci_complete_rq,
1475         .init_hctx      = nvme_admin_init_hctx,
1476         .exit_hctx      = nvme_admin_exit_hctx,
1477         .init_request   = nvme_init_request,
1478         .timeout        = nvme_timeout,
1479 };
1480
1481 static const struct blk_mq_ops nvme_mq_ops = {
1482         .queue_rq       = nvme_queue_rq,
1483         .complete       = nvme_pci_complete_rq,
1484         .init_hctx      = nvme_init_hctx,
1485         .init_request   = nvme_init_request,
1486         .map_queues     = nvme_pci_map_queues,
1487         .timeout        = nvme_timeout,
1488         .poll           = nvme_poll,
1489 };
1490
1491 static void nvme_dev_remove_admin(struct nvme_dev *dev)
1492 {
1493         if (dev->ctrl.admin_q && !blk_queue_dying(dev->ctrl.admin_q)) {
1494                 /*
1495                  * If the controller was reset during removal, it's possible
1496                  * user requests may be waiting on a stopped queue. Start the
1497                  * queue to flush these to completion.
1498                  */
1499                 blk_mq_unquiesce_queue(dev->ctrl.admin_q);
1500                 blk_cleanup_queue(dev->ctrl.admin_q);
1501                 blk_mq_free_tag_set(&dev->admin_tagset);
1502         }
1503 }
1504
1505 static int nvme_alloc_admin_tags(struct nvme_dev *dev)
1506 {
1507         if (!dev->ctrl.admin_q) {
1508                 dev->admin_tagset.ops = &nvme_mq_admin_ops;
1509                 dev->admin_tagset.nr_hw_queues = 1;
1510
1511                 dev->admin_tagset.queue_depth = NVME_AQ_MQ_TAG_DEPTH;
1512                 dev->admin_tagset.timeout = ADMIN_TIMEOUT;
1513                 dev->admin_tagset.numa_node = dev_to_node(dev->dev);
1514                 dev->admin_tagset.cmd_size = nvme_pci_cmd_size(dev, false);
1515                 dev->admin_tagset.flags = BLK_MQ_F_NO_SCHED;
1516                 dev->admin_tagset.driver_data = dev;
1517
1518                 if (blk_mq_alloc_tag_set(&dev->admin_tagset))
1519                         return -ENOMEM;
1520                 dev->ctrl.admin_tagset = &dev->admin_tagset;
1521
1522                 dev->ctrl.admin_q = blk_mq_init_queue(&dev->admin_tagset);
1523                 if (IS_ERR(dev->ctrl.admin_q)) {
1524                         blk_mq_free_tag_set(&dev->admin_tagset);
1525                         dev->ctrl.admin_q = NULL;
1526                         return -ENOMEM;
1527                 }
1528                 if (!blk_get_queue(dev->ctrl.admin_q)) {
1529                         nvme_dev_remove_admin(dev);
1530                         dev->ctrl.admin_q = NULL;
1531                         return -ENODEV;
1532                 }
1533         } else
1534                 blk_mq_unquiesce_queue(dev->ctrl.admin_q);
1535
1536         return 0;
1537 }
1538
1539 static unsigned long db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
1540 {
1541         return NVME_REG_DBS + ((nr_io_queues + 1) * 8 * dev->db_stride);
1542 }
1543
1544 static int nvme_remap_bar(struct nvme_dev *dev, unsigned long size)
1545 {
1546         struct pci_dev *pdev = to_pci_dev(dev->dev);
1547
1548         if (size <= dev->bar_mapped_size)
1549                 return 0;
1550         if (size > pci_resource_len(pdev, 0))
1551                 return -ENOMEM;
1552         if (dev->bar)
1553                 iounmap(dev->bar);
1554         dev->bar = ioremap(pci_resource_start(pdev, 0), size);
1555         if (!dev->bar) {
1556                 dev->bar_mapped_size = 0;
1557                 return -ENOMEM;
1558         }
1559         dev->bar_mapped_size = size;
1560         dev->dbs = dev->bar + NVME_REG_DBS;
1561
1562         return 0;
1563 }
1564
1565 static int nvme_pci_configure_admin_queue(struct nvme_dev *dev)
1566 {
1567         int result;
1568         u32 aqa;
1569         struct nvme_queue *nvmeq;
1570
1571         result = nvme_remap_bar(dev, db_bar_size(dev, 0));
1572         if (result < 0)
1573                 return result;
1574
1575         dev->subsystem = readl(dev->bar + NVME_REG_VS) >= NVME_VS(1, 1, 0) ?
1576                                 NVME_CAP_NSSRC(dev->ctrl.cap) : 0;
1577
1578         if (dev->subsystem &&
1579             (readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_NSSRO))
1580                 writel(NVME_CSTS_NSSRO, dev->bar + NVME_REG_CSTS);
1581
1582         result = nvme_disable_ctrl(&dev->ctrl, dev->ctrl.cap);
1583         if (result < 0)
1584                 return result;
1585
1586         result = nvme_alloc_queue(dev, 0, NVME_AQ_DEPTH);
1587         if (result)
1588                 return result;
1589
1590         nvmeq = &dev->queues[0];
1591         aqa = nvmeq->q_depth - 1;
1592         aqa |= aqa << 16;
1593
1594         writel(aqa, dev->bar + NVME_REG_AQA);
1595         lo_hi_writeq(nvmeq->sq_dma_addr, dev->bar + NVME_REG_ASQ);
1596         lo_hi_writeq(nvmeq->cq_dma_addr, dev->bar + NVME_REG_ACQ);
1597
1598         result = nvme_enable_ctrl(&dev->ctrl, dev->ctrl.cap);
1599         if (result)
1600                 return result;
1601
1602         nvmeq->cq_vector = 0;
1603         nvme_init_queue(nvmeq, 0);
1604         result = queue_request_irq(nvmeq);
1605         if (result) {
1606                 nvmeq->cq_vector = -1;
1607                 return result;
1608         }
1609
1610         return result;
1611 }
1612
1613 static int nvme_create_io_queues(struct nvme_dev *dev)
1614 {
1615         unsigned i, max;
1616         int ret = 0;
1617
1618         for (i = dev->ctrl.queue_count; i <= dev->max_qid; i++) {
1619                 if (nvme_alloc_queue(dev, i, dev->q_depth)) {
1620                         ret = -ENOMEM;
1621                         break;
1622                 }
1623         }
1624
1625         max = min(dev->max_qid, dev->ctrl.queue_count - 1);
1626         for (i = dev->online_queues; i <= max; i++) {
1627                 ret = nvme_create_queue(&dev->queues[i], i);
1628                 if (ret)
1629                         break;
1630         }
1631
1632         /*
1633          * Ignore failing Create SQ/CQ commands, we can continue with less
1634          * than the desired amount of queues, and even a controller without
1635          * I/O queues can still be used to issue admin commands.  This might
1636          * be useful to upgrade a buggy firmware for example.
1637          */
1638         return ret >= 0 ? 0 : ret;
1639 }
1640
1641 static ssize_t nvme_cmb_show(struct device *dev,
1642                              struct device_attribute *attr,
1643                              char *buf)
1644 {
1645         struct nvme_dev *ndev = to_nvme_dev(dev_get_drvdata(dev));
1646
1647         return scnprintf(buf, PAGE_SIZE, "cmbloc : x%08x\ncmbsz  : x%08x\n",
1648                        ndev->cmbloc, ndev->cmbsz);
1649 }
1650 static DEVICE_ATTR(cmb, S_IRUGO, nvme_cmb_show, NULL);
1651
1652 static u64 nvme_cmb_size_unit(struct nvme_dev *dev)
1653 {
1654         u8 szu = (dev->cmbsz >> NVME_CMBSZ_SZU_SHIFT) & NVME_CMBSZ_SZU_MASK;
1655
1656         return 1ULL << (12 + 4 * szu);
1657 }
1658
1659 static u32 nvme_cmb_size(struct nvme_dev *dev)
1660 {
1661         return (dev->cmbsz >> NVME_CMBSZ_SZ_SHIFT) & NVME_CMBSZ_SZ_MASK;
1662 }
1663
1664 static void nvme_map_cmb(struct nvme_dev *dev)
1665 {
1666         u64 size, offset;
1667         resource_size_t bar_size;
1668         struct pci_dev *pdev = to_pci_dev(dev->dev);
1669         int bar;
1670
1671         if (dev->cmb_size)
1672                 return;
1673
1674         dev->cmbsz = readl(dev->bar + NVME_REG_CMBSZ);
1675         if (!dev->cmbsz)
1676                 return;
1677         dev->cmbloc = readl(dev->bar + NVME_REG_CMBLOC);
1678
1679         if (!use_cmb_sqes)
1680                 return;
1681
1682         size = nvme_cmb_size_unit(dev) * nvme_cmb_size(dev);
1683         offset = nvme_cmb_size_unit(dev) * NVME_CMB_OFST(dev->cmbloc);
1684         bar = NVME_CMB_BIR(dev->cmbloc);
1685         bar_size = pci_resource_len(pdev, bar);
1686
1687         if (offset > bar_size)
1688                 return;
1689
1690         /*
1691          * Controllers may support a CMB size larger than their BAR,
1692          * for example, due to being behind a bridge. Reduce the CMB to
1693          * the reported size of the BAR
1694          */
1695         if (size > bar_size - offset)
1696                 size = bar_size - offset;
1697
1698         dev->cmb = ioremap_wc(pci_resource_start(pdev, bar) + offset, size);
1699         if (!dev->cmb)
1700                 return;
1701         dev->cmb_bus_addr = pci_bus_address(pdev, bar) + offset;
1702         dev->cmb_size = size;
1703
1704         if (sysfs_add_file_to_group(&dev->ctrl.device->kobj,
1705                                     &dev_attr_cmb.attr, NULL))
1706                 dev_warn(dev->ctrl.device,
1707                          "failed to add sysfs attribute for CMB\n");
1708 }
1709
1710 static inline void nvme_release_cmb(struct nvme_dev *dev)
1711 {
1712         if (dev->cmb) {
1713                 iounmap(dev->cmb);
1714                 dev->cmb = NULL;
1715                 sysfs_remove_file_from_group(&dev->ctrl.device->kobj,
1716                                              &dev_attr_cmb.attr, NULL);
1717                 dev->cmbsz = 0;
1718         }
1719 }
1720
1721 static int nvme_set_host_mem(struct nvme_dev *dev, u32 bits)
1722 {
1723         u64 dma_addr = dev->host_mem_descs_dma;
1724         struct nvme_command c;
1725         int ret;
1726
1727         memset(&c, 0, sizeof(c));
1728         c.features.opcode       = nvme_admin_set_features;
1729         c.features.fid          = cpu_to_le32(NVME_FEAT_HOST_MEM_BUF);
1730         c.features.dword11      = cpu_to_le32(bits);
1731         c.features.dword12      = cpu_to_le32(dev->host_mem_size >>
1732                                               ilog2(dev->ctrl.page_size));
1733         c.features.dword13      = cpu_to_le32(lower_32_bits(dma_addr));
1734         c.features.dword14      = cpu_to_le32(upper_32_bits(dma_addr));
1735         c.features.dword15      = cpu_to_le32(dev->nr_host_mem_descs);
1736
1737         ret = nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1738         if (ret) {
1739                 dev_warn(dev->ctrl.device,
1740                          "failed to set host mem (err %d, flags %#x).\n",
1741                          ret, bits);
1742         }
1743         return ret;
1744 }
1745
1746 static void nvme_free_host_mem(struct nvme_dev *dev)
1747 {
1748         int i;
1749
1750         for (i = 0; i < dev->nr_host_mem_descs; i++) {
1751                 struct nvme_host_mem_buf_desc *desc = &dev->host_mem_descs[i];
1752                 size_t size = le32_to_cpu(desc->size) * dev->ctrl.page_size;
1753
1754                 dma_free_attrs(dev->dev, size, dev->host_mem_desc_bufs[i],
1755                                le64_to_cpu(desc->addr),
1756                                DMA_ATTR_NO_KERNEL_MAPPING | DMA_ATTR_NO_WARN);
1757         }
1758
1759         kfree(dev->host_mem_desc_bufs);
1760         dev->host_mem_desc_bufs = NULL;
1761         dma_free_coherent(dev->dev,
1762                         dev->nr_host_mem_descs * sizeof(*dev->host_mem_descs),
1763                         dev->host_mem_descs, dev->host_mem_descs_dma);
1764         dev->host_mem_descs = NULL;
1765         dev->nr_host_mem_descs = 0;
1766 }
1767
1768 static int __nvme_alloc_host_mem(struct nvme_dev *dev, u64 preferred,
1769                 u32 chunk_size)
1770 {
1771         struct nvme_host_mem_buf_desc *descs;
1772         u32 max_entries, len;
1773         dma_addr_t descs_dma;
1774         int i = 0;
1775         void **bufs;
1776         u64 size, tmp;
1777
1778         tmp = (preferred + chunk_size - 1);
1779         do_div(tmp, chunk_size);
1780         max_entries = tmp;
1781
1782         if (dev->ctrl.hmmaxd && dev->ctrl.hmmaxd < max_entries)
1783                 max_entries = dev->ctrl.hmmaxd;
1784
1785         descs = dma_zalloc_coherent(dev->dev, max_entries * sizeof(*descs),
1786                         &descs_dma, GFP_KERNEL);
1787         if (!descs)
1788                 goto out;
1789
1790         bufs = kcalloc(max_entries, sizeof(*bufs), GFP_KERNEL);
1791         if (!bufs)
1792                 goto out_free_descs;
1793
1794         for (size = 0; size < preferred && i < max_entries; size += len) {
1795                 dma_addr_t dma_addr;
1796
1797                 len = min_t(u64, chunk_size, preferred - size);
1798                 bufs[i] = dma_alloc_attrs(dev->dev, len, &dma_addr, GFP_KERNEL,
1799                                 DMA_ATTR_NO_KERNEL_MAPPING | DMA_ATTR_NO_WARN);
1800                 if (!bufs[i])
1801                         break;
1802
1803                 descs[i].addr = cpu_to_le64(dma_addr);
1804                 descs[i].size = cpu_to_le32(len / dev->ctrl.page_size);
1805                 i++;
1806         }
1807
1808         if (!size)
1809                 goto out_free_bufs;
1810
1811         dev->nr_host_mem_descs = i;
1812         dev->host_mem_size = size;
1813         dev->host_mem_descs = descs;
1814         dev->host_mem_descs_dma = descs_dma;
1815         dev->host_mem_desc_bufs = bufs;
1816         return 0;
1817
1818 out_free_bufs:
1819         while (--i >= 0) {
1820                 size_t size = le32_to_cpu(descs[i].size) * dev->ctrl.page_size;
1821
1822                 dma_free_attrs(dev->dev, size, bufs[i],
1823                                le64_to_cpu(descs[i].addr),
1824                                DMA_ATTR_NO_KERNEL_MAPPING | DMA_ATTR_NO_WARN);
1825         }
1826
1827         kfree(bufs);
1828 out_free_descs:
1829         dma_free_coherent(dev->dev, max_entries * sizeof(*descs), descs,
1830                         descs_dma);
1831 out:
1832         dev->host_mem_descs = NULL;
1833         return -ENOMEM;
1834 }
1835
1836 static int nvme_alloc_host_mem(struct nvme_dev *dev, u64 min, u64 preferred)
1837 {
1838         u32 chunk_size;
1839
1840         /* start big and work our way down */
1841         for (chunk_size = min_t(u64, preferred, PAGE_SIZE * MAX_ORDER_NR_PAGES);
1842              chunk_size >= max_t(u32, dev->ctrl.hmminds * 4096, PAGE_SIZE * 2);
1843              chunk_size /= 2) {
1844                 if (!__nvme_alloc_host_mem(dev, preferred, chunk_size)) {
1845                         if (!min || dev->host_mem_size >= min)
1846                                 return 0;
1847                         nvme_free_host_mem(dev);
1848                 }
1849         }
1850
1851         return -ENOMEM;
1852 }
1853
1854 static int nvme_setup_host_mem(struct nvme_dev *dev)
1855 {
1856         u64 max = (u64)max_host_mem_size_mb * SZ_1M;
1857         u64 preferred = (u64)dev->ctrl.hmpre * 4096;
1858         u64 min = (u64)dev->ctrl.hmmin * 4096;
1859         u32 enable_bits = NVME_HOST_MEM_ENABLE;
1860         int ret;
1861
1862         preferred = min(preferred, max);
1863         if (min > max) {
1864                 dev_warn(dev->ctrl.device,
1865                         "min host memory (%lld MiB) above limit (%d MiB).\n",
1866                         min >> ilog2(SZ_1M), max_host_mem_size_mb);
1867                 nvme_free_host_mem(dev);
1868                 return 0;
1869         }
1870
1871         /*
1872          * If we already have a buffer allocated check if we can reuse it.
1873          */
1874         if (dev->host_mem_descs) {
1875                 if (dev->host_mem_size >= min)
1876                         enable_bits |= NVME_HOST_MEM_RETURN;
1877                 else
1878                         nvme_free_host_mem(dev);
1879         }
1880
1881         if (!dev->host_mem_descs) {
1882                 if (nvme_alloc_host_mem(dev, min, preferred)) {
1883                         dev_warn(dev->ctrl.device,
1884                                 "failed to allocate host memory buffer.\n");
1885                         return 0; /* controller must work without HMB */
1886                 }
1887
1888                 dev_info(dev->ctrl.device,
1889                         "allocated %lld MiB host memory buffer.\n",
1890                         dev->host_mem_size >> ilog2(SZ_1M));
1891         }
1892
1893         ret = nvme_set_host_mem(dev, enable_bits);
1894         if (ret)
1895                 nvme_free_host_mem(dev);
1896         return ret;
1897 }
1898
1899 static int nvme_setup_io_queues(struct nvme_dev *dev)
1900 {
1901         struct nvme_queue *adminq = &dev->queues[0];
1902         struct pci_dev *pdev = to_pci_dev(dev->dev);
1903         int result, nr_io_queues;
1904         unsigned long size;
1905
1906         struct irq_affinity affd = {
1907                 .pre_vectors = 1
1908         };
1909
1910         nr_io_queues = num_possible_cpus();
1911         result = nvme_set_queue_count(&dev->ctrl, &nr_io_queues);
1912         if (result < 0)
1913                 return result;
1914
1915         if (nr_io_queues == 0)
1916                 return 0;
1917
1918         if (dev->cmb && (dev->cmbsz & NVME_CMBSZ_SQS)) {
1919                 result = nvme_cmb_qdepth(dev, nr_io_queues,
1920                                 sizeof(struct nvme_command));
1921                 if (result > 0)
1922                         dev->q_depth = result;
1923                 else
1924                         nvme_release_cmb(dev);
1925         }
1926
1927         do {
1928                 size = db_bar_size(dev, nr_io_queues);
1929                 result = nvme_remap_bar(dev, size);
1930                 if (!result)
1931                         break;
1932                 if (!--nr_io_queues)
1933                         return -ENOMEM;
1934         } while (1);
1935         adminq->q_db = dev->dbs;
1936
1937         /* Deregister the admin queue's interrupt */
1938         pci_free_irq(pdev, 0, adminq);
1939
1940         /*
1941          * If we enable msix early due to not intx, disable it again before
1942          * setting up the full range we need.
1943          */
1944         pci_free_irq_vectors(pdev);
1945         result = pci_alloc_irq_vectors_affinity(pdev, 1, nr_io_queues + 1,
1946                         PCI_IRQ_ALL_TYPES | PCI_IRQ_AFFINITY, &affd);
1947         if (result <= 0)
1948                 return -EIO;
1949         dev->num_vecs = result;
1950         dev->max_qid = max(result - 1, 1);
1951
1952         /*
1953          * Should investigate if there's a performance win from allocating
1954          * more queues than interrupt vectors; it might allow the submission
1955          * path to scale better, even if the receive path is limited by the
1956          * number of interrupts.
1957          */
1958
1959         result = queue_request_irq(adminq);
1960         if (result) {
1961                 adminq->cq_vector = -1;
1962                 return result;
1963         }
1964         return nvme_create_io_queues(dev);
1965 }
1966
1967 static void nvme_del_queue_end(struct request *req, blk_status_t error)
1968 {
1969         struct nvme_queue *nvmeq = req->end_io_data;
1970
1971         blk_mq_free_request(req);
1972         complete(&nvmeq->dev->ioq_wait);
1973 }
1974
1975 static void nvme_del_cq_end(struct request *req, blk_status_t error)
1976 {
1977         struct nvme_queue *nvmeq = req->end_io_data;
1978         u16 start, end;
1979
1980         if (!error) {
1981                 unsigned long flags;
1982
1983                 spin_lock_irqsave(&nvmeq->cq_lock, flags);
1984                 nvme_process_cq(nvmeq, &start, &end, -1);
1985                 spin_unlock_irqrestore(&nvmeq->cq_lock, flags);
1986
1987                 nvme_complete_cqes(nvmeq, start, end);
1988         }
1989
1990         nvme_del_queue_end(req, error);
1991 }
1992
1993 static int nvme_delete_queue(struct nvme_queue *nvmeq, u8 opcode)
1994 {
1995         struct request_queue *q = nvmeq->dev->ctrl.admin_q;
1996         struct request *req;
1997         struct nvme_command cmd;
1998
1999         memset(&cmd, 0, sizeof(cmd));
2000         cmd.delete_queue.opcode = opcode;
2001         cmd.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2002
2003         req = nvme_alloc_request(q, &cmd, BLK_MQ_REQ_NOWAIT, NVME_QID_ANY);
2004         if (IS_ERR(req))
2005                 return PTR_ERR(req);
2006
2007         req->timeout = ADMIN_TIMEOUT;
2008         req->end_io_data = nvmeq;
2009
2010         blk_execute_rq_nowait(q, NULL, req, false,
2011                         opcode == nvme_admin_delete_cq ?
2012                                 nvme_del_cq_end : nvme_del_queue_end);
2013         return 0;
2014 }
2015
2016 static void nvme_disable_io_queues(struct nvme_dev *dev)
2017 {
2018         int pass, queues = dev->online_queues - 1;
2019         unsigned long timeout;
2020         u8 opcode = nvme_admin_delete_sq;
2021
2022         for (pass = 0; pass < 2; pass++) {
2023                 int sent = 0, i = queues;
2024
2025                 reinit_completion(&dev->ioq_wait);
2026  retry:
2027                 timeout = ADMIN_TIMEOUT;
2028                 for (; i > 0; i--, sent++)
2029                         if (nvme_delete_queue(&dev->queues[i], opcode))
2030                                 break;
2031
2032                 while (sent--) {
2033                         timeout = wait_for_completion_io_timeout(&dev->ioq_wait, timeout);
2034                         if (timeout == 0)
2035                                 return;
2036                         if (i)
2037                                 goto retry;
2038                 }
2039                 opcode = nvme_admin_delete_cq;
2040         }
2041 }
2042
2043 /*
2044  * return error value only when tagset allocation failed
2045  */
2046 static int nvme_dev_add(struct nvme_dev *dev)
2047 {
2048         int ret;
2049
2050         if (!dev->ctrl.tagset) {
2051                 dev->tagset.ops = &nvme_mq_ops;
2052                 dev->tagset.nr_hw_queues = dev->online_queues - 1;
2053                 dev->tagset.timeout = NVME_IO_TIMEOUT;
2054                 dev->tagset.numa_node = dev_to_node(dev->dev);
2055                 dev->tagset.queue_depth =
2056                                 min_t(int, dev->q_depth, BLK_MQ_MAX_DEPTH) - 1;
2057                 dev->tagset.cmd_size = nvme_pci_cmd_size(dev, false);
2058                 if ((dev->ctrl.sgls & ((1 << 0) | (1 << 1))) && sgl_threshold) {
2059                         dev->tagset.cmd_size = max(dev->tagset.cmd_size,
2060                                         nvme_pci_cmd_size(dev, true));
2061                 }
2062                 dev->tagset.flags = BLK_MQ_F_SHOULD_MERGE;
2063                 dev->tagset.driver_data = dev;
2064
2065                 ret = blk_mq_alloc_tag_set(&dev->tagset);
2066                 if (ret) {
2067                         dev_warn(dev->ctrl.device,
2068                                 "IO queues tagset allocation failed %d\n", ret);
2069                         return ret;
2070                 }
2071                 dev->ctrl.tagset = &dev->tagset;
2072
2073                 nvme_dbbuf_set(dev);
2074         } else {
2075                 blk_mq_update_nr_hw_queues(&dev->tagset, dev->online_queues - 1);
2076
2077                 /* Free previously allocated queues that are no longer usable */
2078                 nvme_free_queues(dev, dev->online_queues);
2079         }
2080
2081         return 0;
2082 }
2083
2084 static int nvme_pci_enable(struct nvme_dev *dev)
2085 {
2086         int result = -ENOMEM;
2087         struct pci_dev *pdev = to_pci_dev(dev->dev);
2088
2089         if (pci_enable_device_mem(pdev))
2090                 return result;
2091
2092         pci_set_master(pdev);
2093
2094         if (dma_set_mask_and_coherent(dev->dev, DMA_BIT_MASK(64)) &&
2095             dma_set_mask_and_coherent(dev->dev, DMA_BIT_MASK(32)))
2096                 goto disable;
2097
2098         if (readl(dev->bar + NVME_REG_CSTS) == -1) {
2099                 result = -ENODEV;
2100                 goto disable;
2101         }
2102
2103         /*
2104          * Some devices and/or platforms don't advertise or work with INTx
2105          * interrupts. Pre-enable a single MSIX or MSI vec for setup. We'll
2106          * adjust this later.
2107          */
2108         result = pci_alloc_irq_vectors(pdev, 1, 1, PCI_IRQ_ALL_TYPES);
2109         if (result < 0)
2110                 return result;
2111
2112         dev->ctrl.cap = lo_hi_readq(dev->bar + NVME_REG_CAP);
2113
2114         dev->q_depth = min_t(int, NVME_CAP_MQES(dev->ctrl.cap) + 1,
2115                                 io_queue_depth);
2116         dev->db_stride = 1 << NVME_CAP_STRIDE(dev->ctrl.cap);
2117         dev->dbs = dev->bar + 4096;
2118
2119         /*
2120          * Temporary fix for the Apple controller found in the MacBook8,1 and
2121          * some MacBook7,1 to avoid controller resets and data loss.
2122          */
2123         if (pdev->vendor == PCI_VENDOR_ID_APPLE && pdev->device == 0x2001) {
2124                 dev->q_depth = 2;
2125                 dev_warn(dev->ctrl.device, "detected Apple NVMe controller, "
2126                         "set queue depth=%u to work around controller resets\n",
2127                         dev->q_depth);
2128         } else if (pdev->vendor == PCI_VENDOR_ID_SAMSUNG &&
2129                    (pdev->device == 0xa821 || pdev->device == 0xa822) &&
2130                    NVME_CAP_MQES(dev->ctrl.cap) == 0) {
2131                 dev->q_depth = 64;
2132                 dev_err(dev->ctrl.device, "detected PM1725 NVMe controller, "
2133                         "set queue depth=%u\n", dev->q_depth);
2134         }
2135
2136         nvme_map_cmb(dev);
2137
2138         pci_enable_pcie_error_reporting(pdev);
2139         pci_save_state(pdev);
2140         return 0;
2141
2142  disable:
2143         pci_disable_device(pdev);
2144         return result;
2145 }
2146
2147 static void nvme_dev_unmap(struct nvme_dev *dev)
2148 {
2149         if (dev->bar)
2150                 iounmap(dev->bar);
2151         pci_release_mem_regions(to_pci_dev(dev->dev));
2152 }
2153
2154 static void nvme_pci_disable(struct nvme_dev *dev)
2155 {
2156         struct pci_dev *pdev = to_pci_dev(dev->dev);
2157
2158         pci_free_irq_vectors(pdev);
2159
2160         if (pci_is_enabled(pdev)) {
2161                 pci_disable_pcie_error_reporting(pdev);
2162                 pci_disable_device(pdev);
2163         }
2164 }
2165
2166 static void nvme_dev_disable(struct nvme_dev *dev, bool shutdown)
2167 {
2168         int i;
2169         bool dead = true;
2170         struct pci_dev *pdev = to_pci_dev(dev->dev);
2171
2172         mutex_lock(&dev->shutdown_lock);
2173         if (pci_is_enabled(pdev)) {
2174                 u32 csts = readl(dev->bar + NVME_REG_CSTS);
2175
2176                 if (dev->ctrl.state == NVME_CTRL_LIVE ||
2177                     dev->ctrl.state == NVME_CTRL_RESETTING)
2178                         nvme_start_freeze(&dev->ctrl);
2179                 dead = !!((csts & NVME_CSTS_CFS) || !(csts & NVME_CSTS_RDY) ||
2180                         pdev->error_state  != pci_channel_io_normal);
2181         }
2182
2183         /*
2184          * Give the controller a chance to complete all entered requests if
2185          * doing a safe shutdown.
2186          */
2187         if (!dead) {
2188                 if (shutdown)
2189                         nvme_wait_freeze_timeout(&dev->ctrl, NVME_IO_TIMEOUT);
2190         }
2191
2192         nvme_stop_queues(&dev->ctrl);
2193
2194         if (!dead && dev->ctrl.queue_count > 0) {
2195                 nvme_disable_io_queues(dev);
2196                 nvme_disable_admin_queue(dev, shutdown);
2197         }
2198         for (i = dev->ctrl.queue_count - 1; i >= 0; i--)
2199                 nvme_suspend_queue(&dev->queues[i]);
2200
2201         nvme_pci_disable(dev);
2202
2203         blk_mq_tagset_busy_iter(&dev->tagset, nvme_cancel_request, &dev->ctrl);
2204         blk_mq_tagset_busy_iter(&dev->admin_tagset, nvme_cancel_request, &dev->ctrl);
2205
2206         /*
2207          * The driver will not be starting up queues again if shutting down so
2208          * must flush all entered requests to their failed completion to avoid
2209          * deadlocking blk-mq hot-cpu notifier.
2210          */
2211         if (shutdown) {
2212                 nvme_start_queues(&dev->ctrl);
2213                 if (dev->ctrl.admin_q && !blk_queue_dying(dev->ctrl.admin_q))
2214                         blk_mq_unquiesce_queue(dev->ctrl.admin_q);
2215         }
2216         mutex_unlock(&dev->shutdown_lock);
2217 }
2218
2219 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2220 {
2221         dev->prp_page_pool = dma_pool_create("prp list page", dev->dev,
2222                                                 PAGE_SIZE, PAGE_SIZE, 0);
2223         if (!dev->prp_page_pool)
2224                 return -ENOMEM;
2225
2226         /* Optimisation for I/Os between 4k and 128k */
2227         dev->prp_small_pool = dma_pool_create("prp list 256", dev->dev,
2228                                                 256, 256, 0);
2229         if (!dev->prp_small_pool) {
2230                 dma_pool_destroy(dev->prp_page_pool);
2231                 return -ENOMEM;
2232         }
2233         return 0;
2234 }
2235
2236 static void nvme_release_prp_pools(struct nvme_dev *dev)
2237 {
2238         dma_pool_destroy(dev->prp_page_pool);
2239         dma_pool_destroy(dev->prp_small_pool);
2240 }
2241
2242 static void nvme_pci_free_ctrl(struct nvme_ctrl *ctrl)
2243 {
2244         struct nvme_dev *dev = to_nvme_dev(ctrl);
2245
2246         nvme_dbbuf_dma_free(dev);
2247         put_device(dev->dev);
2248         if (dev->tagset.tags)
2249                 blk_mq_free_tag_set(&dev->tagset);
2250         if (dev->ctrl.admin_q)
2251                 blk_put_queue(dev->ctrl.admin_q);
2252         kfree(dev->queues);
2253         free_opal_dev(dev->ctrl.opal_dev);
2254         mempool_destroy(dev->iod_mempool);
2255         kfree(dev);
2256 }
2257
2258 static void nvme_remove_dead_ctrl(struct nvme_dev *dev, int status)
2259 {
2260         dev_warn(dev->ctrl.device, "Removing after probe failure status: %d\n", status);
2261
2262         nvme_get_ctrl(&dev->ctrl);
2263         nvme_dev_disable(dev, false);
2264         nvme_kill_queues(&dev->ctrl);
2265         if (!queue_work(nvme_wq, &dev->remove_work))
2266                 nvme_put_ctrl(&dev->ctrl);
2267 }
2268
2269 static void nvme_reset_work(struct work_struct *work)
2270 {
2271         struct nvme_dev *dev =
2272                 container_of(work, struct nvme_dev, ctrl.reset_work);
2273         bool was_suspend = !!(dev->ctrl.ctrl_config & NVME_CC_SHN_NORMAL);
2274         int result;
2275         enum nvme_ctrl_state new_state = NVME_CTRL_LIVE;
2276
2277         if (dev->ctrl.state != NVME_CTRL_RESETTING) {
2278                 dev_warn(dev->ctrl.device, "ctrl state %d is not RESETTING\n",
2279                          dev->ctrl.state);
2280                 result = -ENODEV;
2281                 goto out;
2282         }
2283
2284         /*
2285          * If we're called to reset a live controller first shut it down before
2286          * moving on.
2287          */
2288         if (dev->ctrl.ctrl_config & NVME_CC_ENABLE)
2289                 nvme_dev_disable(dev, false);
2290
2291         mutex_lock(&dev->shutdown_lock);
2292         result = nvme_pci_enable(dev);
2293         if (result)
2294                 goto out_unlock;
2295
2296         result = nvme_pci_configure_admin_queue(dev);
2297         if (result)
2298                 goto out_unlock;
2299
2300         result = nvme_alloc_admin_tags(dev);
2301         if (result)
2302                 goto out_unlock;
2303
2304         /*
2305          * Limit the max command size to prevent iod->sg allocations going
2306          * over a single page.
2307          */
2308         dev->ctrl.max_hw_sectors = NVME_MAX_KB_SZ << 1;
2309         dev->ctrl.max_segments = NVME_MAX_SEGS;
2310         mutex_unlock(&dev->shutdown_lock);
2311
2312         /*
2313          * Introduce CONNECTING state from nvme-fc/rdma transports to mark the
2314          * initializing procedure here.
2315          */
2316         if (!nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_CONNECTING)) {
2317                 dev_warn(dev->ctrl.device,
2318                         "failed to mark controller CONNECTING\n");
2319                 result = -EBUSY;
2320                 goto out;
2321         }
2322
2323         result = nvme_init_identify(&dev->ctrl);
2324         if (result)
2325                 goto out;
2326
2327         if (dev->ctrl.oacs & NVME_CTRL_OACS_SEC_SUPP) {
2328                 if (!dev->ctrl.opal_dev)
2329                         dev->ctrl.opal_dev =
2330                                 init_opal_dev(&dev->ctrl, &nvme_sec_submit);
2331                 else if (was_suspend)
2332                         opal_unlock_from_suspend(dev->ctrl.opal_dev);
2333         } else {
2334                 free_opal_dev(dev->ctrl.opal_dev);
2335                 dev->ctrl.opal_dev = NULL;
2336         }
2337
2338         if (dev->ctrl.oacs & NVME_CTRL_OACS_DBBUF_SUPP) {
2339                 result = nvme_dbbuf_dma_alloc(dev);
2340                 if (result)
2341                         dev_warn(dev->dev,
2342                                  "unable to allocate dma for dbbuf\n");
2343         }
2344
2345         if (dev->ctrl.hmpre) {
2346                 result = nvme_setup_host_mem(dev);
2347                 if (result < 0)
2348                         goto out;
2349         }
2350
2351         result = nvme_setup_io_queues(dev);
2352         if (result)
2353                 goto out;
2354
2355         /*
2356          * Keep the controller around but remove all namespaces if we don't have
2357          * any working I/O queue.
2358          */
2359         if (dev->online_queues < 2) {
2360                 dev_warn(dev->ctrl.device, "IO queues not created\n");
2361                 nvme_kill_queues(&dev->ctrl);
2362                 nvme_remove_namespaces(&dev->ctrl);
2363                 new_state = NVME_CTRL_ADMIN_ONLY;
2364         } else {
2365                 nvme_start_queues(&dev->ctrl);
2366                 nvme_wait_freeze(&dev->ctrl);
2367                 /* hit this only when allocate tagset fails */
2368                 if (nvme_dev_add(dev))
2369                         new_state = NVME_CTRL_ADMIN_ONLY;
2370                 nvme_unfreeze(&dev->ctrl);
2371         }
2372
2373         /*
2374          * If only admin queue live, keep it to do further investigation or
2375          * recovery.
2376          */
2377         if (!nvme_change_ctrl_state(&dev->ctrl, new_state)) {
2378                 dev_warn(dev->ctrl.device,
2379                         "failed to mark controller state %d\n", new_state);
2380                 result = -ENODEV;
2381                 goto out;
2382         }
2383
2384         nvme_start_ctrl(&dev->ctrl);
2385         return;
2386
2387  out_unlock:
2388         mutex_unlock(&dev->shutdown_lock);
2389  out:
2390         nvme_remove_dead_ctrl(dev, result);
2391 }
2392
2393 static void nvme_remove_dead_ctrl_work(struct work_struct *work)
2394 {
2395         struct nvme_dev *dev = container_of(work, struct nvme_dev, remove_work);
2396         struct pci_dev *pdev = to_pci_dev(dev->dev);
2397
2398         if (pci_get_drvdata(pdev))
2399                 device_release_driver(&pdev->dev);
2400         nvme_put_ctrl(&dev->ctrl);
2401 }
2402
2403 static int nvme_pci_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
2404 {
2405         *val = readl(to_nvme_dev(ctrl)->bar + off);
2406         return 0;
2407 }
2408
2409 static int nvme_pci_reg_write32(struct nvme_ctrl *ctrl, u32 off, u32 val)
2410 {
2411         writel(val, to_nvme_dev(ctrl)->bar + off);
2412         return 0;
2413 }
2414
2415 static int nvme_pci_reg_read64(struct nvme_ctrl *ctrl, u32 off, u64 *val)
2416 {
2417         *val = lo_hi_readq(to_nvme_dev(ctrl)->bar + off);
2418         return 0;
2419 }
2420
2421 static int nvme_pci_get_address(struct nvme_ctrl *ctrl, char *buf, int size)
2422 {
2423         struct pci_dev *pdev = to_pci_dev(to_nvme_dev(ctrl)->dev);
2424
2425         return snprintf(buf, size, "%s", dev_name(&pdev->dev));
2426 }
2427
2428 static const struct nvme_ctrl_ops nvme_pci_ctrl_ops = {
2429         .name                   = "pcie",
2430         .module                 = THIS_MODULE,
2431         .flags                  = NVME_F_METADATA_SUPPORTED,
2432         .reg_read32             = nvme_pci_reg_read32,
2433         .reg_write32            = nvme_pci_reg_write32,
2434         .reg_read64             = nvme_pci_reg_read64,
2435         .free_ctrl              = nvme_pci_free_ctrl,
2436         .submit_async_event     = nvme_pci_submit_async_event,
2437         .get_address            = nvme_pci_get_address,
2438 };
2439
2440 static int nvme_dev_map(struct nvme_dev *dev)
2441 {
2442         struct pci_dev *pdev = to_pci_dev(dev->dev);
2443
2444         if (pci_request_mem_regions(pdev, "nvme"))
2445                 return -ENODEV;
2446
2447         if (nvme_remap_bar(dev, NVME_REG_DBS + 4096))
2448                 goto release;
2449
2450         return 0;
2451   release:
2452         pci_release_mem_regions(pdev);
2453         return -ENODEV;
2454 }
2455
2456 static unsigned long check_vendor_combination_bug(struct pci_dev *pdev)
2457 {
2458         if (pdev->vendor == 0x144d && pdev->device == 0xa802) {
2459                 /*
2460                  * Several Samsung devices seem to drop off the PCIe bus
2461                  * randomly when APST is on and uses the deepest sleep state.
2462                  * This has been observed on a Samsung "SM951 NVMe SAMSUNG
2463                  * 256GB", a "PM951 NVMe SAMSUNG 512GB", and a "Samsung SSD
2464                  * 950 PRO 256GB", but it seems to be restricted to two Dell
2465                  * laptops.
2466                  */
2467                 if (dmi_match(DMI_SYS_VENDOR, "Dell Inc.") &&
2468                     (dmi_match(DMI_PRODUCT_NAME, "XPS 15 9550") ||
2469                      dmi_match(DMI_PRODUCT_NAME, "Precision 5510")))
2470                         return NVME_QUIRK_NO_DEEPEST_PS;
2471         } else if (pdev->vendor == 0x144d && pdev->device == 0xa804) {
2472                 /*
2473                  * Samsung SSD 960 EVO drops off the PCIe bus after system
2474                  * suspend on a Ryzen board, ASUS PRIME B350M-A, as well as
2475                  * within few minutes after bootup on a Coffee Lake board -
2476                  * ASUS PRIME Z370-A
2477                  */
2478                 if (dmi_match(DMI_BOARD_VENDOR, "ASUSTeK COMPUTER INC.") &&
2479                     (dmi_match(DMI_BOARD_NAME, "PRIME B350M-A") ||
2480                      dmi_match(DMI_BOARD_NAME, "PRIME Z370-A")))
2481                         return NVME_QUIRK_NO_APST;
2482         }
2483
2484         return 0;
2485 }
2486
2487 static void nvme_async_probe(void *data, async_cookie_t cookie)
2488 {
2489         struct nvme_dev *dev = data;
2490
2491         flush_work(&dev->ctrl.reset_work);
2492         flush_work(&dev->ctrl.scan_work);
2493         nvme_put_ctrl(&dev->ctrl);
2494 }
2495
2496 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2497 {
2498         int node, result = -ENOMEM;
2499         struct nvme_dev *dev;
2500         unsigned long quirks = id->driver_data;
2501         size_t alloc_size;
2502
2503         node = dev_to_node(&pdev->dev);
2504         if (node == NUMA_NO_NODE)
2505                 set_dev_node(&pdev->dev, first_memory_node);
2506
2507         dev = kzalloc_node(sizeof(*dev), GFP_KERNEL, node);
2508         if (!dev)
2509                 return -ENOMEM;
2510
2511         dev->queues = kcalloc_node(num_possible_cpus() + 1,
2512                         sizeof(struct nvme_queue), GFP_KERNEL, node);
2513         if (!dev->queues)
2514                 goto free;
2515
2516         dev->dev = get_device(&pdev->dev);
2517         pci_set_drvdata(pdev, dev);
2518
2519         result = nvme_dev_map(dev);
2520         if (result)
2521                 goto put_pci;
2522
2523         INIT_WORK(&dev->ctrl.reset_work, nvme_reset_work);
2524         INIT_WORK(&dev->remove_work, nvme_remove_dead_ctrl_work);
2525         mutex_init(&dev->shutdown_lock);
2526         init_completion(&dev->ioq_wait);
2527
2528         result = nvme_setup_prp_pools(dev);
2529         if (result)
2530                 goto unmap;
2531
2532         quirks |= check_vendor_combination_bug(pdev);
2533
2534         /*
2535          * Double check that our mempool alloc size will cover the biggest
2536          * command we support.
2537          */
2538         alloc_size = nvme_pci_iod_alloc_size(dev, NVME_MAX_KB_SZ,
2539                                                 NVME_MAX_SEGS, true);
2540         WARN_ON_ONCE(alloc_size > PAGE_SIZE);
2541
2542         dev->iod_mempool = mempool_create_node(1, mempool_kmalloc,
2543                                                 mempool_kfree,
2544                                                 (void *) alloc_size,
2545                                                 GFP_KERNEL, node);
2546         if (!dev->iod_mempool) {
2547                 result = -ENOMEM;
2548                 goto release_pools;
2549         }
2550
2551         result = nvme_init_ctrl(&dev->ctrl, &pdev->dev, &nvme_pci_ctrl_ops,
2552                         quirks);
2553         if (result)
2554                 goto release_mempool;
2555
2556         dev_info(dev->ctrl.device, "pci function %s\n", dev_name(&pdev->dev));
2557
2558         nvme_reset_ctrl(&dev->ctrl);
2559         nvme_get_ctrl(&dev->ctrl);
2560         async_schedule(nvme_async_probe, dev);
2561
2562         return 0;
2563
2564  release_mempool:
2565         mempool_destroy(dev->iod_mempool);
2566  release_pools:
2567         nvme_release_prp_pools(dev);
2568  unmap:
2569         nvme_dev_unmap(dev);
2570  put_pci:
2571         put_device(dev->dev);
2572  free:
2573         kfree(dev->queues);
2574         kfree(dev);
2575         return result;
2576 }
2577
2578 static void nvme_reset_prepare(struct pci_dev *pdev)
2579 {
2580         struct nvme_dev *dev = pci_get_drvdata(pdev);
2581         nvme_dev_disable(dev, false);
2582 }
2583
2584 static void nvme_reset_done(struct pci_dev *pdev)
2585 {
2586         struct nvme_dev *dev = pci_get_drvdata(pdev);
2587         nvme_reset_ctrl_sync(&dev->ctrl);
2588 }
2589
2590 static void nvme_shutdown(struct pci_dev *pdev)
2591 {
2592         struct nvme_dev *dev = pci_get_drvdata(pdev);
2593         nvme_dev_disable(dev, true);
2594 }
2595
2596 /*
2597  * The driver's remove may be called on a device in a partially initialized
2598  * state. This function must not have any dependencies on the device state in
2599  * order to proceed.
2600  */
2601 static void nvme_remove(struct pci_dev *pdev)
2602 {
2603         struct nvme_dev *dev = pci_get_drvdata(pdev);
2604
2605         nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DELETING);
2606         pci_set_drvdata(pdev, NULL);
2607
2608         if (!pci_device_is_present(pdev)) {
2609                 nvme_change_ctrl_state(&dev->ctrl, NVME_CTRL_DEAD);
2610                 nvme_dev_disable(dev, true);
2611         }
2612
2613         flush_work(&dev->ctrl.reset_work);
2614         nvme_stop_ctrl(&dev->ctrl);
2615         nvme_remove_namespaces(&dev->ctrl);
2616         nvme_dev_disable(dev, true);
2617         nvme_release_cmb(dev);
2618         nvme_free_host_mem(dev);
2619         nvme_dev_remove_admin(dev);
2620         nvme_free_queues(dev, 0);
2621         nvme_uninit_ctrl(&dev->ctrl);
2622         nvme_release_prp_pools(dev);
2623         nvme_dev_unmap(dev);
2624         nvme_put_ctrl(&dev->ctrl);
2625 }
2626
2627 #ifdef CONFIG_PM_SLEEP
2628 static int nvme_suspend(struct device *dev)
2629 {
2630         struct pci_dev *pdev = to_pci_dev(dev);
2631         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2632
2633         nvme_dev_disable(ndev, true);
2634         return 0;
2635 }
2636
2637 static int nvme_resume(struct device *dev)
2638 {
2639         struct pci_dev *pdev = to_pci_dev(dev);
2640         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2641
2642         nvme_reset_ctrl(&ndev->ctrl);
2643         return 0;
2644 }
2645 #endif
2646
2647 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2648
2649 static pci_ers_result_t nvme_error_detected(struct pci_dev *pdev,
2650                                                 pci_channel_state_t state)
2651 {
2652         struct nvme_dev *dev = pci_get_drvdata(pdev);
2653
2654         /*
2655          * A frozen channel requires a reset. When detected, this method will
2656          * shutdown the controller to quiesce. The controller will be restarted
2657          * after the slot reset through driver's slot_reset callback.
2658          */
2659         switch (state) {
2660         case pci_channel_io_normal:
2661                 return PCI_ERS_RESULT_CAN_RECOVER;
2662         case pci_channel_io_frozen:
2663                 dev_warn(dev->ctrl.device,
2664                         "frozen state error detected, reset controller\n");
2665                 nvme_dev_disable(dev, false);
2666                 return PCI_ERS_RESULT_NEED_RESET;
2667         case pci_channel_io_perm_failure:
2668                 dev_warn(dev->ctrl.device,
2669                         "failure state error detected, request disconnect\n");
2670                 return PCI_ERS_RESULT_DISCONNECT;
2671         }
2672         return PCI_ERS_RESULT_NEED_RESET;
2673 }
2674
2675 static pci_ers_result_t nvme_slot_reset(struct pci_dev *pdev)
2676 {
2677         struct nvme_dev *dev = pci_get_drvdata(pdev);
2678
2679         dev_info(dev->ctrl.device, "restart after slot reset\n");
2680         pci_restore_state(pdev);
2681         nvme_reset_ctrl(&dev->ctrl);
2682         return PCI_ERS_RESULT_RECOVERED;
2683 }
2684
2685 static void nvme_error_resume(struct pci_dev *pdev)
2686 {
2687         struct nvme_dev *dev = pci_get_drvdata(pdev);
2688
2689         flush_work(&dev->ctrl.reset_work);
2690         pci_cleanup_aer_uncorrect_error_status(pdev);
2691 }
2692
2693 static const struct pci_error_handlers nvme_err_handler = {
2694         .error_detected = nvme_error_detected,
2695         .slot_reset     = nvme_slot_reset,
2696         .resume         = nvme_error_resume,
2697         .reset_prepare  = nvme_reset_prepare,
2698         .reset_done     = nvme_reset_done,
2699 };
2700
2701 static const struct pci_device_id nvme_id_table[] = {
2702         { PCI_VDEVICE(INTEL, 0x0953),
2703                 .driver_data = NVME_QUIRK_STRIPE_SIZE |
2704                                 NVME_QUIRK_DEALLOCATE_ZEROES, },
2705         { PCI_VDEVICE(INTEL, 0x0a53),
2706                 .driver_data = NVME_QUIRK_STRIPE_SIZE |
2707                                 NVME_QUIRK_DEALLOCATE_ZEROES, },
2708         { PCI_VDEVICE(INTEL, 0x0a54),
2709                 .driver_data = NVME_QUIRK_STRIPE_SIZE |
2710                                 NVME_QUIRK_DEALLOCATE_ZEROES, },
2711         { PCI_VDEVICE(INTEL, 0x0a55),
2712                 .driver_data = NVME_QUIRK_STRIPE_SIZE |
2713                                 NVME_QUIRK_DEALLOCATE_ZEROES, },
2714         { PCI_VDEVICE(INTEL, 0xf1a5),   /* Intel 600P/P3100 */
2715                 .driver_data = NVME_QUIRK_NO_DEEPEST_PS |
2716                                 NVME_QUIRK_MEDIUM_PRIO_SQ },
2717         { PCI_VDEVICE(INTEL, 0x5845),   /* Qemu emulated controller */
2718                 .driver_data = NVME_QUIRK_IDENTIFY_CNS, },
2719         { PCI_DEVICE(0x1bb1, 0x0100),   /* Seagate Nytro Flash Storage */
2720                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2721         { PCI_DEVICE(0x1c58, 0x0003),   /* HGST adapter */
2722                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2723         { PCI_DEVICE(0x1c58, 0x0023),   /* WDC SN200 adapter */
2724                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2725         { PCI_DEVICE(0x1c5f, 0x0540),   /* Memblaze Pblaze4 adapter */
2726                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2727         { PCI_DEVICE(0x144d, 0xa821),   /* Samsung PM1725 */
2728                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2729         { PCI_DEVICE(0x144d, 0xa822),   /* Samsung PM1725a */
2730                 .driver_data = NVME_QUIRK_DELAY_BEFORE_CHK_RDY, },
2731         { PCI_DEVICE(0x1d1d, 0x1f1f),   /* LighNVM qemu device */
2732                 .driver_data = NVME_QUIRK_LIGHTNVM, },
2733         { PCI_DEVICE(0x1d1d, 0x2807),   /* CNEX WL */
2734                 .driver_data = NVME_QUIRK_LIGHTNVM, },
2735         { PCI_DEVICE(0x1d1d, 0x2601),   /* CNEX Granby */
2736                 .driver_data = NVME_QUIRK_LIGHTNVM, },
2737         { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2738         { PCI_DEVICE(0x2646, 0x2263),   /* KINGSTON A2000 NVMe SSD  */
2739                 .driver_data = NVME_QUIRK_NO_DEEPEST_PS, },
2740         { PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2001) },
2741         { PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2003) },
2742         { 0, }
2743 };
2744 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2745
2746 static struct pci_driver nvme_driver = {
2747         .name           = "nvme",
2748         .id_table       = nvme_id_table,
2749         .probe          = nvme_probe,
2750         .remove         = nvme_remove,
2751         .shutdown       = nvme_shutdown,
2752         .driver         = {
2753                 .pm     = &nvme_dev_pm_ops,
2754         },
2755         .sriov_configure = pci_sriov_configure_simple,
2756         .err_handler    = &nvme_err_handler,
2757 };
2758
2759 static int __init nvme_init(void)
2760 {
2761         return pci_register_driver(&nvme_driver);
2762 }
2763
2764 static void __exit nvme_exit(void)
2765 {
2766         pci_unregister_driver(&nvme_driver);
2767         flush_workqueue(nvme_wq);
2768         _nvme_check_size();
2769 }
2770
2771 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2772 MODULE_LICENSE("GPL");
2773 MODULE_VERSION("1.0");
2774 module_init(nvme_init);
2775 module_exit(nvme_exit);