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