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