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