Bluetooth: Read LE Max data length command
[platform/kernel/linux-starfive.git] / block / genhd.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  gendisk handling
4  *
5  * Portions Copyright (C) 2020 Christoph Hellwig
6  */
7
8 #include <linux/module.h>
9 #include <linux/ctype.h>
10 #include <linux/fs.h>
11 #include <linux/kdev_t.h>
12 #include <linux/kernel.h>
13 #include <linux/blkdev.h>
14 #include <linux/backing-dev.h>
15 #include <linux/init.h>
16 #include <linux/spinlock.h>
17 #include <linux/proc_fs.h>
18 #include <linux/seq_file.h>
19 #include <linux/slab.h>
20 #include <linux/kmod.h>
21 #include <linux/major.h>
22 #include <linux/mutex.h>
23 #include <linux/idr.h>
24 #include <linux/log2.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/badblocks.h>
27 #include <linux/part_stat.h>
28 #include <linux/blktrace_api.h>
29
30 #include "blk-throttle.h"
31 #include "blk.h"
32 #include "blk-mq-sched.h"
33 #include "blk-rq-qos.h"
34 #include "blk-cgroup.h"
35
36 static struct kobject *block_depr;
37
38 /*
39  * Unique, monotonically increasing sequential number associated with block
40  * devices instances (i.e. incremented each time a device is attached).
41  * Associating uevents with block devices in userspace is difficult and racy:
42  * the uevent netlink socket is lossy, and on slow and overloaded systems has
43  * a very high latency.
44  * Block devices do not have exclusive owners in userspace, any process can set
45  * one up (e.g. loop devices). Moreover, device names can be reused (e.g. loop0
46  * can be reused again and again).
47  * A userspace process setting up a block device and watching for its events
48  * cannot thus reliably tell whether an event relates to the device it just set
49  * up or another earlier instance with the same name.
50  * This sequential number allows userspace processes to solve this problem, and
51  * uniquely associate an uevent to the lifetime to a device.
52  */
53 static atomic64_t diskseq;
54
55 /* for extended dynamic devt allocation, currently only one major is used */
56 #define NR_EXT_DEVT             (1 << MINORBITS)
57 static DEFINE_IDA(ext_devt_ida);
58
59 void set_capacity(struct gendisk *disk, sector_t sectors)
60 {
61         struct block_device *bdev = disk->part0;
62
63         spin_lock(&bdev->bd_size_lock);
64         i_size_write(bdev->bd_inode, (loff_t)sectors << SECTOR_SHIFT);
65         bdev->bd_nr_sectors = sectors;
66         spin_unlock(&bdev->bd_size_lock);
67 }
68 EXPORT_SYMBOL(set_capacity);
69
70 /*
71  * Set disk capacity and notify if the size is not currently zero and will not
72  * be set to zero.  Returns true if a uevent was sent, otherwise false.
73  */
74 bool set_capacity_and_notify(struct gendisk *disk, sector_t size)
75 {
76         sector_t capacity = get_capacity(disk);
77         char *envp[] = { "RESIZE=1", NULL };
78
79         set_capacity(disk, size);
80
81         /*
82          * Only print a message and send a uevent if the gendisk is user visible
83          * and alive.  This avoids spamming the log and udev when setting the
84          * initial capacity during probing.
85          */
86         if (size == capacity ||
87             !disk_live(disk) ||
88             (disk->flags & GENHD_FL_HIDDEN))
89                 return false;
90
91         pr_info("%s: detected capacity change from %lld to %lld\n",
92                 disk->disk_name, capacity, size);
93
94         /*
95          * Historically we did not send a uevent for changes to/from an empty
96          * device.
97          */
98         if (!capacity || !size)
99                 return false;
100         kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
101         return true;
102 }
103 EXPORT_SYMBOL_GPL(set_capacity_and_notify);
104
105 static void part_stat_read_all(struct block_device *part,
106                 struct disk_stats *stat)
107 {
108         int cpu;
109
110         memset(stat, 0, sizeof(struct disk_stats));
111         for_each_possible_cpu(cpu) {
112                 struct disk_stats *ptr = per_cpu_ptr(part->bd_stats, cpu);
113                 int group;
114
115                 for (group = 0; group < NR_STAT_GROUPS; group++) {
116                         stat->nsecs[group] += ptr->nsecs[group];
117                         stat->sectors[group] += ptr->sectors[group];
118                         stat->ios[group] += ptr->ios[group];
119                         stat->merges[group] += ptr->merges[group];
120                 }
121
122                 stat->io_ticks += ptr->io_ticks;
123         }
124 }
125
126 static unsigned int part_in_flight(struct block_device *part)
127 {
128         unsigned int inflight = 0;
129         int cpu;
130
131         for_each_possible_cpu(cpu) {
132                 inflight += part_stat_local_read_cpu(part, in_flight[0], cpu) +
133                             part_stat_local_read_cpu(part, in_flight[1], cpu);
134         }
135         if ((int)inflight < 0)
136                 inflight = 0;
137
138         return inflight;
139 }
140
141 static void part_in_flight_rw(struct block_device *part,
142                 unsigned int inflight[2])
143 {
144         int cpu;
145
146         inflight[0] = 0;
147         inflight[1] = 0;
148         for_each_possible_cpu(cpu) {
149                 inflight[0] += part_stat_local_read_cpu(part, in_flight[0], cpu);
150                 inflight[1] += part_stat_local_read_cpu(part, in_flight[1], cpu);
151         }
152         if ((int)inflight[0] < 0)
153                 inflight[0] = 0;
154         if ((int)inflight[1] < 0)
155                 inflight[1] = 0;
156 }
157
158 /*
159  * Can be deleted altogether. Later.
160  *
161  */
162 #define BLKDEV_MAJOR_HASH_SIZE 255
163 static struct blk_major_name {
164         struct blk_major_name *next;
165         int major;
166         char name[16];
167 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
168         void (*probe)(dev_t devt);
169 #endif
170 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
171 static DEFINE_MUTEX(major_names_lock);
172 static DEFINE_SPINLOCK(major_names_spinlock);
173
174 /* index in the above - for now: assume no multimajor ranges */
175 static inline int major_to_index(unsigned major)
176 {
177         return major % BLKDEV_MAJOR_HASH_SIZE;
178 }
179
180 #ifdef CONFIG_PROC_FS
181 void blkdev_show(struct seq_file *seqf, off_t offset)
182 {
183         struct blk_major_name *dp;
184
185         spin_lock(&major_names_spinlock);
186         for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
187                 if (dp->major == offset)
188                         seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
189         spin_unlock(&major_names_spinlock);
190 }
191 #endif /* CONFIG_PROC_FS */
192
193 /**
194  * __register_blkdev - register a new block device
195  *
196  * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
197  *         @major = 0, try to allocate any unused major number.
198  * @name: the name of the new block device as a zero terminated string
199  * @probe: pre-devtmpfs / pre-udev callback used to create disks when their
200  *         pre-created device node is accessed. When a probe call uses
201  *         add_disk() and it fails the driver must cleanup resources. This
202  *         interface may soon be removed.
203  *
204  * The @name must be unique within the system.
205  *
206  * The return value depends on the @major input parameter:
207  *
208  *  - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
209  *    then the function returns zero on success, or a negative error code
210  *  - if any unused major number was requested with @major = 0 parameter
211  *    then the return value is the allocated major number in range
212  *    [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
213  *
214  * See Documentation/admin-guide/devices.txt for the list of allocated
215  * major numbers.
216  *
217  * Use register_blkdev instead for any new code.
218  */
219 int __register_blkdev(unsigned int major, const char *name,
220                 void (*probe)(dev_t devt))
221 {
222         struct blk_major_name **n, *p;
223         int index, ret = 0;
224
225         mutex_lock(&major_names_lock);
226
227         /* temporary */
228         if (major == 0) {
229                 for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
230                         if (major_names[index] == NULL)
231                                 break;
232                 }
233
234                 if (index == 0) {
235                         printk("%s: failed to get major for %s\n",
236                                __func__, name);
237                         ret = -EBUSY;
238                         goto out;
239                 }
240                 major = index;
241                 ret = major;
242         }
243
244         if (major >= BLKDEV_MAJOR_MAX) {
245                 pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
246                        __func__, major, BLKDEV_MAJOR_MAX-1, name);
247
248                 ret = -EINVAL;
249                 goto out;
250         }
251
252         p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
253         if (p == NULL) {
254                 ret = -ENOMEM;
255                 goto out;
256         }
257
258         p->major = major;
259 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
260         p->probe = probe;
261 #endif
262         strlcpy(p->name, name, sizeof(p->name));
263         p->next = NULL;
264         index = major_to_index(major);
265
266         spin_lock(&major_names_spinlock);
267         for (n = &major_names[index]; *n; n = &(*n)->next) {
268                 if ((*n)->major == major)
269                         break;
270         }
271         if (!*n)
272                 *n = p;
273         else
274                 ret = -EBUSY;
275         spin_unlock(&major_names_spinlock);
276
277         if (ret < 0) {
278                 printk("register_blkdev: cannot get major %u for %s\n",
279                        major, name);
280                 kfree(p);
281         }
282 out:
283         mutex_unlock(&major_names_lock);
284         return ret;
285 }
286 EXPORT_SYMBOL(__register_blkdev);
287
288 void unregister_blkdev(unsigned int major, const char *name)
289 {
290         struct blk_major_name **n;
291         struct blk_major_name *p = NULL;
292         int index = major_to_index(major);
293
294         mutex_lock(&major_names_lock);
295         spin_lock(&major_names_spinlock);
296         for (n = &major_names[index]; *n; n = &(*n)->next)
297                 if ((*n)->major == major)
298                         break;
299         if (!*n || strcmp((*n)->name, name)) {
300                 WARN_ON(1);
301         } else {
302                 p = *n;
303                 *n = p->next;
304         }
305         spin_unlock(&major_names_spinlock);
306         mutex_unlock(&major_names_lock);
307         kfree(p);
308 }
309
310 EXPORT_SYMBOL(unregister_blkdev);
311
312 int blk_alloc_ext_minor(void)
313 {
314         int idx;
315
316         idx = ida_alloc_range(&ext_devt_ida, 0, NR_EXT_DEVT - 1, GFP_KERNEL);
317         if (idx == -ENOSPC)
318                 return -EBUSY;
319         return idx;
320 }
321
322 void blk_free_ext_minor(unsigned int minor)
323 {
324         ida_free(&ext_devt_ida, minor);
325 }
326
327 static char *bdevt_str(dev_t devt, char *buf)
328 {
329         if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
330                 char tbuf[BDEVT_SIZE];
331                 snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
332                 snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
333         } else
334                 snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
335
336         return buf;
337 }
338
339 void disk_uevent(struct gendisk *disk, enum kobject_action action)
340 {
341         struct block_device *part;
342         unsigned long idx;
343
344         rcu_read_lock();
345         xa_for_each(&disk->part_tbl, idx, part) {
346                 if (bdev_is_partition(part) && !bdev_nr_sectors(part))
347                         continue;
348                 if (!kobject_get_unless_zero(&part->bd_device.kobj))
349                         continue;
350
351                 rcu_read_unlock();
352                 kobject_uevent(bdev_kobj(part), action);
353                 put_device(&part->bd_device);
354                 rcu_read_lock();
355         }
356         rcu_read_unlock();
357 }
358 EXPORT_SYMBOL_GPL(disk_uevent);
359
360 int disk_scan_partitions(struct gendisk *disk, fmode_t mode)
361 {
362         struct block_device *bdev;
363         int ret = 0;
364
365         if (disk->flags & (GENHD_FL_NO_PART | GENHD_FL_HIDDEN))
366                 return -EINVAL;
367         if (test_bit(GD_SUPPRESS_PART_SCAN, &disk->state))
368                 return -EINVAL;
369         if (disk->open_partitions)
370                 return -EBUSY;
371
372         /*
373          * If the device is opened exclusively by current thread already, it's
374          * safe to scan partitons, otherwise, use bd_prepare_to_claim() to
375          * synchronize with other exclusive openers and other partition
376          * scanners.
377          */
378         if (!(mode & FMODE_EXCL)) {
379                 ret = bd_prepare_to_claim(disk->part0, disk_scan_partitions);
380                 if (ret)
381                         return ret;
382         }
383
384         set_bit(GD_NEED_PART_SCAN, &disk->state);
385         bdev = blkdev_get_by_dev(disk_devt(disk), mode & ~FMODE_EXCL, NULL);
386         if (IS_ERR(bdev))
387                 ret =  PTR_ERR(bdev);
388         else
389                 blkdev_put(bdev, mode & ~FMODE_EXCL);
390
391         /*
392          * If blkdev_get_by_dev() failed early, GD_NEED_PART_SCAN is still set,
393          * and this will cause that re-assemble partitioned raid device will
394          * creat partition for underlying disk.
395          */
396         clear_bit(GD_NEED_PART_SCAN, &disk->state);
397         if (!(mode & FMODE_EXCL))
398                 bd_abort_claiming(disk->part0, disk_scan_partitions);
399         return ret;
400 }
401
402 /**
403  * device_add_disk - add disk information to kernel list
404  * @parent: parent device for the disk
405  * @disk: per-device partitioning information
406  * @groups: Additional per-device sysfs groups
407  *
408  * This function registers the partitioning information in @disk
409  * with the kernel.
410  */
411 int __must_check device_add_disk(struct device *parent, struct gendisk *disk,
412                                  const struct attribute_group **groups)
413
414 {
415         struct device *ddev = disk_to_dev(disk);
416         int ret;
417
418         /* Only makes sense for bio-based to set ->poll_bio */
419         if (queue_is_mq(disk->queue) && disk->fops->poll_bio)
420                 return -EINVAL;
421
422         /*
423          * The disk queue should now be all set with enough information about
424          * the device for the elevator code to pick an adequate default
425          * elevator if one is needed, that is, for devices requesting queue
426          * registration.
427          */
428         elevator_init_mq(disk->queue);
429
430         /*
431          * If the driver provides an explicit major number it also must provide
432          * the number of minors numbers supported, and those will be used to
433          * setup the gendisk.
434          * Otherwise just allocate the device numbers for both the whole device
435          * and all partitions from the extended dev_t space.
436          */
437         ret = -EINVAL;
438         if (disk->major) {
439                 if (WARN_ON(!disk->minors))
440                         goto out_exit_elevator;
441
442                 if (disk->minors > DISK_MAX_PARTS) {
443                         pr_err("block: can't allocate more than %d partitions\n",
444                                 DISK_MAX_PARTS);
445                         disk->minors = DISK_MAX_PARTS;
446                 }
447                 if (disk->first_minor + disk->minors > MINORMASK + 1)
448                         goto out_exit_elevator;
449         } else {
450                 if (WARN_ON(disk->minors))
451                         goto out_exit_elevator;
452
453                 ret = blk_alloc_ext_minor();
454                 if (ret < 0)
455                         goto out_exit_elevator;
456                 disk->major = BLOCK_EXT_MAJOR;
457                 disk->first_minor = ret;
458         }
459
460         /* delay uevents, until we scanned partition table */
461         dev_set_uevent_suppress(ddev, 1);
462
463         ddev->parent = parent;
464         ddev->groups = groups;
465         dev_set_name(ddev, "%s", disk->disk_name);
466         if (!(disk->flags & GENHD_FL_HIDDEN))
467                 ddev->devt = MKDEV(disk->major, disk->first_minor);
468         ret = device_add(ddev);
469         if (ret)
470                 goto out_free_ext_minor;
471
472         ret = disk_alloc_events(disk);
473         if (ret)
474                 goto out_device_del;
475
476         if (!sysfs_deprecated) {
477                 ret = sysfs_create_link(block_depr, &ddev->kobj,
478                                         kobject_name(&ddev->kobj));
479                 if (ret)
480                         goto out_device_del;
481         }
482
483         /*
484          * avoid probable deadlock caused by allocating memory with
485          * GFP_KERNEL in runtime_resume callback of its all ancestor
486          * devices
487          */
488         pm_runtime_set_memalloc_noio(ddev, true);
489
490         ret = blk_integrity_add(disk);
491         if (ret)
492                 goto out_del_block_link;
493
494         disk->part0->bd_holder_dir =
495                 kobject_create_and_add("holders", &ddev->kobj);
496         if (!disk->part0->bd_holder_dir) {
497                 ret = -ENOMEM;
498                 goto out_del_integrity;
499         }
500         disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
501         if (!disk->slave_dir) {
502                 ret = -ENOMEM;
503                 goto out_put_holder_dir;
504         }
505
506         ret = bd_register_pending_holders(disk);
507         if (ret < 0)
508                 goto out_put_slave_dir;
509
510         ret = blk_register_queue(disk);
511         if (ret)
512                 goto out_put_slave_dir;
513
514         if (!(disk->flags & GENHD_FL_HIDDEN)) {
515                 ret = bdi_register(disk->bdi, "%u:%u",
516                                    disk->major, disk->first_minor);
517                 if (ret)
518                         goto out_unregister_queue;
519                 bdi_set_owner(disk->bdi, ddev);
520                 ret = sysfs_create_link(&ddev->kobj,
521                                         &disk->bdi->dev->kobj, "bdi");
522                 if (ret)
523                         goto out_unregister_bdi;
524
525                 /* Make sure the first partition scan will be proceed */
526                 if (get_capacity(disk) && !(disk->flags & GENHD_FL_NO_PART) &&
527                     !test_bit(GD_SUPPRESS_PART_SCAN, &disk->state))
528                         set_bit(GD_NEED_PART_SCAN, &disk->state);
529
530                 bdev_add(disk->part0, ddev->devt);
531                 if (get_capacity(disk))
532                         disk_scan_partitions(disk, FMODE_READ);
533
534                 /*
535                  * Announce the disk and partitions after all partitions are
536                  * created. (for hidden disks uevents remain suppressed forever)
537                  */
538                 dev_set_uevent_suppress(ddev, 0);
539                 disk_uevent(disk, KOBJ_ADD);
540         } else {
541                 /*
542                  * Even if the block_device for a hidden gendisk is not
543                  * registered, it needs to have a valid bd_dev so that the
544                  * freeing of the dynamic major works.
545                  */
546                 disk->part0->bd_dev = MKDEV(disk->major, disk->first_minor);
547         }
548
549         disk_update_readahead(disk);
550         disk_add_events(disk);
551         set_bit(GD_ADDED, &disk->state);
552         return 0;
553
554 out_unregister_bdi:
555         if (!(disk->flags & GENHD_FL_HIDDEN))
556                 bdi_unregister(disk->bdi);
557 out_unregister_queue:
558         blk_unregister_queue(disk);
559         rq_qos_exit(disk->queue);
560 out_put_slave_dir:
561         kobject_put(disk->slave_dir);
562         disk->slave_dir = NULL;
563 out_put_holder_dir:
564         kobject_put(disk->part0->bd_holder_dir);
565 out_del_integrity:
566         blk_integrity_del(disk);
567 out_del_block_link:
568         if (!sysfs_deprecated)
569                 sysfs_remove_link(block_depr, dev_name(ddev));
570 out_device_del:
571         device_del(ddev);
572 out_free_ext_minor:
573         if (disk->major == BLOCK_EXT_MAJOR)
574                 blk_free_ext_minor(disk->first_minor);
575 out_exit_elevator:
576         if (disk->queue->elevator)
577                 elevator_exit(disk->queue);
578         return ret;
579 }
580 EXPORT_SYMBOL(device_add_disk);
581
582 /**
583  * blk_mark_disk_dead - mark a disk as dead
584  * @disk: disk to mark as dead
585  *
586  * Mark as disk as dead (e.g. surprise removed) and don't accept any new I/O
587  * to this disk.
588  */
589 void blk_mark_disk_dead(struct gendisk *disk)
590 {
591         set_bit(GD_DEAD, &disk->state);
592         blk_queue_start_drain(disk->queue);
593 }
594 EXPORT_SYMBOL_GPL(blk_mark_disk_dead);
595
596 /**
597  * del_gendisk - remove the gendisk
598  * @disk: the struct gendisk to remove
599  *
600  * Removes the gendisk and all its associated resources. This deletes the
601  * partitions associated with the gendisk, and unregisters the associated
602  * request_queue.
603  *
604  * This is the counter to the respective __device_add_disk() call.
605  *
606  * The final removal of the struct gendisk happens when its refcount reaches 0
607  * with put_disk(), which should be called after del_gendisk(), if
608  * __device_add_disk() was used.
609  *
610  * Drivers exist which depend on the release of the gendisk to be synchronous,
611  * it should not be deferred.
612  *
613  * Context: can sleep
614  */
615 void del_gendisk(struct gendisk *disk)
616 {
617         struct request_queue *q = disk->queue;
618
619         might_sleep();
620
621         if (WARN_ON_ONCE(!disk_live(disk) && !(disk->flags & GENHD_FL_HIDDEN)))
622                 return;
623
624         blk_integrity_del(disk);
625         disk_del_events(disk);
626
627         mutex_lock(&disk->open_mutex);
628         remove_inode_hash(disk->part0->bd_inode);
629         blk_drop_partitions(disk);
630         mutex_unlock(&disk->open_mutex);
631
632         fsync_bdev(disk->part0);
633         __invalidate_device(disk->part0, true);
634
635         /*
636          * Fail any new I/O.
637          */
638         set_bit(GD_DEAD, &disk->state);
639         if (test_bit(GD_OWNS_QUEUE, &disk->state))
640                 blk_queue_flag_set(QUEUE_FLAG_DYING, q);
641         set_capacity(disk, 0);
642
643         /*
644          * Prevent new I/O from crossing bio_queue_enter().
645          */
646         blk_queue_start_drain(q);
647
648         if (!(disk->flags & GENHD_FL_HIDDEN)) {
649                 sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
650
651                 /*
652                  * Unregister bdi before releasing device numbers (as they can
653                  * get reused and we'd get clashes in sysfs).
654                  */
655                 bdi_unregister(disk->bdi);
656         }
657
658         blk_unregister_queue(disk);
659
660         kobject_put(disk->part0->bd_holder_dir);
661         kobject_put(disk->slave_dir);
662         disk->slave_dir = NULL;
663
664         part_stat_set_all(disk->part0, 0);
665         disk->part0->bd_stamp = 0;
666         if (!sysfs_deprecated)
667                 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
668         pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
669         device_del(disk_to_dev(disk));
670
671         blk_mq_freeze_queue_wait(q);
672
673         blk_throtl_cancel_bios(disk);
674
675         blk_sync_queue(q);
676         blk_flush_integrity();
677         blk_mq_cancel_work_sync(q);
678
679         blk_mq_quiesce_queue(q);
680         if (q->elevator) {
681                 mutex_lock(&q->sysfs_lock);
682                 elevator_exit(q);
683                 mutex_unlock(&q->sysfs_lock);
684         }
685         rq_qos_exit(q);
686         blk_mq_unquiesce_queue(q);
687
688         /*
689          * If the disk does not own the queue, allow using passthrough requests
690          * again.  Else leave the queue frozen to fail all I/O.
691          */
692         if (!test_bit(GD_OWNS_QUEUE, &disk->state)) {
693                 blk_queue_flag_clear(QUEUE_FLAG_INIT_DONE, q);
694                 __blk_mq_unfreeze_queue(q, true);
695         } else {
696                 if (queue_is_mq(q))
697                         blk_mq_exit_queue(q);
698         }
699 }
700 EXPORT_SYMBOL(del_gendisk);
701
702 /**
703  * invalidate_disk - invalidate the disk
704  * @disk: the struct gendisk to invalidate
705  *
706  * A helper to invalidates the disk. It will clean the disk's associated
707  * buffer/page caches and reset its internal states so that the disk
708  * can be reused by the drivers.
709  *
710  * Context: can sleep
711  */
712 void invalidate_disk(struct gendisk *disk)
713 {
714         struct block_device *bdev = disk->part0;
715
716         invalidate_bdev(bdev);
717         bdev->bd_inode->i_mapping->wb_err = 0;
718         set_capacity(disk, 0);
719 }
720 EXPORT_SYMBOL(invalidate_disk);
721
722 /* sysfs access to bad-blocks list. */
723 static ssize_t disk_badblocks_show(struct device *dev,
724                                         struct device_attribute *attr,
725                                         char *page)
726 {
727         struct gendisk *disk = dev_to_disk(dev);
728
729         if (!disk->bb)
730                 return sprintf(page, "\n");
731
732         return badblocks_show(disk->bb, page, 0);
733 }
734
735 static ssize_t disk_badblocks_store(struct device *dev,
736                                         struct device_attribute *attr,
737                                         const char *page, size_t len)
738 {
739         struct gendisk *disk = dev_to_disk(dev);
740
741         if (!disk->bb)
742                 return -ENXIO;
743
744         return badblocks_store(disk->bb, page, len, 0);
745 }
746
747 #ifdef CONFIG_BLOCK_LEGACY_AUTOLOAD
748 void blk_request_module(dev_t devt)
749 {
750         unsigned int major = MAJOR(devt);
751         struct blk_major_name **n;
752
753         mutex_lock(&major_names_lock);
754         for (n = &major_names[major_to_index(major)]; *n; n = &(*n)->next) {
755                 if ((*n)->major == major && (*n)->probe) {
756                         (*n)->probe(devt);
757                         mutex_unlock(&major_names_lock);
758                         return;
759                 }
760         }
761         mutex_unlock(&major_names_lock);
762
763         if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
764                 /* Make old-style 2.4 aliases work */
765                 request_module("block-major-%d", MAJOR(devt));
766 }
767 #endif /* CONFIG_BLOCK_LEGACY_AUTOLOAD */
768
769 /*
770  * print a full list of all partitions - intended for places where the root
771  * filesystem can't be mounted and thus to give the victim some idea of what
772  * went wrong
773  */
774 void __init printk_all_partitions(void)
775 {
776         struct class_dev_iter iter;
777         struct device *dev;
778
779         class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
780         while ((dev = class_dev_iter_next(&iter))) {
781                 struct gendisk *disk = dev_to_disk(dev);
782                 struct block_device *part;
783                 char devt_buf[BDEVT_SIZE];
784                 unsigned long idx;
785
786                 /*
787                  * Don't show empty devices or things that have been
788                  * suppressed
789                  */
790                 if (get_capacity(disk) == 0 || (disk->flags & GENHD_FL_HIDDEN))
791                         continue;
792
793                 /*
794                  * Note, unlike /proc/partitions, I am showing the numbers in
795                  * hex - the same format as the root= option takes.
796                  */
797                 rcu_read_lock();
798                 xa_for_each(&disk->part_tbl, idx, part) {
799                         if (!bdev_nr_sectors(part))
800                                 continue;
801                         printk("%s%s %10llu %pg %s",
802                                bdev_is_partition(part) ? "  " : "",
803                                bdevt_str(part->bd_dev, devt_buf),
804                                bdev_nr_sectors(part) >> 1, part,
805                                part->bd_meta_info ?
806                                         part->bd_meta_info->uuid : "");
807                         if (bdev_is_partition(part))
808                                 printk("\n");
809                         else if (dev->parent && dev->parent->driver)
810                                 printk(" driver: %s\n",
811                                         dev->parent->driver->name);
812                         else
813                                 printk(" (driver?)\n");
814                 }
815                 rcu_read_unlock();
816         }
817         class_dev_iter_exit(&iter);
818 }
819
820 #ifdef CONFIG_PROC_FS
821 /* iterator */
822 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
823 {
824         loff_t skip = *pos;
825         struct class_dev_iter *iter;
826         struct device *dev;
827
828         iter = kmalloc(sizeof(*iter), GFP_KERNEL);
829         if (!iter)
830                 return ERR_PTR(-ENOMEM);
831
832         seqf->private = iter;
833         class_dev_iter_init(iter, &block_class, NULL, &disk_type);
834         do {
835                 dev = class_dev_iter_next(iter);
836                 if (!dev)
837                         return NULL;
838         } while (skip--);
839
840         return dev_to_disk(dev);
841 }
842
843 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
844 {
845         struct device *dev;
846
847         (*pos)++;
848         dev = class_dev_iter_next(seqf->private);
849         if (dev)
850                 return dev_to_disk(dev);
851
852         return NULL;
853 }
854
855 static void disk_seqf_stop(struct seq_file *seqf, void *v)
856 {
857         struct class_dev_iter *iter = seqf->private;
858
859         /* stop is called even after start failed :-( */
860         if (iter) {
861                 class_dev_iter_exit(iter);
862                 kfree(iter);
863                 seqf->private = NULL;
864         }
865 }
866
867 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
868 {
869         void *p;
870
871         p = disk_seqf_start(seqf, pos);
872         if (!IS_ERR_OR_NULL(p) && !*pos)
873                 seq_puts(seqf, "major minor  #blocks  name\n\n");
874         return p;
875 }
876
877 static int show_partition(struct seq_file *seqf, void *v)
878 {
879         struct gendisk *sgp = v;
880         struct block_device *part;
881         unsigned long idx;
882
883         if (!get_capacity(sgp) || (sgp->flags & GENHD_FL_HIDDEN))
884                 return 0;
885
886         rcu_read_lock();
887         xa_for_each(&sgp->part_tbl, idx, part) {
888                 if (!bdev_nr_sectors(part))
889                         continue;
890                 seq_printf(seqf, "%4d  %7d %10llu %pg\n",
891                            MAJOR(part->bd_dev), MINOR(part->bd_dev),
892                            bdev_nr_sectors(part) >> 1, part);
893         }
894         rcu_read_unlock();
895         return 0;
896 }
897
898 static const struct seq_operations partitions_op = {
899         .start  = show_partition_start,
900         .next   = disk_seqf_next,
901         .stop   = disk_seqf_stop,
902         .show   = show_partition
903 };
904 #endif
905
906 static int __init genhd_device_init(void)
907 {
908         int error;
909
910         block_class.dev_kobj = sysfs_dev_block_kobj;
911         error = class_register(&block_class);
912         if (unlikely(error))
913                 return error;
914         blk_dev_init();
915
916         register_blkdev(BLOCK_EXT_MAJOR, "blkext");
917
918         /* create top-level block dir */
919         if (!sysfs_deprecated)
920                 block_depr = kobject_create_and_add("block", NULL);
921         return 0;
922 }
923
924 subsys_initcall(genhd_device_init);
925
926 static ssize_t disk_range_show(struct device *dev,
927                                struct device_attribute *attr, char *buf)
928 {
929         struct gendisk *disk = dev_to_disk(dev);
930
931         return sprintf(buf, "%d\n", disk->minors);
932 }
933
934 static ssize_t disk_ext_range_show(struct device *dev,
935                                    struct device_attribute *attr, char *buf)
936 {
937         struct gendisk *disk = dev_to_disk(dev);
938
939         return sprintf(buf, "%d\n",
940                 (disk->flags & GENHD_FL_NO_PART) ? 1 : DISK_MAX_PARTS);
941 }
942
943 static ssize_t disk_removable_show(struct device *dev,
944                                    struct device_attribute *attr, char *buf)
945 {
946         struct gendisk *disk = dev_to_disk(dev);
947
948         return sprintf(buf, "%d\n",
949                        (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
950 }
951
952 static ssize_t disk_hidden_show(struct device *dev,
953                                    struct device_attribute *attr, char *buf)
954 {
955         struct gendisk *disk = dev_to_disk(dev);
956
957         return sprintf(buf, "%d\n",
958                        (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
959 }
960
961 static ssize_t disk_ro_show(struct device *dev,
962                                    struct device_attribute *attr, char *buf)
963 {
964         struct gendisk *disk = dev_to_disk(dev);
965
966         return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
967 }
968
969 ssize_t part_size_show(struct device *dev,
970                        struct device_attribute *attr, char *buf)
971 {
972         return sprintf(buf, "%llu\n", bdev_nr_sectors(dev_to_bdev(dev)));
973 }
974
975 ssize_t part_stat_show(struct device *dev,
976                        struct device_attribute *attr, char *buf)
977 {
978         struct block_device *bdev = dev_to_bdev(dev);
979         struct request_queue *q = bdev_get_queue(bdev);
980         struct disk_stats stat;
981         unsigned int inflight;
982
983         if (queue_is_mq(q))
984                 inflight = blk_mq_in_flight(q, bdev);
985         else
986                 inflight = part_in_flight(bdev);
987
988         if (inflight) {
989                 part_stat_lock();
990                 update_io_ticks(bdev, jiffies, true);
991                 part_stat_unlock();
992         }
993         part_stat_read_all(bdev, &stat);
994         return sprintf(buf,
995                 "%8lu %8lu %8llu %8u "
996                 "%8lu %8lu %8llu %8u "
997                 "%8u %8u %8u "
998                 "%8lu %8lu %8llu %8u "
999                 "%8lu %8u"
1000                 "\n",
1001                 stat.ios[STAT_READ],
1002                 stat.merges[STAT_READ],
1003                 (unsigned long long)stat.sectors[STAT_READ],
1004                 (unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1005                 stat.ios[STAT_WRITE],
1006                 stat.merges[STAT_WRITE],
1007                 (unsigned long long)stat.sectors[STAT_WRITE],
1008                 (unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1009                 inflight,
1010                 jiffies_to_msecs(stat.io_ticks),
1011                 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1012                                       stat.nsecs[STAT_WRITE] +
1013                                       stat.nsecs[STAT_DISCARD] +
1014                                       stat.nsecs[STAT_FLUSH],
1015                                                 NSEC_PER_MSEC),
1016                 stat.ios[STAT_DISCARD],
1017                 stat.merges[STAT_DISCARD],
1018                 (unsigned long long)stat.sectors[STAT_DISCARD],
1019                 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1020                 stat.ios[STAT_FLUSH],
1021                 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1022 }
1023
1024 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1025                            char *buf)
1026 {
1027         struct block_device *bdev = dev_to_bdev(dev);
1028         struct request_queue *q = bdev_get_queue(bdev);
1029         unsigned int inflight[2];
1030
1031         if (queue_is_mq(q))
1032                 blk_mq_in_flight_rw(q, bdev, inflight);
1033         else
1034                 part_in_flight_rw(bdev, inflight);
1035
1036         return sprintf(buf, "%8u %8u\n", inflight[0], inflight[1]);
1037 }
1038
1039 static ssize_t disk_capability_show(struct device *dev,
1040                                     struct device_attribute *attr, char *buf)
1041 {
1042         struct gendisk *disk = dev_to_disk(dev);
1043
1044         return sprintf(buf, "%x\n", disk->flags);
1045 }
1046
1047 static ssize_t disk_alignment_offset_show(struct device *dev,
1048                                           struct device_attribute *attr,
1049                                           char *buf)
1050 {
1051         struct gendisk *disk = dev_to_disk(dev);
1052
1053         return sprintf(buf, "%d\n", bdev_alignment_offset(disk->part0));
1054 }
1055
1056 static ssize_t disk_discard_alignment_show(struct device *dev,
1057                                            struct device_attribute *attr,
1058                                            char *buf)
1059 {
1060         struct gendisk *disk = dev_to_disk(dev);
1061
1062         return sprintf(buf, "%d\n", bdev_alignment_offset(disk->part0));
1063 }
1064
1065 static ssize_t diskseq_show(struct device *dev,
1066                             struct device_attribute *attr, char *buf)
1067 {
1068         struct gendisk *disk = dev_to_disk(dev);
1069
1070         return sprintf(buf, "%llu\n", disk->diskseq);
1071 }
1072
1073 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1074 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1075 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1076 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1077 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1078 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1079 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1080 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1081 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1082 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1083 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1084 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1085 static DEVICE_ATTR(diskseq, 0444, diskseq_show, NULL);
1086
1087 #ifdef CONFIG_FAIL_MAKE_REQUEST
1088 ssize_t part_fail_show(struct device *dev,
1089                        struct device_attribute *attr, char *buf)
1090 {
1091         return sprintf(buf, "%d\n", dev_to_bdev(dev)->bd_make_it_fail);
1092 }
1093
1094 ssize_t part_fail_store(struct device *dev,
1095                         struct device_attribute *attr,
1096                         const char *buf, size_t count)
1097 {
1098         int i;
1099
1100         if (count > 0 && sscanf(buf, "%d", &i) > 0)
1101                 dev_to_bdev(dev)->bd_make_it_fail = i;
1102
1103         return count;
1104 }
1105
1106 static struct device_attribute dev_attr_fail =
1107         __ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1108 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1109
1110 #ifdef CONFIG_FAIL_IO_TIMEOUT
1111 static struct device_attribute dev_attr_fail_timeout =
1112         __ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1113 #endif
1114
1115 static struct attribute *disk_attrs[] = {
1116         &dev_attr_range.attr,
1117         &dev_attr_ext_range.attr,
1118         &dev_attr_removable.attr,
1119         &dev_attr_hidden.attr,
1120         &dev_attr_ro.attr,
1121         &dev_attr_size.attr,
1122         &dev_attr_alignment_offset.attr,
1123         &dev_attr_discard_alignment.attr,
1124         &dev_attr_capability.attr,
1125         &dev_attr_stat.attr,
1126         &dev_attr_inflight.attr,
1127         &dev_attr_badblocks.attr,
1128         &dev_attr_events.attr,
1129         &dev_attr_events_async.attr,
1130         &dev_attr_events_poll_msecs.attr,
1131         &dev_attr_diskseq.attr,
1132 #ifdef CONFIG_FAIL_MAKE_REQUEST
1133         &dev_attr_fail.attr,
1134 #endif
1135 #ifdef CONFIG_FAIL_IO_TIMEOUT
1136         &dev_attr_fail_timeout.attr,
1137 #endif
1138         NULL
1139 };
1140
1141 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1142 {
1143         struct device *dev = container_of(kobj, typeof(*dev), kobj);
1144         struct gendisk *disk = dev_to_disk(dev);
1145
1146         if (a == &dev_attr_badblocks.attr && !disk->bb)
1147                 return 0;
1148         return a->mode;
1149 }
1150
1151 static struct attribute_group disk_attr_group = {
1152         .attrs = disk_attrs,
1153         .is_visible = disk_visible,
1154 };
1155
1156 static const struct attribute_group *disk_attr_groups[] = {
1157         &disk_attr_group,
1158 #ifdef CONFIG_BLK_DEV_IO_TRACE
1159         &blk_trace_attr_group,
1160 #endif
1161         NULL
1162 };
1163
1164 /**
1165  * disk_release - releases all allocated resources of the gendisk
1166  * @dev: the device representing this disk
1167  *
1168  * This function releases all allocated resources of the gendisk.
1169  *
1170  * Drivers which used __device_add_disk() have a gendisk with a request_queue
1171  * assigned. Since the request_queue sits on top of the gendisk for these
1172  * drivers we also call blk_put_queue() for them, and we expect the
1173  * request_queue refcount to reach 0 at this point, and so the request_queue
1174  * will also be freed prior to the disk.
1175  *
1176  * Context: can sleep
1177  */
1178 static void disk_release(struct device *dev)
1179 {
1180         struct gendisk *disk = dev_to_disk(dev);
1181
1182         might_sleep();
1183         WARN_ON_ONCE(disk_live(disk));
1184
1185         blk_trace_remove(disk->queue);
1186
1187         /*
1188          * To undo the all initialization from blk_mq_init_allocated_queue in
1189          * case of a probe failure where add_disk is never called we have to
1190          * call blk_mq_exit_queue here. We can't do this for the more common
1191          * teardown case (yet) as the tagset can be gone by the time the disk
1192          * is released once it was added.
1193          */
1194         if (queue_is_mq(disk->queue) &&
1195             test_bit(GD_OWNS_QUEUE, &disk->state) &&
1196             !test_bit(GD_ADDED, &disk->state))
1197                 blk_mq_exit_queue(disk->queue);
1198
1199         blkcg_exit_disk(disk);
1200
1201         bioset_exit(&disk->bio_split);
1202
1203         disk_release_events(disk);
1204         kfree(disk->random);
1205         disk_free_zone_bitmaps(disk);
1206         xa_destroy(&disk->part_tbl);
1207
1208         disk->queue->disk = NULL;
1209         blk_put_queue(disk->queue);
1210
1211         if (test_bit(GD_ADDED, &disk->state) && disk->fops->free_disk)
1212                 disk->fops->free_disk(disk);
1213
1214         iput(disk->part0->bd_inode);    /* frees the disk */
1215 }
1216
1217 static int block_uevent(struct device *dev, struct kobj_uevent_env *env)
1218 {
1219         struct gendisk *disk = dev_to_disk(dev);
1220
1221         return add_uevent_var(env, "DISKSEQ=%llu", disk->diskseq);
1222 }
1223
1224 struct class block_class = {
1225         .name           = "block",
1226         .dev_uevent     = block_uevent,
1227 };
1228
1229 static char *block_devnode(struct device *dev, umode_t *mode,
1230                            kuid_t *uid, kgid_t *gid)
1231 {
1232         struct gendisk *disk = dev_to_disk(dev);
1233
1234         if (disk->fops->devnode)
1235                 return disk->fops->devnode(disk, mode);
1236         return NULL;
1237 }
1238
1239 const struct device_type disk_type = {
1240         .name           = "disk",
1241         .groups         = disk_attr_groups,
1242         .release        = disk_release,
1243         .devnode        = block_devnode,
1244 };
1245
1246 #ifdef CONFIG_PROC_FS
1247 /*
1248  * aggregate disk stat collector.  Uses the same stats that the sysfs
1249  * entries do, above, but makes them available through one seq_file.
1250  *
1251  * The output looks suspiciously like /proc/partitions with a bunch of
1252  * extra fields.
1253  */
1254 static int diskstats_show(struct seq_file *seqf, void *v)
1255 {
1256         struct gendisk *gp = v;
1257         struct block_device *hd;
1258         unsigned int inflight;
1259         struct disk_stats stat;
1260         unsigned long idx;
1261
1262         /*
1263         if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1264                 seq_puts(seqf,  "major minor name"
1265                                 "     rio rmerge rsect ruse wio wmerge "
1266                                 "wsect wuse running use aveq"
1267                                 "\n\n");
1268         */
1269
1270         rcu_read_lock();
1271         xa_for_each(&gp->part_tbl, idx, hd) {
1272                 if (bdev_is_partition(hd) && !bdev_nr_sectors(hd))
1273                         continue;
1274                 if (queue_is_mq(gp->queue))
1275                         inflight = blk_mq_in_flight(gp->queue, hd);
1276                 else
1277                         inflight = part_in_flight(hd);
1278
1279                 if (inflight) {
1280                         part_stat_lock();
1281                         update_io_ticks(hd, jiffies, true);
1282                         part_stat_unlock();
1283                 }
1284                 part_stat_read_all(hd, &stat);
1285                 seq_printf(seqf, "%4d %7d %pg "
1286                            "%lu %lu %lu %u "
1287                            "%lu %lu %lu %u "
1288                            "%u %u %u "
1289                            "%lu %lu %lu %u "
1290                            "%lu %u"
1291                            "\n",
1292                            MAJOR(hd->bd_dev), MINOR(hd->bd_dev), hd,
1293                            stat.ios[STAT_READ],
1294                            stat.merges[STAT_READ],
1295                            stat.sectors[STAT_READ],
1296                            (unsigned int)div_u64(stat.nsecs[STAT_READ],
1297                                                         NSEC_PER_MSEC),
1298                            stat.ios[STAT_WRITE],
1299                            stat.merges[STAT_WRITE],
1300                            stat.sectors[STAT_WRITE],
1301                            (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1302                                                         NSEC_PER_MSEC),
1303                            inflight,
1304                            jiffies_to_msecs(stat.io_ticks),
1305                            (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1306                                                  stat.nsecs[STAT_WRITE] +
1307                                                  stat.nsecs[STAT_DISCARD] +
1308                                                  stat.nsecs[STAT_FLUSH],
1309                                                         NSEC_PER_MSEC),
1310                            stat.ios[STAT_DISCARD],
1311                            stat.merges[STAT_DISCARD],
1312                            stat.sectors[STAT_DISCARD],
1313                            (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1314                                                  NSEC_PER_MSEC),
1315                            stat.ios[STAT_FLUSH],
1316                            (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1317                                                  NSEC_PER_MSEC)
1318                         );
1319         }
1320         rcu_read_unlock();
1321
1322         return 0;
1323 }
1324
1325 static const struct seq_operations diskstats_op = {
1326         .start  = disk_seqf_start,
1327         .next   = disk_seqf_next,
1328         .stop   = disk_seqf_stop,
1329         .show   = diskstats_show
1330 };
1331
1332 static int __init proc_genhd_init(void)
1333 {
1334         proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1335         proc_create_seq("partitions", 0, NULL, &partitions_op);
1336         return 0;
1337 }
1338 module_init(proc_genhd_init);
1339 #endif /* CONFIG_PROC_FS */
1340
1341 dev_t part_devt(struct gendisk *disk, u8 partno)
1342 {
1343         struct block_device *part;
1344         dev_t devt = 0;
1345
1346         rcu_read_lock();
1347         part = xa_load(&disk->part_tbl, partno);
1348         if (part)
1349                 devt = part->bd_dev;
1350         rcu_read_unlock();
1351
1352         return devt;
1353 }
1354
1355 dev_t blk_lookup_devt(const char *name, int partno)
1356 {
1357         dev_t devt = MKDEV(0, 0);
1358         struct class_dev_iter iter;
1359         struct device *dev;
1360
1361         class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1362         while ((dev = class_dev_iter_next(&iter))) {
1363                 struct gendisk *disk = dev_to_disk(dev);
1364
1365                 if (strcmp(dev_name(dev), name))
1366                         continue;
1367
1368                 if (partno < disk->minors) {
1369                         /* We need to return the right devno, even
1370                          * if the partition doesn't exist yet.
1371                          */
1372                         devt = MKDEV(MAJOR(dev->devt),
1373                                      MINOR(dev->devt) + partno);
1374                 } else {
1375                         devt = part_devt(disk, partno);
1376                         if (devt)
1377                                 break;
1378                 }
1379         }
1380         class_dev_iter_exit(&iter);
1381         return devt;
1382 }
1383
1384 struct gendisk *__alloc_disk_node(struct request_queue *q, int node_id,
1385                 struct lock_class_key *lkclass)
1386 {
1387         struct gendisk *disk;
1388
1389         disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1390         if (!disk)
1391                 return NULL;
1392
1393         if (bioset_init(&disk->bio_split, BIO_POOL_SIZE, 0, 0))
1394                 goto out_free_disk;
1395
1396         disk->bdi = bdi_alloc(node_id);
1397         if (!disk->bdi)
1398                 goto out_free_bioset;
1399
1400         /* bdev_alloc() might need the queue, set before the first call */
1401         disk->queue = q;
1402
1403         disk->part0 = bdev_alloc(disk, 0);
1404         if (!disk->part0)
1405                 goto out_free_bdi;
1406
1407         disk->node_id = node_id;
1408         mutex_init(&disk->open_mutex);
1409         xa_init(&disk->part_tbl);
1410         if (xa_insert(&disk->part_tbl, 0, disk->part0, GFP_KERNEL))
1411                 goto out_destroy_part_tbl;
1412
1413         if (blkcg_init_disk(disk))
1414                 goto out_erase_part0;
1415
1416         rand_initialize_disk(disk);
1417         disk_to_dev(disk)->class = &block_class;
1418         disk_to_dev(disk)->type = &disk_type;
1419         device_initialize(disk_to_dev(disk));
1420         inc_diskseq(disk);
1421         q->disk = disk;
1422         lockdep_init_map(&disk->lockdep_map, "(bio completion)", lkclass, 0);
1423 #ifdef CONFIG_BLOCK_HOLDER_DEPRECATED
1424         INIT_LIST_HEAD(&disk->slave_bdevs);
1425 #endif
1426         return disk;
1427
1428 out_erase_part0:
1429         xa_erase(&disk->part_tbl, 0);
1430 out_destroy_part_tbl:
1431         xa_destroy(&disk->part_tbl);
1432         disk->part0->bd_disk = NULL;
1433         iput(disk->part0->bd_inode);
1434 out_free_bdi:
1435         bdi_put(disk->bdi);
1436 out_free_bioset:
1437         bioset_exit(&disk->bio_split);
1438 out_free_disk:
1439         kfree(disk);
1440         return NULL;
1441 }
1442
1443 struct gendisk *__blk_alloc_disk(int node, struct lock_class_key *lkclass)
1444 {
1445         struct request_queue *q;
1446         struct gendisk *disk;
1447
1448         q = blk_alloc_queue(node, false);
1449         if (!q)
1450                 return NULL;
1451
1452         disk = __alloc_disk_node(q, node, lkclass);
1453         if (!disk) {
1454                 blk_put_queue(q);
1455                 return NULL;
1456         }
1457         set_bit(GD_OWNS_QUEUE, &disk->state);
1458         return disk;
1459 }
1460 EXPORT_SYMBOL(__blk_alloc_disk);
1461
1462 /**
1463  * put_disk - decrements the gendisk refcount
1464  * @disk: the struct gendisk to decrement the refcount for
1465  *
1466  * This decrements the refcount for the struct gendisk. When this reaches 0
1467  * we'll have disk_release() called.
1468  *
1469  * Note: for blk-mq disk put_disk must be called before freeing the tag_set
1470  * when handling probe errors (that is before add_disk() is called).
1471  *
1472  * Context: Any context, but the last reference must not be dropped from
1473  *          atomic context.
1474  */
1475 void put_disk(struct gendisk *disk)
1476 {
1477         if (disk)
1478                 put_device(disk_to_dev(disk));
1479 }
1480 EXPORT_SYMBOL(put_disk);
1481
1482 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1483 {
1484         char event[] = "DISK_RO=1";
1485         char *envp[] = { event, NULL };
1486
1487         if (!ro)
1488                 event[8] = '0';
1489         kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1490 }
1491
1492 /**
1493  * set_disk_ro - set a gendisk read-only
1494  * @disk:       gendisk to operate on
1495  * @read_only:  %true to set the disk read-only, %false set the disk read/write
1496  *
1497  * This function is used to indicate whether a given disk device should have its
1498  * read-only flag set. set_disk_ro() is typically used by device drivers to
1499  * indicate whether the underlying physical device is write-protected.
1500  */
1501 void set_disk_ro(struct gendisk *disk, bool read_only)
1502 {
1503         if (read_only) {
1504                 if (test_and_set_bit(GD_READ_ONLY, &disk->state))
1505                         return;
1506         } else {
1507                 if (!test_and_clear_bit(GD_READ_ONLY, &disk->state))
1508                         return;
1509         }
1510         set_disk_ro_uevent(disk, read_only);
1511 }
1512 EXPORT_SYMBOL(set_disk_ro);
1513
1514 void inc_diskseq(struct gendisk *disk)
1515 {
1516         disk->diskseq = atomic64_inc_return(&diskseq);
1517 }