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