nvme: refactor nvme_queue_rq
[linux-2.6-block.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/bitops.h>
16 #include <linux/blkdev.h>
17 #include <linux/blk-mq.h>
18 #include <linux/cpu.h>
19 #include <linux/delay.h>
20 #include <linux/errno.h>
21 #include <linux/fs.h>
22 #include <linux/genhd.h>
23 #include <linux/hdreg.h>
24 #include <linux/idr.h>
25 #include <linux/init.h>
26 #include <linux/interrupt.h>
27 #include <linux/io.h>
28 #include <linux/kdev_t.h>
29 #include <linux/kthread.h>
30 #include <linux/kernel.h>
31 #include <linux/list_sort.h>
32 #include <linux/mm.h>
33 #include <linux/module.h>
34 #include <linux/moduleparam.h>
35 #include <linux/pci.h>
36 #include <linux/poison.h>
37 #include <linux/ptrace.h>
38 #include <linux/sched.h>
39 #include <linux/slab.h>
40 #include <linux/t10-pi.h>
41 #include <linux/types.h>
42 #include <linux/pr.h>
43 #include <scsi/sg.h>
44 #include <linux/io-64-nonatomic-lo-hi.h>
45 #include <asm/unaligned.h>
46
47 #include <uapi/linux/nvme_ioctl.h>
48 #include "nvme.h"
49
50 #define NVME_MINORS             (1U << MINORBITS)
51 #define NVME_Q_DEPTH            1024
52 #define NVME_AQ_DEPTH           256
53 #define SQ_SIZE(depth)          (depth * sizeof(struct nvme_command))
54 #define CQ_SIZE(depth)          (depth * sizeof(struct nvme_completion))
55 #define SHUTDOWN_TIMEOUT        (shutdown_timeout * HZ)
56
57 unsigned char admin_timeout = 60;
58 module_param(admin_timeout, byte, 0644);
59 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
60
61 unsigned char nvme_io_timeout = 30;
62 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
63 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
64
65 static unsigned char shutdown_timeout = 5;
66 module_param(shutdown_timeout, byte, 0644);
67 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
68
69 static int nvme_major;
70 module_param(nvme_major, int, 0);
71
72 static int nvme_char_major;
73 module_param(nvme_char_major, int, 0);
74
75 static int use_threaded_interrupts;
76 module_param(use_threaded_interrupts, int, 0);
77
78 static bool use_cmb_sqes = true;
79 module_param(use_cmb_sqes, bool, 0644);
80 MODULE_PARM_DESC(use_cmb_sqes, "use controller's memory buffer for I/O SQes");
81
82 static DEFINE_SPINLOCK(dev_list_lock);
83 static LIST_HEAD(dev_list);
84 static struct task_struct *nvme_thread;
85 static struct workqueue_struct *nvme_workq;
86 static wait_queue_head_t nvme_kthread_wait;
87
88 static struct class *nvme_class;
89
90 struct nvme_dev;
91 struct nvme_queue;
92
93 static int __nvme_reset(struct nvme_dev *dev);
94 static int nvme_reset(struct nvme_dev *dev);
95 static void nvme_process_cq(struct nvme_queue *nvmeq);
96 static void nvme_dead_ctrl(struct nvme_dev *dev);
97
98 struct async_cmd_info {
99         struct kthread_work work;
100         struct kthread_worker *worker;
101         struct request *req;
102         u32 result;
103         int status;
104         void *ctx;
105 };
106
107 /*
108  * Represents an NVM Express device.  Each nvme_dev is a PCI function.
109  */
110 struct nvme_dev {
111         struct list_head node;
112         struct nvme_queue **queues;
113         struct blk_mq_tag_set tagset;
114         struct blk_mq_tag_set admin_tagset;
115         u32 __iomem *dbs;
116         struct device *dev;
117         struct dma_pool *prp_page_pool;
118         struct dma_pool *prp_small_pool;
119         unsigned queue_count;
120         unsigned online_queues;
121         unsigned max_qid;
122         int q_depth;
123         u32 db_stride;
124         u32 ctrl_config;
125         struct msix_entry *entry;
126         void __iomem *bar;
127         struct list_head namespaces;
128         struct kref kref;
129         struct device *device;
130         struct work_struct reset_work;
131         struct work_struct probe_work;
132         struct work_struct scan_work;
133         bool subsystem;
134         u32 max_hw_sectors;
135         u32 stripe_size;
136         u32 page_size;
137         void __iomem *cmb;
138         dma_addr_t cmb_dma_addr;
139         u64 cmb_size;
140         u32 cmbsz;
141
142         struct nvme_ctrl ctrl;
143 };
144
145 static inline struct nvme_dev *to_nvme_dev(struct nvme_ctrl *ctrl)
146 {
147         return container_of(ctrl, struct nvme_dev, ctrl);
148 }
149
150 /*
151  * An NVM Express queue.  Each device has at least two (one for admin
152  * commands and one for I/O commands).
153  */
154 struct nvme_queue {
155         struct device *q_dmadev;
156         struct nvme_dev *dev;
157         char irqname[24];       /* nvme4294967295-65535\0 */
158         spinlock_t q_lock;
159         struct nvme_command *sq_cmds;
160         struct nvme_command __iomem *sq_cmds_io;
161         volatile struct nvme_completion *cqes;
162         struct blk_mq_tags **tags;
163         dma_addr_t sq_dma_addr;
164         dma_addr_t cq_dma_addr;
165         u32 __iomem *q_db;
166         u16 q_depth;
167         s16 cq_vector;
168         u16 sq_head;
169         u16 sq_tail;
170         u16 cq_head;
171         u16 qid;
172         u8 cq_phase;
173         u8 cqe_seen;
174         struct async_cmd_info cmdinfo;
175 };
176
177 /*
178  * The nvme_iod describes the data in an I/O, including the list of PRP
179  * entries.  You can't see it in this data structure because C doesn't let
180  * me express that.  Use nvme_alloc_iod to ensure there's enough space
181  * allocated to store the PRP list.
182  */
183 struct nvme_iod {
184         unsigned long private;  /* For the use of the submitter of the I/O */
185         int npages;             /* In the PRP list. 0 means small pool in use */
186         int offset;             /* Of PRP list */
187         int nents;              /* Used in scatterlist */
188         int length;             /* Of data, in bytes */
189         dma_addr_t first_dma;
190         struct scatterlist meta_sg[1]; /* metadata requires single contiguous buffer */
191         struct scatterlist sg[0];
192 };
193
194 /*
195  * Check we didin't inadvertently grow the command struct
196  */
197 static inline void _nvme_check_size(void)
198 {
199         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
200         BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
201         BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
202         BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
203         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
204         BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
205         BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
206         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
207         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
208         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
209         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
210         BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
211 }
212
213 typedef void (*nvme_completion_fn)(struct nvme_queue *, void *,
214                                                 struct nvme_completion *);
215
216 struct nvme_cmd_info {
217         nvme_completion_fn fn;
218         void *ctx;
219         int aborted;
220         struct nvme_queue *nvmeq;
221         struct nvme_iod iod[0];
222 };
223
224 /*
225  * Max size of iod being embedded in the request payload
226  */
227 #define NVME_INT_PAGES          2
228 #define NVME_INT_BYTES(dev)     (NVME_INT_PAGES * (dev)->page_size)
229 #define NVME_INT_MASK           0x01
230
231 /*
232  * Will slightly overestimate the number of pages needed.  This is OK
233  * as it only leads to a small amount of wasted memory for the lifetime of
234  * the I/O.
235  */
236 static int nvme_npages(unsigned size, struct nvme_dev *dev)
237 {
238         unsigned nprps = DIV_ROUND_UP(size + dev->page_size, dev->page_size);
239         return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
240 }
241
242 static unsigned int nvme_cmd_size(struct nvme_dev *dev)
243 {
244         unsigned int ret = sizeof(struct nvme_cmd_info);
245
246         ret += sizeof(struct nvme_iod);
247         ret += sizeof(__le64 *) * nvme_npages(NVME_INT_BYTES(dev), dev);
248         ret += sizeof(struct scatterlist) * NVME_INT_PAGES;
249
250         return ret;
251 }
252
253 static int nvme_admin_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
254                                 unsigned int hctx_idx)
255 {
256         struct nvme_dev *dev = data;
257         struct nvme_queue *nvmeq = dev->queues[0];
258
259         WARN_ON(hctx_idx != 0);
260         WARN_ON(dev->admin_tagset.tags[0] != hctx->tags);
261         WARN_ON(nvmeq->tags);
262
263         hctx->driver_data = nvmeq;
264         nvmeq->tags = &dev->admin_tagset.tags[0];
265         return 0;
266 }
267
268 static void nvme_admin_exit_hctx(struct blk_mq_hw_ctx *hctx, unsigned int hctx_idx)
269 {
270         struct nvme_queue *nvmeq = hctx->driver_data;
271
272         nvmeq->tags = NULL;
273 }
274
275 static int nvme_admin_init_request(void *data, struct request *req,
276                                 unsigned int hctx_idx, unsigned int rq_idx,
277                                 unsigned int numa_node)
278 {
279         struct nvme_dev *dev = data;
280         struct nvme_cmd_info *cmd = blk_mq_rq_to_pdu(req);
281         struct nvme_queue *nvmeq = dev->queues[0];
282
283         BUG_ON(!nvmeq);
284         cmd->nvmeq = nvmeq;
285         return 0;
286 }
287
288 static int nvme_init_hctx(struct blk_mq_hw_ctx *hctx, void *data,
289                           unsigned int hctx_idx)
290 {
291         struct nvme_dev *dev = data;
292         struct nvme_queue *nvmeq = dev->queues[hctx_idx + 1];
293
294         if (!nvmeq->tags)
295                 nvmeq->tags = &dev->tagset.tags[hctx_idx];
296
297         WARN_ON(dev->tagset.tags[hctx_idx] != hctx->tags);
298         hctx->driver_data = nvmeq;
299         return 0;
300 }
301
302 static int nvme_init_request(void *data, struct request *req,
303                                 unsigned int hctx_idx, unsigned int rq_idx,
304                                 unsigned int numa_node)
305 {
306         struct nvme_dev *dev = data;
307         struct nvme_cmd_info *cmd = blk_mq_rq_to_pdu(req);
308         struct nvme_queue *nvmeq = dev->queues[hctx_idx + 1];
309
310         BUG_ON(!nvmeq);
311         cmd->nvmeq = nvmeq;
312         return 0;
313 }
314
315 static void nvme_set_info(struct nvme_cmd_info *cmd, void *ctx,
316                                 nvme_completion_fn handler)
317 {
318         cmd->fn = handler;
319         cmd->ctx = ctx;
320         cmd->aborted = 0;
321         blk_mq_start_request(blk_mq_rq_from_pdu(cmd));
322 }
323
324 static void *iod_get_private(struct nvme_iod *iod)
325 {
326         return (void *) (iod->private & ~0x1UL);
327 }
328
329 /*
330  * If bit 0 is set, the iod is embedded in the request payload.
331  */
332 static bool iod_should_kfree(struct nvme_iod *iod)
333 {
334         return (iod->private & NVME_INT_MASK) == 0;
335 }
336
337 /* Special values must be less than 0x1000 */
338 #define CMD_CTX_BASE            ((void *)POISON_POINTER_DELTA)
339 #define CMD_CTX_CANCELLED       (0x30C + CMD_CTX_BASE)
340 #define CMD_CTX_COMPLETED       (0x310 + CMD_CTX_BASE)
341 #define CMD_CTX_INVALID         (0x314 + CMD_CTX_BASE)
342
343 static void special_completion(struct nvme_queue *nvmeq, void *ctx,
344                                                 struct nvme_completion *cqe)
345 {
346         if (ctx == CMD_CTX_CANCELLED)
347                 return;
348         if (ctx == CMD_CTX_COMPLETED) {
349                 dev_warn(nvmeq->q_dmadev,
350                                 "completed id %d twice on queue %d\n",
351                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
352                 return;
353         }
354         if (ctx == CMD_CTX_INVALID) {
355                 dev_warn(nvmeq->q_dmadev,
356                                 "invalid id %d completed on queue %d\n",
357                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
358                 return;
359         }
360         dev_warn(nvmeq->q_dmadev, "Unknown special completion %p\n", ctx);
361 }
362
363 static void *cancel_cmd_info(struct nvme_cmd_info *cmd, nvme_completion_fn *fn)
364 {
365         void *ctx;
366
367         if (fn)
368                 *fn = cmd->fn;
369         ctx = cmd->ctx;
370         cmd->fn = special_completion;
371         cmd->ctx = CMD_CTX_CANCELLED;
372         return ctx;
373 }
374
375 static void async_req_completion(struct nvme_queue *nvmeq, void *ctx,
376                                                 struct nvme_completion *cqe)
377 {
378         u32 result = le32_to_cpup(&cqe->result);
379         u16 status = le16_to_cpup(&cqe->status) >> 1;
380
381         if (status == NVME_SC_SUCCESS || status == NVME_SC_ABORT_REQ)
382                 ++nvmeq->dev->ctrl.event_limit;
383         if (status != NVME_SC_SUCCESS)
384                 return;
385
386         switch (result & 0xff07) {
387         case NVME_AER_NOTICE_NS_CHANGED:
388                 dev_info(nvmeq->q_dmadev, "rescanning\n");
389                 schedule_work(&nvmeq->dev->scan_work);
390         default:
391                 dev_warn(nvmeq->q_dmadev, "async event result %08x\n", result);
392         }
393 }
394
395 static void abort_completion(struct nvme_queue *nvmeq, void *ctx,
396                                                 struct nvme_completion *cqe)
397 {
398         struct request *req = ctx;
399
400         u16 status = le16_to_cpup(&cqe->status) >> 1;
401         u32 result = le32_to_cpup(&cqe->result);
402
403         blk_mq_free_request(req);
404
405         dev_warn(nvmeq->q_dmadev, "Abort status:%x result:%x", status, result);
406         ++nvmeq->dev->ctrl.abort_limit;
407 }
408
409 static void async_completion(struct nvme_queue *nvmeq, void *ctx,
410                                                 struct nvme_completion *cqe)
411 {
412         struct async_cmd_info *cmdinfo = ctx;
413         cmdinfo->result = le32_to_cpup(&cqe->result);
414         cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
415         queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
416         blk_mq_free_request(cmdinfo->req);
417 }
418
419 static inline struct nvme_cmd_info *get_cmd_from_tag(struct nvme_queue *nvmeq,
420                                   unsigned int tag)
421 {
422         struct request *req = blk_mq_tag_to_rq(*nvmeq->tags, tag);
423
424         return blk_mq_rq_to_pdu(req);
425 }
426
427 /*
428  * Called with local interrupts disabled and the q_lock held.  May not sleep.
429  */
430 static void *nvme_finish_cmd(struct nvme_queue *nvmeq, int tag,
431                                                 nvme_completion_fn *fn)
432 {
433         struct nvme_cmd_info *cmd = get_cmd_from_tag(nvmeq, tag);
434         void *ctx;
435         if (tag >= nvmeq->q_depth) {
436                 *fn = special_completion;
437                 return CMD_CTX_INVALID;
438         }
439         if (fn)
440                 *fn = cmd->fn;
441         ctx = cmd->ctx;
442         cmd->fn = special_completion;
443         cmd->ctx = CMD_CTX_COMPLETED;
444         return ctx;
445 }
446
447 /**
448  * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
449  * @nvmeq: The queue to use
450  * @cmd: The command to send
451  *
452  * Safe to use from interrupt context
453  */
454 static void __nvme_submit_cmd(struct nvme_queue *nvmeq,
455                                                 struct nvme_command *cmd)
456 {
457         u16 tail = nvmeq->sq_tail;
458
459         if (nvmeq->sq_cmds_io)
460                 memcpy_toio(&nvmeq->sq_cmds_io[tail], cmd, sizeof(*cmd));
461         else
462                 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
463
464         if (++tail == nvmeq->q_depth)
465                 tail = 0;
466         writel(tail, nvmeq->q_db);
467         nvmeq->sq_tail = tail;
468 }
469
470 static void nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
471 {
472         unsigned long flags;
473         spin_lock_irqsave(&nvmeq->q_lock, flags);
474         __nvme_submit_cmd(nvmeq, cmd);
475         spin_unlock_irqrestore(&nvmeq->q_lock, flags);
476 }
477
478 static __le64 **iod_list(struct nvme_iod *iod)
479 {
480         return ((void *)iod) + iod->offset;
481 }
482
483 static inline void iod_init(struct nvme_iod *iod, unsigned nbytes,
484                             unsigned nseg, unsigned long private)
485 {
486         iod->private = private;
487         iod->offset = offsetof(struct nvme_iod, sg[nseg]);
488         iod->npages = -1;
489         iod->length = nbytes;
490         iod->nents = 0;
491 }
492
493 static struct nvme_iod *
494 __nvme_alloc_iod(unsigned nseg, unsigned bytes, struct nvme_dev *dev,
495                  unsigned long priv, gfp_t gfp)
496 {
497         struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
498                                 sizeof(__le64 *) * nvme_npages(bytes, dev) +
499                                 sizeof(struct scatterlist) * nseg, gfp);
500
501         if (iod)
502                 iod_init(iod, bytes, nseg, priv);
503
504         return iod;
505 }
506
507 static struct nvme_iod *nvme_alloc_iod(struct request *rq, struct nvme_dev *dev,
508                                        gfp_t gfp)
509 {
510         unsigned size = !(rq->cmd_flags & REQ_DISCARD) ? blk_rq_bytes(rq) :
511                                                 sizeof(struct nvme_dsm_range);
512         struct nvme_iod *iod;
513
514         if (rq->nr_phys_segments <= NVME_INT_PAGES &&
515             size <= NVME_INT_BYTES(dev)) {
516                 struct nvme_cmd_info *cmd = blk_mq_rq_to_pdu(rq);
517
518                 iod = cmd->iod;
519                 iod_init(iod, size, rq->nr_phys_segments,
520                                 (unsigned long) rq | NVME_INT_MASK);
521                 return iod;
522         }
523
524         return __nvme_alloc_iod(rq->nr_phys_segments, size, dev,
525                                 (unsigned long) rq, gfp);
526 }
527
528 static void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
529 {
530         const int last_prp = dev->page_size / 8 - 1;
531         int i;
532         __le64 **list = iod_list(iod);
533         dma_addr_t prp_dma = iod->first_dma;
534
535         if (iod->npages == 0)
536                 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
537         for (i = 0; i < iod->npages; i++) {
538                 __le64 *prp_list = list[i];
539                 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
540                 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
541                 prp_dma = next_prp_dma;
542         }
543
544         if (iod_should_kfree(iod))
545                 kfree(iod);
546 }
547
548 static int nvme_error_status(u16 status)
549 {
550         switch (status & 0x7ff) {
551         case NVME_SC_SUCCESS:
552                 return 0;
553         case NVME_SC_CAP_EXCEEDED:
554                 return -ENOSPC;
555         default:
556                 return -EIO;
557         }
558 }
559
560 #ifdef CONFIG_BLK_DEV_INTEGRITY
561 static void nvme_dif_prep(u32 p, u32 v, struct t10_pi_tuple *pi)
562 {
563         if (be32_to_cpu(pi->ref_tag) == v)
564                 pi->ref_tag = cpu_to_be32(p);
565 }
566
567 static void nvme_dif_complete(u32 p, u32 v, struct t10_pi_tuple *pi)
568 {
569         if (be32_to_cpu(pi->ref_tag) == p)
570                 pi->ref_tag = cpu_to_be32(v);
571 }
572
573 /**
574  * nvme_dif_remap - remaps ref tags to bip seed and physical lba
575  *
576  * The virtual start sector is the one that was originally submitted by the
577  * block layer. Due to partitioning, MD/DM cloning, etc. the actual physical
578  * start sector may be different. Remap protection information to match the
579  * physical LBA on writes, and back to the original seed on reads.
580  *
581  * Type 0 and 3 do not have a ref tag, so no remapping required.
582  */
583 static void nvme_dif_remap(struct request *req,
584                         void (*dif_swap)(u32 p, u32 v, struct t10_pi_tuple *pi))
585 {
586         struct nvme_ns *ns = req->rq_disk->private_data;
587         struct bio_integrity_payload *bip;
588         struct t10_pi_tuple *pi;
589         void *p, *pmap;
590         u32 i, nlb, ts, phys, virt;
591
592         if (!ns->pi_type || ns->pi_type == NVME_NS_DPS_PI_TYPE3)
593                 return;
594
595         bip = bio_integrity(req->bio);
596         if (!bip)
597                 return;
598
599         pmap = kmap_atomic(bip->bip_vec->bv_page) + bip->bip_vec->bv_offset;
600
601         p = pmap;
602         virt = bip_get_seed(bip);
603         phys = nvme_block_nr(ns, blk_rq_pos(req));
604         nlb = (blk_rq_bytes(req) >> ns->lba_shift);
605         ts = ns->disk->queue->integrity.tuple_size;
606
607         for (i = 0; i < nlb; i++, virt++, phys++) {
608                 pi = (struct t10_pi_tuple *)p;
609                 dif_swap(phys, virt, pi);
610                 p += ts;
611         }
612         kunmap_atomic(pmap);
613 }
614
615 static void nvme_init_integrity(struct nvme_ns *ns)
616 {
617         struct blk_integrity integrity;
618
619         switch (ns->pi_type) {
620         case NVME_NS_DPS_PI_TYPE3:
621                 integrity.profile = &t10_pi_type3_crc;
622                 break;
623         case NVME_NS_DPS_PI_TYPE1:
624         case NVME_NS_DPS_PI_TYPE2:
625                 integrity.profile = &t10_pi_type1_crc;
626                 break;
627         default:
628                 integrity.profile = NULL;
629                 break;
630         }
631         integrity.tuple_size = ns->ms;
632         blk_integrity_register(ns->disk, &integrity);
633         blk_queue_max_integrity_segments(ns->queue, 1);
634 }
635 #else /* CONFIG_BLK_DEV_INTEGRITY */
636 static void nvme_dif_remap(struct request *req,
637                         void (*dif_swap)(u32 p, u32 v, struct t10_pi_tuple *pi))
638 {
639 }
640 static void nvme_dif_prep(u32 p, u32 v, struct t10_pi_tuple *pi)
641 {
642 }
643 static void nvme_dif_complete(u32 p, u32 v, struct t10_pi_tuple *pi)
644 {
645 }
646 static void nvme_init_integrity(struct nvme_ns *ns)
647 {
648 }
649 #endif
650
651 static void req_completion(struct nvme_queue *nvmeq, void *ctx,
652                                                 struct nvme_completion *cqe)
653 {
654         struct nvme_iod *iod = ctx;
655         struct request *req = iod_get_private(iod);
656         struct nvme_cmd_info *cmd_rq = blk_mq_rq_to_pdu(req);
657         u16 status = le16_to_cpup(&cqe->status) >> 1;
658         bool requeue = false;
659         int error = 0;
660
661         if (unlikely(status)) {
662                 if (!(status & NVME_SC_DNR || blk_noretry_request(req))
663                     && (jiffies - req->start_time) < req->timeout) {
664                         unsigned long flags;
665
666                         requeue = true;
667                         blk_mq_requeue_request(req);
668                         spin_lock_irqsave(req->q->queue_lock, flags);
669                         if (!blk_queue_stopped(req->q))
670                                 blk_mq_kick_requeue_list(req->q);
671                         spin_unlock_irqrestore(req->q->queue_lock, flags);
672                         goto release_iod;
673                 }
674
675                 if (req->cmd_type == REQ_TYPE_DRV_PRIV) {
676                         if (cmd_rq->ctx == CMD_CTX_CANCELLED)
677                                 error = -EINTR;
678                         else
679                                 error = status;
680                 } else {
681                         error = nvme_error_status(status);
682                 }
683         }
684
685         if (req->cmd_type == REQ_TYPE_DRV_PRIV) {
686                 u32 result = le32_to_cpup(&cqe->result);
687                 req->special = (void *)(uintptr_t)result;
688         }
689
690         if (cmd_rq->aborted)
691                 dev_warn(nvmeq->dev->dev,
692                         "completing aborted command with status:%04x\n",
693                         error);
694
695 release_iod:
696         if (iod->nents) {
697                 dma_unmap_sg(nvmeq->dev->dev, iod->sg, iod->nents,
698                         rq_data_dir(req) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
699                 if (blk_integrity_rq(req)) {
700                         if (!rq_data_dir(req))
701                                 nvme_dif_remap(req, nvme_dif_complete);
702                         dma_unmap_sg(nvmeq->dev->dev, iod->meta_sg, 1,
703                                 rq_data_dir(req) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
704                 }
705         }
706         nvme_free_iod(nvmeq->dev, iod);
707
708         if (likely(!requeue))
709                 blk_mq_complete_request(req, error);
710 }
711
712 static bool nvme_setup_prps(struct nvme_dev *dev, struct nvme_iod *iod,
713                 int total_len)
714 {
715         struct dma_pool *pool;
716         int length = total_len;
717         struct scatterlist *sg = iod->sg;
718         int dma_len = sg_dma_len(sg);
719         u64 dma_addr = sg_dma_address(sg);
720         u32 page_size = dev->page_size;
721         int offset = dma_addr & (page_size - 1);
722         __le64 *prp_list;
723         __le64 **list = iod_list(iod);
724         dma_addr_t prp_dma;
725         int nprps, i;
726
727         length -= (page_size - offset);
728         if (length <= 0)
729                 return true;
730
731         dma_len -= (page_size - offset);
732         if (dma_len) {
733                 dma_addr += (page_size - offset);
734         } else {
735                 sg = sg_next(sg);
736                 dma_addr = sg_dma_address(sg);
737                 dma_len = sg_dma_len(sg);
738         }
739
740         if (length <= page_size) {
741                 iod->first_dma = dma_addr;
742                 return true;
743         }
744
745         nprps = DIV_ROUND_UP(length, page_size);
746         if (nprps <= (256 / 8)) {
747                 pool = dev->prp_small_pool;
748                 iod->npages = 0;
749         } else {
750                 pool = dev->prp_page_pool;
751                 iod->npages = 1;
752         }
753
754         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
755         if (!prp_list) {
756                 iod->first_dma = dma_addr;
757                 iod->npages = -1;
758                 return false;
759         }
760         list[0] = prp_list;
761         iod->first_dma = prp_dma;
762         i = 0;
763         for (;;) {
764                 if (i == page_size >> 3) {
765                         __le64 *old_prp_list = prp_list;
766                         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
767                         if (!prp_list)
768                                 return false;
769                         list[iod->npages++] = prp_list;
770                         prp_list[0] = old_prp_list[i - 1];
771                         old_prp_list[i - 1] = cpu_to_le64(prp_dma);
772                         i = 1;
773                 }
774                 prp_list[i++] = cpu_to_le64(dma_addr);
775                 dma_len -= page_size;
776                 dma_addr += page_size;
777                 length -= page_size;
778                 if (length <= 0)
779                         break;
780                 if (dma_len > 0)
781                         continue;
782                 BUG_ON(dma_len < 0);
783                 sg = sg_next(sg);
784                 dma_addr = sg_dma_address(sg);
785                 dma_len = sg_dma_len(sg);
786         }
787
788         return true;
789 }
790
791 static int nvme_map_data(struct nvme_dev *dev, struct nvme_iod *iod,
792                 struct nvme_command *cmnd)
793 {
794         struct request *req = iod_get_private(iod);
795         struct request_queue *q = req->q;
796         enum dma_data_direction dma_dir = rq_data_dir(req) ?
797                         DMA_TO_DEVICE : DMA_FROM_DEVICE;
798         int ret = BLK_MQ_RQ_QUEUE_ERROR;
799
800         sg_init_table(iod->sg, req->nr_phys_segments);
801         iod->nents = blk_rq_map_sg(q, req, iod->sg);
802         if (!iod->nents)
803                 goto out;
804
805         ret = BLK_MQ_RQ_QUEUE_BUSY;
806         if (!dma_map_sg(dev->dev, iod->sg, iod->nents, dma_dir))
807                 goto out;
808
809         if (!nvme_setup_prps(dev, iod, blk_rq_bytes(req)))
810                 goto out_unmap;
811
812         ret = BLK_MQ_RQ_QUEUE_ERROR;
813         if (blk_integrity_rq(req)) {
814                 if (blk_rq_count_integrity_sg(q, req->bio) != 1)
815                         goto out_unmap;
816
817                 sg_init_table(iod->meta_sg, 1);
818                 if (blk_rq_map_integrity_sg(q, req->bio, iod->meta_sg) != 1)
819                         goto out_unmap;
820
821                 if (rq_data_dir(req))
822                         nvme_dif_remap(req, nvme_dif_prep);
823
824                 if (!dma_map_sg(dev->dev, iod->meta_sg, 1, dma_dir))
825                         goto out_unmap;
826         }
827
828         cmnd->rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
829         cmnd->rw.prp2 = cpu_to_le64(iod->first_dma);
830         if (blk_integrity_rq(req))
831                 cmnd->rw.metadata = cpu_to_le64(sg_dma_address(iod->meta_sg));
832         return BLK_MQ_RQ_QUEUE_OK;
833
834 out_unmap:
835         dma_unmap_sg(dev->dev, iod->sg, iod->nents, dma_dir);
836 out:
837         return ret;
838 }
839
840 /*
841  * We reuse the small pool to allocate the 16-byte range here as it is not
842  * worth having a special pool for these or additional cases to handle freeing
843  * the iod.
844  */
845 static int nvme_setup_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
846                 struct nvme_iod *iod, struct nvme_command *cmnd)
847 {
848         struct request *req = iod_get_private(iod);
849         struct nvme_dsm_range *range;
850
851         range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
852                                                 &iod->first_dma);
853         if (!range)
854                 return BLK_MQ_RQ_QUEUE_BUSY;
855         iod_list(iod)[0] = (__le64 *)range;
856         iod->npages = 0;
857
858         range->cattr = cpu_to_le32(0);
859         range->nlb = cpu_to_le32(blk_rq_bytes(req) >> ns->lba_shift);
860         range->slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
861
862         memset(cmnd, 0, sizeof(*cmnd));
863         cmnd->dsm.opcode = nvme_cmd_dsm;
864         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
865         cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
866         cmnd->dsm.nr = 0;
867         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
868         return BLK_MQ_RQ_QUEUE_OK;
869 }
870
871 static void nvme_setup_flush(struct nvme_ns *ns, struct nvme_command *cmnd)
872 {
873         memset(cmnd, 0, sizeof(*cmnd));
874         cmnd->common.opcode = nvme_cmd_flush;
875         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
876 }
877
878 static void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
879                 struct nvme_command *cmnd)
880 {
881         u16 control = 0;
882         u32 dsmgmt = 0;
883
884         if (req->cmd_flags & REQ_FUA)
885                 control |= NVME_RW_FUA;
886         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
887                 control |= NVME_RW_LR;
888
889         if (req->cmd_flags & REQ_RAHEAD)
890                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
891
892         memset(cmnd, 0, sizeof(*cmnd));
893         cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
894         cmnd->rw.command_id = req->tag;
895         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
896         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
897         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
898
899         if (ns->ms) {
900                 switch (ns->pi_type) {
901                 case NVME_NS_DPS_PI_TYPE3:
902                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
903                         break;
904                 case NVME_NS_DPS_PI_TYPE1:
905                 case NVME_NS_DPS_PI_TYPE2:
906                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
907                                         NVME_RW_PRINFO_PRCHK_REF;
908                         cmnd->rw.reftag = cpu_to_le32(
909                                         nvme_block_nr(ns, blk_rq_pos(req)));
910                         break;
911                 }
912                 if (!blk_integrity_rq(req))
913                         control |= NVME_RW_PRINFO_PRACT;
914         }
915
916         cmnd->rw.control = cpu_to_le16(control);
917         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
918 }
919
920 /*
921  * NOTE: ns is NULL when called on the admin queue.
922  */
923 static int nvme_queue_rq(struct blk_mq_hw_ctx *hctx,
924                          const struct blk_mq_queue_data *bd)
925 {
926         struct nvme_ns *ns = hctx->queue->queuedata;
927         struct nvme_queue *nvmeq = hctx->driver_data;
928         struct nvme_dev *dev = nvmeq->dev;
929         struct request *req = bd->rq;
930         struct nvme_cmd_info *cmd = blk_mq_rq_to_pdu(req);
931         struct nvme_iod *iod;
932         struct nvme_command cmnd;
933         int ret = BLK_MQ_RQ_QUEUE_OK;
934
935         /*
936          * If formated with metadata, require the block layer provide a buffer
937          * unless this namespace is formated such that the metadata can be
938          * stripped/generated by the controller with PRACT=1.
939          */
940         if (ns && ns->ms && !blk_integrity_rq(req)) {
941                 if (!(ns->pi_type && ns->ms == 8) &&
942                                         req->cmd_type != REQ_TYPE_DRV_PRIV) {
943                         blk_mq_complete_request(req, -EFAULT);
944                         return BLK_MQ_RQ_QUEUE_OK;
945                 }
946         }
947
948         iod = nvme_alloc_iod(req, dev, GFP_ATOMIC);
949         if (!iod)
950                 return BLK_MQ_RQ_QUEUE_BUSY;
951
952         if (req->cmd_flags & REQ_DISCARD) {
953                 ret = nvme_setup_discard(nvmeq, ns, iod, &cmnd);
954         } else {
955                 if (req->cmd_type == REQ_TYPE_DRV_PRIV)
956                         memcpy(&cmnd, req->cmd, sizeof(cmnd));
957                 else if (req->cmd_flags & REQ_FLUSH)
958                         nvme_setup_flush(ns, &cmnd);
959                 else
960                         nvme_setup_rw(ns, req, &cmnd);
961
962                 if (req->nr_phys_segments)
963                         ret = nvme_map_data(dev, iod, &cmnd);
964         }
965
966         if (ret)
967                 goto out;
968
969         cmnd.common.command_id = req->tag;
970         nvme_set_info(cmd, iod, req_completion);
971
972         spin_lock_irq(&nvmeq->q_lock);
973         __nvme_submit_cmd(nvmeq, &cmnd);
974         nvme_process_cq(nvmeq);
975         spin_unlock_irq(&nvmeq->q_lock);
976         return BLK_MQ_RQ_QUEUE_OK;
977 out:
978         nvme_free_iod(dev, iod);
979         return ret;
980 }
981
982 static void __nvme_process_cq(struct nvme_queue *nvmeq, unsigned int *tag)
983 {
984         u16 head, phase;
985
986         head = nvmeq->cq_head;
987         phase = nvmeq->cq_phase;
988
989         for (;;) {
990                 void *ctx;
991                 nvme_completion_fn fn;
992                 struct nvme_completion cqe = nvmeq->cqes[head];
993                 if ((le16_to_cpu(cqe.status) & 1) != phase)
994                         break;
995                 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
996                 if (++head == nvmeq->q_depth) {
997                         head = 0;
998                         phase = !phase;
999                 }
1000                 if (tag && *tag == cqe.command_id)
1001                         *tag = -1;
1002                 ctx = nvme_finish_cmd(nvmeq, cqe.command_id, &fn);
1003                 fn(nvmeq, ctx, &cqe);
1004         }
1005
1006         /* If the controller ignores the cq head doorbell and continuously
1007          * writes to the queue, it is theoretically possible to wrap around
1008          * the queue twice and mistakenly return IRQ_NONE.  Linux only
1009          * requires that 0.1% of your interrupts are handled, so this isn't
1010          * a big problem.
1011          */
1012         if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
1013                 return;
1014
1015         if (likely(nvmeq->cq_vector >= 0))
1016                 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
1017         nvmeq->cq_head = head;
1018         nvmeq->cq_phase = phase;
1019
1020         nvmeq->cqe_seen = 1;
1021 }
1022
1023 static void nvme_process_cq(struct nvme_queue *nvmeq)
1024 {
1025         __nvme_process_cq(nvmeq, NULL);
1026 }
1027
1028 static irqreturn_t nvme_irq(int irq, void *data)
1029 {
1030         irqreturn_t result;
1031         struct nvme_queue *nvmeq = data;
1032         spin_lock(&nvmeq->q_lock);
1033         nvme_process_cq(nvmeq);
1034         result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
1035         nvmeq->cqe_seen = 0;
1036         spin_unlock(&nvmeq->q_lock);
1037         return result;
1038 }
1039
1040 static irqreturn_t nvme_irq_check(int irq, void *data)
1041 {
1042         struct nvme_queue *nvmeq = data;
1043         struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
1044         if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
1045                 return IRQ_NONE;
1046         return IRQ_WAKE_THREAD;
1047 }
1048
1049 static int nvme_poll(struct blk_mq_hw_ctx *hctx, unsigned int tag)
1050 {
1051         struct nvme_queue *nvmeq = hctx->driver_data;
1052
1053         if ((le16_to_cpu(nvmeq->cqes[nvmeq->cq_head].status) & 1) ==
1054             nvmeq->cq_phase) {
1055                 spin_lock_irq(&nvmeq->q_lock);
1056                 __nvme_process_cq(nvmeq, &tag);
1057                 spin_unlock_irq(&nvmeq->q_lock);
1058
1059                 if (tag == -1)
1060                         return 1;
1061         }
1062
1063         return 0;
1064 }
1065
1066 static int nvme_submit_async_admin_req(struct nvme_dev *dev)
1067 {
1068         struct nvme_queue *nvmeq = dev->queues[0];
1069         struct nvme_command c;
1070         struct nvme_cmd_info *cmd_info;
1071         struct request *req;
1072
1073         req = blk_mq_alloc_request(dev->ctrl.admin_q, WRITE,
1074                         BLK_MQ_REQ_NOWAIT | BLK_MQ_REQ_RESERVED);
1075         if (IS_ERR(req))
1076                 return PTR_ERR(req);
1077
1078         req->cmd_flags |= REQ_NO_TIMEOUT;
1079         cmd_info = blk_mq_rq_to_pdu(req);
1080         nvme_set_info(cmd_info, NULL, async_req_completion);
1081
1082         memset(&c, 0, sizeof(c));
1083         c.common.opcode = nvme_admin_async_event;
1084         c.common.command_id = req->tag;
1085
1086         blk_mq_free_request(req);
1087         __nvme_submit_cmd(nvmeq, &c);
1088         return 0;
1089 }
1090
1091 static int nvme_submit_admin_async_cmd(struct nvme_dev *dev,
1092                         struct nvme_command *cmd,
1093                         struct async_cmd_info *cmdinfo, unsigned timeout)
1094 {
1095         struct nvme_queue *nvmeq = dev->queues[0];
1096         struct request *req;
1097         struct nvme_cmd_info *cmd_rq;
1098
1099         req = blk_mq_alloc_request(dev->ctrl.admin_q, WRITE, 0);
1100         if (IS_ERR(req))
1101                 return PTR_ERR(req);
1102
1103         req->timeout = timeout;
1104         cmd_rq = blk_mq_rq_to_pdu(req);
1105         cmdinfo->req = req;
1106         nvme_set_info(cmd_rq, cmdinfo, async_completion);
1107         cmdinfo->status = -EINTR;
1108
1109         cmd->common.command_id = req->tag;
1110
1111         nvme_submit_cmd(nvmeq, cmd);
1112         return 0;
1113 }
1114
1115 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
1116 {
1117         struct nvme_command c;
1118
1119         memset(&c, 0, sizeof(c));
1120         c.delete_queue.opcode = opcode;
1121         c.delete_queue.qid = cpu_to_le16(id);
1122
1123         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1124 }
1125
1126 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
1127                                                 struct nvme_queue *nvmeq)
1128 {
1129         struct nvme_command c;
1130         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
1131
1132         /*
1133          * Note: we (ab)use the fact the the prp fields survive if no data
1134          * is attached to the request.
1135          */
1136         memset(&c, 0, sizeof(c));
1137         c.create_cq.opcode = nvme_admin_create_cq;
1138         c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1139         c.create_cq.cqid = cpu_to_le16(qid);
1140         c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1141         c.create_cq.cq_flags = cpu_to_le16(flags);
1142         c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
1143
1144         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1145 }
1146
1147 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1148                                                 struct nvme_queue *nvmeq)
1149 {
1150         struct nvme_command c;
1151         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
1152
1153         /*
1154          * Note: we (ab)use the fact the the prp fields survive if no data
1155          * is attached to the request.
1156          */
1157         memset(&c, 0, sizeof(c));
1158         c.create_sq.opcode = nvme_admin_create_sq;
1159         c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1160         c.create_sq.sqid = cpu_to_le16(qid);
1161         c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1162         c.create_sq.sq_flags = cpu_to_le16(flags);
1163         c.create_sq.cqid = cpu_to_le16(qid);
1164
1165         return nvme_submit_sync_cmd(dev->ctrl.admin_q, &c, NULL, 0);
1166 }
1167
1168 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1169 {
1170         return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1171 }
1172
1173 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1174 {
1175         return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1176 }
1177
1178 /**
1179  * nvme_abort_req - Attempt aborting a request
1180  *
1181  * Schedule controller reset if the command was already aborted once before and
1182  * still hasn't been returned to the driver, or if this is the admin queue.
1183  */
1184 static void nvme_abort_req(struct request *req)
1185 {
1186         struct nvme_cmd_info *cmd_rq = blk_mq_rq_to_pdu(req);
1187         struct nvme_queue *nvmeq = cmd_rq->nvmeq;
1188         struct nvme_dev *dev = nvmeq->dev;
1189         struct request *abort_req;
1190         struct nvme_cmd_info *abort_cmd;
1191         struct nvme_command cmd;
1192
1193         if (!nvmeq->qid || cmd_rq->aborted) {
1194                 spin_lock(&dev_list_lock);
1195                 if (!__nvme_reset(dev)) {
1196                         dev_warn(dev->dev,
1197                                  "I/O %d QID %d timeout, reset controller\n",
1198                                  req->tag, nvmeq->qid);
1199                 }
1200                 spin_unlock(&dev_list_lock);
1201                 return;
1202         }
1203
1204         if (!dev->ctrl.abort_limit)
1205                 return;
1206
1207         abort_req = blk_mq_alloc_request(dev->ctrl.admin_q, WRITE,
1208                         BLK_MQ_REQ_NOWAIT);
1209         if (IS_ERR(abort_req))
1210                 return;
1211
1212         abort_cmd = blk_mq_rq_to_pdu(abort_req);
1213         nvme_set_info(abort_cmd, abort_req, abort_completion);
1214
1215         memset(&cmd, 0, sizeof(cmd));
1216         cmd.abort.opcode = nvme_admin_abort_cmd;
1217         cmd.abort.cid = req->tag;
1218         cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1219         cmd.abort.command_id = abort_req->tag;
1220
1221         --dev->ctrl.abort_limit;
1222         cmd_rq->aborted = 1;
1223
1224         dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", req->tag,
1225                                                         nvmeq->qid);
1226         nvme_submit_cmd(dev->queues[0], &cmd);
1227 }
1228
1229 static void nvme_cancel_queue_ios(struct request *req, void *data, bool reserved)
1230 {
1231         struct nvme_queue *nvmeq = data;
1232         void *ctx;
1233         nvme_completion_fn fn;
1234         struct nvme_cmd_info *cmd;
1235         struct nvme_completion cqe;
1236
1237         if (!blk_mq_request_started(req))
1238                 return;
1239
1240         cmd = blk_mq_rq_to_pdu(req);
1241
1242         if (cmd->ctx == CMD_CTX_CANCELLED)
1243                 return;
1244
1245         if (blk_queue_dying(req->q))
1246                 cqe.status = cpu_to_le16((NVME_SC_ABORT_REQ | NVME_SC_DNR) << 1);
1247         else
1248                 cqe.status = cpu_to_le16(NVME_SC_ABORT_REQ << 1);
1249
1250
1251         dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n",
1252                                                 req->tag, nvmeq->qid);
1253         ctx = cancel_cmd_info(cmd, &fn);
1254         fn(nvmeq, ctx, &cqe);
1255 }
1256
1257 static enum blk_eh_timer_return nvme_timeout(struct request *req, bool reserved)
1258 {
1259         struct nvme_cmd_info *cmd = blk_mq_rq_to_pdu(req);
1260         struct nvme_queue *nvmeq = cmd->nvmeq;
1261
1262         dev_warn(nvmeq->q_dmadev, "Timeout I/O %d QID %d\n", req->tag,
1263                                                         nvmeq->qid);
1264         spin_lock_irq(&nvmeq->q_lock);
1265         nvme_abort_req(req);
1266         spin_unlock_irq(&nvmeq->q_lock);
1267
1268         /*
1269          * The aborted req will be completed on receiving the abort req.
1270          * We enable the timer again. If hit twice, it'll cause a device reset,
1271          * as the device then is in a faulty state.
1272          */
1273         return BLK_EH_RESET_TIMER;
1274 }
1275
1276 static void nvme_free_queue(struct nvme_queue *nvmeq)
1277 {
1278         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1279                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1280         if (nvmeq->sq_cmds)
1281                 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1282                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1283         kfree(nvmeq);
1284 }
1285
1286 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1287 {
1288         int i;
1289
1290         for (i = dev->queue_count - 1; i >= lowest; i--) {
1291                 struct nvme_queue *nvmeq = dev->queues[i];
1292                 dev->queue_count--;
1293                 dev->queues[i] = NULL;
1294                 nvme_free_queue(nvmeq);
1295         }
1296 }
1297
1298 /**
1299  * nvme_suspend_queue - put queue into suspended state
1300  * @nvmeq - queue to suspend
1301  */
1302 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1303 {
1304         int vector;
1305
1306         spin_lock_irq(&nvmeq->q_lock);
1307         if (nvmeq->cq_vector == -1) {
1308                 spin_unlock_irq(&nvmeq->q_lock);
1309                 return 1;
1310         }
1311         vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1312         nvmeq->dev->online_queues--;
1313         nvmeq->cq_vector = -1;
1314         spin_unlock_irq(&nvmeq->q_lock);
1315
1316         if (!nvmeq->qid && nvmeq->dev->ctrl.admin_q)
1317                 blk_mq_freeze_queue_start(nvmeq->dev->ctrl.admin_q);
1318
1319         irq_set_affinity_hint(vector, NULL);
1320         free_irq(vector, nvmeq);
1321
1322         return 0;
1323 }
1324
1325 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1326 {
1327         spin_lock_irq(&nvmeq->q_lock);
1328         if (nvmeq->tags && *nvmeq->tags)
1329                 blk_mq_all_tag_busy_iter(*nvmeq->tags, nvme_cancel_queue_ios, nvmeq);
1330         spin_unlock_irq(&nvmeq->q_lock);
1331 }
1332
1333 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1334 {
1335         struct nvme_queue *nvmeq = dev->queues[qid];
1336
1337         if (!nvmeq)
1338                 return;
1339         if (nvme_suspend_queue(nvmeq))
1340                 return;
1341
1342         /* Don't tell the adapter to delete the admin queue.
1343          * Don't tell a removed adapter to delete IO queues. */
1344         if (qid && readl(dev->bar + NVME_REG_CSTS) != -1) {
1345                 adapter_delete_sq(dev, qid);
1346                 adapter_delete_cq(dev, qid);
1347         }
1348
1349         spin_lock_irq(&nvmeq->q_lock);
1350         nvme_process_cq(nvmeq);
1351         spin_unlock_irq(&nvmeq->q_lock);
1352 }
1353
1354 static int nvme_cmb_qdepth(struct nvme_dev *dev, int nr_io_queues,
1355                                 int entry_size)
1356 {
1357         int q_depth = dev->q_depth;
1358         unsigned q_size_aligned = roundup(q_depth * entry_size, dev->page_size);
1359
1360         if (q_size_aligned * nr_io_queues > dev->cmb_size) {
1361                 u64 mem_per_q = div_u64(dev->cmb_size, nr_io_queues);
1362                 mem_per_q = round_down(mem_per_q, dev->page_size);
1363                 q_depth = div_u64(mem_per_q, entry_size);
1364
1365                 /*
1366                  * Ensure the reduced q_depth is above some threshold where it
1367                  * would be better to map queues in system memory with the
1368                  * original depth
1369                  */
1370                 if (q_depth < 64)
1371                         return -ENOMEM;
1372         }
1373
1374         return q_depth;
1375 }
1376
1377 static int nvme_alloc_sq_cmds(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1378                                 int qid, int depth)
1379 {
1380         if (qid && dev->cmb && use_cmb_sqes && NVME_CMB_SQS(dev->cmbsz)) {
1381                 unsigned offset = (qid - 1) *
1382                                         roundup(SQ_SIZE(depth), dev->page_size);
1383                 nvmeq->sq_dma_addr = dev->cmb_dma_addr + offset;
1384                 nvmeq->sq_cmds_io = dev->cmb + offset;
1385         } else {
1386                 nvmeq->sq_cmds = dma_alloc_coherent(dev->dev, SQ_SIZE(depth),
1387                                         &nvmeq->sq_dma_addr, GFP_KERNEL);
1388                 if (!nvmeq->sq_cmds)
1389                         return -ENOMEM;
1390         }
1391
1392         return 0;
1393 }
1394
1395 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1396                                                         int depth)
1397 {
1398         struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq), GFP_KERNEL);
1399         if (!nvmeq)
1400                 return NULL;
1401
1402         nvmeq->cqes = dma_zalloc_coherent(dev->dev, CQ_SIZE(depth),
1403                                           &nvmeq->cq_dma_addr, GFP_KERNEL);
1404         if (!nvmeq->cqes)
1405                 goto free_nvmeq;
1406
1407         if (nvme_alloc_sq_cmds(dev, nvmeq, qid, depth))
1408                 goto free_cqdma;
1409
1410         nvmeq->q_dmadev = dev->dev;
1411         nvmeq->dev = dev;
1412         snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1413                         dev->ctrl.instance, qid);
1414         spin_lock_init(&nvmeq->q_lock);
1415         nvmeq->cq_head = 0;
1416         nvmeq->cq_phase = 1;
1417         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1418         nvmeq->q_depth = depth;
1419         nvmeq->qid = qid;
1420         nvmeq->cq_vector = -1;
1421         dev->queues[qid] = nvmeq;
1422
1423         /* make sure queue descriptor is set before queue count, for kthread */
1424         mb();
1425         dev->queue_count++;
1426
1427         return nvmeq;
1428
1429  free_cqdma:
1430         dma_free_coherent(dev->dev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1431                                                         nvmeq->cq_dma_addr);
1432  free_nvmeq:
1433         kfree(nvmeq);
1434         return NULL;
1435 }
1436
1437 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1438                                                         const char *name)
1439 {
1440         if (use_threaded_interrupts)
1441                 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1442                                         nvme_irq_check, nvme_irq, IRQF_SHARED,
1443                                         name, nvmeq);
1444         return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1445                                 IRQF_SHARED, name, nvmeq);
1446 }
1447
1448 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1449 {
1450         struct nvme_dev *dev = nvmeq->dev;
1451
1452         spin_lock_irq(&nvmeq->q_lock);
1453         nvmeq->sq_tail = 0;
1454         nvmeq->cq_head = 0;
1455         nvmeq->cq_phase = 1;
1456         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1457         memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1458         dev->online_queues++;
1459         spin_unlock_irq(&nvmeq->q_lock);
1460 }
1461
1462 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1463 {
1464         struct nvme_dev *dev = nvmeq->dev;
1465         int result;
1466
1467         nvmeq->cq_vector = qid - 1;
1468         result = adapter_alloc_cq(dev, qid, nvmeq);
1469         if (result < 0)
1470                 return result;
1471
1472         result = adapter_alloc_sq(dev, qid, nvmeq);
1473         if (result < 0)
1474                 goto release_cq;
1475
1476         result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1477         if (result < 0)
1478                 goto release_sq;
1479
1480         nvme_init_queue(nvmeq, qid);
1481         return result;
1482
1483  release_sq:
1484         adapter_delete_sq(dev, qid);
1485  release_cq:
1486         adapter_delete_cq(dev, qid);
1487         return result;
1488 }
1489
1490 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1491 {
1492         unsigned long timeout;
1493         u32 bit = enabled ? NVME_CSTS_RDY : 0;
1494
1495         timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1496
1497         while ((readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_RDY) != bit) {
1498                 msleep(100);
1499                 if (fatal_signal_pending(current))
1500                         return -EINTR;
1501                 if (time_after(jiffies, timeout)) {
1502                         dev_err(dev->dev,
1503                                 "Device not ready; aborting %s\n", enabled ?
1504                                                 "initialisation" : "reset");
1505                         return -ENODEV;
1506                 }
1507         }
1508
1509         return 0;
1510 }
1511
1512 /*
1513  * If the device has been passed off to us in an enabled state, just clear
1514  * the enabled bit.  The spec says we should set the 'shutdown notification
1515  * bits', but doing so may cause the device to complete commands to the
1516  * admin queue ... and we don't know what memory that might be pointing at!
1517  */
1518 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1519 {
1520         dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1521         dev->ctrl_config &= ~NVME_CC_ENABLE;
1522         writel(dev->ctrl_config, dev->bar + NVME_REG_CC);
1523
1524         return nvme_wait_ready(dev, cap, false);
1525 }
1526
1527 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1528 {
1529         dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1530         dev->ctrl_config |= NVME_CC_ENABLE;
1531         writel(dev->ctrl_config, dev->bar + NVME_REG_CC);
1532
1533         return nvme_wait_ready(dev, cap, true);
1534 }
1535
1536 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1537 {
1538         unsigned long timeout;
1539
1540         dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1541         dev->ctrl_config |= NVME_CC_SHN_NORMAL;
1542
1543         writel(dev->ctrl_config, dev->bar + NVME_REG_CC);
1544
1545         timeout = SHUTDOWN_TIMEOUT + jiffies;
1546         while ((readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_SHST_MASK) !=
1547                                                         NVME_CSTS_SHST_CMPLT) {
1548                 msleep(100);
1549                 if (fatal_signal_pending(current))
1550                         return -EINTR;
1551                 if (time_after(jiffies, timeout)) {
1552                         dev_err(dev->dev,
1553                                 "Device shutdown incomplete; abort shutdown\n");
1554                         return -ENODEV;
1555                 }
1556         }
1557
1558         return 0;
1559 }
1560
1561 static struct blk_mq_ops nvme_mq_admin_ops = {
1562         .queue_rq       = nvme_queue_rq,
1563         .map_queue      = blk_mq_map_queue,
1564         .init_hctx      = nvme_admin_init_hctx,
1565         .exit_hctx      = nvme_admin_exit_hctx,
1566         .init_request   = nvme_admin_init_request,
1567         .timeout        = nvme_timeout,
1568 };
1569
1570 static struct blk_mq_ops nvme_mq_ops = {
1571         .queue_rq       = nvme_queue_rq,
1572         .map_queue      = blk_mq_map_queue,
1573         .init_hctx      = nvme_init_hctx,
1574         .init_request   = nvme_init_request,
1575         .timeout        = nvme_timeout,
1576         .poll           = nvme_poll,
1577 };
1578
1579 static void nvme_dev_remove_admin(struct nvme_dev *dev)
1580 {
1581         if (dev->ctrl.admin_q && !blk_queue_dying(dev->ctrl.admin_q)) {
1582                 blk_cleanup_queue(dev->ctrl.admin_q);
1583                 blk_mq_free_tag_set(&dev->admin_tagset);
1584         }
1585 }
1586
1587 static int nvme_alloc_admin_tags(struct nvme_dev *dev)
1588 {
1589         if (!dev->ctrl.admin_q) {
1590                 dev->admin_tagset.ops = &nvme_mq_admin_ops;
1591                 dev->admin_tagset.nr_hw_queues = 1;
1592                 dev->admin_tagset.queue_depth = NVME_AQ_DEPTH - 1;
1593                 dev->admin_tagset.reserved_tags = 1;
1594                 dev->admin_tagset.timeout = ADMIN_TIMEOUT;
1595                 dev->admin_tagset.numa_node = dev_to_node(dev->dev);
1596                 dev->admin_tagset.cmd_size = nvme_cmd_size(dev);
1597                 dev->admin_tagset.driver_data = dev;
1598
1599                 if (blk_mq_alloc_tag_set(&dev->admin_tagset))
1600                         return -ENOMEM;
1601
1602                 dev->ctrl.admin_q = blk_mq_init_queue(&dev->admin_tagset);
1603                 if (IS_ERR(dev->ctrl.admin_q)) {
1604                         blk_mq_free_tag_set(&dev->admin_tagset);
1605                         return -ENOMEM;
1606                 }
1607                 if (!blk_get_queue(dev->ctrl.admin_q)) {
1608                         nvme_dev_remove_admin(dev);
1609                         dev->ctrl.admin_q = NULL;
1610                         return -ENODEV;
1611                 }
1612         } else
1613                 blk_mq_unfreeze_queue(dev->ctrl.admin_q);
1614
1615         return 0;
1616 }
1617
1618 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1619 {
1620         int result;
1621         u32 aqa;
1622         u64 cap = lo_hi_readq(dev->bar + NVME_REG_CAP);
1623         struct nvme_queue *nvmeq;
1624         /*
1625          * default to a 4K page size, with the intention to update this
1626          * path in the future to accomodate architectures with differing
1627          * kernel and IO page sizes.
1628          */
1629         unsigned page_shift = 12;
1630         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12;
1631
1632         if (page_shift < dev_page_min) {
1633                 dev_err(dev->dev,
1634                                 "Minimum device page size (%u) too large for "
1635                                 "host (%u)\n", 1 << dev_page_min,
1636                                 1 << page_shift);
1637                 return -ENODEV;
1638         }
1639
1640         dev->subsystem = readl(dev->bar + NVME_REG_VS) >= NVME_VS(1, 1) ?
1641                                                 NVME_CAP_NSSRC(cap) : 0;
1642
1643         if (dev->subsystem &&
1644             (readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_NSSRO))
1645                 writel(NVME_CSTS_NSSRO, dev->bar + NVME_REG_CSTS);
1646
1647         result = nvme_disable_ctrl(dev, cap);
1648         if (result < 0)
1649                 return result;
1650
1651         nvmeq = dev->queues[0];
1652         if (!nvmeq) {
1653                 nvmeq = nvme_alloc_queue(dev, 0, NVME_AQ_DEPTH);
1654                 if (!nvmeq)
1655                         return -ENOMEM;
1656         }
1657
1658         aqa = nvmeq->q_depth - 1;
1659         aqa |= aqa << 16;
1660
1661         dev->page_size = 1 << page_shift;
1662
1663         dev->ctrl_config = NVME_CC_CSS_NVM;
1664         dev->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1665         dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1666         dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1667
1668         writel(aqa, dev->bar + NVME_REG_AQA);
1669         lo_hi_writeq(nvmeq->sq_dma_addr, dev->bar + NVME_REG_ASQ);
1670         lo_hi_writeq(nvmeq->cq_dma_addr, dev->bar + NVME_REG_ACQ);
1671
1672         result = nvme_enable_ctrl(dev, cap);
1673         if (result)
1674                 goto free_nvmeq;
1675
1676         nvmeq->cq_vector = 0;
1677         result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1678         if (result) {
1679                 nvmeq->cq_vector = -1;
1680                 goto free_nvmeq;
1681         }
1682
1683         return result;
1684
1685  free_nvmeq:
1686         nvme_free_queues(dev, 0);
1687         return result;
1688 }
1689
1690 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1691 {
1692         struct nvme_dev *dev = to_nvme_dev(ns->ctrl);
1693         struct nvme_user_io io;
1694         struct nvme_command c;
1695         unsigned length, meta_len;
1696         int status, write;
1697         dma_addr_t meta_dma = 0;
1698         void *meta = NULL;
1699         void __user *metadata;
1700
1701         if (copy_from_user(&io, uio, sizeof(io)))
1702                 return -EFAULT;
1703
1704         switch (io.opcode) {
1705         case nvme_cmd_write:
1706         case nvme_cmd_read:
1707         case nvme_cmd_compare:
1708                 break;
1709         default:
1710                 return -EINVAL;
1711         }
1712
1713         length = (io.nblocks + 1) << ns->lba_shift;
1714         meta_len = (io.nblocks + 1) * ns->ms;
1715         metadata = (void __user *)(uintptr_t)io.metadata;
1716         write = io.opcode & 1;
1717
1718         if (ns->ext) {
1719                 length += meta_len;
1720                 meta_len = 0;
1721         }
1722         if (meta_len) {
1723                 if (((io.metadata & 3) || !io.metadata) && !ns->ext)
1724                         return -EINVAL;
1725
1726                 meta = dma_alloc_coherent(dev->dev, meta_len,
1727                                                 &meta_dma, GFP_KERNEL);
1728
1729                 if (!meta) {
1730                         status = -ENOMEM;
1731                         goto unmap;
1732                 }
1733                 if (write) {
1734                         if (copy_from_user(meta, metadata, meta_len)) {
1735                                 status = -EFAULT;
1736                                 goto unmap;
1737                         }
1738                 }
1739         }
1740
1741         memset(&c, 0, sizeof(c));
1742         c.rw.opcode = io.opcode;
1743         c.rw.flags = io.flags;
1744         c.rw.nsid = cpu_to_le32(ns->ns_id);
1745         c.rw.slba = cpu_to_le64(io.slba);
1746         c.rw.length = cpu_to_le16(io.nblocks);
1747         c.rw.control = cpu_to_le16(io.control);
1748         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1749         c.rw.reftag = cpu_to_le32(io.reftag);
1750         c.rw.apptag = cpu_to_le16(io.apptag);
1751         c.rw.appmask = cpu_to_le16(io.appmask);
1752         c.rw.metadata = cpu_to_le64(meta_dma);
1753
1754         status = __nvme_submit_sync_cmd(ns->queue, &c, NULL,
1755                         (void __user *)(uintptr_t)io.addr, length, NULL, 0);
1756  unmap:
1757         if (meta) {
1758                 if (status == NVME_SC_SUCCESS && !write) {
1759                         if (copy_to_user(metadata, meta, meta_len))
1760                                 status = -EFAULT;
1761                 }
1762                 dma_free_coherent(dev->dev, meta_len, meta, meta_dma);
1763         }
1764         return status;
1765 }
1766
1767 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1768                         struct nvme_passthru_cmd __user *ucmd)
1769 {
1770         struct nvme_passthru_cmd cmd;
1771         struct nvme_command c;
1772         unsigned timeout = 0;
1773         int status;
1774
1775         if (!capable(CAP_SYS_ADMIN))
1776                 return -EACCES;
1777         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1778                 return -EFAULT;
1779
1780         memset(&c, 0, sizeof(c));
1781         c.common.opcode = cmd.opcode;
1782         c.common.flags = cmd.flags;
1783         c.common.nsid = cpu_to_le32(cmd.nsid);
1784         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1785         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1786         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1787         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1788         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1789         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1790         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1791         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1792
1793         if (cmd.timeout_ms)
1794                 timeout = msecs_to_jiffies(cmd.timeout_ms);
1795
1796         status = __nvme_submit_sync_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1797                         NULL, (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1798                         &cmd.result, timeout);
1799         if (status >= 0) {
1800                 if (put_user(cmd.result, &ucmd->result))
1801                         return -EFAULT;
1802         }
1803
1804         return status;
1805 }
1806
1807 static int nvme_subsys_reset(struct nvme_dev *dev)
1808 {
1809         if (!dev->subsystem)
1810                 return -ENOTTY;
1811
1812         writel(0x4E564D65, dev->bar + NVME_REG_NSSR); /* "NVMe" */
1813         return 0;
1814 }
1815
1816 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1817                                                         unsigned long arg)
1818 {
1819         struct nvme_ns *ns = bdev->bd_disk->private_data;
1820
1821         switch (cmd) {
1822         case NVME_IOCTL_ID:
1823                 force_successful_syscall_return();
1824                 return ns->ns_id;
1825         case NVME_IOCTL_ADMIN_CMD:
1826                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1827         case NVME_IOCTL_IO_CMD:
1828                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1829         case NVME_IOCTL_SUBMIT_IO:
1830                 return nvme_submit_io(ns, (void __user *)arg);
1831         case SG_GET_VERSION_NUM:
1832                 return nvme_sg_get_version_num((void __user *)arg);
1833         case SG_IO:
1834                 return nvme_sg_io(ns, (void __user *)arg);
1835         default:
1836                 return -ENOTTY;
1837         }
1838 }
1839
1840 #ifdef CONFIG_COMPAT
1841 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1842                                         unsigned int cmd, unsigned long arg)
1843 {
1844         switch (cmd) {
1845         case SG_IO:
1846                 return -ENOIOCTLCMD;
1847         }
1848         return nvme_ioctl(bdev, mode, cmd, arg);
1849 }
1850 #else
1851 #define nvme_compat_ioctl       NULL
1852 #endif
1853
1854 static void nvme_free_dev(struct kref *kref);
1855 static void nvme_free_ns(struct kref *kref)
1856 {
1857         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
1858         struct nvme_dev *dev = to_nvme_dev(ns->ctrl);
1859
1860         if (ns->type == NVME_NS_LIGHTNVM)
1861                 nvme_nvm_unregister(ns->queue, ns->disk->disk_name);
1862
1863         spin_lock(&dev_list_lock);
1864         ns->disk->private_data = NULL;
1865         spin_unlock(&dev_list_lock);
1866
1867         kref_put(&dev->kref, nvme_free_dev);
1868         put_disk(ns->disk);
1869         kfree(ns);
1870 }
1871
1872 static int nvme_open(struct block_device *bdev, fmode_t mode)
1873 {
1874         int ret = 0;
1875         struct nvme_ns *ns;
1876
1877         spin_lock(&dev_list_lock);
1878         ns = bdev->bd_disk->private_data;
1879         if (!ns)
1880                 ret = -ENXIO;
1881         else if (!kref_get_unless_zero(&ns->kref))
1882                 ret = -ENXIO;
1883         spin_unlock(&dev_list_lock);
1884
1885         return ret;
1886 }
1887
1888 static void nvme_release(struct gendisk *disk, fmode_t mode)
1889 {
1890         struct nvme_ns *ns = disk->private_data;
1891         kref_put(&ns->kref, nvme_free_ns);
1892 }
1893
1894 static int nvme_getgeo(struct block_device *bd, struct hd_geometry *geo)
1895 {
1896         /* some standard values */
1897         geo->heads = 1 << 6;
1898         geo->sectors = 1 << 5;
1899         geo->cylinders = get_capacity(bd->bd_disk) >> 11;
1900         return 0;
1901 }
1902
1903 static void nvme_config_discard(struct nvme_ns *ns)
1904 {
1905         u32 logical_block_size = queue_logical_block_size(ns->queue);
1906         ns->queue->limits.discard_zeroes_data = 0;
1907         ns->queue->limits.discard_alignment = logical_block_size;
1908         ns->queue->limits.discard_granularity = logical_block_size;
1909         blk_queue_max_discard_sectors(ns->queue, 0xffffffff);
1910         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1911 }
1912
1913 static int nvme_revalidate_disk(struct gendisk *disk)
1914 {
1915         struct nvme_ns *ns = disk->private_data;
1916         struct nvme_dev *dev = to_nvme_dev(ns->ctrl);
1917         struct nvme_id_ns *id;
1918         u8 lbaf, pi_type;
1919         u16 old_ms;
1920         unsigned short bs;
1921
1922         if (nvme_identify_ns(&dev->ctrl, ns->ns_id, &id)) {
1923                 dev_warn(dev->dev, "%s: Identify failure nvme%dn%d\n", __func__,
1924                                                 dev->ctrl.instance, ns->ns_id);
1925                 return -ENODEV;
1926         }
1927         if (id->ncap == 0) {
1928                 kfree(id);
1929                 return -ENODEV;
1930         }
1931
1932         if (nvme_nvm_ns_supported(ns, id) && ns->type != NVME_NS_LIGHTNVM) {
1933                 if (nvme_nvm_register(ns->queue, disk->disk_name)) {
1934                         dev_warn(dev->dev,
1935                                 "%s: LightNVM init failure\n", __func__);
1936                         kfree(id);
1937                         return -ENODEV;
1938                 }
1939                 ns->type = NVME_NS_LIGHTNVM;
1940         }
1941
1942         old_ms = ns->ms;
1943         lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
1944         ns->lba_shift = id->lbaf[lbaf].ds;
1945         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1946         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1947
1948         /*
1949          * If identify namespace failed, use default 512 byte block size so
1950          * block layer can use before failing read/write for 0 capacity.
1951          */
1952         if (ns->lba_shift == 0)
1953                 ns->lba_shift = 9;
1954         bs = 1 << ns->lba_shift;
1955
1956         /* XXX: PI implementation requires metadata equal t10 pi tuple size */
1957         pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
1958                                         id->dps & NVME_NS_DPS_PI_MASK : 0;
1959
1960         blk_mq_freeze_queue(disk->queue);
1961         if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
1962                                 ns->ms != old_ms ||
1963                                 bs != queue_logical_block_size(disk->queue) ||
1964                                 (ns->ms && ns->ext)))
1965                 blk_integrity_unregister(disk);
1966
1967         ns->pi_type = pi_type;
1968         blk_queue_logical_block_size(ns->queue, bs);
1969
1970         if (ns->ms && !ns->ext)
1971                 nvme_init_integrity(ns);
1972
1973         if ((ns->ms && !(ns->ms == 8 && ns->pi_type) &&
1974                                                 !blk_get_integrity(disk)) ||
1975                                                 ns->type == NVME_NS_LIGHTNVM)
1976                 set_capacity(disk, 0);
1977         else
1978                 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1979
1980         if (dev->ctrl.oncs & NVME_CTRL_ONCS_DSM)
1981                 nvme_config_discard(ns);
1982         blk_mq_unfreeze_queue(disk->queue);
1983
1984         kfree(id);
1985         return 0;
1986 }
1987
1988 static char nvme_pr_type(enum pr_type type)
1989 {
1990         switch (type) {
1991         case PR_WRITE_EXCLUSIVE:
1992                 return 1;
1993         case PR_EXCLUSIVE_ACCESS:
1994                 return 2;
1995         case PR_WRITE_EXCLUSIVE_REG_ONLY:
1996                 return 3;
1997         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1998                 return 4;
1999         case PR_WRITE_EXCLUSIVE_ALL_REGS:
2000                 return 5;
2001         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
2002                 return 6;
2003         default:
2004                 return 0;
2005         }
2006 };
2007
2008 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
2009                                 u64 key, u64 sa_key, u8 op)
2010 {
2011         struct nvme_ns *ns = bdev->bd_disk->private_data;
2012         struct nvme_command c;
2013         u8 data[16] = { 0, };
2014
2015         put_unaligned_le64(key, &data[0]);
2016         put_unaligned_le64(sa_key, &data[8]);
2017
2018         memset(&c, 0, sizeof(c));
2019         c.common.opcode = op;
2020         c.common.nsid = cpu_to_le32(ns->ns_id);
2021         c.common.cdw10[0] = cpu_to_le32(cdw10);
2022
2023         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
2024 }
2025
2026 static int nvme_pr_register(struct block_device *bdev, u64 old,
2027                 u64 new, unsigned flags)
2028 {
2029         u32 cdw10;
2030
2031         if (flags & ~PR_FL_IGNORE_KEY)
2032                 return -EOPNOTSUPP;
2033
2034         cdw10 = old ? 2 : 0;
2035         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2036         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2037         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2038 }
2039
2040 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2041                 enum pr_type type, unsigned flags)
2042 {
2043         u32 cdw10;
2044
2045         if (flags & ~PR_FL_IGNORE_KEY)
2046                 return -EOPNOTSUPP;
2047
2048         cdw10 = nvme_pr_type(type) << 8;
2049         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2050         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2051 }
2052
2053 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2054                 enum pr_type type, bool abort)
2055 {
2056         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
2057         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2058 }
2059
2060 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2061 {
2062         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2063         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2064 }
2065
2066 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2067 {
2068         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
2069         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2070 }
2071
2072 static const struct pr_ops nvme_pr_ops = {
2073         .pr_register    = nvme_pr_register,
2074         .pr_reserve     = nvme_pr_reserve,
2075         .pr_release     = nvme_pr_release,
2076         .pr_preempt     = nvme_pr_preempt,
2077         .pr_clear       = nvme_pr_clear,
2078 };
2079
2080 static const struct block_device_operations nvme_fops = {
2081         .owner          = THIS_MODULE,
2082         .ioctl          = nvme_ioctl,
2083         .compat_ioctl   = nvme_compat_ioctl,
2084         .open           = nvme_open,
2085         .release        = nvme_release,
2086         .getgeo         = nvme_getgeo,
2087         .revalidate_disk= nvme_revalidate_disk,
2088         .pr_ops         = &nvme_pr_ops,
2089 };
2090
2091 static int nvme_kthread(void *data)
2092 {
2093         struct nvme_dev *dev, *next;
2094
2095         while (!kthread_should_stop()) {
2096                 set_current_state(TASK_INTERRUPTIBLE);
2097                 spin_lock(&dev_list_lock);
2098                 list_for_each_entry_safe(dev, next, &dev_list, node) {
2099                         int i;
2100                         u32 csts = readl(dev->bar + NVME_REG_CSTS);
2101
2102                         if ((dev->subsystem && (csts & NVME_CSTS_NSSRO)) ||
2103                                                         csts & NVME_CSTS_CFS) {
2104                                 if (!__nvme_reset(dev)) {
2105                                         dev_warn(dev->dev,
2106                                                 "Failed status: %x, reset controller\n",
2107                                                 readl(dev->bar + NVME_REG_CSTS));
2108                                 }
2109                                 continue;
2110                         }
2111                         for (i = 0; i < dev->queue_count; i++) {
2112                                 struct nvme_queue *nvmeq = dev->queues[i];
2113                                 if (!nvmeq)
2114                                         continue;
2115                                 spin_lock_irq(&nvmeq->q_lock);
2116                                 nvme_process_cq(nvmeq);
2117
2118                                 while (i == 0 && dev->ctrl.event_limit > 0) {
2119                                         if (nvme_submit_async_admin_req(dev))
2120                                                 break;
2121                                         dev->ctrl.event_limit--;
2122                                 }
2123                                 spin_unlock_irq(&nvmeq->q_lock);
2124                         }
2125                 }
2126                 spin_unlock(&dev_list_lock);
2127                 schedule_timeout(round_jiffies_relative(HZ));
2128         }
2129         return 0;
2130 }
2131
2132 static void nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid)
2133 {
2134         struct nvme_ns *ns;
2135         struct gendisk *disk;
2136         int node = dev_to_node(dev->dev);
2137
2138         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2139         if (!ns)
2140                 return;
2141
2142         ns->queue = blk_mq_init_queue(&dev->tagset);
2143         if (IS_ERR(ns->queue))
2144                 goto out_free_ns;
2145         queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
2146         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2147         ns->ctrl = &dev->ctrl;
2148         ns->queue->queuedata = ns;
2149
2150         disk = alloc_disk_node(0, node);
2151         if (!disk)
2152                 goto out_free_queue;
2153
2154         kref_init(&ns->kref);
2155         ns->ns_id = nsid;
2156         ns->disk = disk;
2157         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2158         list_add_tail(&ns->list, &dev->namespaces);
2159
2160         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2161         if (dev->max_hw_sectors) {
2162                 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
2163                 blk_queue_max_segments(ns->queue,
2164                         (dev->max_hw_sectors / (dev->page_size >> 9)) + 1);
2165         }
2166         if (dev->stripe_size)
2167                 blk_queue_chunk_sectors(ns->queue, dev->stripe_size >> 9);
2168         if (dev->ctrl.vwc & NVME_CTRL_VWC_PRESENT)
2169                 blk_queue_flush(ns->queue, REQ_FLUSH | REQ_FUA);
2170         blk_queue_virt_boundary(ns->queue, dev->page_size - 1);
2171
2172         disk->major = nvme_major;
2173         disk->first_minor = 0;
2174         disk->fops = &nvme_fops;
2175         disk->private_data = ns;
2176         disk->queue = ns->queue;
2177         disk->driverfs_dev = dev->device;
2178         disk->flags = GENHD_FL_EXT_DEVT;
2179         sprintf(disk->disk_name, "nvme%dn%d", dev->ctrl.instance, nsid);
2180
2181         /*
2182          * Initialize capacity to 0 until we establish the namespace format and
2183          * setup integrity extentions if necessary. The revalidate_disk after
2184          * add_disk allows the driver to register with integrity if the format
2185          * requires it.
2186          */
2187         set_capacity(disk, 0);
2188         if (nvme_revalidate_disk(ns->disk))
2189                 goto out_free_disk;
2190
2191         kref_get(&dev->kref);
2192         if (ns->type != NVME_NS_LIGHTNVM) {
2193                 add_disk(ns->disk);
2194                 if (ns->ms) {
2195                         struct block_device *bd = bdget_disk(ns->disk, 0);
2196                         if (!bd)
2197                                 return;
2198                         if (blkdev_get(bd, FMODE_READ, NULL)) {
2199                                 bdput(bd);
2200                                 return;
2201                         }
2202                         blkdev_reread_part(bd);
2203                         blkdev_put(bd, FMODE_READ);
2204                 }
2205         }
2206         return;
2207  out_free_disk:
2208         kfree(disk);
2209         list_del(&ns->list);
2210  out_free_queue:
2211         blk_cleanup_queue(ns->queue);
2212  out_free_ns:
2213         kfree(ns);
2214 }
2215
2216 /*
2217  * Create I/O queues.  Failing to create an I/O queue is not an issue,
2218  * we can continue with less than the desired amount of queues, and
2219  * even a controller without I/O queues an still be used to issue
2220  * admin commands.  This might be useful to upgrade a buggy firmware
2221  * for example.
2222  */
2223 static void nvme_create_io_queues(struct nvme_dev *dev)
2224 {
2225         unsigned i;
2226
2227         for (i = dev->queue_count; i <= dev->max_qid; i++)
2228                 if (!nvme_alloc_queue(dev, i, dev->q_depth))
2229                         break;
2230
2231         for (i = dev->online_queues; i <= dev->queue_count - 1; i++)
2232                 if (nvme_create_queue(dev->queues[i], i)) {
2233                         nvme_free_queues(dev, i);
2234                         break;
2235                 }
2236 }
2237
2238 static int set_queue_count(struct nvme_dev *dev, int count)
2239 {
2240         int status;
2241         u32 result;
2242         u32 q_count = (count - 1) | ((count - 1) << 16);
2243
2244         status = nvme_set_features(&dev->ctrl, NVME_FEAT_NUM_QUEUES, q_count, 0,
2245                                                                 &result);
2246         if (status < 0)
2247                 return status;
2248         if (status > 0) {
2249                 dev_err(dev->dev, "Could not set queue count (%d)\n", status);
2250                 return 0;
2251         }
2252         return min(result & 0xffff, result >> 16) + 1;
2253 }
2254
2255 static void __iomem *nvme_map_cmb(struct nvme_dev *dev)
2256 {
2257         u64 szu, size, offset;
2258         u32 cmbloc;
2259         resource_size_t bar_size;
2260         struct pci_dev *pdev = to_pci_dev(dev->dev);
2261         void __iomem *cmb;
2262         dma_addr_t dma_addr;
2263
2264         if (!use_cmb_sqes)
2265                 return NULL;
2266
2267         dev->cmbsz = readl(dev->bar + NVME_REG_CMBSZ);
2268         if (!(NVME_CMB_SZ(dev->cmbsz)))
2269                 return NULL;
2270
2271         cmbloc = readl(dev->bar + NVME_REG_CMBLOC);
2272
2273         szu = (u64)1 << (12 + 4 * NVME_CMB_SZU(dev->cmbsz));
2274         size = szu * NVME_CMB_SZ(dev->cmbsz);
2275         offset = szu * NVME_CMB_OFST(cmbloc);
2276         bar_size = pci_resource_len(pdev, NVME_CMB_BIR(cmbloc));
2277
2278         if (offset > bar_size)
2279                 return NULL;
2280
2281         /*
2282          * Controllers may support a CMB size larger than their BAR,
2283          * for example, due to being behind a bridge. Reduce the CMB to
2284          * the reported size of the BAR
2285          */
2286         if (size > bar_size - offset)
2287                 size = bar_size - offset;
2288
2289         dma_addr = pci_resource_start(pdev, NVME_CMB_BIR(cmbloc)) + offset;
2290         cmb = ioremap_wc(dma_addr, size);
2291         if (!cmb)
2292                 return NULL;
2293
2294         dev->cmb_dma_addr = dma_addr;
2295         dev->cmb_size = size;
2296         return cmb;
2297 }
2298
2299 static inline void nvme_release_cmb(struct nvme_dev *dev)
2300 {
2301         if (dev->cmb) {
2302                 iounmap(dev->cmb);
2303                 dev->cmb = NULL;
2304         }
2305 }
2306
2307 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2308 {
2309         return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
2310 }
2311
2312 static int nvme_setup_io_queues(struct nvme_dev *dev)
2313 {
2314         struct nvme_queue *adminq = dev->queues[0];
2315         struct pci_dev *pdev = to_pci_dev(dev->dev);
2316         int result, i, vecs, nr_io_queues, size;
2317
2318         nr_io_queues = num_possible_cpus();
2319         result = set_queue_count(dev, nr_io_queues);
2320         if (result <= 0)
2321                 return result;
2322         if (result < nr_io_queues)
2323                 nr_io_queues = result;
2324
2325         if (dev->cmb && NVME_CMB_SQS(dev->cmbsz)) {
2326                 result = nvme_cmb_qdepth(dev, nr_io_queues,
2327                                 sizeof(struct nvme_command));
2328                 if (result > 0)
2329                         dev->q_depth = result;
2330                 else
2331                         nvme_release_cmb(dev);
2332         }
2333
2334         size = db_bar_size(dev, nr_io_queues);
2335         if (size > 8192) {
2336                 iounmap(dev->bar);
2337                 do {
2338                         dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2339                         if (dev->bar)
2340                                 break;
2341                         if (!--nr_io_queues)
2342                                 return -ENOMEM;
2343                         size = db_bar_size(dev, nr_io_queues);
2344                 } while (1);
2345                 dev->dbs = dev->bar + 4096;
2346                 adminq->q_db = dev->dbs;
2347         }
2348
2349         /* Deregister the admin queue's interrupt */
2350         free_irq(dev->entry[0].vector, adminq);
2351
2352         /*
2353          * If we enable msix early due to not intx, disable it again before
2354          * setting up the full range we need.
2355          */
2356         if (!pdev->irq)
2357                 pci_disable_msix(pdev);
2358
2359         for (i = 0; i < nr_io_queues; i++)
2360                 dev->entry[i].entry = i;
2361         vecs = pci_enable_msix_range(pdev, dev->entry, 1, nr_io_queues);
2362         if (vecs < 0) {
2363                 vecs = pci_enable_msi_range(pdev, 1, min(nr_io_queues, 32));
2364                 if (vecs < 0) {
2365                         vecs = 1;
2366                 } else {
2367                         for (i = 0; i < vecs; i++)
2368                                 dev->entry[i].vector = i + pdev->irq;
2369                 }
2370         }
2371
2372         /*
2373          * Should investigate if there's a performance win from allocating
2374          * more queues than interrupt vectors; it might allow the submission
2375          * path to scale better, even if the receive path is limited by the
2376          * number of interrupts.
2377          */
2378         nr_io_queues = vecs;
2379         dev->max_qid = nr_io_queues;
2380
2381         result = queue_request_irq(dev, adminq, adminq->irqname);
2382         if (result) {
2383                 adminq->cq_vector = -1;
2384                 goto free_queues;
2385         }
2386
2387         /* Free previously allocated queues that are no longer usable */
2388         nvme_free_queues(dev, nr_io_queues + 1);
2389         nvme_create_io_queues(dev);
2390
2391         return 0;
2392
2393  free_queues:
2394         nvme_free_queues(dev, 1);
2395         return result;
2396 }
2397
2398 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2399 {
2400         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2401         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2402
2403         return nsa->ns_id - nsb->ns_id;
2404 }
2405
2406 static struct nvme_ns *nvme_find_ns(struct nvme_dev *dev, unsigned nsid)
2407 {
2408         struct nvme_ns *ns;
2409
2410         list_for_each_entry(ns, &dev->namespaces, list) {
2411                 if (ns->ns_id == nsid)
2412                         return ns;
2413                 if (ns->ns_id > nsid)
2414                         break;
2415         }
2416         return NULL;
2417 }
2418
2419 static inline bool nvme_io_incapable(struct nvme_dev *dev)
2420 {
2421         return (!dev->bar ||
2422                 readl(dev->bar + NVME_REG_CSTS) & NVME_CSTS_CFS ||
2423                 dev->online_queues < 2);
2424 }
2425
2426 static void nvme_ns_remove(struct nvme_ns *ns)
2427 {
2428         bool kill = nvme_io_incapable(to_nvme_dev(ns->ctrl)) &&
2429                         !blk_queue_dying(ns->queue);
2430
2431         if (kill)
2432                 blk_set_queue_dying(ns->queue);
2433         if (ns->disk->flags & GENHD_FL_UP)
2434                 del_gendisk(ns->disk);
2435         if (kill || !blk_queue_dying(ns->queue)) {
2436                 blk_mq_abort_requeue_list(ns->queue);
2437                 blk_cleanup_queue(ns->queue);
2438         }
2439         list_del_init(&ns->list);
2440         kref_put(&ns->kref, nvme_free_ns);
2441 }
2442
2443 static void nvme_scan_namespaces(struct nvme_dev *dev, unsigned nn)
2444 {
2445         struct nvme_ns *ns, *next;
2446         unsigned i;
2447
2448         for (i = 1; i <= nn; i++) {
2449                 ns = nvme_find_ns(dev, i);
2450                 if (ns) {
2451                         if (revalidate_disk(ns->disk))
2452                                 nvme_ns_remove(ns);
2453                 } else
2454                         nvme_alloc_ns(dev, i);
2455         }
2456         list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2457                 if (ns->ns_id > nn)
2458                         nvme_ns_remove(ns);
2459         }
2460         list_sort(NULL, &dev->namespaces, ns_cmp);
2461 }
2462
2463 static void nvme_set_irq_hints(struct nvme_dev *dev)
2464 {
2465         struct nvme_queue *nvmeq;
2466         int i;
2467
2468         for (i = 0; i < dev->online_queues; i++) {
2469                 nvmeq = dev->queues[i];
2470
2471                 if (!nvmeq->tags || !(*nvmeq->tags))
2472                         continue;
2473
2474                 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
2475                                         blk_mq_tags_cpumask(*nvmeq->tags));
2476         }
2477 }
2478
2479 static void nvme_dev_scan(struct work_struct *work)
2480 {
2481         struct nvme_dev *dev = container_of(work, struct nvme_dev, scan_work);
2482         struct nvme_id_ctrl *ctrl;
2483
2484         if (!dev->tagset.tags)
2485                 return;
2486         if (nvme_identify_ctrl(&dev->ctrl, &ctrl))
2487                 return;
2488         nvme_scan_namespaces(dev, le32_to_cpup(&ctrl->nn));
2489         kfree(ctrl);
2490         nvme_set_irq_hints(dev);
2491 }
2492
2493 /*
2494  * Return: error value if an error occurred setting up the queues or calling
2495  * Identify Device.  0 if these succeeded, even if adding some of the
2496  * namespaces failed.  At the moment, these failures are silent.  TBD which
2497  * failures should be reported.
2498  */
2499 static int nvme_dev_add(struct nvme_dev *dev)
2500 {
2501         struct pci_dev *pdev = to_pci_dev(dev->dev);
2502         int res;
2503         struct nvme_id_ctrl *ctrl;
2504         int shift = NVME_CAP_MPSMIN(lo_hi_readq(dev->bar + NVME_REG_CAP)) + 12;
2505
2506         res = nvme_identify_ctrl(&dev->ctrl, &ctrl);
2507         if (res) {
2508                 dev_err(dev->dev, "Identify Controller failed (%d)\n", res);
2509                 return -EIO;
2510         }
2511
2512         dev->ctrl.oncs = le16_to_cpup(&ctrl->oncs);
2513         dev->ctrl.abort_limit = ctrl->acl + 1;
2514         dev->ctrl.vwc = ctrl->vwc;
2515         memcpy(dev->ctrl.serial, ctrl->sn, sizeof(ctrl->sn));
2516         memcpy(dev->ctrl.model, ctrl->mn, sizeof(ctrl->mn));
2517         memcpy(dev->ctrl.firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2518         if (ctrl->mdts)
2519                 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2520         else
2521                 dev->max_hw_sectors = UINT_MAX;
2522         if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2523                         (pdev->device == 0x0953) && ctrl->vs[3]) {
2524                 unsigned int max_hw_sectors;
2525
2526                 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2527                 max_hw_sectors = dev->stripe_size >> (shift - 9);
2528                 if (dev->max_hw_sectors) {
2529                         dev->max_hw_sectors = min(max_hw_sectors,
2530                                                         dev->max_hw_sectors);
2531                 } else
2532                         dev->max_hw_sectors = max_hw_sectors;
2533         }
2534         kfree(ctrl);
2535
2536         if (!dev->tagset.tags) {
2537                 dev->tagset.ops = &nvme_mq_ops;
2538                 dev->tagset.nr_hw_queues = dev->online_queues - 1;
2539                 dev->tagset.timeout = NVME_IO_TIMEOUT;
2540                 dev->tagset.numa_node = dev_to_node(dev->dev);
2541                 dev->tagset.queue_depth =
2542                                 min_t(int, dev->q_depth, BLK_MQ_MAX_DEPTH) - 1;
2543                 dev->tagset.cmd_size = nvme_cmd_size(dev);
2544                 dev->tagset.flags = BLK_MQ_F_SHOULD_MERGE;
2545                 dev->tagset.driver_data = dev;
2546
2547                 if (blk_mq_alloc_tag_set(&dev->tagset))
2548                         return 0;
2549         }
2550         schedule_work(&dev->scan_work);
2551         return 0;
2552 }
2553
2554 static int nvme_dev_map(struct nvme_dev *dev)
2555 {
2556         u64 cap;
2557         int bars, result = -ENOMEM;
2558         struct pci_dev *pdev = to_pci_dev(dev->dev);
2559
2560         if (pci_enable_device_mem(pdev))
2561                 return result;
2562
2563         dev->entry[0].vector = pdev->irq;
2564         pci_set_master(pdev);
2565         bars = pci_select_bars(pdev, IORESOURCE_MEM);
2566         if (!bars)
2567                 goto disable_pci;
2568
2569         if (pci_request_selected_regions(pdev, bars, "nvme"))
2570                 goto disable_pci;
2571
2572         if (dma_set_mask_and_coherent(dev->dev, DMA_BIT_MASK(64)) &&
2573             dma_set_mask_and_coherent(dev->dev, DMA_BIT_MASK(32)))
2574                 goto disable;
2575
2576         dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2577         if (!dev->bar)
2578                 goto disable;
2579
2580         if (readl(dev->bar + NVME_REG_CSTS) == -1) {
2581                 result = -ENODEV;
2582                 goto unmap;
2583         }
2584
2585         /*
2586          * Some devices don't advertse INTx interrupts, pre-enable a single
2587          * MSIX vec for setup. We'll adjust this later.
2588          */
2589         if (!pdev->irq) {
2590                 result = pci_enable_msix(pdev, dev->entry, 1);
2591                 if (result < 0)
2592                         goto unmap;
2593         }
2594
2595         cap = lo_hi_readq(dev->bar + NVME_REG_CAP);
2596
2597         dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2598         dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
2599         dev->dbs = dev->bar + 4096;
2600         if (readl(dev->bar + NVME_REG_VS) >= NVME_VS(1, 2))
2601                 dev->cmb = nvme_map_cmb(dev);
2602
2603         return 0;
2604
2605  unmap:
2606         iounmap(dev->bar);
2607         dev->bar = NULL;
2608  disable:
2609         pci_release_regions(pdev);
2610  disable_pci:
2611         pci_disable_device(pdev);
2612         return result;
2613 }
2614
2615 static void nvme_dev_unmap(struct nvme_dev *dev)
2616 {
2617         struct pci_dev *pdev = to_pci_dev(dev->dev);
2618
2619         if (pdev->msi_enabled)
2620                 pci_disable_msi(pdev);
2621         else if (pdev->msix_enabled)
2622                 pci_disable_msix(pdev);
2623
2624         if (dev->bar) {
2625                 iounmap(dev->bar);
2626                 dev->bar = NULL;
2627                 pci_release_regions(pdev);
2628         }
2629
2630         if (pci_is_enabled(pdev))
2631                 pci_disable_device(pdev);
2632 }
2633
2634 struct nvme_delq_ctx {
2635         struct task_struct *waiter;
2636         struct kthread_worker *worker;
2637         atomic_t refcount;
2638 };
2639
2640 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2641 {
2642         dq->waiter = current;
2643         mb();
2644
2645         for (;;) {
2646                 set_current_state(TASK_KILLABLE);
2647                 if (!atomic_read(&dq->refcount))
2648                         break;
2649                 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2650                                         fatal_signal_pending(current)) {
2651                         /*
2652                          * Disable the controller first since we can't trust it
2653                          * at this point, but leave the admin queue enabled
2654                          * until all queue deletion requests are flushed.
2655                          * FIXME: This may take a while if there are more h/w
2656                          * queues than admin tags.
2657                          */
2658                         set_current_state(TASK_RUNNING);
2659                         nvme_disable_ctrl(dev,
2660                                 lo_hi_readq(dev->bar + NVME_REG_CAP));
2661                         nvme_clear_queue(dev->queues[0]);
2662                         flush_kthread_worker(dq->worker);
2663                         nvme_disable_queue(dev, 0);
2664                         return;
2665                 }
2666         }
2667         set_current_state(TASK_RUNNING);
2668 }
2669
2670 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2671 {
2672         atomic_dec(&dq->refcount);
2673         if (dq->waiter)
2674                 wake_up_process(dq->waiter);
2675 }
2676
2677 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2678 {
2679         atomic_inc(&dq->refcount);
2680         return dq;
2681 }
2682
2683 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2684 {
2685         struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2686         nvme_put_dq(dq);
2687
2688         spin_lock_irq(&nvmeq->q_lock);
2689         nvme_process_cq(nvmeq);
2690         spin_unlock_irq(&nvmeq->q_lock);
2691 }
2692
2693 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2694                                                 kthread_work_func_t fn)
2695 {
2696         struct nvme_command c;
2697
2698         memset(&c, 0, sizeof(c));
2699         c.delete_queue.opcode = opcode;
2700         c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2701
2702         init_kthread_work(&nvmeq->cmdinfo.work, fn);
2703         return nvme_submit_admin_async_cmd(nvmeq->dev, &c, &nvmeq->cmdinfo,
2704                                                                 ADMIN_TIMEOUT);
2705 }
2706
2707 static void nvme_del_cq_work_handler(struct kthread_work *work)
2708 {
2709         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2710                                                         cmdinfo.work);
2711         nvme_del_queue_end(nvmeq);
2712 }
2713
2714 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2715 {
2716         return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2717                                                 nvme_del_cq_work_handler);
2718 }
2719
2720 static void nvme_del_sq_work_handler(struct kthread_work *work)
2721 {
2722         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2723                                                         cmdinfo.work);
2724         int status = nvmeq->cmdinfo.status;
2725
2726         if (!status)
2727                 status = nvme_delete_cq(nvmeq);
2728         if (status)
2729                 nvme_del_queue_end(nvmeq);
2730 }
2731
2732 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2733 {
2734         return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2735                                                 nvme_del_sq_work_handler);
2736 }
2737
2738 static void nvme_del_queue_start(struct kthread_work *work)
2739 {
2740         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2741                                                         cmdinfo.work);
2742         if (nvme_delete_sq(nvmeq))
2743                 nvme_del_queue_end(nvmeq);
2744 }
2745
2746 static void nvme_disable_io_queues(struct nvme_dev *dev)
2747 {
2748         int i;
2749         DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2750         struct nvme_delq_ctx dq;
2751         struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2752                                         &worker, "nvme%d", dev->ctrl.instance);
2753
2754         if (IS_ERR(kworker_task)) {
2755                 dev_err(dev->dev,
2756                         "Failed to create queue del task\n");
2757                 for (i = dev->queue_count - 1; i > 0; i--)
2758                         nvme_disable_queue(dev, i);
2759                 return;
2760         }
2761
2762         dq.waiter = NULL;
2763         atomic_set(&dq.refcount, 0);
2764         dq.worker = &worker;
2765         for (i = dev->queue_count - 1; i > 0; i--) {
2766                 struct nvme_queue *nvmeq = dev->queues[i];
2767
2768                 if (nvme_suspend_queue(nvmeq))
2769                         continue;
2770                 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2771                 nvmeq->cmdinfo.worker = dq.worker;
2772                 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2773                 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2774         }
2775         nvme_wait_dq(&dq, dev);
2776         kthread_stop(kworker_task);
2777 }
2778
2779 /*
2780 * Remove the node from the device list and check
2781 * for whether or not we need to stop the nvme_thread.
2782 */
2783 static void nvme_dev_list_remove(struct nvme_dev *dev)
2784 {
2785         struct task_struct *tmp = NULL;
2786
2787         spin_lock(&dev_list_lock);
2788         list_del_init(&dev->node);
2789         if (list_empty(&dev_list) && !IS_ERR_OR_NULL(nvme_thread)) {
2790                 tmp = nvme_thread;
2791                 nvme_thread = NULL;
2792         }
2793         spin_unlock(&dev_list_lock);
2794
2795         if (tmp)
2796                 kthread_stop(tmp);
2797 }
2798
2799 static void nvme_freeze_queues(struct nvme_dev *dev)
2800 {
2801         struct nvme_ns *ns;
2802
2803         list_for_each_entry(ns, &dev->namespaces, list) {
2804                 blk_mq_freeze_queue_start(ns->queue);
2805
2806                 spin_lock_irq(ns->queue->queue_lock);
2807                 queue_flag_set(QUEUE_FLAG_STOPPED, ns->queue);
2808                 spin_unlock_irq(ns->queue->queue_lock);
2809
2810                 blk_mq_cancel_requeue_work(ns->queue);
2811                 blk_mq_stop_hw_queues(ns->queue);
2812         }
2813 }
2814
2815 static void nvme_unfreeze_queues(struct nvme_dev *dev)
2816 {
2817         struct nvme_ns *ns;
2818
2819         list_for_each_entry(ns, &dev->namespaces, list) {
2820                 queue_flag_clear_unlocked(QUEUE_FLAG_STOPPED, ns->queue);
2821                 blk_mq_unfreeze_queue(ns->queue);
2822                 blk_mq_start_stopped_hw_queues(ns->queue, true);
2823                 blk_mq_kick_requeue_list(ns->queue);
2824         }
2825 }
2826
2827 static void nvme_dev_shutdown(struct nvme_dev *dev)
2828 {
2829         int i;
2830         u32 csts = -1;
2831
2832         nvme_dev_list_remove(dev);
2833
2834         if (dev->bar) {
2835                 nvme_freeze_queues(dev);
2836                 csts = readl(dev->bar + NVME_REG_CSTS);
2837         }
2838         if (csts & NVME_CSTS_CFS || !(csts & NVME_CSTS_RDY)) {
2839                 for (i = dev->queue_count - 1; i >= 0; i--) {
2840                         struct nvme_queue *nvmeq = dev->queues[i];
2841                         nvme_suspend_queue(nvmeq);
2842                 }
2843         } else {
2844                 nvme_disable_io_queues(dev);
2845                 nvme_shutdown_ctrl(dev);
2846                 nvme_disable_queue(dev, 0);
2847         }
2848         nvme_dev_unmap(dev);
2849
2850         for (i = dev->queue_count - 1; i >= 0; i--)
2851                 nvme_clear_queue(dev->queues[i]);
2852 }
2853
2854 static void nvme_dev_remove(struct nvme_dev *dev)
2855 {
2856         struct nvme_ns *ns, *next;
2857
2858         list_for_each_entry_safe(ns, next, &dev->namespaces, list)
2859                 nvme_ns_remove(ns);
2860 }
2861
2862 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2863 {
2864         dev->prp_page_pool = dma_pool_create("prp list page", dev->dev,
2865                                                 PAGE_SIZE, PAGE_SIZE, 0);
2866         if (!dev->prp_page_pool)
2867                 return -ENOMEM;
2868
2869         /* Optimisation for I/Os between 4k and 128k */
2870         dev->prp_small_pool = dma_pool_create("prp list 256", dev->dev,
2871                                                 256, 256, 0);
2872         if (!dev->prp_small_pool) {
2873                 dma_pool_destroy(dev->prp_page_pool);
2874                 return -ENOMEM;
2875         }
2876         return 0;
2877 }
2878
2879 static void nvme_release_prp_pools(struct nvme_dev *dev)
2880 {
2881         dma_pool_destroy(dev->prp_page_pool);
2882         dma_pool_destroy(dev->prp_small_pool);
2883 }
2884
2885 static DEFINE_IDA(nvme_instance_ida);
2886
2887 static int nvme_set_instance(struct nvme_dev *dev)
2888 {
2889         int instance, error;
2890
2891         do {
2892                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2893                         return -ENODEV;
2894
2895                 spin_lock(&dev_list_lock);
2896                 error = ida_get_new(&nvme_instance_ida, &instance);
2897                 spin_unlock(&dev_list_lock);
2898         } while (error == -EAGAIN);
2899
2900         if (error)
2901                 return -ENODEV;
2902
2903         dev->ctrl.instance = instance;
2904         return 0;
2905 }
2906
2907 static void nvme_release_instance(struct nvme_dev *dev)
2908 {
2909         spin_lock(&dev_list_lock);
2910         ida_remove(&nvme_instance_ida, dev->ctrl.instance);
2911         spin_unlock(&dev_list_lock);
2912 }
2913
2914 static void nvme_free_dev(struct kref *kref)
2915 {
2916         struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2917
2918         put_device(dev->dev);
2919         put_device(dev->device);
2920         nvme_release_instance(dev);
2921         if (dev->tagset.tags)
2922                 blk_mq_free_tag_set(&dev->tagset);
2923         if (dev->ctrl.admin_q)
2924                 blk_put_queue(dev->ctrl.admin_q);
2925         kfree(dev->queues);
2926         kfree(dev->entry);
2927         kfree(dev);
2928 }
2929
2930 static int nvme_dev_open(struct inode *inode, struct file *f)
2931 {
2932         struct nvme_dev *dev;
2933         int instance = iminor(inode);
2934         int ret = -ENODEV;
2935
2936         spin_lock(&dev_list_lock);
2937         list_for_each_entry(dev, &dev_list, node) {
2938                 if (dev->ctrl.instance == instance) {
2939                         if (!dev->ctrl.admin_q) {
2940                                 ret = -EWOULDBLOCK;
2941                                 break;
2942                         }
2943                         if (!kref_get_unless_zero(&dev->kref))
2944                                 break;
2945                         f->private_data = dev;
2946                         ret = 0;
2947                         break;
2948                 }
2949         }
2950         spin_unlock(&dev_list_lock);
2951
2952         return ret;
2953 }
2954
2955 static int nvme_dev_release(struct inode *inode, struct file *f)
2956 {
2957         struct nvme_dev *dev = f->private_data;
2958         kref_put(&dev->kref, nvme_free_dev);
2959         return 0;
2960 }
2961
2962 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2963 {
2964         struct nvme_dev *dev = f->private_data;
2965         struct nvme_ns *ns;
2966
2967         switch (cmd) {
2968         case NVME_IOCTL_ADMIN_CMD:
2969                 return nvme_user_cmd(&dev->ctrl, NULL, (void __user *)arg);
2970         case NVME_IOCTL_IO_CMD:
2971                 if (list_empty(&dev->namespaces))
2972                         return -ENOTTY;
2973                 ns = list_first_entry(&dev->namespaces, struct nvme_ns, list);
2974                 return nvme_user_cmd(&dev->ctrl, ns, (void __user *)arg);
2975         case NVME_IOCTL_RESET:
2976                 dev_warn(dev->dev, "resetting controller\n");
2977                 return nvme_reset(dev);
2978         case NVME_IOCTL_SUBSYS_RESET:
2979                 return nvme_subsys_reset(dev);
2980         default:
2981                 return -ENOTTY;
2982         }
2983 }
2984
2985 static const struct file_operations nvme_dev_fops = {
2986         .owner          = THIS_MODULE,
2987         .open           = nvme_dev_open,
2988         .release        = nvme_dev_release,
2989         .unlocked_ioctl = nvme_dev_ioctl,
2990         .compat_ioctl   = nvme_dev_ioctl,
2991 };
2992
2993 static void nvme_probe_work(struct work_struct *work)
2994 {
2995         struct nvme_dev *dev = container_of(work, struct nvme_dev, probe_work);
2996         bool start_thread = false;
2997         int result;
2998
2999         result = nvme_dev_map(dev);
3000         if (result)
3001                 goto out;
3002
3003         result = nvme_configure_admin_queue(dev);
3004         if (result)
3005                 goto unmap;
3006
3007         spin_lock(&dev_list_lock);
3008         if (list_empty(&dev_list) && IS_ERR_OR_NULL(nvme_thread)) {
3009                 start_thread = true;
3010                 nvme_thread = NULL;
3011         }
3012         list_add(&dev->node, &dev_list);
3013         spin_unlock(&dev_list_lock);
3014
3015         if (start_thread) {
3016                 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
3017                 wake_up_all(&nvme_kthread_wait);
3018         } else
3019                 wait_event_killable(nvme_kthread_wait, nvme_thread);
3020
3021         if (IS_ERR_OR_NULL(nvme_thread)) {
3022                 result = nvme_thread ? PTR_ERR(nvme_thread) : -EINTR;
3023                 goto disable;
3024         }
3025
3026         nvme_init_queue(dev->queues[0], 0);
3027         result = nvme_alloc_admin_tags(dev);
3028         if (result)
3029                 goto disable;
3030
3031         result = nvme_setup_io_queues(dev);
3032         if (result)
3033                 goto free_tags;
3034
3035         dev->ctrl.event_limit = 1;
3036
3037         /*
3038          * Keep the controller around but remove all namespaces if we don't have
3039          * any working I/O queue.
3040          */
3041         if (dev->online_queues < 2) {
3042                 dev_warn(dev->dev, "IO queues not created\n");
3043                 nvme_dev_remove(dev);
3044         } else {
3045                 nvme_unfreeze_queues(dev);
3046                 nvme_dev_add(dev);
3047         }
3048
3049         return;
3050
3051  free_tags:
3052         nvme_dev_remove_admin(dev);
3053         blk_put_queue(dev->ctrl.admin_q);
3054         dev->ctrl.admin_q = NULL;
3055         dev->queues[0]->tags = NULL;
3056  disable:
3057         nvme_disable_queue(dev, 0);
3058         nvme_dev_list_remove(dev);
3059  unmap:
3060         nvme_dev_unmap(dev);
3061  out:
3062         if (!work_busy(&dev->reset_work))
3063                 nvme_dead_ctrl(dev);
3064 }
3065
3066 static int nvme_remove_dead_ctrl(void *arg)
3067 {
3068         struct nvme_dev *dev = (struct nvme_dev *)arg;
3069         struct pci_dev *pdev = to_pci_dev(dev->dev);
3070
3071         if (pci_get_drvdata(pdev))
3072                 pci_stop_and_remove_bus_device_locked(pdev);
3073         kref_put(&dev->kref, nvme_free_dev);
3074         return 0;
3075 }
3076
3077 static void nvme_dead_ctrl(struct nvme_dev *dev)
3078 {
3079         dev_warn(dev->dev, "Device failed to resume\n");
3080         kref_get(&dev->kref);
3081         if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
3082                                                 dev->ctrl.instance))) {
3083                 dev_err(dev->dev,
3084                         "Failed to start controller remove task\n");
3085                 kref_put(&dev->kref, nvme_free_dev);
3086         }
3087 }
3088
3089 static void nvme_reset_work(struct work_struct *ws)
3090 {
3091         struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
3092         bool in_probe = work_busy(&dev->probe_work);
3093
3094         nvme_dev_shutdown(dev);
3095
3096         /* Synchronize with device probe so that work will see failure status
3097          * and exit gracefully without trying to schedule another reset */
3098         flush_work(&dev->probe_work);
3099
3100         /* Fail this device if reset occured during probe to avoid
3101          * infinite initialization loops. */
3102         if (in_probe) {
3103                 nvme_dead_ctrl(dev);
3104                 return;
3105         }
3106         /* Schedule device resume asynchronously so the reset work is available
3107          * to cleanup errors that may occur during reinitialization */
3108         schedule_work(&dev->probe_work);
3109 }
3110
3111 static int __nvme_reset(struct nvme_dev *dev)
3112 {
3113         if (work_pending(&dev->reset_work))
3114                 return -EBUSY;
3115         list_del_init(&dev->node);
3116         queue_work(nvme_workq, &dev->reset_work);
3117         return 0;
3118 }
3119
3120 static int nvme_reset(struct nvme_dev *dev)
3121 {
3122         int ret;
3123
3124         if (!dev->ctrl.admin_q || blk_queue_dying(dev->ctrl.admin_q))
3125                 return -ENODEV;
3126
3127         spin_lock(&dev_list_lock);
3128         ret = __nvme_reset(dev);
3129         spin_unlock(&dev_list_lock);
3130
3131         if (!ret) {
3132                 flush_work(&dev->reset_work);
3133                 flush_work(&dev->probe_work);
3134                 return 0;
3135         }
3136
3137         return ret;
3138 }
3139
3140 static ssize_t nvme_sysfs_reset(struct device *dev,
3141                                 struct device_attribute *attr, const char *buf,
3142                                 size_t count)
3143 {
3144         struct nvme_dev *ndev = dev_get_drvdata(dev);
3145         int ret;
3146
3147         ret = nvme_reset(ndev);
3148         if (ret < 0)
3149                 return ret;
3150
3151         return count;
3152 }
3153 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3154
3155 static int nvme_pci_reg_read32(struct nvme_ctrl *ctrl, u32 off, u32 *val)
3156 {
3157         *val = readl(to_nvme_dev(ctrl)->bar + off);
3158         return 0;
3159 }
3160
3161 static const struct nvme_ctrl_ops nvme_pci_ctrl_ops = {
3162         .reg_read32             = nvme_pci_reg_read32,
3163 };
3164
3165 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
3166 {
3167         int node, result = -ENOMEM;
3168         struct nvme_dev *dev;
3169
3170         node = dev_to_node(&pdev->dev);
3171         if (node == NUMA_NO_NODE)
3172                 set_dev_node(&pdev->dev, 0);
3173
3174         dev = kzalloc_node(sizeof(*dev), GFP_KERNEL, node);
3175         if (!dev)
3176                 return -ENOMEM;
3177         dev->entry = kzalloc_node(num_possible_cpus() * sizeof(*dev->entry),
3178                                                         GFP_KERNEL, node);
3179         if (!dev->entry)
3180                 goto free;
3181         dev->queues = kzalloc_node((num_possible_cpus() + 1) * sizeof(void *),
3182                                                         GFP_KERNEL, node);
3183         if (!dev->queues)
3184                 goto free;
3185
3186         INIT_LIST_HEAD(&dev->namespaces);
3187         INIT_WORK(&dev->reset_work, nvme_reset_work);
3188         dev->dev = get_device(&pdev->dev);
3189         pci_set_drvdata(pdev, dev);
3190
3191         dev->ctrl.ops = &nvme_pci_ctrl_ops;
3192         dev->ctrl.dev = dev->dev;
3193
3194         result = nvme_set_instance(dev);
3195         if (result)
3196                 goto put_pci;
3197
3198         result = nvme_setup_prp_pools(dev);
3199         if (result)
3200                 goto release;
3201
3202         kref_init(&dev->kref);
3203         dev->device = device_create(nvme_class, &pdev->dev,
3204                                 MKDEV(nvme_char_major, dev->ctrl.instance),
3205                                 dev, "nvme%d", dev->ctrl.instance);
3206         if (IS_ERR(dev->device)) {
3207                 result = PTR_ERR(dev->device);
3208                 goto release_pools;
3209         }
3210         get_device(dev->device);
3211         dev_set_drvdata(dev->device, dev);
3212
3213         result = device_create_file(dev->device, &dev_attr_reset_controller);
3214         if (result)
3215                 goto put_dev;
3216
3217         INIT_LIST_HEAD(&dev->node);
3218         INIT_WORK(&dev->scan_work, nvme_dev_scan);
3219         INIT_WORK(&dev->probe_work, nvme_probe_work);
3220         schedule_work(&dev->probe_work);
3221         return 0;
3222
3223  put_dev:
3224         device_destroy(nvme_class, MKDEV(nvme_char_major, dev->ctrl.instance));
3225         put_device(dev->device);
3226  release_pools:
3227         nvme_release_prp_pools(dev);
3228  release:
3229         nvme_release_instance(dev);
3230  put_pci:
3231         put_device(dev->dev);
3232  free:
3233         kfree(dev->queues);
3234         kfree(dev->entry);
3235         kfree(dev);
3236         return result;
3237 }
3238
3239 static void nvme_reset_notify(struct pci_dev *pdev, bool prepare)
3240 {
3241         struct nvme_dev *dev = pci_get_drvdata(pdev);
3242
3243         if (prepare)
3244                 nvme_dev_shutdown(dev);
3245         else
3246                 schedule_work(&dev->probe_work);
3247 }
3248
3249 static void nvme_shutdown(struct pci_dev *pdev)
3250 {
3251         struct nvme_dev *dev = pci_get_drvdata(pdev);
3252         nvme_dev_shutdown(dev);
3253 }
3254
3255 static void nvme_remove(struct pci_dev *pdev)
3256 {
3257         struct nvme_dev *dev = pci_get_drvdata(pdev);
3258
3259         spin_lock(&dev_list_lock);
3260         list_del_init(&dev->node);
3261         spin_unlock(&dev_list_lock);
3262
3263         pci_set_drvdata(pdev, NULL);
3264         flush_work(&dev->probe_work);
3265         flush_work(&dev->reset_work);
3266         flush_work(&dev->scan_work);
3267         device_remove_file(dev->device, &dev_attr_reset_controller);
3268         nvme_dev_remove(dev);
3269         nvme_dev_shutdown(dev);
3270         nvme_dev_remove_admin(dev);
3271         device_destroy(nvme_class, MKDEV(nvme_char_major, dev->ctrl.instance));
3272         nvme_free_queues(dev, 0);
3273         nvme_release_cmb(dev);
3274         nvme_release_prp_pools(dev);
3275         kref_put(&dev->kref, nvme_free_dev);
3276 }
3277
3278 /* These functions are yet to be implemented */
3279 #define nvme_error_detected NULL
3280 #define nvme_dump_registers NULL
3281 #define nvme_link_reset NULL
3282 #define nvme_slot_reset NULL
3283 #define nvme_error_resume NULL
3284
3285 #ifdef CONFIG_PM_SLEEP
3286 static int nvme_suspend(struct device *dev)
3287 {
3288         struct pci_dev *pdev = to_pci_dev(dev);
3289         struct nvme_dev *ndev = pci_get_drvdata(pdev);
3290
3291         nvme_dev_shutdown(ndev);
3292         return 0;
3293 }
3294
3295 static int nvme_resume(struct device *dev)
3296 {
3297         struct pci_dev *pdev = to_pci_dev(dev);
3298         struct nvme_dev *ndev = pci_get_drvdata(pdev);
3299
3300         schedule_work(&ndev->probe_work);
3301         return 0;
3302 }
3303 #endif
3304
3305 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
3306
3307 static const struct pci_error_handlers nvme_err_handler = {
3308         .error_detected = nvme_error_detected,
3309         .mmio_enabled   = nvme_dump_registers,
3310         .link_reset     = nvme_link_reset,
3311         .slot_reset     = nvme_slot_reset,
3312         .resume         = nvme_error_resume,
3313         .reset_notify   = nvme_reset_notify,
3314 };
3315
3316 /* Move to pci_ids.h later */
3317 #define PCI_CLASS_STORAGE_EXPRESS       0x010802
3318
3319 static const struct pci_device_id nvme_id_table[] = {
3320         { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
3321         { PCI_DEVICE(PCI_VENDOR_ID_APPLE, 0x2001) },
3322         { 0, }
3323 };
3324 MODULE_DEVICE_TABLE(pci, nvme_id_table);
3325
3326 static struct pci_driver nvme_driver = {
3327         .name           = "nvme",
3328         .id_table       = nvme_id_table,
3329         .probe          = nvme_probe,
3330         .remove         = nvme_remove,
3331         .shutdown       = nvme_shutdown,
3332         .driver         = {
3333                 .pm     = &nvme_dev_pm_ops,
3334         },
3335         .err_handler    = &nvme_err_handler,
3336 };
3337
3338 static int __init nvme_init(void)
3339 {
3340         int result;
3341
3342         init_waitqueue_head(&nvme_kthread_wait);
3343
3344         nvme_workq = create_singlethread_workqueue("nvme");
3345         if (!nvme_workq)
3346                 return -ENOMEM;
3347
3348         result = register_blkdev(nvme_major, "nvme");
3349         if (result < 0)
3350                 goto kill_workq;
3351         else if (result > 0)
3352                 nvme_major = result;
3353
3354         result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
3355                                                         &nvme_dev_fops);
3356         if (result < 0)
3357                 goto unregister_blkdev;
3358         else if (result > 0)
3359                 nvme_char_major = result;
3360
3361         nvme_class = class_create(THIS_MODULE, "nvme");
3362         if (IS_ERR(nvme_class)) {
3363                 result = PTR_ERR(nvme_class);
3364                 goto unregister_chrdev;
3365         }
3366
3367         result = pci_register_driver(&nvme_driver);
3368         if (result)
3369                 goto destroy_class;
3370         return 0;
3371
3372  destroy_class:
3373         class_destroy(nvme_class);
3374  unregister_chrdev:
3375         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
3376  unregister_blkdev:
3377         unregister_blkdev(nvme_major, "nvme");
3378  kill_workq:
3379         destroy_workqueue(nvme_workq);
3380         return result;
3381 }
3382
3383 static void __exit nvme_exit(void)
3384 {
3385         pci_unregister_driver(&nvme_driver);
3386         unregister_blkdev(nvme_major, "nvme");
3387         destroy_workqueue(nvme_workq);
3388         class_destroy(nvme_class);
3389         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
3390         BUG_ON(nvme_thread && !IS_ERR(nvme_thread));
3391         _nvme_check_size();
3392 }
3393
3394 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
3395 MODULE_LICENSE("GPL");
3396 MODULE_VERSION("1.0");
3397 module_init(nvme_init);
3398 module_exit(nvme_exit);