]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/block/nvme-core.c
NVMe: IOCTL path RCU protect queue access
[karo-tx-linux.git] / drivers / block / nvme-core.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011, 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  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <linux/nvme.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/fs.h>
26 #include <linux/genhd.h>
27 #include <linux/idr.h>
28 #include <linux/init.h>
29 #include <linux/interrupt.h>
30 #include <linux/io.h>
31 #include <linux/kdev_t.h>
32 #include <linux/kthread.h>
33 #include <linux/kernel.h>
34 #include <linux/mm.h>
35 #include <linux/module.h>
36 #include <linux/moduleparam.h>
37 #include <linux/pci.h>
38 #include <linux/poison.h>
39 #include <linux/ptrace.h>
40 #include <linux/sched.h>
41 #include <linux/slab.h>
42 #include <linux/types.h>
43 #include <scsi/sg.h>
44 #include <asm-generic/io-64-nonatomic-lo-hi.h>
45
46 #define NVME_Q_DEPTH 1024
47 #define SQ_SIZE(depth)          (depth * sizeof(struct nvme_command))
48 #define CQ_SIZE(depth)          (depth * sizeof(struct nvme_completion))
49 #define ADMIN_TIMEOUT   (60 * HZ)
50
51 static int nvme_major;
52 module_param(nvme_major, int, 0);
53
54 static int use_threaded_interrupts;
55 module_param(use_threaded_interrupts, int, 0);
56
57 static DEFINE_SPINLOCK(dev_list_lock);
58 static LIST_HEAD(dev_list);
59 static struct task_struct *nvme_thread;
60 static struct workqueue_struct *nvme_workq;
61
62 static void nvme_reset_failed_dev(struct work_struct *ws);
63
64 struct async_cmd_info {
65         struct kthread_work work;
66         struct kthread_worker *worker;
67         u32 result;
68         int status;
69         void *ctx;
70 };
71
72 /*
73  * An NVM Express queue.  Each device has at least two (one for admin
74  * commands and one for I/O commands).
75  */
76 struct nvme_queue {
77         struct rcu_head r_head;
78         struct device *q_dmadev;
79         struct nvme_dev *dev;
80         char irqname[24];       /* nvme4294967295-65535\0 */
81         spinlock_t q_lock;
82         struct nvme_command *sq_cmds;
83         volatile struct nvme_completion *cqes;
84         dma_addr_t sq_dma_addr;
85         dma_addr_t cq_dma_addr;
86         wait_queue_head_t sq_full;
87         wait_queue_t sq_cong_wait;
88         struct bio_list sq_cong;
89         u32 __iomem *q_db;
90         u16 q_depth;
91         u16 cq_vector;
92         u16 sq_head;
93         u16 sq_tail;
94         u16 cq_head;
95         u16 qid;
96         u8 cq_phase;
97         u8 cqe_seen;
98         u8 q_suspended;
99         struct async_cmd_info cmdinfo;
100         unsigned long cmdid_data[];
101 };
102
103 /*
104  * Check we didin't inadvertently grow the command struct
105  */
106 static inline void _nvme_check_size(void)
107 {
108         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
109         BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
110         BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
111         BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
112         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
113         BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
114         BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
115         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
116         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
117         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
118         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
119         BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
120 }
121
122 typedef void (*nvme_completion_fn)(struct nvme_dev *, void *,
123                                                 struct nvme_completion *);
124
125 struct nvme_cmd_info {
126         nvme_completion_fn fn;
127         void *ctx;
128         unsigned long timeout;
129         int aborted;
130 };
131
132 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
133 {
134         return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
135 }
136
137 static unsigned nvme_queue_extra(int depth)
138 {
139         return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
140 }
141
142 /**
143  * alloc_cmdid() - Allocate a Command ID
144  * @nvmeq: The queue that will be used for this command
145  * @ctx: A pointer that will be passed to the handler
146  * @handler: The function to call on completion
147  *
148  * Allocate a Command ID for a queue.  The data passed in will
149  * be passed to the completion handler.  This is implemented by using
150  * the bottom two bits of the ctx pointer to store the handler ID.
151  * Passing in a pointer that's not 4-byte aligned will cause a BUG.
152  * We can change this if it becomes a problem.
153  *
154  * May be called with local interrupts disabled and the q_lock held,
155  * or with interrupts enabled and no locks held.
156  */
157 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
158                                 nvme_completion_fn handler, unsigned timeout)
159 {
160         int depth = nvmeq->q_depth - 1;
161         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
162         int cmdid;
163
164         do {
165                 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
166                 if (cmdid >= depth)
167                         return -EBUSY;
168         } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
169
170         info[cmdid].fn = handler;
171         info[cmdid].ctx = ctx;
172         info[cmdid].timeout = jiffies + timeout;
173         info[cmdid].aborted = 0;
174         return cmdid;
175 }
176
177 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
178                                 nvme_completion_fn handler, unsigned timeout)
179 {
180         int cmdid;
181         wait_event_killable(nvmeq->sq_full,
182                 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
183         return (cmdid < 0) ? -EINTR : cmdid;
184 }
185
186 /* Special values must be less than 0x1000 */
187 #define CMD_CTX_BASE            ((void *)POISON_POINTER_DELTA)
188 #define CMD_CTX_CANCELLED       (0x30C + CMD_CTX_BASE)
189 #define CMD_CTX_COMPLETED       (0x310 + CMD_CTX_BASE)
190 #define CMD_CTX_INVALID         (0x314 + CMD_CTX_BASE)
191 #define CMD_CTX_FLUSH           (0x318 + CMD_CTX_BASE)
192 #define CMD_CTX_ABORT           (0x31C + CMD_CTX_BASE)
193
194 static void special_completion(struct nvme_dev *dev, void *ctx,
195                                                 struct nvme_completion *cqe)
196 {
197         if (ctx == CMD_CTX_CANCELLED)
198                 return;
199         if (ctx == CMD_CTX_FLUSH)
200                 return;
201         if (ctx == CMD_CTX_ABORT) {
202                 ++dev->abort_limit;
203                 return;
204         }
205         if (ctx == CMD_CTX_COMPLETED) {
206                 dev_warn(&dev->pci_dev->dev,
207                                 "completed id %d twice on queue %d\n",
208                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
209                 return;
210         }
211         if (ctx == CMD_CTX_INVALID) {
212                 dev_warn(&dev->pci_dev->dev,
213                                 "invalid id %d completed on queue %d\n",
214                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
215                 return;
216         }
217
218         dev_warn(&dev->pci_dev->dev, "Unknown special completion %p\n", ctx);
219 }
220
221 static void async_completion(struct nvme_dev *dev, void *ctx,
222                                                 struct nvme_completion *cqe)
223 {
224         struct async_cmd_info *cmdinfo = ctx;
225         cmdinfo->result = le32_to_cpup(&cqe->result);
226         cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
227         queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
228 }
229
230 /*
231  * Called with local interrupts disabled and the q_lock held.  May not sleep.
232  */
233 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
234                                                 nvme_completion_fn *fn)
235 {
236         void *ctx;
237         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
238
239         if (cmdid >= nvmeq->q_depth) {
240                 *fn = special_completion;
241                 return CMD_CTX_INVALID;
242         }
243         if (fn)
244                 *fn = info[cmdid].fn;
245         ctx = info[cmdid].ctx;
246         info[cmdid].fn = special_completion;
247         info[cmdid].ctx = CMD_CTX_COMPLETED;
248         clear_bit(cmdid, nvmeq->cmdid_data);
249         wake_up(&nvmeq->sq_full);
250         return ctx;
251 }
252
253 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
254                                                 nvme_completion_fn *fn)
255 {
256         void *ctx;
257         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
258         if (fn)
259                 *fn = info[cmdid].fn;
260         ctx = info[cmdid].ctx;
261         info[cmdid].fn = special_completion;
262         info[cmdid].ctx = CMD_CTX_CANCELLED;
263         return ctx;
264 }
265
266 static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
267 {
268         return rcu_dereference_raw(dev->queues[qid]);
269 }
270
271 static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
272 {
273         rcu_read_lock();
274         return rcu_dereference(dev->queues[get_cpu() + 1]);
275 }
276
277 static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
278 {
279         put_cpu();
280         rcu_read_unlock();
281 }
282
283 static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
284                                                         __acquires(RCU)
285 {
286         rcu_read_lock();
287         return rcu_dereference(dev->queues[q_idx]);
288 }
289
290 static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
291 {
292         rcu_read_unlock();
293 }
294
295 /**
296  * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
297  * @nvmeq: The queue to use
298  * @cmd: The command to send
299  *
300  * Safe to use from interrupt context
301  */
302 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
303 {
304         unsigned long flags;
305         u16 tail;
306         spin_lock_irqsave(&nvmeq->q_lock, flags);
307         if (nvmeq->q_suspended) {
308                 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
309                 return -EBUSY;
310         }
311         tail = nvmeq->sq_tail;
312         memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
313         if (++tail == nvmeq->q_depth)
314                 tail = 0;
315         writel(tail, nvmeq->q_db);
316         nvmeq->sq_tail = tail;
317         spin_unlock_irqrestore(&nvmeq->q_lock, flags);
318
319         return 0;
320 }
321
322 static __le64 **iod_list(struct nvme_iod *iod)
323 {
324         return ((void *)iod) + iod->offset;
325 }
326
327 /*
328  * Will slightly overestimate the number of pages needed.  This is OK
329  * as it only leads to a small amount of wasted memory for the lifetime of
330  * the I/O.
331  */
332 static int nvme_npages(unsigned size)
333 {
334         unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
335         return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
336 }
337
338 static struct nvme_iod *
339 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
340 {
341         struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
342                                 sizeof(__le64 *) * nvme_npages(nbytes) +
343                                 sizeof(struct scatterlist) * nseg, gfp);
344
345         if (iod) {
346                 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
347                 iod->npages = -1;
348                 iod->length = nbytes;
349                 iod->nents = 0;
350                 iod->start_time = jiffies;
351         }
352
353         return iod;
354 }
355
356 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
357 {
358         const int last_prp = PAGE_SIZE / 8 - 1;
359         int i;
360         __le64 **list = iod_list(iod);
361         dma_addr_t prp_dma = iod->first_dma;
362
363         if (iod->npages == 0)
364                 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
365         for (i = 0; i < iod->npages; i++) {
366                 __le64 *prp_list = list[i];
367                 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
368                 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
369                 prp_dma = next_prp_dma;
370         }
371         kfree(iod);
372 }
373
374 static void nvme_start_io_acct(struct bio *bio)
375 {
376         struct gendisk *disk = bio->bi_bdev->bd_disk;
377         const int rw = bio_data_dir(bio);
378         int cpu = part_stat_lock();
379         part_round_stats(cpu, &disk->part0);
380         part_stat_inc(cpu, &disk->part0, ios[rw]);
381         part_stat_add(cpu, &disk->part0, sectors[rw], bio_sectors(bio));
382         part_inc_in_flight(&disk->part0, rw);
383         part_stat_unlock();
384 }
385
386 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
387 {
388         struct gendisk *disk = bio->bi_bdev->bd_disk;
389         const int rw = bio_data_dir(bio);
390         unsigned long duration = jiffies - start_time;
391         int cpu = part_stat_lock();
392         part_stat_add(cpu, &disk->part0, ticks[rw], duration);
393         part_round_stats(cpu, &disk->part0);
394         part_dec_in_flight(&disk->part0, rw);
395         part_stat_unlock();
396 }
397
398 static void bio_completion(struct nvme_dev *dev, void *ctx,
399                                                 struct nvme_completion *cqe)
400 {
401         struct nvme_iod *iod = ctx;
402         struct bio *bio = iod->private;
403         u16 status = le16_to_cpup(&cqe->status) >> 1;
404
405         if (iod->nents) {
406                 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
407                         bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
408                 nvme_end_io_acct(bio, iod->start_time);
409         }
410         nvme_free_iod(dev, iod);
411         if (status)
412                 bio_endio(bio, -EIO);
413         else
414                 bio_endio(bio, 0);
415 }
416
417 /* length is in bytes.  gfp flags indicates whether we may sleep. */
418 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_common_command *cmd,
419                         struct nvme_iod *iod, int total_len, gfp_t gfp)
420 {
421         struct dma_pool *pool;
422         int length = total_len;
423         struct scatterlist *sg = iod->sg;
424         int dma_len = sg_dma_len(sg);
425         u64 dma_addr = sg_dma_address(sg);
426         int offset = offset_in_page(dma_addr);
427         __le64 *prp_list;
428         __le64 **list = iod_list(iod);
429         dma_addr_t prp_dma;
430         int nprps, i;
431
432         cmd->prp1 = cpu_to_le64(dma_addr);
433         length -= (PAGE_SIZE - offset);
434         if (length <= 0)
435                 return total_len;
436
437         dma_len -= (PAGE_SIZE - offset);
438         if (dma_len) {
439                 dma_addr += (PAGE_SIZE - offset);
440         } else {
441                 sg = sg_next(sg);
442                 dma_addr = sg_dma_address(sg);
443                 dma_len = sg_dma_len(sg);
444         }
445
446         if (length <= PAGE_SIZE) {
447                 cmd->prp2 = cpu_to_le64(dma_addr);
448                 return total_len;
449         }
450
451         nprps = DIV_ROUND_UP(length, PAGE_SIZE);
452         if (nprps <= (256 / 8)) {
453                 pool = dev->prp_small_pool;
454                 iod->npages = 0;
455         } else {
456                 pool = dev->prp_page_pool;
457                 iod->npages = 1;
458         }
459
460         prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
461         if (!prp_list) {
462                 cmd->prp2 = cpu_to_le64(dma_addr);
463                 iod->npages = -1;
464                 return (total_len - length) + PAGE_SIZE;
465         }
466         list[0] = prp_list;
467         iod->first_dma = prp_dma;
468         cmd->prp2 = cpu_to_le64(prp_dma);
469         i = 0;
470         for (;;) {
471                 if (i == PAGE_SIZE / 8) {
472                         __le64 *old_prp_list = prp_list;
473                         prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
474                         if (!prp_list)
475                                 return total_len - length;
476                         list[iod->npages++] = prp_list;
477                         prp_list[0] = old_prp_list[i - 1];
478                         old_prp_list[i - 1] = cpu_to_le64(prp_dma);
479                         i = 1;
480                 }
481                 prp_list[i++] = cpu_to_le64(dma_addr);
482                 dma_len -= PAGE_SIZE;
483                 dma_addr += PAGE_SIZE;
484                 length -= PAGE_SIZE;
485                 if (length <= 0)
486                         break;
487                 if (dma_len > 0)
488                         continue;
489                 BUG_ON(dma_len < 0);
490                 sg = sg_next(sg);
491                 dma_addr = sg_dma_address(sg);
492                 dma_len = sg_dma_len(sg);
493         }
494
495         return total_len;
496 }
497
498 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
499                                  int len)
500 {
501         struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
502         if (!split)
503                 return -ENOMEM;
504
505         bio_chain(split, bio);
506
507         if (bio_list_empty(&nvmeq->sq_cong))
508                 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
509         bio_list_add(&nvmeq->sq_cong, split);
510         bio_list_add(&nvmeq->sq_cong, bio);
511
512         return 0;
513 }
514
515 /* NVMe scatterlists require no holes in the virtual address */
516 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2)   ((vec2)->bv_offset || \
517                         (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
518
519 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
520                 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
521 {
522         struct bio_vec bvec, bvprv;
523         struct bvec_iter iter;
524         struct scatterlist *sg = NULL;
525         int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
526         int first = 1;
527
528         if (nvmeq->dev->stripe_size)
529                 split_len = nvmeq->dev->stripe_size -
530                         ((bio->bi_iter.bi_sector << 9) &
531                          (nvmeq->dev->stripe_size - 1));
532
533         sg_init_table(iod->sg, psegs);
534         bio_for_each_segment(bvec, bio, iter) {
535                 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
536                         sg->length += bvec.bv_len;
537                 } else {
538                         if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
539                                 return nvme_split_and_submit(bio, nvmeq,
540                                                              length);
541
542                         sg = sg ? sg + 1 : iod->sg;
543                         sg_set_page(sg, bvec.bv_page,
544                                     bvec.bv_len, bvec.bv_offset);
545                         nsegs++;
546                 }
547
548                 if (split_len - length < bvec.bv_len)
549                         return nvme_split_and_submit(bio, nvmeq, split_len);
550                 length += bvec.bv_len;
551                 bvprv = bvec;
552                 first = 0;
553         }
554         iod->nents = nsegs;
555         sg_mark_end(sg);
556         if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
557                 return -ENOMEM;
558
559         BUG_ON(length != bio->bi_iter.bi_size);
560         return length;
561 }
562
563 /*
564  * We reuse the small pool to allocate the 16-byte range here as it is not
565  * worth having a special pool for these or additional cases to handle freeing
566  * the iod.
567  */
568 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
569                 struct bio *bio, struct nvme_iod *iod, int cmdid)
570 {
571         struct nvme_dsm_range *range;
572         struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
573
574         range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
575                                                         &iod->first_dma);
576         if (!range)
577                 return -ENOMEM;
578
579         iod_list(iod)[0] = (__le64 *)range;
580         iod->npages = 0;
581
582         range->cattr = cpu_to_le32(0);
583         range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
584         range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
585
586         memset(cmnd, 0, sizeof(*cmnd));
587         cmnd->dsm.opcode = nvme_cmd_dsm;
588         cmnd->dsm.command_id = cmdid;
589         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
590         cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
591         cmnd->dsm.nr = 0;
592         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
593
594         if (++nvmeq->sq_tail == nvmeq->q_depth)
595                 nvmeq->sq_tail = 0;
596         writel(nvmeq->sq_tail, nvmeq->q_db);
597
598         return 0;
599 }
600
601 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
602                                                                 int cmdid)
603 {
604         struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
605
606         memset(cmnd, 0, sizeof(*cmnd));
607         cmnd->common.opcode = nvme_cmd_flush;
608         cmnd->common.command_id = cmdid;
609         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
610
611         if (++nvmeq->sq_tail == nvmeq->q_depth)
612                 nvmeq->sq_tail = 0;
613         writel(nvmeq->sq_tail, nvmeq->q_db);
614
615         return 0;
616 }
617
618 int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
619 {
620         int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
621                                         special_completion, NVME_IO_TIMEOUT);
622         if (unlikely(cmdid < 0))
623                 return cmdid;
624
625         return nvme_submit_flush(nvmeq, ns, cmdid);
626 }
627
628 /*
629  * Called with local interrupts disabled and the q_lock held.  May not sleep.
630  */
631 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
632                                                                 struct bio *bio)
633 {
634         struct nvme_command *cmnd;
635         struct nvme_iod *iod;
636         enum dma_data_direction dma_dir;
637         int cmdid, length, result;
638         u16 control;
639         u32 dsmgmt;
640         int psegs = bio_phys_segments(ns->queue, bio);
641
642         if ((bio->bi_rw & REQ_FLUSH) && psegs) {
643                 result = nvme_submit_flush_data(nvmeq, ns);
644                 if (result)
645                         return result;
646         }
647
648         result = -ENOMEM;
649         iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, GFP_ATOMIC);
650         if (!iod)
651                 goto nomem;
652         iod->private = bio;
653
654         result = -EBUSY;
655         cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
656         if (unlikely(cmdid < 0))
657                 goto free_iod;
658
659         if (bio->bi_rw & REQ_DISCARD) {
660                 result = nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
661                 if (result)
662                         goto free_cmdid;
663                 return result;
664         }
665         if ((bio->bi_rw & REQ_FLUSH) && !psegs)
666                 return nvme_submit_flush(nvmeq, ns, cmdid);
667
668         control = 0;
669         if (bio->bi_rw & REQ_FUA)
670                 control |= NVME_RW_FUA;
671         if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
672                 control |= NVME_RW_LR;
673
674         dsmgmt = 0;
675         if (bio->bi_rw & REQ_RAHEAD)
676                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
677
678         cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
679
680         memset(cmnd, 0, sizeof(*cmnd));
681         if (bio_data_dir(bio)) {
682                 cmnd->rw.opcode = nvme_cmd_write;
683                 dma_dir = DMA_TO_DEVICE;
684         } else {
685                 cmnd->rw.opcode = nvme_cmd_read;
686                 dma_dir = DMA_FROM_DEVICE;
687         }
688
689         result = nvme_map_bio(nvmeq, iod, bio, dma_dir, psegs);
690         if (result <= 0)
691                 goto free_cmdid;
692         length = result;
693
694         cmnd->rw.command_id = cmdid;
695         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
696         length = nvme_setup_prps(nvmeq->dev, &cmnd->common, iod, length,
697                                                                 GFP_ATOMIC);
698         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
699         cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
700         cmnd->rw.control = cpu_to_le16(control);
701         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
702
703         nvme_start_io_acct(bio);
704         if (++nvmeq->sq_tail == nvmeq->q_depth)
705                 nvmeq->sq_tail = 0;
706         writel(nvmeq->sq_tail, nvmeq->q_db);
707
708         return 0;
709
710  free_cmdid:
711         free_cmdid(nvmeq, cmdid, NULL);
712  free_iod:
713         nvme_free_iod(nvmeq->dev, iod);
714  nomem:
715         return result;
716 }
717
718 static int nvme_process_cq(struct nvme_queue *nvmeq)
719 {
720         u16 head, phase;
721
722         head = nvmeq->cq_head;
723         phase = nvmeq->cq_phase;
724
725         for (;;) {
726                 void *ctx;
727                 nvme_completion_fn fn;
728                 struct nvme_completion cqe = nvmeq->cqes[head];
729                 if ((le16_to_cpu(cqe.status) & 1) != phase)
730                         break;
731                 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
732                 if (++head == nvmeq->q_depth) {
733                         head = 0;
734                         phase = !phase;
735                 }
736
737                 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
738                 fn(nvmeq->dev, ctx, &cqe);
739         }
740
741         /* If the controller ignores the cq head doorbell and continuously
742          * writes to the queue, it is theoretically possible to wrap around
743          * the queue twice and mistakenly return IRQ_NONE.  Linux only
744          * requires that 0.1% of your interrupts are handled, so this isn't
745          * a big problem.
746          */
747         if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
748                 return 0;
749
750         writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
751         nvmeq->cq_head = head;
752         nvmeq->cq_phase = phase;
753
754         nvmeq->cqe_seen = 1;
755         return 1;
756 }
757
758 static void nvme_make_request(struct request_queue *q, struct bio *bio)
759 {
760         struct nvme_ns *ns = q->queuedata;
761         struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
762         int result = -EBUSY;
763
764         if (!nvmeq) {
765                 put_nvmeq(NULL);
766                 bio_endio(bio, -EIO);
767                 return;
768         }
769
770         spin_lock_irq(&nvmeq->q_lock);
771         if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
772                 result = nvme_submit_bio_queue(nvmeq, ns, bio);
773         if (unlikely(result)) {
774                 if (bio_list_empty(&nvmeq->sq_cong))
775                         add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
776                 bio_list_add(&nvmeq->sq_cong, bio);
777         }
778
779         nvme_process_cq(nvmeq);
780         spin_unlock_irq(&nvmeq->q_lock);
781         put_nvmeq(nvmeq);
782 }
783
784 static irqreturn_t nvme_irq(int irq, void *data)
785 {
786         irqreturn_t result;
787         struct nvme_queue *nvmeq = data;
788         spin_lock(&nvmeq->q_lock);
789         nvme_process_cq(nvmeq);
790         result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
791         nvmeq->cqe_seen = 0;
792         spin_unlock(&nvmeq->q_lock);
793         return result;
794 }
795
796 static irqreturn_t nvme_irq_check(int irq, void *data)
797 {
798         struct nvme_queue *nvmeq = data;
799         struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
800         if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
801                 return IRQ_NONE;
802         return IRQ_WAKE_THREAD;
803 }
804
805 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
806 {
807         spin_lock_irq(&nvmeq->q_lock);
808         cancel_cmdid(nvmeq, cmdid, NULL);
809         spin_unlock_irq(&nvmeq->q_lock);
810 }
811
812 struct sync_cmd_info {
813         struct task_struct *task;
814         u32 result;
815         int status;
816 };
817
818 static void sync_completion(struct nvme_dev *dev, void *ctx,
819                                                 struct nvme_completion *cqe)
820 {
821         struct sync_cmd_info *cmdinfo = ctx;
822         cmdinfo->result = le32_to_cpup(&cqe->result);
823         cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
824         wake_up_process(cmdinfo->task);
825 }
826
827 /*
828  * Returns 0 on success.  If the result is negative, it's a Linux error code;
829  * if the result is positive, it's an NVM Express status code
830  */
831 static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
832                                                 struct nvme_command *cmd,
833                                                 u32 *result, unsigned timeout)
834 {
835         int cmdid, ret;
836         struct sync_cmd_info cmdinfo;
837         struct nvme_queue *nvmeq;
838
839         nvmeq = lock_nvmeq(dev, q_idx);
840         if (!nvmeq) {
841                 unlock_nvmeq(nvmeq);
842                 return -ENODEV;
843         }
844
845         cmdinfo.task = current;
846         cmdinfo.status = -EINTR;
847
848         cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
849         if (cmdid < 0) {
850                 unlock_nvmeq(nvmeq);
851                 return cmdid;
852         }
853         cmd->common.command_id = cmdid;
854
855         set_current_state(TASK_KILLABLE);
856         ret = nvme_submit_cmd(nvmeq, cmd);
857         if (ret) {
858                 free_cmdid(nvmeq, cmdid, NULL);
859                 unlock_nvmeq(nvmeq);
860                 set_current_state(TASK_RUNNING);
861                 return ret;
862         }
863         unlock_nvmeq(nvmeq);
864         schedule_timeout(timeout);
865
866         if (cmdinfo.status == -EINTR) {
867                 nvmeq = lock_nvmeq(dev, q_idx);
868                 if (nvmeq)
869                         nvme_abort_command(nvmeq, cmdid);
870                 unlock_nvmeq(nvmeq);
871                 return -EINTR;
872         }
873
874         if (result)
875                 *result = cmdinfo.result;
876
877         return cmdinfo.status;
878 }
879
880 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
881                         struct nvme_command *cmd,
882                         struct async_cmd_info *cmdinfo, unsigned timeout)
883 {
884         int cmdid;
885
886         cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
887         if (cmdid < 0)
888                 return cmdid;
889         cmdinfo->status = -EINTR;
890         cmd->common.command_id = cmdid;
891         return nvme_submit_cmd(nvmeq, cmd);
892 }
893
894 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
895                                                                 u32 *result)
896 {
897         return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
898 }
899
900 int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
901                                                                 u32 *result)
902 {
903         return nvme_submit_sync_cmd(dev, smp_processor_id() + 1, cmd, result,
904                                                         NVME_IO_TIMEOUT);
905 }
906
907 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
908                 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
909 {
910         return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
911                                                                 ADMIN_TIMEOUT);
912 }
913
914 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
915 {
916         int status;
917         struct nvme_command c;
918
919         memset(&c, 0, sizeof(c));
920         c.delete_queue.opcode = opcode;
921         c.delete_queue.qid = cpu_to_le16(id);
922
923         status = nvme_submit_admin_cmd(dev, &c, NULL);
924         if (status)
925                 return -EIO;
926         return 0;
927 }
928
929 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
930                                                 struct nvme_queue *nvmeq)
931 {
932         int status;
933         struct nvme_command c;
934         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
935
936         memset(&c, 0, sizeof(c));
937         c.create_cq.opcode = nvme_admin_create_cq;
938         c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
939         c.create_cq.cqid = cpu_to_le16(qid);
940         c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
941         c.create_cq.cq_flags = cpu_to_le16(flags);
942         c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
943
944         status = nvme_submit_admin_cmd(dev, &c, NULL);
945         if (status)
946                 return -EIO;
947         return 0;
948 }
949
950 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
951                                                 struct nvme_queue *nvmeq)
952 {
953         int status;
954         struct nvme_command c;
955         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
956
957         memset(&c, 0, sizeof(c));
958         c.create_sq.opcode = nvme_admin_create_sq;
959         c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
960         c.create_sq.sqid = cpu_to_le16(qid);
961         c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
962         c.create_sq.sq_flags = cpu_to_le16(flags);
963         c.create_sq.cqid = cpu_to_le16(qid);
964
965         status = nvme_submit_admin_cmd(dev, &c, NULL);
966         if (status)
967                 return -EIO;
968         return 0;
969 }
970
971 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
972 {
973         return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
974 }
975
976 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
977 {
978         return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
979 }
980
981 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
982                                                         dma_addr_t dma_addr)
983 {
984         struct nvme_command c;
985
986         memset(&c, 0, sizeof(c));
987         c.identify.opcode = nvme_admin_identify;
988         c.identify.nsid = cpu_to_le32(nsid);
989         c.identify.prp1 = cpu_to_le64(dma_addr);
990         c.identify.cns = cpu_to_le32(cns);
991
992         return nvme_submit_admin_cmd(dev, &c, NULL);
993 }
994
995 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
996                                         dma_addr_t dma_addr, u32 *result)
997 {
998         struct nvme_command c;
999
1000         memset(&c, 0, sizeof(c));
1001         c.features.opcode = nvme_admin_get_features;
1002         c.features.nsid = cpu_to_le32(nsid);
1003         c.features.prp1 = cpu_to_le64(dma_addr);
1004         c.features.fid = cpu_to_le32(fid);
1005
1006         return nvme_submit_admin_cmd(dev, &c, result);
1007 }
1008
1009 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1010                                         dma_addr_t dma_addr, u32 *result)
1011 {
1012         struct nvme_command c;
1013
1014         memset(&c, 0, sizeof(c));
1015         c.features.opcode = nvme_admin_set_features;
1016         c.features.prp1 = cpu_to_le64(dma_addr);
1017         c.features.fid = cpu_to_le32(fid);
1018         c.features.dword11 = cpu_to_le32(dword11);
1019
1020         return nvme_submit_admin_cmd(dev, &c, result);
1021 }
1022
1023 /**
1024  * nvme_abort_cmd - Attempt aborting a command
1025  * @cmdid: Command id of a timed out IO
1026  * @queue: The queue with timed out IO
1027  *
1028  * Schedule controller reset if the command was already aborted once before and
1029  * still hasn't been returned to the driver, or if this is the admin queue.
1030  */
1031 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1032 {
1033         int a_cmdid;
1034         struct nvme_command cmd;
1035         struct nvme_dev *dev = nvmeq->dev;
1036         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1037         struct nvme_queue *adminq;
1038
1039         if (!nvmeq->qid || info[cmdid].aborted) {
1040                 if (work_busy(&dev->reset_work))
1041                         return;
1042                 list_del_init(&dev->node);
1043                 dev_warn(&dev->pci_dev->dev,
1044                         "I/O %d QID %d timeout, reset controller\n", cmdid,
1045                                                                 nvmeq->qid);
1046                 PREPARE_WORK(&dev->reset_work, nvme_reset_failed_dev);
1047                 queue_work(nvme_workq, &dev->reset_work);
1048                 return;
1049         }
1050
1051         if (!dev->abort_limit)
1052                 return;
1053
1054         adminq = rcu_dereference(dev->queues[0]);
1055         a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
1056                                                                 ADMIN_TIMEOUT);
1057         if (a_cmdid < 0)
1058                 return;
1059
1060         memset(&cmd, 0, sizeof(cmd));
1061         cmd.abort.opcode = nvme_admin_abort_cmd;
1062         cmd.abort.cid = cmdid;
1063         cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1064         cmd.abort.command_id = a_cmdid;
1065
1066         --dev->abort_limit;
1067         info[cmdid].aborted = 1;
1068         info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1069
1070         dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1071                                                         nvmeq->qid);
1072         nvme_submit_cmd(adminq, &cmd);
1073 }
1074
1075 /**
1076  * nvme_cancel_ios - Cancel outstanding I/Os
1077  * @queue: The queue to cancel I/Os on
1078  * @timeout: True to only cancel I/Os which have timed out
1079  */
1080 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1081 {
1082         int depth = nvmeq->q_depth - 1;
1083         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1084         unsigned long now = jiffies;
1085         int cmdid;
1086
1087         for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1088                 void *ctx;
1089                 nvme_completion_fn fn;
1090                 static struct nvme_completion cqe = {
1091                         .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1092                 };
1093
1094                 if (timeout && !time_after(now, info[cmdid].timeout))
1095                         continue;
1096                 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1097                         continue;
1098                 if (timeout && nvmeq->dev->initialized) {
1099                         nvme_abort_cmd(cmdid, nvmeq);
1100                         continue;
1101                 }
1102                 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1103                                                                 nvmeq->qid);
1104                 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1105                 fn(nvmeq->dev, ctx, &cqe);
1106         }
1107 }
1108
1109 static void nvme_free_queue(struct rcu_head *r)
1110 {
1111         struct nvme_queue *nvmeq = container_of(r, struct nvme_queue, r_head);
1112
1113         spin_lock_irq(&nvmeq->q_lock);
1114         while (bio_list_peek(&nvmeq->sq_cong)) {
1115                 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1116                 bio_endio(bio, -EIO);
1117         }
1118         spin_unlock_irq(&nvmeq->q_lock);
1119
1120         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1121                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1122         dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1123                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1124         kfree(nvmeq);
1125 }
1126
1127 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1128 {
1129         int i;
1130
1131         for (i = num_possible_cpus(); i > dev->queue_count - 1; i--)
1132                 rcu_assign_pointer(dev->queues[i], NULL);
1133         for (i = dev->queue_count - 1; i >= lowest; i--) {
1134                 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
1135                 rcu_assign_pointer(dev->queues[i], NULL);
1136                 call_rcu(&nvmeq->r_head, nvme_free_queue);
1137                 dev->queue_count--;
1138         }
1139 }
1140
1141 /**
1142  * nvme_suspend_queue - put queue into suspended state
1143  * @nvmeq - queue to suspend
1144  *
1145  * Returns 1 if already suspended, 0 otherwise.
1146  */
1147 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1148 {
1149         int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1150
1151         spin_lock_irq(&nvmeq->q_lock);
1152         if (nvmeq->q_suspended) {
1153                 spin_unlock_irq(&nvmeq->q_lock);
1154                 return 1;
1155         }
1156         nvmeq->q_suspended = 1;
1157         spin_unlock_irq(&nvmeq->q_lock);
1158
1159         irq_set_affinity_hint(vector, NULL);
1160         free_irq(vector, nvmeq);
1161
1162         return 0;
1163 }
1164
1165 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1166 {
1167         spin_lock_irq(&nvmeq->q_lock);
1168         nvme_process_cq(nvmeq);
1169         nvme_cancel_ios(nvmeq, false);
1170         spin_unlock_irq(&nvmeq->q_lock);
1171 }
1172
1173 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1174 {
1175         struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
1176
1177         if (!nvmeq)
1178                 return;
1179         if (nvme_suspend_queue(nvmeq))
1180                 return;
1181
1182         /* Don't tell the adapter to delete the admin queue.
1183          * Don't tell a removed adapter to delete IO queues. */
1184         if (qid && readl(&dev->bar->csts) != -1) {
1185                 adapter_delete_sq(dev, qid);
1186                 adapter_delete_cq(dev, qid);
1187         }
1188         nvme_clear_queue(nvmeq);
1189 }
1190
1191 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1192                                                         int depth, int vector)
1193 {
1194         struct device *dmadev = &dev->pci_dev->dev;
1195         unsigned extra = nvme_queue_extra(depth);
1196         struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1197         if (!nvmeq)
1198                 return NULL;
1199
1200         nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1201                                         &nvmeq->cq_dma_addr, GFP_KERNEL);
1202         if (!nvmeq->cqes)
1203                 goto free_nvmeq;
1204         memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1205
1206         nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1207                                         &nvmeq->sq_dma_addr, GFP_KERNEL);
1208         if (!nvmeq->sq_cmds)
1209                 goto free_cqdma;
1210
1211         nvmeq->q_dmadev = dmadev;
1212         nvmeq->dev = dev;
1213         snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1214                         dev->instance, qid);
1215         spin_lock_init(&nvmeq->q_lock);
1216         nvmeq->cq_head = 0;
1217         nvmeq->cq_phase = 1;
1218         init_waitqueue_head(&nvmeq->sq_full);
1219         init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1220         bio_list_init(&nvmeq->sq_cong);
1221         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1222         nvmeq->q_depth = depth;
1223         nvmeq->cq_vector = vector;
1224         nvmeq->qid = qid;
1225         nvmeq->q_suspended = 1;
1226         dev->queue_count++;
1227         rcu_assign_pointer(dev->queues[qid], nvmeq);
1228
1229         return nvmeq;
1230
1231  free_cqdma:
1232         dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1233                                                         nvmeq->cq_dma_addr);
1234  free_nvmeq:
1235         kfree(nvmeq);
1236         return NULL;
1237 }
1238
1239 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1240                                                         const char *name)
1241 {
1242         if (use_threaded_interrupts)
1243                 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1244                                         nvme_irq_check, nvme_irq, IRQF_SHARED,
1245                                         name, nvmeq);
1246         return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1247                                 IRQF_SHARED, name, nvmeq);
1248 }
1249
1250 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1251 {
1252         struct nvme_dev *dev = nvmeq->dev;
1253         unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1254
1255         nvmeq->sq_tail = 0;
1256         nvmeq->cq_head = 0;
1257         nvmeq->cq_phase = 1;
1258         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1259         memset(nvmeq->cmdid_data, 0, extra);
1260         memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1261         nvme_cancel_ios(nvmeq, false);
1262         nvmeq->q_suspended = 0;
1263 }
1264
1265 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1266 {
1267         struct nvme_dev *dev = nvmeq->dev;
1268         int result;
1269
1270         result = adapter_alloc_cq(dev, qid, nvmeq);
1271         if (result < 0)
1272                 return result;
1273
1274         result = adapter_alloc_sq(dev, qid, nvmeq);
1275         if (result < 0)
1276                 goto release_cq;
1277
1278         result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1279         if (result < 0)
1280                 goto release_sq;
1281
1282         spin_lock_irq(&nvmeq->q_lock);
1283         nvme_init_queue(nvmeq, qid);
1284         spin_unlock_irq(&nvmeq->q_lock);
1285
1286         return result;
1287
1288  release_sq:
1289         adapter_delete_sq(dev, qid);
1290  release_cq:
1291         adapter_delete_cq(dev, qid);
1292         return result;
1293 }
1294
1295 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1296 {
1297         unsigned long timeout;
1298         u32 bit = enabled ? NVME_CSTS_RDY : 0;
1299
1300         timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1301
1302         while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1303                 msleep(100);
1304                 if (fatal_signal_pending(current))
1305                         return -EINTR;
1306                 if (time_after(jiffies, timeout)) {
1307                         dev_err(&dev->pci_dev->dev,
1308                                 "Device not ready; aborting initialisation\n");
1309                         return -ENODEV;
1310                 }
1311         }
1312
1313         return 0;
1314 }
1315
1316 /*
1317  * If the device has been passed off to us in an enabled state, just clear
1318  * the enabled bit.  The spec says we should set the 'shutdown notification
1319  * bits', but doing so may cause the device to complete commands to the
1320  * admin queue ... and we don't know what memory that might be pointing at!
1321  */
1322 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1323 {
1324         u32 cc = readl(&dev->bar->cc);
1325
1326         if (cc & NVME_CC_ENABLE)
1327                 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1328         return nvme_wait_ready(dev, cap, false);
1329 }
1330
1331 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1332 {
1333         return nvme_wait_ready(dev, cap, true);
1334 }
1335
1336 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1337 {
1338         unsigned long timeout;
1339         u32 cc;
1340
1341         cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1342         writel(cc, &dev->bar->cc);
1343
1344         timeout = 2 * HZ + jiffies;
1345         while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1346                                                         NVME_CSTS_SHST_CMPLT) {
1347                 msleep(100);
1348                 if (fatal_signal_pending(current))
1349                         return -EINTR;
1350                 if (time_after(jiffies, timeout)) {
1351                         dev_err(&dev->pci_dev->dev,
1352                                 "Device shutdown incomplete; abort shutdown\n");
1353                         return -ENODEV;
1354                 }
1355         }
1356
1357         return 0;
1358 }
1359
1360 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1361 {
1362         int result;
1363         u32 aqa;
1364         u64 cap = readq(&dev->bar->cap);
1365         struct nvme_queue *nvmeq;
1366
1367         result = nvme_disable_ctrl(dev, cap);
1368         if (result < 0)
1369                 return result;
1370
1371         nvmeq = raw_nvmeq(dev, 0);
1372         if (!nvmeq) {
1373                 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1374                 if (!nvmeq)
1375                         return -ENOMEM;
1376         }
1377
1378         aqa = nvmeq->q_depth - 1;
1379         aqa |= aqa << 16;
1380
1381         dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1382         dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1383         dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1384         dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1385
1386         writel(aqa, &dev->bar->aqa);
1387         writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1388         writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1389         writel(dev->ctrl_config, &dev->bar->cc);
1390
1391         result = nvme_enable_ctrl(dev, cap);
1392         if (result)
1393                 return result;
1394
1395         result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1396         if (result)
1397                 return result;
1398
1399         spin_lock_irq(&nvmeq->q_lock);
1400         nvme_init_queue(nvmeq, 0);
1401         spin_unlock_irq(&nvmeq->q_lock);
1402         return result;
1403 }
1404
1405 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1406                                 unsigned long addr, unsigned length)
1407 {
1408         int i, err, count, nents, offset;
1409         struct scatterlist *sg;
1410         struct page **pages;
1411         struct nvme_iod *iod;
1412
1413         if (addr & 3)
1414                 return ERR_PTR(-EINVAL);
1415         if (!length || length > INT_MAX - PAGE_SIZE)
1416                 return ERR_PTR(-EINVAL);
1417
1418         offset = offset_in_page(addr);
1419         count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1420         pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1421         if (!pages)
1422                 return ERR_PTR(-ENOMEM);
1423
1424         err = get_user_pages_fast(addr, count, 1, pages);
1425         if (err < count) {
1426                 count = err;
1427                 err = -EFAULT;
1428                 goto put_pages;
1429         }
1430
1431         iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1432         sg = iod->sg;
1433         sg_init_table(sg, count);
1434         for (i = 0; i < count; i++) {
1435                 sg_set_page(&sg[i], pages[i],
1436                             min_t(unsigned, length, PAGE_SIZE - offset),
1437                             offset);
1438                 length -= (PAGE_SIZE - offset);
1439                 offset = 0;
1440         }
1441         sg_mark_end(&sg[i - 1]);
1442         iod->nents = count;
1443
1444         err = -ENOMEM;
1445         nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1446                                 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1447         if (!nents)
1448                 goto free_iod;
1449
1450         kfree(pages);
1451         return iod;
1452
1453  free_iod:
1454         kfree(iod);
1455  put_pages:
1456         for (i = 0; i < count; i++)
1457                 put_page(pages[i]);
1458         kfree(pages);
1459         return ERR_PTR(err);
1460 }
1461
1462 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1463                         struct nvme_iod *iod)
1464 {
1465         int i;
1466
1467         dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1468                                 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1469
1470         for (i = 0; i < iod->nents; i++)
1471                 put_page(sg_page(&iod->sg[i]));
1472 }
1473
1474 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1475 {
1476         struct nvme_dev *dev = ns->dev;
1477         struct nvme_user_io io;
1478         struct nvme_command c;
1479         unsigned length, meta_len;
1480         int status, i;
1481         struct nvme_iod *iod, *meta_iod = NULL;
1482         dma_addr_t meta_dma_addr;
1483         void *meta, *uninitialized_var(meta_mem);
1484
1485         if (copy_from_user(&io, uio, sizeof(io)))
1486                 return -EFAULT;
1487         length = (io.nblocks + 1) << ns->lba_shift;
1488         meta_len = (io.nblocks + 1) * ns->ms;
1489
1490         if (meta_len && ((io.metadata & 3) || !io.metadata))
1491                 return -EINVAL;
1492
1493         switch (io.opcode) {
1494         case nvme_cmd_write:
1495         case nvme_cmd_read:
1496         case nvme_cmd_compare:
1497                 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1498                 break;
1499         default:
1500                 return -EINVAL;
1501         }
1502
1503         if (IS_ERR(iod))
1504                 return PTR_ERR(iod);
1505
1506         memset(&c, 0, sizeof(c));
1507         c.rw.opcode = io.opcode;
1508         c.rw.flags = io.flags;
1509         c.rw.nsid = cpu_to_le32(ns->ns_id);
1510         c.rw.slba = cpu_to_le64(io.slba);
1511         c.rw.length = cpu_to_le16(io.nblocks);
1512         c.rw.control = cpu_to_le16(io.control);
1513         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1514         c.rw.reftag = cpu_to_le32(io.reftag);
1515         c.rw.apptag = cpu_to_le16(io.apptag);
1516         c.rw.appmask = cpu_to_le16(io.appmask);
1517
1518         if (meta_len) {
1519                 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1520                                                                 meta_len);
1521                 if (IS_ERR(meta_iod)) {
1522                         status = PTR_ERR(meta_iod);
1523                         meta_iod = NULL;
1524                         goto unmap;
1525                 }
1526
1527                 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1528                                                 &meta_dma_addr, GFP_KERNEL);
1529                 if (!meta_mem) {
1530                         status = -ENOMEM;
1531                         goto unmap;
1532                 }
1533
1534                 if (io.opcode & 1) {
1535                         int meta_offset = 0;
1536
1537                         for (i = 0; i < meta_iod->nents; i++) {
1538                                 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1539                                                 meta_iod->sg[i].offset;
1540                                 memcpy(meta_mem + meta_offset, meta,
1541                                                 meta_iod->sg[i].length);
1542                                 kunmap_atomic(meta);
1543                                 meta_offset += meta_iod->sg[i].length;
1544                         }
1545                 }
1546
1547                 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1548         }
1549
1550         length = nvme_setup_prps(dev, &c.common, iod, length, GFP_KERNEL);
1551
1552         if (length != (io.nblocks + 1) << ns->lba_shift)
1553                 status = -ENOMEM;
1554         else
1555                 status = nvme_submit_io_cmd(dev, &c, NULL);
1556
1557         if (meta_len) {
1558                 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1559                         int meta_offset = 0;
1560
1561                         for (i = 0; i < meta_iod->nents; i++) {
1562                                 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1563                                                 meta_iod->sg[i].offset;
1564                                 memcpy(meta, meta_mem + meta_offset,
1565                                                 meta_iod->sg[i].length);
1566                                 kunmap_atomic(meta);
1567                                 meta_offset += meta_iod->sg[i].length;
1568                         }
1569                 }
1570
1571                 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1572                                                                 meta_dma_addr);
1573         }
1574
1575  unmap:
1576         nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1577         nvme_free_iod(dev, iod);
1578
1579         if (meta_iod) {
1580                 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1581                 nvme_free_iod(dev, meta_iod);
1582         }
1583
1584         return status;
1585 }
1586
1587 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1588                                         struct nvme_admin_cmd __user *ucmd)
1589 {
1590         struct nvme_admin_cmd cmd;
1591         struct nvme_command c;
1592         int status, length;
1593         struct nvme_iod *uninitialized_var(iod);
1594         unsigned timeout;
1595
1596         if (!capable(CAP_SYS_ADMIN))
1597                 return -EACCES;
1598         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1599                 return -EFAULT;
1600
1601         memset(&c, 0, sizeof(c));
1602         c.common.opcode = cmd.opcode;
1603         c.common.flags = cmd.flags;
1604         c.common.nsid = cpu_to_le32(cmd.nsid);
1605         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1606         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1607         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1608         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1609         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1610         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1611         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1612         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1613
1614         length = cmd.data_len;
1615         if (cmd.data_len) {
1616                 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1617                                                                 length);
1618                 if (IS_ERR(iod))
1619                         return PTR_ERR(iod);
1620                 length = nvme_setup_prps(dev, &c.common, iod, length,
1621                                                                 GFP_KERNEL);
1622         }
1623
1624         timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1625                                                                 ADMIN_TIMEOUT;
1626         if (length != cmd.data_len)
1627                 status = -ENOMEM;
1628         else
1629                 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
1630
1631         if (cmd.data_len) {
1632                 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1633                 nvme_free_iod(dev, iod);
1634         }
1635
1636         if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1637                                                         sizeof(cmd.result)))
1638                 status = -EFAULT;
1639
1640         return status;
1641 }
1642
1643 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1644                                                         unsigned long arg)
1645 {
1646         struct nvme_ns *ns = bdev->bd_disk->private_data;
1647
1648         switch (cmd) {
1649         case NVME_IOCTL_ID:
1650                 force_successful_syscall_return();
1651                 return ns->ns_id;
1652         case NVME_IOCTL_ADMIN_CMD:
1653                 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1654         case NVME_IOCTL_SUBMIT_IO:
1655                 return nvme_submit_io(ns, (void __user *)arg);
1656         case SG_GET_VERSION_NUM:
1657                 return nvme_sg_get_version_num((void __user *)arg);
1658         case SG_IO:
1659                 return nvme_sg_io(ns, (void __user *)arg);
1660         default:
1661                 return -ENOTTY;
1662         }
1663 }
1664
1665 #ifdef CONFIG_COMPAT
1666 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1667                                         unsigned int cmd, unsigned long arg)
1668 {
1669         struct nvme_ns *ns = bdev->bd_disk->private_data;
1670
1671         switch (cmd) {
1672         case SG_IO:
1673                 return nvme_sg_io32(ns, arg);
1674         }
1675         return nvme_ioctl(bdev, mode, cmd, arg);
1676 }
1677 #else
1678 #define nvme_compat_ioctl       NULL
1679 #endif
1680
1681 static int nvme_open(struct block_device *bdev, fmode_t mode)
1682 {
1683         struct nvme_ns *ns = bdev->bd_disk->private_data;
1684         struct nvme_dev *dev = ns->dev;
1685
1686         kref_get(&dev->kref);
1687         return 0;
1688 }
1689
1690 static void nvme_free_dev(struct kref *kref);
1691
1692 static void nvme_release(struct gendisk *disk, fmode_t mode)
1693 {
1694         struct nvme_ns *ns = disk->private_data;
1695         struct nvme_dev *dev = ns->dev;
1696
1697         kref_put(&dev->kref, nvme_free_dev);
1698 }
1699
1700 static const struct block_device_operations nvme_fops = {
1701         .owner          = THIS_MODULE,
1702         .ioctl          = nvme_ioctl,
1703         .compat_ioctl   = nvme_compat_ioctl,
1704         .open           = nvme_open,
1705         .release        = nvme_release,
1706 };
1707
1708 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1709 {
1710         while (bio_list_peek(&nvmeq->sq_cong)) {
1711                 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1712                 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1713
1714                 if (bio_list_empty(&nvmeq->sq_cong))
1715                         remove_wait_queue(&nvmeq->sq_full,
1716                                                         &nvmeq->sq_cong_wait);
1717                 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1718                         if (bio_list_empty(&nvmeq->sq_cong))
1719                                 add_wait_queue(&nvmeq->sq_full,
1720                                                         &nvmeq->sq_cong_wait);
1721                         bio_list_add_head(&nvmeq->sq_cong, bio);
1722                         break;
1723                 }
1724         }
1725 }
1726
1727 static int nvme_kthread(void *data)
1728 {
1729         struct nvme_dev *dev, *next;
1730
1731         while (!kthread_should_stop()) {
1732                 set_current_state(TASK_INTERRUPTIBLE);
1733                 spin_lock(&dev_list_lock);
1734                 list_for_each_entry_safe(dev, next, &dev_list, node) {
1735                         int i;
1736                         if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1737                                                         dev->initialized) {
1738                                 if (work_busy(&dev->reset_work))
1739                                         continue;
1740                                 list_del_init(&dev->node);
1741                                 dev_warn(&dev->pci_dev->dev,
1742                                         "Failed status, reset controller\n");
1743                                 PREPARE_WORK(&dev->reset_work,
1744                                                         nvme_reset_failed_dev);
1745                                 queue_work(nvme_workq, &dev->reset_work);
1746                                 continue;
1747                         }
1748                         rcu_read_lock();
1749                         for (i = 0; i < dev->queue_count; i++) {
1750                                 struct nvme_queue *nvmeq =
1751                                                 rcu_dereference(dev->queues[i]);
1752                                 if (!nvmeq)
1753                                         continue;
1754                                 spin_lock_irq(&nvmeq->q_lock);
1755                                 if (nvmeq->q_suspended)
1756                                         goto unlock;
1757                                 nvme_process_cq(nvmeq);
1758                                 nvme_cancel_ios(nvmeq, true);
1759                                 nvme_resubmit_bios(nvmeq);
1760  unlock:
1761                                 spin_unlock_irq(&nvmeq->q_lock);
1762                         }
1763                         rcu_read_unlock();
1764                 }
1765                 spin_unlock(&dev_list_lock);
1766                 schedule_timeout(round_jiffies_relative(HZ));
1767         }
1768         return 0;
1769 }
1770
1771 static void nvme_config_discard(struct nvme_ns *ns)
1772 {
1773         u32 logical_block_size = queue_logical_block_size(ns->queue);
1774         ns->queue->limits.discard_zeroes_data = 0;
1775         ns->queue->limits.discard_alignment = logical_block_size;
1776         ns->queue->limits.discard_granularity = logical_block_size;
1777         ns->queue->limits.max_discard_sectors = 0xffffffff;
1778         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1779 }
1780
1781 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1782                         struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1783 {
1784         struct nvme_ns *ns;
1785         struct gendisk *disk;
1786         int lbaf;
1787
1788         if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1789                 return NULL;
1790
1791         ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1792         if (!ns)
1793                 return NULL;
1794         ns->queue = blk_alloc_queue(GFP_KERNEL);
1795         if (!ns->queue)
1796                 goto out_free_ns;
1797         ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1798         queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1799         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1800         blk_queue_make_request(ns->queue, nvme_make_request);
1801         ns->dev = dev;
1802         ns->queue->queuedata = ns;
1803
1804         disk = alloc_disk(0);
1805         if (!disk)
1806                 goto out_free_queue;
1807         ns->ns_id = nsid;
1808         ns->disk = disk;
1809         lbaf = id->flbas & 0xf;
1810         ns->lba_shift = id->lbaf[lbaf].ds;
1811         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1812         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1813         if (dev->max_hw_sectors)
1814                 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1815
1816         disk->major = nvme_major;
1817         disk->first_minor = 0;
1818         disk->fops = &nvme_fops;
1819         disk->private_data = ns;
1820         disk->queue = ns->queue;
1821         disk->driverfs_dev = &dev->pci_dev->dev;
1822         disk->flags = GENHD_FL_EXT_DEVT;
1823         sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1824         set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1825
1826         if (dev->oncs & NVME_CTRL_ONCS_DSM)
1827                 nvme_config_discard(ns);
1828
1829         return ns;
1830
1831  out_free_queue:
1832         blk_cleanup_queue(ns->queue);
1833  out_free_ns:
1834         kfree(ns);
1835         return NULL;
1836 }
1837
1838 static int set_queue_count(struct nvme_dev *dev, int count)
1839 {
1840         int status;
1841         u32 result;
1842         u32 q_count = (count - 1) | ((count - 1) << 16);
1843
1844         status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
1845                                                                 &result);
1846         if (status)
1847                 return status < 0 ? -EIO : -EBUSY;
1848         return min(result & 0xffff, result >> 16) + 1;
1849 }
1850
1851 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
1852 {
1853         return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
1854 }
1855
1856 static int nvme_setup_io_queues(struct nvme_dev *dev)
1857 {
1858         struct nvme_queue *adminq = raw_nvmeq(dev, 0);
1859         struct pci_dev *pdev = dev->pci_dev;
1860         int result, cpu, i, vecs, nr_io_queues, size, q_depth;
1861
1862         nr_io_queues = num_online_cpus();
1863         result = set_queue_count(dev, nr_io_queues);
1864         if (result < 0)
1865                 return result;
1866         if (result < nr_io_queues)
1867                 nr_io_queues = result;
1868
1869         size = db_bar_size(dev, nr_io_queues);
1870         if (size > 8192) {
1871                 iounmap(dev->bar);
1872                 do {
1873                         dev->bar = ioremap(pci_resource_start(pdev, 0), size);
1874                         if (dev->bar)
1875                                 break;
1876                         if (!--nr_io_queues)
1877                                 return -ENOMEM;
1878                         size = db_bar_size(dev, nr_io_queues);
1879                 } while (1);
1880                 dev->dbs = ((void __iomem *)dev->bar) + 4096;
1881                 adminq->q_db = dev->dbs;
1882         }
1883
1884         /* Deregister the admin queue's interrupt */
1885         free_irq(dev->entry[0].vector, adminq);
1886
1887         vecs = nr_io_queues;
1888         for (i = 0; i < vecs; i++)
1889                 dev->entry[i].entry = i;
1890         for (;;) {
1891                 result = pci_enable_msix(pdev, dev->entry, vecs);
1892                 if (result <= 0)
1893                         break;
1894                 vecs = result;
1895         }
1896
1897         if (result < 0) {
1898                 vecs = nr_io_queues;
1899                 if (vecs > 32)
1900                         vecs = 32;
1901                 for (;;) {
1902                         result = pci_enable_msi_block(pdev, vecs);
1903                         if (result == 0) {
1904                                 for (i = 0; i < vecs; i++)
1905                                         dev->entry[i].vector = i + pdev->irq;
1906                                 break;
1907                         } else if (result < 0) {
1908                                 vecs = 1;
1909                                 break;
1910                         }
1911                         vecs = result;
1912                 }
1913         }
1914
1915         /*
1916          * Should investigate if there's a performance win from allocating
1917          * more queues than interrupt vectors; it might allow the submission
1918          * path to scale better, even if the receive path is limited by the
1919          * number of interrupts.
1920          */
1921         nr_io_queues = vecs;
1922
1923         result = queue_request_irq(dev, adminq, adminq->irqname);
1924         if (result) {
1925                 adminq->q_suspended = 1;
1926                 goto free_queues;
1927         }
1928
1929         /* Free previously allocated queues that are no longer usable */
1930         nvme_free_queues(dev, nr_io_queues);
1931
1932         cpu = cpumask_first(cpu_online_mask);
1933         for (i = 0; i < nr_io_queues; i++) {
1934                 irq_set_affinity_hint(dev->entry[i].vector, get_cpu_mask(cpu));
1935                 cpu = cpumask_next(cpu, cpu_online_mask);
1936         }
1937
1938         q_depth = min_t(int, NVME_CAP_MQES(readq(&dev->bar->cap)) + 1,
1939                                                                 NVME_Q_DEPTH);
1940         for (i = dev->queue_count - 1; i < nr_io_queues; i++) {
1941                 if (!nvme_alloc_queue(dev, i + 1, q_depth, i)) {
1942                         result = -ENOMEM;
1943                         goto free_queues;
1944                 }
1945         }
1946
1947         for (; i < num_possible_cpus(); i++) {
1948                 int target = i % rounddown_pow_of_two(dev->queue_count - 1);
1949                 rcu_assign_pointer(dev->queues[i + 1], dev->queues[target + 1]);
1950         }
1951
1952         for (i = 1; i < dev->queue_count; i++) {
1953                 result = nvme_create_queue(raw_nvmeq(dev, i), i);
1954                 if (result) {
1955                         for (--i; i > 0; i--)
1956                                 nvme_disable_queue(dev, i);
1957                         goto free_queues;
1958                 }
1959         }
1960
1961         return 0;
1962
1963  free_queues:
1964         nvme_free_queues(dev, 1);
1965         return result;
1966 }
1967
1968 /*
1969  * Return: error value if an error occurred setting up the queues or calling
1970  * Identify Device.  0 if these succeeded, even if adding some of the
1971  * namespaces failed.  At the moment, these failures are silent.  TBD which
1972  * failures should be reported.
1973  */
1974 static int nvme_dev_add(struct nvme_dev *dev)
1975 {
1976         struct pci_dev *pdev = dev->pci_dev;
1977         int res;
1978         unsigned nn, i;
1979         struct nvme_ns *ns;
1980         struct nvme_id_ctrl *ctrl;
1981         struct nvme_id_ns *id_ns;
1982         void *mem;
1983         dma_addr_t dma_addr;
1984         int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
1985
1986         mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
1987         if (!mem)
1988                 return -ENOMEM;
1989
1990         res = nvme_identify(dev, 0, 1, dma_addr);
1991         if (res) {
1992                 res = -EIO;
1993                 goto out;
1994         }
1995
1996         ctrl = mem;
1997         nn = le32_to_cpup(&ctrl->nn);
1998         dev->oncs = le16_to_cpup(&ctrl->oncs);
1999         dev->abort_limit = ctrl->acl + 1;
2000         memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2001         memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2002         memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2003         if (ctrl->mdts)
2004                 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2005         if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2006                         (pdev->device == 0x0953) && ctrl->vs[3])
2007                 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2008
2009         id_ns = mem;
2010         for (i = 1; i <= nn; i++) {
2011                 res = nvme_identify(dev, i, 0, dma_addr);
2012                 if (res)
2013                         continue;
2014
2015                 if (id_ns->ncap == 0)
2016                         continue;
2017
2018                 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2019                                                         dma_addr + 4096, NULL);
2020                 if (res)
2021                         memset(mem + 4096, 0, 4096);
2022
2023                 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2024                 if (ns)
2025                         list_add_tail(&ns->list, &dev->namespaces);
2026         }
2027         list_for_each_entry(ns, &dev->namespaces, list)
2028                 add_disk(ns->disk);
2029         res = 0;
2030
2031  out:
2032         dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2033         return res;
2034 }
2035
2036 static int nvme_dev_map(struct nvme_dev *dev)
2037 {
2038         int bars, result = -ENOMEM;
2039         struct pci_dev *pdev = dev->pci_dev;
2040
2041         if (pci_enable_device_mem(pdev))
2042                 return result;
2043
2044         dev->entry[0].vector = pdev->irq;
2045         pci_set_master(pdev);
2046         bars = pci_select_bars(pdev, IORESOURCE_MEM);
2047         if (pci_request_selected_regions(pdev, bars, "nvme"))
2048                 goto disable_pci;
2049
2050         if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2051             dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2052                 goto disable;
2053
2054         dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2055         if (!dev->bar)
2056                 goto disable;
2057         if (readl(&dev->bar->csts) == -1) {
2058                 result = -ENODEV;
2059                 goto unmap;
2060         }
2061         dev->db_stride = 1 << NVME_CAP_STRIDE(readq(&dev->bar->cap));
2062         dev->dbs = ((void __iomem *)dev->bar) + 4096;
2063
2064         return 0;
2065
2066  unmap:
2067         iounmap(dev->bar);
2068         dev->bar = NULL;
2069  disable:
2070         pci_release_regions(pdev);
2071  disable_pci:
2072         pci_disable_device(pdev);
2073         return result;
2074 }
2075
2076 static void nvme_dev_unmap(struct nvme_dev *dev)
2077 {
2078         if (dev->pci_dev->msi_enabled)
2079                 pci_disable_msi(dev->pci_dev);
2080         else if (dev->pci_dev->msix_enabled)
2081                 pci_disable_msix(dev->pci_dev);
2082
2083         if (dev->bar) {
2084                 iounmap(dev->bar);
2085                 dev->bar = NULL;
2086                 pci_release_regions(dev->pci_dev);
2087         }
2088
2089         if (pci_is_enabled(dev->pci_dev))
2090                 pci_disable_device(dev->pci_dev);
2091 }
2092
2093 struct nvme_delq_ctx {
2094         struct task_struct *waiter;
2095         struct kthread_worker *worker;
2096         atomic_t refcount;
2097 };
2098
2099 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2100 {
2101         dq->waiter = current;
2102         mb();
2103
2104         for (;;) {
2105                 set_current_state(TASK_KILLABLE);
2106                 if (!atomic_read(&dq->refcount))
2107                         break;
2108                 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2109                                         fatal_signal_pending(current)) {
2110                         set_current_state(TASK_RUNNING);
2111
2112                         nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2113                         nvme_disable_queue(dev, 0);
2114
2115                         send_sig(SIGKILL, dq->worker->task, 1);
2116                         flush_kthread_worker(dq->worker);
2117                         return;
2118                 }
2119         }
2120         set_current_state(TASK_RUNNING);
2121 }
2122
2123 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2124 {
2125         atomic_dec(&dq->refcount);
2126         if (dq->waiter)
2127                 wake_up_process(dq->waiter);
2128 }
2129
2130 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2131 {
2132         atomic_inc(&dq->refcount);
2133         return dq;
2134 }
2135
2136 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2137 {
2138         struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2139
2140         nvme_clear_queue(nvmeq);
2141         nvme_put_dq(dq);
2142 }
2143
2144 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2145                                                 kthread_work_func_t fn)
2146 {
2147         struct nvme_command c;
2148
2149         memset(&c, 0, sizeof(c));
2150         c.delete_queue.opcode = opcode;
2151         c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2152
2153         init_kthread_work(&nvmeq->cmdinfo.work, fn);
2154         return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2155 }
2156
2157 static void nvme_del_cq_work_handler(struct kthread_work *work)
2158 {
2159         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2160                                                         cmdinfo.work);
2161         nvme_del_queue_end(nvmeq);
2162 }
2163
2164 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2165 {
2166         return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2167                                                 nvme_del_cq_work_handler);
2168 }
2169
2170 static void nvme_del_sq_work_handler(struct kthread_work *work)
2171 {
2172         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2173                                                         cmdinfo.work);
2174         int status = nvmeq->cmdinfo.status;
2175
2176         if (!status)
2177                 status = nvme_delete_cq(nvmeq);
2178         if (status)
2179                 nvme_del_queue_end(nvmeq);
2180 }
2181
2182 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2183 {
2184         return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2185                                                 nvme_del_sq_work_handler);
2186 }
2187
2188 static void nvme_del_queue_start(struct kthread_work *work)
2189 {
2190         struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2191                                                         cmdinfo.work);
2192         allow_signal(SIGKILL);
2193         if (nvme_delete_sq(nvmeq))
2194                 nvme_del_queue_end(nvmeq);
2195 }
2196
2197 static void nvme_disable_io_queues(struct nvme_dev *dev)
2198 {
2199         int i;
2200         DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2201         struct nvme_delq_ctx dq;
2202         struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2203                                         &worker, "nvme%d", dev->instance);
2204
2205         if (IS_ERR(kworker_task)) {
2206                 dev_err(&dev->pci_dev->dev,
2207                         "Failed to create queue del task\n");
2208                 for (i = dev->queue_count - 1; i > 0; i--)
2209                         nvme_disable_queue(dev, i);
2210                 return;
2211         }
2212
2213         dq.waiter = NULL;
2214         atomic_set(&dq.refcount, 0);
2215         dq.worker = &worker;
2216         for (i = dev->queue_count - 1; i > 0; i--) {
2217                 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2218
2219                 if (nvme_suspend_queue(nvmeq))
2220                         continue;
2221                 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2222                 nvmeq->cmdinfo.worker = dq.worker;
2223                 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2224                 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2225         }
2226         nvme_wait_dq(&dq, dev);
2227         kthread_stop(kworker_task);
2228 }
2229
2230 static void nvme_dev_shutdown(struct nvme_dev *dev)
2231 {
2232         int i;
2233
2234         dev->initialized = 0;
2235
2236         spin_lock(&dev_list_lock);
2237         list_del_init(&dev->node);
2238         spin_unlock(&dev_list_lock);
2239
2240         if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2241                 for (i = dev->queue_count - 1; i >= 0; i--) {
2242                         struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2243                         nvme_suspend_queue(nvmeq);
2244                         nvme_clear_queue(nvmeq);
2245                 }
2246         } else {
2247                 nvme_disable_io_queues(dev);
2248                 nvme_shutdown_ctrl(dev);
2249                 nvme_disable_queue(dev, 0);
2250         }
2251         nvme_dev_unmap(dev);
2252 }
2253
2254 static void nvme_dev_remove(struct nvme_dev *dev)
2255 {
2256         struct nvme_ns *ns;
2257
2258         list_for_each_entry(ns, &dev->namespaces, list) {
2259                 if (ns->disk->flags & GENHD_FL_UP)
2260                         del_gendisk(ns->disk);
2261                 if (!blk_queue_dying(ns->queue))
2262                         blk_cleanup_queue(ns->queue);
2263         }
2264 }
2265
2266 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2267 {
2268         struct device *dmadev = &dev->pci_dev->dev;
2269         dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2270                                                 PAGE_SIZE, PAGE_SIZE, 0);
2271         if (!dev->prp_page_pool)
2272                 return -ENOMEM;
2273
2274         /* Optimisation for I/Os between 4k and 128k */
2275         dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2276                                                 256, 256, 0);
2277         if (!dev->prp_small_pool) {
2278                 dma_pool_destroy(dev->prp_page_pool);
2279                 return -ENOMEM;
2280         }
2281         return 0;
2282 }
2283
2284 static void nvme_release_prp_pools(struct nvme_dev *dev)
2285 {
2286         dma_pool_destroy(dev->prp_page_pool);
2287         dma_pool_destroy(dev->prp_small_pool);
2288 }
2289
2290 static DEFINE_IDA(nvme_instance_ida);
2291
2292 static int nvme_set_instance(struct nvme_dev *dev)
2293 {
2294         int instance, error;
2295
2296         do {
2297                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2298                         return -ENODEV;
2299
2300                 spin_lock(&dev_list_lock);
2301                 error = ida_get_new(&nvme_instance_ida, &instance);
2302                 spin_unlock(&dev_list_lock);
2303         } while (error == -EAGAIN);
2304
2305         if (error)
2306                 return -ENODEV;
2307
2308         dev->instance = instance;
2309         return 0;
2310 }
2311
2312 static void nvme_release_instance(struct nvme_dev *dev)
2313 {
2314         spin_lock(&dev_list_lock);
2315         ida_remove(&nvme_instance_ida, dev->instance);
2316         spin_unlock(&dev_list_lock);
2317 }
2318
2319 static void nvme_free_namespaces(struct nvme_dev *dev)
2320 {
2321         struct nvme_ns *ns, *next;
2322
2323         list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2324                 list_del(&ns->list);
2325                 put_disk(ns->disk);
2326                 kfree(ns);
2327         }
2328 }
2329
2330 static void nvme_free_dev(struct kref *kref)
2331 {
2332         struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2333
2334         nvme_free_namespaces(dev);
2335         kfree(dev->queues);
2336         kfree(dev->entry);
2337         kfree(dev);
2338 }
2339
2340 static int nvme_dev_open(struct inode *inode, struct file *f)
2341 {
2342         struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2343                                                                 miscdev);
2344         kref_get(&dev->kref);
2345         f->private_data = dev;
2346         return 0;
2347 }
2348
2349 static int nvme_dev_release(struct inode *inode, struct file *f)
2350 {
2351         struct nvme_dev *dev = f->private_data;
2352         kref_put(&dev->kref, nvme_free_dev);
2353         return 0;
2354 }
2355
2356 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2357 {
2358         struct nvme_dev *dev = f->private_data;
2359         switch (cmd) {
2360         case NVME_IOCTL_ADMIN_CMD:
2361                 return nvme_user_admin_cmd(dev, (void __user *)arg);
2362         default:
2363                 return -ENOTTY;
2364         }
2365 }
2366
2367 static const struct file_operations nvme_dev_fops = {
2368         .owner          = THIS_MODULE,
2369         .open           = nvme_dev_open,
2370         .release        = nvme_dev_release,
2371         .unlocked_ioctl = nvme_dev_ioctl,
2372         .compat_ioctl   = nvme_dev_ioctl,
2373 };
2374
2375 static int nvme_dev_start(struct nvme_dev *dev)
2376 {
2377         int result;
2378
2379         result = nvme_dev_map(dev);
2380         if (result)
2381                 return result;
2382
2383         result = nvme_configure_admin_queue(dev);
2384         if (result)
2385                 goto unmap;
2386
2387         spin_lock(&dev_list_lock);
2388         list_add(&dev->node, &dev_list);
2389         spin_unlock(&dev_list_lock);
2390
2391         result = nvme_setup_io_queues(dev);
2392         if (result && result != -EBUSY)
2393                 goto disable;
2394
2395         return result;
2396
2397  disable:
2398         nvme_disable_queue(dev, 0);
2399         spin_lock(&dev_list_lock);
2400         list_del_init(&dev->node);
2401         spin_unlock(&dev_list_lock);
2402  unmap:
2403         nvme_dev_unmap(dev);
2404         return result;
2405 }
2406
2407 static int nvme_remove_dead_ctrl(void *arg)
2408 {
2409         struct nvme_dev *dev = (struct nvme_dev *)arg;
2410         struct pci_dev *pdev = dev->pci_dev;
2411
2412         if (pci_get_drvdata(pdev))
2413                 pci_stop_and_remove_bus_device(pdev);
2414         kref_put(&dev->kref, nvme_free_dev);
2415         return 0;
2416 }
2417
2418 static void nvme_remove_disks(struct work_struct *ws)
2419 {
2420         struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2421
2422         nvme_dev_remove(dev);
2423         nvme_free_queues(dev, 1);
2424 }
2425
2426 static int nvme_dev_resume(struct nvme_dev *dev)
2427 {
2428         int ret;
2429
2430         ret = nvme_dev_start(dev);
2431         if (ret && ret != -EBUSY)
2432                 return ret;
2433         if (ret == -EBUSY) {
2434                 spin_lock(&dev_list_lock);
2435                 PREPARE_WORK(&dev->reset_work, nvme_remove_disks);
2436                 queue_work(nvme_workq, &dev->reset_work);
2437                 spin_unlock(&dev_list_lock);
2438         }
2439         dev->initialized = 1;
2440         return 0;
2441 }
2442
2443 static void nvme_dev_reset(struct nvme_dev *dev)
2444 {
2445         nvme_dev_shutdown(dev);
2446         if (nvme_dev_resume(dev)) {
2447                 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2448                 kref_get(&dev->kref);
2449                 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2450                                                         dev->instance))) {
2451                         dev_err(&dev->pci_dev->dev,
2452                                 "Failed to start controller remove task\n");
2453                         kref_put(&dev->kref, nvme_free_dev);
2454                 }
2455         }
2456 }
2457
2458 static void nvme_reset_failed_dev(struct work_struct *ws)
2459 {
2460         struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2461         nvme_dev_reset(dev);
2462 }
2463
2464 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2465 {
2466         int result = -ENOMEM;
2467         struct nvme_dev *dev;
2468
2469         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2470         if (!dev)
2471                 return -ENOMEM;
2472         dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2473                                                                 GFP_KERNEL);
2474         if (!dev->entry)
2475                 goto free;
2476         dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2477                                                                 GFP_KERNEL);
2478         if (!dev->queues)
2479                 goto free;
2480
2481         INIT_LIST_HEAD(&dev->namespaces);
2482         INIT_WORK(&dev->reset_work, nvme_reset_failed_dev);
2483         dev->pci_dev = pdev;
2484         pci_set_drvdata(pdev, dev);
2485         result = nvme_set_instance(dev);
2486         if (result)
2487                 goto free;
2488
2489         result = nvme_setup_prp_pools(dev);
2490         if (result)
2491                 goto release;
2492
2493         kref_init(&dev->kref);
2494         result = nvme_dev_start(dev);
2495         if (result) {
2496                 if (result == -EBUSY)
2497                         goto create_cdev;
2498                 goto release_pools;
2499         }
2500
2501         result = nvme_dev_add(dev);
2502         if (result)
2503                 goto shutdown;
2504
2505  create_cdev:
2506         scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2507         dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2508         dev->miscdev.parent = &pdev->dev;
2509         dev->miscdev.name = dev->name;
2510         dev->miscdev.fops = &nvme_dev_fops;
2511         result = misc_register(&dev->miscdev);
2512         if (result)
2513                 goto remove;
2514
2515         dev->initialized = 1;
2516         return 0;
2517
2518  remove:
2519         nvme_dev_remove(dev);
2520         nvme_free_namespaces(dev);
2521  shutdown:
2522         nvme_dev_shutdown(dev);
2523  release_pools:
2524         nvme_free_queues(dev, 0);
2525         nvme_release_prp_pools(dev);
2526  release:
2527         nvme_release_instance(dev);
2528  free:
2529         kfree(dev->queues);
2530         kfree(dev->entry);
2531         kfree(dev);
2532         return result;
2533 }
2534
2535 static void nvme_shutdown(struct pci_dev *pdev)
2536 {
2537         struct nvme_dev *dev = pci_get_drvdata(pdev);
2538         nvme_dev_shutdown(dev);
2539 }
2540
2541 static void nvme_remove(struct pci_dev *pdev)
2542 {
2543         struct nvme_dev *dev = pci_get_drvdata(pdev);
2544
2545         spin_lock(&dev_list_lock);
2546         list_del_init(&dev->node);
2547         spin_unlock(&dev_list_lock);
2548
2549         pci_set_drvdata(pdev, NULL);
2550         flush_work(&dev->reset_work);
2551         misc_deregister(&dev->miscdev);
2552         nvme_dev_remove(dev);
2553         nvme_dev_shutdown(dev);
2554         nvme_free_queues(dev, 0);
2555         rcu_barrier();
2556         nvme_release_instance(dev);
2557         nvme_release_prp_pools(dev);
2558         kref_put(&dev->kref, nvme_free_dev);
2559 }
2560
2561 /* These functions are yet to be implemented */
2562 #define nvme_error_detected NULL
2563 #define nvme_dump_registers NULL
2564 #define nvme_link_reset NULL
2565 #define nvme_slot_reset NULL
2566 #define nvme_error_resume NULL
2567
2568 #ifdef CONFIG_PM_SLEEP
2569 static int nvme_suspend(struct device *dev)
2570 {
2571         struct pci_dev *pdev = to_pci_dev(dev);
2572         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2573
2574         nvme_dev_shutdown(ndev);
2575         return 0;
2576 }
2577
2578 static int nvme_resume(struct device *dev)
2579 {
2580         struct pci_dev *pdev = to_pci_dev(dev);
2581         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2582
2583         if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2584                 PREPARE_WORK(&ndev->reset_work, nvme_reset_failed_dev);
2585                 queue_work(nvme_workq, &ndev->reset_work);
2586         }
2587         return 0;
2588 }
2589 #endif
2590
2591 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2592
2593 static const struct pci_error_handlers nvme_err_handler = {
2594         .error_detected = nvme_error_detected,
2595         .mmio_enabled   = nvme_dump_registers,
2596         .link_reset     = nvme_link_reset,
2597         .slot_reset     = nvme_slot_reset,
2598         .resume         = nvme_error_resume,
2599 };
2600
2601 /* Move to pci_ids.h later */
2602 #define PCI_CLASS_STORAGE_EXPRESS       0x010802
2603
2604 static DEFINE_PCI_DEVICE_TABLE(nvme_id_table) = {
2605         { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2606         { 0, }
2607 };
2608 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2609
2610 static struct pci_driver nvme_driver = {
2611         .name           = "nvme",
2612         .id_table       = nvme_id_table,
2613         .probe          = nvme_probe,
2614         .remove         = nvme_remove,
2615         .shutdown       = nvme_shutdown,
2616         .driver         = {
2617                 .pm     = &nvme_dev_pm_ops,
2618         },
2619         .err_handler    = &nvme_err_handler,
2620 };
2621
2622 static int __init nvme_init(void)
2623 {
2624         int result;
2625
2626         nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2627         if (IS_ERR(nvme_thread))
2628                 return PTR_ERR(nvme_thread);
2629
2630         result = -ENOMEM;
2631         nvme_workq = create_singlethread_workqueue("nvme");
2632         if (!nvme_workq)
2633                 goto kill_kthread;
2634
2635         result = register_blkdev(nvme_major, "nvme");
2636         if (result < 0)
2637                 goto kill_workq;
2638         else if (result > 0)
2639                 nvme_major = result;
2640
2641         result = pci_register_driver(&nvme_driver);
2642         if (result)
2643                 goto unregister_blkdev;
2644         return 0;
2645
2646  unregister_blkdev:
2647         unregister_blkdev(nvme_major, "nvme");
2648  kill_workq:
2649         destroy_workqueue(nvme_workq);
2650  kill_kthread:
2651         kthread_stop(nvme_thread);
2652         return result;
2653 }
2654
2655 static void __exit nvme_exit(void)
2656 {
2657         pci_unregister_driver(&nvme_driver);
2658         unregister_blkdev(nvme_major, "nvme");
2659         destroy_workqueue(nvme_workq);
2660         kthread_stop(nvme_thread);
2661 }
2662
2663 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2664 MODULE_LICENSE("GPL");
2665 MODULE_VERSION("0.8");
2666 module_init(nvme_init);
2667 module_exit(nvme_exit);