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