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