]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/nvme/host/core.c
block: ensure bios return from blk_get_request are properly initialized
[karo-tx-linux.git] / drivers / nvme / host / 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/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/pr.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <scsi/sg.h>
30 #include <asm/unaligned.h>
31
32 #include "nvme.h"
33 #include "fabrics.h"
34
35 #define NVME_MINORS             (1U << MINORBITS)
36
37 unsigned char admin_timeout = 60;
38 module_param(admin_timeout, byte, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
41
42 unsigned char nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
46
47 unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
50
51 unsigned int nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, uint, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
54 EXPORT_SYMBOL_GPL(nvme_max_retries);
55
56 static int nvme_char_major;
57 module_param(nvme_char_major, int, 0);
58
59 static LIST_HEAD(nvme_ctrl_list);
60 static DEFINE_SPINLOCK(dev_list_lock);
61
62 static struct class *nvme_class;
63
64 void nvme_cancel_request(struct request *req, void *data, bool reserved)
65 {
66         int status;
67
68         if (!blk_mq_request_started(req))
69                 return;
70
71         dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
72                                 "Cancelling I/O %d", req->tag);
73
74         status = NVME_SC_ABORT_REQ;
75         if (blk_queue_dying(req->q))
76                 status |= NVME_SC_DNR;
77         blk_mq_complete_request(req, status);
78 }
79 EXPORT_SYMBOL_GPL(nvme_cancel_request);
80
81 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
82                 enum nvme_ctrl_state new_state)
83 {
84         enum nvme_ctrl_state old_state = ctrl->state;
85         bool changed = false;
86
87         spin_lock_irq(&ctrl->lock);
88         switch (new_state) {
89         case NVME_CTRL_LIVE:
90                 switch (old_state) {
91                 case NVME_CTRL_NEW:
92                 case NVME_CTRL_RESETTING:
93                 case NVME_CTRL_RECONNECTING:
94                         changed = true;
95                         /* FALLTHRU */
96                 default:
97                         break;
98                 }
99                 break;
100         case NVME_CTRL_RESETTING:
101                 switch (old_state) {
102                 case NVME_CTRL_NEW:
103                 case NVME_CTRL_LIVE:
104                 case NVME_CTRL_RECONNECTING:
105                         changed = true;
106                         /* FALLTHRU */
107                 default:
108                         break;
109                 }
110                 break;
111         case NVME_CTRL_RECONNECTING:
112                 switch (old_state) {
113                 case NVME_CTRL_LIVE:
114                         changed = true;
115                         /* FALLTHRU */
116                 default:
117                         break;
118                 }
119                 break;
120         case NVME_CTRL_DELETING:
121                 switch (old_state) {
122                 case NVME_CTRL_LIVE:
123                 case NVME_CTRL_RESETTING:
124                 case NVME_CTRL_RECONNECTING:
125                         changed = true;
126                         /* FALLTHRU */
127                 default:
128                         break;
129                 }
130                 break;
131         case NVME_CTRL_DEAD:
132                 switch (old_state) {
133                 case NVME_CTRL_DELETING:
134                         changed = true;
135                         /* FALLTHRU */
136                 default:
137                         break;
138                 }
139                 break;
140         default:
141                 break;
142         }
143         spin_unlock_irq(&ctrl->lock);
144
145         if (changed)
146                 ctrl->state = new_state;
147
148         return changed;
149 }
150 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
151
152 static void nvme_free_ns(struct kref *kref)
153 {
154         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
155
156         if (ns->type == NVME_NS_LIGHTNVM)
157                 nvme_nvm_unregister(ns->queue, ns->disk->disk_name);
158
159         spin_lock(&dev_list_lock);
160         ns->disk->private_data = NULL;
161         spin_unlock(&dev_list_lock);
162
163         put_disk(ns->disk);
164         ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
165         nvme_put_ctrl(ns->ctrl);
166         kfree(ns);
167 }
168
169 static void nvme_put_ns(struct nvme_ns *ns)
170 {
171         kref_put(&ns->kref, nvme_free_ns);
172 }
173
174 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
175 {
176         struct nvme_ns *ns;
177
178         spin_lock(&dev_list_lock);
179         ns = disk->private_data;
180         if (ns) {
181                 if (!kref_get_unless_zero(&ns->kref))
182                         goto fail;
183                 if (!try_module_get(ns->ctrl->ops->module))
184                         goto fail_put_ns;
185         }
186         spin_unlock(&dev_list_lock);
187
188         return ns;
189
190 fail_put_ns:
191         kref_put(&ns->kref, nvme_free_ns);
192 fail:
193         spin_unlock(&dev_list_lock);
194         return NULL;
195 }
196
197 void nvme_requeue_req(struct request *req)
198 {
199         unsigned long flags;
200
201         blk_mq_requeue_request(req);
202         spin_lock_irqsave(req->q->queue_lock, flags);
203         if (!blk_queue_stopped(req->q))
204                 blk_mq_kick_requeue_list(req->q);
205         spin_unlock_irqrestore(req->q->queue_lock, flags);
206 }
207 EXPORT_SYMBOL_GPL(nvme_requeue_req);
208
209 struct request *nvme_alloc_request(struct request_queue *q,
210                 struct nvme_command *cmd, unsigned int flags, int qid)
211 {
212         struct request *req;
213
214         if (qid == NVME_QID_ANY) {
215                 req = blk_mq_alloc_request(q, nvme_is_write(cmd), flags);
216         } else {
217                 req = blk_mq_alloc_request_hctx(q, nvme_is_write(cmd), flags,
218                                 qid ? qid - 1 : 0);
219         }
220         if (IS_ERR(req))
221                 return req;
222
223         req->cmd_type = REQ_TYPE_DRV_PRIV;
224         req->cmd_flags |= REQ_FAILFAST_DRIVER;
225         req->cmd = (unsigned char *)cmd;
226         req->cmd_len = sizeof(struct nvme_command);
227
228         return req;
229 }
230 EXPORT_SYMBOL_GPL(nvme_alloc_request);
231
232 static inline void nvme_setup_flush(struct nvme_ns *ns,
233                 struct nvme_command *cmnd)
234 {
235         memset(cmnd, 0, sizeof(*cmnd));
236         cmnd->common.opcode = nvme_cmd_flush;
237         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
238 }
239
240 static inline int nvme_setup_discard(struct nvme_ns *ns, struct request *req,
241                 struct nvme_command *cmnd)
242 {
243         struct nvme_dsm_range *range;
244         struct page *page;
245         int offset;
246         unsigned int nr_bytes = blk_rq_bytes(req);
247
248         range = kmalloc(sizeof(*range), GFP_ATOMIC);
249         if (!range)
250                 return BLK_MQ_RQ_QUEUE_BUSY;
251
252         range->cattr = cpu_to_le32(0);
253         range->nlb = cpu_to_le32(nr_bytes >> ns->lba_shift);
254         range->slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
255
256         memset(cmnd, 0, sizeof(*cmnd));
257         cmnd->dsm.opcode = nvme_cmd_dsm;
258         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
259         cmnd->dsm.nr = 0;
260         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
261
262         req->completion_data = range;
263         page = virt_to_page(range);
264         offset = offset_in_page(range);
265         blk_add_request_payload(req, page, offset, sizeof(*range));
266
267         /*
268          * we set __data_len back to the size of the area to be discarded
269          * on disk. This allows us to report completion on the full amount
270          * of blocks described by the request.
271          */
272         req->__data_len = nr_bytes;
273
274         return 0;
275 }
276
277 static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
278                 struct nvme_command *cmnd)
279 {
280         u16 control = 0;
281         u32 dsmgmt = 0;
282
283         if (req->cmd_flags & REQ_FUA)
284                 control |= NVME_RW_FUA;
285         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
286                 control |= NVME_RW_LR;
287
288         if (req->cmd_flags & REQ_RAHEAD)
289                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
290
291         memset(cmnd, 0, sizeof(*cmnd));
292         cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
293         cmnd->rw.command_id = req->tag;
294         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
295         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
296         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
297
298         if (ns->ms) {
299                 switch (ns->pi_type) {
300                 case NVME_NS_DPS_PI_TYPE3:
301                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
302                         break;
303                 case NVME_NS_DPS_PI_TYPE1:
304                 case NVME_NS_DPS_PI_TYPE2:
305                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
306                                         NVME_RW_PRINFO_PRCHK_REF;
307                         cmnd->rw.reftag = cpu_to_le32(
308                                         nvme_block_nr(ns, blk_rq_pos(req)));
309                         break;
310                 }
311                 if (!blk_integrity_rq(req))
312                         control |= NVME_RW_PRINFO_PRACT;
313         }
314
315         cmnd->rw.control = cpu_to_le16(control);
316         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
317 }
318
319 int nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
320                 struct nvme_command *cmd)
321 {
322         int ret = 0;
323
324         if (req->cmd_type == REQ_TYPE_DRV_PRIV)
325                 memcpy(cmd, req->cmd, sizeof(*cmd));
326         else if (req_op(req) == REQ_OP_FLUSH)
327                 nvme_setup_flush(ns, cmd);
328         else if (req_op(req) == REQ_OP_DISCARD)
329                 ret = nvme_setup_discard(ns, req, cmd);
330         else
331                 nvme_setup_rw(ns, req, cmd);
332
333         return ret;
334 }
335 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
336
337 /*
338  * Returns 0 on success.  If the result is negative, it's a Linux error code;
339  * if the result is positive, it's an NVM Express status code
340  */
341 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
342                 struct nvme_completion *cqe, void *buffer, unsigned bufflen,
343                 unsigned timeout, int qid, int at_head, int flags)
344 {
345         struct request *req;
346         int ret;
347
348         req = nvme_alloc_request(q, cmd, flags, qid);
349         if (IS_ERR(req))
350                 return PTR_ERR(req);
351
352         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
353         req->special = cqe;
354
355         if (buffer && bufflen) {
356                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
357                 if (ret)
358                         goto out;
359         }
360
361         blk_execute_rq(req->q, NULL, req, at_head);
362         ret = req->errors;
363  out:
364         blk_mq_free_request(req);
365         return ret;
366 }
367 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
368
369 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
370                 void *buffer, unsigned bufflen)
371 {
372         return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
373                         NVME_QID_ANY, 0, 0);
374 }
375 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
376
377 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
378                 void __user *ubuffer, unsigned bufflen,
379                 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
380                 u32 *result, unsigned timeout)
381 {
382         bool write = nvme_is_write(cmd);
383         struct nvme_completion cqe;
384         struct nvme_ns *ns = q->queuedata;
385         struct gendisk *disk = ns ? ns->disk : NULL;
386         struct request *req;
387         struct bio *bio = NULL;
388         void *meta = NULL;
389         int ret;
390
391         req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
392         if (IS_ERR(req))
393                 return PTR_ERR(req);
394
395         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
396         req->special = &cqe;
397
398         if (ubuffer && bufflen) {
399                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
400                                 GFP_KERNEL);
401                 if (ret)
402                         goto out;
403                 bio = req->bio;
404
405                 if (!disk)
406                         goto submit;
407                 bio->bi_bdev = bdget_disk(disk, 0);
408                 if (!bio->bi_bdev) {
409                         ret = -ENODEV;
410                         goto out_unmap;
411                 }
412
413                 if (meta_buffer && meta_len) {
414                         struct bio_integrity_payload *bip;
415
416                         meta = kmalloc(meta_len, GFP_KERNEL);
417                         if (!meta) {
418                                 ret = -ENOMEM;
419                                 goto out_unmap;
420                         }
421
422                         if (write) {
423                                 if (copy_from_user(meta, meta_buffer,
424                                                 meta_len)) {
425                                         ret = -EFAULT;
426                                         goto out_free_meta;
427                                 }
428                         }
429
430                         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
431                         if (IS_ERR(bip)) {
432                                 ret = PTR_ERR(bip);
433                                 goto out_free_meta;
434                         }
435
436                         bip->bip_iter.bi_size = meta_len;
437                         bip->bip_iter.bi_sector = meta_seed;
438
439                         ret = bio_integrity_add_page(bio, virt_to_page(meta),
440                                         meta_len, offset_in_page(meta));
441                         if (ret != meta_len) {
442                                 ret = -ENOMEM;
443                                 goto out_free_meta;
444                         }
445                 }
446         }
447  submit:
448         blk_execute_rq(req->q, disk, req, 0);
449         ret = req->errors;
450         if (result)
451                 *result = le32_to_cpu(cqe.result);
452         if (meta && !ret && !write) {
453                 if (copy_to_user(meta_buffer, meta, meta_len))
454                         ret = -EFAULT;
455         }
456  out_free_meta:
457         kfree(meta);
458  out_unmap:
459         if (bio) {
460                 if (disk && bio->bi_bdev)
461                         bdput(bio->bi_bdev);
462                 blk_rq_unmap_user(bio);
463         }
464  out:
465         blk_mq_free_request(req);
466         return ret;
467 }
468
469 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
470                 void __user *ubuffer, unsigned bufflen, u32 *result,
471                 unsigned timeout)
472 {
473         return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
474                         result, timeout);
475 }
476
477 static void nvme_keep_alive_end_io(struct request *rq, int error)
478 {
479         struct nvme_ctrl *ctrl = rq->end_io_data;
480
481         blk_mq_free_request(rq);
482
483         if (error) {
484                 dev_err(ctrl->device,
485                         "failed nvme_keep_alive_end_io error=%d\n", error);
486                 return;
487         }
488
489         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
490 }
491
492 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
493 {
494         struct nvme_command c;
495         struct request *rq;
496
497         memset(&c, 0, sizeof(c));
498         c.common.opcode = nvme_admin_keep_alive;
499
500         rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
501                         NVME_QID_ANY);
502         if (IS_ERR(rq))
503                 return PTR_ERR(rq);
504
505         rq->timeout = ctrl->kato * HZ;
506         rq->end_io_data = ctrl;
507
508         blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
509
510         return 0;
511 }
512
513 static void nvme_keep_alive_work(struct work_struct *work)
514 {
515         struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
516                         struct nvme_ctrl, ka_work);
517
518         if (nvme_keep_alive(ctrl)) {
519                 /* allocation failure, reset the controller */
520                 dev_err(ctrl->device, "keep-alive failed\n");
521                 ctrl->ops->reset_ctrl(ctrl);
522                 return;
523         }
524 }
525
526 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
527 {
528         if (unlikely(ctrl->kato == 0))
529                 return;
530
531         INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
532         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
533 }
534 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
535
536 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
537 {
538         if (unlikely(ctrl->kato == 0))
539                 return;
540
541         cancel_delayed_work_sync(&ctrl->ka_work);
542 }
543 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
544
545 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
546 {
547         struct nvme_command c = { };
548         int error;
549
550         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
551         c.identify.opcode = nvme_admin_identify;
552         c.identify.cns = cpu_to_le32(1);
553
554         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
555         if (!*id)
556                 return -ENOMEM;
557
558         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
559                         sizeof(struct nvme_id_ctrl));
560         if (error)
561                 kfree(*id);
562         return error;
563 }
564
565 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
566 {
567         struct nvme_command c = { };
568
569         c.identify.opcode = nvme_admin_identify;
570         c.identify.cns = cpu_to_le32(2);
571         c.identify.nsid = cpu_to_le32(nsid);
572         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
573 }
574
575 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
576                 struct nvme_id_ns **id)
577 {
578         struct nvme_command c = { };
579         int error;
580
581         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
582         c.identify.opcode = nvme_admin_identify,
583         c.identify.nsid = cpu_to_le32(nsid),
584
585         *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
586         if (!*id)
587                 return -ENOMEM;
588
589         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
590                         sizeof(struct nvme_id_ns));
591         if (error)
592                 kfree(*id);
593         return error;
594 }
595
596 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
597                                         dma_addr_t dma_addr, u32 *result)
598 {
599         struct nvme_command c;
600         struct nvme_completion cqe;
601         int ret;
602
603         memset(&c, 0, sizeof(c));
604         c.features.opcode = nvme_admin_get_features;
605         c.features.nsid = cpu_to_le32(nsid);
606         c.features.dptr.prp1 = cpu_to_le64(dma_addr);
607         c.features.fid = cpu_to_le32(fid);
608
609         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &cqe, NULL, 0, 0,
610                         NVME_QID_ANY, 0, 0);
611         if (ret >= 0)
612                 *result = le32_to_cpu(cqe.result);
613         return ret;
614 }
615
616 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
617                                         dma_addr_t dma_addr, u32 *result)
618 {
619         struct nvme_command c;
620         struct nvme_completion cqe;
621         int ret;
622
623         memset(&c, 0, sizeof(c));
624         c.features.opcode = nvme_admin_set_features;
625         c.features.dptr.prp1 = cpu_to_le64(dma_addr);
626         c.features.fid = cpu_to_le32(fid);
627         c.features.dword11 = cpu_to_le32(dword11);
628
629         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &cqe, NULL, 0, 0,
630                         NVME_QID_ANY, 0, 0);
631         if (ret >= 0)
632                 *result = le32_to_cpu(cqe.result);
633         return ret;
634 }
635
636 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
637 {
638         struct nvme_command c = { };
639         int error;
640
641         c.common.opcode = nvme_admin_get_log_page,
642         c.common.nsid = cpu_to_le32(0xFFFFFFFF),
643         c.common.cdw10[0] = cpu_to_le32(
644                         (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
645                          NVME_LOG_SMART),
646
647         *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
648         if (!*log)
649                 return -ENOMEM;
650
651         error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
652                         sizeof(struct nvme_smart_log));
653         if (error)
654                 kfree(*log);
655         return error;
656 }
657
658 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
659 {
660         u32 q_count = (*count - 1) | ((*count - 1) << 16);
661         u32 result;
662         int status, nr_io_queues;
663
664         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, 0,
665                         &result);
666         if (status < 0)
667                 return status;
668
669         /*
670          * Degraded controllers might return an error when setting the queue
671          * count.  We still want to be able to bring them online and offer
672          * access to the admin queue, as that might be only way to fix them up.
673          */
674         if (status > 0) {
675                 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
676                 *count = 0;
677         } else {
678                 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
679                 *count = min(*count, nr_io_queues);
680         }
681
682         return 0;
683 }
684 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
685
686 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
687 {
688         struct nvme_user_io io;
689         struct nvme_command c;
690         unsigned length, meta_len;
691         void __user *metadata;
692
693         if (copy_from_user(&io, uio, sizeof(io)))
694                 return -EFAULT;
695         if (io.flags)
696                 return -EINVAL;
697
698         switch (io.opcode) {
699         case nvme_cmd_write:
700         case nvme_cmd_read:
701         case nvme_cmd_compare:
702                 break;
703         default:
704                 return -EINVAL;
705         }
706
707         length = (io.nblocks + 1) << ns->lba_shift;
708         meta_len = (io.nblocks + 1) * ns->ms;
709         metadata = (void __user *)(uintptr_t)io.metadata;
710
711         if (ns->ext) {
712                 length += meta_len;
713                 meta_len = 0;
714         } else if (meta_len) {
715                 if ((io.metadata & 3) || !io.metadata)
716                         return -EINVAL;
717         }
718
719         memset(&c, 0, sizeof(c));
720         c.rw.opcode = io.opcode;
721         c.rw.flags = io.flags;
722         c.rw.nsid = cpu_to_le32(ns->ns_id);
723         c.rw.slba = cpu_to_le64(io.slba);
724         c.rw.length = cpu_to_le16(io.nblocks);
725         c.rw.control = cpu_to_le16(io.control);
726         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
727         c.rw.reftag = cpu_to_le32(io.reftag);
728         c.rw.apptag = cpu_to_le16(io.apptag);
729         c.rw.appmask = cpu_to_le16(io.appmask);
730
731         return __nvme_submit_user_cmd(ns->queue, &c,
732                         (void __user *)(uintptr_t)io.addr, length,
733                         metadata, meta_len, io.slba, NULL, 0);
734 }
735
736 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
737                         struct nvme_passthru_cmd __user *ucmd)
738 {
739         struct nvme_passthru_cmd cmd;
740         struct nvme_command c;
741         unsigned timeout = 0;
742         int status;
743
744         if (!capable(CAP_SYS_ADMIN))
745                 return -EACCES;
746         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
747                 return -EFAULT;
748         if (cmd.flags)
749                 return -EINVAL;
750
751         memset(&c, 0, sizeof(c));
752         c.common.opcode = cmd.opcode;
753         c.common.flags = cmd.flags;
754         c.common.nsid = cpu_to_le32(cmd.nsid);
755         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
756         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
757         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
758         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
759         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
760         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
761         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
762         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
763
764         if (cmd.timeout_ms)
765                 timeout = msecs_to_jiffies(cmd.timeout_ms);
766
767         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
768                         (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
769                         &cmd.result, timeout);
770         if (status >= 0) {
771                 if (put_user(cmd.result, &ucmd->result))
772                         return -EFAULT;
773         }
774
775         return status;
776 }
777
778 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
779                 unsigned int cmd, unsigned long arg)
780 {
781         struct nvme_ns *ns = bdev->bd_disk->private_data;
782
783         switch (cmd) {
784         case NVME_IOCTL_ID:
785                 force_successful_syscall_return();
786                 return ns->ns_id;
787         case NVME_IOCTL_ADMIN_CMD:
788                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
789         case NVME_IOCTL_IO_CMD:
790                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
791         case NVME_IOCTL_SUBMIT_IO:
792                 return nvme_submit_io(ns, (void __user *)arg);
793 #ifdef CONFIG_BLK_DEV_NVME_SCSI
794         case SG_GET_VERSION_NUM:
795                 return nvme_sg_get_version_num((void __user *)arg);
796         case SG_IO:
797                 return nvme_sg_io(ns, (void __user *)arg);
798 #endif
799         default:
800                 return -ENOTTY;
801         }
802 }
803
804 #ifdef CONFIG_COMPAT
805 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
806                         unsigned int cmd, unsigned long arg)
807 {
808         switch (cmd) {
809         case SG_IO:
810                 return -ENOIOCTLCMD;
811         }
812         return nvme_ioctl(bdev, mode, cmd, arg);
813 }
814 #else
815 #define nvme_compat_ioctl       NULL
816 #endif
817
818 static int nvme_open(struct block_device *bdev, fmode_t mode)
819 {
820         return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
821 }
822
823 static void nvme_release(struct gendisk *disk, fmode_t mode)
824 {
825         struct nvme_ns *ns = disk->private_data;
826
827         module_put(ns->ctrl->ops->module);
828         nvme_put_ns(ns);
829 }
830
831 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
832 {
833         /* some standard values */
834         geo->heads = 1 << 6;
835         geo->sectors = 1 << 5;
836         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
837         return 0;
838 }
839
840 #ifdef CONFIG_BLK_DEV_INTEGRITY
841 static void nvme_init_integrity(struct nvme_ns *ns)
842 {
843         struct blk_integrity integrity;
844
845         switch (ns->pi_type) {
846         case NVME_NS_DPS_PI_TYPE3:
847                 integrity.profile = &t10_pi_type3_crc;
848                 integrity.tag_size = sizeof(u16) + sizeof(u32);
849                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
850                 break;
851         case NVME_NS_DPS_PI_TYPE1:
852         case NVME_NS_DPS_PI_TYPE2:
853                 integrity.profile = &t10_pi_type1_crc;
854                 integrity.tag_size = sizeof(u16);
855                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
856                 break;
857         default:
858                 integrity.profile = NULL;
859                 break;
860         }
861         integrity.tuple_size = ns->ms;
862         blk_integrity_register(ns->disk, &integrity);
863         blk_queue_max_integrity_segments(ns->queue, 1);
864 }
865 #else
866 static void nvme_init_integrity(struct nvme_ns *ns)
867 {
868 }
869 #endif /* CONFIG_BLK_DEV_INTEGRITY */
870
871 static void nvme_config_discard(struct nvme_ns *ns)
872 {
873         struct nvme_ctrl *ctrl = ns->ctrl;
874         u32 logical_block_size = queue_logical_block_size(ns->queue);
875
876         if (ctrl->quirks & NVME_QUIRK_DISCARD_ZEROES)
877                 ns->queue->limits.discard_zeroes_data = 1;
878         else
879                 ns->queue->limits.discard_zeroes_data = 0;
880
881         ns->queue->limits.discard_alignment = logical_block_size;
882         ns->queue->limits.discard_granularity = logical_block_size;
883         blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
884         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
885 }
886
887 static int nvme_revalidate_disk(struct gendisk *disk)
888 {
889         struct nvme_ns *ns = disk->private_data;
890         struct nvme_id_ns *id;
891         u8 lbaf, pi_type;
892         u16 old_ms;
893         unsigned short bs;
894
895         if (test_bit(NVME_NS_DEAD, &ns->flags)) {
896                 set_capacity(disk, 0);
897                 return -ENODEV;
898         }
899         if (nvme_identify_ns(ns->ctrl, ns->ns_id, &id)) {
900                 dev_warn(disk_to_dev(ns->disk), "%s: Identify failure\n",
901                                 __func__);
902                 return -ENODEV;
903         }
904         if (id->ncap == 0) {
905                 kfree(id);
906                 return -ENODEV;
907         }
908
909         if (nvme_nvm_ns_supported(ns, id) && ns->type != NVME_NS_LIGHTNVM) {
910                 if (nvme_nvm_register(ns->queue, disk->disk_name)) {
911                         dev_warn(disk_to_dev(ns->disk),
912                                 "%s: LightNVM init failure\n", __func__);
913                         kfree(id);
914                         return -ENODEV;
915                 }
916                 ns->type = NVME_NS_LIGHTNVM;
917         }
918
919         if (ns->ctrl->vs >= NVME_VS(1, 1))
920                 memcpy(ns->eui, id->eui64, sizeof(ns->eui));
921         if (ns->ctrl->vs >= NVME_VS(1, 2))
922                 memcpy(ns->uuid, id->nguid, sizeof(ns->uuid));
923
924         old_ms = ns->ms;
925         lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
926         ns->lba_shift = id->lbaf[lbaf].ds;
927         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
928         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
929
930         /*
931          * If identify namespace failed, use default 512 byte block size so
932          * block layer can use before failing read/write for 0 capacity.
933          */
934         if (ns->lba_shift == 0)
935                 ns->lba_shift = 9;
936         bs = 1 << ns->lba_shift;
937         /* XXX: PI implementation requires metadata equal t10 pi tuple size */
938         pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
939                                         id->dps & NVME_NS_DPS_PI_MASK : 0;
940
941         blk_mq_freeze_queue(disk->queue);
942         if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
943                                 ns->ms != old_ms ||
944                                 bs != queue_logical_block_size(disk->queue) ||
945                                 (ns->ms && ns->ext)))
946                 blk_integrity_unregister(disk);
947
948         ns->pi_type = pi_type;
949         blk_queue_logical_block_size(ns->queue, bs);
950
951         if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
952                 nvme_init_integrity(ns);
953         if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
954                 set_capacity(disk, 0);
955         else
956                 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
957
958         if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
959                 nvme_config_discard(ns);
960         blk_mq_unfreeze_queue(disk->queue);
961
962         kfree(id);
963         return 0;
964 }
965
966 static char nvme_pr_type(enum pr_type type)
967 {
968         switch (type) {
969         case PR_WRITE_EXCLUSIVE:
970                 return 1;
971         case PR_EXCLUSIVE_ACCESS:
972                 return 2;
973         case PR_WRITE_EXCLUSIVE_REG_ONLY:
974                 return 3;
975         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
976                 return 4;
977         case PR_WRITE_EXCLUSIVE_ALL_REGS:
978                 return 5;
979         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
980                 return 6;
981         default:
982                 return 0;
983         }
984 };
985
986 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
987                                 u64 key, u64 sa_key, u8 op)
988 {
989         struct nvme_ns *ns = bdev->bd_disk->private_data;
990         struct nvme_command c;
991         u8 data[16] = { 0, };
992
993         put_unaligned_le64(key, &data[0]);
994         put_unaligned_le64(sa_key, &data[8]);
995
996         memset(&c, 0, sizeof(c));
997         c.common.opcode = op;
998         c.common.nsid = cpu_to_le32(ns->ns_id);
999         c.common.cdw10[0] = cpu_to_le32(cdw10);
1000
1001         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1002 }
1003
1004 static int nvme_pr_register(struct block_device *bdev, u64 old,
1005                 u64 new, unsigned flags)
1006 {
1007         u32 cdw10;
1008
1009         if (flags & ~PR_FL_IGNORE_KEY)
1010                 return -EOPNOTSUPP;
1011
1012         cdw10 = old ? 2 : 0;
1013         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1014         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1015         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1016 }
1017
1018 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1019                 enum pr_type type, unsigned flags)
1020 {
1021         u32 cdw10;
1022
1023         if (flags & ~PR_FL_IGNORE_KEY)
1024                 return -EOPNOTSUPP;
1025
1026         cdw10 = nvme_pr_type(type) << 8;
1027         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1028         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1029 }
1030
1031 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1032                 enum pr_type type, bool abort)
1033 {
1034         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1035         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1036 }
1037
1038 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1039 {
1040         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1041         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1042 }
1043
1044 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1045 {
1046         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1047         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1048 }
1049
1050 static const struct pr_ops nvme_pr_ops = {
1051         .pr_register    = nvme_pr_register,
1052         .pr_reserve     = nvme_pr_reserve,
1053         .pr_release     = nvme_pr_release,
1054         .pr_preempt     = nvme_pr_preempt,
1055         .pr_clear       = nvme_pr_clear,
1056 };
1057
1058 static const struct block_device_operations nvme_fops = {
1059         .owner          = THIS_MODULE,
1060         .ioctl          = nvme_ioctl,
1061         .compat_ioctl   = nvme_compat_ioctl,
1062         .open           = nvme_open,
1063         .release        = nvme_release,
1064         .getgeo         = nvme_getgeo,
1065         .revalidate_disk= nvme_revalidate_disk,
1066         .pr_ops         = &nvme_pr_ops,
1067 };
1068
1069 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1070 {
1071         unsigned long timeout =
1072                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1073         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1074         int ret;
1075
1076         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1077                 if ((csts & NVME_CSTS_RDY) == bit)
1078                         break;
1079
1080                 msleep(100);
1081                 if (fatal_signal_pending(current))
1082                         return -EINTR;
1083                 if (time_after(jiffies, timeout)) {
1084                         dev_err(ctrl->device,
1085                                 "Device not ready; aborting %s\n", enabled ?
1086                                                 "initialisation" : "reset");
1087                         return -ENODEV;
1088                 }
1089         }
1090
1091         return ret;
1092 }
1093
1094 /*
1095  * If the device has been passed off to us in an enabled state, just clear
1096  * the enabled bit.  The spec says we should set the 'shutdown notification
1097  * bits', but doing so may cause the device to complete commands to the
1098  * admin queue ... and we don't know what memory that might be pointing at!
1099  */
1100 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1101 {
1102         int ret;
1103
1104         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1105         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1106
1107         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1108         if (ret)
1109                 return ret;
1110
1111         /* Checking for ctrl->tagset is a trick to avoid sleeping on module
1112          * load, since we only need the quirk on reset_controller. Notice
1113          * that the HGST device needs this delay only in firmware activation
1114          * procedure; unfortunately we have no (easy) way to verify this.
1115          */
1116         if ((ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY) && ctrl->tagset)
1117                 msleep(NVME_QUIRK_DELAY_AMOUNT);
1118
1119         return nvme_wait_ready(ctrl, cap, false);
1120 }
1121 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1122
1123 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1124 {
1125         /*
1126          * Default to a 4K page size, with the intention to update this
1127          * path in the future to accomodate architectures with differing
1128          * kernel and IO page sizes.
1129          */
1130         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1131         int ret;
1132
1133         if (page_shift < dev_page_min) {
1134                 dev_err(ctrl->device,
1135                         "Minimum device page size %u too large for host (%u)\n",
1136                         1 << dev_page_min, 1 << page_shift);
1137                 return -ENODEV;
1138         }
1139
1140         ctrl->page_size = 1 << page_shift;
1141
1142         ctrl->ctrl_config = NVME_CC_CSS_NVM;
1143         ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1144         ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1145         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1146         ctrl->ctrl_config |= NVME_CC_ENABLE;
1147
1148         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1149         if (ret)
1150                 return ret;
1151         return nvme_wait_ready(ctrl, cap, true);
1152 }
1153 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1154
1155 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1156 {
1157         unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1158         u32 csts;
1159         int ret;
1160
1161         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1162         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1163
1164         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1165         if (ret)
1166                 return ret;
1167
1168         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1169                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1170                         break;
1171
1172                 msleep(100);
1173                 if (fatal_signal_pending(current))
1174                         return -EINTR;
1175                 if (time_after(jiffies, timeout)) {
1176                         dev_err(ctrl->device,
1177                                 "Device shutdown incomplete; abort shutdown\n");
1178                         return -ENODEV;
1179                 }
1180         }
1181
1182         return ret;
1183 }
1184 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1185
1186 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1187                 struct request_queue *q)
1188 {
1189         bool vwc = false;
1190
1191         if (ctrl->max_hw_sectors) {
1192                 u32 max_segments =
1193                         (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1194
1195                 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1196                 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1197         }
1198         if (ctrl->stripe_size)
1199                 blk_queue_chunk_sectors(q, ctrl->stripe_size >> 9);
1200         blk_queue_virt_boundary(q, ctrl->page_size - 1);
1201         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1202                 vwc = true;
1203         blk_queue_write_cache(q, vwc, vwc);
1204 }
1205
1206 /*
1207  * Initialize the cached copies of the Identify data and various controller
1208  * register in our nvme_ctrl structure.  This should be called as soon as
1209  * the admin queue is fully up and running.
1210  */
1211 int nvme_init_identify(struct nvme_ctrl *ctrl)
1212 {
1213         struct nvme_id_ctrl *id;
1214         u64 cap;
1215         int ret, page_shift;
1216         u32 max_hw_sectors;
1217
1218         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1219         if (ret) {
1220                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1221                 return ret;
1222         }
1223
1224         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1225         if (ret) {
1226                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1227                 return ret;
1228         }
1229         page_shift = NVME_CAP_MPSMIN(cap) + 12;
1230
1231         if (ctrl->vs >= NVME_VS(1, 1))
1232                 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1233
1234         ret = nvme_identify_ctrl(ctrl, &id);
1235         if (ret) {
1236                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1237                 return -EIO;
1238         }
1239
1240         ctrl->vid = le16_to_cpu(id->vid);
1241         ctrl->oncs = le16_to_cpup(&id->oncs);
1242         atomic_set(&ctrl->abort_limit, id->acl + 1);
1243         ctrl->vwc = id->vwc;
1244         ctrl->cntlid = le16_to_cpup(&id->cntlid);
1245         memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1246         memcpy(ctrl->model, id->mn, sizeof(id->mn));
1247         memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1248         if (id->mdts)
1249                 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1250         else
1251                 max_hw_sectors = UINT_MAX;
1252         ctrl->max_hw_sectors =
1253                 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1254
1255         if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) && id->vs[3]) {
1256                 unsigned int max_hw_sectors;
1257
1258                 ctrl->stripe_size = 1 << (id->vs[3] + page_shift);
1259                 max_hw_sectors = ctrl->stripe_size >> (page_shift - 9);
1260                 if (ctrl->max_hw_sectors) {
1261                         ctrl->max_hw_sectors = min(max_hw_sectors,
1262                                                         ctrl->max_hw_sectors);
1263                 } else {
1264                         ctrl->max_hw_sectors = max_hw_sectors;
1265                 }
1266         }
1267
1268         nvme_set_queue_limits(ctrl, ctrl->admin_q);
1269         ctrl->sgls = le32_to_cpu(id->sgls);
1270         ctrl->kas = le16_to_cpu(id->kas);
1271
1272         if (ctrl->ops->is_fabrics) {
1273                 ctrl->icdoff = le16_to_cpu(id->icdoff);
1274                 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1275                 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1276                 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1277
1278                 /*
1279                  * In fabrics we need to verify the cntlid matches the
1280                  * admin connect
1281                  */
1282                 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1283                         ret = -EINVAL;
1284
1285                 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1286                         dev_err(ctrl->dev,
1287                                 "keep-alive support is mandatory for fabrics\n");
1288                         ret = -EINVAL;
1289                 }
1290         } else {
1291                 ctrl->cntlid = le16_to_cpu(id->cntlid);
1292         }
1293
1294         kfree(id);
1295         return ret;
1296 }
1297 EXPORT_SYMBOL_GPL(nvme_init_identify);
1298
1299 static int nvme_dev_open(struct inode *inode, struct file *file)
1300 {
1301         struct nvme_ctrl *ctrl;
1302         int instance = iminor(inode);
1303         int ret = -ENODEV;
1304
1305         spin_lock(&dev_list_lock);
1306         list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1307                 if (ctrl->instance != instance)
1308                         continue;
1309
1310                 if (!ctrl->admin_q) {
1311                         ret = -EWOULDBLOCK;
1312                         break;
1313                 }
1314                 if (!kref_get_unless_zero(&ctrl->kref))
1315                         break;
1316                 file->private_data = ctrl;
1317                 ret = 0;
1318                 break;
1319         }
1320         spin_unlock(&dev_list_lock);
1321
1322         return ret;
1323 }
1324
1325 static int nvme_dev_release(struct inode *inode, struct file *file)
1326 {
1327         nvme_put_ctrl(file->private_data);
1328         return 0;
1329 }
1330
1331 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1332 {
1333         struct nvme_ns *ns;
1334         int ret;
1335
1336         mutex_lock(&ctrl->namespaces_mutex);
1337         if (list_empty(&ctrl->namespaces)) {
1338                 ret = -ENOTTY;
1339                 goto out_unlock;
1340         }
1341
1342         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1343         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1344                 dev_warn(ctrl->device,
1345                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1346                 ret = -EINVAL;
1347                 goto out_unlock;
1348         }
1349
1350         dev_warn(ctrl->device,
1351                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1352         kref_get(&ns->kref);
1353         mutex_unlock(&ctrl->namespaces_mutex);
1354
1355         ret = nvme_user_cmd(ctrl, ns, argp);
1356         nvme_put_ns(ns);
1357         return ret;
1358
1359 out_unlock:
1360         mutex_unlock(&ctrl->namespaces_mutex);
1361         return ret;
1362 }
1363
1364 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1365                 unsigned long arg)
1366 {
1367         struct nvme_ctrl *ctrl = file->private_data;
1368         void __user *argp = (void __user *)arg;
1369
1370         switch (cmd) {
1371         case NVME_IOCTL_ADMIN_CMD:
1372                 return nvme_user_cmd(ctrl, NULL, argp);
1373         case NVME_IOCTL_IO_CMD:
1374                 return nvme_dev_user_cmd(ctrl, argp);
1375         case NVME_IOCTL_RESET:
1376                 dev_warn(ctrl->device, "resetting controller\n");
1377                 return ctrl->ops->reset_ctrl(ctrl);
1378         case NVME_IOCTL_SUBSYS_RESET:
1379                 return nvme_reset_subsystem(ctrl);
1380         case NVME_IOCTL_RESCAN:
1381                 nvme_queue_scan(ctrl);
1382                 return 0;
1383         default:
1384                 return -ENOTTY;
1385         }
1386 }
1387
1388 static const struct file_operations nvme_dev_fops = {
1389         .owner          = THIS_MODULE,
1390         .open           = nvme_dev_open,
1391         .release        = nvme_dev_release,
1392         .unlocked_ioctl = nvme_dev_ioctl,
1393         .compat_ioctl   = nvme_dev_ioctl,
1394 };
1395
1396 static ssize_t nvme_sysfs_reset(struct device *dev,
1397                                 struct device_attribute *attr, const char *buf,
1398                                 size_t count)
1399 {
1400         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1401         int ret;
1402
1403         ret = ctrl->ops->reset_ctrl(ctrl);
1404         if (ret < 0)
1405                 return ret;
1406         return count;
1407 }
1408 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1409
1410 static ssize_t nvme_sysfs_rescan(struct device *dev,
1411                                 struct device_attribute *attr, const char *buf,
1412                                 size_t count)
1413 {
1414         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1415
1416         nvme_queue_scan(ctrl);
1417         return count;
1418 }
1419 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1420
1421 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1422                                                                 char *buf)
1423 {
1424         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1425         struct nvme_ctrl *ctrl = ns->ctrl;
1426         int serial_len = sizeof(ctrl->serial);
1427         int model_len = sizeof(ctrl->model);
1428
1429         if (memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1430                 return sprintf(buf, "eui.%16phN\n", ns->uuid);
1431
1432         if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1433                 return sprintf(buf, "eui.%8phN\n", ns->eui);
1434
1435         while (ctrl->serial[serial_len - 1] == ' ')
1436                 serial_len--;
1437         while (ctrl->model[model_len - 1] == ' ')
1438                 model_len--;
1439
1440         return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1441                 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1442 }
1443 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1444
1445 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1446                                                                 char *buf)
1447 {
1448         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1449         return sprintf(buf, "%pU\n", ns->uuid);
1450 }
1451 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1452
1453 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1454                                                                 char *buf)
1455 {
1456         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1457         return sprintf(buf, "%8phd\n", ns->eui);
1458 }
1459 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1460
1461 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1462                                                                 char *buf)
1463 {
1464         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1465         return sprintf(buf, "%d\n", ns->ns_id);
1466 }
1467 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1468
1469 static struct attribute *nvme_ns_attrs[] = {
1470         &dev_attr_wwid.attr,
1471         &dev_attr_uuid.attr,
1472         &dev_attr_eui.attr,
1473         &dev_attr_nsid.attr,
1474         NULL,
1475 };
1476
1477 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1478                 struct attribute *a, int n)
1479 {
1480         struct device *dev = container_of(kobj, struct device, kobj);
1481         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1482
1483         if (a == &dev_attr_uuid.attr) {
1484                 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1485                         return 0;
1486         }
1487         if (a == &dev_attr_eui.attr) {
1488                 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1489                         return 0;
1490         }
1491         return a->mode;
1492 }
1493
1494 static const struct attribute_group nvme_ns_attr_group = {
1495         .attrs          = nvme_ns_attrs,
1496         .is_visible     = nvme_ns_attrs_are_visible,
1497 };
1498
1499 #define nvme_show_str_function(field)                                           \
1500 static ssize_t  field##_show(struct device *dev,                                \
1501                             struct device_attribute *attr, char *buf)           \
1502 {                                                                               \
1503         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
1504         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);   \
1505 }                                                                               \
1506 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1507
1508 #define nvme_show_int_function(field)                                           \
1509 static ssize_t  field##_show(struct device *dev,                                \
1510                             struct device_attribute *attr, char *buf)           \
1511 {                                                                               \
1512         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
1513         return sprintf(buf, "%d\n", ctrl->field);       \
1514 }                                                                               \
1515 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1516
1517 nvme_show_str_function(model);
1518 nvme_show_str_function(serial);
1519 nvme_show_str_function(firmware_rev);
1520 nvme_show_int_function(cntlid);
1521
1522 static ssize_t nvme_sysfs_delete(struct device *dev,
1523                                 struct device_attribute *attr, const char *buf,
1524                                 size_t count)
1525 {
1526         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1527
1528         if (device_remove_file_self(dev, attr))
1529                 ctrl->ops->delete_ctrl(ctrl);
1530         return count;
1531 }
1532 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1533
1534 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1535                                          struct device_attribute *attr,
1536                                          char *buf)
1537 {
1538         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1539
1540         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
1541 }
1542 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
1543
1544 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
1545                                          struct device_attribute *attr,
1546                                          char *buf)
1547 {
1548         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1549
1550         return snprintf(buf, PAGE_SIZE, "%s\n",
1551                         ctrl->ops->get_subsysnqn(ctrl));
1552 }
1553 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
1554
1555 static ssize_t nvme_sysfs_show_address(struct device *dev,
1556                                          struct device_attribute *attr,
1557                                          char *buf)
1558 {
1559         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1560
1561         return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
1562 }
1563 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
1564
1565 static struct attribute *nvme_dev_attrs[] = {
1566         &dev_attr_reset_controller.attr,
1567         &dev_attr_rescan_controller.attr,
1568         &dev_attr_model.attr,
1569         &dev_attr_serial.attr,
1570         &dev_attr_firmware_rev.attr,
1571         &dev_attr_cntlid.attr,
1572         &dev_attr_delete_controller.attr,
1573         &dev_attr_transport.attr,
1574         &dev_attr_subsysnqn.attr,
1575         &dev_attr_address.attr,
1576         NULL
1577 };
1578
1579 #define CHECK_ATTR(ctrl, a, name)               \
1580         if ((a) == &dev_attr_##name.attr &&     \
1581             !(ctrl)->ops->get_##name)           \
1582                 return 0
1583
1584 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
1585                 struct attribute *a, int n)
1586 {
1587         struct device *dev = container_of(kobj, struct device, kobj);
1588         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1589
1590         if (a == &dev_attr_delete_controller.attr) {
1591                 if (!ctrl->ops->delete_ctrl)
1592                         return 0;
1593         }
1594
1595         CHECK_ATTR(ctrl, a, subsysnqn);
1596         CHECK_ATTR(ctrl, a, address);
1597
1598         return a->mode;
1599 }
1600
1601 static struct attribute_group nvme_dev_attrs_group = {
1602         .attrs          = nvme_dev_attrs,
1603         .is_visible     = nvme_dev_attrs_are_visible,
1604 };
1605
1606 static const struct attribute_group *nvme_dev_attr_groups[] = {
1607         &nvme_dev_attrs_group,
1608         NULL,
1609 };
1610
1611 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1612 {
1613         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1614         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1615
1616         return nsa->ns_id - nsb->ns_id;
1617 }
1618
1619 static struct nvme_ns *nvme_find_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1620 {
1621         struct nvme_ns *ns;
1622
1623         lockdep_assert_held(&ctrl->namespaces_mutex);
1624
1625         list_for_each_entry(ns, &ctrl->namespaces, list) {
1626                 if (ns->ns_id == nsid)
1627                         return ns;
1628                 if (ns->ns_id > nsid)
1629                         break;
1630         }
1631         return NULL;
1632 }
1633
1634 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1635 {
1636         struct nvme_ns *ns;
1637         struct gendisk *disk;
1638         int node = dev_to_node(ctrl->dev);
1639
1640         lockdep_assert_held(&ctrl->namespaces_mutex);
1641
1642         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
1643         if (!ns)
1644                 return;
1645
1646         ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
1647         if (ns->instance < 0)
1648                 goto out_free_ns;
1649
1650         ns->queue = blk_mq_init_queue(ctrl->tagset);
1651         if (IS_ERR(ns->queue))
1652                 goto out_release_instance;
1653         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1654         ns->queue->queuedata = ns;
1655         ns->ctrl = ctrl;
1656
1657         disk = alloc_disk_node(0, node);
1658         if (!disk)
1659                 goto out_free_queue;
1660
1661         kref_init(&ns->kref);
1662         ns->ns_id = nsid;
1663         ns->disk = disk;
1664         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
1665
1666
1667         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1668         nvme_set_queue_limits(ctrl, ns->queue);
1669
1670         disk->fops = &nvme_fops;
1671         disk->private_data = ns;
1672         disk->queue = ns->queue;
1673         disk->flags = GENHD_FL_EXT_DEVT;
1674         sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
1675
1676         if (nvme_revalidate_disk(ns->disk))
1677                 goto out_free_disk;
1678
1679         list_add_tail_rcu(&ns->list, &ctrl->namespaces);
1680         kref_get(&ctrl->kref);
1681         if (ns->type == NVME_NS_LIGHTNVM)
1682                 return;
1683
1684         device_add_disk(ctrl->device, ns->disk);
1685         if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
1686                                         &nvme_ns_attr_group))
1687                 pr_warn("%s: failed to create sysfs group for identification\n",
1688                         ns->disk->disk_name);
1689         return;
1690  out_free_disk:
1691         kfree(disk);
1692  out_free_queue:
1693         blk_cleanup_queue(ns->queue);
1694  out_release_instance:
1695         ida_simple_remove(&ctrl->ns_ida, ns->instance);
1696  out_free_ns:
1697         kfree(ns);
1698 }
1699
1700 static void nvme_ns_remove(struct nvme_ns *ns)
1701 {
1702         lockdep_assert_held(&ns->ctrl->namespaces_mutex);
1703
1704         if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
1705                 return;
1706
1707         if (ns->disk->flags & GENHD_FL_UP) {
1708                 if (blk_get_integrity(ns->disk))
1709                         blk_integrity_unregister(ns->disk);
1710                 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
1711                                         &nvme_ns_attr_group);
1712                 del_gendisk(ns->disk);
1713                 blk_mq_abort_requeue_list(ns->queue);
1714                 blk_cleanup_queue(ns->queue);
1715         }
1716         list_del_init(&ns->list);
1717         synchronize_rcu();
1718         nvme_put_ns(ns);
1719 }
1720
1721 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1722 {
1723         struct nvme_ns *ns;
1724
1725         ns = nvme_find_ns(ctrl, nsid);
1726         if (ns) {
1727                 if (revalidate_disk(ns->disk))
1728                         nvme_ns_remove(ns);
1729         } else
1730                 nvme_alloc_ns(ctrl, nsid);
1731 }
1732
1733 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
1734                                         unsigned nsid)
1735 {
1736         struct nvme_ns *ns, *next;
1737
1738         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
1739                 if (ns->ns_id > nsid)
1740                         nvme_ns_remove(ns);
1741         }
1742 }
1743
1744 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
1745 {
1746         struct nvme_ns *ns;
1747         __le32 *ns_list;
1748         unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
1749         int ret = 0;
1750
1751         ns_list = kzalloc(0x1000, GFP_KERNEL);
1752         if (!ns_list)
1753                 return -ENOMEM;
1754
1755         for (i = 0; i < num_lists; i++) {
1756                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
1757                 if (ret)
1758                         goto free;
1759
1760                 for (j = 0; j < min(nn, 1024U); j++) {
1761                         nsid = le32_to_cpu(ns_list[j]);
1762                         if (!nsid)
1763                                 goto out;
1764
1765                         nvme_validate_ns(ctrl, nsid);
1766
1767                         while (++prev < nsid) {
1768                                 ns = nvme_find_ns(ctrl, prev);
1769                                 if (ns)
1770                                         nvme_ns_remove(ns);
1771                         }
1772                 }
1773                 nn -= j;
1774         }
1775  out:
1776         nvme_remove_invalid_namespaces(ctrl, prev);
1777  free:
1778         kfree(ns_list);
1779         return ret;
1780 }
1781
1782 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
1783 {
1784         unsigned i;
1785
1786         lockdep_assert_held(&ctrl->namespaces_mutex);
1787
1788         for (i = 1; i <= nn; i++)
1789                 nvme_validate_ns(ctrl, i);
1790
1791         nvme_remove_invalid_namespaces(ctrl, nn);
1792 }
1793
1794 static void nvme_scan_work(struct work_struct *work)
1795 {
1796         struct nvme_ctrl *ctrl =
1797                 container_of(work, struct nvme_ctrl, scan_work);
1798         struct nvme_id_ctrl *id;
1799         unsigned nn;
1800
1801         if (ctrl->state != NVME_CTRL_LIVE)
1802                 return;
1803
1804         if (nvme_identify_ctrl(ctrl, &id))
1805                 return;
1806
1807         mutex_lock(&ctrl->namespaces_mutex);
1808         nn = le32_to_cpu(id->nn);
1809         if (ctrl->vs >= NVME_VS(1, 1) &&
1810             !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
1811                 if (!nvme_scan_ns_list(ctrl, nn))
1812                         goto done;
1813         }
1814         nvme_scan_ns_sequential(ctrl, nn);
1815  done:
1816         list_sort(NULL, &ctrl->namespaces, ns_cmp);
1817         mutex_unlock(&ctrl->namespaces_mutex);
1818         kfree(id);
1819
1820         if (ctrl->ops->post_scan)
1821                 ctrl->ops->post_scan(ctrl);
1822 }
1823
1824 void nvme_queue_scan(struct nvme_ctrl *ctrl)
1825 {
1826         /*
1827          * Do not queue new scan work when a controller is reset during
1828          * removal.
1829          */
1830         if (ctrl->state == NVME_CTRL_LIVE)
1831                 schedule_work(&ctrl->scan_work);
1832 }
1833 EXPORT_SYMBOL_GPL(nvme_queue_scan);
1834
1835 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
1836 {
1837         struct nvme_ns *ns, *next;
1838
1839         /*
1840          * The dead states indicates the controller was not gracefully
1841          * disconnected. In that case, we won't be able to flush any data while
1842          * removing the namespaces' disks; fail all the queues now to avoid
1843          * potentially having to clean up the failed sync later.
1844          */
1845         if (ctrl->state == NVME_CTRL_DEAD)
1846                 nvme_kill_queues(ctrl);
1847
1848         mutex_lock(&ctrl->namespaces_mutex);
1849         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
1850                 nvme_ns_remove(ns);
1851         mutex_unlock(&ctrl->namespaces_mutex);
1852 }
1853 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
1854
1855 static void nvme_async_event_work(struct work_struct *work)
1856 {
1857         struct nvme_ctrl *ctrl =
1858                 container_of(work, struct nvme_ctrl, async_event_work);
1859
1860         spin_lock_irq(&ctrl->lock);
1861         while (ctrl->event_limit > 0) {
1862                 int aer_idx = --ctrl->event_limit;
1863
1864                 spin_unlock_irq(&ctrl->lock);
1865                 ctrl->ops->submit_async_event(ctrl, aer_idx);
1866                 spin_lock_irq(&ctrl->lock);
1867         }
1868         spin_unlock_irq(&ctrl->lock);
1869 }
1870
1871 void nvme_complete_async_event(struct nvme_ctrl *ctrl,
1872                 struct nvme_completion *cqe)
1873 {
1874         u16 status = le16_to_cpu(cqe->status) >> 1;
1875         u32 result = le32_to_cpu(cqe->result);
1876
1877         if (status == NVME_SC_SUCCESS || status == NVME_SC_ABORT_REQ) {
1878                 ++ctrl->event_limit;
1879                 schedule_work(&ctrl->async_event_work);
1880         }
1881
1882         if (status != NVME_SC_SUCCESS)
1883                 return;
1884
1885         switch (result & 0xff07) {
1886         case NVME_AER_NOTICE_NS_CHANGED:
1887                 dev_info(ctrl->device, "rescanning\n");
1888                 nvme_queue_scan(ctrl);
1889                 break;
1890         default:
1891                 dev_warn(ctrl->device, "async event result %08x\n", result);
1892         }
1893 }
1894 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
1895
1896 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
1897 {
1898         ctrl->event_limit = NVME_NR_AERS;
1899         schedule_work(&ctrl->async_event_work);
1900 }
1901 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
1902
1903 static DEFINE_IDA(nvme_instance_ida);
1904
1905 static int nvme_set_instance(struct nvme_ctrl *ctrl)
1906 {
1907         int instance, error;
1908
1909         do {
1910                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
1911                         return -ENODEV;
1912
1913                 spin_lock(&dev_list_lock);
1914                 error = ida_get_new(&nvme_instance_ida, &instance);
1915                 spin_unlock(&dev_list_lock);
1916         } while (error == -EAGAIN);
1917
1918         if (error)
1919                 return -ENODEV;
1920
1921         ctrl->instance = instance;
1922         return 0;
1923 }
1924
1925 static void nvme_release_instance(struct nvme_ctrl *ctrl)
1926 {
1927         spin_lock(&dev_list_lock);
1928         ida_remove(&nvme_instance_ida, ctrl->instance);
1929         spin_unlock(&dev_list_lock);
1930 }
1931
1932 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
1933 {
1934         flush_work(&ctrl->async_event_work);
1935         flush_work(&ctrl->scan_work);
1936         nvme_remove_namespaces(ctrl);
1937
1938         device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
1939
1940         spin_lock(&dev_list_lock);
1941         list_del(&ctrl->node);
1942         spin_unlock(&dev_list_lock);
1943 }
1944 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
1945
1946 static void nvme_free_ctrl(struct kref *kref)
1947 {
1948         struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
1949
1950         put_device(ctrl->device);
1951         nvme_release_instance(ctrl);
1952         ida_destroy(&ctrl->ns_ida);
1953
1954         ctrl->ops->free_ctrl(ctrl);
1955 }
1956
1957 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
1958 {
1959         kref_put(&ctrl->kref, nvme_free_ctrl);
1960 }
1961 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
1962
1963 /*
1964  * Initialize a NVMe controller structures.  This needs to be called during
1965  * earliest initialization so that we have the initialized structured around
1966  * during probing.
1967  */
1968 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
1969                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
1970 {
1971         int ret;
1972
1973         ctrl->state = NVME_CTRL_NEW;
1974         spin_lock_init(&ctrl->lock);
1975         INIT_LIST_HEAD(&ctrl->namespaces);
1976         mutex_init(&ctrl->namespaces_mutex);
1977         kref_init(&ctrl->kref);
1978         ctrl->dev = dev;
1979         ctrl->ops = ops;
1980         ctrl->quirks = quirks;
1981         INIT_WORK(&ctrl->scan_work, nvme_scan_work);
1982         INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
1983
1984         ret = nvme_set_instance(ctrl);
1985         if (ret)
1986                 goto out;
1987
1988         ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
1989                                 MKDEV(nvme_char_major, ctrl->instance),
1990                                 ctrl, nvme_dev_attr_groups,
1991                                 "nvme%d", ctrl->instance);
1992         if (IS_ERR(ctrl->device)) {
1993                 ret = PTR_ERR(ctrl->device);
1994                 goto out_release_instance;
1995         }
1996         get_device(ctrl->device);
1997         ida_init(&ctrl->ns_ida);
1998
1999         spin_lock(&dev_list_lock);
2000         list_add_tail(&ctrl->node, &nvme_ctrl_list);
2001         spin_unlock(&dev_list_lock);
2002
2003         return 0;
2004 out_release_instance:
2005         nvme_release_instance(ctrl);
2006 out:
2007         return ret;
2008 }
2009 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2010
2011 /**
2012  * nvme_kill_queues(): Ends all namespace queues
2013  * @ctrl: the dead controller that needs to end
2014  *
2015  * Call this function when the driver determines it is unable to get the
2016  * controller in a state capable of servicing IO.
2017  */
2018 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2019 {
2020         struct nvme_ns *ns;
2021
2022         rcu_read_lock();
2023         list_for_each_entry_rcu(ns, &ctrl->namespaces, list) {
2024                 if (!kref_get_unless_zero(&ns->kref))
2025                         continue;
2026
2027                 /*
2028                  * Revalidating a dead namespace sets capacity to 0. This will
2029                  * end buffered writers dirtying pages that can't be synced.
2030                  */
2031                 if (!test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2032                         revalidate_disk(ns->disk);
2033
2034                 blk_set_queue_dying(ns->queue);
2035                 blk_mq_abort_requeue_list(ns->queue);
2036                 blk_mq_start_stopped_hw_queues(ns->queue, true);
2037
2038                 nvme_put_ns(ns);
2039         }
2040         rcu_read_unlock();
2041 }
2042 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2043
2044 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2045 {
2046         struct nvme_ns *ns;
2047
2048         rcu_read_lock();
2049         list_for_each_entry_rcu(ns, &ctrl->namespaces, list) {
2050                 spin_lock_irq(ns->queue->queue_lock);
2051                 queue_flag_set(QUEUE_FLAG_STOPPED, ns->queue);
2052                 spin_unlock_irq(ns->queue->queue_lock);
2053
2054                 blk_mq_cancel_requeue_work(ns->queue);
2055                 blk_mq_stop_hw_queues(ns->queue);
2056         }
2057         rcu_read_unlock();
2058 }
2059 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2060
2061 void nvme_start_queues(struct nvme_ctrl *ctrl)
2062 {
2063         struct nvme_ns *ns;
2064
2065         rcu_read_lock();
2066         list_for_each_entry_rcu(ns, &ctrl->namespaces, list) {
2067                 queue_flag_clear_unlocked(QUEUE_FLAG_STOPPED, ns->queue);
2068                 blk_mq_start_stopped_hw_queues(ns->queue, true);
2069                 blk_mq_kick_requeue_list(ns->queue);
2070         }
2071         rcu_read_unlock();
2072 }
2073 EXPORT_SYMBOL_GPL(nvme_start_queues);
2074
2075 int __init nvme_core_init(void)
2076 {
2077         int result;
2078
2079         result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2080                                                         &nvme_dev_fops);
2081         if (result < 0)
2082                 return result;
2083         else if (result > 0)
2084                 nvme_char_major = result;
2085
2086         nvme_class = class_create(THIS_MODULE, "nvme");
2087         if (IS_ERR(nvme_class)) {
2088                 result = PTR_ERR(nvme_class);
2089                 goto unregister_chrdev;
2090         }
2091
2092         return 0;
2093
2094  unregister_chrdev:
2095         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2096         return result;
2097 }
2098
2099 void nvme_core_exit(void)
2100 {
2101         class_destroy(nvme_class);
2102         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2103 }
2104
2105 MODULE_LICENSE("GPL");
2106 MODULE_VERSION("1.0");
2107 module_init(nvme_core_init);
2108 module_exit(nvme_core_exit);