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