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