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 void (*probe)(dev_t devt);
406 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
407 static DEFINE_MUTEX(major_names_lock);
409 /* index in the above - for now: assume no multimajor ranges */
410 static inline int major_to_index(unsigned major)
412 return major % BLKDEV_MAJOR_HASH_SIZE;
415 #ifdef CONFIG_PROC_FS
416 void blkdev_show(struct seq_file *seqf, off_t offset)
418 struct blk_major_name *dp;
420 mutex_lock(&major_names_lock);
421 for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
422 if (dp->major == offset)
423 seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
424 mutex_unlock(&major_names_lock);
426 #endif /* CONFIG_PROC_FS */
429 * register_blkdev - register a new block device
431 * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
432 * @major = 0, try to allocate any unused major number.
433 * @name: the name of the new block device as a zero terminated string
435 * The @name must be unique within the system.
437 * The return value depends on the @major input parameter:
439 * - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
440 * then the function returns zero on success, or a negative error code
441 * - if any unused major number was requested with @major = 0 parameter
442 * then the return value is the allocated major number in range
443 * [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
445 * See Documentation/admin-guide/devices.txt for the list of allocated
448 int __register_blkdev(unsigned int major, const char *name,
449 void (*probe)(dev_t devt))
451 struct blk_major_name **n, *p;
454 mutex_lock(&major_names_lock);
458 for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
459 if (major_names[index] == NULL)
464 printk("%s: failed to get major for %s\n",
473 if (major >= BLKDEV_MAJOR_MAX) {
474 pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
475 __func__, major, BLKDEV_MAJOR_MAX-1, name);
481 p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
489 strlcpy(p->name, name, sizeof(p->name));
491 index = major_to_index(major);
493 for (n = &major_names[index]; *n; n = &(*n)->next) {
494 if ((*n)->major == major)
503 printk("register_blkdev: cannot get major %u for %s\n",
508 mutex_unlock(&major_names_lock);
511 EXPORT_SYMBOL(__register_blkdev);
513 void unregister_blkdev(unsigned int major, const char *name)
515 struct blk_major_name **n;
516 struct blk_major_name *p = NULL;
517 int index = major_to_index(major);
519 mutex_lock(&major_names_lock);
520 for (n = &major_names[index]; *n; n = &(*n)->next)
521 if ((*n)->major == major)
523 if (!*n || strcmp((*n)->name, name)) {
529 mutex_unlock(&major_names_lock);
533 EXPORT_SYMBOL(unregister_blkdev);
536 * blk_mangle_minor - scatter minor numbers apart
537 * @minor: minor number to mangle
539 * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
540 * is enabled. Mangling twice gives the original value.
548 static int blk_mangle_minor(int minor)
550 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
553 for (i = 0; i < MINORBITS / 2; i++) {
554 int low = minor & (1 << i);
555 int high = minor & (1 << (MINORBITS - 1 - i));
556 int distance = MINORBITS - 1 - 2 * i;
558 minor ^= low | high; /* clear both bits */
559 low <<= distance; /* swap the positions */
561 minor |= low | high; /* and set */
568 * blk_alloc_devt - allocate a dev_t for a partition
569 * @part: partition to allocate dev_t for
570 * @devt: out parameter for resulting dev_t
572 * Allocate a dev_t for block device.
575 * 0 on success, allocated dev_t is returned in *@devt. -errno on
581 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
583 struct gendisk *disk = part_to_disk(part);
586 /* in consecutive minor range? */
587 if (part->partno < disk->minors) {
588 *devt = MKDEV(disk->major, disk->first_minor + part->partno);
592 /* allocate ext devt */
593 idr_preload(GFP_KERNEL);
595 spin_lock_bh(&ext_devt_lock);
596 idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
597 spin_unlock_bh(&ext_devt_lock);
601 return idx == -ENOSPC ? -EBUSY : idx;
603 *devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
608 * blk_free_devt - free a dev_t
609 * @devt: dev_t to free
611 * Free @devt which was allocated using blk_alloc_devt().
616 void blk_free_devt(dev_t devt)
618 if (devt == MKDEV(0, 0))
621 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
622 spin_lock_bh(&ext_devt_lock);
623 idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
624 spin_unlock_bh(&ext_devt_lock);
629 * We invalidate devt by assigning NULL pointer for devt in idr.
631 void blk_invalidate_devt(dev_t devt)
633 if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
634 spin_lock_bh(&ext_devt_lock);
635 idr_replace(&ext_devt_idr, NULL, blk_mangle_minor(MINOR(devt)));
636 spin_unlock_bh(&ext_devt_lock);
640 static char *bdevt_str(dev_t devt, char *buf)
642 if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
643 char tbuf[BDEVT_SIZE];
644 snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
645 snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
647 snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
653 * Register device numbers dev..(dev+range-1)
654 * range must be nonzero
655 * The hash chain is sorted on range, so that subranges can override.
657 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
658 struct kobject *(*probe)(dev_t, int *, void *),
659 int (*lock)(dev_t, void *), void *data)
661 unsigned n = MAJOR(devt + range - 1) - MAJOR(devt) + 1;
662 unsigned index = MAJOR(devt);
667 p = kmalloc_array(n, sizeof(struct bdev_map), GFP_KERNEL);
671 for (i = 0; i < n; i++, p++) {
680 mutex_lock(&bdev_map_lock);
681 for (i = 0, p -= n; i < n; i++, p++, index++) {
682 struct bdev_map **s = &bdev_map[index % 255];
683 while (*s && (*s)->range < range)
688 mutex_unlock(&bdev_map_lock);
690 EXPORT_SYMBOL(blk_register_region);
692 void blk_unregister_region(dev_t devt, unsigned long range)
694 unsigned n = MAJOR(devt + range - 1) - MAJOR(devt) + 1;
695 unsigned index = MAJOR(devt);
697 struct bdev_map *found = NULL;
699 mutex_lock(&bdev_map_lock);
700 for (i = 0; i < min(n, 255u); i++, index++) {
702 for (s = &bdev_map[index % 255]; *s; s = &(*s)->next) {
703 struct bdev_map *p = *s;
704 if (p->dev == devt && p->range == range) {
712 mutex_unlock(&bdev_map_lock);
715 EXPORT_SYMBOL(blk_unregister_region);
717 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
719 struct gendisk *p = data;
721 return &disk_to_dev(p)->kobj;
724 static int exact_lock(dev_t devt, void *data)
726 struct gendisk *p = data;
728 if (!get_disk_and_module(p))
733 static void disk_scan_partitions(struct gendisk *disk)
735 struct block_device *bdev;
737 if (!get_capacity(disk) || !disk_part_scan_enabled(disk))
740 set_bit(GD_NEED_PART_SCAN, &disk->state);
741 bdev = blkdev_get_by_dev(disk_devt(disk), FMODE_READ, NULL);
743 blkdev_put(bdev, FMODE_READ);
746 static void register_disk(struct device *parent, struct gendisk *disk,
747 const struct attribute_group **groups)
749 struct device *ddev = disk_to_dev(disk);
750 struct disk_part_iter piter;
751 struct hd_struct *part;
754 ddev->parent = parent;
756 dev_set_name(ddev, "%s", disk->disk_name);
758 /* delay uevents, until we scanned partition table */
759 dev_set_uevent_suppress(ddev, 1);
762 WARN_ON(ddev->groups);
763 ddev->groups = groups;
765 if (device_add(ddev))
767 if (!sysfs_deprecated) {
768 err = sysfs_create_link(block_depr, &ddev->kobj,
769 kobject_name(&ddev->kobj));
777 * avoid probable deadlock caused by allocating memory with
778 * GFP_KERNEL in runtime_resume callback of its all ancestor
781 pm_runtime_set_memalloc_noio(ddev, true);
783 disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
784 disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
786 if (disk->flags & GENHD_FL_HIDDEN) {
787 dev_set_uevent_suppress(ddev, 0);
791 disk_scan_partitions(disk);
793 /* announce disk after possible partitions are created */
794 dev_set_uevent_suppress(ddev, 0);
795 kobject_uevent(&ddev->kobj, KOBJ_ADD);
797 /* announce possible partitions */
798 disk_part_iter_init(&piter, disk, 0);
799 while ((part = disk_part_iter_next(&piter)))
800 kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
801 disk_part_iter_exit(&piter);
803 if (disk->queue->backing_dev_info->dev) {
804 err = sysfs_create_link(&ddev->kobj,
805 &disk->queue->backing_dev_info->dev->kobj,
812 * __device_add_disk - add disk information to kernel list
813 * @parent: parent device for the disk
814 * @disk: per-device partitioning information
815 * @groups: Additional per-device sysfs groups
816 * @register_queue: register the queue if set to true
818 * This function registers the partitioning information in @disk
821 * FIXME: error handling
823 static void __device_add_disk(struct device *parent, struct gendisk *disk,
824 const struct attribute_group **groups,
831 * The disk queue should now be all set with enough information about
832 * the device for the elevator code to pick an adequate default
833 * elevator if one is needed, that is, for devices requesting queue
837 elevator_init_mq(disk->queue);
839 /* minors == 0 indicates to use ext devt from part0 and should
840 * be accompanied with EXT_DEVT flag. Make sure all
841 * parameters make sense.
843 WARN_ON(disk->minors && !(disk->major || disk->first_minor));
844 WARN_ON(!disk->minors &&
845 !(disk->flags & (GENHD_FL_EXT_DEVT | GENHD_FL_HIDDEN)));
847 disk->flags |= GENHD_FL_UP;
849 retval = blk_alloc_devt(&disk->part0, &devt);
854 disk->major = MAJOR(devt);
855 disk->first_minor = MINOR(devt);
857 disk_alloc_events(disk);
859 if (disk->flags & GENHD_FL_HIDDEN) {
861 * Don't let hidden disks show up in /proc/partitions,
862 * and don't bother scanning for partitions either.
864 disk->flags |= GENHD_FL_SUPPRESS_PARTITION_INFO;
865 disk->flags |= GENHD_FL_NO_PART_SCAN;
867 struct backing_dev_info *bdi = disk->queue->backing_dev_info;
868 struct device *dev = disk_to_dev(disk);
871 /* Register BDI before referencing it from bdev */
873 ret = bdi_register(bdi, "%u:%u", MAJOR(devt), MINOR(devt));
875 bdi_set_owner(bdi, dev);
876 blk_register_region(disk_devt(disk), disk->minors, NULL,
877 exact_match, exact_lock, disk);
879 register_disk(parent, disk, groups);
881 blk_register_queue(disk);
884 * Take an extra ref on queue which will be put on disk_release()
885 * so that it sticks around as long as @disk is there.
887 WARN_ON_ONCE(!blk_get_queue(disk->queue));
889 disk_add_events(disk);
890 blk_integrity_add(disk);
893 void device_add_disk(struct device *parent, struct gendisk *disk,
894 const struct attribute_group **groups)
897 __device_add_disk(parent, disk, groups, true);
899 EXPORT_SYMBOL(device_add_disk);
901 void device_add_disk_no_queue_reg(struct device *parent, struct gendisk *disk)
903 __device_add_disk(parent, disk, NULL, false);
905 EXPORT_SYMBOL(device_add_disk_no_queue_reg);
907 static void invalidate_partition(struct gendisk *disk, int partno)
909 struct block_device *bdev;
911 bdev = bdget_disk(disk, partno);
916 __invalidate_device(bdev, true);
919 * Unhash the bdev inode for this device so that it gets evicted as soon
920 * as last inode reference is dropped.
922 remove_inode_hash(bdev->bd_inode);
927 * del_gendisk - remove the gendisk
928 * @disk: the struct gendisk to remove
930 * Removes the gendisk and all its associated resources. This deletes the
931 * partitions associated with the gendisk, and unregisters the associated
934 * This is the counter to the respective __device_add_disk() call.
936 * The final removal of the struct gendisk happens when its refcount reaches 0
937 * with put_disk(), which should be called after del_gendisk(), if
938 * __device_add_disk() was used.
940 * Drivers exist which depend on the release of the gendisk to be synchronous,
941 * it should not be deferred.
945 void del_gendisk(struct gendisk *disk)
947 struct disk_part_iter piter;
948 struct hd_struct *part;
952 if (WARN_ON_ONCE(!disk->queue))
955 blk_integrity_del(disk);
956 disk_del_events(disk);
959 * Block lookups of the disk until all bdevs are unhashed and the
960 * disk is marked as dead (GENHD_FL_UP cleared).
962 down_write(&disk->lookup_sem);
963 /* invalidate stuff */
964 disk_part_iter_init(&piter, disk,
965 DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
966 while ((part = disk_part_iter_next(&piter))) {
967 invalidate_partition(disk, part->partno);
968 delete_partition(part);
970 disk_part_iter_exit(&piter);
972 invalidate_partition(disk, 0);
973 set_capacity(disk, 0);
974 disk->flags &= ~GENHD_FL_UP;
975 up_write(&disk->lookup_sem);
977 if (!(disk->flags & GENHD_FL_HIDDEN)) {
978 sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
981 * Unregister bdi before releasing device numbers (as they can
982 * get reused and we'd get clashes in sysfs).
984 bdi_unregister(disk->queue->backing_dev_info);
987 blk_unregister_queue(disk);
989 if (!(disk->flags & GENHD_FL_HIDDEN))
990 blk_unregister_region(disk_devt(disk), disk->minors);
992 * Remove gendisk pointer from idr so that it cannot be looked up
993 * while RCU period before freeing gendisk is running to prevent
994 * use-after-free issues. Note that the device number stays
995 * "in-use" until we really free the gendisk.
997 blk_invalidate_devt(disk_devt(disk));
999 kobject_put(disk->part0.holder_dir);
1000 kobject_put(disk->slave_dir);
1002 part_stat_set_all(&disk->part0, 0);
1003 disk->part0.stamp = 0;
1004 if (!sysfs_deprecated)
1005 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
1006 pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
1007 device_del(disk_to_dev(disk));
1009 EXPORT_SYMBOL(del_gendisk);
1011 /* sysfs access to bad-blocks list. */
1012 static ssize_t disk_badblocks_show(struct device *dev,
1013 struct device_attribute *attr,
1016 struct gendisk *disk = dev_to_disk(dev);
1019 return sprintf(page, "\n");
1021 return badblocks_show(disk->bb, page, 0);
1024 static ssize_t disk_badblocks_store(struct device *dev,
1025 struct device_attribute *attr,
1026 const char *page, size_t len)
1028 struct gendisk *disk = dev_to_disk(dev);
1033 return badblocks_store(disk->bb, page, len, 0);
1036 static void request_gendisk_module(dev_t devt)
1038 unsigned int major = MAJOR(devt);
1039 struct blk_major_name **n;
1041 mutex_lock(&major_names_lock);
1042 for (n = &major_names[major_to_index(major)]; *n; n = &(*n)->next) {
1043 if ((*n)->major == major && (*n)->probe) {
1045 mutex_unlock(&major_names_lock);
1049 mutex_unlock(&major_names_lock);
1051 if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
1052 /* Make old-style 2.4 aliases work */
1053 request_module("block-major-%d", MAJOR(devt));
1056 static struct gendisk *lookup_gendisk(dev_t dev, int *partno)
1058 struct kobject *kobj;
1060 unsigned long best = ~0UL;
1063 mutex_lock(&bdev_map_lock);
1064 for (p = bdev_map[MAJOR(dev) % 255]; p; p = p->next) {
1065 struct kobject *(*probe)(dev_t, int *, void *);
1066 struct module *owner;
1069 if (p->dev > dev || p->dev + p->range - 1 < dev)
1071 if (p->range - 1 >= best)
1073 if (!try_module_get(p->owner))
1078 best = p->range - 1;
1079 *partno = dev - p->dev;
1082 mutex_unlock(&bdev_map_lock);
1084 request_gendisk_module(dev);
1088 if (p->lock && p->lock(dev, data) < 0) {
1092 mutex_unlock(&bdev_map_lock);
1093 kobj = probe(dev, partno, data);
1094 /* Currently ->owner protects _only_ ->probe() itself. */
1097 return dev_to_disk(kobj_to_dev(kobj));
1100 mutex_unlock(&bdev_map_lock);
1106 * get_gendisk - get partitioning information for a given device
1107 * @devt: device to get partitioning information for
1108 * @partno: returned partition index
1110 * This function gets the structure containing partitioning
1111 * information for the given device @devt.
1113 * Context: can sleep
1115 struct gendisk *get_gendisk(dev_t devt, int *partno)
1117 struct gendisk *disk = NULL;
1121 if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
1122 disk = lookup_gendisk(devt, partno);
1124 struct hd_struct *part;
1126 spin_lock_bh(&ext_devt_lock);
1127 part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
1128 if (part && get_disk_and_module(part_to_disk(part))) {
1129 *partno = part->partno;
1130 disk = part_to_disk(part);
1132 spin_unlock_bh(&ext_devt_lock);
1139 * Synchronize with del_gendisk() to not return disk that is being
1142 down_read(&disk->lookup_sem);
1143 if (unlikely((disk->flags & GENHD_FL_HIDDEN) ||
1144 !(disk->flags & GENHD_FL_UP))) {
1145 up_read(&disk->lookup_sem);
1146 put_disk_and_module(disk);
1149 up_read(&disk->lookup_sem);
1155 * bdget_disk - do bdget() by gendisk and partition number
1156 * @disk: gendisk of interest
1157 * @partno: partition number
1159 * Find partition @partno from @disk, do bdget() on it.
1165 * Resulting block_device on success, NULL on failure.
1167 struct block_device *bdget_disk(struct gendisk *disk, int partno)
1169 struct hd_struct *part;
1170 struct block_device *bdev = NULL;
1172 part = disk_get_part(disk, partno);
1174 bdev = bdget_part(part);
1175 disk_put_part(part);
1179 EXPORT_SYMBOL(bdget_disk);
1182 * print a full list of all partitions - intended for places where the root
1183 * filesystem can't be mounted and thus to give the victim some idea of what
1186 void __init printk_all_partitions(void)
1188 struct class_dev_iter iter;
1191 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1192 while ((dev = class_dev_iter_next(&iter))) {
1193 struct gendisk *disk = dev_to_disk(dev);
1194 struct disk_part_iter piter;
1195 struct hd_struct *part;
1196 char name_buf[BDEVNAME_SIZE];
1197 char devt_buf[BDEVT_SIZE];
1200 * Don't show empty devices or things that have been
1203 if (get_capacity(disk) == 0 ||
1204 (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
1208 * Note, unlike /proc/partitions, I am showing the
1209 * numbers in hex - the same format as the root=
1212 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
1213 while ((part = disk_part_iter_next(&piter))) {
1214 bool is_part0 = part == &disk->part0;
1216 printk("%s%s %10llu %s %s", is_part0 ? "" : " ",
1217 bdevt_str(part_devt(part), devt_buf),
1218 (unsigned long long)part_nr_sects_read(part) >> 1
1219 , disk_name(disk, part->partno, name_buf),
1220 part->info ? part->info->uuid : "");
1222 if (dev->parent && dev->parent->driver)
1223 printk(" driver: %s\n",
1224 dev->parent->driver->name);
1226 printk(" (driver?)\n");
1230 disk_part_iter_exit(&piter);
1232 class_dev_iter_exit(&iter);
1235 #ifdef CONFIG_PROC_FS
1237 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
1240 struct class_dev_iter *iter;
1243 iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1245 return ERR_PTR(-ENOMEM);
1247 seqf->private = iter;
1248 class_dev_iter_init(iter, &block_class, NULL, &disk_type);
1250 dev = class_dev_iter_next(iter);
1255 return dev_to_disk(dev);
1258 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
1263 dev = class_dev_iter_next(seqf->private);
1265 return dev_to_disk(dev);
1270 static void disk_seqf_stop(struct seq_file *seqf, void *v)
1272 struct class_dev_iter *iter = seqf->private;
1274 /* stop is called even after start failed :-( */
1276 class_dev_iter_exit(iter);
1278 seqf->private = NULL;
1282 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
1286 p = disk_seqf_start(seqf, pos);
1287 if (!IS_ERR_OR_NULL(p) && !*pos)
1288 seq_puts(seqf, "major minor #blocks name\n\n");
1292 static int show_partition(struct seq_file *seqf, void *v)
1294 struct gendisk *sgp = v;
1295 struct disk_part_iter piter;
1296 struct hd_struct *part;
1297 char buf[BDEVNAME_SIZE];
1299 /* Don't show non-partitionable removeable devices or empty devices */
1300 if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
1301 (sgp->flags & GENHD_FL_REMOVABLE)))
1303 if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
1306 /* show the full disk and all non-0 size partitions of it */
1307 disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
1308 while ((part = disk_part_iter_next(&piter)))
1309 seq_printf(seqf, "%4d %7d %10llu %s\n",
1310 MAJOR(part_devt(part)), MINOR(part_devt(part)),
1311 (unsigned long long)part_nr_sects_read(part) >> 1,
1312 disk_name(sgp, part->partno, buf));
1313 disk_part_iter_exit(&piter);
1318 static const struct seq_operations partitions_op = {
1319 .start = show_partition_start,
1320 .next = disk_seqf_next,
1321 .stop = disk_seqf_stop,
1322 .show = show_partition
1326 static void bdev_map_init(void)
1328 struct bdev_map *base;
1331 base = kzalloc(sizeof(*base), GFP_KERNEL);
1333 panic("cannot allocate bdev_map");
1337 for (i = 0; i < 255; i++)
1341 static int __init genhd_device_init(void)
1345 block_class.dev_kobj = sysfs_dev_block_kobj;
1346 error = class_register(&block_class);
1347 if (unlikely(error))
1352 register_blkdev(BLOCK_EXT_MAJOR, "blkext");
1354 /* create top-level block dir */
1355 if (!sysfs_deprecated)
1356 block_depr = kobject_create_and_add("block", NULL);
1360 subsys_initcall(genhd_device_init);
1362 static ssize_t disk_range_show(struct device *dev,
1363 struct device_attribute *attr, char *buf)
1365 struct gendisk *disk = dev_to_disk(dev);
1367 return sprintf(buf, "%d\n", disk->minors);
1370 static ssize_t disk_ext_range_show(struct device *dev,
1371 struct device_attribute *attr, char *buf)
1373 struct gendisk *disk = dev_to_disk(dev);
1375 return sprintf(buf, "%d\n", disk_max_parts(disk));
1378 static ssize_t disk_removable_show(struct device *dev,
1379 struct device_attribute *attr, char *buf)
1381 struct gendisk *disk = dev_to_disk(dev);
1383 return sprintf(buf, "%d\n",
1384 (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
1387 static ssize_t disk_hidden_show(struct device *dev,
1388 struct device_attribute *attr, char *buf)
1390 struct gendisk *disk = dev_to_disk(dev);
1392 return sprintf(buf, "%d\n",
1393 (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
1396 static ssize_t disk_ro_show(struct device *dev,
1397 struct device_attribute *attr, char *buf)
1399 struct gendisk *disk = dev_to_disk(dev);
1401 return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
1404 ssize_t part_size_show(struct device *dev,
1405 struct device_attribute *attr, char *buf)
1407 struct hd_struct *p = dev_to_part(dev);
1409 return sprintf(buf, "%llu\n",
1410 (unsigned long long)part_nr_sects_read(p));
1413 ssize_t part_stat_show(struct device *dev,
1414 struct device_attribute *attr, char *buf)
1416 struct hd_struct *p = dev_to_part(dev);
1417 struct request_queue *q = part_to_disk(p)->queue;
1418 struct disk_stats stat;
1419 unsigned int inflight;
1421 part_stat_read_all(p, &stat);
1423 inflight = blk_mq_in_flight(q, p);
1425 inflight = part_in_flight(p);
1428 "%8lu %8lu %8llu %8u "
1429 "%8lu %8lu %8llu %8u "
1431 "%8lu %8lu %8llu %8u "
1434 stat.ios[STAT_READ],
1435 stat.merges[STAT_READ],
1436 (unsigned long long)stat.sectors[STAT_READ],
1437 (unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1438 stat.ios[STAT_WRITE],
1439 stat.merges[STAT_WRITE],
1440 (unsigned long long)stat.sectors[STAT_WRITE],
1441 (unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1443 jiffies_to_msecs(stat.io_ticks),
1444 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1445 stat.nsecs[STAT_WRITE] +
1446 stat.nsecs[STAT_DISCARD] +
1447 stat.nsecs[STAT_FLUSH],
1449 stat.ios[STAT_DISCARD],
1450 stat.merges[STAT_DISCARD],
1451 (unsigned long long)stat.sectors[STAT_DISCARD],
1452 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1453 stat.ios[STAT_FLUSH],
1454 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1457 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1460 struct hd_struct *p = dev_to_part(dev);
1461 struct request_queue *q = part_to_disk(p)->queue;
1462 unsigned int inflight[2];
1465 blk_mq_in_flight_rw(q, p, inflight);
1467 part_in_flight_rw(p, inflight);
1469 return sprintf(buf, "%8u %8u\n", inflight[0], inflight[1]);
1472 static ssize_t disk_capability_show(struct device *dev,
1473 struct device_attribute *attr, char *buf)
1475 struct gendisk *disk = dev_to_disk(dev);
1477 return sprintf(buf, "%x\n", disk->flags);
1480 static ssize_t disk_alignment_offset_show(struct device *dev,
1481 struct device_attribute *attr,
1484 struct gendisk *disk = dev_to_disk(dev);
1486 return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
1489 static ssize_t disk_discard_alignment_show(struct device *dev,
1490 struct device_attribute *attr,
1493 struct gendisk *disk = dev_to_disk(dev);
1495 return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
1498 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1499 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1500 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1501 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1502 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1503 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1504 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1505 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1506 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1507 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1508 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1509 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1511 #ifdef CONFIG_FAIL_MAKE_REQUEST
1512 ssize_t part_fail_show(struct device *dev,
1513 struct device_attribute *attr, char *buf)
1515 struct hd_struct *p = dev_to_part(dev);
1517 return sprintf(buf, "%d\n", p->make_it_fail);
1520 ssize_t part_fail_store(struct device *dev,
1521 struct device_attribute *attr,
1522 const char *buf, size_t count)
1524 struct hd_struct *p = dev_to_part(dev);
1527 if (count > 0 && sscanf(buf, "%d", &i) > 0)
1528 p->make_it_fail = (i == 0) ? 0 : 1;
1533 static struct device_attribute dev_attr_fail =
1534 __ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1535 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1537 #ifdef CONFIG_FAIL_IO_TIMEOUT
1538 static struct device_attribute dev_attr_fail_timeout =
1539 __ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1542 static struct attribute *disk_attrs[] = {
1543 &dev_attr_range.attr,
1544 &dev_attr_ext_range.attr,
1545 &dev_attr_removable.attr,
1546 &dev_attr_hidden.attr,
1548 &dev_attr_size.attr,
1549 &dev_attr_alignment_offset.attr,
1550 &dev_attr_discard_alignment.attr,
1551 &dev_attr_capability.attr,
1552 &dev_attr_stat.attr,
1553 &dev_attr_inflight.attr,
1554 &dev_attr_badblocks.attr,
1555 #ifdef CONFIG_FAIL_MAKE_REQUEST
1556 &dev_attr_fail.attr,
1558 #ifdef CONFIG_FAIL_IO_TIMEOUT
1559 &dev_attr_fail_timeout.attr,
1564 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1566 struct device *dev = container_of(kobj, typeof(*dev), kobj);
1567 struct gendisk *disk = dev_to_disk(dev);
1569 if (a == &dev_attr_badblocks.attr && !disk->bb)
1574 static struct attribute_group disk_attr_group = {
1575 .attrs = disk_attrs,
1576 .is_visible = disk_visible,
1579 static const struct attribute_group *disk_attr_groups[] = {
1585 * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1586 * @disk: disk to replace part_tbl for
1587 * @new_ptbl: new part_tbl to install
1589 * Replace disk->part_tbl with @new_ptbl in RCU-safe way. The
1590 * original ptbl is freed using RCU callback.
1593 * Matching bd_mutex locked or the caller is the only user of @disk.
1595 static void disk_replace_part_tbl(struct gendisk *disk,
1596 struct disk_part_tbl *new_ptbl)
1598 struct disk_part_tbl *old_ptbl =
1599 rcu_dereference_protected(disk->part_tbl, 1);
1601 rcu_assign_pointer(disk->part_tbl, new_ptbl);
1604 rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1605 kfree_rcu(old_ptbl, rcu_head);
1610 * disk_expand_part_tbl - expand disk->part_tbl
1611 * @disk: disk to expand part_tbl for
1612 * @partno: expand such that this partno can fit in
1614 * Expand disk->part_tbl such that @partno can fit in. disk->part_tbl
1615 * uses RCU to allow unlocked dereferencing for stats and other stuff.
1618 * Matching bd_mutex locked or the caller is the only user of @disk.
1622 * 0 on success, -errno on failure.
1624 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1626 struct disk_part_tbl *old_ptbl =
1627 rcu_dereference_protected(disk->part_tbl, 1);
1628 struct disk_part_tbl *new_ptbl;
1629 int len = old_ptbl ? old_ptbl->len : 0;
1633 * check for int overflow, since we can get here from blkpg_ioctl()
1634 * with a user passed 'partno'.
1636 target = partno + 1;
1640 /* disk_max_parts() is zero during initialization, ignore if so */
1641 if (disk_max_parts(disk) && target > disk_max_parts(disk))
1647 new_ptbl = kzalloc_node(struct_size(new_ptbl, part, target), GFP_KERNEL,
1652 new_ptbl->len = target;
1654 for (i = 0; i < len; i++)
1655 rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1657 disk_replace_part_tbl(disk, new_ptbl);
1662 * disk_release - releases all allocated resources of the gendisk
1663 * @dev: the device representing this disk
1665 * This function releases all allocated resources of the gendisk.
1667 * The struct gendisk refcount is incremented with get_gendisk() or
1668 * get_disk_and_module(), and its refcount is decremented with
1669 * put_disk_and_module() or put_disk(). Once the refcount reaches 0 this
1670 * function is called.
1672 * Drivers which used __device_add_disk() have a gendisk with a request_queue
1673 * assigned. Since the request_queue sits on top of the gendisk for these
1674 * drivers we also call blk_put_queue() for them, and we expect the
1675 * request_queue refcount to reach 0 at this point, and so the request_queue
1676 * will also be freed prior to the disk.
1678 * Context: can sleep
1680 static void disk_release(struct device *dev)
1682 struct gendisk *disk = dev_to_disk(dev);
1686 blk_free_devt(dev->devt);
1687 disk_release_events(disk);
1688 kfree(disk->random);
1689 disk_replace_part_tbl(disk, NULL);
1690 hd_free_part(&disk->part0);
1692 blk_put_queue(disk->queue);
1695 struct class block_class = {
1699 static char *block_devnode(struct device *dev, umode_t *mode,
1700 kuid_t *uid, kgid_t *gid)
1702 struct gendisk *disk = dev_to_disk(dev);
1704 if (disk->fops->devnode)
1705 return disk->fops->devnode(disk, mode);
1709 const struct device_type disk_type = {
1711 .groups = disk_attr_groups,
1712 .release = disk_release,
1713 .devnode = block_devnode,
1716 #ifdef CONFIG_PROC_FS
1718 * aggregate disk stat collector. Uses the same stats that the sysfs
1719 * entries do, above, but makes them available through one seq_file.
1721 * The output looks suspiciously like /proc/partitions with a bunch of
1724 static int diskstats_show(struct seq_file *seqf, void *v)
1726 struct gendisk *gp = v;
1727 struct disk_part_iter piter;
1728 struct hd_struct *hd;
1729 char buf[BDEVNAME_SIZE];
1730 unsigned int inflight;
1731 struct disk_stats stat;
1734 if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1735 seq_puts(seqf, "major minor name"
1736 " rio rmerge rsect ruse wio wmerge "
1737 "wsect wuse running use aveq"
1741 disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1742 while ((hd = disk_part_iter_next(&piter))) {
1743 part_stat_read_all(hd, &stat);
1744 if (queue_is_mq(gp->queue))
1745 inflight = blk_mq_in_flight(gp->queue, hd);
1747 inflight = part_in_flight(hd);
1749 seq_printf(seqf, "%4d %7d %s "
1756 MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1757 disk_name(gp, hd->partno, buf),
1758 stat.ios[STAT_READ],
1759 stat.merges[STAT_READ],
1760 stat.sectors[STAT_READ],
1761 (unsigned int)div_u64(stat.nsecs[STAT_READ],
1763 stat.ios[STAT_WRITE],
1764 stat.merges[STAT_WRITE],
1765 stat.sectors[STAT_WRITE],
1766 (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1769 jiffies_to_msecs(stat.io_ticks),
1770 (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1771 stat.nsecs[STAT_WRITE] +
1772 stat.nsecs[STAT_DISCARD] +
1773 stat.nsecs[STAT_FLUSH],
1775 stat.ios[STAT_DISCARD],
1776 stat.merges[STAT_DISCARD],
1777 stat.sectors[STAT_DISCARD],
1778 (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1780 stat.ios[STAT_FLUSH],
1781 (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1785 disk_part_iter_exit(&piter);
1790 static const struct seq_operations diskstats_op = {
1791 .start = disk_seqf_start,
1792 .next = disk_seqf_next,
1793 .stop = disk_seqf_stop,
1794 .show = diskstats_show
1797 static int __init proc_genhd_init(void)
1799 proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1800 proc_create_seq("partitions", 0, NULL, &partitions_op);
1803 module_init(proc_genhd_init);
1804 #endif /* CONFIG_PROC_FS */
1806 dev_t blk_lookup_devt(const char *name, int partno)
1808 dev_t devt = MKDEV(0, 0);
1809 struct class_dev_iter iter;
1812 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1813 while ((dev = class_dev_iter_next(&iter))) {
1814 struct gendisk *disk = dev_to_disk(dev);
1815 struct hd_struct *part;
1817 if (strcmp(dev_name(dev), name))
1820 if (partno < disk->minors) {
1821 /* We need to return the right devno, even
1822 * if the partition doesn't exist yet.
1824 devt = MKDEV(MAJOR(dev->devt),
1825 MINOR(dev->devt) + partno);
1828 part = disk_get_part(disk, partno);
1830 devt = part_devt(part);
1831 disk_put_part(part);
1834 disk_put_part(part);
1836 class_dev_iter_exit(&iter);
1840 struct gendisk *__alloc_disk_node(int minors, int node_id)
1842 struct gendisk *disk;
1843 struct disk_part_tbl *ptbl;
1845 if (minors > DISK_MAX_PARTS) {
1847 "block: can't allocate more than %d partitions\n",
1849 minors = DISK_MAX_PARTS;
1852 disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1856 disk->part0.dkstats = alloc_percpu(struct disk_stats);
1857 if (!disk->part0.dkstats)
1860 init_rwsem(&disk->lookup_sem);
1861 disk->node_id = node_id;
1862 if (disk_expand_part_tbl(disk, 0)) {
1863 free_percpu(disk->part0.dkstats);
1867 ptbl = rcu_dereference_protected(disk->part_tbl, 1);
1868 rcu_assign_pointer(ptbl->part[0], &disk->part0);
1871 * set_capacity() and get_capacity() currently don't use
1872 * seqcounter to read/update the part0->nr_sects. Still init
1873 * the counter as we can read the sectors in IO submission
1874 * patch using seqence counters.
1876 * TODO: Ideally set_capacity() and get_capacity() should be
1877 * converted to make use of bd_mutex and sequence counters.
1879 hd_sects_seq_init(&disk->part0);
1880 if (hd_ref_init(&disk->part0))
1881 goto out_free_part0;
1883 disk->minors = minors;
1884 rand_initialize_disk(disk);
1885 disk_to_dev(disk)->class = &block_class;
1886 disk_to_dev(disk)->type = &disk_type;
1887 device_initialize(disk_to_dev(disk));
1891 hd_free_part(&disk->part0);
1896 EXPORT_SYMBOL(__alloc_disk_node);
1899 * get_disk_and_module - increments the gendisk and gendisk fops module refcount
1900 * @disk: the struct gendisk to increment the refcount for
1902 * This increments the refcount for the struct gendisk, and the gendisk's
1903 * fops module owner.
1905 * Context: Any context.
1907 struct kobject *get_disk_and_module(struct gendisk *disk)
1909 struct module *owner;
1910 struct kobject *kobj;
1914 owner = disk->fops->owner;
1915 if (owner && !try_module_get(owner))
1917 kobj = kobject_get_unless_zero(&disk_to_dev(disk)->kobj);
1925 EXPORT_SYMBOL(get_disk_and_module);
1928 * put_disk - decrements the gendisk refcount
1929 * @disk: the struct gendisk to decrement the refcount for
1931 * This decrements the refcount for the struct gendisk. When this reaches 0
1932 * we'll have disk_release() called.
1934 * Context: Any context, but the last reference must not be dropped from
1937 void put_disk(struct gendisk *disk)
1940 kobject_put(&disk_to_dev(disk)->kobj);
1942 EXPORT_SYMBOL(put_disk);
1945 * put_disk_and_module - decrements the module and gendisk refcount
1946 * @disk: the struct gendisk to decrement the refcount for
1948 * This is a counterpart of get_disk_and_module() and thus also of
1951 * Context: Any context, but the last reference must not be dropped from
1954 void put_disk_and_module(struct gendisk *disk)
1957 struct module *owner = disk->fops->owner;
1963 EXPORT_SYMBOL(put_disk_and_module);
1965 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1967 char event[] = "DISK_RO=1";
1968 char *envp[] = { event, NULL };
1972 kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1975 void set_disk_ro(struct gendisk *disk, int flag)
1977 struct disk_part_iter piter;
1978 struct hd_struct *part;
1980 if (disk->part0.policy != flag) {
1981 set_disk_ro_uevent(disk, flag);
1982 disk->part0.policy = flag;
1985 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1986 while ((part = disk_part_iter_next(&piter)))
1987 part->policy = flag;
1988 disk_part_iter_exit(&piter);
1991 EXPORT_SYMBOL(set_disk_ro);
1993 int bdev_read_only(struct block_device *bdev)
1997 return bdev->bd_part->policy;
2000 EXPORT_SYMBOL(bdev_read_only);
2003 * Disk events - monitor disk events like media change and eject request.
2005 struct disk_events {
2006 struct list_head node; /* all disk_event's */
2007 struct gendisk *disk; /* the associated disk */
2010 struct mutex block_mutex; /* protects blocking */
2011 int block; /* event blocking depth */
2012 unsigned int pending; /* events already sent out */
2013 unsigned int clearing; /* events being cleared */
2015 long poll_msecs; /* interval, -1 for default */
2016 struct delayed_work dwork;
2019 static const char *disk_events_strs[] = {
2020 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "media_change",
2021 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "eject_request",
2024 static char *disk_uevents[] = {
2025 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "DISK_MEDIA_CHANGE=1",
2026 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "DISK_EJECT_REQUEST=1",
2029 /* list of all disk_events */
2030 static DEFINE_MUTEX(disk_events_mutex);
2031 static LIST_HEAD(disk_events);
2033 /* disable in-kernel polling by default */
2034 static unsigned long disk_events_dfl_poll_msecs;
2036 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
2038 struct disk_events *ev = disk->ev;
2039 long intv_msecs = 0;
2042 * If device-specific poll interval is set, always use it. If
2043 * the default is being used, poll if the POLL flag is set.
2045 if (ev->poll_msecs >= 0)
2046 intv_msecs = ev->poll_msecs;
2047 else if (disk->event_flags & DISK_EVENT_FLAG_POLL)
2048 intv_msecs = disk_events_dfl_poll_msecs;
2050 return msecs_to_jiffies(intv_msecs);
2054 * disk_block_events - block and flush disk event checking
2055 * @disk: disk to block events for
2057 * On return from this function, it is guaranteed that event checking
2058 * isn't in progress and won't happen until unblocked by
2059 * disk_unblock_events(). Events blocking is counted and the actual
2060 * unblocking happens after the matching number of unblocks are done.
2062 * Note that this intentionally does not block event checking from
2063 * disk_clear_events().
2068 void disk_block_events(struct gendisk *disk)
2070 struct disk_events *ev = disk->ev;
2071 unsigned long flags;
2078 * Outer mutex ensures that the first blocker completes canceling
2079 * the event work before further blockers are allowed to finish.
2081 mutex_lock(&ev->block_mutex);
2083 spin_lock_irqsave(&ev->lock, flags);
2084 cancel = !ev->block++;
2085 spin_unlock_irqrestore(&ev->lock, flags);
2088 cancel_delayed_work_sync(&disk->ev->dwork);
2090 mutex_unlock(&ev->block_mutex);
2093 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
2095 struct disk_events *ev = disk->ev;
2097 unsigned long flags;
2099 spin_lock_irqsave(&ev->lock, flags);
2101 if (WARN_ON_ONCE(ev->block <= 0))
2107 intv = disk_events_poll_jiffies(disk);
2109 queue_delayed_work(system_freezable_power_efficient_wq,
2112 queue_delayed_work(system_freezable_power_efficient_wq,
2115 spin_unlock_irqrestore(&ev->lock, flags);
2119 * disk_unblock_events - unblock disk event checking
2120 * @disk: disk to unblock events for
2122 * Undo disk_block_events(). When the block count reaches zero, it
2123 * starts events polling if configured.
2126 * Don't care. Safe to call from irq context.
2128 void disk_unblock_events(struct gendisk *disk)
2131 __disk_unblock_events(disk, false);
2135 * disk_flush_events - schedule immediate event checking and flushing
2136 * @disk: disk to check and flush events for
2137 * @mask: events to flush
2139 * Schedule immediate event checking on @disk if not blocked. Events in
2140 * @mask are scheduled to be cleared from the driver. Note that this
2141 * doesn't clear the events from @disk->ev.
2144 * If @mask is non-zero must be called with bdev->bd_mutex held.
2146 void disk_flush_events(struct gendisk *disk, unsigned int mask)
2148 struct disk_events *ev = disk->ev;
2153 spin_lock_irq(&ev->lock);
2154 ev->clearing |= mask;
2156 mod_delayed_work(system_freezable_power_efficient_wq,
2158 spin_unlock_irq(&ev->lock);
2162 * disk_clear_events - synchronously check, clear and return pending events
2163 * @disk: disk to fetch and clear events from
2164 * @mask: mask of events to be fetched and cleared
2166 * Disk events are synchronously checked and pending events in @mask
2167 * are cleared and returned. This ignores the block count.
2172 static unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
2174 struct disk_events *ev = disk->ev;
2175 unsigned int pending;
2176 unsigned int clearing = mask;
2181 disk_block_events(disk);
2184 * store the union of mask and ev->clearing on the stack so that the
2185 * race with disk_flush_events does not cause ambiguity (ev->clearing
2186 * can still be modified even if events are blocked).
2188 spin_lock_irq(&ev->lock);
2189 clearing |= ev->clearing;
2191 spin_unlock_irq(&ev->lock);
2193 disk_check_events(ev, &clearing);
2195 * if ev->clearing is not 0, the disk_flush_events got called in the
2196 * middle of this function, so we want to run the workfn without delay.
2198 __disk_unblock_events(disk, ev->clearing ? true : false);
2200 /* then, fetch and clear pending events */
2201 spin_lock_irq(&ev->lock);
2202 pending = ev->pending & mask;
2203 ev->pending &= ~mask;
2204 spin_unlock_irq(&ev->lock);
2205 WARN_ON_ONCE(clearing & mask);
2211 * bdev_check_media_change - check if a removable media has been changed
2212 * @bdev: block device to check
2214 * Check whether a removable media has been changed, and attempt to free all
2215 * dentries and inodes and invalidates all block device page cache entries in
2218 * Returns %true if the block device changed, or %false if not.
2220 bool bdev_check_media_change(struct block_device *bdev)
2222 unsigned int events;
2224 events = disk_clear_events(bdev->bd_disk, DISK_EVENT_MEDIA_CHANGE |
2225 DISK_EVENT_EJECT_REQUEST);
2226 if (!(events & DISK_EVENT_MEDIA_CHANGE))
2229 if (__invalidate_device(bdev, true))
2230 pr_warn("VFS: busy inodes on changed media %s\n",
2231 bdev->bd_disk->disk_name);
2232 set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
2235 EXPORT_SYMBOL(bdev_check_media_change);
2238 * Separate this part out so that a different pointer for clearing_ptr can be
2239 * passed in for disk_clear_events.
2241 static void disk_events_workfn(struct work_struct *work)
2243 struct delayed_work *dwork = to_delayed_work(work);
2244 struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
2246 disk_check_events(ev, &ev->clearing);
2249 static void disk_check_events(struct disk_events *ev,
2250 unsigned int *clearing_ptr)
2252 struct gendisk *disk = ev->disk;
2253 char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
2254 unsigned int clearing = *clearing_ptr;
2255 unsigned int events;
2257 int nr_events = 0, i;
2260 events = disk->fops->check_events(disk, clearing);
2262 /* accumulate pending events and schedule next poll if necessary */
2263 spin_lock_irq(&ev->lock);
2265 events &= ~ev->pending;
2266 ev->pending |= events;
2267 *clearing_ptr &= ~clearing;
2269 intv = disk_events_poll_jiffies(disk);
2270 if (!ev->block && intv)
2271 queue_delayed_work(system_freezable_power_efficient_wq,
2274 spin_unlock_irq(&ev->lock);
2277 * Tell userland about new events. Only the events listed in
2278 * @disk->events are reported, and only if DISK_EVENT_FLAG_UEVENT
2279 * is set. Otherwise, events are processed internally but never
2280 * get reported to userland.
2282 for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
2283 if ((events & disk->events & (1 << i)) &&
2284 (disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2285 envp[nr_events++] = disk_uevents[i];
2288 kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
2292 * A disk events enabled device has the following sysfs nodes under
2293 * its /sys/block/X/ directory.
2295 * events : list of all supported events
2296 * events_async : list of events which can be detected w/o polling
2297 * (always empty, only for backwards compatibility)
2298 * events_poll_msecs : polling interval, 0: disable, -1: system default
2300 static ssize_t __disk_events_show(unsigned int events, char *buf)
2302 const char *delim = "";
2306 for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
2307 if (events & (1 << i)) {
2308 pos += sprintf(buf + pos, "%s%s",
2309 delim, disk_events_strs[i]);
2313 pos += sprintf(buf + pos, "\n");
2317 static ssize_t disk_events_show(struct device *dev,
2318 struct device_attribute *attr, char *buf)
2320 struct gendisk *disk = dev_to_disk(dev);
2322 if (!(disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2325 return __disk_events_show(disk->events, buf);
2328 static ssize_t disk_events_async_show(struct device *dev,
2329 struct device_attribute *attr, char *buf)
2334 static ssize_t disk_events_poll_msecs_show(struct device *dev,
2335 struct device_attribute *attr,
2338 struct gendisk *disk = dev_to_disk(dev);
2341 return sprintf(buf, "-1\n");
2343 return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
2346 static ssize_t disk_events_poll_msecs_store(struct device *dev,
2347 struct device_attribute *attr,
2348 const char *buf, size_t count)
2350 struct gendisk *disk = dev_to_disk(dev);
2353 if (!count || !sscanf(buf, "%ld", &intv))
2356 if (intv < 0 && intv != -1)
2362 disk_block_events(disk);
2363 disk->ev->poll_msecs = intv;
2364 __disk_unblock_events(disk, true);
2369 static const DEVICE_ATTR(events, 0444, disk_events_show, NULL);
2370 static const DEVICE_ATTR(events_async, 0444, disk_events_async_show, NULL);
2371 static const DEVICE_ATTR(events_poll_msecs, 0644,
2372 disk_events_poll_msecs_show,
2373 disk_events_poll_msecs_store);
2375 static const struct attribute *disk_events_attrs[] = {
2376 &dev_attr_events.attr,
2377 &dev_attr_events_async.attr,
2378 &dev_attr_events_poll_msecs.attr,
2383 * The default polling interval can be specified by the kernel
2384 * parameter block.events_dfl_poll_msecs which defaults to 0
2385 * (disable). This can also be modified runtime by writing to
2386 * /sys/module/block/parameters/events_dfl_poll_msecs.
2388 static int disk_events_set_dfl_poll_msecs(const char *val,
2389 const struct kernel_param *kp)
2391 struct disk_events *ev;
2394 ret = param_set_ulong(val, kp);
2398 mutex_lock(&disk_events_mutex);
2400 list_for_each_entry(ev, &disk_events, node)
2401 disk_flush_events(ev->disk, 0);
2403 mutex_unlock(&disk_events_mutex);
2408 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
2409 .set = disk_events_set_dfl_poll_msecs,
2410 .get = param_get_ulong,
2413 #undef MODULE_PARAM_PREFIX
2414 #define MODULE_PARAM_PREFIX "block."
2416 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
2417 &disk_events_dfl_poll_msecs, 0644);
2420 * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
2422 static void disk_alloc_events(struct gendisk *disk)
2424 struct disk_events *ev;
2426 if (!disk->fops->check_events || !disk->events)
2429 ev = kzalloc(sizeof(*ev), GFP_KERNEL);
2431 pr_warn("%s: failed to initialize events\n", disk->disk_name);
2435 INIT_LIST_HEAD(&ev->node);
2437 spin_lock_init(&ev->lock);
2438 mutex_init(&ev->block_mutex);
2440 ev->poll_msecs = -1;
2441 INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
2446 static void disk_add_events(struct gendisk *disk)
2448 /* FIXME: error handling */
2449 if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
2450 pr_warn("%s: failed to create sysfs files for events\n",
2456 mutex_lock(&disk_events_mutex);
2457 list_add_tail(&disk->ev->node, &disk_events);
2458 mutex_unlock(&disk_events_mutex);
2461 * Block count is initialized to 1 and the following initial
2462 * unblock kicks it into action.
2464 __disk_unblock_events(disk, true);
2467 static void disk_del_events(struct gendisk *disk)
2470 disk_block_events(disk);
2472 mutex_lock(&disk_events_mutex);
2473 list_del_init(&disk->ev->node);
2474 mutex_unlock(&disk_events_mutex);
2477 sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
2480 static void disk_release_events(struct gendisk *disk)
2482 /* the block count should be 1 from disk_del_events() */
2483 WARN_ON_ONCE(disk->ev && disk->ev->block != 1);