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