]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/nvme/host/core.c
90b6375a9da5b99148d6d2937a3b2e8daf397aa3
[linux.git] / drivers / nvme / host / core.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/pr.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <linux/pm_qos.h>
30 #include <asm/unaligned.h>
31
32 #include "nvme.h"
33 #include "fabrics.h"
34
35 #define NVME_MINORS             (1U << MINORBITS)
36
37 unsigned int admin_timeout = 60;
38 module_param(admin_timeout, uint, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
41
42 unsigned int nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
46
47 static unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
50
51 static u8 nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, byte, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
54
55 static unsigned long default_ps_max_latency_us = 100000;
56 module_param(default_ps_max_latency_us, ulong, 0644);
57 MODULE_PARM_DESC(default_ps_max_latency_us,
58                  "max power saving latency for new devices; use PM QOS to change per device");
59
60 static bool force_apst;
61 module_param(force_apst, bool, 0644);
62 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
63
64 static bool streams;
65 module_param(streams, bool, 0644);
66 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
67
68 struct workqueue_struct *nvme_wq;
69 EXPORT_SYMBOL_GPL(nvme_wq);
70
71 static DEFINE_IDA(nvme_instance_ida);
72 static dev_t nvme_chr_devt;
73 static struct class *nvme_class;
74
75 static __le32 nvme_get_log_dw10(u8 lid, size_t size)
76 {
77         return cpu_to_le32((((size / 4) - 1) << 16) | lid);
78 }
79
80 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
81 {
82         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
83                 return -EBUSY;
84         if (!queue_work(nvme_wq, &ctrl->reset_work))
85                 return -EBUSY;
86         return 0;
87 }
88 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
89
90 static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
91 {
92         int ret;
93
94         ret = nvme_reset_ctrl(ctrl);
95         if (!ret)
96                 flush_work(&ctrl->reset_work);
97         return ret;
98 }
99
100 static void nvme_delete_ctrl_work(struct work_struct *work)
101 {
102         struct nvme_ctrl *ctrl =
103                 container_of(work, struct nvme_ctrl, delete_work);
104
105         flush_work(&ctrl->reset_work);
106         nvme_stop_ctrl(ctrl);
107         nvme_remove_namespaces(ctrl);
108         ctrl->ops->delete_ctrl(ctrl);
109         nvme_uninit_ctrl(ctrl);
110         nvme_put_ctrl(ctrl);
111 }
112
113 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
114 {
115         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
116                 return -EBUSY;
117         if (!queue_work(nvme_wq, &ctrl->delete_work))
118                 return -EBUSY;
119         return 0;
120 }
121 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
122
123 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
124 {
125         int ret = 0;
126
127         /*
128          * Keep a reference until the work is flushed since ->delete_ctrl
129          * can free the controller.
130          */
131         nvme_get_ctrl(ctrl);
132         ret = nvme_delete_ctrl(ctrl);
133         if (!ret)
134                 flush_work(&ctrl->delete_work);
135         nvme_put_ctrl(ctrl);
136         return ret;
137 }
138 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
139
140 static inline bool nvme_ns_has_pi(struct nvme_ns *ns)
141 {
142         return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple);
143 }
144
145 static blk_status_t nvme_error_status(struct request *req)
146 {
147         switch (nvme_req(req)->status & 0x7ff) {
148         case NVME_SC_SUCCESS:
149                 return BLK_STS_OK;
150         case NVME_SC_CAP_EXCEEDED:
151                 return BLK_STS_NOSPC;
152         case NVME_SC_ONCS_NOT_SUPPORTED:
153                 return BLK_STS_NOTSUPP;
154         case NVME_SC_WRITE_FAULT:
155         case NVME_SC_READ_ERROR:
156         case NVME_SC_UNWRITTEN_BLOCK:
157         case NVME_SC_ACCESS_DENIED:
158         case NVME_SC_READ_ONLY:
159                 return BLK_STS_MEDIUM;
160         case NVME_SC_GUARD_CHECK:
161         case NVME_SC_APPTAG_CHECK:
162         case NVME_SC_REFTAG_CHECK:
163         case NVME_SC_INVALID_PI:
164                 return BLK_STS_PROTECTION;
165         case NVME_SC_RESERVATION_CONFLICT:
166                 return BLK_STS_NEXUS;
167         default:
168                 return BLK_STS_IOERR;
169         }
170 }
171
172 static inline bool nvme_req_needs_retry(struct request *req)
173 {
174         if (blk_noretry_request(req))
175                 return false;
176         if (nvme_req(req)->status & NVME_SC_DNR)
177                 return false;
178         if (nvme_req(req)->retries >= nvme_max_retries)
179                 return false;
180         if (blk_queue_dying(req->q))
181                 return false;
182         return true;
183 }
184
185 void nvme_complete_rq(struct request *req)
186 {
187         if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
188                 nvme_req(req)->retries++;
189                 blk_mq_requeue_request(req, true);
190                 return;
191         }
192
193         blk_mq_end_request(req, nvme_error_status(req));
194 }
195 EXPORT_SYMBOL_GPL(nvme_complete_rq);
196
197 void nvme_cancel_request(struct request *req, void *data, bool reserved)
198 {
199         if (!blk_mq_request_started(req))
200                 return;
201
202         dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
203                                 "Cancelling I/O %d", req->tag);
204
205         nvme_req(req)->status = NVME_SC_ABORT_REQ;
206         blk_mq_complete_request(req);
207
208 }
209 EXPORT_SYMBOL_GPL(nvme_cancel_request);
210
211 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
212                 enum nvme_ctrl_state new_state)
213 {
214         enum nvme_ctrl_state old_state;
215         unsigned long flags;
216         bool changed = false;
217
218         spin_lock_irqsave(&ctrl->lock, flags);
219
220         old_state = ctrl->state;
221         switch (new_state) {
222         case NVME_CTRL_LIVE:
223                 switch (old_state) {
224                 case NVME_CTRL_NEW:
225                 case NVME_CTRL_RESETTING:
226                 case NVME_CTRL_RECONNECTING:
227                         changed = true;
228                         /* FALLTHRU */
229                 default:
230                         break;
231                 }
232                 break;
233         case NVME_CTRL_RESETTING:
234                 switch (old_state) {
235                 case NVME_CTRL_NEW:
236                 case NVME_CTRL_LIVE:
237                         changed = true;
238                         /* FALLTHRU */
239                 default:
240                         break;
241                 }
242                 break;
243         case NVME_CTRL_RECONNECTING:
244                 switch (old_state) {
245                 case NVME_CTRL_LIVE:
246                 case NVME_CTRL_RESETTING:
247                         changed = true;
248                         /* FALLTHRU */
249                 default:
250                         break;
251                 }
252                 break;
253         case NVME_CTRL_DELETING:
254                 switch (old_state) {
255                 case NVME_CTRL_LIVE:
256                 case NVME_CTRL_RESETTING:
257                 case NVME_CTRL_RECONNECTING:
258                         changed = true;
259                         /* FALLTHRU */
260                 default:
261                         break;
262                 }
263                 break;
264         case NVME_CTRL_DEAD:
265                 switch (old_state) {
266                 case NVME_CTRL_DELETING:
267                         changed = true;
268                         /* FALLTHRU */
269                 default:
270                         break;
271                 }
272                 break;
273         default:
274                 break;
275         }
276
277         if (changed)
278                 ctrl->state = new_state;
279
280         spin_unlock_irqrestore(&ctrl->lock, flags);
281
282         return changed;
283 }
284 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
285
286 static void nvme_free_ns(struct kref *kref)
287 {
288         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
289
290         if (ns->ndev)
291                 nvme_nvm_unregister(ns);
292
293         put_disk(ns->disk);
294         ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
295         nvme_put_ctrl(ns->ctrl);
296         kfree(ns);
297 }
298
299 static void nvme_put_ns(struct nvme_ns *ns)
300 {
301         kref_put(&ns->kref, nvme_free_ns);
302 }
303
304 struct request *nvme_alloc_request(struct request_queue *q,
305                 struct nvme_command *cmd, unsigned int flags, int qid)
306 {
307         unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
308         struct request *req;
309
310         if (qid == NVME_QID_ANY) {
311                 req = blk_mq_alloc_request(q, op, flags);
312         } else {
313                 req = blk_mq_alloc_request_hctx(q, op, flags,
314                                 qid ? qid - 1 : 0);
315         }
316         if (IS_ERR(req))
317                 return req;
318
319         req->cmd_flags |= REQ_FAILFAST_DRIVER;
320         nvme_req(req)->cmd = cmd;
321
322         return req;
323 }
324 EXPORT_SYMBOL_GPL(nvme_alloc_request);
325
326 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
327 {
328         struct nvme_command c;
329
330         memset(&c, 0, sizeof(c));
331
332         c.directive.opcode = nvme_admin_directive_send;
333         c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
334         c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
335         c.directive.dtype = NVME_DIR_IDENTIFY;
336         c.directive.tdtype = NVME_DIR_STREAMS;
337         c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
338
339         return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
340 }
341
342 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
343 {
344         return nvme_toggle_streams(ctrl, false);
345 }
346
347 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
348 {
349         return nvme_toggle_streams(ctrl, true);
350 }
351
352 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
353                                   struct streams_directive_params *s, u32 nsid)
354 {
355         struct nvme_command c;
356
357         memset(&c, 0, sizeof(c));
358         memset(s, 0, sizeof(*s));
359
360         c.directive.opcode = nvme_admin_directive_recv;
361         c.directive.nsid = cpu_to_le32(nsid);
362         c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
363         c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
364         c.directive.dtype = NVME_DIR_STREAMS;
365
366         return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
367 }
368
369 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
370 {
371         struct streams_directive_params s;
372         int ret;
373
374         if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
375                 return 0;
376         if (!streams)
377                 return 0;
378
379         ret = nvme_enable_streams(ctrl);
380         if (ret)
381                 return ret;
382
383         ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
384         if (ret)
385                 return ret;
386
387         ctrl->nssa = le16_to_cpu(s.nssa);
388         if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
389                 dev_info(ctrl->device, "too few streams (%u) available\n",
390                                         ctrl->nssa);
391                 nvme_disable_streams(ctrl);
392                 return 0;
393         }
394
395         ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
396         dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
397         return 0;
398 }
399
400 /*
401  * Check if 'req' has a write hint associated with it. If it does, assign
402  * a valid namespace stream to the write.
403  */
404 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
405                                      struct request *req, u16 *control,
406                                      u32 *dsmgmt)
407 {
408         enum rw_hint streamid = req->write_hint;
409
410         if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
411                 streamid = 0;
412         else {
413                 streamid--;
414                 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
415                         return;
416
417                 *control |= NVME_RW_DTYPE_STREAMS;
418                 *dsmgmt |= streamid << 16;
419         }
420
421         if (streamid < ARRAY_SIZE(req->q->write_hints))
422                 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
423 }
424
425 static inline void nvme_setup_flush(struct nvme_ns *ns,
426                 struct nvme_command *cmnd)
427 {
428         memset(cmnd, 0, sizeof(*cmnd));
429         cmnd->common.opcode = nvme_cmd_flush;
430         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
431 }
432
433 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
434                 struct nvme_command *cmnd)
435 {
436         unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
437         struct nvme_dsm_range *range;
438         struct bio *bio;
439
440         range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
441         if (!range)
442                 return BLK_STS_RESOURCE;
443
444         __rq_for_each_bio(bio, req) {
445                 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
446                 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
447
448                 range[n].cattr = cpu_to_le32(0);
449                 range[n].nlb = cpu_to_le32(nlb);
450                 range[n].slba = cpu_to_le64(slba);
451                 n++;
452         }
453
454         if (WARN_ON_ONCE(n != segments)) {
455                 kfree(range);
456                 return BLK_STS_IOERR;
457         }
458
459         memset(cmnd, 0, sizeof(*cmnd));
460         cmnd->dsm.opcode = nvme_cmd_dsm;
461         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
462         cmnd->dsm.nr = cpu_to_le32(segments - 1);
463         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
464
465         req->special_vec.bv_page = virt_to_page(range);
466         req->special_vec.bv_offset = offset_in_page(range);
467         req->special_vec.bv_len = sizeof(*range) * segments;
468         req->rq_flags |= RQF_SPECIAL_PAYLOAD;
469
470         return BLK_STS_OK;
471 }
472
473 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
474                 struct request *req, struct nvme_command *cmnd)
475 {
476         struct nvme_ctrl *ctrl = ns->ctrl;
477         u16 control = 0;
478         u32 dsmgmt = 0;
479
480         if (req->cmd_flags & REQ_FUA)
481                 control |= NVME_RW_FUA;
482         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
483                 control |= NVME_RW_LR;
484
485         if (req->cmd_flags & REQ_RAHEAD)
486                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
487
488         memset(cmnd, 0, sizeof(*cmnd));
489         cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
490         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
491         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
492         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
493
494         if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
495                 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
496
497         if (ns->ms) {
498                 /*
499                  * If formated with metadata, the block layer always provides a
500                  * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled.  Else
501                  * we enable the PRACT bit for protection information or set the
502                  * namespace capacity to zero to prevent any I/O.
503                  */
504                 if (!blk_integrity_rq(req)) {
505                         if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
506                                 return BLK_STS_NOTSUPP;
507                         control |= NVME_RW_PRINFO_PRACT;
508                 }
509
510                 switch (ns->pi_type) {
511                 case NVME_NS_DPS_PI_TYPE3:
512                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
513                         break;
514                 case NVME_NS_DPS_PI_TYPE1:
515                 case NVME_NS_DPS_PI_TYPE2:
516                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
517                                         NVME_RW_PRINFO_PRCHK_REF;
518                         cmnd->rw.reftag = cpu_to_le32(
519                                         nvme_block_nr(ns, blk_rq_pos(req)));
520                         break;
521                 }
522         }
523
524         cmnd->rw.control = cpu_to_le16(control);
525         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
526         return 0;
527 }
528
529 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
530                 struct nvme_command *cmd)
531 {
532         blk_status_t ret = BLK_STS_OK;
533
534         if (!(req->rq_flags & RQF_DONTPREP)) {
535                 nvme_req(req)->retries = 0;
536                 nvme_req(req)->flags = 0;
537                 req->rq_flags |= RQF_DONTPREP;
538         }
539
540         switch (req_op(req)) {
541         case REQ_OP_DRV_IN:
542         case REQ_OP_DRV_OUT:
543                 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
544                 break;
545         case REQ_OP_FLUSH:
546                 nvme_setup_flush(ns, cmd);
547                 break;
548         case REQ_OP_WRITE_ZEROES:
549                 /* currently only aliased to deallocate for a few ctrls: */
550         case REQ_OP_DISCARD:
551                 ret = nvme_setup_discard(ns, req, cmd);
552                 break;
553         case REQ_OP_READ:
554         case REQ_OP_WRITE:
555                 ret = nvme_setup_rw(ns, req, cmd);
556                 break;
557         default:
558                 WARN_ON_ONCE(1);
559                 return BLK_STS_IOERR;
560         }
561
562         cmd->common.command_id = req->tag;
563         return ret;
564 }
565 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
566
567 /*
568  * Returns 0 on success.  If the result is negative, it's a Linux error code;
569  * if the result is positive, it's an NVM Express status code
570  */
571 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
572                 union nvme_result *result, void *buffer, unsigned bufflen,
573                 unsigned timeout, int qid, int at_head, int flags)
574 {
575         struct request *req;
576         int ret;
577
578         req = nvme_alloc_request(q, cmd, flags, qid);
579         if (IS_ERR(req))
580                 return PTR_ERR(req);
581
582         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
583
584         if (buffer && bufflen) {
585                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
586                 if (ret)
587                         goto out;
588         }
589
590         blk_execute_rq(req->q, NULL, req, at_head);
591         if (result)
592                 *result = nvme_req(req)->result;
593         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
594                 ret = -EINTR;
595         else
596                 ret = nvme_req(req)->status;
597  out:
598         blk_mq_free_request(req);
599         return ret;
600 }
601 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
602
603 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
604                 void *buffer, unsigned bufflen)
605 {
606         return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
607                         NVME_QID_ANY, 0, 0);
608 }
609 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
610
611 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
612                 unsigned len, u32 seed, bool write)
613 {
614         struct bio_integrity_payload *bip;
615         int ret = -ENOMEM;
616         void *buf;
617
618         buf = kmalloc(len, GFP_KERNEL);
619         if (!buf)
620                 goto out;
621
622         ret = -EFAULT;
623         if (write && copy_from_user(buf, ubuf, len))
624                 goto out_free_meta;
625
626         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
627         if (IS_ERR(bip)) {
628                 ret = PTR_ERR(bip);
629                 goto out_free_meta;
630         }
631
632         bip->bip_iter.bi_size = len;
633         bip->bip_iter.bi_sector = seed;
634         ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
635                         offset_in_page(buf));
636         if (ret == len)
637                 return buf;
638         ret = -ENOMEM;
639 out_free_meta:
640         kfree(buf);
641 out:
642         return ERR_PTR(ret);
643 }
644
645 static int nvme_submit_user_cmd(struct request_queue *q,
646                 struct nvme_command *cmd, void __user *ubuffer,
647                 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
648                 u32 meta_seed, u32 *result, unsigned timeout)
649 {
650         bool write = nvme_is_write(cmd);
651         struct nvme_ns *ns = q->queuedata;
652         struct gendisk *disk = ns ? ns->disk : NULL;
653         struct request *req;
654         struct bio *bio = NULL;
655         void *meta = NULL;
656         int ret;
657
658         req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
659         if (IS_ERR(req))
660                 return PTR_ERR(req);
661
662         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
663
664         if (ubuffer && bufflen) {
665                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
666                                 GFP_KERNEL);
667                 if (ret)
668                         goto out;
669                 bio = req->bio;
670                 bio->bi_disk = disk;
671                 if (disk && meta_buffer && meta_len) {
672                         meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
673                                         meta_seed, write);
674                         if (IS_ERR(meta)) {
675                                 ret = PTR_ERR(meta);
676                                 goto out_unmap;
677                         }
678                 }
679         }
680
681         blk_execute_rq(req->q, disk, req, 0);
682         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
683                 ret = -EINTR;
684         else
685                 ret = nvme_req(req)->status;
686         if (result)
687                 *result = le32_to_cpu(nvme_req(req)->result.u32);
688         if (meta && !ret && !write) {
689                 if (copy_to_user(meta_buffer, meta, meta_len))
690                         ret = -EFAULT;
691         }
692         kfree(meta);
693  out_unmap:
694         if (bio)
695                 blk_rq_unmap_user(bio);
696  out:
697         blk_mq_free_request(req);
698         return ret;
699 }
700
701 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
702 {
703         struct nvme_ctrl *ctrl = rq->end_io_data;
704
705         blk_mq_free_request(rq);
706
707         if (status) {
708                 dev_err(ctrl->device,
709                         "failed nvme_keep_alive_end_io error=%d\n",
710                                 status);
711                 return;
712         }
713
714         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
715 }
716
717 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
718 {
719         struct nvme_command c;
720         struct request *rq;
721
722         memset(&c, 0, sizeof(c));
723         c.common.opcode = nvme_admin_keep_alive;
724
725         rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
726                         NVME_QID_ANY);
727         if (IS_ERR(rq))
728                 return PTR_ERR(rq);
729
730         rq->timeout = ctrl->kato * HZ;
731         rq->end_io_data = ctrl;
732
733         blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
734
735         return 0;
736 }
737
738 static void nvme_keep_alive_work(struct work_struct *work)
739 {
740         struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
741                         struct nvme_ctrl, ka_work);
742
743         if (nvme_keep_alive(ctrl)) {
744                 /* allocation failure, reset the controller */
745                 dev_err(ctrl->device, "keep-alive failed\n");
746                 nvme_reset_ctrl(ctrl);
747                 return;
748         }
749 }
750
751 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
752 {
753         if (unlikely(ctrl->kato == 0))
754                 return;
755
756         INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
757         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
758 }
759 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
760
761 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
762 {
763         if (unlikely(ctrl->kato == 0))
764                 return;
765
766         cancel_delayed_work_sync(&ctrl->ka_work);
767 }
768 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
769
770 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
771 {
772         struct nvme_command c = { };
773         int error;
774
775         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
776         c.identify.opcode = nvme_admin_identify;
777         c.identify.cns = NVME_ID_CNS_CTRL;
778
779         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
780         if (!*id)
781                 return -ENOMEM;
782
783         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
784                         sizeof(struct nvme_id_ctrl));
785         if (error)
786                 kfree(*id);
787         return error;
788 }
789
790 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
791                 u8 *eui64, u8 *nguid, uuid_t *uuid)
792 {
793         struct nvme_command c = { };
794         int status;
795         void *data;
796         int pos;
797         int len;
798
799         c.identify.opcode = nvme_admin_identify;
800         c.identify.nsid = cpu_to_le32(nsid);
801         c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
802
803         data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
804         if (!data)
805                 return -ENOMEM;
806
807         status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
808                                       NVME_IDENTIFY_DATA_SIZE);
809         if (status)
810                 goto free_data;
811
812         for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
813                 struct nvme_ns_id_desc *cur = data + pos;
814
815                 if (cur->nidl == 0)
816                         break;
817
818                 switch (cur->nidt) {
819                 case NVME_NIDT_EUI64:
820                         if (cur->nidl != NVME_NIDT_EUI64_LEN) {
821                                 dev_warn(ctrl->device,
822                                          "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
823                                          cur->nidl);
824                                 goto free_data;
825                         }
826                         len = NVME_NIDT_EUI64_LEN;
827                         memcpy(eui64, data + pos + sizeof(*cur), len);
828                         break;
829                 case NVME_NIDT_NGUID:
830                         if (cur->nidl != NVME_NIDT_NGUID_LEN) {
831                                 dev_warn(ctrl->device,
832                                          "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
833                                          cur->nidl);
834                                 goto free_data;
835                         }
836                         len = NVME_NIDT_NGUID_LEN;
837                         memcpy(nguid, data + pos + sizeof(*cur), len);
838                         break;
839                 case NVME_NIDT_UUID:
840                         if (cur->nidl != NVME_NIDT_UUID_LEN) {
841                                 dev_warn(ctrl->device,
842                                          "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
843                                          cur->nidl);
844                                 goto free_data;
845                         }
846                         len = NVME_NIDT_UUID_LEN;
847                         uuid_copy(uuid, data + pos + sizeof(*cur));
848                         break;
849                 default:
850                         /* Skip unnkown types */
851                         len = cur->nidl;
852                         break;
853                 }
854
855                 len += sizeof(*cur);
856         }
857 free_data:
858         kfree(data);
859         return status;
860 }
861
862 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
863 {
864         struct nvme_command c = { };
865
866         c.identify.opcode = nvme_admin_identify;
867         c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
868         c.identify.nsid = cpu_to_le32(nsid);
869         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
870 }
871
872 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
873                 unsigned nsid)
874 {
875         struct nvme_id_ns *id;
876         struct nvme_command c = { };
877         int error;
878
879         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
880         c.identify.opcode = nvme_admin_identify;
881         c.identify.nsid = cpu_to_le32(nsid);
882         c.identify.cns = NVME_ID_CNS_NS;
883
884         id = kmalloc(sizeof(*id), GFP_KERNEL);
885         if (!id)
886                 return NULL;
887
888         error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
889         if (error) {
890                 dev_warn(ctrl->device, "Identify namespace failed\n");
891                 kfree(id);
892                 return NULL;
893         }
894
895         return id;
896 }
897
898 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
899                       void *buffer, size_t buflen, u32 *result)
900 {
901         struct nvme_command c;
902         union nvme_result res;
903         int ret;
904
905         memset(&c, 0, sizeof(c));
906         c.features.opcode = nvme_admin_set_features;
907         c.features.fid = cpu_to_le32(fid);
908         c.features.dword11 = cpu_to_le32(dword11);
909
910         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
911                         buffer, buflen, 0, NVME_QID_ANY, 0, 0);
912         if (ret >= 0 && result)
913                 *result = le32_to_cpu(res.u32);
914         return ret;
915 }
916
917 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
918 {
919         u32 q_count = (*count - 1) | ((*count - 1) << 16);
920         u32 result;
921         int status, nr_io_queues;
922
923         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
924                         &result);
925         if (status < 0)
926                 return status;
927
928         /*
929          * Degraded controllers might return an error when setting the queue
930          * count.  We still want to be able to bring them online and offer
931          * access to the admin queue, as that might be only way to fix them up.
932          */
933         if (status > 0) {
934                 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
935                 *count = 0;
936         } else {
937                 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
938                 *count = min(*count, nr_io_queues);
939         }
940
941         return 0;
942 }
943 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
944
945 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
946 {
947         struct nvme_user_io io;
948         struct nvme_command c;
949         unsigned length, meta_len;
950         void __user *metadata;
951
952         if (copy_from_user(&io, uio, sizeof(io)))
953                 return -EFAULT;
954         if (io.flags)
955                 return -EINVAL;
956
957         switch (io.opcode) {
958         case nvme_cmd_write:
959         case nvme_cmd_read:
960         case nvme_cmd_compare:
961                 break;
962         default:
963                 return -EINVAL;
964         }
965
966         length = (io.nblocks + 1) << ns->lba_shift;
967         meta_len = (io.nblocks + 1) * ns->ms;
968         metadata = (void __user *)(uintptr_t)io.metadata;
969
970         if (ns->ext) {
971                 length += meta_len;
972                 meta_len = 0;
973         } else if (meta_len) {
974                 if ((io.metadata & 3) || !io.metadata)
975                         return -EINVAL;
976         }
977
978         memset(&c, 0, sizeof(c));
979         c.rw.opcode = io.opcode;
980         c.rw.flags = io.flags;
981         c.rw.nsid = cpu_to_le32(ns->ns_id);
982         c.rw.slba = cpu_to_le64(io.slba);
983         c.rw.length = cpu_to_le16(io.nblocks);
984         c.rw.control = cpu_to_le16(io.control);
985         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
986         c.rw.reftag = cpu_to_le32(io.reftag);
987         c.rw.apptag = cpu_to_le16(io.apptag);
988         c.rw.appmask = cpu_to_le16(io.appmask);
989
990         return nvme_submit_user_cmd(ns->queue, &c,
991                         (void __user *)(uintptr_t)io.addr, length,
992                         metadata, meta_len, io.slba, NULL, 0);
993 }
994
995 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
996                         struct nvme_passthru_cmd __user *ucmd)
997 {
998         struct nvme_passthru_cmd cmd;
999         struct nvme_command c;
1000         unsigned timeout = 0;
1001         int status;
1002
1003         if (!capable(CAP_SYS_ADMIN))
1004                 return -EACCES;
1005         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1006                 return -EFAULT;
1007         if (cmd.flags)
1008                 return -EINVAL;
1009
1010         memset(&c, 0, sizeof(c));
1011         c.common.opcode = cmd.opcode;
1012         c.common.flags = cmd.flags;
1013         c.common.nsid = cpu_to_le32(cmd.nsid);
1014         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1015         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1016         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1017         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1018         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1019         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1020         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1021         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1022
1023         if (cmd.timeout_ms)
1024                 timeout = msecs_to_jiffies(cmd.timeout_ms);
1025
1026         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1027                         (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1028                         (void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1029                         0, &cmd.result, timeout);
1030         if (status >= 0) {
1031                 if (put_user(cmd.result, &ucmd->result))
1032                         return -EFAULT;
1033         }
1034
1035         return status;
1036 }
1037
1038 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1039                 unsigned int cmd, unsigned long arg)
1040 {
1041         struct nvme_ns *ns = bdev->bd_disk->private_data;
1042
1043         switch (cmd) {
1044         case NVME_IOCTL_ID:
1045                 force_successful_syscall_return();
1046                 return ns->ns_id;
1047         case NVME_IOCTL_ADMIN_CMD:
1048                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1049         case NVME_IOCTL_IO_CMD:
1050                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1051         case NVME_IOCTL_SUBMIT_IO:
1052                 return nvme_submit_io(ns, (void __user *)arg);
1053         default:
1054 #ifdef CONFIG_NVM
1055                 if (ns->ndev)
1056                         return nvme_nvm_ioctl(ns, cmd, arg);
1057 #endif
1058                 if (is_sed_ioctl(cmd))
1059                         return sed_ioctl(ns->ctrl->opal_dev, cmd,
1060                                          (void __user *) arg);
1061                 return -ENOTTY;
1062         }
1063 }
1064
1065 static int nvme_open(struct block_device *bdev, fmode_t mode)
1066 {
1067         struct nvme_ns *ns = bdev->bd_disk->private_data;
1068
1069         if (!kref_get_unless_zero(&ns->kref))
1070                 return -ENXIO;
1071         return 0;
1072 }
1073
1074 static void nvme_release(struct gendisk *disk, fmode_t mode)
1075 {
1076         nvme_put_ns(disk->private_data);
1077 }
1078
1079 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1080 {
1081         /* some standard values */
1082         geo->heads = 1 << 6;
1083         geo->sectors = 1 << 5;
1084         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1085         return 0;
1086 }
1087
1088 #ifdef CONFIG_BLK_DEV_INTEGRITY
1089 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1090 {
1091         struct blk_integrity integrity;
1092
1093         memset(&integrity, 0, sizeof(integrity));
1094         switch (pi_type) {
1095         case NVME_NS_DPS_PI_TYPE3:
1096                 integrity.profile = &t10_pi_type3_crc;
1097                 integrity.tag_size = sizeof(u16) + sizeof(u32);
1098                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1099                 break;
1100         case NVME_NS_DPS_PI_TYPE1:
1101         case NVME_NS_DPS_PI_TYPE2:
1102                 integrity.profile = &t10_pi_type1_crc;
1103                 integrity.tag_size = sizeof(u16);
1104                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1105                 break;
1106         default:
1107                 integrity.profile = NULL;
1108                 break;
1109         }
1110         integrity.tuple_size = ms;
1111         blk_integrity_register(disk, &integrity);
1112         blk_queue_max_integrity_segments(disk->queue, 1);
1113 }
1114 #else
1115 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1116 {
1117 }
1118 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1119
1120 static void nvme_set_chunk_size(struct nvme_ns *ns)
1121 {
1122         u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1123         blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1124 }
1125
1126 static void nvme_config_discard(struct nvme_ctrl *ctrl,
1127                 unsigned stream_alignment, struct request_queue *queue)
1128 {
1129         u32 size = queue_logical_block_size(queue);
1130
1131         if (stream_alignment)
1132                 size *= stream_alignment;
1133
1134         BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1135                         NVME_DSM_MAX_RANGES);
1136
1137         queue->limits.discard_alignment = size;
1138         queue->limits.discard_granularity = size;
1139
1140         blk_queue_max_discard_sectors(queue, UINT_MAX);
1141         blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1142         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, queue);
1143
1144         if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1145                 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1146 }
1147
1148 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1149                 struct nvme_id_ns *id, u8 *eui64, u8 *nguid, uuid_t *uuid)
1150 {
1151         if (ctrl->vs >= NVME_VS(1, 1, 0))
1152                 memcpy(eui64, id->eui64, sizeof(id->eui64));
1153         if (ctrl->vs >= NVME_VS(1, 2, 0))
1154                 memcpy(nguid, id->nguid, sizeof(id->nguid));
1155         if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1156                  /* Don't treat error as fatal we potentially
1157                   * already have a NGUID or EUI-64
1158                   */
1159                 if (nvme_identify_ns_descs(ctrl, nsid, eui64, nguid, uuid))
1160                         dev_warn(ctrl->device,
1161                                  "%s: Identify Descriptors failed\n", __func__);
1162         }
1163 }
1164
1165 static void nvme_update_disk_info(struct gendisk *disk,
1166                 struct nvme_ns *ns, struct nvme_id_ns *id)
1167 {
1168         sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9);
1169         unsigned stream_alignment = 0;
1170
1171         if (ns->ctrl->nr_streams && ns->sws && ns->sgs)
1172                 stream_alignment = ns->sws * ns->sgs;
1173
1174         blk_mq_freeze_queue(disk->queue);
1175         blk_integrity_unregister(disk);
1176
1177         blk_queue_logical_block_size(disk->queue, 1 << ns->lba_shift);
1178         if (ns->ms && !ns->ext &&
1179             (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1180                 nvme_init_integrity(disk, ns->ms, ns->pi_type);
1181         if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk))
1182                 capacity = 0;
1183         set_capacity(disk, capacity);
1184
1185         if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
1186                 nvme_config_discard(ns->ctrl, stream_alignment, disk->queue);
1187         blk_mq_unfreeze_queue(disk->queue);
1188 }
1189
1190 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1191 {
1192         struct nvme_ns *ns = disk->private_data;
1193
1194         /*
1195          * If identify namespace failed, use default 512 byte block size so
1196          * block layer can use before failing read/write for 0 capacity.
1197          */
1198         ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1199         if (ns->lba_shift == 0)
1200                 ns->lba_shift = 9;
1201         ns->noiob = le16_to_cpu(id->noiob);
1202         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1203         ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1204         /* the PI implementation requires metadata equal t10 pi tuple size */
1205         if (ns->ms == sizeof(struct t10_pi_tuple))
1206                 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1207         else
1208                 ns->pi_type = 0;
1209
1210         if (ns->noiob)
1211                 nvme_set_chunk_size(ns);
1212         nvme_update_disk_info(disk, ns, id);
1213 }
1214
1215 static int nvme_revalidate_disk(struct gendisk *disk)
1216 {
1217         struct nvme_ns *ns = disk->private_data;
1218         struct nvme_ctrl *ctrl = ns->ctrl;
1219         struct nvme_id_ns *id;
1220         u8 eui64[8] = { 0 }, nguid[16] = { 0 };
1221         uuid_t uuid = uuid_null;
1222         int ret = 0;
1223
1224         if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1225                 set_capacity(disk, 0);
1226                 return -ENODEV;
1227         }
1228
1229         id = nvme_identify_ns(ctrl, ns->ns_id);
1230         if (!id)
1231                 return -ENODEV;
1232
1233         if (id->ncap == 0) {
1234                 ret = -ENODEV;
1235                 goto out;
1236         }
1237
1238         nvme_report_ns_ids(ctrl, ns->ns_id, id, eui64, nguid, &uuid);
1239         if (!uuid_equal(&ns->uuid, &uuid) ||
1240             memcmp(&ns->nguid, &nguid, sizeof(ns->nguid)) ||
1241             memcmp(&ns->eui, &eui64, sizeof(ns->eui))) {
1242                 dev_err(ctrl->device,
1243                         "identifiers changed for nsid %d\n", ns->ns_id);
1244                 ret = -ENODEV;
1245         }
1246
1247 out:
1248         kfree(id);
1249         return ret;
1250 }
1251
1252 static char nvme_pr_type(enum pr_type type)
1253 {
1254         switch (type) {
1255         case PR_WRITE_EXCLUSIVE:
1256                 return 1;
1257         case PR_EXCLUSIVE_ACCESS:
1258                 return 2;
1259         case PR_WRITE_EXCLUSIVE_REG_ONLY:
1260                 return 3;
1261         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1262                 return 4;
1263         case PR_WRITE_EXCLUSIVE_ALL_REGS:
1264                 return 5;
1265         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1266                 return 6;
1267         default:
1268                 return 0;
1269         }
1270 };
1271
1272 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1273                                 u64 key, u64 sa_key, u8 op)
1274 {
1275         struct nvme_ns *ns = bdev->bd_disk->private_data;
1276         struct nvme_command c;
1277         u8 data[16] = { 0, };
1278
1279         put_unaligned_le64(key, &data[0]);
1280         put_unaligned_le64(sa_key, &data[8]);
1281
1282         memset(&c, 0, sizeof(c));
1283         c.common.opcode = op;
1284         c.common.nsid = cpu_to_le32(ns->ns_id);
1285         c.common.cdw10[0] = cpu_to_le32(cdw10);
1286
1287         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1288 }
1289
1290 static int nvme_pr_register(struct block_device *bdev, u64 old,
1291                 u64 new, unsigned flags)
1292 {
1293         u32 cdw10;
1294
1295         if (flags & ~PR_FL_IGNORE_KEY)
1296                 return -EOPNOTSUPP;
1297
1298         cdw10 = old ? 2 : 0;
1299         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1300         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1301         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1302 }
1303
1304 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1305                 enum pr_type type, unsigned flags)
1306 {
1307         u32 cdw10;
1308
1309         if (flags & ~PR_FL_IGNORE_KEY)
1310                 return -EOPNOTSUPP;
1311
1312         cdw10 = nvme_pr_type(type) << 8;
1313         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1314         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1315 }
1316
1317 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1318                 enum pr_type type, bool abort)
1319 {
1320         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1321         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1322 }
1323
1324 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1325 {
1326         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1327         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1328 }
1329
1330 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1331 {
1332         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1333         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1334 }
1335
1336 static const struct pr_ops nvme_pr_ops = {
1337         .pr_register    = nvme_pr_register,
1338         .pr_reserve     = nvme_pr_reserve,
1339         .pr_release     = nvme_pr_release,
1340         .pr_preempt     = nvme_pr_preempt,
1341         .pr_clear       = nvme_pr_clear,
1342 };
1343
1344 #ifdef CONFIG_BLK_SED_OPAL
1345 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1346                 bool send)
1347 {
1348         struct nvme_ctrl *ctrl = data;
1349         struct nvme_command cmd;
1350
1351         memset(&cmd, 0, sizeof(cmd));
1352         if (send)
1353                 cmd.common.opcode = nvme_admin_security_send;
1354         else
1355                 cmd.common.opcode = nvme_admin_security_recv;
1356         cmd.common.nsid = 0;
1357         cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1358         cmd.common.cdw10[1] = cpu_to_le32(len);
1359
1360         return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1361                                       ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1362 }
1363 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1364 #endif /* CONFIG_BLK_SED_OPAL */
1365
1366 static const struct block_device_operations nvme_fops = {
1367         .owner          = THIS_MODULE,
1368         .ioctl          = nvme_ioctl,
1369         .compat_ioctl   = nvme_ioctl,
1370         .open           = nvme_open,
1371         .release        = nvme_release,
1372         .getgeo         = nvme_getgeo,
1373         .revalidate_disk= nvme_revalidate_disk,
1374         .pr_ops         = &nvme_pr_ops,
1375 };
1376
1377 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1378 {
1379         unsigned long timeout =
1380                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1381         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1382         int ret;
1383
1384         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1385                 if (csts == ~0)
1386                         return -ENODEV;
1387                 if ((csts & NVME_CSTS_RDY) == bit)
1388                         break;
1389
1390                 msleep(100);
1391                 if (fatal_signal_pending(current))
1392                         return -EINTR;
1393                 if (time_after(jiffies, timeout)) {
1394                         dev_err(ctrl->device,
1395                                 "Device not ready; aborting %s\n", enabled ?
1396                                                 "initialisation" : "reset");
1397                         return -ENODEV;
1398                 }
1399         }
1400
1401         return ret;
1402 }
1403
1404 /*
1405  * If the device has been passed off to us in an enabled state, just clear
1406  * the enabled bit.  The spec says we should set the 'shutdown notification
1407  * bits', but doing so may cause the device to complete commands to the
1408  * admin queue ... and we don't know what memory that might be pointing at!
1409  */
1410 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1411 {
1412         int ret;
1413
1414         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1415         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1416
1417         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1418         if (ret)
1419                 return ret;
1420
1421         if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1422                 msleep(NVME_QUIRK_DELAY_AMOUNT);
1423
1424         return nvme_wait_ready(ctrl, cap, false);
1425 }
1426 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1427
1428 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1429 {
1430         /*
1431          * Default to a 4K page size, with the intention to update this
1432          * path in the future to accomodate architectures with differing
1433          * kernel and IO page sizes.
1434          */
1435         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1436         int ret;
1437
1438         if (page_shift < dev_page_min) {
1439                 dev_err(ctrl->device,
1440                         "Minimum device page size %u too large for host (%u)\n",
1441                         1 << dev_page_min, 1 << page_shift);
1442                 return -ENODEV;
1443         }
1444
1445         ctrl->page_size = 1 << page_shift;
1446
1447         ctrl->ctrl_config = NVME_CC_CSS_NVM;
1448         ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1449         ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1450         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1451         ctrl->ctrl_config |= NVME_CC_ENABLE;
1452
1453         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1454         if (ret)
1455                 return ret;
1456         return nvme_wait_ready(ctrl, cap, true);
1457 }
1458 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1459
1460 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1461 {
1462         unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1463         u32 csts;
1464         int ret;
1465
1466         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1467         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1468
1469         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1470         if (ret)
1471                 return ret;
1472
1473         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1474                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1475                         break;
1476
1477                 msleep(100);
1478                 if (fatal_signal_pending(current))
1479                         return -EINTR;
1480                 if (time_after(jiffies, timeout)) {
1481                         dev_err(ctrl->device,
1482                                 "Device shutdown incomplete; abort shutdown\n");
1483                         return -ENODEV;
1484                 }
1485         }
1486
1487         return ret;
1488 }
1489 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1490
1491 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1492                 struct request_queue *q)
1493 {
1494         bool vwc = false;
1495
1496         if (ctrl->max_hw_sectors) {
1497                 u32 max_segments =
1498                         (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1499
1500                 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1501                 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1502         }
1503         if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1504                 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1505         blk_queue_virt_boundary(q, ctrl->page_size - 1);
1506         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1507                 vwc = true;
1508         blk_queue_write_cache(q, vwc, vwc);
1509 }
1510
1511 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1512 {
1513         __le64 ts;
1514         int ret;
1515
1516         if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1517                 return 0;
1518
1519         ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1520         ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1521                         NULL);
1522         if (ret)
1523                 dev_warn_once(ctrl->device,
1524                         "could not set timestamp (%d)\n", ret);
1525         return ret;
1526 }
1527
1528 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1529 {
1530         /*
1531          * APST (Autonomous Power State Transition) lets us program a
1532          * table of power state transitions that the controller will
1533          * perform automatically.  We configure it with a simple
1534          * heuristic: we are willing to spend at most 2% of the time
1535          * transitioning between power states.  Therefore, when running
1536          * in any given state, we will enter the next lower-power
1537          * non-operational state after waiting 50 * (enlat + exlat)
1538          * microseconds, as long as that state's exit latency is under
1539          * the requested maximum latency.
1540          *
1541          * We will not autonomously enter any non-operational state for
1542          * which the total latency exceeds ps_max_latency_us.  Users
1543          * can set ps_max_latency_us to zero to turn off APST.
1544          */
1545
1546         unsigned apste;
1547         struct nvme_feat_auto_pst *table;
1548         u64 max_lat_us = 0;
1549         int max_ps = -1;
1550         int ret;
1551
1552         /*
1553          * If APST isn't supported or if we haven't been initialized yet,
1554          * then don't do anything.
1555          */
1556         if (!ctrl->apsta)
1557                 return 0;
1558
1559         if (ctrl->npss > 31) {
1560                 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1561                 return 0;
1562         }
1563
1564         table = kzalloc(sizeof(*table), GFP_KERNEL);
1565         if (!table)
1566                 return 0;
1567
1568         if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1569                 /* Turn off APST. */
1570                 apste = 0;
1571                 dev_dbg(ctrl->device, "APST disabled\n");
1572         } else {
1573                 __le64 target = cpu_to_le64(0);
1574                 int state;
1575
1576                 /*
1577                  * Walk through all states from lowest- to highest-power.
1578                  * According to the spec, lower-numbered states use more
1579                  * power.  NPSS, despite the name, is the index of the
1580                  * lowest-power state, not the number of states.
1581                  */
1582                 for (state = (int)ctrl->npss; state >= 0; state--) {
1583                         u64 total_latency_us, exit_latency_us, transition_ms;
1584
1585                         if (target)
1586                                 table->entries[state] = target;
1587
1588                         /*
1589                          * Don't allow transitions to the deepest state
1590                          * if it's quirked off.
1591                          */
1592                         if (state == ctrl->npss &&
1593                             (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1594                                 continue;
1595
1596                         /*
1597                          * Is this state a useful non-operational state for
1598                          * higher-power states to autonomously transition to?
1599                          */
1600                         if (!(ctrl->psd[state].flags &
1601                               NVME_PS_FLAGS_NON_OP_STATE))
1602                                 continue;
1603
1604                         exit_latency_us =
1605                                 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1606                         if (exit_latency_us > ctrl->ps_max_latency_us)
1607                                 continue;
1608
1609                         total_latency_us =
1610                                 exit_latency_us +
1611                                 le32_to_cpu(ctrl->psd[state].entry_lat);
1612
1613                         /*
1614                          * This state is good.  Use it as the APST idle
1615                          * target for higher power states.
1616                          */
1617                         transition_ms = total_latency_us + 19;
1618                         do_div(transition_ms, 20);
1619                         if (transition_ms > (1 << 24) - 1)
1620                                 transition_ms = (1 << 24) - 1;
1621
1622                         target = cpu_to_le64((state << 3) |
1623                                              (transition_ms << 8));
1624
1625                         if (max_ps == -1)
1626                                 max_ps = state;
1627
1628                         if (total_latency_us > max_lat_us)
1629                                 max_lat_us = total_latency_us;
1630                 }
1631
1632                 apste = 1;
1633
1634                 if (max_ps == -1) {
1635                         dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1636                 } else {
1637                         dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1638                                 max_ps, max_lat_us, (int)sizeof(*table), table);
1639                 }
1640         }
1641
1642         ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1643                                 table, sizeof(*table), NULL);
1644         if (ret)
1645                 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1646
1647         kfree(table);
1648         return ret;
1649 }
1650
1651 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1652 {
1653         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1654         u64 latency;
1655
1656         switch (val) {
1657         case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1658         case PM_QOS_LATENCY_ANY:
1659                 latency = U64_MAX;
1660                 break;
1661
1662         default:
1663                 latency = val;
1664         }
1665
1666         if (ctrl->ps_max_latency_us != latency) {
1667                 ctrl->ps_max_latency_us = latency;
1668                 nvme_configure_apst(ctrl);
1669         }
1670 }
1671
1672 struct nvme_core_quirk_entry {
1673         /*
1674          * NVMe model and firmware strings are padded with spaces.  For
1675          * simplicity, strings in the quirk table are padded with NULLs
1676          * instead.
1677          */
1678         u16 vid;
1679         const char *mn;
1680         const char *fr;
1681         unsigned long quirks;
1682 };
1683
1684 static const struct nvme_core_quirk_entry core_quirks[] = {
1685         {
1686                 /*
1687                  * This Toshiba device seems to die using any APST states.  See:
1688                  * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1689                  */
1690                 .vid = 0x1179,
1691                 .mn = "THNSF5256GPUK TOSHIBA",
1692                 .quirks = NVME_QUIRK_NO_APST,
1693         }
1694 };
1695
1696 /* match is null-terminated but idstr is space-padded. */
1697 static bool string_matches(const char *idstr, const char *match, size_t len)
1698 {
1699         size_t matchlen;
1700
1701         if (!match)
1702                 return true;
1703
1704         matchlen = strlen(match);
1705         WARN_ON_ONCE(matchlen > len);
1706
1707         if (memcmp(idstr, match, matchlen))
1708                 return false;
1709
1710         for (; matchlen < len; matchlen++)
1711                 if (idstr[matchlen] != ' ')
1712                         return false;
1713
1714         return true;
1715 }
1716
1717 static bool quirk_matches(const struct nvme_id_ctrl *id,
1718                           const struct nvme_core_quirk_entry *q)
1719 {
1720         return q->vid == le16_to_cpu(id->vid) &&
1721                 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1722                 string_matches(id->fr, q->fr, sizeof(id->fr));
1723 }
1724
1725 static void nvme_init_subnqn(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1726 {
1727         size_t nqnlen;
1728         int off;
1729
1730         nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
1731         if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
1732                 strcpy(ctrl->subnqn, id->subnqn);
1733                 return;
1734         }
1735
1736         if (ctrl->vs >= NVME_VS(1, 2, 1))
1737                 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
1738
1739         /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
1740         off = snprintf(ctrl->subnqn, NVMF_NQN_SIZE,
1741                         "nqn.2014.08.org.nvmexpress:%4x%4x",
1742                         le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
1743         memcpy(ctrl->subnqn + off, id->sn, sizeof(id->sn));
1744         off += sizeof(id->sn);
1745         memcpy(ctrl->subnqn + off, id->mn, sizeof(id->mn));
1746         off += sizeof(id->mn);
1747         memset(ctrl->subnqn + off, 0, sizeof(ctrl->subnqn) - off);
1748 }
1749
1750 static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log,
1751                         size_t size)
1752 {
1753         struct nvme_command c = { };
1754
1755         c.common.opcode = nvme_admin_get_log_page;
1756         c.common.nsid = cpu_to_le32(NVME_NSID_ALL);
1757         c.common.cdw10[0] = nvme_get_log_dw10(log_page, size);
1758
1759         return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
1760 }
1761
1762 /*
1763  * Initialize the cached copies of the Identify data and various controller
1764  * register in our nvme_ctrl structure.  This should be called as soon as
1765  * the admin queue is fully up and running.
1766  */
1767 int nvme_init_identify(struct nvme_ctrl *ctrl)
1768 {
1769         struct nvme_id_ctrl *id;
1770         u64 cap;
1771         int ret, page_shift;
1772         u32 max_hw_sectors;
1773         bool prev_apst_enabled;
1774
1775         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1776         if (ret) {
1777                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1778                 return ret;
1779         }
1780
1781         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1782         if (ret) {
1783                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1784                 return ret;
1785         }
1786         page_shift = NVME_CAP_MPSMIN(cap) + 12;
1787
1788         if (ctrl->vs >= NVME_VS(1, 1, 0))
1789                 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1790
1791         ret = nvme_identify_ctrl(ctrl, &id);
1792         if (ret) {
1793                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1794                 return -EIO;
1795         }
1796
1797         nvme_init_subnqn(ctrl, id);
1798
1799         if (!ctrl->identified) {
1800                 /*
1801                  * Check for quirks.  Quirk can depend on firmware version,
1802                  * so, in principle, the set of quirks present can change
1803                  * across a reset.  As a possible future enhancement, we
1804                  * could re-scan for quirks every time we reinitialize
1805                  * the device, but we'd have to make sure that the driver
1806                  * behaves intelligently if the quirks change.
1807                  */
1808
1809                 int i;
1810
1811                 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1812                         if (quirk_matches(id, &core_quirks[i]))
1813                                 ctrl->quirks |= core_quirks[i].quirks;
1814                 }
1815         }
1816
1817         if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1818                 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1819                 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1820         }
1821
1822         ctrl->oacs = le16_to_cpu(id->oacs);
1823         ctrl->vid = le16_to_cpu(id->vid);
1824         ctrl->oncs = le16_to_cpup(&id->oncs);
1825         atomic_set(&ctrl->abort_limit, id->acl + 1);
1826         ctrl->vwc = id->vwc;
1827         ctrl->cntlid = le16_to_cpup(&id->cntlid);
1828         memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1829         memcpy(ctrl->model, id->mn, sizeof(id->mn));
1830         memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1831         if (id->mdts)
1832                 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1833         else
1834                 max_hw_sectors = UINT_MAX;
1835         ctrl->max_hw_sectors =
1836                 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1837
1838         nvme_set_queue_limits(ctrl, ctrl->admin_q);
1839         ctrl->sgls = le32_to_cpu(id->sgls);
1840         ctrl->kas = le16_to_cpu(id->kas);
1841
1842         if (id->rtd3e) {
1843                 /* us -> s */
1844                 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
1845
1846                 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
1847                                                  shutdown_timeout, 60);
1848
1849                 if (ctrl->shutdown_timeout != shutdown_timeout)
1850                         dev_warn(ctrl->device,
1851                                  "Shutdown timeout set to %u seconds\n",
1852                                  ctrl->shutdown_timeout);
1853         } else
1854                 ctrl->shutdown_timeout = shutdown_timeout;
1855
1856         ctrl->npss = id->npss;
1857         ctrl->apsta = id->apsta;
1858         prev_apst_enabled = ctrl->apst_enabled;
1859         if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1860                 if (force_apst && id->apsta) {
1861                         dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1862                         ctrl->apst_enabled = true;
1863                 } else {
1864                         ctrl->apst_enabled = false;
1865                 }
1866         } else {
1867                 ctrl->apst_enabled = id->apsta;
1868         }
1869         memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1870
1871         if (ctrl->ops->flags & NVME_F_FABRICS) {
1872                 ctrl->icdoff = le16_to_cpu(id->icdoff);
1873                 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1874                 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1875                 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1876
1877                 /*
1878                  * In fabrics we need to verify the cntlid matches the
1879                  * admin connect
1880                  */
1881                 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
1882                         ret = -EINVAL;
1883                         goto out_free;
1884                 }
1885
1886                 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1887                         dev_err(ctrl->device,
1888                                 "keep-alive support is mandatory for fabrics\n");
1889                         ret = -EINVAL;
1890                         goto out_free;
1891                 }
1892         } else {
1893                 ctrl->cntlid = le16_to_cpu(id->cntlid);
1894                 ctrl->hmpre = le32_to_cpu(id->hmpre);
1895                 ctrl->hmmin = le32_to_cpu(id->hmmin);
1896                 ctrl->hmminds = le32_to_cpu(id->hmminds);
1897                 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
1898         }
1899
1900         kfree(id);
1901
1902         if (ctrl->apst_enabled && !prev_apst_enabled)
1903                 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1904         else if (!ctrl->apst_enabled && prev_apst_enabled)
1905                 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1906
1907         ret = nvme_configure_apst(ctrl);
1908         if (ret < 0)
1909                 return ret;
1910         
1911         ret = nvme_configure_timestamp(ctrl);
1912         if (ret < 0)
1913                 return ret;
1914
1915         ret = nvme_configure_directives(ctrl);
1916         if (ret < 0)
1917                 return ret;
1918
1919         ctrl->identified = true;
1920
1921         return 0;
1922
1923 out_free:
1924         kfree(id);
1925         return ret;
1926 }
1927 EXPORT_SYMBOL_GPL(nvme_init_identify);
1928
1929 static int nvme_dev_open(struct inode *inode, struct file *file)
1930 {
1931         struct nvme_ctrl *ctrl =
1932                 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
1933
1934         if (ctrl->state != NVME_CTRL_LIVE)
1935                 return -EWOULDBLOCK;
1936         file->private_data = ctrl;
1937         return 0;
1938 }
1939
1940 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1941 {
1942         struct nvme_ns *ns;
1943         int ret;
1944
1945         mutex_lock(&ctrl->namespaces_mutex);
1946         if (list_empty(&ctrl->namespaces)) {
1947                 ret = -ENOTTY;
1948                 goto out_unlock;
1949         }
1950
1951         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1952         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1953                 dev_warn(ctrl->device,
1954                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1955                 ret = -EINVAL;
1956                 goto out_unlock;
1957         }
1958
1959         dev_warn(ctrl->device,
1960                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1961         kref_get(&ns->kref);
1962         mutex_unlock(&ctrl->namespaces_mutex);
1963
1964         ret = nvme_user_cmd(ctrl, ns, argp);
1965         nvme_put_ns(ns);
1966         return ret;
1967
1968 out_unlock:
1969         mutex_unlock(&ctrl->namespaces_mutex);
1970         return ret;
1971 }
1972
1973 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1974                 unsigned long arg)
1975 {
1976         struct nvme_ctrl *ctrl = file->private_data;
1977         void __user *argp = (void __user *)arg;
1978
1979         switch (cmd) {
1980         case NVME_IOCTL_ADMIN_CMD:
1981                 return nvme_user_cmd(ctrl, NULL, argp);
1982         case NVME_IOCTL_IO_CMD:
1983                 return nvme_dev_user_cmd(ctrl, argp);
1984         case NVME_IOCTL_RESET:
1985                 dev_warn(ctrl->device, "resetting controller\n");
1986                 return nvme_reset_ctrl_sync(ctrl);
1987         case NVME_IOCTL_SUBSYS_RESET:
1988                 return nvme_reset_subsystem(ctrl);
1989         case NVME_IOCTL_RESCAN:
1990                 nvme_queue_scan(ctrl);
1991                 return 0;
1992         default:
1993                 return -ENOTTY;
1994         }
1995 }
1996
1997 static const struct file_operations nvme_dev_fops = {
1998         .owner          = THIS_MODULE,
1999         .open           = nvme_dev_open,
2000         .unlocked_ioctl = nvme_dev_ioctl,
2001         .compat_ioctl   = nvme_dev_ioctl,
2002 };
2003
2004 static ssize_t nvme_sysfs_reset(struct device *dev,
2005                                 struct device_attribute *attr, const char *buf,
2006                                 size_t count)
2007 {
2008         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2009         int ret;
2010
2011         ret = nvme_reset_ctrl_sync(ctrl);
2012         if (ret < 0)
2013                 return ret;
2014         return count;
2015 }
2016 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2017
2018 static ssize_t nvme_sysfs_rescan(struct device *dev,
2019                                 struct device_attribute *attr, const char *buf,
2020                                 size_t count)
2021 {
2022         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2023
2024         nvme_queue_scan(ctrl);
2025         return count;
2026 }
2027 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2028
2029 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2030                                                                 char *buf)
2031 {
2032         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2033         struct nvme_ctrl *ctrl = ns->ctrl;
2034         int serial_len = sizeof(ctrl->serial);
2035         int model_len = sizeof(ctrl->model);
2036
2037         if (!uuid_is_null(&ns->uuid))
2038                 return sprintf(buf, "uuid.%pU\n", &ns->uuid);
2039
2040         if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2041                 return sprintf(buf, "eui.%16phN\n", ns->nguid);
2042
2043         if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2044                 return sprintf(buf, "eui.%8phN\n", ns->eui);
2045
2046         while (serial_len > 0 && (ctrl->serial[serial_len - 1] == ' ' ||
2047                                   ctrl->serial[serial_len - 1] == '\0'))
2048                 serial_len--;
2049         while (model_len > 0 && (ctrl->model[model_len - 1] == ' ' ||
2050                                  ctrl->model[model_len - 1] == '\0'))
2051                 model_len--;
2052
2053         return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
2054                 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
2055 }
2056 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
2057
2058 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2059                           char *buf)
2060 {
2061         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2062         return sprintf(buf, "%pU\n", ns->nguid);
2063 }
2064 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
2065
2066 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2067                                                                 char *buf)
2068 {
2069         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2070
2071         /* For backward compatibility expose the NGUID to userspace if
2072          * we have no UUID set
2073          */
2074         if (uuid_is_null(&ns->uuid)) {
2075                 printk_ratelimited(KERN_WARNING
2076                                    "No UUID available providing old NGUID\n");
2077                 return sprintf(buf, "%pU\n", ns->nguid);
2078         }
2079         return sprintf(buf, "%pU\n", &ns->uuid);
2080 }
2081 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
2082
2083 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2084                                                                 char *buf)
2085 {
2086         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2087         return sprintf(buf, "%8phd\n", ns->eui);
2088 }
2089 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
2090
2091 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2092                                                                 char *buf)
2093 {
2094         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2095         return sprintf(buf, "%d\n", ns->ns_id);
2096 }
2097 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
2098
2099 static struct attribute *nvme_ns_attrs[] = {
2100         &dev_attr_wwid.attr,
2101         &dev_attr_uuid.attr,
2102         &dev_attr_nguid.attr,
2103         &dev_attr_eui.attr,
2104         &dev_attr_nsid.attr,
2105         NULL,
2106 };
2107
2108 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2109                 struct attribute *a, int n)
2110 {
2111         struct device *dev = container_of(kobj, struct device, kobj);
2112         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2113
2114         if (a == &dev_attr_uuid.attr) {
2115                 if (uuid_is_null(&ns->uuid) ||
2116                     !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2117                         return 0;
2118         }
2119         if (a == &dev_attr_nguid.attr) {
2120                 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2121                         return 0;
2122         }
2123         if (a == &dev_attr_eui.attr) {
2124                 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2125                         return 0;
2126         }
2127         return a->mode;
2128 }
2129
2130 static const struct attribute_group nvme_ns_attr_group = {
2131         .attrs          = nvme_ns_attrs,
2132         .is_visible     = nvme_ns_attrs_are_visible,
2133 };
2134
2135 #define nvme_show_str_function(field)                                           \
2136 static ssize_t  field##_show(struct device *dev,                                \
2137                             struct device_attribute *attr, char *buf)           \
2138 {                                                                               \
2139         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
2140         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);   \
2141 }                                                                               \
2142 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2143
2144 #define nvme_show_int_function(field)                                           \
2145 static ssize_t  field##_show(struct device *dev,                                \
2146                             struct device_attribute *attr, char *buf)           \
2147 {                                                                               \
2148         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
2149         return sprintf(buf, "%d\n", ctrl->field);       \
2150 }                                                                               \
2151 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2152
2153 nvme_show_str_function(model);
2154 nvme_show_str_function(serial);
2155 nvme_show_str_function(firmware_rev);
2156 nvme_show_int_function(cntlid);
2157
2158 static ssize_t nvme_sysfs_delete(struct device *dev,
2159                                 struct device_attribute *attr, const char *buf,
2160                                 size_t count)
2161 {
2162         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2163
2164         if (device_remove_file_self(dev, attr))
2165                 nvme_delete_ctrl_sync(ctrl);
2166         return count;
2167 }
2168 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2169
2170 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2171                                          struct device_attribute *attr,
2172                                          char *buf)
2173 {
2174         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2175
2176         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2177 }
2178 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2179
2180 static ssize_t nvme_sysfs_show_state(struct device *dev,
2181                                      struct device_attribute *attr,
2182                                      char *buf)
2183 {
2184         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2185         static const char *const state_name[] = {
2186                 [NVME_CTRL_NEW]         = "new",
2187                 [NVME_CTRL_LIVE]        = "live",
2188                 [NVME_CTRL_RESETTING]   = "resetting",
2189                 [NVME_CTRL_RECONNECTING]= "reconnecting",
2190                 [NVME_CTRL_DELETING]    = "deleting",
2191                 [NVME_CTRL_DEAD]        = "dead",
2192         };
2193
2194         if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2195             state_name[ctrl->state])
2196                 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2197
2198         return sprintf(buf, "unknown state\n");
2199 }
2200
2201 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2202
2203 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2204                                          struct device_attribute *attr,
2205                                          char *buf)
2206 {
2207         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2208
2209         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subnqn);
2210 }
2211 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2212
2213 static ssize_t nvme_sysfs_show_address(struct device *dev,
2214                                          struct device_attribute *attr,
2215                                          char *buf)
2216 {
2217         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2218
2219         return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2220 }
2221 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2222
2223 static struct attribute *nvme_dev_attrs[] = {
2224         &dev_attr_reset_controller.attr,
2225         &dev_attr_rescan_controller.attr,
2226         &dev_attr_model.attr,
2227         &dev_attr_serial.attr,
2228         &dev_attr_firmware_rev.attr,
2229         &dev_attr_cntlid.attr,
2230         &dev_attr_delete_controller.attr,
2231         &dev_attr_transport.attr,
2232         &dev_attr_subsysnqn.attr,
2233         &dev_attr_address.attr,
2234         &dev_attr_state.attr,
2235         NULL
2236 };
2237
2238 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2239                 struct attribute *a, int n)
2240 {
2241         struct device *dev = container_of(kobj, struct device, kobj);
2242         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2243
2244         if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2245                 return 0;
2246         if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2247                 return 0;
2248
2249         return a->mode;
2250 }
2251
2252 static struct attribute_group nvme_dev_attrs_group = {
2253         .attrs          = nvme_dev_attrs,
2254         .is_visible     = nvme_dev_attrs_are_visible,
2255 };
2256
2257 static const struct attribute_group *nvme_dev_attr_groups[] = {
2258         &nvme_dev_attrs_group,
2259         NULL,
2260 };
2261
2262 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2263 {
2264         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2265         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2266
2267         return nsa->ns_id - nsb->ns_id;
2268 }
2269
2270 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2271 {
2272         struct nvme_ns *ns, *ret = NULL;
2273
2274         mutex_lock(&ctrl->namespaces_mutex);
2275         list_for_each_entry(ns, &ctrl->namespaces, list) {
2276                 if (ns->ns_id == nsid) {
2277                         if (!kref_get_unless_zero(&ns->kref))
2278                                 continue;
2279                         ret = ns;
2280                         break;
2281                 }
2282                 if (ns->ns_id > nsid)
2283                         break;
2284         }
2285         mutex_unlock(&ctrl->namespaces_mutex);
2286         return ret;
2287 }
2288
2289 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2290 {
2291         struct streams_directive_params s;
2292         int ret;
2293
2294         if (!ctrl->nr_streams)
2295                 return 0;
2296
2297         ret = nvme_get_stream_params(ctrl, &s, ns->ns_id);
2298         if (ret)
2299                 return ret;
2300
2301         ns->sws = le32_to_cpu(s.sws);
2302         ns->sgs = le16_to_cpu(s.sgs);
2303
2304         if (ns->sws) {
2305                 unsigned int bs = 1 << ns->lba_shift;
2306
2307                 blk_queue_io_min(ns->queue, bs * ns->sws);
2308                 if (ns->sgs)
2309                         blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2310         }
2311
2312         return 0;
2313 }
2314
2315 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2316 {
2317         struct nvme_ns *ns;
2318         struct gendisk *disk;
2319         struct nvme_id_ns *id;
2320         char disk_name[DISK_NAME_LEN];
2321         int node = dev_to_node(ctrl->dev);
2322
2323         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2324         if (!ns)
2325                 return;
2326
2327         ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2328         if (ns->instance < 0)
2329                 goto out_free_ns;
2330
2331         ns->queue = blk_mq_init_queue(ctrl->tagset);
2332         if (IS_ERR(ns->queue))
2333                 goto out_release_instance;
2334         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2335         ns->queue->queuedata = ns;
2336         ns->ctrl = ctrl;
2337
2338         kref_init(&ns->kref);
2339         ns->ns_id = nsid;
2340         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2341
2342         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2343         nvme_set_queue_limits(ctrl, ns->queue);
2344         nvme_setup_streams_ns(ctrl, ns);
2345
2346         sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2347
2348         id = nvme_identify_ns(ctrl, nsid);
2349         if (!id)
2350                 goto out_free_queue;
2351
2352         if (id->ncap == 0)
2353                 goto out_free_id;
2354
2355         nvme_report_ns_ids(ctrl, ns->ns_id, id, ns->eui, ns->nguid, &ns->uuid);
2356
2357         if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
2358                 if (nvme_nvm_register(ns, disk_name, node)) {
2359                         dev_warn(ctrl->device, "LightNVM init failure\n");
2360                         goto out_free_id;
2361                 }
2362         }
2363
2364         disk = alloc_disk_node(0, node);
2365         if (!disk)
2366                 goto out_free_id;
2367
2368         disk->fops = &nvme_fops;
2369         disk->private_data = ns;
2370         disk->queue = ns->queue;
2371         disk->flags = GENHD_FL_EXT_DEVT;
2372         memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2373         ns->disk = disk;
2374
2375         __nvme_revalidate_disk(disk, id);
2376
2377         mutex_lock(&ctrl->namespaces_mutex);
2378         list_add_tail(&ns->list, &ctrl->namespaces);
2379         mutex_unlock(&ctrl->namespaces_mutex);
2380
2381         nvme_get_ctrl(ctrl);
2382
2383         kfree(id);
2384
2385         device_add_disk(ctrl->device, ns->disk);
2386         if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2387                                         &nvme_ns_attr_group))
2388                 pr_warn("%s: failed to create sysfs group for identification\n",
2389                         ns->disk->disk_name);
2390         if (ns->ndev && nvme_nvm_register_sysfs(ns))
2391                 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2392                         ns->disk->disk_name);
2393         return;
2394  out_free_id:
2395         kfree(id);
2396  out_free_queue:
2397         blk_cleanup_queue(ns->queue);
2398  out_release_instance:
2399         ida_simple_remove(&ctrl->ns_ida, ns->instance);
2400  out_free_ns:
2401         kfree(ns);
2402 }
2403
2404 static void nvme_ns_remove(struct nvme_ns *ns)
2405 {
2406         if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2407                 return;
2408
2409         if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2410                 if (blk_get_integrity(ns->disk))
2411                         blk_integrity_unregister(ns->disk);
2412                 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2413                                         &nvme_ns_attr_group);
2414                 if (ns->ndev)
2415                         nvme_nvm_unregister_sysfs(ns);
2416                 del_gendisk(ns->disk);
2417                 blk_cleanup_queue(ns->queue);
2418         }
2419
2420         mutex_lock(&ns->ctrl->namespaces_mutex);
2421         list_del_init(&ns->list);
2422         mutex_unlock(&ns->ctrl->namespaces_mutex);
2423
2424         nvme_put_ns(ns);
2425 }
2426
2427 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2428 {
2429         struct nvme_ns *ns;
2430
2431         ns = nvme_find_get_ns(ctrl, nsid);
2432         if (ns) {
2433                 if (ns->disk && revalidate_disk(ns->disk))
2434                         nvme_ns_remove(ns);
2435                 nvme_put_ns(ns);
2436         } else
2437                 nvme_alloc_ns(ctrl, nsid);
2438 }
2439
2440 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2441                                         unsigned nsid)
2442 {
2443         struct nvme_ns *ns, *next;
2444
2445         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2446                 if (ns->ns_id > nsid)
2447                         nvme_ns_remove(ns);
2448         }
2449 }
2450
2451 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2452 {
2453         struct nvme_ns *ns;
2454         __le32 *ns_list;
2455         unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2456         int ret = 0;
2457
2458         ns_list = kzalloc(0x1000, GFP_KERNEL);
2459         if (!ns_list)
2460                 return -ENOMEM;
2461
2462         for (i = 0; i < num_lists; i++) {
2463                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2464                 if (ret)
2465                         goto free;
2466
2467                 for (j = 0; j < min(nn, 1024U); j++) {
2468                         nsid = le32_to_cpu(ns_list[j]);
2469                         if (!nsid)
2470                                 goto out;
2471
2472                         nvme_validate_ns(ctrl, nsid);
2473
2474                         while (++prev < nsid) {
2475                                 ns = nvme_find_get_ns(ctrl, prev);
2476                                 if (ns) {
2477                                         nvme_ns_remove(ns);
2478                                         nvme_put_ns(ns);
2479                                 }
2480                         }
2481                 }
2482                 nn -= j;
2483         }
2484  out:
2485         nvme_remove_invalid_namespaces(ctrl, prev);
2486  free:
2487         kfree(ns_list);
2488         return ret;
2489 }
2490
2491 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2492 {
2493         unsigned i;
2494
2495         for (i = 1; i <= nn; i++)
2496                 nvme_validate_ns(ctrl, i);
2497
2498         nvme_remove_invalid_namespaces(ctrl, nn);
2499 }
2500
2501 static void nvme_scan_work(struct work_struct *work)
2502 {
2503         struct nvme_ctrl *ctrl =
2504                 container_of(work, struct nvme_ctrl, scan_work);
2505         struct nvme_id_ctrl *id;
2506         unsigned nn;
2507
2508         if (ctrl->state != NVME_CTRL_LIVE)
2509                 return;
2510
2511         if (nvme_identify_ctrl(ctrl, &id))
2512                 return;
2513
2514         nn = le32_to_cpu(id->nn);
2515         if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2516             !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2517                 if (!nvme_scan_ns_list(ctrl, nn))
2518                         goto done;
2519         }
2520         nvme_scan_ns_sequential(ctrl, nn);
2521  done:
2522         mutex_lock(&ctrl->namespaces_mutex);
2523         list_sort(NULL, &ctrl->namespaces, ns_cmp);
2524         mutex_unlock(&ctrl->namespaces_mutex);
2525         kfree(id);
2526 }
2527
2528 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2529 {
2530         /*
2531          * Do not queue new scan work when a controller is reset during
2532          * removal.
2533          */
2534         if (ctrl->state == NVME_CTRL_LIVE)
2535                 queue_work(nvme_wq, &ctrl->scan_work);
2536 }
2537 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2538
2539 /*
2540  * This function iterates the namespace list unlocked to allow recovery from
2541  * controller failure. It is up to the caller to ensure the namespace list is
2542  * not modified by scan work while this function is executing.
2543  */
2544 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2545 {
2546         struct nvme_ns *ns, *next;
2547
2548         /*
2549          * The dead states indicates the controller was not gracefully
2550          * disconnected. In that case, we won't be able to flush any data while
2551          * removing the namespaces' disks; fail all the queues now to avoid
2552          * potentially having to clean up the failed sync later.
2553          */
2554         if (ctrl->state == NVME_CTRL_DEAD)
2555                 nvme_kill_queues(ctrl);
2556
2557         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2558                 nvme_ns_remove(ns);
2559 }
2560 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2561
2562 static void nvme_async_event_work(struct work_struct *work)
2563 {
2564         struct nvme_ctrl *ctrl =
2565                 container_of(work, struct nvme_ctrl, async_event_work);
2566
2567         spin_lock_irq(&ctrl->lock);
2568         while (ctrl->state == NVME_CTRL_LIVE && ctrl->event_limit > 0) {
2569                 int aer_idx = --ctrl->event_limit;
2570
2571                 spin_unlock_irq(&ctrl->lock);
2572                 ctrl->ops->submit_async_event(ctrl, aer_idx);
2573                 spin_lock_irq(&ctrl->lock);
2574         }
2575         spin_unlock_irq(&ctrl->lock);
2576 }
2577
2578 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
2579 {
2580
2581         u32 csts;
2582
2583         if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
2584                 return false;
2585
2586         if (csts == ~0)
2587                 return false;
2588
2589         return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
2590 }
2591
2592 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
2593 {
2594         struct nvme_fw_slot_info_log *log;
2595
2596         log = kmalloc(sizeof(*log), GFP_KERNEL);
2597         if (!log)
2598                 return;
2599
2600         if (nvme_get_log(ctrl, NVME_LOG_FW_SLOT, log, sizeof(*log)))
2601                 dev_warn(ctrl->device,
2602                                 "Get FW SLOT INFO log error\n");
2603         kfree(log);
2604 }
2605
2606 static void nvme_fw_act_work(struct work_struct *work)
2607 {
2608         struct nvme_ctrl *ctrl = container_of(work,
2609                                 struct nvme_ctrl, fw_act_work);
2610         unsigned long fw_act_timeout;
2611
2612         if (ctrl->mtfa)
2613                 fw_act_timeout = jiffies +
2614                                 msecs_to_jiffies(ctrl->mtfa * 100);
2615         else
2616                 fw_act_timeout = jiffies +
2617                                 msecs_to_jiffies(admin_timeout * 1000);
2618
2619         nvme_stop_queues(ctrl);
2620         while (nvme_ctrl_pp_status(ctrl)) {
2621                 if (time_after(jiffies, fw_act_timeout)) {
2622                         dev_warn(ctrl->device,
2623                                 "Fw activation timeout, reset controller\n");
2624                         nvme_reset_ctrl(ctrl);
2625                         break;
2626                 }
2627                 msleep(100);
2628         }
2629
2630         if (ctrl->state != NVME_CTRL_LIVE)
2631                 return;
2632
2633         nvme_start_queues(ctrl);
2634         /* read FW slot information to clear the AER */
2635         nvme_get_fw_slot_info(ctrl);
2636 }
2637
2638 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2639                 union nvme_result *res)
2640 {
2641         u32 result = le32_to_cpu(res->u32);
2642         bool done = true;
2643
2644         switch (le16_to_cpu(status) >> 1) {
2645         case NVME_SC_SUCCESS:
2646                 done = false;
2647                 /*FALLTHRU*/
2648         case NVME_SC_ABORT_REQ:
2649                 ++ctrl->event_limit;
2650                 if (ctrl->state == NVME_CTRL_LIVE)
2651                         queue_work(nvme_wq, &ctrl->async_event_work);
2652                 break;
2653         default:
2654                 break;
2655         }
2656
2657         if (done)
2658                 return;
2659
2660         switch (result & 0xff07) {
2661         case NVME_AER_NOTICE_NS_CHANGED:
2662                 dev_info(ctrl->device, "rescanning\n");
2663                 nvme_queue_scan(ctrl);
2664                 break;
2665         case NVME_AER_NOTICE_FW_ACT_STARTING:
2666                 queue_work(nvme_wq, &ctrl->fw_act_work);
2667                 break;
2668         default:
2669                 dev_warn(ctrl->device, "async event result %08x\n", result);
2670         }
2671 }
2672 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2673
2674 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2675 {
2676         ctrl->event_limit = NVME_NR_AERS;
2677         queue_work(nvme_wq, &ctrl->async_event_work);
2678 }
2679 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2680
2681 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
2682 {
2683         nvme_stop_keep_alive(ctrl);
2684         flush_work(&ctrl->async_event_work);
2685         flush_work(&ctrl->scan_work);
2686         cancel_work_sync(&ctrl->fw_act_work);
2687 }
2688 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
2689
2690 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
2691 {
2692         if (ctrl->kato)
2693                 nvme_start_keep_alive(ctrl);
2694
2695         if (ctrl->queue_count > 1) {
2696                 nvme_queue_scan(ctrl);
2697                 nvme_queue_async_events(ctrl);
2698                 nvme_start_queues(ctrl);
2699         }
2700 }
2701 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
2702
2703 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2704 {
2705         cdev_device_del(&ctrl->cdev, ctrl->device);
2706 }
2707 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2708
2709 static void nvme_free_ctrl(struct device *dev)
2710 {
2711         struct nvme_ctrl *ctrl =
2712                 container_of(dev, struct nvme_ctrl, ctrl_device);
2713
2714         ida_simple_remove(&nvme_instance_ida, ctrl->instance);
2715         ida_destroy(&ctrl->ns_ida);
2716
2717         ctrl->ops->free_ctrl(ctrl);
2718 }
2719
2720 /*
2721  * Initialize a NVMe controller structures.  This needs to be called during
2722  * earliest initialization so that we have the initialized structured around
2723  * during probing.
2724  */
2725 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2726                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2727 {
2728         int ret;
2729
2730         ctrl->state = NVME_CTRL_NEW;
2731         spin_lock_init(&ctrl->lock);
2732         INIT_LIST_HEAD(&ctrl->namespaces);
2733         mutex_init(&ctrl->namespaces_mutex);
2734         ctrl->dev = dev;
2735         ctrl->ops = ops;
2736         ctrl->quirks = quirks;
2737         INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2738         INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2739         INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
2740         INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
2741
2742         ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
2743         if (ret < 0)
2744                 goto out;
2745         ctrl->instance = ret;
2746
2747         device_initialize(&ctrl->ctrl_device);
2748         ctrl->device = &ctrl->ctrl_device;
2749         ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
2750         ctrl->device->class = nvme_class;
2751         ctrl->device->parent = ctrl->dev;
2752         ctrl->device->groups = nvme_dev_attr_groups;
2753         ctrl->device->release = nvme_free_ctrl;
2754         dev_set_drvdata(ctrl->device, ctrl);
2755         ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
2756         if (ret)
2757                 goto out_release_instance;
2758
2759         cdev_init(&ctrl->cdev, &nvme_dev_fops);
2760         ctrl->cdev.owner = ops->module;
2761         ret = cdev_device_add(&ctrl->cdev, ctrl->device);
2762         if (ret)
2763                 goto out_free_name;
2764
2765         ida_init(&ctrl->ns_ida);
2766
2767         /*
2768          * Initialize latency tolerance controls.  The sysfs files won't
2769          * be visible to userspace unless the device actually supports APST.
2770          */
2771         ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2772         dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2773                 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2774
2775         return 0;
2776 out_free_name:
2777         kfree_const(dev->kobj.name);
2778 out_release_instance:
2779         ida_simple_remove(&nvme_instance_ida, ctrl->instance);
2780 out:
2781         return ret;
2782 }
2783 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2784
2785 /**
2786  * nvme_kill_queues(): Ends all namespace queues
2787  * @ctrl: the dead controller that needs to end
2788  *
2789  * Call this function when the driver determines it is unable to get the
2790  * controller in a state capable of servicing IO.
2791  */
2792 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2793 {
2794         struct nvme_ns *ns;
2795
2796         mutex_lock(&ctrl->namespaces_mutex);
2797
2798         /* Forcibly unquiesce queues to avoid blocking dispatch */
2799         if (ctrl->admin_q)
2800                 blk_mq_unquiesce_queue(ctrl->admin_q);
2801
2802         list_for_each_entry(ns, &ctrl->namespaces, list) {
2803                 /*
2804                  * Revalidating a dead namespace sets capacity to 0. This will
2805                  * end buffered writers dirtying pages that can't be synced.
2806                  */
2807                 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2808                         continue;
2809                 revalidate_disk(ns->disk);
2810                 blk_set_queue_dying(ns->queue);
2811
2812                 /* Forcibly unquiesce queues to avoid blocking dispatch */
2813                 blk_mq_unquiesce_queue(ns->queue);
2814         }
2815         mutex_unlock(&ctrl->namespaces_mutex);
2816 }
2817 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2818
2819 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2820 {
2821         struct nvme_ns *ns;
2822
2823         mutex_lock(&ctrl->namespaces_mutex);
2824         list_for_each_entry(ns, &ctrl->namespaces, list)
2825                 blk_mq_unfreeze_queue(ns->queue);
2826         mutex_unlock(&ctrl->namespaces_mutex);
2827 }
2828 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2829
2830 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2831 {
2832         struct nvme_ns *ns;
2833
2834         mutex_lock(&ctrl->namespaces_mutex);
2835         list_for_each_entry(ns, &ctrl->namespaces, list) {
2836                 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2837                 if (timeout <= 0)
2838                         break;
2839         }
2840         mutex_unlock(&ctrl->namespaces_mutex);
2841 }
2842 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2843
2844 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2845 {
2846         struct nvme_ns *ns;
2847
2848         mutex_lock(&ctrl->namespaces_mutex);
2849         list_for_each_entry(ns, &ctrl->namespaces, list)
2850                 blk_mq_freeze_queue_wait(ns->queue);
2851         mutex_unlock(&ctrl->namespaces_mutex);
2852 }
2853 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2854
2855 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2856 {
2857         struct nvme_ns *ns;
2858
2859         mutex_lock(&ctrl->namespaces_mutex);
2860         list_for_each_entry(ns, &ctrl->namespaces, list)
2861                 blk_freeze_queue_start(ns->queue);
2862         mutex_unlock(&ctrl->namespaces_mutex);
2863 }
2864 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2865
2866 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2867 {
2868         struct nvme_ns *ns;
2869
2870         mutex_lock(&ctrl->namespaces_mutex);
2871         list_for_each_entry(ns, &ctrl->namespaces, list)
2872                 blk_mq_quiesce_queue(ns->queue);
2873         mutex_unlock(&ctrl->namespaces_mutex);
2874 }
2875 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2876
2877 void nvme_start_queues(struct nvme_ctrl *ctrl)
2878 {
2879         struct nvme_ns *ns;
2880
2881         mutex_lock(&ctrl->namespaces_mutex);
2882         list_for_each_entry(ns, &ctrl->namespaces, list)
2883                 blk_mq_unquiesce_queue(ns->queue);
2884         mutex_unlock(&ctrl->namespaces_mutex);
2885 }
2886 EXPORT_SYMBOL_GPL(nvme_start_queues);
2887
2888 int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set)
2889 {
2890         if (!ctrl->ops->reinit_request)
2891                 return 0;
2892
2893         return blk_mq_tagset_iter(set, set->driver_data,
2894                         ctrl->ops->reinit_request);
2895 }
2896 EXPORT_SYMBOL_GPL(nvme_reinit_tagset);
2897
2898 int __init nvme_core_init(void)
2899 {
2900         int result;
2901
2902         nvme_wq = alloc_workqueue("nvme-wq",
2903                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2904         if (!nvme_wq)
2905                 return -ENOMEM;
2906
2907         result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
2908         if (result < 0)
2909                 goto destroy_wq;
2910
2911         nvme_class = class_create(THIS_MODULE, "nvme");
2912         if (IS_ERR(nvme_class)) {
2913                 result = PTR_ERR(nvme_class);
2914                 goto unregister_chrdev;
2915         }
2916
2917         return 0;
2918
2919 unregister_chrdev:
2920         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
2921 destroy_wq:
2922         destroy_workqueue(nvme_wq);
2923         return result;
2924 }
2925
2926 void nvme_core_exit(void)
2927 {
2928         class_destroy(nvme_class);
2929         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
2930         destroy_workqueue(nvme_wq);
2931 }
2932
2933 MODULE_LICENSE("GPL");
2934 MODULE_VERSION("1.0");
2935 module_init(nvme_core_init);
2936 module_exit(nvme_core_exit);