]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/nvme/host/core.c
nvme: provide UUID value to userspace
[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 <linux/pm_qos.h>
30 #include <scsi/sg.h>
31 #include <asm/unaligned.h>
32
33 #include "nvme.h"
34 #include "fabrics.h"
35
36 #define NVME_MINORS             (1U << MINORBITS)
37
38 unsigned char admin_timeout = 60;
39 module_param(admin_timeout, byte, 0644);
40 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
41 EXPORT_SYMBOL_GPL(admin_timeout);
42
43 unsigned char nvme_io_timeout = 30;
44 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
45 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
46 EXPORT_SYMBOL_GPL(nvme_io_timeout);
47
48 unsigned char shutdown_timeout = 5;
49 module_param(shutdown_timeout, byte, 0644);
50 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
51
52 static u8 nvme_max_retries = 5;
53 module_param_named(max_retries, nvme_max_retries, byte, 0644);
54 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
55
56 static int nvme_char_major;
57 module_param(nvme_char_major, int, 0);
58
59 static unsigned long default_ps_max_latency_us = 100000;
60 module_param(default_ps_max_latency_us, ulong, 0644);
61 MODULE_PARM_DESC(default_ps_max_latency_us,
62                  "max power saving latency for new devices; use PM QOS to change per device");
63
64 static bool force_apst;
65 module_param(force_apst, bool, 0644);
66 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
67
68 struct workqueue_struct *nvme_wq;
69 EXPORT_SYMBOL_GPL(nvme_wq);
70
71 static LIST_HEAD(nvme_ctrl_list);
72 static DEFINE_SPINLOCK(dev_list_lock);
73
74 static struct class *nvme_class;
75
76 static blk_status_t nvme_error_status(struct request *req)
77 {
78         switch (nvme_req(req)->status & 0x7ff) {
79         case NVME_SC_SUCCESS:
80                 return BLK_STS_OK;
81         case NVME_SC_CAP_EXCEEDED:
82                 return BLK_STS_NOSPC;
83         case NVME_SC_ONCS_NOT_SUPPORTED:
84                 return BLK_STS_NOTSUPP;
85         case NVME_SC_WRITE_FAULT:
86         case NVME_SC_READ_ERROR:
87         case NVME_SC_UNWRITTEN_BLOCK:
88                 return BLK_STS_MEDIUM;
89         default:
90                 return BLK_STS_IOERR;
91         }
92 }
93
94 static inline bool nvme_req_needs_retry(struct request *req)
95 {
96         if (blk_noretry_request(req))
97                 return false;
98         if (nvme_req(req)->status & NVME_SC_DNR)
99                 return false;
100         if (jiffies - req->start_time >= req->timeout)
101                 return false;
102         if (nvme_req(req)->retries >= nvme_max_retries)
103                 return false;
104         return true;
105 }
106
107 void nvme_complete_rq(struct request *req)
108 {
109         if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
110                 nvme_req(req)->retries++;
111                 blk_mq_requeue_request(req, !blk_mq_queue_stopped(req->q));
112                 return;
113         }
114
115         blk_mq_end_request(req, nvme_error_status(req));
116 }
117 EXPORT_SYMBOL_GPL(nvme_complete_rq);
118
119 void nvme_cancel_request(struct request *req, void *data, bool reserved)
120 {
121         int status;
122
123         if (!blk_mq_request_started(req))
124                 return;
125
126         dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
127                                 "Cancelling I/O %d", req->tag);
128
129         status = NVME_SC_ABORT_REQ;
130         if (blk_queue_dying(req->q))
131                 status |= NVME_SC_DNR;
132         nvme_req(req)->status = status;
133         blk_mq_complete_request(req);
134
135 }
136 EXPORT_SYMBOL_GPL(nvme_cancel_request);
137
138 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
139                 enum nvme_ctrl_state new_state)
140 {
141         enum nvme_ctrl_state old_state;
142         bool changed = false;
143
144         spin_lock_irq(&ctrl->lock);
145
146         old_state = ctrl->state;
147         switch (new_state) {
148         case NVME_CTRL_LIVE:
149                 switch (old_state) {
150                 case NVME_CTRL_NEW:
151                 case NVME_CTRL_RESETTING:
152                 case NVME_CTRL_RECONNECTING:
153                         changed = true;
154                         /* FALLTHRU */
155                 default:
156                         break;
157                 }
158                 break;
159         case NVME_CTRL_RESETTING:
160                 switch (old_state) {
161                 case NVME_CTRL_NEW:
162                 case NVME_CTRL_LIVE:
163                         changed = true;
164                         /* FALLTHRU */
165                 default:
166                         break;
167                 }
168                 break;
169         case NVME_CTRL_RECONNECTING:
170                 switch (old_state) {
171                 case NVME_CTRL_LIVE:
172                         changed = true;
173                         /* FALLTHRU */
174                 default:
175                         break;
176                 }
177                 break;
178         case NVME_CTRL_DELETING:
179                 switch (old_state) {
180                 case NVME_CTRL_LIVE:
181                 case NVME_CTRL_RESETTING:
182                 case NVME_CTRL_RECONNECTING:
183                         changed = true;
184                         /* FALLTHRU */
185                 default:
186                         break;
187                 }
188                 break;
189         case NVME_CTRL_DEAD:
190                 switch (old_state) {
191                 case NVME_CTRL_DELETING:
192                         changed = true;
193                         /* FALLTHRU */
194                 default:
195                         break;
196                 }
197                 break;
198         default:
199                 break;
200         }
201
202         if (changed)
203                 ctrl->state = new_state;
204
205         spin_unlock_irq(&ctrl->lock);
206
207         return changed;
208 }
209 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
210
211 static void nvme_free_ns(struct kref *kref)
212 {
213         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
214
215         if (ns->ndev)
216                 nvme_nvm_unregister(ns);
217
218         if (ns->disk) {
219                 spin_lock(&dev_list_lock);
220                 ns->disk->private_data = NULL;
221                 spin_unlock(&dev_list_lock);
222         }
223
224         put_disk(ns->disk);
225         ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
226         nvme_put_ctrl(ns->ctrl);
227         kfree(ns);
228 }
229
230 static void nvme_put_ns(struct nvme_ns *ns)
231 {
232         kref_put(&ns->kref, nvme_free_ns);
233 }
234
235 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
236 {
237         struct nvme_ns *ns;
238
239         spin_lock(&dev_list_lock);
240         ns = disk->private_data;
241         if (ns) {
242                 if (!kref_get_unless_zero(&ns->kref))
243                         goto fail;
244                 if (!try_module_get(ns->ctrl->ops->module))
245                         goto fail_put_ns;
246         }
247         spin_unlock(&dev_list_lock);
248
249         return ns;
250
251 fail_put_ns:
252         kref_put(&ns->kref, nvme_free_ns);
253 fail:
254         spin_unlock(&dev_list_lock);
255         return NULL;
256 }
257
258 struct request *nvme_alloc_request(struct request_queue *q,
259                 struct nvme_command *cmd, unsigned int flags, int qid)
260 {
261         unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
262         struct request *req;
263
264         if (qid == NVME_QID_ANY) {
265                 req = blk_mq_alloc_request(q, op, flags);
266         } else {
267                 req = blk_mq_alloc_request_hctx(q, op, flags,
268                                 qid ? qid - 1 : 0);
269         }
270         if (IS_ERR(req))
271                 return req;
272
273         req->cmd_flags |= REQ_FAILFAST_DRIVER;
274         nvme_req(req)->cmd = cmd;
275
276         return req;
277 }
278 EXPORT_SYMBOL_GPL(nvme_alloc_request);
279
280 static inline void nvme_setup_flush(struct nvme_ns *ns,
281                 struct nvme_command *cmnd)
282 {
283         memset(cmnd, 0, sizeof(*cmnd));
284         cmnd->common.opcode = nvme_cmd_flush;
285         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
286 }
287
288 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
289                 struct nvme_command *cmnd)
290 {
291         unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
292         struct nvme_dsm_range *range;
293         struct bio *bio;
294
295         range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
296         if (!range)
297                 return BLK_STS_RESOURCE;
298
299         __rq_for_each_bio(bio, req) {
300                 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
301                 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
302
303                 range[n].cattr = cpu_to_le32(0);
304                 range[n].nlb = cpu_to_le32(nlb);
305                 range[n].slba = cpu_to_le64(slba);
306                 n++;
307         }
308
309         if (WARN_ON_ONCE(n != segments)) {
310                 kfree(range);
311                 return BLK_STS_IOERR;
312         }
313
314         memset(cmnd, 0, sizeof(*cmnd));
315         cmnd->dsm.opcode = nvme_cmd_dsm;
316         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
317         cmnd->dsm.nr = cpu_to_le32(segments - 1);
318         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
319
320         req->special_vec.bv_page = virt_to_page(range);
321         req->special_vec.bv_offset = offset_in_page(range);
322         req->special_vec.bv_len = sizeof(*range) * segments;
323         req->rq_flags |= RQF_SPECIAL_PAYLOAD;
324
325         return BLK_STS_OK;
326 }
327
328 static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
329                 struct nvme_command *cmnd)
330 {
331         u16 control = 0;
332         u32 dsmgmt = 0;
333
334         if (req->cmd_flags & REQ_FUA)
335                 control |= NVME_RW_FUA;
336         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
337                 control |= NVME_RW_LR;
338
339         if (req->cmd_flags & REQ_RAHEAD)
340                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
341
342         memset(cmnd, 0, sizeof(*cmnd));
343         cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
344         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
345         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
346         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
347
348         if (ns->ms) {
349                 switch (ns->pi_type) {
350                 case NVME_NS_DPS_PI_TYPE3:
351                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
352                         break;
353                 case NVME_NS_DPS_PI_TYPE1:
354                 case NVME_NS_DPS_PI_TYPE2:
355                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
356                                         NVME_RW_PRINFO_PRCHK_REF;
357                         cmnd->rw.reftag = cpu_to_le32(
358                                         nvme_block_nr(ns, blk_rq_pos(req)));
359                         break;
360                 }
361                 if (!blk_integrity_rq(req))
362                         control |= NVME_RW_PRINFO_PRACT;
363         }
364
365         cmnd->rw.control = cpu_to_le16(control);
366         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
367 }
368
369 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
370                 struct nvme_command *cmd)
371 {
372         blk_status_t ret = BLK_STS_OK;
373
374         if (!(req->rq_flags & RQF_DONTPREP)) {
375                 nvme_req(req)->retries = 0;
376                 nvme_req(req)->flags = 0;
377                 req->rq_flags |= RQF_DONTPREP;
378         }
379
380         switch (req_op(req)) {
381         case REQ_OP_DRV_IN:
382         case REQ_OP_DRV_OUT:
383                 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
384                 break;
385         case REQ_OP_FLUSH:
386                 nvme_setup_flush(ns, cmd);
387                 break;
388         case REQ_OP_WRITE_ZEROES:
389                 /* currently only aliased to deallocate for a few ctrls: */
390         case REQ_OP_DISCARD:
391                 ret = nvme_setup_discard(ns, req, cmd);
392                 break;
393         case REQ_OP_READ:
394         case REQ_OP_WRITE:
395                 nvme_setup_rw(ns, req, cmd);
396                 break;
397         default:
398                 WARN_ON_ONCE(1);
399                 return BLK_STS_IOERR;
400         }
401
402         cmd->common.command_id = req->tag;
403         return ret;
404 }
405 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
406
407 /*
408  * Returns 0 on success.  If the result is negative, it's a Linux error code;
409  * if the result is positive, it's an NVM Express status code
410  */
411 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
412                 union nvme_result *result, void *buffer, unsigned bufflen,
413                 unsigned timeout, int qid, int at_head, int flags)
414 {
415         struct request *req;
416         int ret;
417
418         req = nvme_alloc_request(q, cmd, flags, qid);
419         if (IS_ERR(req))
420                 return PTR_ERR(req);
421
422         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
423
424         if (buffer && bufflen) {
425                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
426                 if (ret)
427                         goto out;
428         }
429
430         blk_execute_rq(req->q, NULL, req, at_head);
431         if (result)
432                 *result = nvme_req(req)->result;
433         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
434                 ret = -EINTR;
435         else
436                 ret = nvme_req(req)->status;
437  out:
438         blk_mq_free_request(req);
439         return ret;
440 }
441 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
442
443 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
444                 void *buffer, unsigned bufflen)
445 {
446         return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
447                         NVME_QID_ANY, 0, 0);
448 }
449 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
450
451 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
452                 void __user *ubuffer, unsigned bufflen,
453                 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
454                 u32 *result, unsigned timeout)
455 {
456         bool write = nvme_is_write(cmd);
457         struct nvme_ns *ns = q->queuedata;
458         struct gendisk *disk = ns ? ns->disk : NULL;
459         struct request *req;
460         struct bio *bio = NULL;
461         void *meta = NULL;
462         int ret;
463
464         req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
465         if (IS_ERR(req))
466                 return PTR_ERR(req);
467
468         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
469
470         if (ubuffer && bufflen) {
471                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
472                                 GFP_KERNEL);
473                 if (ret)
474                         goto out;
475                 bio = req->bio;
476
477                 if (!disk)
478                         goto submit;
479                 bio->bi_bdev = bdget_disk(disk, 0);
480                 if (!bio->bi_bdev) {
481                         ret = -ENODEV;
482                         goto out_unmap;
483                 }
484
485                 if (meta_buffer && meta_len) {
486                         struct bio_integrity_payload *bip;
487
488                         meta = kmalloc(meta_len, GFP_KERNEL);
489                         if (!meta) {
490                                 ret = -ENOMEM;
491                                 goto out_unmap;
492                         }
493
494                         if (write) {
495                                 if (copy_from_user(meta, meta_buffer,
496                                                 meta_len)) {
497                                         ret = -EFAULT;
498                                         goto out_free_meta;
499                                 }
500                         }
501
502                         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
503                         if (IS_ERR(bip)) {
504                                 ret = PTR_ERR(bip);
505                                 goto out_free_meta;
506                         }
507
508                         bip->bip_iter.bi_size = meta_len;
509                         bip->bip_iter.bi_sector = meta_seed;
510
511                         ret = bio_integrity_add_page(bio, virt_to_page(meta),
512                                         meta_len, offset_in_page(meta));
513                         if (ret != meta_len) {
514                                 ret = -ENOMEM;
515                                 goto out_free_meta;
516                         }
517                 }
518         }
519  submit:
520         blk_execute_rq(req->q, disk, req, 0);
521         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
522                 ret = -EINTR;
523         else
524                 ret = nvme_req(req)->status;
525         if (result)
526                 *result = le32_to_cpu(nvme_req(req)->result.u32);
527         if (meta && !ret && !write) {
528                 if (copy_to_user(meta_buffer, meta, meta_len))
529                         ret = -EFAULT;
530         }
531  out_free_meta:
532         kfree(meta);
533  out_unmap:
534         if (bio) {
535                 if (disk && bio->bi_bdev)
536                         bdput(bio->bi_bdev);
537                 blk_rq_unmap_user(bio);
538         }
539  out:
540         blk_mq_free_request(req);
541         return ret;
542 }
543
544 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
545                 void __user *ubuffer, unsigned bufflen, u32 *result,
546                 unsigned timeout)
547 {
548         return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
549                         result, timeout);
550 }
551
552 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
553 {
554         struct nvme_ctrl *ctrl = rq->end_io_data;
555
556         blk_mq_free_request(rq);
557
558         if (status) {
559                 dev_err(ctrl->device,
560                         "failed nvme_keep_alive_end_io error=%d\n",
561                                 status);
562                 return;
563         }
564
565         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
566 }
567
568 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
569 {
570         struct nvme_command c;
571         struct request *rq;
572
573         memset(&c, 0, sizeof(c));
574         c.common.opcode = nvme_admin_keep_alive;
575
576         rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
577                         NVME_QID_ANY);
578         if (IS_ERR(rq))
579                 return PTR_ERR(rq);
580
581         rq->timeout = ctrl->kato * HZ;
582         rq->end_io_data = ctrl;
583
584         blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
585
586         return 0;
587 }
588
589 static void nvme_keep_alive_work(struct work_struct *work)
590 {
591         struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
592                         struct nvme_ctrl, ka_work);
593
594         if (nvme_keep_alive(ctrl)) {
595                 /* allocation failure, reset the controller */
596                 dev_err(ctrl->device, "keep-alive failed\n");
597                 ctrl->ops->reset_ctrl(ctrl);
598                 return;
599         }
600 }
601
602 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
603 {
604         if (unlikely(ctrl->kato == 0))
605                 return;
606
607         INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
608         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
609 }
610 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
611
612 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
613 {
614         if (unlikely(ctrl->kato == 0))
615                 return;
616
617         cancel_delayed_work_sync(&ctrl->ka_work);
618 }
619 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
620
621 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
622 {
623         struct nvme_command c = { };
624         int error;
625
626         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
627         c.identify.opcode = nvme_admin_identify;
628         c.identify.cns = NVME_ID_CNS_CTRL;
629
630         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
631         if (!*id)
632                 return -ENOMEM;
633
634         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
635                         sizeof(struct nvme_id_ctrl));
636         if (error)
637                 kfree(*id);
638         return error;
639 }
640
641 static int nvme_identify_ns_descs(struct nvme_ns *ns, unsigned nsid)
642 {
643         struct nvme_command c = { };
644         int status;
645         void *data;
646         int pos;
647         int len;
648
649         c.identify.opcode = nvme_admin_identify;
650         c.identify.nsid = cpu_to_le32(nsid);
651         c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
652
653         data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
654         if (!data)
655                 return -ENOMEM;
656
657         status = nvme_submit_sync_cmd(ns->ctrl->admin_q, &c, data,
658                                       NVME_IDENTIFY_DATA_SIZE);
659         if (status)
660                 goto free_data;
661
662         for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
663                 struct nvme_ns_id_desc *cur = data + pos;
664
665                 if (cur->nidl == 0)
666                         break;
667
668                 switch (cur->nidt) {
669                 case NVME_NIDT_EUI64:
670                         if (cur->nidl != NVME_NIDT_EUI64_LEN) {
671                                 dev_warn(ns->ctrl->device,
672                                          "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
673                                          cur->nidl);
674                                 goto free_data;
675                         }
676                         len = NVME_NIDT_EUI64_LEN;
677                         memcpy(ns->eui, data + pos + sizeof(*cur), len);
678                         break;
679                 case NVME_NIDT_NGUID:
680                         if (cur->nidl != NVME_NIDT_NGUID_LEN) {
681                                 dev_warn(ns->ctrl->device,
682                                          "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
683                                          cur->nidl);
684                                 goto free_data;
685                         }
686                         len = NVME_NIDT_NGUID_LEN;
687                         memcpy(ns->nguid, data + pos + sizeof(*cur), len);
688                         break;
689                 case NVME_NIDT_UUID:
690                         if (cur->nidl != NVME_NIDT_UUID_LEN) {
691                                 dev_warn(ns->ctrl->device,
692                                          "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
693                                          cur->nidl);
694                                 goto free_data;
695                         }
696                         len = NVME_NIDT_UUID_LEN;
697                         uuid_copy(&ns->uuid, data + pos + sizeof(*cur));
698                         break;
699                 default:
700                         /* Skip unnkown types */
701                         len = cur->nidl;
702                         break;
703                 }
704
705                 len += sizeof(*cur);
706         }
707 free_data:
708         kfree(data);
709         return status;
710 }
711
712 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
713 {
714         struct nvme_command c = { };
715
716         c.identify.opcode = nvme_admin_identify;
717         c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
718         c.identify.nsid = cpu_to_le32(nsid);
719         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
720 }
721
722 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
723                 struct nvme_id_ns **id)
724 {
725         struct nvme_command c = { };
726         int error;
727
728         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
729         c.identify.opcode = nvme_admin_identify;
730         c.identify.nsid = cpu_to_le32(nsid);
731         c.identify.cns = NVME_ID_CNS_NS;
732
733         *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
734         if (!*id)
735                 return -ENOMEM;
736
737         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
738                         sizeof(struct nvme_id_ns));
739         if (error)
740                 kfree(*id);
741         return error;
742 }
743
744 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
745                       void *buffer, size_t buflen, u32 *result)
746 {
747         struct nvme_command c;
748         union nvme_result res;
749         int ret;
750
751         memset(&c, 0, sizeof(c));
752         c.features.opcode = nvme_admin_get_features;
753         c.features.nsid = cpu_to_le32(nsid);
754         c.features.fid = cpu_to_le32(fid);
755
756         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, buffer, buflen, 0,
757                         NVME_QID_ANY, 0, 0);
758         if (ret >= 0 && result)
759                 *result = le32_to_cpu(res.u32);
760         return ret;
761 }
762
763 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
764                       void *buffer, size_t buflen, u32 *result)
765 {
766         struct nvme_command c;
767         union nvme_result res;
768         int ret;
769
770         memset(&c, 0, sizeof(c));
771         c.features.opcode = nvme_admin_set_features;
772         c.features.fid = cpu_to_le32(fid);
773         c.features.dword11 = cpu_to_le32(dword11);
774
775         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
776                         buffer, buflen, 0, NVME_QID_ANY, 0, 0);
777         if (ret >= 0 && result)
778                 *result = le32_to_cpu(res.u32);
779         return ret;
780 }
781
782 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
783 {
784         struct nvme_command c = { };
785         int error;
786
787         c.common.opcode = nvme_admin_get_log_page,
788         c.common.nsid = cpu_to_le32(0xFFFFFFFF),
789         c.common.cdw10[0] = cpu_to_le32(
790                         (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
791                          NVME_LOG_SMART),
792
793         *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
794         if (!*log)
795                 return -ENOMEM;
796
797         error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
798                         sizeof(struct nvme_smart_log));
799         if (error)
800                 kfree(*log);
801         return error;
802 }
803
804 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
805 {
806         u32 q_count = (*count - 1) | ((*count - 1) << 16);
807         u32 result;
808         int status, nr_io_queues;
809
810         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
811                         &result);
812         if (status < 0)
813                 return status;
814
815         /*
816          * Degraded controllers might return an error when setting the queue
817          * count.  We still want to be able to bring them online and offer
818          * access to the admin queue, as that might be only way to fix them up.
819          */
820         if (status > 0) {
821                 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
822                 *count = 0;
823         } else {
824                 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
825                 *count = min(*count, nr_io_queues);
826         }
827
828         return 0;
829 }
830 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
831
832 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
833 {
834         struct nvme_user_io io;
835         struct nvme_command c;
836         unsigned length, meta_len;
837         void __user *metadata;
838
839         if (copy_from_user(&io, uio, sizeof(io)))
840                 return -EFAULT;
841         if (io.flags)
842                 return -EINVAL;
843
844         switch (io.opcode) {
845         case nvme_cmd_write:
846         case nvme_cmd_read:
847         case nvme_cmd_compare:
848                 break;
849         default:
850                 return -EINVAL;
851         }
852
853         length = (io.nblocks + 1) << ns->lba_shift;
854         meta_len = (io.nblocks + 1) * ns->ms;
855         metadata = (void __user *)(uintptr_t)io.metadata;
856
857         if (ns->ext) {
858                 length += meta_len;
859                 meta_len = 0;
860         } else if (meta_len) {
861                 if ((io.metadata & 3) || !io.metadata)
862                         return -EINVAL;
863         }
864
865         memset(&c, 0, sizeof(c));
866         c.rw.opcode = io.opcode;
867         c.rw.flags = io.flags;
868         c.rw.nsid = cpu_to_le32(ns->ns_id);
869         c.rw.slba = cpu_to_le64(io.slba);
870         c.rw.length = cpu_to_le16(io.nblocks);
871         c.rw.control = cpu_to_le16(io.control);
872         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
873         c.rw.reftag = cpu_to_le32(io.reftag);
874         c.rw.apptag = cpu_to_le16(io.apptag);
875         c.rw.appmask = cpu_to_le16(io.appmask);
876
877         return __nvme_submit_user_cmd(ns->queue, &c,
878                         (void __user *)(uintptr_t)io.addr, length,
879                         metadata, meta_len, io.slba, NULL, 0);
880 }
881
882 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
883                         struct nvme_passthru_cmd __user *ucmd)
884 {
885         struct nvme_passthru_cmd cmd;
886         struct nvme_command c;
887         unsigned timeout = 0;
888         int status;
889
890         if (!capable(CAP_SYS_ADMIN))
891                 return -EACCES;
892         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
893                 return -EFAULT;
894         if (cmd.flags)
895                 return -EINVAL;
896
897         memset(&c, 0, sizeof(c));
898         c.common.opcode = cmd.opcode;
899         c.common.flags = cmd.flags;
900         c.common.nsid = cpu_to_le32(cmd.nsid);
901         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
902         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
903         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
904         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
905         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
906         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
907         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
908         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
909
910         if (cmd.timeout_ms)
911                 timeout = msecs_to_jiffies(cmd.timeout_ms);
912
913         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
914                         (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
915                         &cmd.result, timeout);
916         if (status >= 0) {
917                 if (put_user(cmd.result, &ucmd->result))
918                         return -EFAULT;
919         }
920
921         return status;
922 }
923
924 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
925                 unsigned int cmd, unsigned long arg)
926 {
927         struct nvme_ns *ns = bdev->bd_disk->private_data;
928
929         switch (cmd) {
930         case NVME_IOCTL_ID:
931                 force_successful_syscall_return();
932                 return ns->ns_id;
933         case NVME_IOCTL_ADMIN_CMD:
934                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
935         case NVME_IOCTL_IO_CMD:
936                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
937         case NVME_IOCTL_SUBMIT_IO:
938                 return nvme_submit_io(ns, (void __user *)arg);
939 #ifdef CONFIG_BLK_DEV_NVME_SCSI
940         case SG_GET_VERSION_NUM:
941                 return nvme_sg_get_version_num((void __user *)arg);
942         case SG_IO:
943                 return nvme_sg_io(ns, (void __user *)arg);
944 #endif
945         default:
946 #ifdef CONFIG_NVM
947                 if (ns->ndev)
948                         return nvme_nvm_ioctl(ns, cmd, arg);
949 #endif
950                 if (is_sed_ioctl(cmd))
951                         return sed_ioctl(ns->ctrl->opal_dev, cmd,
952                                          (void __user *) arg);
953                 return -ENOTTY;
954         }
955 }
956
957 #ifdef CONFIG_COMPAT
958 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
959                         unsigned int cmd, unsigned long arg)
960 {
961         switch (cmd) {
962         case SG_IO:
963                 return -ENOIOCTLCMD;
964         }
965         return nvme_ioctl(bdev, mode, cmd, arg);
966 }
967 #else
968 #define nvme_compat_ioctl       NULL
969 #endif
970
971 static int nvme_open(struct block_device *bdev, fmode_t mode)
972 {
973         return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
974 }
975
976 static void nvme_release(struct gendisk *disk, fmode_t mode)
977 {
978         struct nvme_ns *ns = disk->private_data;
979
980         module_put(ns->ctrl->ops->module);
981         nvme_put_ns(ns);
982 }
983
984 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
985 {
986         /* some standard values */
987         geo->heads = 1 << 6;
988         geo->sectors = 1 << 5;
989         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
990         return 0;
991 }
992
993 #ifdef CONFIG_BLK_DEV_INTEGRITY
994 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
995                 u16 bs)
996 {
997         struct nvme_ns *ns = disk->private_data;
998         u16 old_ms = ns->ms;
999         u8 pi_type = 0;
1000
1001         ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1002         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1003
1004         /* PI implementation requires metadata equal t10 pi tuple size */
1005         if (ns->ms == sizeof(struct t10_pi_tuple))
1006                 pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1007
1008         if (blk_get_integrity(disk) &&
1009             (ns->pi_type != pi_type || ns->ms != old_ms ||
1010              bs != queue_logical_block_size(disk->queue) ||
1011              (ns->ms && ns->ext)))
1012                 blk_integrity_unregister(disk);
1013
1014         ns->pi_type = pi_type;
1015 }
1016
1017 static void nvme_init_integrity(struct nvme_ns *ns)
1018 {
1019         struct blk_integrity integrity;
1020
1021         memset(&integrity, 0, sizeof(integrity));
1022         switch (ns->pi_type) {
1023         case NVME_NS_DPS_PI_TYPE3:
1024                 integrity.profile = &t10_pi_type3_crc;
1025                 integrity.tag_size = sizeof(u16) + sizeof(u32);
1026                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1027                 break;
1028         case NVME_NS_DPS_PI_TYPE1:
1029         case NVME_NS_DPS_PI_TYPE2:
1030                 integrity.profile = &t10_pi_type1_crc;
1031                 integrity.tag_size = sizeof(u16);
1032                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1033                 break;
1034         default:
1035                 integrity.profile = NULL;
1036                 break;
1037         }
1038         integrity.tuple_size = ns->ms;
1039         blk_integrity_register(ns->disk, &integrity);
1040         blk_queue_max_integrity_segments(ns->queue, 1);
1041 }
1042 #else
1043 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1044                 u16 bs)
1045 {
1046 }
1047 static void nvme_init_integrity(struct nvme_ns *ns)
1048 {
1049 }
1050 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1051
1052 static void nvme_config_discard(struct nvme_ns *ns)
1053 {
1054         struct nvme_ctrl *ctrl = ns->ctrl;
1055         u32 logical_block_size = queue_logical_block_size(ns->queue);
1056
1057         BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1058                         NVME_DSM_MAX_RANGES);
1059
1060         ns->queue->limits.discard_alignment = logical_block_size;
1061         ns->queue->limits.discard_granularity = logical_block_size;
1062         blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
1063         blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1064         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1065
1066         if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1067                 blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1068 }
1069
1070 static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
1071 {
1072         if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
1073                 dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
1074                 return -ENODEV;
1075         }
1076
1077         if ((*id)->ncap == 0) {
1078                 kfree(*id);
1079                 return -ENODEV;
1080         }
1081
1082         if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
1083                 memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
1084         if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
1085                 memcpy(ns->nguid, (*id)->nguid, sizeof(ns->nguid));
1086         if (ns->ctrl->vs >= NVME_VS(1, 3, 0)) {
1087                  /* Don't treat error as fatal we potentially
1088                   * already have a NGUID or EUI-64
1089                   */
1090                 if (nvme_identify_ns_descs(ns, ns->ns_id))
1091                         dev_warn(ns->ctrl->device,
1092                                  "%s: Identify Descriptors failed\n", __func__);
1093         }
1094
1095         return 0;
1096 }
1097
1098 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1099 {
1100         struct nvme_ns *ns = disk->private_data;
1101         u16 bs;
1102
1103         /*
1104          * If identify namespace failed, use default 512 byte block size so
1105          * block layer can use before failing read/write for 0 capacity.
1106          */
1107         ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1108         if (ns->lba_shift == 0)
1109                 ns->lba_shift = 9;
1110         bs = 1 << ns->lba_shift;
1111
1112         blk_mq_freeze_queue(disk->queue);
1113
1114         if (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
1115                 nvme_prep_integrity(disk, id, bs);
1116         blk_queue_logical_block_size(ns->queue, bs);
1117         if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1118                 nvme_init_integrity(ns);
1119         if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1120                 set_capacity(disk, 0);
1121         else
1122                 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1123
1124         if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
1125                 nvme_config_discard(ns);
1126         blk_mq_unfreeze_queue(disk->queue);
1127 }
1128
1129 static int nvme_revalidate_disk(struct gendisk *disk)
1130 {
1131         struct nvme_ns *ns = disk->private_data;
1132         struct nvme_id_ns *id = NULL;
1133         int ret;
1134
1135         if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1136                 set_capacity(disk, 0);
1137                 return -ENODEV;
1138         }
1139
1140         ret = nvme_revalidate_ns(ns, &id);
1141         if (ret)
1142                 return ret;
1143
1144         __nvme_revalidate_disk(disk, id);
1145         kfree(id);
1146
1147         return 0;
1148 }
1149
1150 static char nvme_pr_type(enum pr_type type)
1151 {
1152         switch (type) {
1153         case PR_WRITE_EXCLUSIVE:
1154                 return 1;
1155         case PR_EXCLUSIVE_ACCESS:
1156                 return 2;
1157         case PR_WRITE_EXCLUSIVE_REG_ONLY:
1158                 return 3;
1159         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1160                 return 4;
1161         case PR_WRITE_EXCLUSIVE_ALL_REGS:
1162                 return 5;
1163         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1164                 return 6;
1165         default:
1166                 return 0;
1167         }
1168 };
1169
1170 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1171                                 u64 key, u64 sa_key, u8 op)
1172 {
1173         struct nvme_ns *ns = bdev->bd_disk->private_data;
1174         struct nvme_command c;
1175         u8 data[16] = { 0, };
1176
1177         put_unaligned_le64(key, &data[0]);
1178         put_unaligned_le64(sa_key, &data[8]);
1179
1180         memset(&c, 0, sizeof(c));
1181         c.common.opcode = op;
1182         c.common.nsid = cpu_to_le32(ns->ns_id);
1183         c.common.cdw10[0] = cpu_to_le32(cdw10);
1184
1185         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1186 }
1187
1188 static int nvme_pr_register(struct block_device *bdev, u64 old,
1189                 u64 new, unsigned flags)
1190 {
1191         u32 cdw10;
1192
1193         if (flags & ~PR_FL_IGNORE_KEY)
1194                 return -EOPNOTSUPP;
1195
1196         cdw10 = old ? 2 : 0;
1197         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1198         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1199         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1200 }
1201
1202 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1203                 enum pr_type type, unsigned flags)
1204 {
1205         u32 cdw10;
1206
1207         if (flags & ~PR_FL_IGNORE_KEY)
1208                 return -EOPNOTSUPP;
1209
1210         cdw10 = nvme_pr_type(type) << 8;
1211         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1212         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1213 }
1214
1215 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1216                 enum pr_type type, bool abort)
1217 {
1218         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1219         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1220 }
1221
1222 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1223 {
1224         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1225         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1226 }
1227
1228 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1229 {
1230         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1231         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1232 }
1233
1234 static const struct pr_ops nvme_pr_ops = {
1235         .pr_register    = nvme_pr_register,
1236         .pr_reserve     = nvme_pr_reserve,
1237         .pr_release     = nvme_pr_release,
1238         .pr_preempt     = nvme_pr_preempt,
1239         .pr_clear       = nvme_pr_clear,
1240 };
1241
1242 #ifdef CONFIG_BLK_SED_OPAL
1243 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1244                 bool send)
1245 {
1246         struct nvme_ctrl *ctrl = data;
1247         struct nvme_command cmd;
1248
1249         memset(&cmd, 0, sizeof(cmd));
1250         if (send)
1251                 cmd.common.opcode = nvme_admin_security_send;
1252         else
1253                 cmd.common.opcode = nvme_admin_security_recv;
1254         cmd.common.nsid = 0;
1255         cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1256         cmd.common.cdw10[1] = cpu_to_le32(len);
1257
1258         return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1259                                       ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1260 }
1261 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1262 #endif /* CONFIG_BLK_SED_OPAL */
1263
1264 static const struct block_device_operations nvme_fops = {
1265         .owner          = THIS_MODULE,
1266         .ioctl          = nvme_ioctl,
1267         .compat_ioctl   = nvme_compat_ioctl,
1268         .open           = nvme_open,
1269         .release        = nvme_release,
1270         .getgeo         = nvme_getgeo,
1271         .revalidate_disk= nvme_revalidate_disk,
1272         .pr_ops         = &nvme_pr_ops,
1273 };
1274
1275 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1276 {
1277         unsigned long timeout =
1278                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1279         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1280         int ret;
1281
1282         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1283                 if (csts == ~0)
1284                         return -ENODEV;
1285                 if ((csts & NVME_CSTS_RDY) == bit)
1286                         break;
1287
1288                 msleep(100);
1289                 if (fatal_signal_pending(current))
1290                         return -EINTR;
1291                 if (time_after(jiffies, timeout)) {
1292                         dev_err(ctrl->device,
1293                                 "Device not ready; aborting %s\n", enabled ?
1294                                                 "initialisation" : "reset");
1295                         return -ENODEV;
1296                 }
1297         }
1298
1299         return ret;
1300 }
1301
1302 /*
1303  * If the device has been passed off to us in an enabled state, just clear
1304  * the enabled bit.  The spec says we should set the 'shutdown notification
1305  * bits', but doing so may cause the device to complete commands to the
1306  * admin queue ... and we don't know what memory that might be pointing at!
1307  */
1308 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1309 {
1310         int ret;
1311
1312         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1313         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1314
1315         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1316         if (ret)
1317                 return ret;
1318
1319         if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1320                 msleep(NVME_QUIRK_DELAY_AMOUNT);
1321
1322         return nvme_wait_ready(ctrl, cap, false);
1323 }
1324 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1325
1326 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1327 {
1328         /*
1329          * Default to a 4K page size, with the intention to update this
1330          * path in the future to accomodate architectures with differing
1331          * kernel and IO page sizes.
1332          */
1333         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1334         int ret;
1335
1336         if (page_shift < dev_page_min) {
1337                 dev_err(ctrl->device,
1338                         "Minimum device page size %u too large for host (%u)\n",
1339                         1 << dev_page_min, 1 << page_shift);
1340                 return -ENODEV;
1341         }
1342
1343         ctrl->page_size = 1 << page_shift;
1344
1345         ctrl->ctrl_config = NVME_CC_CSS_NVM;
1346         ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1347         ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1348         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1349         ctrl->ctrl_config |= NVME_CC_ENABLE;
1350
1351         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1352         if (ret)
1353                 return ret;
1354         return nvme_wait_ready(ctrl, cap, true);
1355 }
1356 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1357
1358 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1359 {
1360         unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1361         u32 csts;
1362         int ret;
1363
1364         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1365         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1366
1367         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1368         if (ret)
1369                 return ret;
1370
1371         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1372                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1373                         break;
1374
1375                 msleep(100);
1376                 if (fatal_signal_pending(current))
1377                         return -EINTR;
1378                 if (time_after(jiffies, timeout)) {
1379                         dev_err(ctrl->device,
1380                                 "Device shutdown incomplete; abort shutdown\n");
1381                         return -ENODEV;
1382                 }
1383         }
1384
1385         return ret;
1386 }
1387 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1388
1389 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1390                 struct request_queue *q)
1391 {
1392         bool vwc = false;
1393
1394         if (ctrl->max_hw_sectors) {
1395                 u32 max_segments =
1396                         (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1397
1398                 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1399                 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1400         }
1401         if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1402                 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1403         blk_queue_virt_boundary(q, ctrl->page_size - 1);
1404         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1405                 vwc = true;
1406         blk_queue_write_cache(q, vwc, vwc);
1407 }
1408
1409 static void nvme_configure_apst(struct nvme_ctrl *ctrl)
1410 {
1411         /*
1412          * APST (Autonomous Power State Transition) lets us program a
1413          * table of power state transitions that the controller will
1414          * perform automatically.  We configure it with a simple
1415          * heuristic: we are willing to spend at most 2% of the time
1416          * transitioning between power states.  Therefore, when running
1417          * in any given state, we will enter the next lower-power
1418          * non-operational state after waiting 50 * (enlat + exlat)
1419          * microseconds, as long as that state's exit latency is under
1420          * the requested maximum latency.
1421          *
1422          * We will not autonomously enter any non-operational state for
1423          * which the total latency exceeds ps_max_latency_us.  Users
1424          * can set ps_max_latency_us to zero to turn off APST.
1425          */
1426
1427         unsigned apste;
1428         struct nvme_feat_auto_pst *table;
1429         u64 max_lat_us = 0;
1430         int max_ps = -1;
1431         int ret;
1432
1433         /*
1434          * If APST isn't supported or if we haven't been initialized yet,
1435          * then don't do anything.
1436          */
1437         if (!ctrl->apsta)
1438                 return;
1439
1440         if (ctrl->npss > 31) {
1441                 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1442                 return;
1443         }
1444
1445         table = kzalloc(sizeof(*table), GFP_KERNEL);
1446         if (!table)
1447                 return;
1448
1449         if (ctrl->ps_max_latency_us == 0) {
1450                 /* Turn off APST. */
1451                 apste = 0;
1452                 dev_dbg(ctrl->device, "APST disabled\n");
1453         } else {
1454                 __le64 target = cpu_to_le64(0);
1455                 int state;
1456
1457                 /*
1458                  * Walk through all states from lowest- to highest-power.
1459                  * According to the spec, lower-numbered states use more
1460                  * power.  NPSS, despite the name, is the index of the
1461                  * lowest-power state, not the number of states.
1462                  */
1463                 for (state = (int)ctrl->npss; state >= 0; state--) {
1464                         u64 total_latency_us, exit_latency_us, transition_ms;
1465
1466                         if (target)
1467                                 table->entries[state] = target;
1468
1469                         /*
1470                          * Don't allow transitions to the deepest state
1471                          * if it's quirked off.
1472                          */
1473                         if (state == ctrl->npss &&
1474                             (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1475                                 continue;
1476
1477                         /*
1478                          * Is this state a useful non-operational state for
1479                          * higher-power states to autonomously transition to?
1480                          */
1481                         if (!(ctrl->psd[state].flags &
1482                               NVME_PS_FLAGS_NON_OP_STATE))
1483                                 continue;
1484
1485                         exit_latency_us =
1486                                 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1487                         if (exit_latency_us > ctrl->ps_max_latency_us)
1488                                 continue;
1489
1490                         total_latency_us =
1491                                 exit_latency_us +
1492                                 le32_to_cpu(ctrl->psd[state].entry_lat);
1493
1494                         /*
1495                          * This state is good.  Use it as the APST idle
1496                          * target for higher power states.
1497                          */
1498                         transition_ms = total_latency_us + 19;
1499                         do_div(transition_ms, 20);
1500                         if (transition_ms > (1 << 24) - 1)
1501                                 transition_ms = (1 << 24) - 1;
1502
1503                         target = cpu_to_le64((state << 3) |
1504                                              (transition_ms << 8));
1505
1506                         if (max_ps == -1)
1507                                 max_ps = state;
1508
1509                         if (total_latency_us > max_lat_us)
1510                                 max_lat_us = total_latency_us;
1511                 }
1512
1513                 apste = 1;
1514
1515                 if (max_ps == -1) {
1516                         dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1517                 } else {
1518                         dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1519                                 max_ps, max_lat_us, (int)sizeof(*table), table);
1520                 }
1521         }
1522
1523         ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1524                                 table, sizeof(*table), NULL);
1525         if (ret)
1526                 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1527
1528         kfree(table);
1529 }
1530
1531 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1532 {
1533         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1534         u64 latency;
1535
1536         switch (val) {
1537         case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1538         case PM_QOS_LATENCY_ANY:
1539                 latency = U64_MAX;
1540                 break;
1541
1542         default:
1543                 latency = val;
1544         }
1545
1546         if (ctrl->ps_max_latency_us != latency) {
1547                 ctrl->ps_max_latency_us = latency;
1548                 nvme_configure_apst(ctrl);
1549         }
1550 }
1551
1552 struct nvme_core_quirk_entry {
1553         /*
1554          * NVMe model and firmware strings are padded with spaces.  For
1555          * simplicity, strings in the quirk table are padded with NULLs
1556          * instead.
1557          */
1558         u16 vid;
1559         const char *mn;
1560         const char *fr;
1561         unsigned long quirks;
1562 };
1563
1564 static const struct nvme_core_quirk_entry core_quirks[] = {
1565         {
1566                 /*
1567                  * This Toshiba device seems to die using any APST states.  See:
1568                  * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1569                  */
1570                 .vid = 0x1179,
1571                 .mn = "THNSF5256GPUK TOSHIBA",
1572                 .quirks = NVME_QUIRK_NO_APST,
1573         }
1574 };
1575
1576 /* match is null-terminated but idstr is space-padded. */
1577 static bool string_matches(const char *idstr, const char *match, size_t len)
1578 {
1579         size_t matchlen;
1580
1581         if (!match)
1582                 return true;
1583
1584         matchlen = strlen(match);
1585         WARN_ON_ONCE(matchlen > len);
1586
1587         if (memcmp(idstr, match, matchlen))
1588                 return false;
1589
1590         for (; matchlen < len; matchlen++)
1591                 if (idstr[matchlen] != ' ')
1592                         return false;
1593
1594         return true;
1595 }
1596
1597 static bool quirk_matches(const struct nvme_id_ctrl *id,
1598                           const struct nvme_core_quirk_entry *q)
1599 {
1600         return q->vid == le16_to_cpu(id->vid) &&
1601                 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1602                 string_matches(id->fr, q->fr, sizeof(id->fr));
1603 }
1604
1605 /*
1606  * Initialize the cached copies of the Identify data and various controller
1607  * register in our nvme_ctrl structure.  This should be called as soon as
1608  * the admin queue is fully up and running.
1609  */
1610 int nvme_init_identify(struct nvme_ctrl *ctrl)
1611 {
1612         struct nvme_id_ctrl *id;
1613         u64 cap;
1614         int ret, page_shift;
1615         u32 max_hw_sectors;
1616         u8 prev_apsta;
1617
1618         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1619         if (ret) {
1620                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1621                 return ret;
1622         }
1623
1624         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1625         if (ret) {
1626                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1627                 return ret;
1628         }
1629         page_shift = NVME_CAP_MPSMIN(cap) + 12;
1630
1631         if (ctrl->vs >= NVME_VS(1, 1, 0))
1632                 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1633
1634         ret = nvme_identify_ctrl(ctrl, &id);
1635         if (ret) {
1636                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1637                 return -EIO;
1638         }
1639
1640         if (!ctrl->identified) {
1641                 /*
1642                  * Check for quirks.  Quirk can depend on firmware version,
1643                  * so, in principle, the set of quirks present can change
1644                  * across a reset.  As a possible future enhancement, we
1645                  * could re-scan for quirks every time we reinitialize
1646                  * the device, but we'd have to make sure that the driver
1647                  * behaves intelligently if the quirks change.
1648                  */
1649
1650                 int i;
1651
1652                 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1653                         if (quirk_matches(id, &core_quirks[i]))
1654                                 ctrl->quirks |= core_quirks[i].quirks;
1655                 }
1656         }
1657
1658         if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1659                 dev_warn(ctrl->dev, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1660                 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1661         }
1662
1663         ctrl->oacs = le16_to_cpu(id->oacs);
1664         ctrl->vid = le16_to_cpu(id->vid);
1665         ctrl->oncs = le16_to_cpup(&id->oncs);
1666         atomic_set(&ctrl->abort_limit, id->acl + 1);
1667         ctrl->vwc = id->vwc;
1668         ctrl->cntlid = le16_to_cpup(&id->cntlid);
1669         memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1670         memcpy(ctrl->model, id->mn, sizeof(id->mn));
1671         memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1672         if (id->mdts)
1673                 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1674         else
1675                 max_hw_sectors = UINT_MAX;
1676         ctrl->max_hw_sectors =
1677                 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1678
1679         nvme_set_queue_limits(ctrl, ctrl->admin_q);
1680         ctrl->sgls = le32_to_cpu(id->sgls);
1681         ctrl->kas = le16_to_cpu(id->kas);
1682
1683         ctrl->npss = id->npss;
1684         prev_apsta = ctrl->apsta;
1685         if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1686                 if (force_apst && id->apsta) {
1687                         dev_warn(ctrl->dev, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1688                         ctrl->apsta = 1;
1689                 } else {
1690                         ctrl->apsta = 0;
1691                 }
1692         } else {
1693                 ctrl->apsta = id->apsta;
1694         }
1695         memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1696
1697         if (ctrl->ops->flags & NVME_F_FABRICS) {
1698                 ctrl->icdoff = le16_to_cpu(id->icdoff);
1699                 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1700                 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1701                 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1702
1703                 /*
1704                  * In fabrics we need to verify the cntlid matches the
1705                  * admin connect
1706                  */
1707                 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1708                         ret = -EINVAL;
1709
1710                 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1711                         dev_err(ctrl->dev,
1712                                 "keep-alive support is mandatory for fabrics\n");
1713                         ret = -EINVAL;
1714                 }
1715         } else {
1716                 ctrl->cntlid = le16_to_cpu(id->cntlid);
1717                 ctrl->hmpre = le32_to_cpu(id->hmpre);
1718                 ctrl->hmmin = le32_to_cpu(id->hmmin);
1719         }
1720
1721         kfree(id);
1722
1723         if (ctrl->apsta && !prev_apsta)
1724                 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1725         else if (!ctrl->apsta && prev_apsta)
1726                 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1727
1728         nvme_configure_apst(ctrl);
1729
1730         ctrl->identified = true;
1731
1732         return ret;
1733 }
1734 EXPORT_SYMBOL_GPL(nvme_init_identify);
1735
1736 static int nvme_dev_open(struct inode *inode, struct file *file)
1737 {
1738         struct nvme_ctrl *ctrl;
1739         int instance = iminor(inode);
1740         int ret = -ENODEV;
1741
1742         spin_lock(&dev_list_lock);
1743         list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1744                 if (ctrl->instance != instance)
1745                         continue;
1746
1747                 if (!ctrl->admin_q) {
1748                         ret = -EWOULDBLOCK;
1749                         break;
1750                 }
1751                 if (!kref_get_unless_zero(&ctrl->kref))
1752                         break;
1753                 file->private_data = ctrl;
1754                 ret = 0;
1755                 break;
1756         }
1757         spin_unlock(&dev_list_lock);
1758
1759         return ret;
1760 }
1761
1762 static int nvme_dev_release(struct inode *inode, struct file *file)
1763 {
1764         nvme_put_ctrl(file->private_data);
1765         return 0;
1766 }
1767
1768 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1769 {
1770         struct nvme_ns *ns;
1771         int ret;
1772
1773         mutex_lock(&ctrl->namespaces_mutex);
1774         if (list_empty(&ctrl->namespaces)) {
1775                 ret = -ENOTTY;
1776                 goto out_unlock;
1777         }
1778
1779         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1780         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1781                 dev_warn(ctrl->device,
1782                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1783                 ret = -EINVAL;
1784                 goto out_unlock;
1785         }
1786
1787         dev_warn(ctrl->device,
1788                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1789         kref_get(&ns->kref);
1790         mutex_unlock(&ctrl->namespaces_mutex);
1791
1792         ret = nvme_user_cmd(ctrl, ns, argp);
1793         nvme_put_ns(ns);
1794         return ret;
1795
1796 out_unlock:
1797         mutex_unlock(&ctrl->namespaces_mutex);
1798         return ret;
1799 }
1800
1801 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1802                 unsigned long arg)
1803 {
1804         struct nvme_ctrl *ctrl = file->private_data;
1805         void __user *argp = (void __user *)arg;
1806
1807         switch (cmd) {
1808         case NVME_IOCTL_ADMIN_CMD:
1809                 return nvme_user_cmd(ctrl, NULL, argp);
1810         case NVME_IOCTL_IO_CMD:
1811                 return nvme_dev_user_cmd(ctrl, argp);
1812         case NVME_IOCTL_RESET:
1813                 dev_warn(ctrl->device, "resetting controller\n");
1814                 return ctrl->ops->reset_ctrl(ctrl);
1815         case NVME_IOCTL_SUBSYS_RESET:
1816                 return nvme_reset_subsystem(ctrl);
1817         case NVME_IOCTL_RESCAN:
1818                 nvme_queue_scan(ctrl);
1819                 return 0;
1820         default:
1821                 return -ENOTTY;
1822         }
1823 }
1824
1825 static const struct file_operations nvme_dev_fops = {
1826         .owner          = THIS_MODULE,
1827         .open           = nvme_dev_open,
1828         .release        = nvme_dev_release,
1829         .unlocked_ioctl = nvme_dev_ioctl,
1830         .compat_ioctl   = nvme_dev_ioctl,
1831 };
1832
1833 static ssize_t nvme_sysfs_reset(struct device *dev,
1834                                 struct device_attribute *attr, const char *buf,
1835                                 size_t count)
1836 {
1837         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1838         int ret;
1839
1840         ret = ctrl->ops->reset_ctrl(ctrl);
1841         if (ret < 0)
1842                 return ret;
1843         return count;
1844 }
1845 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1846
1847 static ssize_t nvme_sysfs_rescan(struct device *dev,
1848                                 struct device_attribute *attr, const char *buf,
1849                                 size_t count)
1850 {
1851         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1852
1853         nvme_queue_scan(ctrl);
1854         return count;
1855 }
1856 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1857
1858 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1859                                                                 char *buf)
1860 {
1861         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1862         struct nvme_ctrl *ctrl = ns->ctrl;
1863         int serial_len = sizeof(ctrl->serial);
1864         int model_len = sizeof(ctrl->model);
1865
1866         if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1867                 return sprintf(buf, "eui.%16phN\n", ns->nguid);
1868
1869         if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1870                 return sprintf(buf, "eui.%8phN\n", ns->eui);
1871
1872         while (ctrl->serial[serial_len - 1] == ' ')
1873                 serial_len--;
1874         while (ctrl->model[model_len - 1] == ' ')
1875                 model_len--;
1876
1877         return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1878                 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1879 }
1880 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1881
1882 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
1883                           char *buf)
1884 {
1885         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1886         return sprintf(buf, "%pU\n", ns->nguid);
1887 }
1888 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
1889
1890 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1891                                                                 char *buf)
1892 {
1893         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1894
1895         /* For backward compatibility expose the NGUID to userspace if
1896          * we have no UUID set
1897          */
1898         if (uuid_is_null(&ns->uuid)) {
1899                 printk_ratelimited(KERN_WARNING
1900                                    "No UUID available providing old NGUID\n");
1901                 return sprintf(buf, "%pU\n", ns->nguid);
1902         }
1903         return sprintf(buf, "%pU\n", &ns->uuid);
1904 }
1905 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1906
1907 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1908                                                                 char *buf)
1909 {
1910         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1911         return sprintf(buf, "%8phd\n", ns->eui);
1912 }
1913 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1914
1915 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1916                                                                 char *buf)
1917 {
1918         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1919         return sprintf(buf, "%d\n", ns->ns_id);
1920 }
1921 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1922
1923 static struct attribute *nvme_ns_attrs[] = {
1924         &dev_attr_wwid.attr,
1925         &dev_attr_uuid.attr,
1926         &dev_attr_nguid.attr,
1927         &dev_attr_eui.attr,
1928         &dev_attr_nsid.attr,
1929         NULL,
1930 };
1931
1932 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1933                 struct attribute *a, int n)
1934 {
1935         struct device *dev = container_of(kobj, struct device, kobj);
1936         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1937
1938         if (a == &dev_attr_uuid.attr) {
1939                 if (uuid_is_null(&ns->uuid) ||
1940                     !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1941                         return 0;
1942         }
1943         if (a == &dev_attr_nguid.attr) {
1944                 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1945                         return 0;
1946         }
1947         if (a == &dev_attr_eui.attr) {
1948                 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1949                         return 0;
1950         }
1951         return a->mode;
1952 }
1953
1954 static const struct attribute_group nvme_ns_attr_group = {
1955         .attrs          = nvme_ns_attrs,
1956         .is_visible     = nvme_ns_attrs_are_visible,
1957 };
1958
1959 #define nvme_show_str_function(field)                                           \
1960 static ssize_t  field##_show(struct device *dev,                                \
1961                             struct device_attribute *attr, char *buf)           \
1962 {                                                                               \
1963         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
1964         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);   \
1965 }                                                                               \
1966 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1967
1968 #define nvme_show_int_function(field)                                           \
1969 static ssize_t  field##_show(struct device *dev,                                \
1970                             struct device_attribute *attr, char *buf)           \
1971 {                                                                               \
1972         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
1973         return sprintf(buf, "%d\n", ctrl->field);       \
1974 }                                                                               \
1975 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1976
1977 nvme_show_str_function(model);
1978 nvme_show_str_function(serial);
1979 nvme_show_str_function(firmware_rev);
1980 nvme_show_int_function(cntlid);
1981
1982 static ssize_t nvme_sysfs_delete(struct device *dev,
1983                                 struct device_attribute *attr, const char *buf,
1984                                 size_t count)
1985 {
1986         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1987
1988         if (device_remove_file_self(dev, attr))
1989                 ctrl->ops->delete_ctrl(ctrl);
1990         return count;
1991 }
1992 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1993
1994 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1995                                          struct device_attribute *attr,
1996                                          char *buf)
1997 {
1998         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1999
2000         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2001 }
2002 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2003
2004 static ssize_t nvme_sysfs_show_state(struct device *dev,
2005                                      struct device_attribute *attr,
2006                                      char *buf)
2007 {
2008         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2009         static const char *const state_name[] = {
2010                 [NVME_CTRL_NEW]         = "new",
2011                 [NVME_CTRL_LIVE]        = "live",
2012                 [NVME_CTRL_RESETTING]   = "resetting",
2013                 [NVME_CTRL_RECONNECTING]= "reconnecting",
2014                 [NVME_CTRL_DELETING]    = "deleting",
2015                 [NVME_CTRL_DEAD]        = "dead",
2016         };
2017
2018         if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2019             state_name[ctrl->state])
2020                 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2021
2022         return sprintf(buf, "unknown state\n");
2023 }
2024
2025 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2026
2027 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2028                                          struct device_attribute *attr,
2029                                          char *buf)
2030 {
2031         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2032
2033         return snprintf(buf, PAGE_SIZE, "%s\n",
2034                         ctrl->ops->get_subsysnqn(ctrl));
2035 }
2036 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2037
2038 static ssize_t nvme_sysfs_show_address(struct device *dev,
2039                                          struct device_attribute *attr,
2040                                          char *buf)
2041 {
2042         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2043
2044         return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2045 }
2046 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2047
2048 static struct attribute *nvme_dev_attrs[] = {
2049         &dev_attr_reset_controller.attr,
2050         &dev_attr_rescan_controller.attr,
2051         &dev_attr_model.attr,
2052         &dev_attr_serial.attr,
2053         &dev_attr_firmware_rev.attr,
2054         &dev_attr_cntlid.attr,
2055         &dev_attr_delete_controller.attr,
2056         &dev_attr_transport.attr,
2057         &dev_attr_subsysnqn.attr,
2058         &dev_attr_address.attr,
2059         &dev_attr_state.attr,
2060         NULL
2061 };
2062
2063 #define CHECK_ATTR(ctrl, a, name)               \
2064         if ((a) == &dev_attr_##name.attr &&     \
2065             !(ctrl)->ops->get_##name)           \
2066                 return 0
2067
2068 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2069                 struct attribute *a, int n)
2070 {
2071         struct device *dev = container_of(kobj, struct device, kobj);
2072         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2073
2074         if (a == &dev_attr_delete_controller.attr) {
2075                 if (!ctrl->ops->delete_ctrl)
2076                         return 0;
2077         }
2078
2079         CHECK_ATTR(ctrl, a, subsysnqn);
2080         CHECK_ATTR(ctrl, a, address);
2081
2082         return a->mode;
2083 }
2084
2085 static struct attribute_group nvme_dev_attrs_group = {
2086         .attrs          = nvme_dev_attrs,
2087         .is_visible     = nvme_dev_attrs_are_visible,
2088 };
2089
2090 static const struct attribute_group *nvme_dev_attr_groups[] = {
2091         &nvme_dev_attrs_group,
2092         NULL,
2093 };
2094
2095 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2096 {
2097         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2098         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2099
2100         return nsa->ns_id - nsb->ns_id;
2101 }
2102
2103 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2104 {
2105         struct nvme_ns *ns, *ret = NULL;
2106
2107         mutex_lock(&ctrl->namespaces_mutex);
2108         list_for_each_entry(ns, &ctrl->namespaces, list) {
2109                 if (ns->ns_id == nsid) {
2110                         kref_get(&ns->kref);
2111                         ret = ns;
2112                         break;
2113                 }
2114                 if (ns->ns_id > nsid)
2115                         break;
2116         }
2117         mutex_unlock(&ctrl->namespaces_mutex);
2118         return ret;
2119 }
2120
2121 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2122 {
2123         struct nvme_ns *ns;
2124         struct gendisk *disk;
2125         struct nvme_id_ns *id;
2126         char disk_name[DISK_NAME_LEN];
2127         int node = dev_to_node(ctrl->dev);
2128
2129         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2130         if (!ns)
2131                 return;
2132
2133         ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2134         if (ns->instance < 0)
2135                 goto out_free_ns;
2136
2137         ns->queue = blk_mq_init_queue(ctrl->tagset);
2138         if (IS_ERR(ns->queue))
2139                 goto out_release_instance;
2140         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2141         ns->queue->queuedata = ns;
2142         ns->ctrl = ctrl;
2143
2144         kref_init(&ns->kref);
2145         ns->ns_id = nsid;
2146         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2147
2148         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2149         nvme_set_queue_limits(ctrl, ns->queue);
2150
2151         sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2152
2153         if (nvme_revalidate_ns(ns, &id))
2154                 goto out_free_queue;
2155
2156         if (nvme_nvm_ns_supported(ns, id) &&
2157                                 nvme_nvm_register(ns, disk_name, node)) {
2158                 dev_warn(ctrl->dev, "%s: LightNVM init failure\n", __func__);
2159                 goto out_free_id;
2160         }
2161
2162         disk = alloc_disk_node(0, node);
2163         if (!disk)
2164                 goto out_free_id;
2165
2166         disk->fops = &nvme_fops;
2167         disk->private_data = ns;
2168         disk->queue = ns->queue;
2169         disk->flags = GENHD_FL_EXT_DEVT;
2170         memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2171         ns->disk = disk;
2172
2173         __nvme_revalidate_disk(disk, id);
2174
2175         mutex_lock(&ctrl->namespaces_mutex);
2176         list_add_tail(&ns->list, &ctrl->namespaces);
2177         mutex_unlock(&ctrl->namespaces_mutex);
2178
2179         kref_get(&ctrl->kref);
2180
2181         kfree(id);
2182
2183         device_add_disk(ctrl->device, ns->disk);
2184         if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2185                                         &nvme_ns_attr_group))
2186                 pr_warn("%s: failed to create sysfs group for identification\n",
2187                         ns->disk->disk_name);
2188         if (ns->ndev && nvme_nvm_register_sysfs(ns))
2189                 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2190                         ns->disk->disk_name);
2191         return;
2192  out_free_id:
2193         kfree(id);
2194  out_free_queue:
2195         blk_cleanup_queue(ns->queue);
2196  out_release_instance:
2197         ida_simple_remove(&ctrl->ns_ida, ns->instance);
2198  out_free_ns:
2199         kfree(ns);
2200 }
2201
2202 static void nvme_ns_remove(struct nvme_ns *ns)
2203 {
2204         if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2205                 return;
2206
2207         if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2208                 if (blk_get_integrity(ns->disk))
2209                         blk_integrity_unregister(ns->disk);
2210                 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2211                                         &nvme_ns_attr_group);
2212                 if (ns->ndev)
2213                         nvme_nvm_unregister_sysfs(ns);
2214                 del_gendisk(ns->disk);
2215                 blk_cleanup_queue(ns->queue);
2216         }
2217
2218         mutex_lock(&ns->ctrl->namespaces_mutex);
2219         list_del_init(&ns->list);
2220         mutex_unlock(&ns->ctrl->namespaces_mutex);
2221
2222         nvme_put_ns(ns);
2223 }
2224
2225 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2226 {
2227         struct nvme_ns *ns;
2228
2229         ns = nvme_find_get_ns(ctrl, nsid);
2230         if (ns) {
2231                 if (ns->disk && revalidate_disk(ns->disk))
2232                         nvme_ns_remove(ns);
2233                 nvme_put_ns(ns);
2234         } else
2235                 nvme_alloc_ns(ctrl, nsid);
2236 }
2237
2238 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2239                                         unsigned nsid)
2240 {
2241         struct nvme_ns *ns, *next;
2242
2243         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2244                 if (ns->ns_id > nsid)
2245                         nvme_ns_remove(ns);
2246         }
2247 }
2248
2249 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2250 {
2251         struct nvme_ns *ns;
2252         __le32 *ns_list;
2253         unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2254         int ret = 0;
2255
2256         ns_list = kzalloc(0x1000, GFP_KERNEL);
2257         if (!ns_list)
2258                 return -ENOMEM;
2259
2260         for (i = 0; i < num_lists; i++) {
2261                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2262                 if (ret)
2263                         goto free;
2264
2265                 for (j = 0; j < min(nn, 1024U); j++) {
2266                         nsid = le32_to_cpu(ns_list[j]);
2267                         if (!nsid)
2268                                 goto out;
2269
2270                         nvme_validate_ns(ctrl, nsid);
2271
2272                         while (++prev < nsid) {
2273                                 ns = nvme_find_get_ns(ctrl, prev);
2274                                 if (ns) {
2275                                         nvme_ns_remove(ns);
2276                                         nvme_put_ns(ns);
2277                                 }
2278                         }
2279                 }
2280                 nn -= j;
2281         }
2282  out:
2283         nvme_remove_invalid_namespaces(ctrl, prev);
2284  free:
2285         kfree(ns_list);
2286         return ret;
2287 }
2288
2289 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2290 {
2291         unsigned i;
2292
2293         for (i = 1; i <= nn; i++)
2294                 nvme_validate_ns(ctrl, i);
2295
2296         nvme_remove_invalid_namespaces(ctrl, nn);
2297 }
2298
2299 static void nvme_scan_work(struct work_struct *work)
2300 {
2301         struct nvme_ctrl *ctrl =
2302                 container_of(work, struct nvme_ctrl, scan_work);
2303         struct nvme_id_ctrl *id;
2304         unsigned nn;
2305
2306         if (ctrl->state != NVME_CTRL_LIVE)
2307                 return;
2308
2309         if (nvme_identify_ctrl(ctrl, &id))
2310                 return;
2311
2312         nn = le32_to_cpu(id->nn);
2313         if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2314             !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2315                 if (!nvme_scan_ns_list(ctrl, nn))
2316                         goto done;
2317         }
2318         nvme_scan_ns_sequential(ctrl, nn);
2319  done:
2320         mutex_lock(&ctrl->namespaces_mutex);
2321         list_sort(NULL, &ctrl->namespaces, ns_cmp);
2322         mutex_unlock(&ctrl->namespaces_mutex);
2323         kfree(id);
2324 }
2325
2326 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2327 {
2328         /*
2329          * Do not queue new scan work when a controller is reset during
2330          * removal.
2331          */
2332         if (ctrl->state == NVME_CTRL_LIVE)
2333                 queue_work(nvme_wq, &ctrl->scan_work);
2334 }
2335 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2336
2337 /*
2338  * This function iterates the namespace list unlocked to allow recovery from
2339  * controller failure. It is up to the caller to ensure the namespace list is
2340  * not modified by scan work while this function is executing.
2341  */
2342 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2343 {
2344         struct nvme_ns *ns, *next;
2345
2346         /*
2347          * The dead states indicates the controller was not gracefully
2348          * disconnected. In that case, we won't be able to flush any data while
2349          * removing the namespaces' disks; fail all the queues now to avoid
2350          * potentially having to clean up the failed sync later.
2351          */
2352         if (ctrl->state == NVME_CTRL_DEAD)
2353                 nvme_kill_queues(ctrl);
2354
2355         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2356                 nvme_ns_remove(ns);
2357 }
2358 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2359
2360 static void nvme_async_event_work(struct work_struct *work)
2361 {
2362         struct nvme_ctrl *ctrl =
2363                 container_of(work, struct nvme_ctrl, async_event_work);
2364
2365         spin_lock_irq(&ctrl->lock);
2366         while (ctrl->event_limit > 0) {
2367                 int aer_idx = --ctrl->event_limit;
2368
2369                 spin_unlock_irq(&ctrl->lock);
2370                 ctrl->ops->submit_async_event(ctrl, aer_idx);
2371                 spin_lock_irq(&ctrl->lock);
2372         }
2373         spin_unlock_irq(&ctrl->lock);
2374 }
2375
2376 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2377                 union nvme_result *res)
2378 {
2379         u32 result = le32_to_cpu(res->u32);
2380         bool done = true;
2381
2382         switch (le16_to_cpu(status) >> 1) {
2383         case NVME_SC_SUCCESS:
2384                 done = false;
2385                 /*FALLTHRU*/
2386         case NVME_SC_ABORT_REQ:
2387                 ++ctrl->event_limit;
2388                 queue_work(nvme_wq, &ctrl->async_event_work);
2389                 break;
2390         default:
2391                 break;
2392         }
2393
2394         if (done)
2395                 return;
2396
2397         switch (result & 0xff07) {
2398         case NVME_AER_NOTICE_NS_CHANGED:
2399                 dev_info(ctrl->device, "rescanning\n");
2400                 nvme_queue_scan(ctrl);
2401                 break;
2402         default:
2403                 dev_warn(ctrl->device, "async event result %08x\n", result);
2404         }
2405 }
2406 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2407
2408 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2409 {
2410         ctrl->event_limit = NVME_NR_AERS;
2411         queue_work(nvme_wq, &ctrl->async_event_work);
2412 }
2413 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2414
2415 static DEFINE_IDA(nvme_instance_ida);
2416
2417 static int nvme_set_instance(struct nvme_ctrl *ctrl)
2418 {
2419         int instance, error;
2420
2421         do {
2422                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2423                         return -ENODEV;
2424
2425                 spin_lock(&dev_list_lock);
2426                 error = ida_get_new(&nvme_instance_ida, &instance);
2427                 spin_unlock(&dev_list_lock);
2428         } while (error == -EAGAIN);
2429
2430         if (error)
2431                 return -ENODEV;
2432
2433         ctrl->instance = instance;
2434         return 0;
2435 }
2436
2437 static void nvme_release_instance(struct nvme_ctrl *ctrl)
2438 {
2439         spin_lock(&dev_list_lock);
2440         ida_remove(&nvme_instance_ida, ctrl->instance);
2441         spin_unlock(&dev_list_lock);
2442 }
2443
2444 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2445 {
2446         flush_work(&ctrl->async_event_work);
2447         flush_work(&ctrl->scan_work);
2448         nvme_remove_namespaces(ctrl);
2449
2450         device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
2451
2452         spin_lock(&dev_list_lock);
2453         list_del(&ctrl->node);
2454         spin_unlock(&dev_list_lock);
2455 }
2456 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2457
2458 static void nvme_free_ctrl(struct kref *kref)
2459 {
2460         struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
2461
2462         put_device(ctrl->device);
2463         nvme_release_instance(ctrl);
2464         ida_destroy(&ctrl->ns_ida);
2465
2466         ctrl->ops->free_ctrl(ctrl);
2467 }
2468
2469 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2470 {
2471         kref_put(&ctrl->kref, nvme_free_ctrl);
2472 }
2473 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
2474
2475 /*
2476  * Initialize a NVMe controller structures.  This needs to be called during
2477  * earliest initialization so that we have the initialized structured around
2478  * during probing.
2479  */
2480 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2481                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2482 {
2483         int ret;
2484
2485         ctrl->state = NVME_CTRL_NEW;
2486         spin_lock_init(&ctrl->lock);
2487         INIT_LIST_HEAD(&ctrl->namespaces);
2488         mutex_init(&ctrl->namespaces_mutex);
2489         kref_init(&ctrl->kref);
2490         ctrl->dev = dev;
2491         ctrl->ops = ops;
2492         ctrl->quirks = quirks;
2493         INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2494         INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2495
2496         ret = nvme_set_instance(ctrl);
2497         if (ret)
2498                 goto out;
2499
2500         ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2501                                 MKDEV(nvme_char_major, ctrl->instance),
2502                                 ctrl, nvme_dev_attr_groups,
2503                                 "nvme%d", ctrl->instance);
2504         if (IS_ERR(ctrl->device)) {
2505                 ret = PTR_ERR(ctrl->device);
2506                 goto out_release_instance;
2507         }
2508         get_device(ctrl->device);
2509         ida_init(&ctrl->ns_ida);
2510
2511         spin_lock(&dev_list_lock);
2512         list_add_tail(&ctrl->node, &nvme_ctrl_list);
2513         spin_unlock(&dev_list_lock);
2514
2515         /*
2516          * Initialize latency tolerance controls.  The sysfs files won't
2517          * be visible to userspace unless the device actually supports APST.
2518          */
2519         ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2520         dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2521                 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2522
2523         return 0;
2524 out_release_instance:
2525         nvme_release_instance(ctrl);
2526 out:
2527         return ret;
2528 }
2529 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2530
2531 /**
2532  * nvme_kill_queues(): Ends all namespace queues
2533  * @ctrl: the dead controller that needs to end
2534  *
2535  * Call this function when the driver determines it is unable to get the
2536  * controller in a state capable of servicing IO.
2537  */
2538 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2539 {
2540         struct nvme_ns *ns;
2541
2542         mutex_lock(&ctrl->namespaces_mutex);
2543
2544         /* Forcibly start all queues to avoid having stuck requests */
2545         blk_mq_start_hw_queues(ctrl->admin_q);
2546
2547         list_for_each_entry(ns, &ctrl->namespaces, list) {
2548                 /*
2549                  * Revalidating a dead namespace sets capacity to 0. This will
2550                  * end buffered writers dirtying pages that can't be synced.
2551                  */
2552                 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2553                         continue;
2554                 revalidate_disk(ns->disk);
2555                 blk_set_queue_dying(ns->queue);
2556
2557                 /*
2558                  * Forcibly start all queues to avoid having stuck requests.
2559                  * Note that we must ensure the queues are not stopped
2560                  * when the final removal happens.
2561                  */
2562                 blk_mq_start_hw_queues(ns->queue);
2563
2564                 /* draining requests in requeue list */
2565                 blk_mq_kick_requeue_list(ns->queue);
2566         }
2567         mutex_unlock(&ctrl->namespaces_mutex);
2568 }
2569 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2570
2571 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2572 {
2573         struct nvme_ns *ns;
2574
2575         mutex_lock(&ctrl->namespaces_mutex);
2576         list_for_each_entry(ns, &ctrl->namespaces, list)
2577                 blk_mq_unfreeze_queue(ns->queue);
2578         mutex_unlock(&ctrl->namespaces_mutex);
2579 }
2580 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2581
2582 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2583 {
2584         struct nvme_ns *ns;
2585
2586         mutex_lock(&ctrl->namespaces_mutex);
2587         list_for_each_entry(ns, &ctrl->namespaces, list) {
2588                 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2589                 if (timeout <= 0)
2590                         break;
2591         }
2592         mutex_unlock(&ctrl->namespaces_mutex);
2593 }
2594 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2595
2596 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2597 {
2598         struct nvme_ns *ns;
2599
2600         mutex_lock(&ctrl->namespaces_mutex);
2601         list_for_each_entry(ns, &ctrl->namespaces, list)
2602                 blk_mq_freeze_queue_wait(ns->queue);
2603         mutex_unlock(&ctrl->namespaces_mutex);
2604 }
2605 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2606
2607 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2608 {
2609         struct nvme_ns *ns;
2610
2611         mutex_lock(&ctrl->namespaces_mutex);
2612         list_for_each_entry(ns, &ctrl->namespaces, list)
2613                 blk_freeze_queue_start(ns->queue);
2614         mutex_unlock(&ctrl->namespaces_mutex);
2615 }
2616 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2617
2618 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2619 {
2620         struct nvme_ns *ns;
2621
2622         mutex_lock(&ctrl->namespaces_mutex);
2623         list_for_each_entry(ns, &ctrl->namespaces, list)
2624                 blk_mq_quiesce_queue(ns->queue);
2625         mutex_unlock(&ctrl->namespaces_mutex);
2626 }
2627 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2628
2629 void nvme_start_queues(struct nvme_ctrl *ctrl)
2630 {
2631         struct nvme_ns *ns;
2632
2633         mutex_lock(&ctrl->namespaces_mutex);
2634         list_for_each_entry(ns, &ctrl->namespaces, list) {
2635                 blk_mq_start_stopped_hw_queues(ns->queue, true);
2636                 blk_mq_kick_requeue_list(ns->queue);
2637         }
2638         mutex_unlock(&ctrl->namespaces_mutex);
2639 }
2640 EXPORT_SYMBOL_GPL(nvme_start_queues);
2641
2642 int __init nvme_core_init(void)
2643 {
2644         int result;
2645
2646         nvme_wq = alloc_workqueue("nvme-wq",
2647                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2648         if (!nvme_wq)
2649                 return -ENOMEM;
2650
2651         result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2652                                                         &nvme_dev_fops);
2653         if (result < 0)
2654                 goto destroy_wq;
2655         else if (result > 0)
2656                 nvme_char_major = result;
2657
2658         nvme_class = class_create(THIS_MODULE, "nvme");
2659         if (IS_ERR(nvme_class)) {
2660                 result = PTR_ERR(nvme_class);
2661                 goto unregister_chrdev;
2662         }
2663
2664         return 0;
2665
2666 unregister_chrdev:
2667         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2668 destroy_wq:
2669         destroy_workqueue(nvme_wq);
2670         return result;
2671 }
2672
2673 void nvme_core_exit(void)
2674 {
2675         class_destroy(nvme_class);
2676         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2677         destroy_workqueue(nvme_wq);
2678 }
2679
2680 MODULE_LICENSE("GPL");
2681 MODULE_VERSION("1.0");
2682 module_init(nvme_core_init);
2683 module_exit(nvme_core_exit);