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