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