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