nvme: fix controller instance leak
[linux-2.6-microblaze.git] / drivers / nvme / host / core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * NVM Express device driver
4  * Copyright (c) 2011-2014, Intel Corporation.
5  */
6
7 #include <linux/blkdev.h>
8 #include <linux/blk-mq.h>
9 #include <linux/compat.h>
10 #include <linux/delay.h>
11 #include <linux/errno.h>
12 #include <linux/hdreg.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/backing-dev.h>
16 #include <linux/list_sort.h>
17 #include <linux/slab.h>
18 #include <linux/types.h>
19 #include <linux/pr.h>
20 #include <linux/ptrace.h>
21 #include <linux/nvme_ioctl.h>
22 #include <linux/pm_qos.h>
23 #include <asm/unaligned.h>
24
25 #include "nvme.h"
26 #include "fabrics.h"
27
28 #define CREATE_TRACE_POINTS
29 #include "trace.h"
30
31 #define NVME_MINORS             (1U << MINORBITS)
32
33 unsigned int admin_timeout = 60;
34 module_param(admin_timeout, uint, 0644);
35 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
36 EXPORT_SYMBOL_GPL(admin_timeout);
37
38 unsigned int nvme_io_timeout = 30;
39 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
40 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
41 EXPORT_SYMBOL_GPL(nvme_io_timeout);
42
43 static unsigned char shutdown_timeout = 5;
44 module_param(shutdown_timeout, byte, 0644);
45 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
46
47 static u8 nvme_max_retries = 5;
48 module_param_named(max_retries, nvme_max_retries, byte, 0644);
49 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
50
51 static unsigned long default_ps_max_latency_us = 100000;
52 module_param(default_ps_max_latency_us, ulong, 0644);
53 MODULE_PARM_DESC(default_ps_max_latency_us,
54                  "max power saving latency for new devices; use PM QOS to change per device");
55
56 static bool force_apst;
57 module_param(force_apst, bool, 0644);
58 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
59
60 static bool streams;
61 module_param(streams, bool, 0644);
62 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
63
64 /*
65  * nvme_wq - hosts nvme related works that are not reset or delete
66  * nvme_reset_wq - hosts nvme reset works
67  * nvme_delete_wq - hosts nvme delete works
68  *
69  * nvme_wq will host works such as scan, aen handling, fw activation,
70  * keep-alive, periodic reconnects etc. nvme_reset_wq
71  * runs reset works which also flush works hosted on nvme_wq for
72  * serialization purposes. nvme_delete_wq host controller deletion
73  * works which flush reset works for serialization.
74  */
75 struct workqueue_struct *nvme_wq;
76 EXPORT_SYMBOL_GPL(nvme_wq);
77
78 struct workqueue_struct *nvme_reset_wq;
79 EXPORT_SYMBOL_GPL(nvme_reset_wq);
80
81 struct workqueue_struct *nvme_delete_wq;
82 EXPORT_SYMBOL_GPL(nvme_delete_wq);
83
84 static LIST_HEAD(nvme_subsystems);
85 static DEFINE_MUTEX(nvme_subsystems_lock);
86
87 static DEFINE_IDA(nvme_instance_ida);
88 static dev_t nvme_chr_devt;
89 static struct class *nvme_class;
90 static struct class *nvme_subsys_class;
91
92 static int _nvme_revalidate_disk(struct gendisk *disk);
93 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
94 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
95                                            unsigned nsid);
96
97 static void nvme_set_queue_dying(struct nvme_ns *ns)
98 {
99         /*
100          * Revalidating a dead namespace sets capacity to 0. This will end
101          * buffered writers dirtying pages that can't be synced.
102          */
103         if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
104                 return;
105         blk_set_queue_dying(ns->queue);
106         /* Forcibly unquiesce queues to avoid blocking dispatch */
107         blk_mq_unquiesce_queue(ns->queue);
108         /*
109          * Revalidate after unblocking dispatchers that may be holding bd_butex
110          */
111         revalidate_disk(ns->disk);
112 }
113
114 static void nvme_queue_scan(struct nvme_ctrl *ctrl)
115 {
116         /*
117          * Only new queue scan work when admin and IO queues are both alive
118          */
119         if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset)
120                 queue_work(nvme_wq, &ctrl->scan_work);
121 }
122
123 /*
124  * Use this function to proceed with scheduling reset_work for a controller
125  * that had previously been set to the resetting state. This is intended for
126  * code paths that can't be interrupted by other reset attempts. A hot removal
127  * may prevent this from succeeding.
128  */
129 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
130 {
131         if (ctrl->state != NVME_CTRL_RESETTING)
132                 return -EBUSY;
133         if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
134                 return -EBUSY;
135         return 0;
136 }
137 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
138
139 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
140 {
141         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
142                 return -EBUSY;
143         if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
144                 return -EBUSY;
145         return 0;
146 }
147 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
148
149 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
150 {
151         int ret;
152
153         ret = nvme_reset_ctrl(ctrl);
154         if (!ret) {
155                 flush_work(&ctrl->reset_work);
156                 if (ctrl->state != NVME_CTRL_LIVE)
157                         ret = -ENETRESET;
158         }
159
160         return ret;
161 }
162 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync);
163
164 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
165 {
166         dev_info(ctrl->device,
167                  "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
168
169         flush_work(&ctrl->reset_work);
170         nvme_stop_ctrl(ctrl);
171         nvme_remove_namespaces(ctrl);
172         ctrl->ops->delete_ctrl(ctrl);
173         nvme_uninit_ctrl(ctrl);
174 }
175
176 static void nvme_delete_ctrl_work(struct work_struct *work)
177 {
178         struct nvme_ctrl *ctrl =
179                 container_of(work, struct nvme_ctrl, delete_work);
180
181         nvme_do_delete_ctrl(ctrl);
182 }
183
184 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
185 {
186         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
187                 return -EBUSY;
188         if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
189                 return -EBUSY;
190         return 0;
191 }
192 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
193
194 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
195 {
196         /*
197          * Keep a reference until nvme_do_delete_ctrl() complete,
198          * since ->delete_ctrl can free the controller.
199          */
200         nvme_get_ctrl(ctrl);
201         if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
202                 nvme_do_delete_ctrl(ctrl);
203         nvme_put_ctrl(ctrl);
204 }
205
206 static blk_status_t nvme_error_status(u16 status)
207 {
208         switch (status & 0x7ff) {
209         case NVME_SC_SUCCESS:
210                 return BLK_STS_OK;
211         case NVME_SC_CAP_EXCEEDED:
212                 return BLK_STS_NOSPC;
213         case NVME_SC_LBA_RANGE:
214         case NVME_SC_CMD_INTERRUPTED:
215         case NVME_SC_NS_NOT_READY:
216                 return BLK_STS_TARGET;
217         case NVME_SC_BAD_ATTRIBUTES:
218         case NVME_SC_ONCS_NOT_SUPPORTED:
219         case NVME_SC_INVALID_OPCODE:
220         case NVME_SC_INVALID_FIELD:
221         case NVME_SC_INVALID_NS:
222                 return BLK_STS_NOTSUPP;
223         case NVME_SC_WRITE_FAULT:
224         case NVME_SC_READ_ERROR:
225         case NVME_SC_UNWRITTEN_BLOCK:
226         case NVME_SC_ACCESS_DENIED:
227         case NVME_SC_READ_ONLY:
228         case NVME_SC_COMPARE_FAILED:
229                 return BLK_STS_MEDIUM;
230         case NVME_SC_GUARD_CHECK:
231         case NVME_SC_APPTAG_CHECK:
232         case NVME_SC_REFTAG_CHECK:
233         case NVME_SC_INVALID_PI:
234                 return BLK_STS_PROTECTION;
235         case NVME_SC_RESERVATION_CONFLICT:
236                 return BLK_STS_NEXUS;
237         case NVME_SC_HOST_PATH_ERROR:
238                 return BLK_STS_TRANSPORT;
239         default:
240                 return BLK_STS_IOERR;
241         }
242 }
243
244 static void nvme_retry_req(struct request *req)
245 {
246         struct nvme_ns *ns = req->q->queuedata;
247         unsigned long delay = 0;
248         u16 crd;
249
250         /* The mask and shift result must be <= 3 */
251         crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
252         if (ns && crd)
253                 delay = ns->ctrl->crdt[crd - 1] * 100;
254
255         nvme_req(req)->retries++;
256         blk_mq_requeue_request(req, false);
257         blk_mq_delay_kick_requeue_list(req->q, delay);
258 }
259
260 enum nvme_disposition {
261         COMPLETE,
262         RETRY,
263         FAILOVER,
264 };
265
266 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
267 {
268         if (likely(nvme_req(req)->status == 0))
269                 return COMPLETE;
270
271         if (blk_noretry_request(req) ||
272             (nvme_req(req)->status & NVME_SC_DNR) ||
273             nvme_req(req)->retries >= nvme_max_retries)
274                 return COMPLETE;
275
276         if (req->cmd_flags & REQ_NVME_MPATH) {
277                 if (nvme_is_path_error(nvme_req(req)->status) ||
278                     blk_queue_dying(req->q))
279                         return FAILOVER;
280         } else {
281                 if (blk_queue_dying(req->q))
282                         return COMPLETE;
283         }
284
285         return RETRY;
286 }
287
288 static inline void nvme_end_req(struct request *req)
289 {
290         blk_status_t status = nvme_error_status(nvme_req(req)->status);
291
292         if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
293             req_op(req) == REQ_OP_ZONE_APPEND)
294                 req->__sector = nvme_lba_to_sect(req->q->queuedata,
295                         le64_to_cpu(nvme_req(req)->result.u64));
296
297         nvme_trace_bio_complete(req, status);
298         blk_mq_end_request(req, status);
299 }
300
301 void nvme_complete_rq(struct request *req)
302 {
303         trace_nvme_complete_rq(req);
304         nvme_cleanup_cmd(req);
305
306         if (nvme_req(req)->ctrl->kas)
307                 nvme_req(req)->ctrl->comp_seen = true;
308
309         switch (nvme_decide_disposition(req)) {
310         case COMPLETE:
311                 nvme_end_req(req);
312                 return;
313         case RETRY:
314                 nvme_retry_req(req);
315                 return;
316         case FAILOVER:
317                 nvme_failover_req(req);
318                 return;
319         }
320 }
321 EXPORT_SYMBOL_GPL(nvme_complete_rq);
322
323 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
324 {
325         dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
326                                 "Cancelling I/O %d", req->tag);
327
328         /* don't abort one completed request */
329         if (blk_mq_request_completed(req))
330                 return true;
331
332         nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
333         blk_mq_complete_request(req);
334         return true;
335 }
336 EXPORT_SYMBOL_GPL(nvme_cancel_request);
337
338 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
339                 enum nvme_ctrl_state new_state)
340 {
341         enum nvme_ctrl_state old_state;
342         unsigned long flags;
343         bool changed = false;
344
345         spin_lock_irqsave(&ctrl->lock, flags);
346
347         old_state = ctrl->state;
348         switch (new_state) {
349         case NVME_CTRL_LIVE:
350                 switch (old_state) {
351                 case NVME_CTRL_NEW:
352                 case NVME_CTRL_RESETTING:
353                 case NVME_CTRL_CONNECTING:
354                         changed = true;
355                         /* FALLTHRU */
356                 default:
357                         break;
358                 }
359                 break;
360         case NVME_CTRL_RESETTING:
361                 switch (old_state) {
362                 case NVME_CTRL_NEW:
363                 case NVME_CTRL_LIVE:
364                         changed = true;
365                         /* FALLTHRU */
366                 default:
367                         break;
368                 }
369                 break;
370         case NVME_CTRL_CONNECTING:
371                 switch (old_state) {
372                 case NVME_CTRL_NEW:
373                 case NVME_CTRL_RESETTING:
374                         changed = true;
375                         /* FALLTHRU */
376                 default:
377                         break;
378                 }
379                 break;
380         case NVME_CTRL_DELETING:
381                 switch (old_state) {
382                 case NVME_CTRL_LIVE:
383                 case NVME_CTRL_RESETTING:
384                 case NVME_CTRL_CONNECTING:
385                         changed = true;
386                         /* FALLTHRU */
387                 default:
388                         break;
389                 }
390                 break;
391         case NVME_CTRL_DELETING_NOIO:
392                 switch (old_state) {
393                 case NVME_CTRL_DELETING:
394                 case NVME_CTRL_DEAD:
395                         changed = true;
396                         /* FALLTHRU */
397                 default:
398                         break;
399                 }
400                 break;
401         case NVME_CTRL_DEAD:
402                 switch (old_state) {
403                 case NVME_CTRL_DELETING:
404                         changed = true;
405                         /* FALLTHRU */
406                 default:
407                         break;
408                 }
409                 break;
410         default:
411                 break;
412         }
413
414         if (changed) {
415                 ctrl->state = new_state;
416                 wake_up_all(&ctrl->state_wq);
417         }
418
419         spin_unlock_irqrestore(&ctrl->lock, flags);
420         if (changed && ctrl->state == NVME_CTRL_LIVE)
421                 nvme_kick_requeue_lists(ctrl);
422         return changed;
423 }
424 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
425
426 /*
427  * Returns true for sink states that can't ever transition back to live.
428  */
429 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
430 {
431         switch (ctrl->state) {
432         case NVME_CTRL_NEW:
433         case NVME_CTRL_LIVE:
434         case NVME_CTRL_RESETTING:
435         case NVME_CTRL_CONNECTING:
436                 return false;
437         case NVME_CTRL_DELETING:
438         case NVME_CTRL_DELETING_NOIO:
439         case NVME_CTRL_DEAD:
440                 return true;
441         default:
442                 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
443                 return true;
444         }
445 }
446
447 /*
448  * Waits for the controller state to be resetting, or returns false if it is
449  * not possible to ever transition to that state.
450  */
451 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
452 {
453         wait_event(ctrl->state_wq,
454                    nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
455                    nvme_state_terminal(ctrl));
456         return ctrl->state == NVME_CTRL_RESETTING;
457 }
458 EXPORT_SYMBOL_GPL(nvme_wait_reset);
459
460 static void nvme_free_ns_head(struct kref *ref)
461 {
462         struct nvme_ns_head *head =
463                 container_of(ref, struct nvme_ns_head, ref);
464
465         nvme_mpath_remove_disk(head);
466         ida_simple_remove(&head->subsys->ns_ida, head->instance);
467         cleanup_srcu_struct(&head->srcu);
468         nvme_put_subsystem(head->subsys);
469         kfree(head);
470 }
471
472 static void nvme_put_ns_head(struct nvme_ns_head *head)
473 {
474         kref_put(&head->ref, nvme_free_ns_head);
475 }
476
477 static void nvme_free_ns(struct kref *kref)
478 {
479         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
480
481         if (ns->ndev)
482                 nvme_nvm_unregister(ns);
483
484         put_disk(ns->disk);
485         nvme_put_ns_head(ns->head);
486         nvme_put_ctrl(ns->ctrl);
487         kfree(ns);
488 }
489
490 void nvme_put_ns(struct nvme_ns *ns)
491 {
492         kref_put(&ns->kref, nvme_free_ns);
493 }
494 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
495
496 static inline void nvme_clear_nvme_request(struct request *req)
497 {
498         if (!(req->rq_flags & RQF_DONTPREP)) {
499                 nvme_req(req)->retries = 0;
500                 nvme_req(req)->flags = 0;
501                 req->rq_flags |= RQF_DONTPREP;
502         }
503 }
504
505 struct request *nvme_alloc_request(struct request_queue *q,
506                 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
507 {
508         unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
509         struct request *req;
510
511         if (qid == NVME_QID_ANY) {
512                 req = blk_mq_alloc_request(q, op, flags);
513         } else {
514                 req = blk_mq_alloc_request_hctx(q, op, flags,
515                                 qid ? qid - 1 : 0);
516         }
517         if (IS_ERR(req))
518                 return req;
519
520         req->cmd_flags |= REQ_FAILFAST_DRIVER;
521         nvme_clear_nvme_request(req);
522         nvme_req(req)->cmd = cmd;
523
524         return req;
525 }
526 EXPORT_SYMBOL_GPL(nvme_alloc_request);
527
528 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
529 {
530         struct nvme_command c;
531
532         memset(&c, 0, sizeof(c));
533
534         c.directive.opcode = nvme_admin_directive_send;
535         c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
536         c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
537         c.directive.dtype = NVME_DIR_IDENTIFY;
538         c.directive.tdtype = NVME_DIR_STREAMS;
539         c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
540
541         return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
542 }
543
544 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
545 {
546         return nvme_toggle_streams(ctrl, false);
547 }
548
549 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
550 {
551         return nvme_toggle_streams(ctrl, true);
552 }
553
554 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
555                                   struct streams_directive_params *s, u32 nsid)
556 {
557         struct nvme_command c;
558
559         memset(&c, 0, sizeof(c));
560         memset(s, 0, sizeof(*s));
561
562         c.directive.opcode = nvme_admin_directive_recv;
563         c.directive.nsid = cpu_to_le32(nsid);
564         c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
565         c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
566         c.directive.dtype = NVME_DIR_STREAMS;
567
568         return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
569 }
570
571 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
572 {
573         struct streams_directive_params s;
574         int ret;
575
576         if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
577                 return 0;
578         if (!streams)
579                 return 0;
580
581         ret = nvme_enable_streams(ctrl);
582         if (ret)
583                 return ret;
584
585         ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
586         if (ret)
587                 goto out_disable_stream;
588
589         ctrl->nssa = le16_to_cpu(s.nssa);
590         if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
591                 dev_info(ctrl->device, "too few streams (%u) available\n",
592                                         ctrl->nssa);
593                 goto out_disable_stream;
594         }
595
596         ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
597         dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
598         return 0;
599
600 out_disable_stream:
601         nvme_disable_streams(ctrl);
602         return ret;
603 }
604
605 /*
606  * Check if 'req' has a write hint associated with it. If it does, assign
607  * a valid namespace stream to the write.
608  */
609 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
610                                      struct request *req, u16 *control,
611                                      u32 *dsmgmt)
612 {
613         enum rw_hint streamid = req->write_hint;
614
615         if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
616                 streamid = 0;
617         else {
618                 streamid--;
619                 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
620                         return;
621
622                 *control |= NVME_RW_DTYPE_STREAMS;
623                 *dsmgmt |= streamid << 16;
624         }
625
626         if (streamid < ARRAY_SIZE(req->q->write_hints))
627                 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
628 }
629
630 static void nvme_setup_passthrough(struct request *req,
631                 struct nvme_command *cmd)
632 {
633         memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
634         /* passthru commands should let the driver set the SGL flags */
635         cmd->common.flags &= ~NVME_CMD_SGL_ALL;
636 }
637
638 static inline void nvme_setup_flush(struct nvme_ns *ns,
639                 struct nvme_command *cmnd)
640 {
641         cmnd->common.opcode = nvme_cmd_flush;
642         cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
643 }
644
645 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
646                 struct nvme_command *cmnd)
647 {
648         unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
649         struct nvme_dsm_range *range;
650         struct bio *bio;
651
652         /*
653          * Some devices do not consider the DSM 'Number of Ranges' field when
654          * determining how much data to DMA. Always allocate memory for maximum
655          * number of segments to prevent device reading beyond end of buffer.
656          */
657         static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
658
659         range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
660         if (!range) {
661                 /*
662                  * If we fail allocation our range, fallback to the controller
663                  * discard page. If that's also busy, it's safe to return
664                  * busy, as we know we can make progress once that's freed.
665                  */
666                 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
667                         return BLK_STS_RESOURCE;
668
669                 range = page_address(ns->ctrl->discard_page);
670         }
671
672         __rq_for_each_bio(bio, req) {
673                 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
674                 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
675
676                 if (n < segments) {
677                         range[n].cattr = cpu_to_le32(0);
678                         range[n].nlb = cpu_to_le32(nlb);
679                         range[n].slba = cpu_to_le64(slba);
680                 }
681                 n++;
682         }
683
684         if (WARN_ON_ONCE(n != segments)) {
685                 if (virt_to_page(range) == ns->ctrl->discard_page)
686                         clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
687                 else
688                         kfree(range);
689                 return BLK_STS_IOERR;
690         }
691
692         cmnd->dsm.opcode = nvme_cmd_dsm;
693         cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
694         cmnd->dsm.nr = cpu_to_le32(segments - 1);
695         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
696
697         req->special_vec.bv_page = virt_to_page(range);
698         req->special_vec.bv_offset = offset_in_page(range);
699         req->special_vec.bv_len = alloc_size;
700         req->rq_flags |= RQF_SPECIAL_PAYLOAD;
701
702         return BLK_STS_OK;
703 }
704
705 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
706                 struct request *req, struct nvme_command *cmnd)
707 {
708         if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
709                 return nvme_setup_discard(ns, req, cmnd);
710
711         cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
712         cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
713         cmnd->write_zeroes.slba =
714                 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
715         cmnd->write_zeroes.length =
716                 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
717         cmnd->write_zeroes.control = 0;
718         return BLK_STS_OK;
719 }
720
721 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
722                 struct request *req, struct nvme_command *cmnd,
723                 enum nvme_opcode op)
724 {
725         struct nvme_ctrl *ctrl = ns->ctrl;
726         u16 control = 0;
727         u32 dsmgmt = 0;
728
729         if (req->cmd_flags & REQ_FUA)
730                 control |= NVME_RW_FUA;
731         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
732                 control |= NVME_RW_LR;
733
734         if (req->cmd_flags & REQ_RAHEAD)
735                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
736
737         cmnd->rw.opcode = op;
738         cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
739         cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
740         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
741
742         if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
743                 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
744
745         if (ns->ms) {
746                 /*
747                  * If formated with metadata, the block layer always provides a
748                  * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled.  Else
749                  * we enable the PRACT bit for protection information or set the
750                  * namespace capacity to zero to prevent any I/O.
751                  */
752                 if (!blk_integrity_rq(req)) {
753                         if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
754                                 return BLK_STS_NOTSUPP;
755                         control |= NVME_RW_PRINFO_PRACT;
756                 }
757
758                 switch (ns->pi_type) {
759                 case NVME_NS_DPS_PI_TYPE3:
760                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
761                         break;
762                 case NVME_NS_DPS_PI_TYPE1:
763                 case NVME_NS_DPS_PI_TYPE2:
764                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
765                                         NVME_RW_PRINFO_PRCHK_REF;
766                         if (op == nvme_cmd_zone_append)
767                                 control |= NVME_RW_APPEND_PIREMAP;
768                         cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
769                         break;
770                 }
771         }
772
773         cmnd->rw.control = cpu_to_le16(control);
774         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
775         return 0;
776 }
777
778 void nvme_cleanup_cmd(struct request *req)
779 {
780         if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
781                 struct nvme_ns *ns = req->rq_disk->private_data;
782                 struct page *page = req->special_vec.bv_page;
783
784                 if (page == ns->ctrl->discard_page)
785                         clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
786                 else
787                         kfree(page_address(page) + req->special_vec.bv_offset);
788         }
789 }
790 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
791
792 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
793                 struct nvme_command *cmd)
794 {
795         blk_status_t ret = BLK_STS_OK;
796
797         nvme_clear_nvme_request(req);
798
799         memset(cmd, 0, sizeof(*cmd));
800         switch (req_op(req)) {
801         case REQ_OP_DRV_IN:
802         case REQ_OP_DRV_OUT:
803                 nvme_setup_passthrough(req, cmd);
804                 break;
805         case REQ_OP_FLUSH:
806                 nvme_setup_flush(ns, cmd);
807                 break;
808         case REQ_OP_ZONE_RESET_ALL:
809         case REQ_OP_ZONE_RESET:
810                 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
811                 break;
812         case REQ_OP_ZONE_OPEN:
813                 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
814                 break;
815         case REQ_OP_ZONE_CLOSE:
816                 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
817                 break;
818         case REQ_OP_ZONE_FINISH:
819                 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
820                 break;
821         case REQ_OP_WRITE_ZEROES:
822                 ret = nvme_setup_write_zeroes(ns, req, cmd);
823                 break;
824         case REQ_OP_DISCARD:
825                 ret = nvme_setup_discard(ns, req, cmd);
826                 break;
827         case REQ_OP_READ:
828                 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
829                 break;
830         case REQ_OP_WRITE:
831                 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
832                 break;
833         case REQ_OP_ZONE_APPEND:
834                 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
835                 break;
836         default:
837                 WARN_ON_ONCE(1);
838                 return BLK_STS_IOERR;
839         }
840
841         cmd->common.command_id = req->tag;
842         trace_nvme_setup_cmd(req, cmd);
843         return ret;
844 }
845 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
846
847 static void nvme_end_sync_rq(struct request *rq, blk_status_t error)
848 {
849         struct completion *waiting = rq->end_io_data;
850
851         rq->end_io_data = NULL;
852         complete(waiting);
853 }
854
855 static void nvme_execute_rq_polled(struct request_queue *q,
856                 struct gendisk *bd_disk, struct request *rq, int at_head)
857 {
858         DECLARE_COMPLETION_ONSTACK(wait);
859
860         WARN_ON_ONCE(!test_bit(QUEUE_FLAG_POLL, &q->queue_flags));
861
862         rq->cmd_flags |= REQ_HIPRI;
863         rq->end_io_data = &wait;
864         blk_execute_rq_nowait(q, bd_disk, rq, at_head, nvme_end_sync_rq);
865
866         while (!completion_done(&wait)) {
867                 blk_poll(q, request_to_qc_t(rq->mq_hctx, rq), true);
868                 cond_resched();
869         }
870 }
871
872 /*
873  * Returns 0 on success.  If the result is negative, it's a Linux error code;
874  * if the result is positive, it's an NVM Express status code
875  */
876 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
877                 union nvme_result *result, void *buffer, unsigned bufflen,
878                 unsigned timeout, int qid, int at_head,
879                 blk_mq_req_flags_t flags, bool poll)
880 {
881         struct request *req;
882         int ret;
883
884         req = nvme_alloc_request(q, cmd, flags, qid);
885         if (IS_ERR(req))
886                 return PTR_ERR(req);
887
888         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
889
890         if (buffer && bufflen) {
891                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
892                 if (ret)
893                         goto out;
894         }
895
896         if (poll)
897                 nvme_execute_rq_polled(req->q, NULL, req, at_head);
898         else
899                 blk_execute_rq(req->q, NULL, req, at_head);
900         if (result)
901                 *result = nvme_req(req)->result;
902         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
903                 ret = -EINTR;
904         else
905                 ret = nvme_req(req)->status;
906  out:
907         blk_mq_free_request(req);
908         return ret;
909 }
910 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
911
912 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
913                 void *buffer, unsigned bufflen)
914 {
915         return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
916                         NVME_QID_ANY, 0, 0, false);
917 }
918 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
919
920 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
921                 unsigned len, u32 seed, bool write)
922 {
923         struct bio_integrity_payload *bip;
924         int ret = -ENOMEM;
925         void *buf;
926
927         buf = kmalloc(len, GFP_KERNEL);
928         if (!buf)
929                 goto out;
930
931         ret = -EFAULT;
932         if (write && copy_from_user(buf, ubuf, len))
933                 goto out_free_meta;
934
935         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
936         if (IS_ERR(bip)) {
937                 ret = PTR_ERR(bip);
938                 goto out_free_meta;
939         }
940
941         bip->bip_iter.bi_size = len;
942         bip->bip_iter.bi_sector = seed;
943         ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
944                         offset_in_page(buf));
945         if (ret == len)
946                 return buf;
947         ret = -ENOMEM;
948 out_free_meta:
949         kfree(buf);
950 out:
951         return ERR_PTR(ret);
952 }
953
954 static u32 nvme_known_admin_effects(u8 opcode)
955 {
956         switch (opcode) {
957         case nvme_admin_format_nvm:
958                 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
959                         NVME_CMD_EFFECTS_CSE_MASK;
960         case nvme_admin_sanitize_nvm:
961                 return NVME_CMD_EFFECTS_CSE_MASK;
962         default:
963                 break;
964         }
965         return 0;
966 }
967
968 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
969 {
970         u32 effects = 0;
971
972         if (ns) {
973                 if (ns->head->effects)
974                         effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
975                 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
976                         dev_warn(ctrl->device,
977                                  "IO command:%02x has unhandled effects:%08x\n",
978                                  opcode, effects);
979                 return 0;
980         }
981
982         if (ctrl->effects)
983                 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
984         effects |= nvme_known_admin_effects(opcode);
985
986         return effects;
987 }
988 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
989
990 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
991                                u8 opcode)
992 {
993         u32 effects = nvme_command_effects(ctrl, ns, opcode);
994
995         /*
996          * For simplicity, IO to all namespaces is quiesced even if the command
997          * effects say only one namespace is affected.
998          */
999         if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1000                 mutex_lock(&ctrl->scan_lock);
1001                 mutex_lock(&ctrl->subsys->lock);
1002                 nvme_mpath_start_freeze(ctrl->subsys);
1003                 nvme_mpath_wait_freeze(ctrl->subsys);
1004                 nvme_start_freeze(ctrl);
1005                 nvme_wait_freeze(ctrl);
1006         }
1007         return effects;
1008 }
1009
1010 static void nvme_update_formats(struct nvme_ctrl *ctrl, u32 *effects)
1011 {
1012         struct nvme_ns *ns;
1013
1014         down_read(&ctrl->namespaces_rwsem);
1015         list_for_each_entry(ns, &ctrl->namespaces, list)
1016                 if (_nvme_revalidate_disk(ns->disk))
1017                         nvme_set_queue_dying(ns);
1018                 else if (blk_queue_is_zoned(ns->disk->queue)) {
1019                         /*
1020                          * IO commands are required to fully revalidate a zoned
1021                          * device. Force the command effects to trigger rescan
1022                          * work so report zones can run in a context with
1023                          * unfrozen IO queues.
1024                          */
1025                         *effects |= NVME_CMD_EFFECTS_NCC;
1026                 }
1027         up_read(&ctrl->namespaces_rwsem);
1028 }
1029
1030 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1031 {
1032         /*
1033          * Revalidate LBA changes prior to unfreezing. This is necessary to
1034          * prevent memory corruption if a logical block size was changed by
1035          * this command.
1036          */
1037         if (effects & NVME_CMD_EFFECTS_LBCC)
1038                 nvme_update_formats(ctrl, &effects);
1039         if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1040                 nvme_unfreeze(ctrl);
1041                 nvme_mpath_unfreeze(ctrl->subsys);
1042                 mutex_unlock(&ctrl->subsys->lock);
1043                 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1044                 mutex_unlock(&ctrl->scan_lock);
1045         }
1046         if (effects & NVME_CMD_EFFECTS_CCC)
1047                 nvme_init_identify(ctrl);
1048         if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1049                 nvme_queue_scan(ctrl);
1050                 flush_work(&ctrl->scan_work);
1051         }
1052 }
1053
1054 void nvme_execute_passthru_rq(struct request *rq)
1055 {
1056         struct nvme_command *cmd = nvme_req(rq)->cmd;
1057         struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl;
1058         struct nvme_ns *ns = rq->q->queuedata;
1059         struct gendisk *disk = ns ? ns->disk : NULL;
1060         u32 effects;
1061
1062         effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode);
1063         blk_execute_rq(rq->q, disk, rq, 0);
1064         nvme_passthru_end(ctrl, effects);
1065 }
1066 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU);
1067
1068 static int nvme_submit_user_cmd(struct request_queue *q,
1069                 struct nvme_command *cmd, void __user *ubuffer,
1070                 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
1071                 u32 meta_seed, u64 *result, unsigned timeout)
1072 {
1073         bool write = nvme_is_write(cmd);
1074         struct nvme_ns *ns = q->queuedata;
1075         struct gendisk *disk = ns ? ns->disk : NULL;
1076         struct request *req;
1077         struct bio *bio = NULL;
1078         void *meta = NULL;
1079         int ret;
1080
1081         req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
1082         if (IS_ERR(req))
1083                 return PTR_ERR(req);
1084
1085         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
1086         nvme_req(req)->flags |= NVME_REQ_USERCMD;
1087
1088         if (ubuffer && bufflen) {
1089                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
1090                                 GFP_KERNEL);
1091                 if (ret)
1092                         goto out;
1093                 bio = req->bio;
1094                 bio->bi_disk = disk;
1095                 if (disk && meta_buffer && meta_len) {
1096                         meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
1097                                         meta_seed, write);
1098                         if (IS_ERR(meta)) {
1099                                 ret = PTR_ERR(meta);
1100                                 goto out_unmap;
1101                         }
1102                         req->cmd_flags |= REQ_INTEGRITY;
1103                 }
1104         }
1105
1106         nvme_execute_passthru_rq(req);
1107         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
1108                 ret = -EINTR;
1109         else
1110                 ret = nvme_req(req)->status;
1111         if (result)
1112                 *result = le64_to_cpu(nvme_req(req)->result.u64);
1113         if (meta && !ret && !write) {
1114                 if (copy_to_user(meta_buffer, meta, meta_len))
1115                         ret = -EFAULT;
1116         }
1117         kfree(meta);
1118  out_unmap:
1119         if (bio)
1120                 blk_rq_unmap_user(bio);
1121  out:
1122         blk_mq_free_request(req);
1123         return ret;
1124 }
1125
1126 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
1127 {
1128         struct nvme_ctrl *ctrl = rq->end_io_data;
1129         unsigned long flags;
1130         bool startka = false;
1131
1132         blk_mq_free_request(rq);
1133
1134         if (status) {
1135                 dev_err(ctrl->device,
1136                         "failed nvme_keep_alive_end_io error=%d\n",
1137                                 status);
1138                 return;
1139         }
1140
1141         ctrl->comp_seen = false;
1142         spin_lock_irqsave(&ctrl->lock, flags);
1143         if (ctrl->state == NVME_CTRL_LIVE ||
1144             ctrl->state == NVME_CTRL_CONNECTING)
1145                 startka = true;
1146         spin_unlock_irqrestore(&ctrl->lock, flags);
1147         if (startka)
1148                 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1149 }
1150
1151 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
1152 {
1153         struct request *rq;
1154
1155         rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
1156                         NVME_QID_ANY);
1157         if (IS_ERR(rq))
1158                 return PTR_ERR(rq);
1159
1160         rq->timeout = ctrl->kato * HZ;
1161         rq->end_io_data = ctrl;
1162
1163         blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
1164
1165         return 0;
1166 }
1167
1168 static void nvme_keep_alive_work(struct work_struct *work)
1169 {
1170         struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1171                         struct nvme_ctrl, ka_work);
1172         bool comp_seen = ctrl->comp_seen;
1173
1174         if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1175                 dev_dbg(ctrl->device,
1176                         "reschedule traffic based keep-alive timer\n");
1177                 ctrl->comp_seen = false;
1178                 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1179                 return;
1180         }
1181
1182         if (nvme_keep_alive(ctrl)) {
1183                 /* allocation failure, reset the controller */
1184                 dev_err(ctrl->device, "keep-alive failed\n");
1185                 nvme_reset_ctrl(ctrl);
1186                 return;
1187         }
1188 }
1189
1190 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1191 {
1192         if (unlikely(ctrl->kato == 0))
1193                 return;
1194
1195         queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1196 }
1197
1198 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1199 {
1200         if (unlikely(ctrl->kato == 0))
1201                 return;
1202
1203         cancel_delayed_work_sync(&ctrl->ka_work);
1204 }
1205 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1206
1207 /*
1208  * In NVMe 1.0 the CNS field was just a binary controller or namespace
1209  * flag, thus sending any new CNS opcodes has a big chance of not working.
1210  * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1211  * (but not for any later version).
1212  */
1213 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1214 {
1215         if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1216                 return ctrl->vs < NVME_VS(1, 2, 0);
1217         return ctrl->vs < NVME_VS(1, 1, 0);
1218 }
1219
1220 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1221 {
1222         struct nvme_command c = { };
1223         int error;
1224
1225         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1226         c.identify.opcode = nvme_admin_identify;
1227         c.identify.cns = NVME_ID_CNS_CTRL;
1228
1229         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1230         if (!*id)
1231                 return -ENOMEM;
1232
1233         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1234                         sizeof(struct nvme_id_ctrl));
1235         if (error)
1236                 kfree(*id);
1237         return error;
1238 }
1239
1240 static bool nvme_multi_css(struct nvme_ctrl *ctrl)
1241 {
1242         return (ctrl->ctrl_config & NVME_CC_CSS_MASK) == NVME_CC_CSS_CSI;
1243 }
1244
1245 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1246                 struct nvme_ns_id_desc *cur, bool *csi_seen)
1247 {
1248         const char *warn_str = "ctrl returned bogus length:";
1249         void *data = cur;
1250
1251         switch (cur->nidt) {
1252         case NVME_NIDT_EUI64:
1253                 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1254                         dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1255                                  warn_str, cur->nidl);
1256                         return -1;
1257                 }
1258                 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1259                 return NVME_NIDT_EUI64_LEN;
1260         case NVME_NIDT_NGUID:
1261                 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1262                         dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1263                                  warn_str, cur->nidl);
1264                         return -1;
1265                 }
1266                 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1267                 return NVME_NIDT_NGUID_LEN;
1268         case NVME_NIDT_UUID:
1269                 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1270                         dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1271                                  warn_str, cur->nidl);
1272                         return -1;
1273                 }
1274                 uuid_copy(&ids->uuid, data + sizeof(*cur));
1275                 return NVME_NIDT_UUID_LEN;
1276         case NVME_NIDT_CSI:
1277                 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1278                         dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1279                                  warn_str, cur->nidl);
1280                         return -1;
1281                 }
1282                 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1283                 *csi_seen = true;
1284                 return NVME_NIDT_CSI_LEN;
1285         default:
1286                 /* Skip unknown types */
1287                 return cur->nidl;
1288         }
1289 }
1290
1291 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1292                 struct nvme_ns_ids *ids)
1293 {
1294         struct nvme_command c = { };
1295         bool csi_seen = false;
1296         int status, pos, len;
1297         void *data;
1298
1299         if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1300                 return 0;
1301
1302         c.identify.opcode = nvme_admin_identify;
1303         c.identify.nsid = cpu_to_le32(nsid);
1304         c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1305
1306         data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1307         if (!data)
1308                 return -ENOMEM;
1309
1310         status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1311                                       NVME_IDENTIFY_DATA_SIZE);
1312         if (status) {
1313                 dev_warn(ctrl->device,
1314                         "Identify Descriptors failed (%d)\n", status);
1315                 goto free_data;
1316         }
1317
1318         for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1319                 struct nvme_ns_id_desc *cur = data + pos;
1320
1321                 if (cur->nidl == 0)
1322                         break;
1323
1324                 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1325                 if (len < 0)
1326                         break;
1327
1328                 len += sizeof(*cur);
1329         }
1330
1331         if (nvme_multi_css(ctrl) && !csi_seen) {
1332                 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1333                          nsid);
1334                 status = -EINVAL;
1335         }
1336
1337 free_data:
1338         kfree(data);
1339         return status;
1340 }
1341
1342 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
1343 {
1344         struct nvme_command c = { };
1345
1346         c.identify.opcode = nvme_admin_identify;
1347         c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
1348         c.identify.nsid = cpu_to_le32(nsid);
1349         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
1350                                     NVME_IDENTIFY_DATA_SIZE);
1351 }
1352
1353 static int nvme_identify_ns(struct nvme_ctrl *ctrl,
1354                 unsigned nsid, struct nvme_id_ns **id)
1355 {
1356         struct nvme_command c = { };
1357         int error;
1358
1359         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1360         c.identify.opcode = nvme_admin_identify;
1361         c.identify.nsid = cpu_to_le32(nsid);
1362         c.identify.cns = NVME_ID_CNS_NS;
1363
1364         *id = kmalloc(sizeof(**id), GFP_KERNEL);
1365         if (!*id)
1366                 return -ENOMEM;
1367
1368         error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1369         if (error) {
1370                 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1371                 kfree(*id);
1372         }
1373
1374         return error;
1375 }
1376
1377 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1378                 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1379 {
1380         union nvme_result res = { 0 };
1381         struct nvme_command c;
1382         int ret;
1383
1384         memset(&c, 0, sizeof(c));
1385         c.features.opcode = op;
1386         c.features.fid = cpu_to_le32(fid);
1387         c.features.dword11 = cpu_to_le32(dword11);
1388
1389         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1390                         buffer, buflen, 0, NVME_QID_ANY, 0, 0, false);
1391         if (ret >= 0 && result)
1392                 *result = le32_to_cpu(res.u32);
1393         return ret;
1394 }
1395
1396 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1397                       unsigned int dword11, void *buffer, size_t buflen,
1398                       u32 *result)
1399 {
1400         return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1401                              buflen, result);
1402 }
1403 EXPORT_SYMBOL_GPL(nvme_set_features);
1404
1405 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1406                       unsigned int dword11, void *buffer, size_t buflen,
1407                       u32 *result)
1408 {
1409         return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1410                              buflen, result);
1411 }
1412 EXPORT_SYMBOL_GPL(nvme_get_features);
1413
1414 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1415 {
1416         u32 q_count = (*count - 1) | ((*count - 1) << 16);
1417         u32 result;
1418         int status, nr_io_queues;
1419
1420         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1421                         &result);
1422         if (status < 0)
1423                 return status;
1424
1425         /*
1426          * Degraded controllers might return an error when setting the queue
1427          * count.  We still want to be able to bring them online and offer
1428          * access to the admin queue, as that might be only way to fix them up.
1429          */
1430         if (status > 0) {
1431                 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1432                 *count = 0;
1433         } else {
1434                 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1435                 *count = min(*count, nr_io_queues);
1436         }
1437
1438         return 0;
1439 }
1440 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1441
1442 #define NVME_AEN_SUPPORTED \
1443         (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1444          NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1445
1446 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1447 {
1448         u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1449         int status;
1450
1451         if (!supported_aens)
1452                 return;
1453
1454         status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1455                         NULL, 0, &result);
1456         if (status)
1457                 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1458                          supported_aens);
1459
1460         queue_work(nvme_wq, &ctrl->async_event_work);
1461 }
1462
1463 /*
1464  * Convert integer values from ioctl structures to user pointers, silently
1465  * ignoring the upper bits in the compat case to match behaviour of 32-bit
1466  * kernels.
1467  */
1468 static void __user *nvme_to_user_ptr(uintptr_t ptrval)
1469 {
1470         if (in_compat_syscall())
1471                 ptrval = (compat_uptr_t)ptrval;
1472         return (void __user *)ptrval;
1473 }
1474
1475 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1476 {
1477         struct nvme_user_io io;
1478         struct nvme_command c;
1479         unsigned length, meta_len;
1480         void __user *metadata;
1481
1482         if (copy_from_user(&io, uio, sizeof(io)))
1483                 return -EFAULT;
1484         if (io.flags)
1485                 return -EINVAL;
1486
1487         switch (io.opcode) {
1488         case nvme_cmd_write:
1489         case nvme_cmd_read:
1490         case nvme_cmd_compare:
1491                 break;
1492         default:
1493                 return -EINVAL;
1494         }
1495
1496         length = (io.nblocks + 1) << ns->lba_shift;
1497         meta_len = (io.nblocks + 1) * ns->ms;
1498         metadata = nvme_to_user_ptr(io.metadata);
1499
1500         if (ns->features & NVME_NS_EXT_LBAS) {
1501                 length += meta_len;
1502                 meta_len = 0;
1503         } else if (meta_len) {
1504                 if ((io.metadata & 3) || !io.metadata)
1505                         return -EINVAL;
1506         }
1507
1508         memset(&c, 0, sizeof(c));
1509         c.rw.opcode = io.opcode;
1510         c.rw.flags = io.flags;
1511         c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1512         c.rw.slba = cpu_to_le64(io.slba);
1513         c.rw.length = cpu_to_le16(io.nblocks);
1514         c.rw.control = cpu_to_le16(io.control);
1515         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1516         c.rw.reftag = cpu_to_le32(io.reftag);
1517         c.rw.apptag = cpu_to_le16(io.apptag);
1518         c.rw.appmask = cpu_to_le16(io.appmask);
1519
1520         return nvme_submit_user_cmd(ns->queue, &c,
1521                         nvme_to_user_ptr(io.addr), length,
1522                         metadata, meta_len, lower_32_bits(io.slba), NULL, 0);
1523 }
1524
1525 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1526                         struct nvme_passthru_cmd __user *ucmd)
1527 {
1528         struct nvme_passthru_cmd cmd;
1529         struct nvme_command c;
1530         unsigned timeout = 0;
1531         u64 result;
1532         int status;
1533
1534         if (!capable(CAP_SYS_ADMIN))
1535                 return -EACCES;
1536         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1537                 return -EFAULT;
1538         if (cmd.flags)
1539                 return -EINVAL;
1540
1541         memset(&c, 0, sizeof(c));
1542         c.common.opcode = cmd.opcode;
1543         c.common.flags = cmd.flags;
1544         c.common.nsid = cpu_to_le32(cmd.nsid);
1545         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1546         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1547         c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1548         c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1549         c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1550         c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1551         c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1552         c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1553
1554         if (cmd.timeout_ms)
1555                 timeout = msecs_to_jiffies(cmd.timeout_ms);
1556
1557         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1558                         nvme_to_user_ptr(cmd.addr), cmd.data_len,
1559                         nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1560                         0, &result, timeout);
1561
1562         if (status >= 0) {
1563                 if (put_user(result, &ucmd->result))
1564                         return -EFAULT;
1565         }
1566
1567         return status;
1568 }
1569
1570 static int nvme_user_cmd64(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1571                         struct nvme_passthru_cmd64 __user *ucmd)
1572 {
1573         struct nvme_passthru_cmd64 cmd;
1574         struct nvme_command c;
1575         unsigned timeout = 0;
1576         int status;
1577
1578         if (!capable(CAP_SYS_ADMIN))
1579                 return -EACCES;
1580         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1581                 return -EFAULT;
1582         if (cmd.flags)
1583                 return -EINVAL;
1584
1585         memset(&c, 0, sizeof(c));
1586         c.common.opcode = cmd.opcode;
1587         c.common.flags = cmd.flags;
1588         c.common.nsid = cpu_to_le32(cmd.nsid);
1589         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1590         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1591         c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1592         c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1593         c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1594         c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1595         c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1596         c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1597
1598         if (cmd.timeout_ms)
1599                 timeout = msecs_to_jiffies(cmd.timeout_ms);
1600
1601         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1602                         nvme_to_user_ptr(cmd.addr), cmd.data_len,
1603                         nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1604                         0, &cmd.result, timeout);
1605
1606         if (status >= 0) {
1607                 if (put_user(cmd.result, &ucmd->result))
1608                         return -EFAULT;
1609         }
1610
1611         return status;
1612 }
1613
1614 /*
1615  * Issue ioctl requests on the first available path.  Note that unlike normal
1616  * block layer requests we will not retry failed request on another controller.
1617  */
1618 struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1619                 struct nvme_ns_head **head, int *srcu_idx)
1620 {
1621 #ifdef CONFIG_NVME_MULTIPATH
1622         if (disk->fops == &nvme_ns_head_ops) {
1623                 struct nvme_ns *ns;
1624
1625                 *head = disk->private_data;
1626                 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1627                 ns = nvme_find_path(*head);
1628                 if (!ns)
1629                         srcu_read_unlock(&(*head)->srcu, *srcu_idx);
1630                 return ns;
1631         }
1632 #endif
1633         *head = NULL;
1634         *srcu_idx = -1;
1635         return disk->private_data;
1636 }
1637
1638 void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1639 {
1640         if (head)
1641                 srcu_read_unlock(&head->srcu, idx);
1642 }
1643
1644 static bool is_ctrl_ioctl(unsigned int cmd)
1645 {
1646         if (cmd == NVME_IOCTL_ADMIN_CMD || cmd == NVME_IOCTL_ADMIN64_CMD)
1647                 return true;
1648         if (is_sed_ioctl(cmd))
1649                 return true;
1650         return false;
1651 }
1652
1653 static int nvme_handle_ctrl_ioctl(struct nvme_ns *ns, unsigned int cmd,
1654                                   void __user *argp,
1655                                   struct nvme_ns_head *head,
1656                                   int srcu_idx)
1657 {
1658         struct nvme_ctrl *ctrl = ns->ctrl;
1659         int ret;
1660
1661         nvme_get_ctrl(ns->ctrl);
1662         nvme_put_ns_from_disk(head, srcu_idx);
1663
1664         switch (cmd) {
1665         case NVME_IOCTL_ADMIN_CMD:
1666                 ret = nvme_user_cmd(ctrl, NULL, argp);
1667                 break;
1668         case NVME_IOCTL_ADMIN64_CMD:
1669                 ret = nvme_user_cmd64(ctrl, NULL, argp);
1670                 break;
1671         default:
1672                 ret = sed_ioctl(ctrl->opal_dev, cmd, argp);
1673                 break;
1674         }
1675         nvme_put_ctrl(ctrl);
1676         return ret;
1677 }
1678
1679 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1680                 unsigned int cmd, unsigned long arg)
1681 {
1682         struct nvme_ns_head *head = NULL;
1683         void __user *argp = (void __user *)arg;
1684         struct nvme_ns *ns;
1685         int srcu_idx, ret;
1686
1687         ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1688         if (unlikely(!ns))
1689                 return -EWOULDBLOCK;
1690
1691         /*
1692          * Handle ioctls that apply to the controller instead of the namespace
1693          * seperately and drop the ns SRCU reference early.  This avoids a
1694          * deadlock when deleting namespaces using the passthrough interface.
1695          */
1696         if (is_ctrl_ioctl(cmd))
1697                 return nvme_handle_ctrl_ioctl(ns, cmd, argp, head, srcu_idx);
1698
1699         switch (cmd) {
1700         case NVME_IOCTL_ID:
1701                 force_successful_syscall_return();
1702                 ret = ns->head->ns_id;
1703                 break;
1704         case NVME_IOCTL_IO_CMD:
1705                 ret = nvme_user_cmd(ns->ctrl, ns, argp);
1706                 break;
1707         case NVME_IOCTL_SUBMIT_IO:
1708                 ret = nvme_submit_io(ns, argp);
1709                 break;
1710         case NVME_IOCTL_IO64_CMD:
1711                 ret = nvme_user_cmd64(ns->ctrl, ns, argp);
1712                 break;
1713         default:
1714                 if (ns->ndev)
1715                         ret = nvme_nvm_ioctl(ns, cmd, arg);
1716                 else
1717                         ret = -ENOTTY;
1718         }
1719
1720         nvme_put_ns_from_disk(head, srcu_idx);
1721         return ret;
1722 }
1723
1724 #ifdef CONFIG_COMPAT
1725 struct nvme_user_io32 {
1726         __u8    opcode;
1727         __u8    flags;
1728         __u16   control;
1729         __u16   nblocks;
1730         __u16   rsvd;
1731         __u64   metadata;
1732         __u64   addr;
1733         __u64   slba;
1734         __u32   dsmgmt;
1735         __u32   reftag;
1736         __u16   apptag;
1737         __u16   appmask;
1738 } __attribute__((__packed__));
1739
1740 #define NVME_IOCTL_SUBMIT_IO32  _IOW('N', 0x42, struct nvme_user_io32)
1741
1742 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1743                 unsigned int cmd, unsigned long arg)
1744 {
1745         /*
1746          * Corresponds to the difference of NVME_IOCTL_SUBMIT_IO
1747          * between 32 bit programs and 64 bit kernel.
1748          * The cause is that the results of sizeof(struct nvme_user_io),
1749          * which is used to define NVME_IOCTL_SUBMIT_IO,
1750          * are not same between 32 bit compiler and 64 bit compiler.
1751          * NVME_IOCTL_SUBMIT_IO32 is for 64 bit kernel handling
1752          * NVME_IOCTL_SUBMIT_IO issued from 32 bit programs.
1753          * Other IOCTL numbers are same between 32 bit and 64 bit.
1754          * So there is nothing to do regarding to other IOCTL numbers.
1755          */
1756         if (cmd == NVME_IOCTL_SUBMIT_IO32)
1757                 return nvme_ioctl(bdev, mode, NVME_IOCTL_SUBMIT_IO, arg);
1758
1759         return nvme_ioctl(bdev, mode, cmd, arg);
1760 }
1761 #else
1762 #define nvme_compat_ioctl       NULL
1763 #endif /* CONFIG_COMPAT */
1764
1765 static int nvme_open(struct block_device *bdev, fmode_t mode)
1766 {
1767         struct nvme_ns *ns = bdev->bd_disk->private_data;
1768
1769 #ifdef CONFIG_NVME_MULTIPATH
1770         /* should never be called due to GENHD_FL_HIDDEN */
1771         if (WARN_ON_ONCE(ns->head->disk))
1772                 goto fail;
1773 #endif
1774         if (!kref_get_unless_zero(&ns->kref))
1775                 goto fail;
1776         if (!try_module_get(ns->ctrl->ops->module))
1777                 goto fail_put_ns;
1778
1779         return 0;
1780
1781 fail_put_ns:
1782         nvme_put_ns(ns);
1783 fail:
1784         return -ENXIO;
1785 }
1786
1787 static void nvme_release(struct gendisk *disk, fmode_t mode)
1788 {
1789         struct nvme_ns *ns = disk->private_data;
1790
1791         module_put(ns->ctrl->ops->module);
1792         nvme_put_ns(ns);
1793 }
1794
1795 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1796 {
1797         /* some standard values */
1798         geo->heads = 1 << 6;
1799         geo->sectors = 1 << 5;
1800         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1801         return 0;
1802 }
1803
1804 #ifdef CONFIG_BLK_DEV_INTEGRITY
1805 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1806                                 u32 max_integrity_segments)
1807 {
1808         struct blk_integrity integrity;
1809
1810         memset(&integrity, 0, sizeof(integrity));
1811         switch (pi_type) {
1812         case NVME_NS_DPS_PI_TYPE3:
1813                 integrity.profile = &t10_pi_type3_crc;
1814                 integrity.tag_size = sizeof(u16) + sizeof(u32);
1815                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1816                 break;
1817         case NVME_NS_DPS_PI_TYPE1:
1818         case NVME_NS_DPS_PI_TYPE2:
1819                 integrity.profile = &t10_pi_type1_crc;
1820                 integrity.tag_size = sizeof(u16);
1821                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1822                 break;
1823         default:
1824                 integrity.profile = NULL;
1825                 break;
1826         }
1827         integrity.tuple_size = ms;
1828         blk_integrity_register(disk, &integrity);
1829         blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1830 }
1831 #else
1832 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1833                                 u32 max_integrity_segments)
1834 {
1835 }
1836 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1837
1838 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1839 {
1840         struct nvme_ctrl *ctrl = ns->ctrl;
1841         struct request_queue *queue = disk->queue;
1842         u32 size = queue_logical_block_size(queue);
1843
1844         if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1845                 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1846                 return;
1847         }
1848
1849         if (ctrl->nr_streams && ns->sws && ns->sgs)
1850                 size *= ns->sws * ns->sgs;
1851
1852         BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1853                         NVME_DSM_MAX_RANGES);
1854
1855         queue->limits.discard_alignment = 0;
1856         queue->limits.discard_granularity = size;
1857
1858         /* If discard is already enabled, don't reset queue limits */
1859         if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1860                 return;
1861
1862         blk_queue_max_discard_sectors(queue, UINT_MAX);
1863         blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1864
1865         if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1866                 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1867 }
1868
1869 static void nvme_config_write_zeroes(struct gendisk *disk, struct nvme_ns *ns)
1870 {
1871         u64 max_blocks;
1872
1873         if (!(ns->ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) ||
1874             (ns->ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
1875                 return;
1876         /*
1877          * Even though NVMe spec explicitly states that MDTS is not
1878          * applicable to the write-zeroes:- "The restriction does not apply to
1879          * commands that do not transfer data between the host and the
1880          * controller (e.g., Write Uncorrectable ro Write Zeroes command).".
1881          * In order to be more cautious use controller's max_hw_sectors value
1882          * to configure the maximum sectors for the write-zeroes which is
1883          * configured based on the controller's MDTS field in the
1884          * nvme_init_identify() if available.
1885          */
1886         if (ns->ctrl->max_hw_sectors == UINT_MAX)
1887                 max_blocks = (u64)USHRT_MAX + 1;
1888         else
1889                 max_blocks = ns->ctrl->max_hw_sectors + 1;
1890
1891         blk_queue_max_write_zeroes_sectors(disk->queue,
1892                                            nvme_lba_to_sect(ns, max_blocks));
1893 }
1894
1895 static int nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1896                 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1897 {
1898         memset(ids, 0, sizeof(*ids));
1899
1900         if (ctrl->vs >= NVME_VS(1, 1, 0))
1901                 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1902         if (ctrl->vs >= NVME_VS(1, 2, 0))
1903                 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1904         if (ctrl->vs >= NVME_VS(1, 3, 0) || nvme_multi_css(ctrl))
1905                 return nvme_identify_ns_descs(ctrl, nsid, ids);
1906         return 0;
1907 }
1908
1909 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1910 {
1911         return !uuid_is_null(&ids->uuid) ||
1912                 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1913                 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1914 }
1915
1916 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1917 {
1918         return uuid_equal(&a->uuid, &b->uuid) &&
1919                 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1920                 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1921                 a->csi == b->csi;
1922 }
1923
1924 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1925                                  u32 *phys_bs, u32 *io_opt)
1926 {
1927         struct streams_directive_params s;
1928         int ret;
1929
1930         if (!ctrl->nr_streams)
1931                 return 0;
1932
1933         ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1934         if (ret)
1935                 return ret;
1936
1937         ns->sws = le32_to_cpu(s.sws);
1938         ns->sgs = le16_to_cpu(s.sgs);
1939
1940         if (ns->sws) {
1941                 *phys_bs = ns->sws * (1 << ns->lba_shift);
1942                 if (ns->sgs)
1943                         *io_opt = *phys_bs * ns->sgs;
1944         }
1945
1946         return 0;
1947 }
1948
1949 static void nvme_update_disk_info(struct gendisk *disk,
1950                 struct nvme_ns *ns, struct nvme_id_ns *id)
1951 {
1952         sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1953         unsigned short bs = 1 << ns->lba_shift;
1954         u32 atomic_bs, phys_bs, io_opt = 0;
1955
1956         if (ns->lba_shift > PAGE_SHIFT) {
1957                 /* unsupported block size, set capacity to 0 later */
1958                 bs = (1 << 9);
1959         }
1960         blk_mq_freeze_queue(disk->queue);
1961         blk_integrity_unregister(disk);
1962
1963         atomic_bs = phys_bs = bs;
1964         nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1965         if (id->nabo == 0) {
1966                 /*
1967                  * Bit 1 indicates whether NAWUPF is defined for this namespace
1968                  * and whether it should be used instead of AWUPF. If NAWUPF ==
1969                  * 0 then AWUPF must be used instead.
1970                  */
1971                 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1972                         atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1973                 else
1974                         atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1975         }
1976
1977         if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1978                 /* NPWG = Namespace Preferred Write Granularity */
1979                 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1980                 /* NOWS = Namespace Optimal Write Size */
1981                 io_opt = bs * (1 + le16_to_cpu(id->nows));
1982         }
1983
1984         blk_queue_logical_block_size(disk->queue, bs);
1985         /*
1986          * Linux filesystems assume writing a single physical block is
1987          * an atomic operation. Hence limit the physical block size to the
1988          * value of the Atomic Write Unit Power Fail parameter.
1989          */
1990         blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1991         blk_queue_io_min(disk->queue, phys_bs);
1992         blk_queue_io_opt(disk->queue, io_opt);
1993
1994         /*
1995          * The block layer can't support LBA sizes larger than the page size
1996          * yet, so catch this early and don't allow block I/O.
1997          */
1998         if (ns->lba_shift > PAGE_SHIFT)
1999                 capacity = 0;
2000
2001         /*
2002          * Register a metadata profile for PI, or the plain non-integrity NVMe
2003          * metadata masquerading as Type 0 if supported, otherwise reject block
2004          * I/O to namespaces with metadata except when the namespace supports
2005          * PI, as it can strip/insert in that case.
2006          */
2007         if (ns->ms) {
2008                 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
2009                     (ns->features & NVME_NS_METADATA_SUPPORTED))
2010                         nvme_init_integrity(disk, ns->ms, ns->pi_type,
2011                                             ns->ctrl->max_integrity_segments);
2012                 else if (!nvme_ns_has_pi(ns))
2013                         capacity = 0;
2014         }
2015
2016         set_capacity_revalidate_and_notify(disk, capacity, false);
2017
2018         nvme_config_discard(disk, ns);
2019         nvme_config_write_zeroes(disk, ns);
2020
2021         if (id->nsattr & NVME_NS_ATTR_RO)
2022                 set_disk_ro(disk, true);
2023         else
2024                 set_disk_ro(disk, false);
2025
2026         blk_mq_unfreeze_queue(disk->queue);
2027 }
2028
2029 static int __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
2030 {
2031         unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
2032         struct nvme_ns *ns = disk->private_data;
2033         struct nvme_ctrl *ctrl = ns->ctrl;
2034         int ret;
2035         u32 iob;
2036
2037         /*
2038          * If identify namespace failed, use default 512 byte block size so
2039          * block layer can use before failing read/write for 0 capacity.
2040          */
2041         ns->lba_shift = id->lbaf[lbaf].ds;
2042         if (ns->lba_shift == 0)
2043                 ns->lba_shift = 9;
2044
2045         switch (ns->head->ids.csi) {
2046         case NVME_CSI_NVM:
2047                 break;
2048         case NVME_CSI_ZNS:
2049                 ret = nvme_update_zone_info(disk, ns, lbaf);
2050                 if (ret) {
2051                         dev_warn(ctrl->device,
2052                                 "failed to add zoned namespace:%u ret:%d\n",
2053                                 ns->head->ns_id, ret);
2054                         return ret;
2055                 }
2056                 break;
2057         default:
2058                 dev_warn(ctrl->device, "unknown csi:%u ns:%u\n",
2059                         ns->head->ids.csi, ns->head->ns_id);
2060                 return -ENODEV;
2061         }
2062
2063         if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
2064             is_power_of_2(ctrl->max_hw_sectors))
2065                 iob = ctrl->max_hw_sectors;
2066         else
2067                 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
2068
2069         ns->features = 0;
2070         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
2071         /* the PI implementation requires metadata equal t10 pi tuple size */
2072         if (ns->ms == sizeof(struct t10_pi_tuple))
2073                 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
2074         else
2075                 ns->pi_type = 0;
2076
2077         if (ns->ms) {
2078                 /*
2079                  * For PCIe only the separate metadata pointer is supported,
2080                  * as the block layer supplies metadata in a separate bio_vec
2081                  * chain. For Fabrics, only metadata as part of extended data
2082                  * LBA is supported on the wire per the Fabrics specification,
2083                  * but the HBA/HCA will do the remapping from the separate
2084                  * metadata buffers for us.
2085                  */
2086                 if (id->flbas & NVME_NS_FLBAS_META_EXT) {
2087                         ns->features |= NVME_NS_EXT_LBAS;
2088                         if ((ctrl->ops->flags & NVME_F_FABRICS) &&
2089                             (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED) &&
2090                             ctrl->max_integrity_segments)
2091                                 ns->features |= NVME_NS_METADATA_SUPPORTED;
2092                 } else {
2093                         if (WARN_ON_ONCE(ctrl->ops->flags & NVME_F_FABRICS))
2094                                 return -EINVAL;
2095                         if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
2096                                 ns->features |= NVME_NS_METADATA_SUPPORTED;
2097                 }
2098         }
2099
2100         if (iob && !blk_queue_is_zoned(ns->queue))
2101                 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(iob));
2102         nvme_update_disk_info(disk, ns, id);
2103 #ifdef CONFIG_NVME_MULTIPATH
2104         if (ns->head->disk) {
2105                 nvme_update_disk_info(ns->head->disk, ns, id);
2106                 blk_stack_limits(&ns->head->disk->queue->limits,
2107                                  &ns->queue->limits, 0);
2108                 nvme_mpath_update_disk_size(ns->head->disk);
2109         }
2110 #endif
2111         return 0;
2112 }
2113
2114 static int _nvme_revalidate_disk(struct gendisk *disk)
2115 {
2116         struct nvme_ns *ns = disk->private_data;
2117         struct nvme_ctrl *ctrl = ns->ctrl;
2118         struct nvme_id_ns *id;
2119         struct nvme_ns_ids ids;
2120         int ret = 0;
2121
2122         if (test_bit(NVME_NS_DEAD, &ns->flags)) {
2123                 set_capacity(disk, 0);
2124                 return -ENODEV;
2125         }
2126
2127         ret = nvme_identify_ns(ctrl, ns->head->ns_id, &id);
2128         if (ret)
2129                 goto out;
2130
2131         if (id->ncap == 0) {
2132                 ret = -ENODEV;
2133                 goto free_id;
2134         }
2135
2136         ret = nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
2137         if (ret)
2138                 goto free_id;
2139
2140         if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
2141                 dev_err(ctrl->device,
2142                         "identifiers changed for nsid %d\n", ns->head->ns_id);
2143                 ret = -ENODEV;
2144                 goto free_id;
2145         }
2146
2147         ret = __nvme_revalidate_disk(disk, id);
2148 free_id:
2149         kfree(id);
2150 out:
2151         /*
2152          * Only fail the function if we got a fatal error back from the
2153          * device, otherwise ignore the error and just move on.
2154          */
2155         if (ret == -ENOMEM || (ret > 0 && !(ret & NVME_SC_DNR)))
2156                 ret = 0;
2157         else if (ret > 0)
2158                 ret = blk_status_to_errno(nvme_error_status(ret));
2159         return ret;
2160 }
2161
2162 static int nvme_revalidate_disk(struct gendisk *disk)
2163 {
2164         int ret;
2165
2166         ret = _nvme_revalidate_disk(disk);
2167         if (ret)
2168                 return ret;
2169
2170 #ifdef CONFIG_BLK_DEV_ZONED
2171         if (blk_queue_is_zoned(disk->queue)) {
2172                 struct nvme_ns *ns = disk->private_data;
2173                 struct nvme_ctrl *ctrl = ns->ctrl;
2174
2175                 ret = blk_revalidate_disk_zones(disk, NULL);
2176                 if (!ret)
2177                         blk_queue_max_zone_append_sectors(disk->queue,
2178                                                           ctrl->max_zone_append);
2179         }
2180 #endif
2181         return ret;
2182 }
2183
2184 static char nvme_pr_type(enum pr_type type)
2185 {
2186         switch (type) {
2187         case PR_WRITE_EXCLUSIVE:
2188                 return 1;
2189         case PR_EXCLUSIVE_ACCESS:
2190                 return 2;
2191         case PR_WRITE_EXCLUSIVE_REG_ONLY:
2192                 return 3;
2193         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
2194                 return 4;
2195         case PR_WRITE_EXCLUSIVE_ALL_REGS:
2196                 return 5;
2197         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
2198                 return 6;
2199         default:
2200                 return 0;
2201         }
2202 };
2203
2204 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
2205                                 u64 key, u64 sa_key, u8 op)
2206 {
2207         struct nvme_ns_head *head = NULL;
2208         struct nvme_ns *ns;
2209         struct nvme_command c;
2210         int srcu_idx, ret;
2211         u8 data[16] = { 0, };
2212
2213         ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
2214         if (unlikely(!ns))
2215                 return -EWOULDBLOCK;
2216
2217         put_unaligned_le64(key, &data[0]);
2218         put_unaligned_le64(sa_key, &data[8]);
2219
2220         memset(&c, 0, sizeof(c));
2221         c.common.opcode = op;
2222         c.common.nsid = cpu_to_le32(ns->head->ns_id);
2223         c.common.cdw10 = cpu_to_le32(cdw10);
2224
2225         ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
2226         nvme_put_ns_from_disk(head, srcu_idx);
2227         return ret;
2228 }
2229
2230 static int nvme_pr_register(struct block_device *bdev, u64 old,
2231                 u64 new, unsigned flags)
2232 {
2233         u32 cdw10;
2234
2235         if (flags & ~PR_FL_IGNORE_KEY)
2236                 return -EOPNOTSUPP;
2237
2238         cdw10 = old ? 2 : 0;
2239         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2240         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2241         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2242 }
2243
2244 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2245                 enum pr_type type, unsigned flags)
2246 {
2247         u32 cdw10;
2248
2249         if (flags & ~PR_FL_IGNORE_KEY)
2250                 return -EOPNOTSUPP;
2251
2252         cdw10 = nvme_pr_type(type) << 8;
2253         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2254         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2255 }
2256
2257 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2258                 enum pr_type type, bool abort)
2259 {
2260         u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
2261         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2262 }
2263
2264 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2265 {
2266         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2267         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2268 }
2269
2270 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2271 {
2272         u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
2273         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2274 }
2275
2276 static const struct pr_ops nvme_pr_ops = {
2277         .pr_register    = nvme_pr_register,
2278         .pr_reserve     = nvme_pr_reserve,
2279         .pr_release     = nvme_pr_release,
2280         .pr_preempt     = nvme_pr_preempt,
2281         .pr_clear       = nvme_pr_clear,
2282 };
2283
2284 #ifdef CONFIG_BLK_SED_OPAL
2285 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2286                 bool send)
2287 {
2288         struct nvme_ctrl *ctrl = data;
2289         struct nvme_command cmd;
2290
2291         memset(&cmd, 0, sizeof(cmd));
2292         if (send)
2293                 cmd.common.opcode = nvme_admin_security_send;
2294         else
2295                 cmd.common.opcode = nvme_admin_security_recv;
2296         cmd.common.nsid = 0;
2297         cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2298         cmd.common.cdw11 = cpu_to_le32(len);
2299
2300         return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
2301                                       ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0, false);
2302 }
2303 EXPORT_SYMBOL_GPL(nvme_sec_submit);
2304 #endif /* CONFIG_BLK_SED_OPAL */
2305
2306 static const struct block_device_operations nvme_fops = {
2307         .owner          = THIS_MODULE,
2308         .ioctl          = nvme_ioctl,
2309         .compat_ioctl   = nvme_compat_ioctl,
2310         .open           = nvme_open,
2311         .release        = nvme_release,
2312         .getgeo         = nvme_getgeo,
2313         .revalidate_disk= nvme_revalidate_disk,
2314         .report_zones   = nvme_report_zones,
2315         .pr_ops         = &nvme_pr_ops,
2316 };
2317
2318 #ifdef CONFIG_NVME_MULTIPATH
2319 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
2320 {
2321         struct nvme_ns_head *head = bdev->bd_disk->private_data;
2322
2323         if (!kref_get_unless_zero(&head->ref))
2324                 return -ENXIO;
2325         return 0;
2326 }
2327
2328 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
2329 {
2330         nvme_put_ns_head(disk->private_data);
2331 }
2332
2333 const struct block_device_operations nvme_ns_head_ops = {
2334         .owner          = THIS_MODULE,
2335         .submit_bio     = nvme_ns_head_submit_bio,
2336         .open           = nvme_ns_head_open,
2337         .release        = nvme_ns_head_release,
2338         .ioctl          = nvme_ioctl,
2339         .compat_ioctl   = nvme_compat_ioctl,
2340         .getgeo         = nvme_getgeo,
2341         .report_zones   = nvme_report_zones,
2342         .pr_ops         = &nvme_pr_ops,
2343 };
2344 #endif /* CONFIG_NVME_MULTIPATH */
2345
2346 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2347 {
2348         unsigned long timeout =
2349                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2350         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2351         int ret;
2352
2353         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2354                 if (csts == ~0)
2355                         return -ENODEV;
2356                 if ((csts & NVME_CSTS_RDY) == bit)
2357                         break;
2358
2359                 usleep_range(1000, 2000);
2360                 if (fatal_signal_pending(current))
2361                         return -EINTR;
2362                 if (time_after(jiffies, timeout)) {
2363                         dev_err(ctrl->device,
2364                                 "Device not ready; aborting %s, CSTS=0x%x\n",
2365                                 enabled ? "initialisation" : "reset", csts);
2366                         return -ENODEV;
2367                 }
2368         }
2369
2370         return ret;
2371 }
2372
2373 /*
2374  * If the device has been passed off to us in an enabled state, just clear
2375  * the enabled bit.  The spec says we should set the 'shutdown notification
2376  * bits', but doing so may cause the device to complete commands to the
2377  * admin queue ... and we don't know what memory that might be pointing at!
2378  */
2379 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2380 {
2381         int ret;
2382
2383         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2384         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2385
2386         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2387         if (ret)
2388                 return ret;
2389
2390         if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2391                 msleep(NVME_QUIRK_DELAY_AMOUNT);
2392
2393         return nvme_wait_ready(ctrl, ctrl->cap, false);
2394 }
2395 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2396
2397 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2398 {
2399         unsigned dev_page_min;
2400         int ret;
2401
2402         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2403         if (ret) {
2404                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2405                 return ret;
2406         }
2407         dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2408
2409         if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2410                 dev_err(ctrl->device,
2411                         "Minimum device page size %u too large for host (%u)\n",
2412                         1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2413                 return -ENODEV;
2414         }
2415
2416         if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2417                 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2418         else
2419                 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2420         ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2421         ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2422         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2423         ctrl->ctrl_config |= NVME_CC_ENABLE;
2424
2425         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2426         if (ret)
2427                 return ret;
2428         return nvme_wait_ready(ctrl, ctrl->cap, true);
2429 }
2430 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2431
2432 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2433 {
2434         unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2435         u32 csts;
2436         int ret;
2437
2438         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2439         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2440
2441         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2442         if (ret)
2443                 return ret;
2444
2445         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2446                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2447                         break;
2448
2449                 msleep(100);
2450                 if (fatal_signal_pending(current))
2451                         return -EINTR;
2452                 if (time_after(jiffies, timeout)) {
2453                         dev_err(ctrl->device,
2454                                 "Device shutdown incomplete; abort shutdown\n");
2455                         return -ENODEV;
2456                 }
2457         }
2458
2459         return ret;
2460 }
2461 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2462
2463 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
2464                 struct request_queue *q)
2465 {
2466         bool vwc = false;
2467
2468         if (ctrl->max_hw_sectors) {
2469                 u32 max_segments =
2470                         (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
2471
2472                 max_segments = min_not_zero(max_segments, ctrl->max_segments);
2473                 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
2474                 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
2475         }
2476         blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
2477         blk_queue_dma_alignment(q, 7);
2478         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
2479                 vwc = true;
2480         blk_queue_write_cache(q, vwc, vwc);
2481 }
2482
2483 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2484 {
2485         __le64 ts;
2486         int ret;
2487
2488         if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2489                 return 0;
2490
2491         ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2492         ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2493                         NULL);
2494         if (ret)
2495                 dev_warn_once(ctrl->device,
2496                         "could not set timestamp (%d)\n", ret);
2497         return ret;
2498 }
2499
2500 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2501 {
2502         struct nvme_feat_host_behavior *host;
2503         int ret;
2504
2505         /* Don't bother enabling the feature if retry delay is not reported */
2506         if (!ctrl->crdt[0])
2507                 return 0;
2508
2509         host = kzalloc(sizeof(*host), GFP_KERNEL);
2510         if (!host)
2511                 return 0;
2512
2513         host->acre = NVME_ENABLE_ACRE;
2514         ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2515                                 host, sizeof(*host), NULL);
2516         kfree(host);
2517         return ret;
2518 }
2519
2520 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2521 {
2522         /*
2523          * APST (Autonomous Power State Transition) lets us program a
2524          * table of power state transitions that the controller will
2525          * perform automatically.  We configure it with a simple
2526          * heuristic: we are willing to spend at most 2% of the time
2527          * transitioning between power states.  Therefore, when running
2528          * in any given state, we will enter the next lower-power
2529          * non-operational state after waiting 50 * (enlat + exlat)
2530          * microseconds, as long as that state's exit latency is under
2531          * the requested maximum latency.
2532          *
2533          * We will not autonomously enter any non-operational state for
2534          * which the total latency exceeds ps_max_latency_us.  Users
2535          * can set ps_max_latency_us to zero to turn off APST.
2536          */
2537
2538         unsigned apste;
2539         struct nvme_feat_auto_pst *table;
2540         u64 max_lat_us = 0;
2541         int max_ps = -1;
2542         int ret;
2543
2544         /*
2545          * If APST isn't supported or if we haven't been initialized yet,
2546          * then don't do anything.
2547          */
2548         if (!ctrl->apsta)
2549                 return 0;
2550
2551         if (ctrl->npss > 31) {
2552                 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2553                 return 0;
2554         }
2555
2556         table = kzalloc(sizeof(*table), GFP_KERNEL);
2557         if (!table)
2558                 return 0;
2559
2560         if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2561                 /* Turn off APST. */
2562                 apste = 0;
2563                 dev_dbg(ctrl->device, "APST disabled\n");
2564         } else {
2565                 __le64 target = cpu_to_le64(0);
2566                 int state;
2567
2568                 /*
2569                  * Walk through all states from lowest- to highest-power.
2570                  * According to the spec, lower-numbered states use more
2571                  * power.  NPSS, despite the name, is the index of the
2572                  * lowest-power state, not the number of states.
2573                  */
2574                 for (state = (int)ctrl->npss; state >= 0; state--) {
2575                         u64 total_latency_us, exit_latency_us, transition_ms;
2576
2577                         if (target)
2578                                 table->entries[state] = target;
2579
2580                         /*
2581                          * Don't allow transitions to the deepest state
2582                          * if it's quirked off.
2583                          */
2584                         if (state == ctrl->npss &&
2585                             (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2586                                 continue;
2587
2588                         /*
2589                          * Is this state a useful non-operational state for
2590                          * higher-power states to autonomously transition to?
2591                          */
2592                         if (!(ctrl->psd[state].flags &
2593                               NVME_PS_FLAGS_NON_OP_STATE))
2594                                 continue;
2595
2596                         exit_latency_us =
2597                                 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2598                         if (exit_latency_us > ctrl->ps_max_latency_us)
2599                                 continue;
2600
2601                         total_latency_us =
2602                                 exit_latency_us +
2603                                 le32_to_cpu(ctrl->psd[state].entry_lat);
2604
2605                         /*
2606                          * This state is good.  Use it as the APST idle
2607                          * target for higher power states.
2608                          */
2609                         transition_ms = total_latency_us + 19;
2610                         do_div(transition_ms, 20);
2611                         if (transition_ms > (1 << 24) - 1)
2612                                 transition_ms = (1 << 24) - 1;
2613
2614                         target = cpu_to_le64((state << 3) |
2615                                              (transition_ms << 8));
2616
2617                         if (max_ps == -1)
2618                                 max_ps = state;
2619
2620                         if (total_latency_us > max_lat_us)
2621                                 max_lat_us = total_latency_us;
2622                 }
2623
2624                 apste = 1;
2625
2626                 if (max_ps == -1) {
2627                         dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2628                 } else {
2629                         dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2630                                 max_ps, max_lat_us, (int)sizeof(*table), table);
2631                 }
2632         }
2633
2634         ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2635                                 table, sizeof(*table), NULL);
2636         if (ret)
2637                 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2638
2639         kfree(table);
2640         return ret;
2641 }
2642
2643 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2644 {
2645         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2646         u64 latency;
2647
2648         switch (val) {
2649         case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2650         case PM_QOS_LATENCY_ANY:
2651                 latency = U64_MAX;
2652                 break;
2653
2654         default:
2655                 latency = val;
2656         }
2657
2658         if (ctrl->ps_max_latency_us != latency) {
2659                 ctrl->ps_max_latency_us = latency;
2660                 nvme_configure_apst(ctrl);
2661         }
2662 }
2663
2664 struct nvme_core_quirk_entry {
2665         /*
2666          * NVMe model and firmware strings are padded with spaces.  For
2667          * simplicity, strings in the quirk table are padded with NULLs
2668          * instead.
2669          */
2670         u16 vid;
2671         const char *mn;
2672         const char *fr;
2673         unsigned long quirks;
2674 };
2675
2676 static const struct nvme_core_quirk_entry core_quirks[] = {
2677         {
2678                 /*
2679                  * This Toshiba device seems to die using any APST states.  See:
2680                  * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2681                  */
2682                 .vid = 0x1179,
2683                 .mn = "THNSF5256GPUK TOSHIBA",
2684                 .quirks = NVME_QUIRK_NO_APST,
2685         },
2686         {
2687                 /*
2688                  * This LiteON CL1-3D*-Q11 firmware version has a race
2689                  * condition associated with actions related to suspend to idle
2690                  * LiteON has resolved the problem in future firmware
2691                  */
2692                 .vid = 0x14a4,
2693                 .fr = "22301111",
2694                 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2695         }
2696 };
2697
2698 /* match is null-terminated but idstr is space-padded. */
2699 static bool string_matches(const char *idstr, const char *match, size_t len)
2700 {
2701         size_t matchlen;
2702
2703         if (!match)
2704                 return true;
2705
2706         matchlen = strlen(match);
2707         WARN_ON_ONCE(matchlen > len);
2708
2709         if (memcmp(idstr, match, matchlen))
2710                 return false;
2711
2712         for (; matchlen < len; matchlen++)
2713                 if (idstr[matchlen] != ' ')
2714                         return false;
2715
2716         return true;
2717 }
2718
2719 static bool quirk_matches(const struct nvme_id_ctrl *id,
2720                           const struct nvme_core_quirk_entry *q)
2721 {
2722         return q->vid == le16_to_cpu(id->vid) &&
2723                 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2724                 string_matches(id->fr, q->fr, sizeof(id->fr));
2725 }
2726
2727 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2728                 struct nvme_id_ctrl *id)
2729 {
2730         size_t nqnlen;
2731         int off;
2732
2733         if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2734                 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2735                 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2736                         strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2737                         return;
2738                 }
2739
2740                 if (ctrl->vs >= NVME_VS(1, 2, 1))
2741                         dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2742         }
2743
2744         /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2745         off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2746                         "nqn.2014.08.org.nvmexpress:%04x%04x",
2747                         le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2748         memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2749         off += sizeof(id->sn);
2750         memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2751         off += sizeof(id->mn);
2752         memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2753 }
2754
2755 static void nvme_release_subsystem(struct device *dev)
2756 {
2757         struct nvme_subsystem *subsys =
2758                 container_of(dev, struct nvme_subsystem, dev);
2759
2760         if (subsys->instance >= 0)
2761                 ida_simple_remove(&nvme_instance_ida, subsys->instance);
2762         kfree(subsys);
2763 }
2764
2765 static void nvme_destroy_subsystem(struct kref *ref)
2766 {
2767         struct nvme_subsystem *subsys =
2768                         container_of(ref, struct nvme_subsystem, ref);
2769
2770         mutex_lock(&nvme_subsystems_lock);
2771         list_del(&subsys->entry);
2772         mutex_unlock(&nvme_subsystems_lock);
2773
2774         ida_destroy(&subsys->ns_ida);
2775         device_del(&subsys->dev);
2776         put_device(&subsys->dev);
2777 }
2778
2779 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2780 {
2781         kref_put(&subsys->ref, nvme_destroy_subsystem);
2782 }
2783
2784 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2785 {
2786         struct nvme_subsystem *subsys;
2787
2788         lockdep_assert_held(&nvme_subsystems_lock);
2789
2790         /*
2791          * Fail matches for discovery subsystems. This results
2792          * in each discovery controller bound to a unique subsystem.
2793          * This avoids issues with validating controller values
2794          * that can only be true when there is a single unique subsystem.
2795          * There may be multiple and completely independent entities
2796          * that provide discovery controllers.
2797          */
2798         if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2799                 return NULL;
2800
2801         list_for_each_entry(subsys, &nvme_subsystems, entry) {
2802                 if (strcmp(subsys->subnqn, subsysnqn))
2803                         continue;
2804                 if (!kref_get_unless_zero(&subsys->ref))
2805                         continue;
2806                 return subsys;
2807         }
2808
2809         return NULL;
2810 }
2811
2812 #define SUBSYS_ATTR_RO(_name, _mode, _show)                     \
2813         struct device_attribute subsys_attr_##_name = \
2814                 __ATTR(_name, _mode, _show, NULL)
2815
2816 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2817                                     struct device_attribute *attr,
2818                                     char *buf)
2819 {
2820         struct nvme_subsystem *subsys =
2821                 container_of(dev, struct nvme_subsystem, dev);
2822
2823         return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2824 }
2825 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2826
2827 #define nvme_subsys_show_str_function(field)                            \
2828 static ssize_t subsys_##field##_show(struct device *dev,                \
2829                             struct device_attribute *attr, char *buf)   \
2830 {                                                                       \
2831         struct nvme_subsystem *subsys =                                 \
2832                 container_of(dev, struct nvme_subsystem, dev);          \
2833         return sprintf(buf, "%.*s\n",                                   \
2834                        (int)sizeof(subsys->field), subsys->field);      \
2835 }                                                                       \
2836 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2837
2838 nvme_subsys_show_str_function(model);
2839 nvme_subsys_show_str_function(serial);
2840 nvme_subsys_show_str_function(firmware_rev);
2841
2842 static struct attribute *nvme_subsys_attrs[] = {
2843         &subsys_attr_model.attr,
2844         &subsys_attr_serial.attr,
2845         &subsys_attr_firmware_rev.attr,
2846         &subsys_attr_subsysnqn.attr,
2847 #ifdef CONFIG_NVME_MULTIPATH
2848         &subsys_attr_iopolicy.attr,
2849 #endif
2850         NULL,
2851 };
2852
2853 static struct attribute_group nvme_subsys_attrs_group = {
2854         .attrs = nvme_subsys_attrs,
2855 };
2856
2857 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2858         &nvme_subsys_attrs_group,
2859         NULL,
2860 };
2861
2862 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2863                 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2864 {
2865         struct nvme_ctrl *tmp;
2866
2867         lockdep_assert_held(&nvme_subsystems_lock);
2868
2869         list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2870                 if (nvme_state_terminal(tmp))
2871                         continue;
2872
2873                 if (tmp->cntlid == ctrl->cntlid) {
2874                         dev_err(ctrl->device,
2875                                 "Duplicate cntlid %u with %s, rejecting\n",
2876                                 ctrl->cntlid, dev_name(tmp->device));
2877                         return false;
2878                 }
2879
2880                 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2881                     (ctrl->opts && ctrl->opts->discovery_nqn))
2882                         continue;
2883
2884                 dev_err(ctrl->device,
2885                         "Subsystem does not support multiple controllers\n");
2886                 return false;
2887         }
2888
2889         return true;
2890 }
2891
2892 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2893 {
2894         struct nvme_subsystem *subsys, *found;
2895         int ret;
2896
2897         subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2898         if (!subsys)
2899                 return -ENOMEM;
2900
2901         subsys->instance = -1;
2902         mutex_init(&subsys->lock);
2903         kref_init(&subsys->ref);
2904         INIT_LIST_HEAD(&subsys->ctrls);
2905         INIT_LIST_HEAD(&subsys->nsheads);
2906         nvme_init_subnqn(subsys, ctrl, id);
2907         memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2908         memcpy(subsys->model, id->mn, sizeof(subsys->model));
2909         memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2910         subsys->vendor_id = le16_to_cpu(id->vid);
2911         subsys->cmic = id->cmic;
2912         subsys->awupf = le16_to_cpu(id->awupf);
2913 #ifdef CONFIG_NVME_MULTIPATH
2914         subsys->iopolicy = NVME_IOPOLICY_NUMA;
2915 #endif
2916
2917         subsys->dev.class = nvme_subsys_class;
2918         subsys->dev.release = nvme_release_subsystem;
2919         subsys->dev.groups = nvme_subsys_attrs_groups;
2920         dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2921         device_initialize(&subsys->dev);
2922
2923         mutex_lock(&nvme_subsystems_lock);
2924         found = __nvme_find_get_subsystem(subsys->subnqn);
2925         if (found) {
2926                 put_device(&subsys->dev);
2927                 subsys = found;
2928
2929                 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2930                         ret = -EINVAL;
2931                         goto out_put_subsystem;
2932                 }
2933         } else {
2934                 ret = device_add(&subsys->dev);
2935                 if (ret) {
2936                         dev_err(ctrl->device,
2937                                 "failed to register subsystem device.\n");
2938                         put_device(&subsys->dev);
2939                         goto out_unlock;
2940                 }
2941                 ida_init(&subsys->ns_ida);
2942                 list_add_tail(&subsys->entry, &nvme_subsystems);
2943         }
2944
2945         ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2946                                 dev_name(ctrl->device));
2947         if (ret) {
2948                 dev_err(ctrl->device,
2949                         "failed to create sysfs link from subsystem.\n");
2950                 goto out_put_subsystem;
2951         }
2952
2953         if (!found)
2954                 subsys->instance = ctrl->instance;
2955         ctrl->subsys = subsys;
2956         list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2957         mutex_unlock(&nvme_subsystems_lock);
2958         return 0;
2959
2960 out_put_subsystem:
2961         nvme_put_subsystem(subsys);
2962 out_unlock:
2963         mutex_unlock(&nvme_subsystems_lock);
2964         return ret;
2965 }
2966
2967 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2968                 void *log, size_t size, u64 offset)
2969 {
2970         struct nvme_command c = { };
2971         u32 dwlen = nvme_bytes_to_numd(size);
2972
2973         c.get_log_page.opcode = nvme_admin_get_log_page;
2974         c.get_log_page.nsid = cpu_to_le32(nsid);
2975         c.get_log_page.lid = log_page;
2976         c.get_log_page.lsp = lsp;
2977         c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2978         c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2979         c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2980         c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2981         c.get_log_page.csi = csi;
2982
2983         return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2984 }
2985
2986 static struct nvme_cel *nvme_find_cel(struct nvme_ctrl *ctrl, u8 csi)
2987 {
2988         struct nvme_cel *cel, *ret = NULL;
2989
2990         spin_lock_irq(&ctrl->lock);
2991         list_for_each_entry(cel, &ctrl->cels, entry) {
2992                 if (cel->csi == csi) {
2993                         ret = cel;
2994                         break;
2995                 }
2996         }
2997         spin_unlock_irq(&ctrl->lock);
2998
2999         return ret;
3000 }
3001
3002 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
3003                                 struct nvme_effects_log **log)
3004 {
3005         struct nvme_cel *cel = nvme_find_cel(ctrl, csi);
3006         int ret;
3007
3008         if (cel)
3009                 goto out;
3010
3011         cel = kzalloc(sizeof(*cel), GFP_KERNEL);
3012         if (!cel)
3013                 return -ENOMEM;
3014
3015         ret = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CMD_EFFECTS, 0, csi,
3016                         &cel->log, sizeof(cel->log), 0);
3017         if (ret) {
3018                 kfree(cel);
3019                 return ret;
3020         }
3021
3022         cel->csi = csi;
3023
3024         spin_lock_irq(&ctrl->lock);
3025         list_add_tail(&cel->entry, &ctrl->cels);
3026         spin_unlock_irq(&ctrl->lock);
3027 out:
3028         *log = &cel->log;
3029         return 0;
3030 }
3031
3032 /*
3033  * Initialize the cached copies of the Identify data and various controller
3034  * register in our nvme_ctrl structure.  This should be called as soon as
3035  * the admin queue is fully up and running.
3036  */
3037 int nvme_init_identify(struct nvme_ctrl *ctrl)
3038 {
3039         struct nvme_id_ctrl *id;
3040         int ret, page_shift;
3041         u32 max_hw_sectors;
3042         bool prev_apst_enabled;
3043
3044         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3045         if (ret) {
3046                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3047                 return ret;
3048         }
3049         page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12;
3050         ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3051
3052         if (ctrl->vs >= NVME_VS(1, 1, 0))
3053                 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3054
3055         ret = nvme_identify_ctrl(ctrl, &id);
3056         if (ret) {
3057                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
3058                 return -EIO;
3059         }
3060
3061         if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
3062                 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3063                 if (ret < 0)
3064                         goto out_free;
3065         }
3066
3067         if (!(ctrl->ops->flags & NVME_F_FABRICS))
3068                 ctrl->cntlid = le16_to_cpu(id->cntlid);
3069
3070         if (!ctrl->identified) {
3071                 int i;
3072
3073                 ret = nvme_init_subsystem(ctrl, id);
3074                 if (ret)
3075                         goto out_free;
3076
3077                 /*
3078                  * Check for quirks.  Quirk can depend on firmware version,
3079                  * so, in principle, the set of quirks present can change
3080                  * across a reset.  As a possible future enhancement, we
3081                  * could re-scan for quirks every time we reinitialize
3082                  * the device, but we'd have to make sure that the driver
3083                  * behaves intelligently if the quirks change.
3084                  */
3085                 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
3086                         if (quirk_matches(id, &core_quirks[i]))
3087                                 ctrl->quirks |= core_quirks[i].quirks;
3088                 }
3089         }
3090
3091         if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
3092                 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
3093                 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
3094         }
3095
3096         ctrl->crdt[0] = le16_to_cpu(id->crdt1);
3097         ctrl->crdt[1] = le16_to_cpu(id->crdt2);
3098         ctrl->crdt[2] = le16_to_cpu(id->crdt3);
3099
3100         ctrl->oacs = le16_to_cpu(id->oacs);
3101         ctrl->oncs = le16_to_cpu(id->oncs);
3102         ctrl->mtfa = le16_to_cpu(id->mtfa);
3103         ctrl->oaes = le32_to_cpu(id->oaes);
3104         ctrl->wctemp = le16_to_cpu(id->wctemp);
3105         ctrl->cctemp = le16_to_cpu(id->cctemp);
3106
3107         atomic_set(&ctrl->abort_limit, id->acl + 1);
3108         ctrl->vwc = id->vwc;
3109         if (id->mdts)
3110                 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
3111         else
3112                 max_hw_sectors = UINT_MAX;
3113         ctrl->max_hw_sectors =
3114                 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
3115
3116         nvme_set_queue_limits(ctrl, ctrl->admin_q);
3117         ctrl->sgls = le32_to_cpu(id->sgls);
3118         ctrl->kas = le16_to_cpu(id->kas);
3119         ctrl->max_namespaces = le32_to_cpu(id->mnan);
3120         ctrl->ctratt = le32_to_cpu(id->ctratt);
3121
3122         if (id->rtd3e) {
3123                 /* us -> s */
3124                 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
3125
3126                 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
3127                                                  shutdown_timeout, 60);
3128
3129                 if (ctrl->shutdown_timeout != shutdown_timeout)
3130                         dev_info(ctrl->device,
3131                                  "Shutdown timeout set to %u seconds\n",
3132                                  ctrl->shutdown_timeout);
3133         } else
3134                 ctrl->shutdown_timeout = shutdown_timeout;
3135
3136         ctrl->npss = id->npss;
3137         ctrl->apsta = id->apsta;
3138         prev_apst_enabled = ctrl->apst_enabled;
3139         if (ctrl->quirks & NVME_QUIRK_NO_APST) {
3140                 if (force_apst && id->apsta) {
3141                         dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
3142                         ctrl->apst_enabled = true;
3143                 } else {
3144                         ctrl->apst_enabled = false;
3145                 }
3146         } else {
3147                 ctrl->apst_enabled = id->apsta;
3148         }
3149         memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
3150
3151         if (ctrl->ops->flags & NVME_F_FABRICS) {
3152                 ctrl->icdoff = le16_to_cpu(id->icdoff);
3153                 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
3154                 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
3155                 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
3156
3157                 /*
3158                  * In fabrics we need to verify the cntlid matches the
3159                  * admin connect
3160                  */
3161                 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
3162                         dev_err(ctrl->device,
3163                                 "Mismatching cntlid: Connect %u vs Identify "
3164                                 "%u, rejecting\n",
3165                                 ctrl->cntlid, le16_to_cpu(id->cntlid));
3166                         ret = -EINVAL;
3167                         goto out_free;
3168                 }
3169
3170                 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
3171                         dev_err(ctrl->device,
3172                                 "keep-alive support is mandatory for fabrics\n");
3173                         ret = -EINVAL;
3174                         goto out_free;
3175                 }
3176         } else {
3177                 ctrl->hmpre = le32_to_cpu(id->hmpre);
3178                 ctrl->hmmin = le32_to_cpu(id->hmmin);
3179                 ctrl->hmminds = le32_to_cpu(id->hmminds);
3180                 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
3181         }
3182
3183         ret = nvme_mpath_init(ctrl, id);
3184         kfree(id);
3185
3186         if (ret < 0)
3187                 return ret;
3188
3189         if (ctrl->apst_enabled && !prev_apst_enabled)
3190                 dev_pm_qos_expose_latency_tolerance(ctrl->device);
3191         else if (!ctrl->apst_enabled && prev_apst_enabled)
3192                 dev_pm_qos_hide_latency_tolerance(ctrl->device);
3193
3194         ret = nvme_configure_apst(ctrl);
3195         if (ret < 0)
3196                 return ret;
3197         
3198         ret = nvme_configure_timestamp(ctrl);
3199         if (ret < 0)
3200                 return ret;
3201
3202         ret = nvme_configure_directives(ctrl);
3203         if (ret < 0)
3204                 return ret;
3205
3206         ret = nvme_configure_acre(ctrl);
3207         if (ret < 0)
3208                 return ret;
3209
3210         if (!ctrl->identified)
3211                 nvme_hwmon_init(ctrl);
3212
3213         ctrl->identified = true;
3214
3215         return 0;
3216
3217 out_free:
3218         kfree(id);
3219         return ret;
3220 }
3221 EXPORT_SYMBOL_GPL(nvme_init_identify);
3222
3223 static int nvme_dev_open(struct inode *inode, struct file *file)
3224 {
3225         struct nvme_ctrl *ctrl =
3226                 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3227
3228         switch (ctrl->state) {
3229         case NVME_CTRL_LIVE:
3230                 break;
3231         default:
3232                 return -EWOULDBLOCK;
3233         }
3234
3235         file->private_data = ctrl;
3236         return 0;
3237 }
3238
3239 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
3240 {
3241         struct nvme_ns *ns;
3242         int ret;
3243
3244         down_read(&ctrl->namespaces_rwsem);
3245         if (list_empty(&ctrl->namespaces)) {
3246                 ret = -ENOTTY;
3247                 goto out_unlock;
3248         }
3249
3250         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
3251         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
3252                 dev_warn(ctrl->device,
3253                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
3254                 ret = -EINVAL;
3255                 goto out_unlock;
3256         }
3257
3258         dev_warn(ctrl->device,
3259                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
3260         kref_get(&ns->kref);
3261         up_read(&ctrl->namespaces_rwsem);
3262
3263         ret = nvme_user_cmd(ctrl, ns, argp);
3264         nvme_put_ns(ns);
3265         return ret;
3266
3267 out_unlock:
3268         up_read(&ctrl->namespaces_rwsem);
3269         return ret;
3270 }
3271
3272 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
3273                 unsigned long arg)
3274 {
3275         struct nvme_ctrl *ctrl = file->private_data;
3276         void __user *argp = (void __user *)arg;
3277
3278         switch (cmd) {
3279         case NVME_IOCTL_ADMIN_CMD:
3280                 return nvme_user_cmd(ctrl, NULL, argp);
3281         case NVME_IOCTL_ADMIN64_CMD:
3282                 return nvme_user_cmd64(ctrl, NULL, argp);
3283         case NVME_IOCTL_IO_CMD:
3284                 return nvme_dev_user_cmd(ctrl, argp);
3285         case NVME_IOCTL_RESET:
3286                 dev_warn(ctrl->device, "resetting controller\n");
3287                 return nvme_reset_ctrl_sync(ctrl);
3288         case NVME_IOCTL_SUBSYS_RESET:
3289                 return nvme_reset_subsystem(ctrl);
3290         case NVME_IOCTL_RESCAN:
3291                 nvme_queue_scan(ctrl);
3292                 return 0;
3293         default:
3294                 return -ENOTTY;
3295         }
3296 }
3297
3298 static const struct file_operations nvme_dev_fops = {
3299         .owner          = THIS_MODULE,
3300         .open           = nvme_dev_open,
3301         .unlocked_ioctl = nvme_dev_ioctl,
3302         .compat_ioctl   = compat_ptr_ioctl,
3303 };
3304
3305 static ssize_t nvme_sysfs_reset(struct device *dev,
3306                                 struct device_attribute *attr, const char *buf,
3307                                 size_t count)
3308 {
3309         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3310         int ret;
3311
3312         ret = nvme_reset_ctrl_sync(ctrl);
3313         if (ret < 0)
3314                 return ret;
3315         return count;
3316 }
3317 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3318
3319 static ssize_t nvme_sysfs_rescan(struct device *dev,
3320                                 struct device_attribute *attr, const char *buf,
3321                                 size_t count)
3322 {
3323         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3324
3325         nvme_queue_scan(ctrl);
3326         return count;
3327 }
3328 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
3329
3330 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
3331 {
3332         struct gendisk *disk = dev_to_disk(dev);
3333
3334         if (disk->fops == &nvme_fops)
3335                 return nvme_get_ns_from_dev(dev)->head;
3336         else
3337                 return disk->private_data;
3338 }
3339
3340 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
3341                 char *buf)
3342 {
3343         struct nvme_ns_head *head = dev_to_ns_head(dev);
3344         struct nvme_ns_ids *ids = &head->ids;
3345         struct nvme_subsystem *subsys = head->subsys;
3346         int serial_len = sizeof(subsys->serial);
3347         int model_len = sizeof(subsys->model);
3348
3349         if (!uuid_is_null(&ids->uuid))
3350                 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
3351
3352         if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3353                 return sprintf(buf, "eui.%16phN\n", ids->nguid);
3354
3355         if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3356                 return sprintf(buf, "eui.%8phN\n", ids->eui64);
3357
3358         while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3359                                   subsys->serial[serial_len - 1] == '\0'))
3360                 serial_len--;
3361         while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3362                                  subsys->model[model_len - 1] == '\0'))
3363                 model_len--;
3364
3365         return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3366                 serial_len, subsys->serial, model_len, subsys->model,
3367                 head->ns_id);
3368 }
3369 static DEVICE_ATTR_RO(wwid);
3370
3371 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3372                 char *buf)
3373 {
3374         return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3375 }
3376 static DEVICE_ATTR_RO(nguid);
3377
3378 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3379                 char *buf)
3380 {
3381         struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3382
3383         /* For backward compatibility expose the NGUID to userspace if
3384          * we have no UUID set
3385          */
3386         if (uuid_is_null(&ids->uuid)) {
3387                 printk_ratelimited(KERN_WARNING
3388                                    "No UUID available providing old NGUID\n");
3389                 return sprintf(buf, "%pU\n", ids->nguid);
3390         }
3391         return sprintf(buf, "%pU\n", &ids->uuid);
3392 }
3393 static DEVICE_ATTR_RO(uuid);
3394
3395 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3396                 char *buf)
3397 {
3398         return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3399 }
3400 static DEVICE_ATTR_RO(eui);
3401
3402 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3403                 char *buf)
3404 {
3405         return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3406 }
3407 static DEVICE_ATTR_RO(nsid);
3408
3409 static struct attribute *nvme_ns_id_attrs[] = {
3410         &dev_attr_wwid.attr,
3411         &dev_attr_uuid.attr,
3412         &dev_attr_nguid.attr,
3413         &dev_attr_eui.attr,
3414         &dev_attr_nsid.attr,
3415 #ifdef CONFIG_NVME_MULTIPATH
3416         &dev_attr_ana_grpid.attr,
3417         &dev_attr_ana_state.attr,
3418 #endif
3419         NULL,
3420 };
3421
3422 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3423                 struct attribute *a, int n)
3424 {
3425         struct device *dev = container_of(kobj, struct device, kobj);
3426         struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3427
3428         if (a == &dev_attr_uuid.attr) {
3429                 if (uuid_is_null(&ids->uuid) &&
3430                     !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3431                         return 0;
3432         }
3433         if (a == &dev_attr_nguid.attr) {
3434                 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3435                         return 0;
3436         }
3437         if (a == &dev_attr_eui.attr) {
3438                 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3439                         return 0;
3440         }
3441 #ifdef CONFIG_NVME_MULTIPATH
3442         if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3443                 if (dev_to_disk(dev)->fops != &nvme_fops) /* per-path attr */
3444                         return 0;
3445                 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3446                         return 0;
3447         }
3448 #endif
3449         return a->mode;
3450 }
3451
3452 static const struct attribute_group nvme_ns_id_attr_group = {
3453         .attrs          = nvme_ns_id_attrs,
3454         .is_visible     = nvme_ns_id_attrs_are_visible,
3455 };
3456
3457 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3458         &nvme_ns_id_attr_group,
3459 #ifdef CONFIG_NVM
3460         &nvme_nvm_attr_group,
3461 #endif
3462         NULL,
3463 };
3464
3465 #define nvme_show_str_function(field)                                           \
3466 static ssize_t  field##_show(struct device *dev,                                \
3467                             struct device_attribute *attr, char *buf)           \
3468 {                                                                               \
3469         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
3470         return sprintf(buf, "%.*s\n",                                           \
3471                 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field);         \
3472 }                                                                               \
3473 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3474
3475 nvme_show_str_function(model);
3476 nvme_show_str_function(serial);
3477 nvme_show_str_function(firmware_rev);
3478
3479 #define nvme_show_int_function(field)                                           \
3480 static ssize_t  field##_show(struct device *dev,                                \
3481                             struct device_attribute *attr, char *buf)           \
3482 {                                                                               \
3483         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
3484         return sprintf(buf, "%d\n", ctrl->field);       \
3485 }                                                                               \
3486 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3487
3488 nvme_show_int_function(cntlid);
3489 nvme_show_int_function(numa_node);
3490 nvme_show_int_function(queue_count);
3491 nvme_show_int_function(sqsize);
3492
3493 static ssize_t nvme_sysfs_delete(struct device *dev,
3494                                 struct device_attribute *attr, const char *buf,
3495                                 size_t count)
3496 {
3497         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3498
3499         /* Can't delete non-created controllers */
3500         if (!ctrl->created)
3501                 return -EBUSY;
3502
3503         if (device_remove_file_self(dev, attr))
3504                 nvme_delete_ctrl_sync(ctrl);
3505         return count;
3506 }
3507 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3508
3509 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3510                                          struct device_attribute *attr,
3511                                          char *buf)
3512 {
3513         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3514
3515         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
3516 }
3517 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3518
3519 static ssize_t nvme_sysfs_show_state(struct device *dev,
3520                                      struct device_attribute *attr,
3521                                      char *buf)
3522 {
3523         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3524         static const char *const state_name[] = {
3525                 [NVME_CTRL_NEW]         = "new",
3526                 [NVME_CTRL_LIVE]        = "live",
3527                 [NVME_CTRL_RESETTING]   = "resetting",
3528                 [NVME_CTRL_CONNECTING]  = "connecting",
3529                 [NVME_CTRL_DELETING]    = "deleting",
3530                 [NVME_CTRL_DELETING_NOIO]= "deleting (no IO)",
3531                 [NVME_CTRL_DEAD]        = "dead",
3532         };
3533
3534         if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3535             state_name[ctrl->state])
3536                 return sprintf(buf, "%s\n", state_name[ctrl->state]);
3537
3538         return sprintf(buf, "unknown state\n");
3539 }
3540
3541 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3542
3543 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3544                                          struct device_attribute *attr,
3545                                          char *buf)
3546 {
3547         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3548
3549         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
3550 }
3551 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3552
3553 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3554                                         struct device_attribute *attr,
3555                                         char *buf)
3556 {
3557         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3558
3559         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->opts->host->nqn);
3560 }
3561 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3562
3563 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3564                                         struct device_attribute *attr,
3565                                         char *buf)
3566 {
3567         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3568
3569         return snprintf(buf, PAGE_SIZE, "%pU\n", &ctrl->opts->host->id);
3570 }
3571 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3572
3573 static ssize_t nvme_sysfs_show_address(struct device *dev,
3574                                          struct device_attribute *attr,
3575                                          char *buf)
3576 {
3577         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3578
3579         return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3580 }
3581 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3582
3583 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev,
3584                 struct device_attribute *attr, char *buf)
3585 {
3586         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3587         struct nvmf_ctrl_options *opts = ctrl->opts;
3588
3589         if (ctrl->opts->max_reconnects == -1)
3590                 return sprintf(buf, "off\n");
3591         return sprintf(buf, "%d\n",
3592                         opts->max_reconnects * opts->reconnect_delay);
3593 }
3594
3595 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev,
3596                 struct device_attribute *attr, const char *buf, size_t count)
3597 {
3598         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3599         struct nvmf_ctrl_options *opts = ctrl->opts;
3600         int ctrl_loss_tmo, err;
3601
3602         err = kstrtoint(buf, 10, &ctrl_loss_tmo);
3603         if (err)
3604                 return -EINVAL;
3605
3606         else if (ctrl_loss_tmo < 0)
3607                 opts->max_reconnects = -1;
3608         else
3609                 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
3610                                                 opts->reconnect_delay);
3611         return count;
3612 }
3613 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR,
3614         nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store);
3615
3616 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev,
3617                 struct device_attribute *attr, char *buf)
3618 {
3619         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3620
3621         if (ctrl->opts->reconnect_delay == -1)
3622                 return sprintf(buf, "off\n");
3623         return sprintf(buf, "%d\n", ctrl->opts->reconnect_delay);
3624 }
3625
3626 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev,
3627                 struct device_attribute *attr, const char *buf, size_t count)
3628 {
3629         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3630         unsigned int v;
3631         int err;
3632
3633         err = kstrtou32(buf, 10, &v);
3634         if (err)
3635                 return err;
3636
3637         ctrl->opts->reconnect_delay = v;
3638         return count;
3639 }
3640 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR,
3641         nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store);
3642
3643 static struct attribute *nvme_dev_attrs[] = {
3644         &dev_attr_reset_controller.attr,
3645         &dev_attr_rescan_controller.attr,
3646         &dev_attr_model.attr,
3647         &dev_attr_serial.attr,
3648         &dev_attr_firmware_rev.attr,
3649         &dev_attr_cntlid.attr,
3650         &dev_attr_delete_controller.attr,
3651         &dev_attr_transport.attr,
3652         &dev_attr_subsysnqn.attr,
3653         &dev_attr_address.attr,
3654         &dev_attr_state.attr,
3655         &dev_attr_numa_node.attr,
3656         &dev_attr_queue_count.attr,
3657         &dev_attr_sqsize.attr,
3658         &dev_attr_hostnqn.attr,
3659         &dev_attr_hostid.attr,
3660         &dev_attr_ctrl_loss_tmo.attr,
3661         &dev_attr_reconnect_delay.attr,
3662         NULL
3663 };
3664
3665 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3666                 struct attribute *a, int n)
3667 {
3668         struct device *dev = container_of(kobj, struct device, kobj);
3669         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3670
3671         if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3672                 return 0;
3673         if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3674                 return 0;
3675         if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3676                 return 0;
3677         if (a == &dev_attr_hostid.attr && !ctrl->opts)
3678                 return 0;
3679         if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts)
3680                 return 0;
3681         if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts)
3682                 return 0;
3683
3684         return a->mode;
3685 }
3686
3687 static struct attribute_group nvme_dev_attrs_group = {
3688         .attrs          = nvme_dev_attrs,
3689         .is_visible     = nvme_dev_attrs_are_visible,
3690 };
3691
3692 static const struct attribute_group *nvme_dev_attr_groups[] = {
3693         &nvme_dev_attrs_group,
3694         NULL,
3695 };
3696
3697 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3698                 unsigned nsid)
3699 {
3700         struct nvme_ns_head *h;
3701
3702         lockdep_assert_held(&subsys->lock);
3703
3704         list_for_each_entry(h, &subsys->nsheads, entry) {
3705                 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
3706                         return h;
3707         }
3708
3709         return NULL;
3710 }
3711
3712 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3713                 struct nvme_ns_head *new)
3714 {
3715         struct nvme_ns_head *h;
3716
3717         lockdep_assert_held(&subsys->lock);
3718
3719         list_for_each_entry(h, &subsys->nsheads, entry) {
3720                 if (nvme_ns_ids_valid(&new->ids) &&
3721                     nvme_ns_ids_equal(&new->ids, &h->ids))
3722                         return -EINVAL;
3723         }
3724
3725         return 0;
3726 }
3727
3728 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3729                 unsigned nsid, struct nvme_ns_ids *ids)
3730 {
3731         struct nvme_ns_head *head;
3732         size_t size = sizeof(*head);
3733         int ret = -ENOMEM;
3734
3735 #ifdef CONFIG_NVME_MULTIPATH
3736         size += num_possible_nodes() * sizeof(struct nvme_ns *);
3737 #endif
3738
3739         head = kzalloc(size, GFP_KERNEL);
3740         if (!head)
3741                 goto out;
3742         ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3743         if (ret < 0)
3744                 goto out_free_head;
3745         head->instance = ret;
3746         INIT_LIST_HEAD(&head->list);
3747         ret = init_srcu_struct(&head->srcu);
3748         if (ret)
3749                 goto out_ida_remove;
3750         head->subsys = ctrl->subsys;
3751         head->ns_id = nsid;
3752         head->ids = *ids;
3753         kref_init(&head->ref);
3754
3755         ret = __nvme_check_ids(ctrl->subsys, head);
3756         if (ret) {
3757                 dev_err(ctrl->device,
3758                         "duplicate IDs for nsid %d\n", nsid);
3759                 goto out_cleanup_srcu;
3760         }
3761
3762         if (head->ids.csi) {
3763                 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3764                 if (ret)
3765                         goto out_cleanup_srcu;
3766         } else
3767                 head->effects = ctrl->effects;
3768
3769         ret = nvme_mpath_alloc_disk(ctrl, head);
3770         if (ret)
3771                 goto out_cleanup_srcu;
3772
3773         list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3774
3775         kref_get(&ctrl->subsys->ref);
3776
3777         return head;
3778 out_cleanup_srcu:
3779         cleanup_srcu_struct(&head->srcu);
3780 out_ida_remove:
3781         ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3782 out_free_head:
3783         kfree(head);
3784 out:
3785         if (ret > 0)
3786                 ret = blk_status_to_errno(nvme_error_status(ret));
3787         return ERR_PTR(ret);
3788 }
3789
3790 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3791                 struct nvme_id_ns *id)
3792 {
3793         struct nvme_ctrl *ctrl = ns->ctrl;
3794         bool is_shared = id->nmic & NVME_NS_NMIC_SHARED;
3795         struct nvme_ns_head *head = NULL;
3796         struct nvme_ns_ids ids;
3797         int ret = 0;
3798
3799         ret = nvme_report_ns_ids(ctrl, nsid, id, &ids);
3800         if (ret) {
3801                 if (ret < 0)
3802                         return ret;
3803                 return blk_status_to_errno(nvme_error_status(ret));
3804         }
3805
3806         mutex_lock(&ctrl->subsys->lock);
3807         head = nvme_find_ns_head(ctrl->subsys, nsid);
3808         if (!head) {
3809                 head = nvme_alloc_ns_head(ctrl, nsid, &ids);
3810                 if (IS_ERR(head)) {
3811                         ret = PTR_ERR(head);
3812                         goto out_unlock;
3813                 }
3814                 head->shared = is_shared;
3815         } else {
3816                 ret = -EINVAL;
3817                 if (!is_shared || !head->shared) {
3818                         dev_err(ctrl->device,
3819                                 "Duplicate unshared namespace %d\n", nsid);
3820                         goto out_put_ns_head;
3821                 }
3822                 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
3823                         dev_err(ctrl->device,
3824                                 "IDs don't match for shared namespace %d\n",
3825                                         nsid);
3826                         goto out_put_ns_head;
3827                 }
3828         }
3829
3830         list_add_tail(&ns->siblings, &head->list);
3831         ns->head = head;
3832         mutex_unlock(&ctrl->subsys->lock);
3833         return 0;
3834
3835 out_put_ns_head:
3836         nvme_put_ns_head(head);
3837 out_unlock:
3838         mutex_unlock(&ctrl->subsys->lock);
3839         return ret;
3840 }
3841
3842 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
3843 {
3844         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3845         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3846
3847         return nsa->head->ns_id - nsb->head->ns_id;
3848 }
3849
3850 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3851 {
3852         struct nvme_ns *ns, *ret = NULL;
3853
3854         down_read(&ctrl->namespaces_rwsem);
3855         list_for_each_entry(ns, &ctrl->namespaces, list) {
3856                 if (ns->head->ns_id == nsid) {
3857                         if (!kref_get_unless_zero(&ns->kref))
3858                                 continue;
3859                         ret = ns;
3860                         break;
3861                 }
3862                 if (ns->head->ns_id > nsid)
3863                         break;
3864         }
3865         up_read(&ctrl->namespaces_rwsem);
3866         return ret;
3867 }
3868 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3869
3870 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3871 {
3872         struct nvme_ns *ns;
3873         struct gendisk *disk;
3874         struct nvme_id_ns *id;
3875         char disk_name[DISK_NAME_LEN];
3876         int node = ctrl->numa_node, flags = GENHD_FL_EXT_DEVT, ret;
3877
3878         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3879         if (!ns)
3880                 return;
3881
3882         ns->queue = blk_mq_init_queue(ctrl->tagset);
3883         if (IS_ERR(ns->queue))
3884                 goto out_free_ns;
3885
3886         if (ctrl->opts && ctrl->opts->data_digest)
3887                 ns->queue->backing_dev_info->capabilities
3888                         |= BDI_CAP_STABLE_WRITES;
3889
3890         blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3891         if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3892                 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3893
3894         ns->queue->queuedata = ns;
3895         ns->ctrl = ctrl;
3896
3897         kref_init(&ns->kref);
3898         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
3899
3900         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
3901         nvme_set_queue_limits(ctrl, ns->queue);
3902
3903         ret = nvme_identify_ns(ctrl, nsid, &id);
3904         if (ret)
3905                 goto out_free_queue;
3906
3907         if (id->ncap == 0)      /* no namespace (legacy quirk) */
3908                 goto out_free_id;
3909
3910         ret = nvme_init_ns_head(ns, nsid, id);
3911         if (ret)
3912                 goto out_free_id;
3913         nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3914
3915         disk = alloc_disk_node(0, node);
3916         if (!disk)
3917                 goto out_unlink_ns;
3918
3919         disk->fops = &nvme_fops;
3920         disk->private_data = ns;
3921         disk->queue = ns->queue;
3922         disk->flags = flags;
3923         memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3924         ns->disk = disk;
3925
3926         if (__nvme_revalidate_disk(disk, id))
3927                 goto out_put_disk;
3928
3929         if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3930                 ret = nvme_nvm_register(ns, disk_name, node);
3931                 if (ret) {
3932                         dev_warn(ctrl->device, "LightNVM init failure\n");
3933                         goto out_put_disk;
3934                 }
3935         }
3936
3937         down_write(&ctrl->namespaces_rwsem);
3938         list_add_tail(&ns->list, &ctrl->namespaces);
3939         up_write(&ctrl->namespaces_rwsem);
3940
3941         nvme_get_ctrl(ctrl);
3942
3943         device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups);
3944
3945         nvme_mpath_add_disk(ns, id);
3946         nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3947         kfree(id);
3948
3949         return;
3950  out_put_disk:
3951         /* prevent double queue cleanup */
3952         ns->disk->queue = NULL;
3953         put_disk(ns->disk);
3954  out_unlink_ns:
3955         mutex_lock(&ctrl->subsys->lock);
3956         list_del_rcu(&ns->siblings);
3957         if (list_empty(&ns->head->list))
3958                 list_del_init(&ns->head->entry);
3959         mutex_unlock(&ctrl->subsys->lock);
3960         nvme_put_ns_head(ns->head);
3961  out_free_id:
3962         kfree(id);
3963  out_free_queue:
3964         blk_cleanup_queue(ns->queue);
3965  out_free_ns:
3966         kfree(ns);
3967 }
3968
3969 static void nvme_ns_remove(struct nvme_ns *ns)
3970 {
3971         if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3972                 return;
3973
3974         nvme_fault_inject_fini(&ns->fault_inject);
3975
3976         mutex_lock(&ns->ctrl->subsys->lock);
3977         list_del_rcu(&ns->siblings);
3978         if (list_empty(&ns->head->list))
3979                 list_del_init(&ns->head->entry);
3980         mutex_unlock(&ns->ctrl->subsys->lock);
3981
3982         synchronize_rcu(); /* guarantee not available in head->list */
3983         nvme_mpath_clear_current_path(ns);
3984         synchronize_srcu(&ns->head->srcu); /* wait for concurrent submissions */
3985
3986         if (ns->disk->flags & GENHD_FL_UP) {
3987                 del_gendisk(ns->disk);
3988                 blk_cleanup_queue(ns->queue);
3989                 if (blk_get_integrity(ns->disk))
3990                         blk_integrity_unregister(ns->disk);
3991         }
3992
3993         down_write(&ns->ctrl->namespaces_rwsem);
3994         list_del_init(&ns->list);
3995         up_write(&ns->ctrl->namespaces_rwsem);
3996
3997         nvme_mpath_check_last_path(ns);
3998         nvme_put_ns(ns);
3999 }
4000
4001 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
4002 {
4003         struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
4004
4005         if (ns) {
4006                 nvme_ns_remove(ns);
4007                 nvme_put_ns(ns);
4008         }
4009 }
4010
4011 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
4012 {
4013         struct nvme_ns *ns;
4014
4015         ns = nvme_find_get_ns(ctrl, nsid);
4016         if (ns) {
4017                 if (revalidate_disk(ns->disk))
4018                         nvme_ns_remove(ns);
4019                 nvme_put_ns(ns);
4020         } else
4021                 nvme_alloc_ns(ctrl, nsid);
4022 }
4023
4024 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
4025                                         unsigned nsid)
4026 {
4027         struct nvme_ns *ns, *next;
4028         LIST_HEAD(rm_list);
4029
4030         down_write(&ctrl->namespaces_rwsem);
4031         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
4032                 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
4033                         list_move_tail(&ns->list, &rm_list);
4034         }
4035         up_write(&ctrl->namespaces_rwsem);
4036
4037         list_for_each_entry_safe(ns, next, &rm_list, list)
4038                 nvme_ns_remove(ns);
4039
4040 }
4041
4042 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
4043 {
4044         const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
4045         __le32 *ns_list;
4046         u32 prev = 0;
4047         int ret = 0, i;
4048
4049         if (nvme_ctrl_limited_cns(ctrl))
4050                 return -EOPNOTSUPP;
4051
4052         ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
4053         if (!ns_list)
4054                 return -ENOMEM;
4055
4056         for (;;) {
4057                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
4058                 if (ret)
4059                         goto free;
4060
4061                 for (i = 0; i < nr_entries; i++) {
4062                         u32 nsid = le32_to_cpu(ns_list[i]);
4063
4064                         if (!nsid)      /* end of the list? */
4065                                 goto out;
4066                         nvme_validate_ns(ctrl, nsid);
4067                         while (++prev < nsid)
4068                                 nvme_ns_remove_by_nsid(ctrl, prev);
4069                 }
4070         }
4071  out:
4072         nvme_remove_invalid_namespaces(ctrl, prev);
4073  free:
4074         kfree(ns_list);
4075         return ret;
4076 }
4077
4078 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
4079 {
4080         struct nvme_id_ctrl *id;
4081         u32 nn, i;
4082
4083         if (nvme_identify_ctrl(ctrl, &id))
4084                 return;
4085         nn = le32_to_cpu(id->nn);
4086         kfree(id);
4087
4088         for (i = 1; i <= nn; i++)
4089                 nvme_validate_ns(ctrl, i);
4090
4091         nvme_remove_invalid_namespaces(ctrl, nn);
4092 }
4093
4094 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
4095 {
4096         size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
4097         __le32 *log;
4098         int error;
4099
4100         log = kzalloc(log_size, GFP_KERNEL);
4101         if (!log)
4102                 return;
4103
4104         /*
4105          * We need to read the log to clear the AEN, but we don't want to rely
4106          * on it for the changed namespace information as userspace could have
4107          * raced with us in reading the log page, which could cause us to miss
4108          * updates.
4109          */
4110         error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
4111                         NVME_CSI_NVM, log, log_size, 0);
4112         if (error)
4113                 dev_warn(ctrl->device,
4114                         "reading changed ns log failed: %d\n", error);
4115
4116         kfree(log);
4117 }
4118
4119 static void nvme_scan_work(struct work_struct *work)
4120 {
4121         struct nvme_ctrl *ctrl =
4122                 container_of(work, struct nvme_ctrl, scan_work);
4123
4124         /* No tagset on a live ctrl means IO queues could not created */
4125         if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
4126                 return;
4127
4128         if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
4129                 dev_info(ctrl->device, "rescanning namespaces.\n");
4130                 nvme_clear_changed_ns_log(ctrl);
4131         }
4132
4133         mutex_lock(&ctrl->scan_lock);
4134         if (nvme_scan_ns_list(ctrl) != 0)
4135                 nvme_scan_ns_sequential(ctrl);
4136         mutex_unlock(&ctrl->scan_lock);
4137
4138         down_write(&ctrl->namespaces_rwsem);
4139         list_sort(NULL, &ctrl->namespaces, ns_cmp);
4140         up_write(&ctrl->namespaces_rwsem);
4141 }
4142
4143 /*
4144  * This function iterates the namespace list unlocked to allow recovery from
4145  * controller failure. It is up to the caller to ensure the namespace list is
4146  * not modified by scan work while this function is executing.
4147  */
4148 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
4149 {
4150         struct nvme_ns *ns, *next;
4151         LIST_HEAD(ns_list);
4152
4153         /*
4154          * make sure to requeue I/O to all namespaces as these
4155          * might result from the scan itself and must complete
4156          * for the scan_work to make progress
4157          */
4158         nvme_mpath_clear_ctrl_paths(ctrl);
4159
4160         /* prevent racing with ns scanning */
4161         flush_work(&ctrl->scan_work);
4162
4163         /*
4164          * The dead states indicates the controller was not gracefully
4165          * disconnected. In that case, we won't be able to flush any data while
4166          * removing the namespaces' disks; fail all the queues now to avoid
4167          * potentially having to clean up the failed sync later.
4168          */
4169         if (ctrl->state == NVME_CTRL_DEAD)
4170                 nvme_kill_queues(ctrl);
4171
4172         /* this is a no-op when called from the controller reset handler */
4173         nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4174
4175         down_write(&ctrl->namespaces_rwsem);
4176         list_splice_init(&ctrl->namespaces, &ns_list);
4177         up_write(&ctrl->namespaces_rwsem);
4178
4179         list_for_each_entry_safe(ns, next, &ns_list, list)
4180                 nvme_ns_remove(ns);
4181 }
4182 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4183
4184 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
4185 {
4186         struct nvme_ctrl *ctrl =
4187                 container_of(dev, struct nvme_ctrl, ctrl_device);
4188         struct nvmf_ctrl_options *opts = ctrl->opts;
4189         int ret;
4190
4191         ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4192         if (ret)
4193                 return ret;
4194
4195         if (opts) {
4196                 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4197                 if (ret)
4198                         return ret;
4199
4200                 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4201                                 opts->trsvcid ?: "none");
4202                 if (ret)
4203                         return ret;
4204
4205                 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4206                                 opts->host_traddr ?: "none");
4207         }
4208         return ret;
4209 }
4210
4211 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4212 {
4213         char *envp[2] = { NULL, NULL };
4214         u32 aen_result = ctrl->aen_result;
4215
4216         ctrl->aen_result = 0;
4217         if (!aen_result)
4218                 return;
4219
4220         envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4221         if (!envp[0])
4222                 return;
4223         kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4224         kfree(envp[0]);
4225 }
4226
4227 static void nvme_async_event_work(struct work_struct *work)
4228 {
4229         struct nvme_ctrl *ctrl =
4230                 container_of(work, struct nvme_ctrl, async_event_work);
4231
4232         nvme_aen_uevent(ctrl);
4233         ctrl->ops->submit_async_event(ctrl);
4234 }
4235
4236 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4237 {
4238
4239         u32 csts;
4240
4241         if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4242                 return false;
4243
4244         if (csts == ~0)
4245                 return false;
4246
4247         return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4248 }
4249
4250 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4251 {
4252         struct nvme_fw_slot_info_log *log;
4253
4254         log = kmalloc(sizeof(*log), GFP_KERNEL);
4255         if (!log)
4256                 return;
4257
4258         if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4259                         log, sizeof(*log), 0))
4260                 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4261         kfree(log);
4262 }
4263
4264 static void nvme_fw_act_work(struct work_struct *work)
4265 {
4266         struct nvme_ctrl *ctrl = container_of(work,
4267                                 struct nvme_ctrl, fw_act_work);
4268         unsigned long fw_act_timeout;
4269
4270         if (ctrl->mtfa)
4271                 fw_act_timeout = jiffies +
4272                                 msecs_to_jiffies(ctrl->mtfa * 100);
4273         else
4274                 fw_act_timeout = jiffies +
4275                                 msecs_to_jiffies(admin_timeout * 1000);
4276
4277         nvme_stop_queues(ctrl);
4278         while (nvme_ctrl_pp_status(ctrl)) {
4279                 if (time_after(jiffies, fw_act_timeout)) {
4280                         dev_warn(ctrl->device,
4281                                 "Fw activation timeout, reset controller\n");
4282                         nvme_try_sched_reset(ctrl);
4283                         return;
4284                 }
4285                 msleep(100);
4286         }
4287
4288         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4289                 return;
4290
4291         nvme_start_queues(ctrl);
4292         /* read FW slot information to clear the AER */
4293         nvme_get_fw_slot_info(ctrl);
4294 }
4295
4296 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4297 {
4298         u32 aer_notice_type = (result & 0xff00) >> 8;
4299
4300         trace_nvme_async_event(ctrl, aer_notice_type);
4301
4302         switch (aer_notice_type) {
4303         case NVME_AER_NOTICE_NS_CHANGED:
4304                 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4305                 nvme_queue_scan(ctrl);
4306                 break;
4307         case NVME_AER_NOTICE_FW_ACT_STARTING:
4308                 /*
4309                  * We are (ab)using the RESETTING state to prevent subsequent
4310                  * recovery actions from interfering with the controller's
4311                  * firmware activation.
4312                  */
4313                 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4314                         queue_work(nvme_wq, &ctrl->fw_act_work);
4315                 break;
4316 #ifdef CONFIG_NVME_MULTIPATH
4317         case NVME_AER_NOTICE_ANA:
4318                 if (!ctrl->ana_log_buf)
4319                         break;
4320                 queue_work(nvme_wq, &ctrl->ana_work);
4321                 break;
4322 #endif
4323         case NVME_AER_NOTICE_DISC_CHANGED:
4324                 ctrl->aen_result = result;
4325                 break;
4326         default:
4327                 dev_warn(ctrl->device, "async event result %08x\n", result);
4328         }
4329 }
4330
4331 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4332                 volatile union nvme_result *res)
4333 {
4334         u32 result = le32_to_cpu(res->u32);
4335         u32 aer_type = result & 0x07;
4336
4337         if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4338                 return;
4339
4340         switch (aer_type) {
4341         case NVME_AER_NOTICE:
4342                 nvme_handle_aen_notice(ctrl, result);
4343                 break;
4344         case NVME_AER_ERROR:
4345         case NVME_AER_SMART:
4346         case NVME_AER_CSS:
4347         case NVME_AER_VS:
4348                 trace_nvme_async_event(ctrl, aer_type);
4349                 ctrl->aen_result = result;
4350                 break;
4351         default:
4352                 break;
4353         }
4354         queue_work(nvme_wq, &ctrl->async_event_work);
4355 }
4356 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4357
4358 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4359 {
4360         nvme_mpath_stop(ctrl);
4361         nvme_stop_keep_alive(ctrl);
4362         flush_work(&ctrl->async_event_work);
4363         cancel_work_sync(&ctrl->fw_act_work);
4364 }
4365 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4366
4367 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4368 {
4369         nvme_start_keep_alive(ctrl);
4370
4371         nvme_enable_aen(ctrl);
4372
4373         if (ctrl->queue_count > 1) {
4374                 nvme_queue_scan(ctrl);
4375                 nvme_start_queues(ctrl);
4376         }
4377         ctrl->created = true;
4378 }
4379 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4380
4381 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4382 {
4383         nvme_fault_inject_fini(&ctrl->fault_inject);
4384         dev_pm_qos_hide_latency_tolerance(ctrl->device);
4385         cdev_device_del(&ctrl->cdev, ctrl->device);
4386         nvme_put_ctrl(ctrl);
4387 }
4388 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4389
4390 static void nvme_free_ctrl(struct device *dev)
4391 {
4392         struct nvme_ctrl *ctrl =
4393                 container_of(dev, struct nvme_ctrl, ctrl_device);
4394         struct nvme_subsystem *subsys = ctrl->subsys;
4395         struct nvme_cel *cel, *next;
4396
4397         if (!subsys || ctrl->instance != subsys->instance)
4398                 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4399
4400         list_for_each_entry_safe(cel, next, &ctrl->cels, entry) {
4401                 list_del(&cel->entry);
4402                 kfree(cel);
4403         }
4404
4405         nvme_mpath_uninit(ctrl);
4406         __free_page(ctrl->discard_page);
4407
4408         if (subsys) {
4409                 mutex_lock(&nvme_subsystems_lock);
4410                 list_del(&ctrl->subsys_entry);
4411                 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4412                 mutex_unlock(&nvme_subsystems_lock);
4413         }
4414
4415         ctrl->ops->free_ctrl(ctrl);
4416
4417         if (subsys)
4418                 nvme_put_subsystem(subsys);
4419 }
4420
4421 /*
4422  * Initialize a NVMe controller structures.  This needs to be called during
4423  * earliest initialization so that we have the initialized structured around
4424  * during probing.
4425  */
4426 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4427                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4428 {
4429         int ret;
4430
4431         ctrl->state = NVME_CTRL_NEW;
4432         spin_lock_init(&ctrl->lock);
4433         mutex_init(&ctrl->scan_lock);
4434         INIT_LIST_HEAD(&ctrl->namespaces);
4435         INIT_LIST_HEAD(&ctrl->cels);
4436         init_rwsem(&ctrl->namespaces_rwsem);
4437         ctrl->dev = dev;
4438         ctrl->ops = ops;
4439         ctrl->quirks = quirks;
4440         ctrl->numa_node = NUMA_NO_NODE;
4441         INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4442         INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4443         INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4444         INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4445         init_waitqueue_head(&ctrl->state_wq);
4446
4447         INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4448         memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4449         ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4450
4451         BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4452                         PAGE_SIZE);
4453         ctrl->discard_page = alloc_page(GFP_KERNEL);
4454         if (!ctrl->discard_page) {
4455                 ret = -ENOMEM;
4456                 goto out;
4457         }
4458
4459         ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4460         if (ret < 0)
4461                 goto out;
4462         ctrl->instance = ret;
4463
4464         device_initialize(&ctrl->ctrl_device);
4465         ctrl->device = &ctrl->ctrl_device;
4466         ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
4467         ctrl->device->class = nvme_class;
4468         ctrl->device->parent = ctrl->dev;
4469         ctrl->device->groups = nvme_dev_attr_groups;
4470         ctrl->device->release = nvme_free_ctrl;
4471         dev_set_drvdata(ctrl->device, ctrl);
4472         ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4473         if (ret)
4474                 goto out_release_instance;
4475
4476         nvme_get_ctrl(ctrl);
4477         cdev_init(&ctrl->cdev, &nvme_dev_fops);
4478         ctrl->cdev.owner = ops->module;
4479         ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4480         if (ret)
4481                 goto out_free_name;
4482
4483         /*
4484          * Initialize latency tolerance controls.  The sysfs files won't
4485          * be visible to userspace unless the device actually supports APST.
4486          */
4487         ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4488         dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4489                 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4490
4491         nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4492
4493         return 0;
4494 out_free_name:
4495         nvme_put_ctrl(ctrl);
4496         kfree_const(ctrl->device->kobj.name);
4497 out_release_instance:
4498         ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4499 out:
4500         if (ctrl->discard_page)
4501                 __free_page(ctrl->discard_page);
4502         return ret;
4503 }
4504 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4505
4506 /**
4507  * nvme_kill_queues(): Ends all namespace queues
4508  * @ctrl: the dead controller that needs to end
4509  *
4510  * Call this function when the driver determines it is unable to get the
4511  * controller in a state capable of servicing IO.
4512  */
4513 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4514 {
4515         struct nvme_ns *ns;
4516
4517         down_read(&ctrl->namespaces_rwsem);
4518
4519         /* Forcibly unquiesce queues to avoid blocking dispatch */
4520         if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4521                 blk_mq_unquiesce_queue(ctrl->admin_q);
4522
4523         list_for_each_entry(ns, &ctrl->namespaces, list)
4524                 nvme_set_queue_dying(ns);
4525
4526         up_read(&ctrl->namespaces_rwsem);
4527 }
4528 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4529
4530 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4531 {
4532         struct nvme_ns *ns;
4533
4534         down_read(&ctrl->namespaces_rwsem);
4535         list_for_each_entry(ns, &ctrl->namespaces, list)
4536                 blk_mq_unfreeze_queue(ns->queue);
4537         up_read(&ctrl->namespaces_rwsem);
4538 }
4539 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4540
4541 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4542 {
4543         struct nvme_ns *ns;
4544
4545         down_read(&ctrl->namespaces_rwsem);
4546         list_for_each_entry(ns, &ctrl->namespaces, list) {
4547                 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4548                 if (timeout <= 0)
4549                         break;
4550         }
4551         up_read(&ctrl->namespaces_rwsem);
4552         return timeout;
4553 }
4554 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4555
4556 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4557 {
4558         struct nvme_ns *ns;
4559
4560         down_read(&ctrl->namespaces_rwsem);
4561         list_for_each_entry(ns, &ctrl->namespaces, list)
4562                 blk_mq_freeze_queue_wait(ns->queue);
4563         up_read(&ctrl->namespaces_rwsem);
4564 }
4565 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4566
4567 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4568 {
4569         struct nvme_ns *ns;
4570
4571         down_read(&ctrl->namespaces_rwsem);
4572         list_for_each_entry(ns, &ctrl->namespaces, list)
4573                 blk_freeze_queue_start(ns->queue);
4574         up_read(&ctrl->namespaces_rwsem);
4575 }
4576 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4577
4578 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4579 {
4580         struct nvme_ns *ns;
4581
4582         down_read(&ctrl->namespaces_rwsem);
4583         list_for_each_entry(ns, &ctrl->namespaces, list)
4584                 blk_mq_quiesce_queue(ns->queue);
4585         up_read(&ctrl->namespaces_rwsem);
4586 }
4587 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4588
4589 void nvme_start_queues(struct nvme_ctrl *ctrl)
4590 {
4591         struct nvme_ns *ns;
4592
4593         down_read(&ctrl->namespaces_rwsem);
4594         list_for_each_entry(ns, &ctrl->namespaces, list)
4595                 blk_mq_unquiesce_queue(ns->queue);
4596         up_read(&ctrl->namespaces_rwsem);
4597 }
4598 EXPORT_SYMBOL_GPL(nvme_start_queues);
4599
4600
4601 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4602 {
4603         struct nvme_ns *ns;
4604
4605         down_read(&ctrl->namespaces_rwsem);
4606         list_for_each_entry(ns, &ctrl->namespaces, list)
4607                 blk_sync_queue(ns->queue);
4608         up_read(&ctrl->namespaces_rwsem);
4609
4610         if (ctrl->admin_q)
4611                 blk_sync_queue(ctrl->admin_q);
4612 }
4613 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4614
4615 struct nvme_ctrl *nvme_ctrl_get_by_path(const char *path)
4616 {
4617         struct nvme_ctrl *ctrl;
4618         struct file *f;
4619
4620         f = filp_open(path, O_RDWR, 0);
4621         if (IS_ERR(f))
4622                 return ERR_CAST(f);
4623
4624         if (f->f_op != &nvme_dev_fops) {
4625                 ctrl = ERR_PTR(-EINVAL);
4626                 goto out_close;
4627         }
4628
4629         ctrl = f->private_data;
4630         nvme_get_ctrl(ctrl);
4631
4632 out_close:
4633         filp_close(f, NULL);
4634         return ctrl;
4635 }
4636 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_get_by_path, NVME_TARGET_PASSTHRU);
4637
4638 /*
4639  * Check we didn't inadvertently grow the command structure sizes:
4640  */
4641 static inline void _nvme_check_size(void)
4642 {
4643         BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4644         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4645         BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4646         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4647         BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4648         BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4649         BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4650         BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4651         BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4652         BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4653         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4654         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4655         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4656         BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4657         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4658         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4659         BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4660         BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4661         BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4662 }
4663
4664
4665 static int __init nvme_core_init(void)
4666 {
4667         int result = -ENOMEM;
4668
4669         _nvme_check_size();
4670
4671         nvme_wq = alloc_workqueue("nvme-wq",
4672                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4673         if (!nvme_wq)
4674                 goto out;
4675
4676         nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4677                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4678         if (!nvme_reset_wq)
4679                 goto destroy_wq;
4680
4681         nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4682                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4683         if (!nvme_delete_wq)
4684                 goto destroy_reset_wq;
4685
4686         result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
4687         if (result < 0)
4688                 goto destroy_delete_wq;
4689
4690         nvme_class = class_create(THIS_MODULE, "nvme");
4691         if (IS_ERR(nvme_class)) {
4692                 result = PTR_ERR(nvme_class);
4693                 goto unregister_chrdev;
4694         }
4695         nvme_class->dev_uevent = nvme_class_uevent;
4696
4697         nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4698         if (IS_ERR(nvme_subsys_class)) {
4699                 result = PTR_ERR(nvme_subsys_class);
4700                 goto destroy_class;
4701         }
4702         return 0;
4703
4704 destroy_class:
4705         class_destroy(nvme_class);
4706 unregister_chrdev:
4707         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4708 destroy_delete_wq:
4709         destroy_workqueue(nvme_delete_wq);
4710 destroy_reset_wq:
4711         destroy_workqueue(nvme_reset_wq);
4712 destroy_wq:
4713         destroy_workqueue(nvme_wq);
4714 out:
4715         return result;
4716 }
4717
4718 static void __exit nvme_core_exit(void)
4719 {
4720         class_destroy(nvme_subsys_class);
4721         class_destroy(nvme_class);
4722         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4723         destroy_workqueue(nvme_delete_wq);
4724         destroy_workqueue(nvme_reset_wq);
4725         destroy_workqueue(nvme_wq);
4726         ida_destroy(&nvme_instance_ida);
4727 }
4728
4729 MODULE_LICENSE("GPL");
4730 MODULE_VERSION("1.0");
4731 module_init(nvme_core_init);
4732 module_exit(nvme_core_exit);