]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/nvme/host/core.c
Merge remote-tracking branch 'device-mapper/for-next'
[karo-tx-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 <scsi/sg.h>
30 #include <asm/unaligned.h>
31
32 #include "nvme.h"
33
34 #define NVME_MINORS             (1U << MINORBITS)
35
36 unsigned char admin_timeout = 60;
37 module_param(admin_timeout, byte, 0644);
38 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
39 EXPORT_SYMBOL_GPL(admin_timeout);
40
41 unsigned char nvme_io_timeout = 30;
42 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
43 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
44 EXPORT_SYMBOL_GPL(nvme_io_timeout);
45
46 unsigned char shutdown_timeout = 5;
47 module_param(shutdown_timeout, byte, 0644);
48 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
49
50 static int nvme_major;
51 module_param(nvme_major, int, 0);
52
53 static int nvme_char_major;
54 module_param(nvme_char_major, int, 0);
55
56 static LIST_HEAD(nvme_ctrl_list);
57 static DEFINE_SPINLOCK(dev_list_lock);
58
59 static struct class *nvme_class;
60
61 static void nvme_free_ns(struct kref *kref)
62 {
63         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
64
65         if (ns->type == NVME_NS_LIGHTNVM)
66                 nvme_nvm_unregister(ns->queue, ns->disk->disk_name);
67
68         spin_lock(&dev_list_lock);
69         ns->disk->private_data = NULL;
70         spin_unlock(&dev_list_lock);
71
72         nvme_put_ctrl(ns->ctrl);
73         put_disk(ns->disk);
74         kfree(ns);
75 }
76
77 static void nvme_put_ns(struct nvme_ns *ns)
78 {
79         kref_put(&ns->kref, nvme_free_ns);
80 }
81
82 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
83 {
84         struct nvme_ns *ns;
85
86         spin_lock(&dev_list_lock);
87         ns = disk->private_data;
88         if (ns) {
89                 if (!kref_get_unless_zero(&ns->kref))
90                         goto fail;
91                 if (!try_module_get(ns->ctrl->ops->module))
92                         goto fail_put_ns;
93         }
94         spin_unlock(&dev_list_lock);
95
96         return ns;
97
98 fail_put_ns:
99         kref_put(&ns->kref, nvme_free_ns);
100 fail:
101         spin_unlock(&dev_list_lock);
102         return NULL;
103 }
104
105 void nvme_requeue_req(struct request *req)
106 {
107         unsigned long flags;
108
109         blk_mq_requeue_request(req);
110         spin_lock_irqsave(req->q->queue_lock, flags);
111         if (!blk_queue_stopped(req->q))
112                 blk_mq_kick_requeue_list(req->q);
113         spin_unlock_irqrestore(req->q->queue_lock, flags);
114 }
115 EXPORT_SYMBOL_GPL(nvme_requeue_req);
116
117 struct request *nvme_alloc_request(struct request_queue *q,
118                 struct nvme_command *cmd, unsigned int flags)
119 {
120         bool write = cmd->common.opcode & 1;
121         struct request *req;
122
123         req = blk_mq_alloc_request(q, write, flags);
124         if (IS_ERR(req))
125                 return req;
126
127         req->cmd_type = REQ_TYPE_DRV_PRIV;
128         req->cmd_flags |= REQ_FAILFAST_DRIVER;
129         req->__data_len = 0;
130         req->__sector = (sector_t) -1;
131         req->bio = req->biotail = NULL;
132
133         req->cmd = (unsigned char *)cmd;
134         req->cmd_len = sizeof(struct nvme_command);
135         req->special = (void *)0;
136
137         return req;
138 }
139 EXPORT_SYMBOL_GPL(nvme_alloc_request);
140
141 /*
142  * Returns 0 on success.  If the result is negative, it's a Linux error code;
143  * if the result is positive, it's an NVM Express status code
144  */
145 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
146                 void *buffer, unsigned bufflen, u32 *result, unsigned timeout)
147 {
148         struct request *req;
149         int ret;
150
151         req = nvme_alloc_request(q, cmd, 0);
152         if (IS_ERR(req))
153                 return PTR_ERR(req);
154
155         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
156
157         if (buffer && bufflen) {
158                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
159                 if (ret)
160                         goto out;
161         }
162
163         blk_execute_rq(req->q, NULL, req, 0);
164         if (result)
165                 *result = (u32)(uintptr_t)req->special;
166         ret = req->errors;
167  out:
168         blk_mq_free_request(req);
169         return ret;
170 }
171
172 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
173                 void *buffer, unsigned bufflen)
174 {
175         return __nvme_submit_sync_cmd(q, cmd, buffer, bufflen, NULL, 0);
176 }
177 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
178
179 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
180                 void __user *ubuffer, unsigned bufflen,
181                 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
182                 u32 *result, unsigned timeout)
183 {
184         bool write = cmd->common.opcode & 1;
185         struct nvme_ns *ns = q->queuedata;
186         struct gendisk *disk = ns ? ns->disk : NULL;
187         struct request *req;
188         struct bio *bio = NULL;
189         void *meta = NULL;
190         int ret;
191
192         req = nvme_alloc_request(q, cmd, 0);
193         if (IS_ERR(req))
194                 return PTR_ERR(req);
195
196         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
197
198         if (ubuffer && bufflen) {
199                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
200                                 GFP_KERNEL);
201                 if (ret)
202                         goto out;
203                 bio = req->bio;
204
205                 if (!disk)
206                         goto submit;
207                 bio->bi_bdev = bdget_disk(disk, 0);
208                 if (!bio->bi_bdev) {
209                         ret = -ENODEV;
210                         goto out_unmap;
211                 }
212
213                 if (meta_buffer) {
214                         struct bio_integrity_payload *bip;
215
216                         meta = kmalloc(meta_len, GFP_KERNEL);
217                         if (!meta) {
218                                 ret = -ENOMEM;
219                                 goto out_unmap;
220                         }
221
222                         if (write) {
223                                 if (copy_from_user(meta, meta_buffer,
224                                                 meta_len)) {
225                                         ret = -EFAULT;
226                                         goto out_free_meta;
227                                 }
228                         }
229
230                         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
231                         if (IS_ERR(bip)) {
232                                 ret = PTR_ERR(bip);
233                                 goto out_free_meta;
234                         }
235
236                         bip->bip_iter.bi_size = meta_len;
237                         bip->bip_iter.bi_sector = meta_seed;
238
239                         ret = bio_integrity_add_page(bio, virt_to_page(meta),
240                                         meta_len, offset_in_page(meta));
241                         if (ret != meta_len) {
242                                 ret = -ENOMEM;
243                                 goto out_free_meta;
244                         }
245                 }
246         }
247  submit:
248         blk_execute_rq(req->q, disk, req, 0);
249         ret = req->errors;
250         if (result)
251                 *result = (u32)(uintptr_t)req->special;
252         if (meta && !ret && !write) {
253                 if (copy_to_user(meta_buffer, meta, meta_len))
254                         ret = -EFAULT;
255         }
256  out_free_meta:
257         kfree(meta);
258  out_unmap:
259         if (bio) {
260                 if (disk && bio->bi_bdev)
261                         bdput(bio->bi_bdev);
262                 blk_rq_unmap_user(bio);
263         }
264  out:
265         blk_mq_free_request(req);
266         return ret;
267 }
268
269 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
270                 void __user *ubuffer, unsigned bufflen, u32 *result,
271                 unsigned timeout)
272 {
273         return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
274                         result, timeout);
275 }
276
277 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
278 {
279         struct nvme_command c = { };
280         int error;
281
282         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
283         c.identify.opcode = nvme_admin_identify;
284         c.identify.cns = cpu_to_le32(1);
285
286         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
287         if (!*id)
288                 return -ENOMEM;
289
290         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
291                         sizeof(struct nvme_id_ctrl));
292         if (error)
293                 kfree(*id);
294         return error;
295 }
296
297 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
298 {
299         struct nvme_command c = { };
300
301         c.identify.opcode = nvme_admin_identify;
302         c.identify.cns = cpu_to_le32(2);
303         c.identify.nsid = cpu_to_le32(nsid);
304         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
305 }
306
307 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
308                 struct nvme_id_ns **id)
309 {
310         struct nvme_command c = { };
311         int error;
312
313         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
314         c.identify.opcode = nvme_admin_identify,
315         c.identify.nsid = cpu_to_le32(nsid),
316
317         *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
318         if (!*id)
319                 return -ENOMEM;
320
321         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
322                         sizeof(struct nvme_id_ns));
323         if (error)
324                 kfree(*id);
325         return error;
326 }
327
328 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
329                                         dma_addr_t dma_addr, u32 *result)
330 {
331         struct nvme_command c;
332
333         memset(&c, 0, sizeof(c));
334         c.features.opcode = nvme_admin_get_features;
335         c.features.nsid = cpu_to_le32(nsid);
336         c.features.prp1 = cpu_to_le64(dma_addr);
337         c.features.fid = cpu_to_le32(fid);
338
339         return __nvme_submit_sync_cmd(dev->admin_q, &c, NULL, 0, result, 0);
340 }
341
342 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
343                                         dma_addr_t dma_addr, u32 *result)
344 {
345         struct nvme_command c;
346
347         memset(&c, 0, sizeof(c));
348         c.features.opcode = nvme_admin_set_features;
349         c.features.prp1 = cpu_to_le64(dma_addr);
350         c.features.fid = cpu_to_le32(fid);
351         c.features.dword11 = cpu_to_le32(dword11);
352
353         return __nvme_submit_sync_cmd(dev->admin_q, &c, NULL, 0, result, 0);
354 }
355
356 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
357 {
358         struct nvme_command c = { };
359         int error;
360
361         c.common.opcode = nvme_admin_get_log_page,
362         c.common.nsid = cpu_to_le32(0xFFFFFFFF),
363         c.common.cdw10[0] = cpu_to_le32(
364                         (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
365                          NVME_LOG_SMART),
366
367         *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
368         if (!*log)
369                 return -ENOMEM;
370
371         error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
372                         sizeof(struct nvme_smart_log));
373         if (error)
374                 kfree(*log);
375         return error;
376 }
377
378 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
379 {
380         u32 q_count = (*count - 1) | ((*count - 1) << 16);
381         u32 result;
382         int status, nr_io_queues;
383
384         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, 0,
385                         &result);
386         if (status)
387                 return status;
388
389         nr_io_queues = min(result & 0xffff, result >> 16) + 1;
390         *count = min(*count, nr_io_queues);
391         return 0;
392 }
393 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
394
395 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
396 {
397         struct nvme_user_io io;
398         struct nvme_command c;
399         unsigned length, meta_len;
400         void __user *metadata;
401
402         if (copy_from_user(&io, uio, sizeof(io)))
403                 return -EFAULT;
404
405         switch (io.opcode) {
406         case nvme_cmd_write:
407         case nvme_cmd_read:
408         case nvme_cmd_compare:
409                 break;
410         default:
411                 return -EINVAL;
412         }
413
414         length = (io.nblocks + 1) << ns->lba_shift;
415         meta_len = (io.nblocks + 1) * ns->ms;
416         metadata = (void __user *)(uintptr_t)io.metadata;
417
418         if (ns->ext) {
419                 length += meta_len;
420                 meta_len = 0;
421         } else if (meta_len) {
422                 if ((io.metadata & 3) || !io.metadata)
423                         return -EINVAL;
424         }
425
426         memset(&c, 0, sizeof(c));
427         c.rw.opcode = io.opcode;
428         c.rw.flags = io.flags;
429         c.rw.nsid = cpu_to_le32(ns->ns_id);
430         c.rw.slba = cpu_to_le64(io.slba);
431         c.rw.length = cpu_to_le16(io.nblocks);
432         c.rw.control = cpu_to_le16(io.control);
433         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
434         c.rw.reftag = cpu_to_le32(io.reftag);
435         c.rw.apptag = cpu_to_le16(io.apptag);
436         c.rw.appmask = cpu_to_le16(io.appmask);
437
438         return __nvme_submit_user_cmd(ns->queue, &c,
439                         (void __user *)(uintptr_t)io.addr, length,
440                         metadata, meta_len, io.slba, NULL, 0);
441 }
442
443 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
444                         struct nvme_passthru_cmd __user *ucmd)
445 {
446         struct nvme_passthru_cmd cmd;
447         struct nvme_command c;
448         unsigned timeout = 0;
449         int status;
450
451         if (!capable(CAP_SYS_ADMIN))
452                 return -EACCES;
453         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
454                 return -EFAULT;
455
456         memset(&c, 0, sizeof(c));
457         c.common.opcode = cmd.opcode;
458         c.common.flags = cmd.flags;
459         c.common.nsid = cpu_to_le32(cmd.nsid);
460         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
461         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
462         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
463         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
464         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
465         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
466         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
467         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
468
469         if (cmd.timeout_ms)
470                 timeout = msecs_to_jiffies(cmd.timeout_ms);
471
472         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
473                         (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
474                         &cmd.result, timeout);
475         if (status >= 0) {
476                 if (put_user(cmd.result, &ucmd->result))
477                         return -EFAULT;
478         }
479
480         return status;
481 }
482
483 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
484                 unsigned int cmd, unsigned long arg)
485 {
486         struct nvme_ns *ns = bdev->bd_disk->private_data;
487
488         switch (cmd) {
489         case NVME_IOCTL_ID:
490                 force_successful_syscall_return();
491                 return ns->ns_id;
492         case NVME_IOCTL_ADMIN_CMD:
493                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
494         case NVME_IOCTL_IO_CMD:
495                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
496         case NVME_IOCTL_SUBMIT_IO:
497                 return nvme_submit_io(ns, (void __user *)arg);
498 #ifdef CONFIG_BLK_DEV_NVME_SCSI
499         case SG_GET_VERSION_NUM:
500                 return nvme_sg_get_version_num((void __user *)arg);
501         case SG_IO:
502                 return nvme_sg_io(ns, (void __user *)arg);
503 #endif
504         default:
505                 return -ENOTTY;
506         }
507 }
508
509 #ifdef CONFIG_COMPAT
510 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
511                         unsigned int cmd, unsigned long arg)
512 {
513         switch (cmd) {
514         case SG_IO:
515                 return -ENOIOCTLCMD;
516         }
517         return nvme_ioctl(bdev, mode, cmd, arg);
518 }
519 #else
520 #define nvme_compat_ioctl       NULL
521 #endif
522
523 static int nvme_open(struct block_device *bdev, fmode_t mode)
524 {
525         return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
526 }
527
528 static void nvme_release(struct gendisk *disk, fmode_t mode)
529 {
530         struct nvme_ns *ns = disk->private_data;
531
532         module_put(ns->ctrl->ops->module);
533         nvme_put_ns(ns);
534 }
535
536 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
537 {
538         /* some standard values */
539         geo->heads = 1 << 6;
540         geo->sectors = 1 << 5;
541         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
542         return 0;
543 }
544
545 #ifdef CONFIG_BLK_DEV_INTEGRITY
546 static void nvme_init_integrity(struct nvme_ns *ns)
547 {
548         struct blk_integrity integrity;
549
550         switch (ns->pi_type) {
551         case NVME_NS_DPS_PI_TYPE3:
552                 integrity.profile = &t10_pi_type3_crc;
553                 break;
554         case NVME_NS_DPS_PI_TYPE1:
555         case NVME_NS_DPS_PI_TYPE2:
556                 integrity.profile = &t10_pi_type1_crc;
557                 break;
558         default:
559                 integrity.profile = NULL;
560                 break;
561         }
562         integrity.tuple_size = ns->ms;
563         blk_integrity_register(ns->disk, &integrity);
564         blk_queue_max_integrity_segments(ns->queue, 1);
565 }
566 #else
567 static void nvme_init_integrity(struct nvme_ns *ns)
568 {
569 }
570 #endif /* CONFIG_BLK_DEV_INTEGRITY */
571
572 static void nvme_config_discard(struct nvme_ns *ns)
573 {
574         u32 logical_block_size = queue_logical_block_size(ns->queue);
575         ns->queue->limits.discard_zeroes_data = 0;
576         ns->queue->limits.discard_alignment = logical_block_size;
577         ns->queue->limits.discard_granularity = logical_block_size;
578         blk_queue_max_discard_sectors(ns->queue, 0xffffffff);
579         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
580 }
581
582 static int nvme_revalidate_disk(struct gendisk *disk)
583 {
584         struct nvme_ns *ns = disk->private_data;
585         struct nvme_id_ns *id;
586         u8 lbaf, pi_type;
587         u16 old_ms;
588         unsigned short bs;
589
590         if (nvme_identify_ns(ns->ctrl, ns->ns_id, &id)) {
591                 dev_warn(disk_to_dev(ns->disk), "%s: Identify failure\n",
592                                 __func__);
593                 return -ENODEV;
594         }
595         if (id->ncap == 0) {
596                 kfree(id);
597                 return -ENODEV;
598         }
599
600         if (nvme_nvm_ns_supported(ns, id) && ns->type != NVME_NS_LIGHTNVM) {
601                 if (nvme_nvm_register(ns->queue, disk->disk_name)) {
602                         dev_warn(disk_to_dev(ns->disk),
603                                 "%s: LightNVM init failure\n", __func__);
604                         kfree(id);
605                         return -ENODEV;
606                 }
607                 ns->type = NVME_NS_LIGHTNVM;
608         }
609
610         if (ns->ctrl->vs >= NVME_VS(1, 1))
611                 memcpy(ns->eui, id->eui64, sizeof(ns->eui));
612         if (ns->ctrl->vs >= NVME_VS(1, 2))
613                 memcpy(ns->uuid, id->nguid, sizeof(ns->uuid));
614
615         old_ms = ns->ms;
616         lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
617         ns->lba_shift = id->lbaf[lbaf].ds;
618         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
619         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
620
621         /*
622          * If identify namespace failed, use default 512 byte block size so
623          * block layer can use before failing read/write for 0 capacity.
624          */
625         if (ns->lba_shift == 0)
626                 ns->lba_shift = 9;
627         bs = 1 << ns->lba_shift;
628         /* XXX: PI implementation requires metadata equal t10 pi tuple size */
629         pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
630                                         id->dps & NVME_NS_DPS_PI_MASK : 0;
631
632         blk_mq_freeze_queue(disk->queue);
633         if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
634                                 ns->ms != old_ms ||
635                                 bs != queue_logical_block_size(disk->queue) ||
636                                 (ns->ms && ns->ext)))
637                 blk_integrity_unregister(disk);
638
639         ns->pi_type = pi_type;
640         blk_queue_logical_block_size(ns->queue, bs);
641
642         if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
643                 nvme_init_integrity(ns);
644         if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
645                 set_capacity(disk, 0);
646         else
647                 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
648
649         if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
650                 nvme_config_discard(ns);
651         blk_mq_unfreeze_queue(disk->queue);
652
653         kfree(id);
654         return 0;
655 }
656
657 static char nvme_pr_type(enum pr_type type)
658 {
659         switch (type) {
660         case PR_WRITE_EXCLUSIVE:
661                 return 1;
662         case PR_EXCLUSIVE_ACCESS:
663                 return 2;
664         case PR_WRITE_EXCLUSIVE_REG_ONLY:
665                 return 3;
666         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
667                 return 4;
668         case PR_WRITE_EXCLUSIVE_ALL_REGS:
669                 return 5;
670         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
671                 return 6;
672         default:
673                 return 0;
674         }
675 };
676
677 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
678                                 u64 key, u64 sa_key, u8 op)
679 {
680         struct nvme_ns *ns = bdev->bd_disk->private_data;
681         struct nvme_command c;
682         u8 data[16] = { 0, };
683
684         put_unaligned_le64(key, &data[0]);
685         put_unaligned_le64(sa_key, &data[8]);
686
687         memset(&c, 0, sizeof(c));
688         c.common.opcode = op;
689         c.common.nsid = cpu_to_le32(ns->ns_id);
690         c.common.cdw10[0] = cpu_to_le32(cdw10);
691
692         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
693 }
694
695 static int nvme_pr_register(struct block_device *bdev, u64 old,
696                 u64 new, unsigned flags)
697 {
698         u32 cdw10;
699
700         if (flags & ~PR_FL_IGNORE_KEY)
701                 return -EOPNOTSUPP;
702
703         cdw10 = old ? 2 : 0;
704         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
705         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
706         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
707 }
708
709 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
710                 enum pr_type type, unsigned flags)
711 {
712         u32 cdw10;
713
714         if (flags & ~PR_FL_IGNORE_KEY)
715                 return -EOPNOTSUPP;
716
717         cdw10 = nvme_pr_type(type) << 8;
718         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
719         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
720 }
721
722 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
723                 enum pr_type type, bool abort)
724 {
725         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
726         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
727 }
728
729 static int nvme_pr_clear(struct block_device *bdev, u64 key)
730 {
731         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
732         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
733 }
734
735 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
736 {
737         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
738         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
739 }
740
741 static const struct pr_ops nvme_pr_ops = {
742         .pr_register    = nvme_pr_register,
743         .pr_reserve     = nvme_pr_reserve,
744         .pr_release     = nvme_pr_release,
745         .pr_preempt     = nvme_pr_preempt,
746         .pr_clear       = nvme_pr_clear,
747 };
748
749 static const struct block_device_operations nvme_fops = {
750         .owner          = THIS_MODULE,
751         .ioctl          = nvme_ioctl,
752         .compat_ioctl   = nvme_compat_ioctl,
753         .open           = nvme_open,
754         .release        = nvme_release,
755         .getgeo         = nvme_getgeo,
756         .revalidate_disk= nvme_revalidate_disk,
757         .pr_ops         = &nvme_pr_ops,
758 };
759
760 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
761 {
762         unsigned long timeout =
763                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
764         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
765         int ret;
766
767         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
768                 if ((csts & NVME_CSTS_RDY) == bit)
769                         break;
770
771                 msleep(100);
772                 if (fatal_signal_pending(current))
773                         return -EINTR;
774                 if (time_after(jiffies, timeout)) {
775                         dev_err(ctrl->device,
776                                 "Device not ready; aborting %s\n", enabled ?
777                                                 "initialisation" : "reset");
778                         return -ENODEV;
779                 }
780         }
781
782         return ret;
783 }
784
785 /*
786  * If the device has been passed off to us in an enabled state, just clear
787  * the enabled bit.  The spec says we should set the 'shutdown notification
788  * bits', but doing so may cause the device to complete commands to the
789  * admin queue ... and we don't know what memory that might be pointing at!
790  */
791 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
792 {
793         int ret;
794
795         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
796         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
797
798         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
799         if (ret)
800                 return ret;
801         return nvme_wait_ready(ctrl, cap, false);
802 }
803 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
804
805 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
806 {
807         /*
808          * Default to a 4K page size, with the intention to update this
809          * path in the future to accomodate architectures with differing
810          * kernel and IO page sizes.
811          */
812         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
813         int ret;
814
815         if (page_shift < dev_page_min) {
816                 dev_err(ctrl->device,
817                         "Minimum device page size %u too large for host (%u)\n",
818                         1 << dev_page_min, 1 << page_shift);
819                 return -ENODEV;
820         }
821
822         ctrl->page_size = 1 << page_shift;
823
824         ctrl->ctrl_config = NVME_CC_CSS_NVM;
825         ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
826         ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
827         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
828         ctrl->ctrl_config |= NVME_CC_ENABLE;
829
830         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
831         if (ret)
832                 return ret;
833         return nvme_wait_ready(ctrl, cap, true);
834 }
835 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
836
837 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
838 {
839         unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
840         u32 csts;
841         int ret;
842
843         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
844         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
845
846         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
847         if (ret)
848                 return ret;
849
850         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
851                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
852                         break;
853
854                 msleep(100);
855                 if (fatal_signal_pending(current))
856                         return -EINTR;
857                 if (time_after(jiffies, timeout)) {
858                         dev_err(ctrl->device,
859                                 "Device shutdown incomplete; abort shutdown\n");
860                         return -ENODEV;
861                 }
862         }
863
864         return ret;
865 }
866 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
867
868 /*
869  * Initialize the cached copies of the Identify data and various controller
870  * register in our nvme_ctrl structure.  This should be called as soon as
871  * the admin queue is fully up and running.
872  */
873 int nvme_init_identify(struct nvme_ctrl *ctrl)
874 {
875         struct nvme_id_ctrl *id;
876         u64 cap;
877         int ret, page_shift;
878
879         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
880         if (ret) {
881                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
882                 return ret;
883         }
884
885         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
886         if (ret) {
887                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
888                 return ret;
889         }
890         page_shift = NVME_CAP_MPSMIN(cap) + 12;
891
892         if (ctrl->vs >= NVME_VS(1, 1))
893                 ctrl->subsystem = NVME_CAP_NSSRC(cap);
894
895         ret = nvme_identify_ctrl(ctrl, &id);
896         if (ret) {
897                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
898                 return -EIO;
899         }
900
901         ctrl->oncs = le16_to_cpup(&id->oncs);
902         atomic_set(&ctrl->abort_limit, id->acl + 1);
903         ctrl->vwc = id->vwc;
904         memcpy(ctrl->serial, id->sn, sizeof(id->sn));
905         memcpy(ctrl->model, id->mn, sizeof(id->mn));
906         memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
907         if (id->mdts)
908                 ctrl->max_hw_sectors = 1 << (id->mdts + page_shift - 9);
909         else
910                 ctrl->max_hw_sectors = UINT_MAX;
911
912         if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) && id->vs[3]) {
913                 unsigned int max_hw_sectors;
914
915                 ctrl->stripe_size = 1 << (id->vs[3] + page_shift);
916                 max_hw_sectors = ctrl->stripe_size >> (page_shift - 9);
917                 if (ctrl->max_hw_sectors) {
918                         ctrl->max_hw_sectors = min(max_hw_sectors,
919                                                         ctrl->max_hw_sectors);
920                 } else {
921                         ctrl->max_hw_sectors = max_hw_sectors;
922                 }
923         }
924
925         kfree(id);
926         return 0;
927 }
928 EXPORT_SYMBOL_GPL(nvme_init_identify);
929
930 static int nvme_dev_open(struct inode *inode, struct file *file)
931 {
932         struct nvme_ctrl *ctrl;
933         int instance = iminor(inode);
934         int ret = -ENODEV;
935
936         spin_lock(&dev_list_lock);
937         list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
938                 if (ctrl->instance != instance)
939                         continue;
940
941                 if (!ctrl->admin_q) {
942                         ret = -EWOULDBLOCK;
943                         break;
944                 }
945                 if (!kref_get_unless_zero(&ctrl->kref))
946                         break;
947                 file->private_data = ctrl;
948                 ret = 0;
949                 break;
950         }
951         spin_unlock(&dev_list_lock);
952
953         return ret;
954 }
955
956 static int nvme_dev_release(struct inode *inode, struct file *file)
957 {
958         nvme_put_ctrl(file->private_data);
959         return 0;
960 }
961
962 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
963 {
964         struct nvme_ns *ns;
965         int ret;
966
967         mutex_lock(&ctrl->namespaces_mutex);
968         if (list_empty(&ctrl->namespaces)) {
969                 ret = -ENOTTY;
970                 goto out_unlock;
971         }
972
973         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
974         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
975                 dev_warn(ctrl->device,
976                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
977                 ret = -EINVAL;
978                 goto out_unlock;
979         }
980
981         dev_warn(ctrl->device,
982                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
983         kref_get(&ns->kref);
984         mutex_unlock(&ctrl->namespaces_mutex);
985
986         ret = nvme_user_cmd(ctrl, ns, argp);
987         nvme_put_ns(ns);
988         return ret;
989
990 out_unlock:
991         mutex_unlock(&ctrl->namespaces_mutex);
992         return ret;
993 }
994
995 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
996                 unsigned long arg)
997 {
998         struct nvme_ctrl *ctrl = file->private_data;
999         void __user *argp = (void __user *)arg;
1000
1001         switch (cmd) {
1002         case NVME_IOCTL_ADMIN_CMD:
1003                 return nvme_user_cmd(ctrl, NULL, argp);
1004         case NVME_IOCTL_IO_CMD:
1005                 return nvme_dev_user_cmd(ctrl, argp);
1006         case NVME_IOCTL_RESET:
1007                 dev_warn(ctrl->device, "resetting controller\n");
1008                 return ctrl->ops->reset_ctrl(ctrl);
1009         case NVME_IOCTL_SUBSYS_RESET:
1010                 return nvme_reset_subsystem(ctrl);
1011         default:
1012                 return -ENOTTY;
1013         }
1014 }
1015
1016 static const struct file_operations nvme_dev_fops = {
1017         .owner          = THIS_MODULE,
1018         .open           = nvme_dev_open,
1019         .release        = nvme_dev_release,
1020         .unlocked_ioctl = nvme_dev_ioctl,
1021         .compat_ioctl   = nvme_dev_ioctl,
1022 };
1023
1024 static ssize_t nvme_sysfs_reset(struct device *dev,
1025                                 struct device_attribute *attr, const char *buf,
1026                                 size_t count)
1027 {
1028         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1029         int ret;
1030
1031         ret = ctrl->ops->reset_ctrl(ctrl);
1032         if (ret < 0)
1033                 return ret;
1034         return count;
1035 }
1036 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1037
1038 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1039                                                                 char *buf)
1040 {
1041         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1042         return sprintf(buf, "%pU\n", ns->uuid);
1043 }
1044 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1045
1046 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1047                                                                 char *buf)
1048 {
1049         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1050         return sprintf(buf, "%8phd\n", ns->eui);
1051 }
1052 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1053
1054 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1055                                                                 char *buf)
1056 {
1057         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1058         return sprintf(buf, "%d\n", ns->ns_id);
1059 }
1060 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1061
1062 static struct attribute *nvme_ns_attrs[] = {
1063         &dev_attr_uuid.attr,
1064         &dev_attr_eui.attr,
1065         &dev_attr_nsid.attr,
1066         NULL,
1067 };
1068
1069 static umode_t nvme_attrs_are_visible(struct kobject *kobj,
1070                 struct attribute *a, int n)
1071 {
1072         struct device *dev = container_of(kobj, struct device, kobj);
1073         struct nvme_ns *ns = dev_to_disk(dev)->private_data;
1074
1075         if (a == &dev_attr_uuid.attr) {
1076                 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1077                         return 0;
1078         }
1079         if (a == &dev_attr_eui.attr) {
1080                 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1081                         return 0;
1082         }
1083         return a->mode;
1084 }
1085
1086 static const struct attribute_group nvme_ns_attr_group = {
1087         .attrs          = nvme_ns_attrs,
1088         .is_visible     = nvme_attrs_are_visible,
1089 };
1090
1091 #define nvme_show_function(field)                                               \
1092 static ssize_t  field##_show(struct device *dev,                                \
1093                             struct device_attribute *attr, char *buf)           \
1094 {                                                                               \
1095         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
1096         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);   \
1097 }                                                                               \
1098 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1099
1100 nvme_show_function(model);
1101 nvme_show_function(serial);
1102 nvme_show_function(firmware_rev);
1103
1104 static struct attribute *nvme_dev_attrs[] = {
1105         &dev_attr_reset_controller.attr,
1106         &dev_attr_model.attr,
1107         &dev_attr_serial.attr,
1108         &dev_attr_firmware_rev.attr,
1109         NULL
1110 };
1111
1112 static struct attribute_group nvme_dev_attrs_group = {
1113         .attrs = nvme_dev_attrs,
1114 };
1115
1116 static const struct attribute_group *nvme_dev_attr_groups[] = {
1117         &nvme_dev_attrs_group,
1118         NULL,
1119 };
1120
1121 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1122 {
1123         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1124         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1125
1126         return nsa->ns_id - nsb->ns_id;
1127 }
1128
1129 static struct nvme_ns *nvme_find_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1130 {
1131         struct nvme_ns *ns;
1132
1133         lockdep_assert_held(&ctrl->namespaces_mutex);
1134
1135         list_for_each_entry(ns, &ctrl->namespaces, list) {
1136                 if (ns->ns_id == nsid)
1137                         return ns;
1138                 if (ns->ns_id > nsid)
1139                         break;
1140         }
1141         return NULL;
1142 }
1143
1144 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1145 {
1146         struct nvme_ns *ns;
1147         struct gendisk *disk;
1148         int node = dev_to_node(ctrl->dev);
1149
1150         lockdep_assert_held(&ctrl->namespaces_mutex);
1151
1152         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
1153         if (!ns)
1154                 return;
1155
1156         ns->queue = blk_mq_init_queue(ctrl->tagset);
1157         if (IS_ERR(ns->queue))
1158                 goto out_free_ns;
1159         queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1160         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1161         ns->queue->queuedata = ns;
1162         ns->ctrl = ctrl;
1163
1164         disk = alloc_disk_node(0, node);
1165         if (!disk)
1166                 goto out_free_queue;
1167
1168         kref_init(&ns->kref);
1169         ns->ns_id = nsid;
1170         ns->disk = disk;
1171         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
1172
1173         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1174         if (ctrl->max_hw_sectors) {
1175                 blk_queue_max_hw_sectors(ns->queue, ctrl->max_hw_sectors);
1176                 blk_queue_max_segments(ns->queue,
1177                         (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1);
1178         }
1179         if (ctrl->stripe_size)
1180                 blk_queue_chunk_sectors(ns->queue, ctrl->stripe_size >> 9);
1181         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1182                 blk_queue_flush(ns->queue, REQ_FLUSH | REQ_FUA);
1183         blk_queue_virt_boundary(ns->queue, ctrl->page_size - 1);
1184
1185         disk->major = nvme_major;
1186         disk->first_minor = 0;
1187         disk->fops = &nvme_fops;
1188         disk->private_data = ns;
1189         disk->queue = ns->queue;
1190         disk->driverfs_dev = ctrl->device;
1191         disk->flags = GENHD_FL_EXT_DEVT;
1192         sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance, nsid);
1193
1194         if (nvme_revalidate_disk(ns->disk))
1195                 goto out_free_disk;
1196
1197         list_add_tail(&ns->list, &ctrl->namespaces);
1198         kref_get(&ctrl->kref);
1199         if (ns->type == NVME_NS_LIGHTNVM)
1200                 return;
1201
1202         add_disk(ns->disk);
1203         if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
1204                                         &nvme_ns_attr_group))
1205                 pr_warn("%s: failed to create sysfs group for identification\n",
1206                         ns->disk->disk_name);
1207         return;
1208  out_free_disk:
1209         kfree(disk);
1210  out_free_queue:
1211         blk_cleanup_queue(ns->queue);
1212  out_free_ns:
1213         kfree(ns);
1214 }
1215
1216 static void nvme_ns_remove(struct nvme_ns *ns)
1217 {
1218         bool kill = nvme_io_incapable(ns->ctrl) &&
1219                         !blk_queue_dying(ns->queue);
1220
1221         lockdep_assert_held(&ns->ctrl->namespaces_mutex);
1222
1223         if (kill) {
1224                 blk_set_queue_dying(ns->queue);
1225
1226                 /*
1227                  * The controller was shutdown first if we got here through
1228                  * device removal. The shutdown may requeue outstanding
1229                  * requests. These need to be aborted immediately so
1230                  * del_gendisk doesn't block indefinitely for their completion.
1231                  */
1232                 blk_mq_abort_requeue_list(ns->queue);
1233         }
1234         if (ns->disk->flags & GENHD_FL_UP) {
1235                 if (blk_get_integrity(ns->disk))
1236                         blk_integrity_unregister(ns->disk);
1237                 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
1238                                         &nvme_ns_attr_group);
1239                 del_gendisk(ns->disk);
1240         }
1241         if (kill || !blk_queue_dying(ns->queue)) {
1242                 blk_mq_abort_requeue_list(ns->queue);
1243                 blk_cleanup_queue(ns->queue);
1244         }
1245         list_del_init(&ns->list);
1246         nvme_put_ns(ns);
1247 }
1248
1249 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1250 {
1251         struct nvme_ns *ns;
1252
1253         ns = nvme_find_ns(ctrl, nsid);
1254         if (ns) {
1255                 if (revalidate_disk(ns->disk))
1256                         nvme_ns_remove(ns);
1257         } else
1258                 nvme_alloc_ns(ctrl, nsid);
1259 }
1260
1261 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
1262 {
1263         struct nvme_ns *ns;
1264         __le32 *ns_list;
1265         unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
1266         int ret = 0;
1267
1268         ns_list = kzalloc(0x1000, GFP_KERNEL);
1269         if (!ns_list)
1270                 return -ENOMEM;
1271
1272         for (i = 0; i < num_lists; i++) {
1273                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
1274                 if (ret)
1275                         goto out;
1276
1277                 for (j = 0; j < min(nn, 1024U); j++) {
1278                         nsid = le32_to_cpu(ns_list[j]);
1279                         if (!nsid)
1280                                 goto out;
1281
1282                         nvme_validate_ns(ctrl, nsid);
1283
1284                         while (++prev < nsid) {
1285                                 ns = nvme_find_ns(ctrl, prev);
1286                                 if (ns)
1287                                         nvme_ns_remove(ns);
1288                         }
1289                 }
1290                 nn -= j;
1291         }
1292  out:
1293         kfree(ns_list);
1294         return ret;
1295 }
1296
1297 static void __nvme_scan_namespaces(struct nvme_ctrl *ctrl, unsigned nn)
1298 {
1299         struct nvme_ns *ns, *next;
1300         unsigned i;
1301
1302         lockdep_assert_held(&ctrl->namespaces_mutex);
1303
1304         for (i = 1; i <= nn; i++)
1305                 nvme_validate_ns(ctrl, i);
1306
1307         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
1308                 if (ns->ns_id > nn)
1309                         nvme_ns_remove(ns);
1310         }
1311 }
1312
1313 void nvme_scan_namespaces(struct nvme_ctrl *ctrl)
1314 {
1315         struct nvme_id_ctrl *id;
1316         unsigned nn;
1317
1318         if (nvme_identify_ctrl(ctrl, &id))
1319                 return;
1320
1321         mutex_lock(&ctrl->namespaces_mutex);
1322         nn = le32_to_cpu(id->nn);
1323         if (ctrl->vs >= NVME_VS(1, 1) &&
1324             !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
1325                 if (!nvme_scan_ns_list(ctrl, nn))
1326                         goto done;
1327         }
1328         __nvme_scan_namespaces(ctrl, le32_to_cpup(&id->nn));
1329  done:
1330         list_sort(NULL, &ctrl->namespaces, ns_cmp);
1331         mutex_unlock(&ctrl->namespaces_mutex);
1332         kfree(id);
1333 }
1334 EXPORT_SYMBOL_GPL(nvme_scan_namespaces);
1335
1336 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
1337 {
1338         struct nvme_ns *ns, *next;
1339
1340         mutex_lock(&ctrl->namespaces_mutex);
1341         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
1342                 nvme_ns_remove(ns);
1343         mutex_unlock(&ctrl->namespaces_mutex);
1344 }
1345 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
1346
1347 static DEFINE_IDA(nvme_instance_ida);
1348
1349 static int nvme_set_instance(struct nvme_ctrl *ctrl)
1350 {
1351         int instance, error;
1352
1353         do {
1354                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
1355                         return -ENODEV;
1356
1357                 spin_lock(&dev_list_lock);
1358                 error = ida_get_new(&nvme_instance_ida, &instance);
1359                 spin_unlock(&dev_list_lock);
1360         } while (error == -EAGAIN);
1361
1362         if (error)
1363                 return -ENODEV;
1364
1365         ctrl->instance = instance;
1366         return 0;
1367 }
1368
1369 static void nvme_release_instance(struct nvme_ctrl *ctrl)
1370 {
1371         spin_lock(&dev_list_lock);
1372         ida_remove(&nvme_instance_ida, ctrl->instance);
1373         spin_unlock(&dev_list_lock);
1374 }
1375
1376 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
1377 {
1378         device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
1379
1380         spin_lock(&dev_list_lock);
1381         list_del(&ctrl->node);
1382         spin_unlock(&dev_list_lock);
1383 }
1384 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
1385
1386 static void nvme_free_ctrl(struct kref *kref)
1387 {
1388         struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
1389
1390         put_device(ctrl->device);
1391         nvme_release_instance(ctrl);
1392
1393         ctrl->ops->free_ctrl(ctrl);
1394 }
1395
1396 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
1397 {
1398         kref_put(&ctrl->kref, nvme_free_ctrl);
1399 }
1400 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
1401
1402 /*
1403  * Initialize a NVMe controller structures.  This needs to be called during
1404  * earliest initialization so that we have the initialized structured around
1405  * during probing.
1406  */
1407 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
1408                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
1409 {
1410         int ret;
1411
1412         INIT_LIST_HEAD(&ctrl->namespaces);
1413         mutex_init(&ctrl->namespaces_mutex);
1414         kref_init(&ctrl->kref);
1415         ctrl->dev = dev;
1416         ctrl->ops = ops;
1417         ctrl->quirks = quirks;
1418
1419         ret = nvme_set_instance(ctrl);
1420         if (ret)
1421                 goto out;
1422
1423         ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
1424                                 MKDEV(nvme_char_major, ctrl->instance),
1425                                 ctrl, nvme_dev_attr_groups,
1426                                 "nvme%d", ctrl->instance);
1427         if (IS_ERR(ctrl->device)) {
1428                 ret = PTR_ERR(ctrl->device);
1429                 goto out_release_instance;
1430         }
1431         get_device(ctrl->device);
1432
1433         spin_lock(&dev_list_lock);
1434         list_add_tail(&ctrl->node, &nvme_ctrl_list);
1435         spin_unlock(&dev_list_lock);
1436
1437         return 0;
1438 out_release_instance:
1439         nvme_release_instance(ctrl);
1440 out:
1441         return ret;
1442 }
1443 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
1444
1445 void nvme_stop_queues(struct nvme_ctrl *ctrl)
1446 {
1447         struct nvme_ns *ns;
1448
1449         mutex_lock(&ctrl->namespaces_mutex);
1450         list_for_each_entry(ns, &ctrl->namespaces, list) {
1451                 spin_lock_irq(ns->queue->queue_lock);
1452                 queue_flag_set(QUEUE_FLAG_STOPPED, ns->queue);
1453                 spin_unlock_irq(ns->queue->queue_lock);
1454
1455                 blk_mq_cancel_requeue_work(ns->queue);
1456                 blk_mq_stop_hw_queues(ns->queue);
1457         }
1458         mutex_unlock(&ctrl->namespaces_mutex);
1459 }
1460 EXPORT_SYMBOL_GPL(nvme_stop_queues);
1461
1462 void nvme_start_queues(struct nvme_ctrl *ctrl)
1463 {
1464         struct nvme_ns *ns;
1465
1466         mutex_lock(&ctrl->namespaces_mutex);
1467         list_for_each_entry(ns, &ctrl->namespaces, list) {
1468                 queue_flag_clear_unlocked(QUEUE_FLAG_STOPPED, ns->queue);
1469                 blk_mq_start_stopped_hw_queues(ns->queue, true);
1470                 blk_mq_kick_requeue_list(ns->queue);
1471         }
1472         mutex_unlock(&ctrl->namespaces_mutex);
1473 }
1474 EXPORT_SYMBOL_GPL(nvme_start_queues);
1475
1476 int __init nvme_core_init(void)
1477 {
1478         int result;
1479
1480         result = register_blkdev(nvme_major, "nvme");
1481         if (result < 0)
1482                 return result;
1483         else if (result > 0)
1484                 nvme_major = result;
1485
1486         result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
1487                                                         &nvme_dev_fops);
1488         if (result < 0)
1489                 goto unregister_blkdev;
1490         else if (result > 0)
1491                 nvme_char_major = result;
1492
1493         nvme_class = class_create(THIS_MODULE, "nvme");
1494         if (IS_ERR(nvme_class)) {
1495                 result = PTR_ERR(nvme_class);
1496                 goto unregister_chrdev;
1497         }
1498
1499         return 0;
1500
1501  unregister_chrdev:
1502         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
1503  unregister_blkdev:
1504         unregister_blkdev(nvme_major, "nvme");
1505         return result;
1506 }
1507
1508 void nvme_core_exit(void)
1509 {
1510         unregister_blkdev(nvme_major, "nvme");
1511         class_destroy(nvme_class);
1512         __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
1513 }
1514
1515 MODULE_LICENSE("GPL");
1516 MODULE_VERSION("1.0");
1517 module_init(nvme_core_init);
1518 module_exit(nvme_core_exit);