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