1 // SPDX-License-Identifier: GPL-2.0
6 #include <linux/module.h>
7 #include <linux/ctype.h>
9 #include <linux/genhd.h>
10 #include <linux/kdev_t.h>
11 #include <linux/kernel.h>
12 #include <linux/blkdev.h>
13 #include <linux/backing-dev.h>
14 #include <linux/init.h>
15 #include <linux/spinlock.h>
16 #include <linux/proc_fs.h>
17 #include <linux/seq_file.h>
18 #include <linux/slab.h>
19 #include <linux/kmod.h>
20 #include <linux/mutex.h>
21 #include <linux/idr.h>
22 #include <linux/log2.h>
23 #include <linux/pm_runtime.h>
24 #include <linux/badblocks.h>
28 static struct kobject *block_depr;
31 struct bdev_map *next;
35 struct kobject *(*probe)(dev_t, int *, void *);
36 int (*lock)(dev_t, void *);
39 static DEFINE_MUTEX(bdev_map_lock);
41 /* for extended dynamic devt allocation, currently only one major is used */
42 #define NR_EXT_DEVT (1 << MINORBITS)
44 /* For extended devt allocation. ext_devt_lock prevents look up
45 * results from going away underneath its user.
47 static DEFINE_SPINLOCK(ext_devt_lock);
48 static DEFINE_IDR(ext_devt_idr);
50 static void disk_check_events(struct disk_events *ev,
51 unsigned int *clearing_ptr);
52 static void disk_alloc_events(struct gendisk *disk);
53 static void disk_add_events(struct gendisk *disk);
54 static void disk_del_events(struct gendisk *disk);
55 static void disk_release_events(struct gendisk *disk);
58 * Set disk capacity and notify if the size is not currently
59 * zero and will not be set to zero
61 bool set_capacity_revalidate_and_notify(struct gendisk *disk, sector_t size,
64 sector_t capacity = get_capacity(disk);
66 set_capacity(disk, size);
68 revalidate_disk_size(disk, true);
70 if (capacity != size && capacity != 0 && size != 0) {
71 char *envp[] = { "RESIZE=1", NULL };
73 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
80 EXPORT_SYMBOL_GPL(set_capacity_revalidate_and_notify);
83 * Format the device name of the indicated disk into the supplied buffer and
84 * return a pointer to that same buffer for convenience.
86 char *disk_name(struct gendisk *hd, int partno, char *buf)
89 snprintf(buf, BDEVNAME_SIZE, "%s", hd->disk_name);
90 else if (isdigit(hd->disk_name[strlen(hd->disk_name)-1]))
91 snprintf(buf, BDEVNAME_SIZE, "%sp%d", hd->disk_name, partno);
93 snprintf(buf, BDEVNAME_SIZE, "%s%d", hd->disk_name, partno);
98 const char *bdevname(struct block_device *bdev, char *buf)
100 return disk_name(bdev->bd_disk, bdev->bd_partno, buf);
102 EXPORT_SYMBOL(bdevname);
104 static void part_stat_read_all(struct hd_struct *part, struct disk_stats *stat)
108 memset(stat, 0, sizeof(struct disk_stats));
109 for_each_possible_cpu(cpu) {
110 struct disk_stats *ptr = per_cpu_ptr(part->dkstats, cpu);
113 for (group = 0; group < NR_STAT_GROUPS; group++) {
114 stat->nsecs[group] += ptr->nsecs[group];
115 stat->sectors[group] += ptr->sectors[group];
116 stat->ios[group] += ptr->ios[group];
117 stat->merges[group] += ptr->merges[group];
120 stat->io_ticks += ptr->io_ticks;
124 static unsigned int part_in_flight(struct hd_struct *part)
126 unsigned int inflight = 0;
129 for_each_possible_cpu(cpu) {
130 inflight += part_stat_local_read_cpu(part, in_flight[0], cpu) +
131 part_stat_local_read_cpu(part, in_flight[1], cpu);
133 if ((int)inflight < 0)
139 static void part_in_flight_rw(struct hd_struct *part, unsigned int inflight[2])
145 for_each_possible_cpu(cpu) {
146 inflight[0] += part_stat_local_read_cpu(part, in_flight[0], cpu);
147 inflight[1] += part_stat_local_read_cpu(part, in_flight[1], cpu);
149 if ((int)inflight[0] < 0)
151 if ((int)inflight[1] < 0)
155 struct hd_struct *__disk_get_part(struct gendisk *disk, int partno)
157 struct disk_part_tbl *ptbl = rcu_dereference(disk->part_tbl);
159 if (unlikely(partno < 0 || partno >= ptbl->len))
161 return rcu_dereference(ptbl->part[partno]);
165 * disk_get_part - get partition
166 * @disk: disk to look partition from
167 * @partno: partition number
169 * Look for partition @partno from @disk. If found, increment
170 * reference count and return it.
176 * Pointer to the found partition on success, NULL if not found.
178 struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
180 struct hd_struct *part;
183 part = __disk_get_part(disk, partno);
185 get_device(part_to_dev(part));
192 * disk_part_iter_init - initialize partition iterator
193 * @piter: iterator to initialize
194 * @disk: disk to iterate over
195 * @flags: DISK_PITER_* flags
197 * Initialize @piter so that it iterates over partitions of @disk.
202 void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
205 struct disk_part_tbl *ptbl;
208 ptbl = rcu_dereference(disk->part_tbl);
213 if (flags & DISK_PITER_REVERSE)
214 piter->idx = ptbl->len - 1;
215 else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
220 piter->flags = flags;
224 EXPORT_SYMBOL_GPL(disk_part_iter_init);
227 * disk_part_iter_next - proceed iterator to the next partition and return it
228 * @piter: iterator of interest
230 * Proceed @piter to the next partition and return it.
235 struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
237 struct disk_part_tbl *ptbl;
240 /* put the last partition */
241 disk_put_part(piter->part);
246 ptbl = rcu_dereference(piter->disk->part_tbl);
248 /* determine iteration parameters */
249 if (piter->flags & DISK_PITER_REVERSE) {
251 if (piter->flags & (DISK_PITER_INCL_PART0 |
252 DISK_PITER_INCL_EMPTY_PART0))
261 /* iterate to the next partition */
262 for (; piter->idx != end; piter->idx += inc) {
263 struct hd_struct *part;
265 part = rcu_dereference(ptbl->part[piter->idx]);
268 if (!part_nr_sects_read(part) &&
269 !(piter->flags & DISK_PITER_INCL_EMPTY) &&
270 !(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
274 get_device(part_to_dev(part));
284 EXPORT_SYMBOL_GPL(disk_part_iter_next);
287 * disk_part_iter_exit - finish up partition iteration
288 * @piter: iter of interest
290 * Called when iteration is over. Cleans up @piter.
295 void disk_part_iter_exit(struct disk_part_iter *piter)
297 disk_put_part(piter->part);
300 EXPORT_SYMBOL_GPL(disk_part_iter_exit);
302 static inline int sector_in_part(struct hd_struct *part, sector_t sector)
304 return part->start_sect <= sector &&
305 sector < part->start_sect + part_nr_sects_read(part);
309 * disk_map_sector_rcu - map sector to partition
310 * @disk: gendisk of interest
311 * @sector: sector to map
313 * Find out which partition @sector maps to on @disk. This is
314 * primarily used for stats accounting.
317 * RCU read locked. The returned partition pointer is always valid
318 * because its refcount is grabbed except for part0, which lifetime
319 * is same with the disk.
322 * Found partition on success, part0 is returned if no partition matches
323 * or the matched partition is being deleted.
325 struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
327 struct disk_part_tbl *ptbl;
328 struct hd_struct *part;
332 ptbl = rcu_dereference(disk->part_tbl);
334 part = rcu_dereference(ptbl->last_lookup);
335 if (part && sector_in_part(part, sector) && hd_struct_try_get(part))
338 for (i = 1; i < ptbl->len; i++) {
339 part = rcu_dereference(ptbl->part[i]);
341 if (part && sector_in_part(part, sector)) {
343 * only live partition can be cached for lookup,
344 * so use-after-free on cached & deleting partition
347 if (!hd_struct_try_get(part))
349 rcu_assign_pointer(ptbl->last_lookup, part);
361 * disk_has_partitions
362 * @disk: gendisk of interest
364 * Walk through the partition table and check if valid partition exists.
370 * True if the gendisk has at least one valid non-zero size partition.
373 bool disk_has_partitions(struct gendisk *disk)
375 struct disk_part_tbl *ptbl;
380 ptbl = rcu_dereference(disk->part_tbl);
382 /* Iterate partitions skipping the whole device at index 0 */
383 for (i = 1; i < ptbl->len; i++) {
384 if (rcu_dereference(ptbl->part[i])) {
394 EXPORT_SYMBOL_GPL(disk_has_partitions);
397 * Can be deleted altogether. Later.
400 #define BLKDEV_MAJOR_HASH_SIZE 255
401 static struct blk_major_name {
402 struct blk_major_name *next;
405 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
406 static DEFINE_MUTEX(major_names_lock);
408 /* index in the above - for now: assume no multimajor ranges */
409 static inline int major_to_index(unsigned major)
411 return major % BLKDEV_MAJOR_HASH_SIZE;
414 #ifdef CONFIG_PROC_FS
415 void blkdev_show(struct seq_file *seqf, off_t offset)
417 struct blk_major_name *dp;
419 mutex_lock(&major_names_lock);
420 for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
421 if (dp->major == offset)
422 seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
423 mutex_unlock(&major_names_lock);
425 #endif /* CONFIG_PROC_FS */
428 * register_blkdev - register a new block device
430 * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
431 * @major = 0, try to allocate any unused major number.
432 * @name: the name of the new block device as a zero terminated string
434 * The @name must be unique within the system.
436 * The return value depends on the @major input parameter:
438 * - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
439 * then the function returns zero on success, or a negative error code
440 * - if any unused major number was requested with @major = 0 parameter
441 * then the return value is the allocated major number in range
442 * [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
444 * See Documentation/admin-guide/devices.txt for the list of allocated
447 int register_blkdev(unsigned int major, const char *name)
449 struct blk_major_name **n, *p;
452 mutex_lock(&major_names_lock);
456 for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
457 if (major_names[index] == NULL)
462 printk("%s: failed to get major for %s\n",
471 if (major >= BLKDEV_MAJOR_MAX) {
472 pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
473 __func__, major, BLKDEV_MAJOR_MAX-1, name);
479 p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
486 strlcpy(p->name, name, sizeof(p->name));
488 index = major_to_index(major);
490 for (n = &major_names[index]; *n; n = &(*n)->next) {
491 if ((*n)->major == major)
500 printk("register_blkdev: cannot get major %u for %s\n",
505 mutex_unlock(&major_names_lock);
509 EXPORT_SYMBOL(register_blkdev);
511 void unregister_blkdev(unsigned int major, const char *name)
513 struct blk_major_name **n;
514 struct blk_major_name *p = NULL;
515 int index = major_to_index(major);
517 mutex_lock(&major_names_lock);
518 for (n = &major_names[index]; *n; n = &(*n)->next)
519 if ((*n)->major == major)
521 if (!*n || strcmp((*n)->name, name)) {
527 mutex_unlock(&major_names_lock);
531 EXPORT_SYMBOL(unregister_blkdev);
534 * blk_mangle_minor - scatter minor numbers apart
535 * @minor: minor number to mangle
537 * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
538 * is enabled. Mangling twice gives the original value.
546 static int blk_mangle_minor(int minor)
548 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
551 for (i = 0; i < MINORBITS / 2; i++) {
552 int low = minor & (1 << i);
553 int high = minor & (1 << (MINORBITS - 1 - i));
554 int distance = MINORBITS - 1 - 2 * i;
556 minor ^= low | high; /* clear both bits */
557 low <<= distance; /* swap the positions */
559 minor |= low | high; /* and set */
566 * blk_alloc_devt - allocate a dev_t for a partition
567 * @part: partition to allocate dev_t for
568 * @devt: out parameter for resulting dev_t
570 * Allocate a dev_t for block device.
573 * 0 on success, allocated dev_t is returned in *@devt. -errno on
579 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
581 struct gendisk *disk = part_to_disk(part);
584 /* in consecutive minor range? */
585 if (part->partno < disk->minors) {
586 *devt = MKDEV(disk->major, disk->first_minor + part->partno);
590 /* allocate ext devt */
591 idr_preload(GFP_KERNEL);
593 spin_lock_bh(&ext_devt_lock);
594 idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
595 spin_unlock_bh(&ext_devt_lock);
599 return idx == -ENOSPC ? -EBUSY : idx;
601 *devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
606 * blk_free_devt - free a dev_t
607 * @devt: dev_t to free
609 * Free @devt which was allocated using blk_alloc_devt().
614 void blk_free_devt(dev_t devt)
616 if (devt == MKDEV(0, 0))
619 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
620 spin_lock_bh(&ext_devt_lock);
621 idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
622 spin_unlock_bh(&ext_devt_lock);
627 * We invalidate devt by assigning NULL pointer for devt in idr.
629 void blk_invalidate_devt(dev_t devt)
631 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
632 spin_lock_bh(&ext_devt_lock);
633 idr_replace(&ext_devt_idr, NULL, blk_mangle_minor(MINOR(devt)));
634 spin_unlock_bh(&ext_devt_lock);
638 static char *bdevt_str(dev_t devt, char *buf)
640 if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
641 char tbuf[BDEVT_SIZE];
642 snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
643 snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
645 snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
651 * Register device numbers dev..(dev+range-1)
652 * range must be nonzero
653 * The hash chain is sorted on range, so that subranges can override.
655 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
656 struct kobject *(*probe)(dev_t, int *, void *),
657 int (*lock)(dev_t, void *), void *data)
659 unsigned n = MAJOR(devt + range - 1) - MAJOR(devt) + 1;
660 unsigned index = MAJOR(devt);
665 p = kmalloc_array(n, sizeof(struct bdev_map), GFP_KERNEL);
669 for (i = 0; i < n; i++, p++) {
678 mutex_lock(&bdev_map_lock);
679 for (i = 0, p -= n; i < n; i++, p++, index++) {
680 struct bdev_map **s = &bdev_map[index % 255];
681 while (*s && (*s)->range < range)
686 mutex_unlock(&bdev_map_lock);
688 EXPORT_SYMBOL(blk_register_region);
690 void blk_unregister_region(dev_t devt, unsigned long range)
692 unsigned n = MAJOR(devt + range - 1) - MAJOR(devt) + 1;
693 unsigned index = MAJOR(devt);
695 struct bdev_map *found = NULL;
697 mutex_lock(&bdev_map_lock);
698 for (i = 0; i < min(n, 255u); i++, index++) {
700 for (s = &bdev_map[index % 255]; *s; s = &(*s)->next) {
701 struct bdev_map *p = *s;
702 if (p->dev == devt && p->range == range) {
710 mutex_unlock(&bdev_map_lock);
713 EXPORT_SYMBOL(blk_unregister_region);
715 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
717 struct gendisk *p = data;
719 return &disk_to_dev(p)->kobj;
722 static int exact_lock(dev_t devt, void *data)
724 struct gendisk *p = data;
726 if (!get_disk_and_module(p))
731 static void disk_scan_partitions(struct gendisk *disk)
733 struct block_device *bdev;
735 if (!get_capacity(disk) || !disk_part_scan_enabled(disk))
738 set_bit(GD_NEED_PART_SCAN, &disk->state);
739 bdev = blkdev_get_by_dev(disk_devt(disk), FMODE_READ, NULL);
741 blkdev_put(bdev, FMODE_READ);
744 static void register_disk(struct device *parent, struct gendisk *disk,
745 const struct attribute_group **groups)
747 struct device *ddev = disk_to_dev(disk);
748 struct disk_part_iter piter;
749 struct hd_struct *part;
752 ddev->parent = parent;
754 dev_set_name(ddev, "%s", disk->disk_name);
756 /* delay uevents, until we scanned partition table */
757 dev_set_uevent_suppress(ddev, 1);
760 WARN_ON(ddev->groups);
761 ddev->groups = groups;
763 if (device_add(ddev))
765 if (!sysfs_deprecated) {
766 err = sysfs_create_link(block_depr, &ddev->kobj,
767 kobject_name(&ddev->kobj));
775 * avoid probable deadlock caused by allocating memory with
776 * GFP_KERNEL in runtime_resume callback of its all ancestor
779 pm_runtime_set_memalloc_noio(ddev, true);
781 disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
782 disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
784 if (disk->flags & GENHD_FL_HIDDEN) {
785 dev_set_uevent_suppress(ddev, 0);
789 disk_scan_partitions(disk);
791 /* announce disk after possible partitions are created */
792 dev_set_uevent_suppress(ddev, 0);
793 kobject_uevent(&ddev->kobj, KOBJ_ADD);
795 /* announce possible partitions */
796 disk_part_iter_init(&piter, disk, 0);
797 while ((part = disk_part_iter_next(&piter)))
798 kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
799 disk_part_iter_exit(&piter);
801 if (disk->queue->backing_dev_info->dev) {
802 err = sysfs_create_link(&ddev->kobj,
803 &disk->queue->backing_dev_info->dev->kobj,
810 * __device_add_disk - add disk information to kernel list
811 * @parent: parent device for the disk
812 * @disk: per-device partitioning information
813 * @groups: Additional per-device sysfs groups
814 * @register_queue: register the queue if set to true
816 * This function registers the partitioning information in @disk
819 * FIXME: error handling
821 static void __device_add_disk(struct device *parent, struct gendisk *disk,
822 const struct attribute_group **groups,
829 * The disk queue should now be all set with enough information about
830 * the device for the elevator code to pick an adequate default
831 * elevator if one is needed, that is, for devices requesting queue
835 elevator_init_mq(disk->queue);
837 /* minors == 0 indicates to use ext devt from part0 and should
838 * be accompanied with EXT_DEVT flag. Make sure all
839 * parameters make sense.
841 WARN_ON(disk->minors && !(disk->major || disk->first_minor));
842 WARN_ON(!disk->minors &&
843 !(disk->flags & (GENHD_FL_EXT_DEVT | GENHD_FL_HIDDEN)));
845 disk->flags |= GENHD_FL_UP;
847 retval = blk_alloc_devt(&disk->part0, &devt);
852 disk->major = MAJOR(devt);
853 disk->first_minor = MINOR(devt);
855 disk_alloc_events(disk);
857 if (disk->flags & GENHD_FL_HIDDEN) {
859 * Don't let hidden disks show up in /proc/partitions,
860 * and don't bother scanning for partitions either.
862 disk->flags |= GENHD_FL_SUPPRESS_PARTITION_INFO;
863 disk->flags |= GENHD_FL_NO_PART_SCAN;
865 struct backing_dev_info *bdi = disk->queue->backing_dev_info;
866 struct device *dev = disk_to_dev(disk);
869 /* Register BDI before referencing it from bdev */
871 ret = bdi_register(bdi, "%u:%u", MAJOR(devt), MINOR(devt));
873 bdi_set_owner(bdi, dev);
874 blk_register_region(disk_devt(disk), disk->minors, NULL,
875 exact_match, exact_lock, disk);
877 register_disk(parent, disk, groups);
879 blk_register_queue(disk);
882 * Take an extra ref on queue which will be put on disk_release()
883 * so that it sticks around as long as @disk is there.
885 WARN_ON_ONCE(!blk_get_queue(disk->queue));
887 disk_add_events(disk);
888 blk_integrity_add(disk);
891 void device_add_disk(struct device *parent, struct gendisk *disk,
892 const struct attribute_group **groups)
895 __device_add_disk(parent, disk, groups, true);
897 EXPORT_SYMBOL(device_add_disk);
899 void device_add_disk_no_queue_reg(struct device *parent, struct gendisk *disk)
901 __device_add_disk(parent, disk, NULL, false);
903 EXPORT_SYMBOL(device_add_disk_no_queue_reg);
905 static void invalidate_partition(struct gendisk *disk, int partno)
907 struct block_device *bdev;
909 bdev = bdget_disk(disk, partno);
914 __invalidate_device(bdev, true);
917 * Unhash the bdev inode for this device so that it gets evicted as soon
918 * as last inode reference is dropped.
920 remove_inode_hash(bdev->bd_inode);
925 * del_gendisk - remove the gendisk
926 * @disk: the struct gendisk to remove
928 * Removes the gendisk and all its associated resources. This deletes the
929 * partitions associated with the gendisk, and unregisters the associated
932 * This is the counter to the respective __device_add_disk() call.
934 * The final removal of the struct gendisk happens when its refcount reaches 0
935 * with put_disk(), which should be called after del_gendisk(), if
936 * __device_add_disk() was used.
938 * Drivers exist which depend on the release of the gendisk to be synchronous,
939 * it should not be deferred.
943 void del_gendisk(struct gendisk *disk)
945 struct disk_part_iter piter;
946 struct hd_struct *part;
950 if (WARN_ON_ONCE(!disk->queue))
953 blk_integrity_del(disk);
954 disk_del_events(disk);
957 * Block lookups of the disk until all bdevs are unhashed and the
958 * disk is marked as dead (GENHD_FL_UP cleared).
960 down_write(&disk->lookup_sem);
961 /* invalidate stuff */
962 disk_part_iter_init(&piter, disk,
963 DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
964 while ((part = disk_part_iter_next(&piter))) {
965 invalidate_partition(disk, part->partno);
966 delete_partition(part);
968 disk_part_iter_exit(&piter);
970 invalidate_partition(disk, 0);
971 set_capacity(disk, 0);
972 disk->flags &= ~GENHD_FL_UP;
973 up_write(&disk->lookup_sem);
975 if (!(disk->flags & GENHD_FL_HIDDEN)) {
976 sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
979 * Unregister bdi before releasing device numbers (as they can
980 * get reused and we'd get clashes in sysfs).
982 bdi_unregister(disk->queue->backing_dev_info);
985 blk_unregister_queue(disk);
987 if (!(disk->flags & GENHD_FL_HIDDEN))
988 blk_unregister_region(disk_devt(disk), disk->minors);
990 * Remove gendisk pointer from idr so that it cannot be looked up
991 * while RCU period before freeing gendisk is running to prevent
992 * use-after-free issues. Note that the device number stays
993 * "in-use" until we really free the gendisk.
995 blk_invalidate_devt(disk_devt(disk));
997 kobject_put(disk->part0.holder_dir);
998 kobject_put(disk->slave_dir);
1000 part_stat_set_all(&disk->part0, 0);
1001 disk->part0.stamp = 0;
1002 if (!sysfs_deprecated)
1003 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
1004 pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
1005 device_del(disk_to_dev(disk));
1007 EXPORT_SYMBOL(del_gendisk);
1009 /* sysfs access to bad-blocks list. */
1010 static ssize_t disk_badblocks_show(struct device *dev,
1011 struct device_attribute *attr,
1014 struct gendisk *disk = dev_to_disk(dev);
1017 return sprintf(page, "\n");
1019 return badblocks_show(disk->bb, page, 0);
1022 static ssize_t disk_badblocks_store(struct device *dev,
1023 struct device_attribute *attr,
1024 const char *page, size_t len)
1026 struct gendisk *disk = dev_to_disk(dev);
1031 return badblocks_store(disk->bb, page, len, 0);
1034 static struct gendisk *lookup_gendisk(dev_t dev, int *partno)
1036 struct kobject *kobj;
1038 unsigned long best = ~0UL;
1041 mutex_lock(&bdev_map_lock);
1042 for (p = bdev_map[MAJOR(dev) % 255]; p; p = p->next) {
1043 struct kobject *(*probe)(dev_t, int *, void *);
1044 struct module *owner;
1047 if (p->dev > dev || p->dev + p->range - 1 < dev)
1049 if (p->range - 1 >= best)
1051 if (!try_module_get(p->owner))
1056 best = p->range - 1;
1057 *partno = dev - p->dev;
1058 if (p->lock && p->lock(dev, data) < 0) {
1062 mutex_unlock(&bdev_map_lock);
1063 kobj = probe(dev, partno, data);
1064 /* Currently ->owner protects _only_ ->probe() itself. */
1067 return dev_to_disk(kobj_to_dev(kobj));
1070 mutex_unlock(&bdev_map_lock);
1076 * get_gendisk - get partitioning information for a given device
1077 * @devt: device to get partitioning information for
1078 * @partno: returned partition index
1080 * This function gets the structure containing partitioning
1081 * information for the given device @devt.
1083 * Context: can sleep
1085 struct gendisk *get_gendisk(dev_t devt, int *partno)
1087 struct gendisk *disk = NULL;
1091 if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
1092 disk = lookup_gendisk(devt, partno);
1094 struct hd_struct *part;
1096 spin_lock_bh(&ext_devt_lock);
1097 part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
1098 if (part && get_disk_and_module(part_to_disk(part))) {
1099 *partno = part->partno;
1100 disk = part_to_disk(part);
1102 spin_unlock_bh(&ext_devt_lock);
1109 * Synchronize with del_gendisk() to not return disk that is being
1112 down_read(&disk->lookup_sem);
1113 if (unlikely((disk->flags & GENHD_FL_HIDDEN) ||
1114 !(disk->flags & GENHD_FL_UP))) {
1115 up_read(&disk->lookup_sem);
1116 put_disk_and_module(disk);
1119 up_read(&disk->lookup_sem);
1125 * bdget_disk - do bdget() by gendisk and partition number
1126 * @disk: gendisk of interest
1127 * @partno: partition number
1129 * Find partition @partno from @disk, do bdget() on it.
1135 * Resulting block_device on success, NULL on failure.
1137 struct block_device *bdget_disk(struct gendisk *disk, int partno)
1139 struct hd_struct *part;
1140 struct block_device *bdev = NULL;
1142 part = disk_get_part(disk, partno);
1144 bdev = bdget_part(part);
1145 disk_put_part(part);
1149 EXPORT_SYMBOL(bdget_disk);
1152 * print a full list of all partitions - intended for places where the root
1153 * filesystem can't be mounted and thus to give the victim some idea of what
1156 void __init printk_all_partitions(void)
1158 struct class_dev_iter iter;
1161 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1162 while ((dev = class_dev_iter_next(&iter))) {
1163 struct gendisk *disk = dev_to_disk(dev);
1164 struct disk_part_iter piter;
1165 struct hd_struct *part;
1166 char name_buf[BDEVNAME_SIZE];
1167 char devt_buf[BDEVT_SIZE];
1170 * Don't show empty devices or things that have been
1173 if (get_capacity(disk) == 0 ||
1174 (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
1178 * Note, unlike /proc/partitions, I am showing the
1179 * numbers in hex - the same format as the root=
1182 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
1183 while ((part = disk_part_iter_next(&piter))) {
1184 bool is_part0 = part == &disk->part0;
1186 printk("%s%s %10llu %s %s", is_part0 ? "" : " ",
1187 bdevt_str(part_devt(part), devt_buf),
1188 (unsigned long long)part_nr_sects_read(part) >> 1
1189 , disk_name(disk, part->partno, name_buf),
1190 part->info ? part->info->uuid : "");
1192 if (dev->parent && dev->parent->driver)
1193 printk(" driver: %s\n",
1194 dev->parent->driver->name);
1196 printk(" (driver?)\n");
1200 disk_part_iter_exit(&piter);
1202 class_dev_iter_exit(&iter);
1205 #ifdef CONFIG_PROC_FS
1207 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
1210 struct class_dev_iter *iter;
1213 iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1215 return ERR_PTR(-ENOMEM);
1217 seqf->private = iter;
1218 class_dev_iter_init(iter, &block_class, NULL, &disk_type);
1220 dev = class_dev_iter_next(iter);
1225 return dev_to_disk(dev);
1228 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
1233 dev = class_dev_iter_next(seqf->private);
1235 return dev_to_disk(dev);
1240 static void disk_seqf_stop(struct seq_file *seqf, void *v)
1242 struct class_dev_iter *iter = seqf->private;
1244 /* stop is called even after start failed :-( */
1246 class_dev_iter_exit(iter);
1248 seqf->private = NULL;
1252 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
1256 p = disk_seqf_start(seqf, pos);
1257 if (!IS_ERR_OR_NULL(p) && !*pos)
1258 seq_puts(seqf, "major minor #blocks name\n\n");
1262 static int show_partition(struct seq_file *seqf, void *v)
1264 struct gendisk *sgp = v;
1265 struct disk_part_iter piter;
1266 struct hd_struct *part;
1267 char buf[BDEVNAME_SIZE];
1269 /* Don't show non-partitionable removeable devices or empty devices */
1270 if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
1271 (sgp->flags & GENHD_FL_REMOVABLE)))
1273 if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
1276 /* show the full disk and all non-0 size partitions of it */
1277 disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
1278 while ((part = disk_part_iter_next(&piter)))
1279 seq_printf(seqf, "%4d %7d %10llu %s\n",
1280 MAJOR(part_devt(part)), MINOR(part_devt(part)),
1281 (unsigned long long)part_nr_sects_read(part) >> 1,
1282 disk_name(sgp, part->partno, buf));
1283 disk_part_iter_exit(&piter);
1288 static const struct seq_operations partitions_op = {
1289 .start = show_partition_start,
1290 .next = disk_seqf_next,
1291 .stop = disk_seqf_stop,
1292 .show = show_partition
1297 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
1299 if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
1300 /* Make old-style 2.4 aliases work */
1301 request_module("block-major-%d", MAJOR(devt));
1305 static void bdev_map_init(void)
1307 struct bdev_map *base;
1310 base = kzalloc(sizeof(*base), GFP_KERNEL);
1312 panic("cannot allocate bdev_map");
1316 base->probe = base_probe;
1317 for (i = 0; i < 255; i++)
1321 static int __init genhd_device_init(void)
1325 block_class.dev_kobj = sysfs_dev_block_kobj;
1326 error = class_register(&block_class);
1327 if (unlikely(error))
1332 register_blkdev(BLOCK_EXT_MAJOR, "blkext");
1334 /* create top-level block dir */
1335 if (!sysfs_deprecated)
1336 block_depr = kobject_create_and_add("block", NULL);
1340 subsys_initcall(genhd_device_init);
1342 static ssize_t disk_range_show(struct device *dev,
1343 struct device_attribute *attr, char *buf)
1345 struct gendisk *disk = dev_to_disk(dev);
1347 return sprintf(buf, "%d\n", disk->minors);
1350 static ssize_t disk_ext_range_show(struct device *dev,
1351 struct device_attribute *attr, char *buf)
1353 struct gendisk *disk = dev_to_disk(dev);
1355 return sprintf(buf, "%d\n", disk_max_parts(disk));
1358 static ssize_t disk_removable_show(struct device *dev,
1359 struct device_attribute *attr, char *buf)
1361 struct gendisk *disk = dev_to_disk(dev);
1363 return sprintf(buf, "%d\n",
1364 (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
1367 static ssize_t disk_hidden_show(struct device *dev,
1368 struct device_attribute *attr, char *buf)
1370 struct gendisk *disk = dev_to_disk(dev);
1372 return sprintf(buf, "%d\n",
1373 (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
1376 static ssize_t disk_ro_show(struct device *dev,
1377 struct device_attribute *attr, char *buf)
1379 struct gendisk *disk = dev_to_disk(dev);
1381 return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
1384 ssize_t part_size_show(struct device *dev,
1385 struct device_attribute *attr, char *buf)
1387 struct hd_struct *p = dev_to_part(dev);
1389 return sprintf(buf, "%llu\n",
1390 (unsigned long long)part_nr_sects_read(p));
1393 ssize_t part_stat_show(struct device *dev,
1394 struct device_attribute *attr, char *buf)
1396 struct hd_struct *p = dev_to_part(dev);
1397 struct request_queue *q = part_to_disk(p)->queue;
1398 struct disk_stats stat;
1399 unsigned int inflight;
1401 part_stat_read_all(p, &stat);
1403 inflight = blk_mq_in_flight(q, p);
1405 inflight = part_in_flight(p);
1408 "%8lu %8lu %8llu %8u "
1409 "%8lu %8lu %8llu %8u "
1411 "%8lu %8lu %8llu %8u "
1414 stat.ios[STAT_READ],
1415 stat.merges[STAT_READ],
1416 (unsigned long long)stat.sectors[STAT_READ],
1417 (unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1418 stat.ios[STAT_WRITE],
1419 stat.merges[STAT_WRITE],
1420 (unsigned long long)stat.sectors[STAT_WRITE],
1421 (unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1423 jiffies_to_msecs(stat.io_ticks),
1424 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1425 stat.nsecs[STAT_WRITE] +
1426 stat.nsecs[STAT_DISCARD] +
1427 stat.nsecs[STAT_FLUSH],
1429 stat.ios[STAT_DISCARD],
1430 stat.merges[STAT_DISCARD],
1431 (unsigned long long)stat.sectors[STAT_DISCARD],
1432 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1433 stat.ios[STAT_FLUSH],
1434 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1437 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1440 struct hd_struct *p = dev_to_part(dev);
1441 struct request_queue *q = part_to_disk(p)->queue;
1442 unsigned int inflight[2];
1445 blk_mq_in_flight_rw(q, p, inflight);
1447 part_in_flight_rw(p, inflight);
1449 return sprintf(buf, "%8u %8u\n", inflight[0], inflight[1]);
1452 static ssize_t disk_capability_show(struct device *dev,
1453 struct device_attribute *attr, char *buf)
1455 struct gendisk *disk = dev_to_disk(dev);
1457 return sprintf(buf, "%x\n", disk->flags);
1460 static ssize_t disk_alignment_offset_show(struct device *dev,
1461 struct device_attribute *attr,
1464 struct gendisk *disk = dev_to_disk(dev);
1466 return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
1469 static ssize_t disk_discard_alignment_show(struct device *dev,
1470 struct device_attribute *attr,
1473 struct gendisk *disk = dev_to_disk(dev);
1475 return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
1478 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1479 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1480 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1481 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1482 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1483 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1484 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1485 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1486 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1487 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1488 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1489 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1491 #ifdef CONFIG_FAIL_MAKE_REQUEST
1492 ssize_t part_fail_show(struct device *dev,
1493 struct device_attribute *attr, char *buf)
1495 struct hd_struct *p = dev_to_part(dev);
1497 return sprintf(buf, "%d\n", p->make_it_fail);
1500 ssize_t part_fail_store(struct device *dev,
1501 struct device_attribute *attr,
1502 const char *buf, size_t count)
1504 struct hd_struct *p = dev_to_part(dev);
1507 if (count > 0 && sscanf(buf, "%d", &i) > 0)
1508 p->make_it_fail = (i == 0) ? 0 : 1;
1513 static struct device_attribute dev_attr_fail =
1514 __ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1515 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1517 #ifdef CONFIG_FAIL_IO_TIMEOUT
1518 static struct device_attribute dev_attr_fail_timeout =
1519 __ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1522 static struct attribute *disk_attrs[] = {
1523 &dev_attr_range.attr,
1524 &dev_attr_ext_range.attr,
1525 &dev_attr_removable.attr,
1526 &dev_attr_hidden.attr,
1528 &dev_attr_size.attr,
1529 &dev_attr_alignment_offset.attr,
1530 &dev_attr_discard_alignment.attr,
1531 &dev_attr_capability.attr,
1532 &dev_attr_stat.attr,
1533 &dev_attr_inflight.attr,
1534 &dev_attr_badblocks.attr,
1535 #ifdef CONFIG_FAIL_MAKE_REQUEST
1536 &dev_attr_fail.attr,
1538 #ifdef CONFIG_FAIL_IO_TIMEOUT
1539 &dev_attr_fail_timeout.attr,
1544 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1546 struct device *dev = container_of(kobj, typeof(*dev), kobj);
1547 struct gendisk *disk = dev_to_disk(dev);
1549 if (a == &dev_attr_badblocks.attr && !disk->bb)
1554 static struct attribute_group disk_attr_group = {
1555 .attrs = disk_attrs,
1556 .is_visible = disk_visible,
1559 static const struct attribute_group *disk_attr_groups[] = {
1565 * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1566 * @disk: disk to replace part_tbl for
1567 * @new_ptbl: new part_tbl to install
1569 * Replace disk->part_tbl with @new_ptbl in RCU-safe way. The
1570 * original ptbl is freed using RCU callback.
1573 * Matching bd_mutex locked or the caller is the only user of @disk.
1575 static void disk_replace_part_tbl(struct gendisk *disk,
1576 struct disk_part_tbl *new_ptbl)
1578 struct disk_part_tbl *old_ptbl =
1579 rcu_dereference_protected(disk->part_tbl, 1);
1581 rcu_assign_pointer(disk->part_tbl, new_ptbl);
1584 rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1585 kfree_rcu(old_ptbl, rcu_head);
1590 * disk_expand_part_tbl - expand disk->part_tbl
1591 * @disk: disk to expand part_tbl for
1592 * @partno: expand such that this partno can fit in
1594 * Expand disk->part_tbl such that @partno can fit in. disk->part_tbl
1595 * uses RCU to allow unlocked dereferencing for stats and other stuff.
1598 * Matching bd_mutex locked or the caller is the only user of @disk.
1602 * 0 on success, -errno on failure.
1604 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1606 struct disk_part_tbl *old_ptbl =
1607 rcu_dereference_protected(disk->part_tbl, 1);
1608 struct disk_part_tbl *new_ptbl;
1609 int len = old_ptbl ? old_ptbl->len : 0;
1613 * check for int overflow, since we can get here from blkpg_ioctl()
1614 * with a user passed 'partno'.
1616 target = partno + 1;
1620 /* disk_max_parts() is zero during initialization, ignore if so */
1621 if (disk_max_parts(disk) && target > disk_max_parts(disk))
1627 new_ptbl = kzalloc_node(struct_size(new_ptbl, part, target), GFP_KERNEL,
1632 new_ptbl->len = target;
1634 for (i = 0; i < len; i++)
1635 rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1637 disk_replace_part_tbl(disk, new_ptbl);
1642 * disk_release - releases all allocated resources of the gendisk
1643 * @dev: the device representing this disk
1645 * This function releases all allocated resources of the gendisk.
1647 * The struct gendisk refcount is incremented with get_gendisk() or
1648 * get_disk_and_module(), and its refcount is decremented with
1649 * put_disk_and_module() or put_disk(). Once the refcount reaches 0 this
1650 * function is called.
1652 * Drivers which used __device_add_disk() have a gendisk with a request_queue
1653 * assigned. Since the request_queue sits on top of the gendisk for these
1654 * drivers we also call blk_put_queue() for them, and we expect the
1655 * request_queue refcount to reach 0 at this point, and so the request_queue
1656 * will also be freed prior to the disk.
1658 * Context: can sleep
1660 static void disk_release(struct device *dev)
1662 struct gendisk *disk = dev_to_disk(dev);
1666 blk_free_devt(dev->devt);
1667 disk_release_events(disk);
1668 kfree(disk->random);
1669 disk_replace_part_tbl(disk, NULL);
1670 hd_free_part(&disk->part0);
1672 blk_put_queue(disk->queue);
1675 struct class block_class = {
1679 static char *block_devnode(struct device *dev, umode_t *mode,
1680 kuid_t *uid, kgid_t *gid)
1682 struct gendisk *disk = dev_to_disk(dev);
1684 if (disk->fops->devnode)
1685 return disk->fops->devnode(disk, mode);
1689 const struct device_type disk_type = {
1691 .groups = disk_attr_groups,
1692 .release = disk_release,
1693 .devnode = block_devnode,
1696 #ifdef CONFIG_PROC_FS
1698 * aggregate disk stat collector. Uses the same stats that the sysfs
1699 * entries do, above, but makes them available through one seq_file.
1701 * The output looks suspiciously like /proc/partitions with a bunch of
1704 static int diskstats_show(struct seq_file *seqf, void *v)
1706 struct gendisk *gp = v;
1707 struct disk_part_iter piter;
1708 struct hd_struct *hd;
1709 char buf[BDEVNAME_SIZE];
1710 unsigned int inflight;
1711 struct disk_stats stat;
1714 if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1715 seq_puts(seqf, "major minor name"
1716 " rio rmerge rsect ruse wio wmerge "
1717 "wsect wuse running use aveq"
1721 disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1722 while ((hd = disk_part_iter_next(&piter))) {
1723 part_stat_read_all(hd, &stat);
1724 if (queue_is_mq(gp->queue))
1725 inflight = blk_mq_in_flight(gp->queue, hd);
1727 inflight = part_in_flight(hd);
1729 seq_printf(seqf, "%4d %7d %s "
1736 MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1737 disk_name(gp, hd->partno, buf),
1738 stat.ios[STAT_READ],
1739 stat.merges[STAT_READ],
1740 stat.sectors[STAT_READ],
1741 (unsigned int)div_u64(stat.nsecs[STAT_READ],
1743 stat.ios[STAT_WRITE],
1744 stat.merges[STAT_WRITE],
1745 stat.sectors[STAT_WRITE],
1746 (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1749 jiffies_to_msecs(stat.io_ticks),
1750 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1751 stat.nsecs[STAT_WRITE] +
1752 stat.nsecs[STAT_DISCARD] +
1753 stat.nsecs[STAT_FLUSH],
1755 stat.ios[STAT_DISCARD],
1756 stat.merges[STAT_DISCARD],
1757 stat.sectors[STAT_DISCARD],
1758 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1760 stat.ios[STAT_FLUSH],
1761 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1765 disk_part_iter_exit(&piter);
1770 static const struct seq_operations diskstats_op = {
1771 .start = disk_seqf_start,
1772 .next = disk_seqf_next,
1773 .stop = disk_seqf_stop,
1774 .show = diskstats_show
1777 static int __init proc_genhd_init(void)
1779 proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1780 proc_create_seq("partitions", 0, NULL, &partitions_op);
1783 module_init(proc_genhd_init);
1784 #endif /* CONFIG_PROC_FS */
1786 dev_t blk_lookup_devt(const char *name, int partno)
1788 dev_t devt = MKDEV(0, 0);
1789 struct class_dev_iter iter;
1792 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1793 while ((dev = class_dev_iter_next(&iter))) {
1794 struct gendisk *disk = dev_to_disk(dev);
1795 struct hd_struct *part;
1797 if (strcmp(dev_name(dev), name))
1800 if (partno < disk->minors) {
1801 /* We need to return the right devno, even
1802 * if the partition doesn't exist yet.
1804 devt = MKDEV(MAJOR(dev->devt),
1805 MINOR(dev->devt) + partno);
1808 part = disk_get_part(disk, partno);
1810 devt = part_devt(part);
1811 disk_put_part(part);
1814 disk_put_part(part);
1816 class_dev_iter_exit(&iter);
1820 struct gendisk *__alloc_disk_node(int minors, int node_id)
1822 struct gendisk *disk;
1823 struct disk_part_tbl *ptbl;
1825 if (minors > DISK_MAX_PARTS) {
1827 "block: can't allocate more than %d partitions\n",
1829 minors = DISK_MAX_PARTS;
1832 disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1836 disk->part0.dkstats = alloc_percpu(struct disk_stats);
1837 if (!disk->part0.dkstats)
1840 init_rwsem(&disk->lookup_sem);
1841 disk->node_id = node_id;
1842 if (disk_expand_part_tbl(disk, 0)) {
1843 free_percpu(disk->part0.dkstats);
1847 ptbl = rcu_dereference_protected(disk->part_tbl, 1);
1848 rcu_assign_pointer(ptbl->part[0], &disk->part0);
1851 * set_capacity() and get_capacity() currently don't use
1852 * seqcounter to read/update the part0->nr_sects. Still init
1853 * the counter as we can read the sectors in IO submission
1854 * patch using seqence counters.
1856 * TODO: Ideally set_capacity() and get_capacity() should be
1857 * converted to make use of bd_mutex and sequence counters.
1859 hd_sects_seq_init(&disk->part0);
1860 if (hd_ref_init(&disk->part0))
1861 goto out_free_part0;
1863 disk->minors = minors;
1864 rand_initialize_disk(disk);
1865 disk_to_dev(disk)->class = &block_class;
1866 disk_to_dev(disk)->type = &disk_type;
1867 device_initialize(disk_to_dev(disk));
1871 hd_free_part(&disk->part0);
1876 EXPORT_SYMBOL(__alloc_disk_node);
1879 * get_disk_and_module - increments the gendisk and gendisk fops module refcount
1880 * @disk: the struct gendisk to increment the refcount for
1882 * This increments the refcount for the struct gendisk, and the gendisk's
1883 * fops module owner.
1885 * Context: Any context.
1887 struct kobject *get_disk_and_module(struct gendisk *disk)
1889 struct module *owner;
1890 struct kobject *kobj;
1894 owner = disk->fops->owner;
1895 if (owner && !try_module_get(owner))
1897 kobj = kobject_get_unless_zero(&disk_to_dev(disk)->kobj);
1905 EXPORT_SYMBOL(get_disk_and_module);
1908 * put_disk - decrements the gendisk refcount
1909 * @disk: the struct gendisk to decrement the refcount for
1911 * This decrements the refcount for the struct gendisk. When this reaches 0
1912 * we'll have disk_release() called.
1914 * Context: Any context, but the last reference must not be dropped from
1917 void put_disk(struct gendisk *disk)
1920 kobject_put(&disk_to_dev(disk)->kobj);
1922 EXPORT_SYMBOL(put_disk);
1925 * put_disk_and_module - decrements the module and gendisk refcount
1926 * @disk: the struct gendisk to decrement the refcount for
1928 * This is a counterpart of get_disk_and_module() and thus also of
1931 * Context: Any context, but the last reference must not be dropped from
1934 void put_disk_and_module(struct gendisk *disk)
1937 struct module *owner = disk->fops->owner;
1943 EXPORT_SYMBOL(put_disk_and_module);
1945 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1947 char event[] = "DISK_RO=1";
1948 char *envp[] = { event, NULL };
1952 kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1955 void set_disk_ro(struct gendisk *disk, int flag)
1957 struct disk_part_iter piter;
1958 struct hd_struct *part;
1960 if (disk->part0.policy != flag) {
1961 set_disk_ro_uevent(disk, flag);
1962 disk->part0.policy = flag;
1965 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1966 while ((part = disk_part_iter_next(&piter)))
1967 part->policy = flag;
1968 disk_part_iter_exit(&piter);
1971 EXPORT_SYMBOL(set_disk_ro);
1973 int bdev_read_only(struct block_device *bdev)
1977 return bdev->bd_part->policy;
1980 EXPORT_SYMBOL(bdev_read_only);
1983 * Disk events - monitor disk events like media change and eject request.
1985 struct disk_events {
1986 struct list_head node; /* all disk_event's */
1987 struct gendisk *disk; /* the associated disk */
1990 struct mutex block_mutex; /* protects blocking */
1991 int block; /* event blocking depth */
1992 unsigned int pending; /* events already sent out */
1993 unsigned int clearing; /* events being cleared */
1995 long poll_msecs; /* interval, -1 for default */
1996 struct delayed_work dwork;
1999 static const char *disk_events_strs[] = {
2000 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "media_change",
2001 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "eject_request",
2004 static char *disk_uevents[] = {
2005 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "DISK_MEDIA_CHANGE=1",
2006 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "DISK_EJECT_REQUEST=1",
2009 /* list of all disk_events */
2010 static DEFINE_MUTEX(disk_events_mutex);
2011 static LIST_HEAD(disk_events);
2013 /* disable in-kernel polling by default */
2014 static unsigned long disk_events_dfl_poll_msecs;
2016 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
2018 struct disk_events *ev = disk->ev;
2019 long intv_msecs = 0;
2022 * If device-specific poll interval is set, always use it. If
2023 * the default is being used, poll if the POLL flag is set.
2025 if (ev->poll_msecs >= 0)
2026 intv_msecs = ev->poll_msecs;
2027 else if (disk->event_flags & DISK_EVENT_FLAG_POLL)
2028 intv_msecs = disk_events_dfl_poll_msecs;
2030 return msecs_to_jiffies(intv_msecs);
2034 * disk_block_events - block and flush disk event checking
2035 * @disk: disk to block events for
2037 * On return from this function, it is guaranteed that event checking
2038 * isn't in progress and won't happen until unblocked by
2039 * disk_unblock_events(). Events blocking is counted and the actual
2040 * unblocking happens after the matching number of unblocks are done.
2042 * Note that this intentionally does not block event checking from
2043 * disk_clear_events().
2048 void disk_block_events(struct gendisk *disk)
2050 struct disk_events *ev = disk->ev;
2051 unsigned long flags;
2058 * Outer mutex ensures that the first blocker completes canceling
2059 * the event work before further blockers are allowed to finish.
2061 mutex_lock(&ev->block_mutex);
2063 spin_lock_irqsave(&ev->lock, flags);
2064 cancel = !ev->block++;
2065 spin_unlock_irqrestore(&ev->lock, flags);
2068 cancel_delayed_work_sync(&disk->ev->dwork);
2070 mutex_unlock(&ev->block_mutex);
2073 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
2075 struct disk_events *ev = disk->ev;
2077 unsigned long flags;
2079 spin_lock_irqsave(&ev->lock, flags);
2081 if (WARN_ON_ONCE(ev->block <= 0))
2087 intv = disk_events_poll_jiffies(disk);
2089 queue_delayed_work(system_freezable_power_efficient_wq,
2092 queue_delayed_work(system_freezable_power_efficient_wq,
2095 spin_unlock_irqrestore(&ev->lock, flags);
2099 * disk_unblock_events - unblock disk event checking
2100 * @disk: disk to unblock events for
2102 * Undo disk_block_events(). When the block count reaches zero, it
2103 * starts events polling if configured.
2106 * Don't care. Safe to call from irq context.
2108 void disk_unblock_events(struct gendisk *disk)
2111 __disk_unblock_events(disk, false);
2115 * disk_flush_events - schedule immediate event checking and flushing
2116 * @disk: disk to check and flush events for
2117 * @mask: events to flush
2119 * Schedule immediate event checking on @disk if not blocked. Events in
2120 * @mask are scheduled to be cleared from the driver. Note that this
2121 * doesn't clear the events from @disk->ev.
2124 * If @mask is non-zero must be called with bdev->bd_mutex held.
2126 void disk_flush_events(struct gendisk *disk, unsigned int mask)
2128 struct disk_events *ev = disk->ev;
2133 spin_lock_irq(&ev->lock);
2134 ev->clearing |= mask;
2136 mod_delayed_work(system_freezable_power_efficient_wq,
2138 spin_unlock_irq(&ev->lock);
2142 * disk_clear_events - synchronously check, clear and return pending events
2143 * @disk: disk to fetch and clear events from
2144 * @mask: mask of events to be fetched and cleared
2146 * Disk events are synchronously checked and pending events in @mask
2147 * are cleared and returned. This ignores the block count.
2152 static unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
2154 struct disk_events *ev = disk->ev;
2155 unsigned int pending;
2156 unsigned int clearing = mask;
2161 disk_block_events(disk);
2164 * store the union of mask and ev->clearing on the stack so that the
2165 * race with disk_flush_events does not cause ambiguity (ev->clearing
2166 * can still be modified even if events are blocked).
2168 spin_lock_irq(&ev->lock);
2169 clearing |= ev->clearing;
2171 spin_unlock_irq(&ev->lock);
2173 disk_check_events(ev, &clearing);
2175 * if ev->clearing is not 0, the disk_flush_events got called in the
2176 * middle of this function, so we want to run the workfn without delay.
2178 __disk_unblock_events(disk, ev->clearing ? true : false);
2180 /* then, fetch and clear pending events */
2181 spin_lock_irq(&ev->lock);
2182 pending = ev->pending & mask;
2183 ev->pending &= ~mask;
2184 spin_unlock_irq(&ev->lock);
2185 WARN_ON_ONCE(clearing & mask);
2191 * bdev_check_media_change - check if a removable media has been changed
2192 * @bdev: block device to check
2194 * Check whether a removable media has been changed, and attempt to free all
2195 * dentries and inodes and invalidates all block device page cache entries in
2198 * Returns %true if the block device changed, or %false if not.
2200 bool bdev_check_media_change(struct block_device *bdev)
2202 unsigned int events;
2204 events = disk_clear_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE |
2205 DISK_EVENT_EJECT_REQUEST);
2206 if (!(events & DISK_EVENT_MEDIA_CHANGE))
2209 if (__invalidate_device(bdev, true))
2210 pr_warn("VFS: busy inodes on changed media %s\n",
2211 bdev->bd_disk->disk_name);
2212 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
2215 EXPORT_SYMBOL(bdev_check_media_change);
2218 * Separate this part out so that a different pointer for clearing_ptr can be
2219 * passed in for disk_clear_events.
2221 static void disk_events_workfn(struct work_struct *work)
2223 struct delayed_work *dwork = to_delayed_work(work);
2224 struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
2226 disk_check_events(ev, &ev->clearing);
2229 static void disk_check_events(struct disk_events *ev,
2230 unsigned int *clearing_ptr)
2232 struct gendisk *disk = ev->disk;
2233 char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
2234 unsigned int clearing = *clearing_ptr;
2235 unsigned int events;
2237 int nr_events = 0, i;
2240 events = disk->fops->check_events(disk, clearing);
2242 /* accumulate pending events and schedule next poll if necessary */
2243 spin_lock_irq(&ev->lock);
2245 events &= ~ev->pending;
2246 ev->pending |= events;
2247 *clearing_ptr &= ~clearing;
2249 intv = disk_events_poll_jiffies(disk);
2250 if (!ev->block && intv)
2251 queue_delayed_work(system_freezable_power_efficient_wq,
2254 spin_unlock_irq(&ev->lock);
2257 * Tell userland about new events. Only the events listed in
2258 * @disk->events are reported, and only if DISK_EVENT_FLAG_UEVENT
2259 * is set. Otherwise, events are processed internally but never
2260 * get reported to userland.
2262 for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
2263 if ((events & disk->events & (1 << i)) &&
2264 (disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2265 envp[nr_events++] = disk_uevents[i];
2268 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
2272 * A disk events enabled device has the following sysfs nodes under
2273 * its /sys/block/X/ directory.
2275 * events : list of all supported events
2276 * events_async : list of events which can be detected w/o polling
2277 * (always empty, only for backwards compatibility)
2278 * events_poll_msecs : polling interval, 0: disable, -1: system default
2280 static ssize_t __disk_events_show(unsigned int events, char *buf)
2282 const char *delim = "";
2286 for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
2287 if (events & (1 << i)) {
2288 pos += sprintf(buf + pos, "%s%s",
2289 delim, disk_events_strs[i]);
2293 pos += sprintf(buf + pos, "\n");
2297 static ssize_t disk_events_show(struct device *dev,
2298 struct device_attribute *attr, char *buf)
2300 struct gendisk *disk = dev_to_disk(dev);
2302 if (!(disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2305 return __disk_events_show(disk->events, buf);
2308 static ssize_t disk_events_async_show(struct device *dev,
2309 struct device_attribute *attr, char *buf)
2314 static ssize_t disk_events_poll_msecs_show(struct device *dev,
2315 struct device_attribute *attr,
2318 struct gendisk *disk = dev_to_disk(dev);
2321 return sprintf(buf, "-1\n");
2323 return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
2326 static ssize_t disk_events_poll_msecs_store(struct device *dev,
2327 struct device_attribute *attr,
2328 const char *buf, size_t count)
2330 struct gendisk *disk = dev_to_disk(dev);
2333 if (!count || !sscanf(buf, "%ld", &intv))
2336 if (intv < 0 && intv != -1)
2342 disk_block_events(disk);
2343 disk->ev->poll_msecs = intv;
2344 __disk_unblock_events(disk, true);
2349 static const DEVICE_ATTR(events, 0444, disk_events_show, NULL);
2350 static const DEVICE_ATTR(events_async, 0444, disk_events_async_show, NULL);
2351 static const DEVICE_ATTR(events_poll_msecs, 0644,
2352 disk_events_poll_msecs_show,
2353 disk_events_poll_msecs_store);
2355 static const struct attribute *disk_events_attrs[] = {
2356 &dev_attr_events.attr,
2357 &dev_attr_events_async.attr,
2358 &dev_attr_events_poll_msecs.attr,
2363 * The default polling interval can be specified by the kernel
2364 * parameter block.events_dfl_poll_msecs which defaults to 0
2365 * (disable). This can also be modified runtime by writing to
2366 * /sys/module/block/parameters/events_dfl_poll_msecs.
2368 static int disk_events_set_dfl_poll_msecs(const char *val,
2369 const struct kernel_param *kp)
2371 struct disk_events *ev;
2374 ret = param_set_ulong(val, kp);
2378 mutex_lock(&disk_events_mutex);
2380 list_for_each_entry(ev, &disk_events, node)
2381 disk_flush_events(ev->disk, 0);
2383 mutex_unlock(&disk_events_mutex);
2388 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
2389 .set = disk_events_set_dfl_poll_msecs,
2390 .get = param_get_ulong,
2393 #undef MODULE_PARAM_PREFIX
2394 #define MODULE_PARAM_PREFIX "block."
2396 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
2397 &disk_events_dfl_poll_msecs, 0644);
2400 * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
2402 static void disk_alloc_events(struct gendisk *disk)
2404 struct disk_events *ev;
2406 if (!disk->fops->check_events || !disk->events)
2409 ev = kzalloc(sizeof(*ev), GFP_KERNEL);
2411 pr_warn("%s: failed to initialize events\n", disk->disk_name);
2415 INIT_LIST_HEAD(&ev->node);
2417 spin_lock_init(&ev->lock);
2418 mutex_init(&ev->block_mutex);
2420 ev->poll_msecs = -1;
2421 INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
2426 static void disk_add_events(struct gendisk *disk)
2428 /* FIXME: error handling */
2429 if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
2430 pr_warn("%s: failed to create sysfs files for events\n",
2436 mutex_lock(&disk_events_mutex);
2437 list_add_tail(&disk->ev->node, &disk_events);
2438 mutex_unlock(&disk_events_mutex);
2441 * Block count is initialized to 1 and the following initial
2442 * unblock kicks it into action.
2444 __disk_unblock_events(disk, true);
2447 static void disk_del_events(struct gendisk *disk)
2450 disk_block_events(disk);
2452 mutex_lock(&disk_events_mutex);
2453 list_del_init(&disk->ev->node);
2454 mutex_unlock(&disk_events_mutex);
2457 sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
2460 static void disk_release_events(struct gendisk *disk)
2462 /* the block count should be 1 from disk_del_events() */
2463 WARN_ON_ONCE(disk->ev && disk->ev->block != 1);