xref: /linux/block/genhd.c (revision dd220a00e8bd5ad7f98ecdc3eed699a7cfabdc27)
1 /*
2  *  gendisk handling
3  */
4 
5 #include <linux/module.h>
6 #include <linux/fs.h>
7 #include <linux/genhd.h>
8 #include <linux/kdev_t.h>
9 #include <linux/kernel.h>
10 #include <linux/blkdev.h>
11 #include <linux/init.h>
12 #include <linux/spinlock.h>
13 #include <linux/proc_fs.h>
14 #include <linux/seq_file.h>
15 #include <linux/slab.h>
16 #include <linux/kmod.h>
17 #include <linux/kobj_map.h>
18 #include <linux/mutex.h>
19 #include <linux/idr.h>
20 #include <linux/log2.h>
21 
22 #include "blk.h"
23 
24 static DEFINE_MUTEX(block_class_lock);
25 struct kobject *block_depr;
26 
27 /* for extended dynamic devt allocation, currently only one major is used */
28 #define MAX_EXT_DEVT		(1 << MINORBITS)
29 
30 /* For extended devt allocation.  ext_devt_mutex prevents look up
31  * results from going away underneath its user.
32  */
33 static DEFINE_MUTEX(ext_devt_mutex);
34 static DEFINE_IDR(ext_devt_idr);
35 
36 static struct device_type disk_type;
37 
38 static void disk_add_events(struct gendisk *disk);
39 static void disk_del_events(struct gendisk *disk);
40 static void disk_release_events(struct gendisk *disk);
41 
42 /**
43  * disk_get_part - get partition
44  * @disk: disk to look partition from
45  * @partno: partition number
46  *
47  * Look for partition @partno from @disk.  If found, increment
48  * reference count and return it.
49  *
50  * CONTEXT:
51  * Don't care.
52  *
53  * RETURNS:
54  * Pointer to the found partition on success, NULL if not found.
55  */
56 struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
57 {
58 	struct hd_struct *part = NULL;
59 	struct disk_part_tbl *ptbl;
60 
61 	if (unlikely(partno < 0))
62 		return NULL;
63 
64 	rcu_read_lock();
65 
66 	ptbl = rcu_dereference(disk->part_tbl);
67 	if (likely(partno < ptbl->len)) {
68 		part = rcu_dereference(ptbl->part[partno]);
69 		if (part)
70 			get_device(part_to_dev(part));
71 	}
72 
73 	rcu_read_unlock();
74 
75 	return part;
76 }
77 EXPORT_SYMBOL_GPL(disk_get_part);
78 
79 /**
80  * disk_part_iter_init - initialize partition iterator
81  * @piter: iterator to initialize
82  * @disk: disk to iterate over
83  * @flags: DISK_PITER_* flags
84  *
85  * Initialize @piter so that it iterates over partitions of @disk.
86  *
87  * CONTEXT:
88  * Don't care.
89  */
90 void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
91 			  unsigned int flags)
92 {
93 	struct disk_part_tbl *ptbl;
94 
95 	rcu_read_lock();
96 	ptbl = rcu_dereference(disk->part_tbl);
97 
98 	piter->disk = disk;
99 	piter->part = NULL;
100 
101 	if (flags & DISK_PITER_REVERSE)
102 		piter->idx = ptbl->len - 1;
103 	else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
104 		piter->idx = 0;
105 	else
106 		piter->idx = 1;
107 
108 	piter->flags = flags;
109 
110 	rcu_read_unlock();
111 }
112 EXPORT_SYMBOL_GPL(disk_part_iter_init);
113 
114 /**
115  * disk_part_iter_next - proceed iterator to the next partition and return it
116  * @piter: iterator of interest
117  *
118  * Proceed @piter to the next partition and return it.
119  *
120  * CONTEXT:
121  * Don't care.
122  */
123 struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
124 {
125 	struct disk_part_tbl *ptbl;
126 	int inc, end;
127 
128 	/* put the last partition */
129 	disk_put_part(piter->part);
130 	piter->part = NULL;
131 
132 	/* get part_tbl */
133 	rcu_read_lock();
134 	ptbl = rcu_dereference(piter->disk->part_tbl);
135 
136 	/* determine iteration parameters */
137 	if (piter->flags & DISK_PITER_REVERSE) {
138 		inc = -1;
139 		if (piter->flags & (DISK_PITER_INCL_PART0 |
140 				    DISK_PITER_INCL_EMPTY_PART0))
141 			end = -1;
142 		else
143 			end = 0;
144 	} else {
145 		inc = 1;
146 		end = ptbl->len;
147 	}
148 
149 	/* iterate to the next partition */
150 	for (; piter->idx != end; piter->idx += inc) {
151 		struct hd_struct *part;
152 
153 		part = rcu_dereference(ptbl->part[piter->idx]);
154 		if (!part)
155 			continue;
156 		if (!part->nr_sects &&
157 		    !(piter->flags & DISK_PITER_INCL_EMPTY) &&
158 		    !(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
159 		      piter->idx == 0))
160 			continue;
161 
162 		get_device(part_to_dev(part));
163 		piter->part = part;
164 		piter->idx += inc;
165 		break;
166 	}
167 
168 	rcu_read_unlock();
169 
170 	return piter->part;
171 }
172 EXPORT_SYMBOL_GPL(disk_part_iter_next);
173 
174 /**
175  * disk_part_iter_exit - finish up partition iteration
176  * @piter: iter of interest
177  *
178  * Called when iteration is over.  Cleans up @piter.
179  *
180  * CONTEXT:
181  * Don't care.
182  */
183 void disk_part_iter_exit(struct disk_part_iter *piter)
184 {
185 	disk_put_part(piter->part);
186 	piter->part = NULL;
187 }
188 EXPORT_SYMBOL_GPL(disk_part_iter_exit);
189 
190 static inline int sector_in_part(struct hd_struct *part, sector_t sector)
191 {
192 	return part->start_sect <= sector &&
193 		sector < part->start_sect + part->nr_sects;
194 }
195 
196 /**
197  * disk_map_sector_rcu - map sector to partition
198  * @disk: gendisk of interest
199  * @sector: sector to map
200  *
201  * Find out which partition @sector maps to on @disk.  This is
202  * primarily used for stats accounting.
203  *
204  * CONTEXT:
205  * RCU read locked.  The returned partition pointer is valid only
206  * while preemption is disabled.
207  *
208  * RETURNS:
209  * Found partition on success, part0 is returned if no partition matches
210  */
211 struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
212 {
213 	struct disk_part_tbl *ptbl;
214 	struct hd_struct *part;
215 	int i;
216 
217 	ptbl = rcu_dereference(disk->part_tbl);
218 
219 	part = rcu_dereference(ptbl->last_lookup);
220 	if (part && sector_in_part(part, sector))
221 		return part;
222 
223 	for (i = 1; i < ptbl->len; i++) {
224 		part = rcu_dereference(ptbl->part[i]);
225 
226 		if (part && sector_in_part(part, sector)) {
227 			rcu_assign_pointer(ptbl->last_lookup, part);
228 			return part;
229 		}
230 	}
231 	return &disk->part0;
232 }
233 EXPORT_SYMBOL_GPL(disk_map_sector_rcu);
234 
235 /*
236  * Can be deleted altogether. Later.
237  *
238  */
239 static struct blk_major_name {
240 	struct blk_major_name *next;
241 	int major;
242 	char name[16];
243 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
244 
245 /* index in the above - for now: assume no multimajor ranges */
246 static inline int major_to_index(unsigned major)
247 {
248 	return major % BLKDEV_MAJOR_HASH_SIZE;
249 }
250 
251 #ifdef CONFIG_PROC_FS
252 void blkdev_show(struct seq_file *seqf, off_t offset)
253 {
254 	struct blk_major_name *dp;
255 
256 	if (offset < BLKDEV_MAJOR_HASH_SIZE) {
257 		mutex_lock(&block_class_lock);
258 		for (dp = major_names[offset]; dp; dp = dp->next)
259 			seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
260 		mutex_unlock(&block_class_lock);
261 	}
262 }
263 #endif /* CONFIG_PROC_FS */
264 
265 /**
266  * register_blkdev - register a new block device
267  *
268  * @major: the requested major device number [1..255]. If @major=0, try to
269  *         allocate any unused major number.
270  * @name: the name of the new block device as a zero terminated string
271  *
272  * The @name must be unique within the system.
273  *
274  * The return value depends on the @major input parameter.
275  *  - if a major device number was requested in range [1..255] then the
276  *    function returns zero on success, or a negative error code
277  *  - if any unused major number was requested with @major=0 parameter
278  *    then the return value is the allocated major number in range
279  *    [1..255] or a negative error code otherwise
280  */
281 int register_blkdev(unsigned int major, const char *name)
282 {
283 	struct blk_major_name **n, *p;
284 	int index, ret = 0;
285 
286 	mutex_lock(&block_class_lock);
287 
288 	/* temporary */
289 	if (major == 0) {
290 		for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
291 			if (major_names[index] == NULL)
292 				break;
293 		}
294 
295 		if (index == 0) {
296 			printk("register_blkdev: failed to get major for %s\n",
297 			       name);
298 			ret = -EBUSY;
299 			goto out;
300 		}
301 		major = index;
302 		ret = major;
303 	}
304 
305 	p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
306 	if (p == NULL) {
307 		ret = -ENOMEM;
308 		goto out;
309 	}
310 
311 	p->major = major;
312 	strlcpy(p->name, name, sizeof(p->name));
313 	p->next = NULL;
314 	index = major_to_index(major);
315 
316 	for (n = &major_names[index]; *n; n = &(*n)->next) {
317 		if ((*n)->major == major)
318 			break;
319 	}
320 	if (!*n)
321 		*n = p;
322 	else
323 		ret = -EBUSY;
324 
325 	if (ret < 0) {
326 		printk("register_blkdev: cannot get major %d for %s\n",
327 		       major, name);
328 		kfree(p);
329 	}
330 out:
331 	mutex_unlock(&block_class_lock);
332 	return ret;
333 }
334 
335 EXPORT_SYMBOL(register_blkdev);
336 
337 void unregister_blkdev(unsigned int major, const char *name)
338 {
339 	struct blk_major_name **n;
340 	struct blk_major_name *p = NULL;
341 	int index = major_to_index(major);
342 
343 	mutex_lock(&block_class_lock);
344 	for (n = &major_names[index]; *n; n = &(*n)->next)
345 		if ((*n)->major == major)
346 			break;
347 	if (!*n || strcmp((*n)->name, name)) {
348 		WARN_ON(1);
349 	} else {
350 		p = *n;
351 		*n = p->next;
352 	}
353 	mutex_unlock(&block_class_lock);
354 	kfree(p);
355 }
356 
357 EXPORT_SYMBOL(unregister_blkdev);
358 
359 static struct kobj_map *bdev_map;
360 
361 /**
362  * blk_mangle_minor - scatter minor numbers apart
363  * @minor: minor number to mangle
364  *
365  * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
366  * is enabled.  Mangling twice gives the original value.
367  *
368  * RETURNS:
369  * Mangled value.
370  *
371  * CONTEXT:
372  * Don't care.
373  */
374 static int blk_mangle_minor(int minor)
375 {
376 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
377 	int i;
378 
379 	for (i = 0; i < MINORBITS / 2; i++) {
380 		int low = minor & (1 << i);
381 		int high = minor & (1 << (MINORBITS - 1 - i));
382 		int distance = MINORBITS - 1 - 2 * i;
383 
384 		minor ^= low | high;	/* clear both bits */
385 		low <<= distance;	/* swap the positions */
386 		high >>= distance;
387 		minor |= low | high;	/* and set */
388 	}
389 #endif
390 	return minor;
391 }
392 
393 /**
394  * blk_alloc_devt - allocate a dev_t for a partition
395  * @part: partition to allocate dev_t for
396  * @devt: out parameter for resulting dev_t
397  *
398  * Allocate a dev_t for block device.
399  *
400  * RETURNS:
401  * 0 on success, allocated dev_t is returned in *@devt.  -errno on
402  * failure.
403  *
404  * CONTEXT:
405  * Might sleep.
406  */
407 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
408 {
409 	struct gendisk *disk = part_to_disk(part);
410 	int idx, rc;
411 
412 	/* in consecutive minor range? */
413 	if (part->partno < disk->minors) {
414 		*devt = MKDEV(disk->major, disk->first_minor + part->partno);
415 		return 0;
416 	}
417 
418 	/* allocate ext devt */
419 	do {
420 		if (!idr_pre_get(&ext_devt_idr, GFP_KERNEL))
421 			return -ENOMEM;
422 		rc = idr_get_new(&ext_devt_idr, part, &idx);
423 	} while (rc == -EAGAIN);
424 
425 	if (rc)
426 		return rc;
427 
428 	if (idx > MAX_EXT_DEVT) {
429 		idr_remove(&ext_devt_idr, idx);
430 		return -EBUSY;
431 	}
432 
433 	*devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
434 	return 0;
435 }
436 
437 /**
438  * blk_free_devt - free a dev_t
439  * @devt: dev_t to free
440  *
441  * Free @devt which was allocated using blk_alloc_devt().
442  *
443  * CONTEXT:
444  * Might sleep.
445  */
446 void blk_free_devt(dev_t devt)
447 {
448 	might_sleep();
449 
450 	if (devt == MKDEV(0, 0))
451 		return;
452 
453 	if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
454 		mutex_lock(&ext_devt_mutex);
455 		idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
456 		mutex_unlock(&ext_devt_mutex);
457 	}
458 }
459 
460 static char *bdevt_str(dev_t devt, char *buf)
461 {
462 	if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
463 		char tbuf[BDEVT_SIZE];
464 		snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
465 		snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
466 	} else
467 		snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
468 
469 	return buf;
470 }
471 
472 /*
473  * Register device numbers dev..(dev+range-1)
474  * range must be nonzero
475  * The hash chain is sorted on range, so that subranges can override.
476  */
477 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
478 			 struct kobject *(*probe)(dev_t, int *, void *),
479 			 int (*lock)(dev_t, void *), void *data)
480 {
481 	kobj_map(bdev_map, devt, range, module, probe, lock, data);
482 }
483 
484 EXPORT_SYMBOL(blk_register_region);
485 
486 void blk_unregister_region(dev_t devt, unsigned long range)
487 {
488 	kobj_unmap(bdev_map, devt, range);
489 }
490 
491 EXPORT_SYMBOL(blk_unregister_region);
492 
493 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
494 {
495 	struct gendisk *p = data;
496 
497 	return &disk_to_dev(p)->kobj;
498 }
499 
500 static int exact_lock(dev_t devt, void *data)
501 {
502 	struct gendisk *p = data;
503 
504 	if (!get_disk(p))
505 		return -1;
506 	return 0;
507 }
508 
509 static void register_disk(struct gendisk *disk)
510 {
511 	struct device *ddev = disk_to_dev(disk);
512 	struct block_device *bdev;
513 	struct disk_part_iter piter;
514 	struct hd_struct *part;
515 	int err;
516 
517 	ddev->parent = disk->driverfs_dev;
518 
519 	dev_set_name(ddev, disk->disk_name);
520 
521 	/* delay uevents, until we scanned partition table */
522 	dev_set_uevent_suppress(ddev, 1);
523 
524 	if (device_add(ddev))
525 		return;
526 	if (!sysfs_deprecated) {
527 		err = sysfs_create_link(block_depr, &ddev->kobj,
528 					kobject_name(&ddev->kobj));
529 		if (err) {
530 			device_del(ddev);
531 			return;
532 		}
533 	}
534 	disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
535 	disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
536 
537 	/* No minors to use for partitions */
538 	if (!disk_part_scan_enabled(disk))
539 		goto exit;
540 
541 	/* No such device (e.g., media were just removed) */
542 	if (!get_capacity(disk))
543 		goto exit;
544 
545 	bdev = bdget_disk(disk, 0);
546 	if (!bdev)
547 		goto exit;
548 
549 	bdev->bd_invalidated = 1;
550 	err = blkdev_get(bdev, FMODE_READ, NULL);
551 	if (err < 0)
552 		goto exit;
553 	blkdev_put(bdev, FMODE_READ);
554 
555 exit:
556 	/* announce disk after possible partitions are created */
557 	dev_set_uevent_suppress(ddev, 0);
558 	kobject_uevent(&ddev->kobj, KOBJ_ADD);
559 
560 	/* announce possible partitions */
561 	disk_part_iter_init(&piter, disk, 0);
562 	while ((part = disk_part_iter_next(&piter)))
563 		kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
564 	disk_part_iter_exit(&piter);
565 }
566 
567 /**
568  * add_disk - add partitioning information to kernel list
569  * @disk: per-device partitioning information
570  *
571  * This function registers the partitioning information in @disk
572  * with the kernel.
573  *
574  * FIXME: error handling
575  */
576 void add_disk(struct gendisk *disk)
577 {
578 	struct backing_dev_info *bdi;
579 	dev_t devt;
580 	int retval;
581 
582 	/* minors == 0 indicates to use ext devt from part0 and should
583 	 * be accompanied with EXT_DEVT flag.  Make sure all
584 	 * parameters make sense.
585 	 */
586 	WARN_ON(disk->minors && !(disk->major || disk->first_minor));
587 	WARN_ON(!disk->minors && !(disk->flags & GENHD_FL_EXT_DEVT));
588 
589 	disk->flags |= GENHD_FL_UP;
590 
591 	retval = blk_alloc_devt(&disk->part0, &devt);
592 	if (retval) {
593 		WARN_ON(1);
594 		return;
595 	}
596 	disk_to_dev(disk)->devt = devt;
597 
598 	/* ->major and ->first_minor aren't supposed to be
599 	 * dereferenced from here on, but set them just in case.
600 	 */
601 	disk->major = MAJOR(devt);
602 	disk->first_minor = MINOR(devt);
603 
604 	/* Register BDI before referencing it from bdev */
605 	bdi = &disk->queue->backing_dev_info;
606 	bdi_register_dev(bdi, disk_devt(disk));
607 
608 	blk_register_region(disk_devt(disk), disk->minors, NULL,
609 			    exact_match, exact_lock, disk);
610 	register_disk(disk);
611 	blk_register_queue(disk);
612 
613 	/*
614 	 * Take an extra ref on queue which will be put on disk_release()
615 	 * so that it sticks around as long as @disk is there.
616 	 */
617 	WARN_ON_ONCE(!blk_get_queue(disk->queue));
618 
619 	retval = sysfs_create_link(&disk_to_dev(disk)->kobj, &bdi->dev->kobj,
620 				   "bdi");
621 	WARN_ON(retval);
622 
623 	disk_add_events(disk);
624 }
625 EXPORT_SYMBOL(add_disk);
626 
627 void del_gendisk(struct gendisk *disk)
628 {
629 	struct disk_part_iter piter;
630 	struct hd_struct *part;
631 
632 	disk_del_events(disk);
633 
634 	/* invalidate stuff */
635 	disk_part_iter_init(&piter, disk,
636 			     DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
637 	while ((part = disk_part_iter_next(&piter))) {
638 		invalidate_partition(disk, part->partno);
639 		delete_partition(disk, part->partno);
640 	}
641 	disk_part_iter_exit(&piter);
642 
643 	invalidate_partition(disk, 0);
644 	blk_free_devt(disk_to_dev(disk)->devt);
645 	set_capacity(disk, 0);
646 	disk->flags &= ~GENHD_FL_UP;
647 
648 	sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
649 	bdi_unregister(&disk->queue->backing_dev_info);
650 	blk_unregister_queue(disk);
651 	blk_unregister_region(disk_devt(disk), disk->minors);
652 
653 	part_stat_set_all(&disk->part0, 0);
654 	disk->part0.stamp = 0;
655 
656 	kobject_put(disk->part0.holder_dir);
657 	kobject_put(disk->slave_dir);
658 	disk->driverfs_dev = NULL;
659 	if (!sysfs_deprecated)
660 		sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
661 	device_del(disk_to_dev(disk));
662 }
663 EXPORT_SYMBOL(del_gendisk);
664 
665 /**
666  * get_gendisk - get partitioning information for a given device
667  * @devt: device to get partitioning information for
668  * @partno: returned partition index
669  *
670  * This function gets the structure containing partitioning
671  * information for the given device @devt.
672  */
673 struct gendisk *get_gendisk(dev_t devt, int *partno)
674 {
675 	struct gendisk *disk = NULL;
676 
677 	if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
678 		struct kobject *kobj;
679 
680 		kobj = kobj_lookup(bdev_map, devt, partno);
681 		if (kobj)
682 			disk = dev_to_disk(kobj_to_dev(kobj));
683 	} else {
684 		struct hd_struct *part;
685 
686 		mutex_lock(&ext_devt_mutex);
687 		part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
688 		if (part && get_disk(part_to_disk(part))) {
689 			*partno = part->partno;
690 			disk = part_to_disk(part);
691 		}
692 		mutex_unlock(&ext_devt_mutex);
693 	}
694 
695 	return disk;
696 }
697 EXPORT_SYMBOL(get_gendisk);
698 
699 /**
700  * bdget_disk - do bdget() by gendisk and partition number
701  * @disk: gendisk of interest
702  * @partno: partition number
703  *
704  * Find partition @partno from @disk, do bdget() on it.
705  *
706  * CONTEXT:
707  * Don't care.
708  *
709  * RETURNS:
710  * Resulting block_device on success, NULL on failure.
711  */
712 struct block_device *bdget_disk(struct gendisk *disk, int partno)
713 {
714 	struct hd_struct *part;
715 	struct block_device *bdev = NULL;
716 
717 	part = disk_get_part(disk, partno);
718 	if (part)
719 		bdev = bdget(part_devt(part));
720 	disk_put_part(part);
721 
722 	return bdev;
723 }
724 EXPORT_SYMBOL(bdget_disk);
725 
726 /*
727  * print a full list of all partitions - intended for places where the root
728  * filesystem can't be mounted and thus to give the victim some idea of what
729  * went wrong
730  */
731 void __init printk_all_partitions(void)
732 {
733 	struct class_dev_iter iter;
734 	struct device *dev;
735 
736 	class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
737 	while ((dev = class_dev_iter_next(&iter))) {
738 		struct gendisk *disk = dev_to_disk(dev);
739 		struct disk_part_iter piter;
740 		struct hd_struct *part;
741 		char name_buf[BDEVNAME_SIZE];
742 		char devt_buf[BDEVT_SIZE];
743 		u8 uuid[PARTITION_META_INFO_UUIDLTH * 2 + 1];
744 
745 		/*
746 		 * Don't show empty devices or things that have been
747 		 * suppressed
748 		 */
749 		if (get_capacity(disk) == 0 ||
750 		    (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
751 			continue;
752 
753 		/*
754 		 * Note, unlike /proc/partitions, I am showing the
755 		 * numbers in hex - the same format as the root=
756 		 * option takes.
757 		 */
758 		disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
759 		while ((part = disk_part_iter_next(&piter))) {
760 			bool is_part0 = part == &disk->part0;
761 
762 			uuid[0] = 0;
763 			if (part->info)
764 				part_unpack_uuid(part->info->uuid, uuid);
765 
766 			printk("%s%s %10llu %s %s", is_part0 ? "" : "  ",
767 			       bdevt_str(part_devt(part), devt_buf),
768 			       (unsigned long long)part->nr_sects >> 1,
769 			       disk_name(disk, part->partno, name_buf), uuid);
770 			if (is_part0) {
771 				if (disk->driverfs_dev != NULL &&
772 				    disk->driverfs_dev->driver != NULL)
773 					printk(" driver: %s\n",
774 					      disk->driverfs_dev->driver->name);
775 				else
776 					printk(" (driver?)\n");
777 			} else
778 				printk("\n");
779 		}
780 		disk_part_iter_exit(&piter);
781 	}
782 	class_dev_iter_exit(&iter);
783 }
784 
785 #ifdef CONFIG_PROC_FS
786 /* iterator */
787 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
788 {
789 	loff_t skip = *pos;
790 	struct class_dev_iter *iter;
791 	struct device *dev;
792 
793 	iter = kmalloc(sizeof(*iter), GFP_KERNEL);
794 	if (!iter)
795 		return ERR_PTR(-ENOMEM);
796 
797 	seqf->private = iter;
798 	class_dev_iter_init(iter, &block_class, NULL, &disk_type);
799 	do {
800 		dev = class_dev_iter_next(iter);
801 		if (!dev)
802 			return NULL;
803 	} while (skip--);
804 
805 	return dev_to_disk(dev);
806 }
807 
808 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
809 {
810 	struct device *dev;
811 
812 	(*pos)++;
813 	dev = class_dev_iter_next(seqf->private);
814 	if (dev)
815 		return dev_to_disk(dev);
816 
817 	return NULL;
818 }
819 
820 static void disk_seqf_stop(struct seq_file *seqf, void *v)
821 {
822 	struct class_dev_iter *iter = seqf->private;
823 
824 	/* stop is called even after start failed :-( */
825 	if (iter) {
826 		class_dev_iter_exit(iter);
827 		kfree(iter);
828 	}
829 }
830 
831 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
832 {
833 	static void *p;
834 
835 	p = disk_seqf_start(seqf, pos);
836 	if (!IS_ERR_OR_NULL(p) && !*pos)
837 		seq_puts(seqf, "major minor  #blocks  name\n\n");
838 	return p;
839 }
840 
841 static int show_partition(struct seq_file *seqf, void *v)
842 {
843 	struct gendisk *sgp = v;
844 	struct disk_part_iter piter;
845 	struct hd_struct *part;
846 	char buf[BDEVNAME_SIZE];
847 
848 	/* Don't show non-partitionable removeable devices or empty devices */
849 	if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
850 				   (sgp->flags & GENHD_FL_REMOVABLE)))
851 		return 0;
852 	if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
853 		return 0;
854 
855 	/* show the full disk and all non-0 size partitions of it */
856 	disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
857 	while ((part = disk_part_iter_next(&piter)))
858 		seq_printf(seqf, "%4d  %7d %10llu %s\n",
859 			   MAJOR(part_devt(part)), MINOR(part_devt(part)),
860 			   (unsigned long long)part->nr_sects >> 1,
861 			   disk_name(sgp, part->partno, buf));
862 	disk_part_iter_exit(&piter);
863 
864 	return 0;
865 }
866 
867 static const struct seq_operations partitions_op = {
868 	.start	= show_partition_start,
869 	.next	= disk_seqf_next,
870 	.stop	= disk_seqf_stop,
871 	.show	= show_partition
872 };
873 
874 static int partitions_open(struct inode *inode, struct file *file)
875 {
876 	return seq_open(file, &partitions_op);
877 }
878 
879 static const struct file_operations proc_partitions_operations = {
880 	.open		= partitions_open,
881 	.read		= seq_read,
882 	.llseek		= seq_lseek,
883 	.release	= seq_release,
884 };
885 #endif
886 
887 
888 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
889 {
890 	if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
891 		/* Make old-style 2.4 aliases work */
892 		request_module("block-major-%d", MAJOR(devt));
893 	return NULL;
894 }
895 
896 static int __init genhd_device_init(void)
897 {
898 	int error;
899 
900 	block_class.dev_kobj = sysfs_dev_block_kobj;
901 	error = class_register(&block_class);
902 	if (unlikely(error))
903 		return error;
904 	bdev_map = kobj_map_init(base_probe, &block_class_lock);
905 	blk_dev_init();
906 
907 	register_blkdev(BLOCK_EXT_MAJOR, "blkext");
908 
909 	/* create top-level block dir */
910 	if (!sysfs_deprecated)
911 		block_depr = kobject_create_and_add("block", NULL);
912 	return 0;
913 }
914 
915 subsys_initcall(genhd_device_init);
916 
917 static ssize_t disk_range_show(struct device *dev,
918 			       struct device_attribute *attr, char *buf)
919 {
920 	struct gendisk *disk = dev_to_disk(dev);
921 
922 	return sprintf(buf, "%d\n", disk->minors);
923 }
924 
925 static ssize_t disk_ext_range_show(struct device *dev,
926 				   struct device_attribute *attr, char *buf)
927 {
928 	struct gendisk *disk = dev_to_disk(dev);
929 
930 	return sprintf(buf, "%d\n", disk_max_parts(disk));
931 }
932 
933 static ssize_t disk_removable_show(struct device *dev,
934 				   struct device_attribute *attr, char *buf)
935 {
936 	struct gendisk *disk = dev_to_disk(dev);
937 
938 	return sprintf(buf, "%d\n",
939 		       (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
940 }
941 
942 static ssize_t disk_ro_show(struct device *dev,
943 				   struct device_attribute *attr, char *buf)
944 {
945 	struct gendisk *disk = dev_to_disk(dev);
946 
947 	return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
948 }
949 
950 static ssize_t disk_capability_show(struct device *dev,
951 				    struct device_attribute *attr, char *buf)
952 {
953 	struct gendisk *disk = dev_to_disk(dev);
954 
955 	return sprintf(buf, "%x\n", disk->flags);
956 }
957 
958 static ssize_t disk_alignment_offset_show(struct device *dev,
959 					  struct device_attribute *attr,
960 					  char *buf)
961 {
962 	struct gendisk *disk = dev_to_disk(dev);
963 
964 	return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
965 }
966 
967 static ssize_t disk_discard_alignment_show(struct device *dev,
968 					   struct device_attribute *attr,
969 					   char *buf)
970 {
971 	struct gendisk *disk = dev_to_disk(dev);
972 
973 	return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
974 }
975 
976 static DEVICE_ATTR(range, S_IRUGO, disk_range_show, NULL);
977 static DEVICE_ATTR(ext_range, S_IRUGO, disk_ext_range_show, NULL);
978 static DEVICE_ATTR(removable, S_IRUGO, disk_removable_show, NULL);
979 static DEVICE_ATTR(ro, S_IRUGO, disk_ro_show, NULL);
980 static DEVICE_ATTR(size, S_IRUGO, part_size_show, NULL);
981 static DEVICE_ATTR(alignment_offset, S_IRUGO, disk_alignment_offset_show, NULL);
982 static DEVICE_ATTR(discard_alignment, S_IRUGO, disk_discard_alignment_show,
983 		   NULL);
984 static DEVICE_ATTR(capability, S_IRUGO, disk_capability_show, NULL);
985 static DEVICE_ATTR(stat, S_IRUGO, part_stat_show, NULL);
986 static DEVICE_ATTR(inflight, S_IRUGO, part_inflight_show, NULL);
987 #ifdef CONFIG_FAIL_MAKE_REQUEST
988 static struct device_attribute dev_attr_fail =
989 	__ATTR(make-it-fail, S_IRUGO|S_IWUSR, part_fail_show, part_fail_store);
990 #endif
991 #ifdef CONFIG_FAIL_IO_TIMEOUT
992 static struct device_attribute dev_attr_fail_timeout =
993 	__ATTR(io-timeout-fail,  S_IRUGO|S_IWUSR, part_timeout_show,
994 		part_timeout_store);
995 #endif
996 
997 static struct attribute *disk_attrs[] = {
998 	&dev_attr_range.attr,
999 	&dev_attr_ext_range.attr,
1000 	&dev_attr_removable.attr,
1001 	&dev_attr_ro.attr,
1002 	&dev_attr_size.attr,
1003 	&dev_attr_alignment_offset.attr,
1004 	&dev_attr_discard_alignment.attr,
1005 	&dev_attr_capability.attr,
1006 	&dev_attr_stat.attr,
1007 	&dev_attr_inflight.attr,
1008 #ifdef CONFIG_FAIL_MAKE_REQUEST
1009 	&dev_attr_fail.attr,
1010 #endif
1011 #ifdef CONFIG_FAIL_IO_TIMEOUT
1012 	&dev_attr_fail_timeout.attr,
1013 #endif
1014 	NULL
1015 };
1016 
1017 static struct attribute_group disk_attr_group = {
1018 	.attrs = disk_attrs,
1019 };
1020 
1021 static const struct attribute_group *disk_attr_groups[] = {
1022 	&disk_attr_group,
1023 	NULL
1024 };
1025 
1026 /**
1027  * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1028  * @disk: disk to replace part_tbl for
1029  * @new_ptbl: new part_tbl to install
1030  *
1031  * Replace disk->part_tbl with @new_ptbl in RCU-safe way.  The
1032  * original ptbl is freed using RCU callback.
1033  *
1034  * LOCKING:
1035  * Matching bd_mutx locked.
1036  */
1037 static void disk_replace_part_tbl(struct gendisk *disk,
1038 				  struct disk_part_tbl *new_ptbl)
1039 {
1040 	struct disk_part_tbl *old_ptbl = disk->part_tbl;
1041 
1042 	rcu_assign_pointer(disk->part_tbl, new_ptbl);
1043 
1044 	if (old_ptbl) {
1045 		rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1046 		kfree_rcu(old_ptbl, rcu_head);
1047 	}
1048 }
1049 
1050 /**
1051  * disk_expand_part_tbl - expand disk->part_tbl
1052  * @disk: disk to expand part_tbl for
1053  * @partno: expand such that this partno can fit in
1054  *
1055  * Expand disk->part_tbl such that @partno can fit in.  disk->part_tbl
1056  * uses RCU to allow unlocked dereferencing for stats and other stuff.
1057  *
1058  * LOCKING:
1059  * Matching bd_mutex locked, might sleep.
1060  *
1061  * RETURNS:
1062  * 0 on success, -errno on failure.
1063  */
1064 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1065 {
1066 	struct disk_part_tbl *old_ptbl = disk->part_tbl;
1067 	struct disk_part_tbl *new_ptbl;
1068 	int len = old_ptbl ? old_ptbl->len : 0;
1069 	int target = partno + 1;
1070 	size_t size;
1071 	int i;
1072 
1073 	/* disk_max_parts() is zero during initialization, ignore if so */
1074 	if (disk_max_parts(disk) && target > disk_max_parts(disk))
1075 		return -EINVAL;
1076 
1077 	if (target <= len)
1078 		return 0;
1079 
1080 	size = sizeof(*new_ptbl) + target * sizeof(new_ptbl->part[0]);
1081 	new_ptbl = kzalloc_node(size, GFP_KERNEL, disk->node_id);
1082 	if (!new_ptbl)
1083 		return -ENOMEM;
1084 
1085 	new_ptbl->len = target;
1086 
1087 	for (i = 0; i < len; i++)
1088 		rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1089 
1090 	disk_replace_part_tbl(disk, new_ptbl);
1091 	return 0;
1092 }
1093 
1094 static void disk_release(struct device *dev)
1095 {
1096 	struct gendisk *disk = dev_to_disk(dev);
1097 
1098 	disk_release_events(disk);
1099 	kfree(disk->random);
1100 	disk_replace_part_tbl(disk, NULL);
1101 	free_part_stats(&disk->part0);
1102 	free_part_info(&disk->part0);
1103 	if (disk->queue)
1104 		blk_put_queue(disk->queue);
1105 	kfree(disk);
1106 }
1107 struct class block_class = {
1108 	.name		= "block",
1109 };
1110 
1111 static char *block_devnode(struct device *dev, umode_t *mode)
1112 {
1113 	struct gendisk *disk = dev_to_disk(dev);
1114 
1115 	if (disk->devnode)
1116 		return disk->devnode(disk, mode);
1117 	return NULL;
1118 }
1119 
1120 static struct device_type disk_type = {
1121 	.name		= "disk",
1122 	.groups		= disk_attr_groups,
1123 	.release	= disk_release,
1124 	.devnode	= block_devnode,
1125 };
1126 
1127 #ifdef CONFIG_PROC_FS
1128 /*
1129  * aggregate disk stat collector.  Uses the same stats that the sysfs
1130  * entries do, above, but makes them available through one seq_file.
1131  *
1132  * The output looks suspiciously like /proc/partitions with a bunch of
1133  * extra fields.
1134  */
1135 static int diskstats_show(struct seq_file *seqf, void *v)
1136 {
1137 	struct gendisk *gp = v;
1138 	struct disk_part_iter piter;
1139 	struct hd_struct *hd;
1140 	char buf[BDEVNAME_SIZE];
1141 	int cpu;
1142 
1143 	/*
1144 	if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1145 		seq_puts(seqf,	"major minor name"
1146 				"     rio rmerge rsect ruse wio wmerge "
1147 				"wsect wuse running use aveq"
1148 				"\n\n");
1149 	*/
1150 
1151 	disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1152 	while ((hd = disk_part_iter_next(&piter))) {
1153 		cpu = part_stat_lock();
1154 		part_round_stats(cpu, hd);
1155 		part_stat_unlock();
1156 		seq_printf(seqf, "%4d %7d %s %lu %lu %lu "
1157 			   "%u %lu %lu %lu %u %u %u %u\n",
1158 			   MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1159 			   disk_name(gp, hd->partno, buf),
1160 			   part_stat_read(hd, ios[READ]),
1161 			   part_stat_read(hd, merges[READ]),
1162 			   part_stat_read(hd, sectors[READ]),
1163 			   jiffies_to_msecs(part_stat_read(hd, ticks[READ])),
1164 			   part_stat_read(hd, ios[WRITE]),
1165 			   part_stat_read(hd, merges[WRITE]),
1166 			   part_stat_read(hd, sectors[WRITE]),
1167 			   jiffies_to_msecs(part_stat_read(hd, ticks[WRITE])),
1168 			   part_in_flight(hd),
1169 			   jiffies_to_msecs(part_stat_read(hd, io_ticks)),
1170 			   jiffies_to_msecs(part_stat_read(hd, time_in_queue))
1171 			);
1172 	}
1173 	disk_part_iter_exit(&piter);
1174 
1175 	return 0;
1176 }
1177 
1178 static const struct seq_operations diskstats_op = {
1179 	.start	= disk_seqf_start,
1180 	.next	= disk_seqf_next,
1181 	.stop	= disk_seqf_stop,
1182 	.show	= diskstats_show
1183 };
1184 
1185 static int diskstats_open(struct inode *inode, struct file *file)
1186 {
1187 	return seq_open(file, &diskstats_op);
1188 }
1189 
1190 static const struct file_operations proc_diskstats_operations = {
1191 	.open		= diskstats_open,
1192 	.read		= seq_read,
1193 	.llseek		= seq_lseek,
1194 	.release	= seq_release,
1195 };
1196 
1197 static int __init proc_genhd_init(void)
1198 {
1199 	proc_create("diskstats", 0, NULL, &proc_diskstats_operations);
1200 	proc_create("partitions", 0, NULL, &proc_partitions_operations);
1201 	return 0;
1202 }
1203 module_init(proc_genhd_init);
1204 #endif /* CONFIG_PROC_FS */
1205 
1206 dev_t blk_lookup_devt(const char *name, int partno)
1207 {
1208 	dev_t devt = MKDEV(0, 0);
1209 	struct class_dev_iter iter;
1210 	struct device *dev;
1211 
1212 	class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1213 	while ((dev = class_dev_iter_next(&iter))) {
1214 		struct gendisk *disk = dev_to_disk(dev);
1215 		struct hd_struct *part;
1216 
1217 		if (strcmp(dev_name(dev), name))
1218 			continue;
1219 
1220 		if (partno < disk->minors) {
1221 			/* We need to return the right devno, even
1222 			 * if the partition doesn't exist yet.
1223 			 */
1224 			devt = MKDEV(MAJOR(dev->devt),
1225 				     MINOR(dev->devt) + partno);
1226 			break;
1227 		}
1228 		part = disk_get_part(disk, partno);
1229 		if (part) {
1230 			devt = part_devt(part);
1231 			disk_put_part(part);
1232 			break;
1233 		}
1234 		disk_put_part(part);
1235 	}
1236 	class_dev_iter_exit(&iter);
1237 	return devt;
1238 }
1239 EXPORT_SYMBOL(blk_lookup_devt);
1240 
1241 struct gendisk *alloc_disk(int minors)
1242 {
1243 	return alloc_disk_node(minors, -1);
1244 }
1245 EXPORT_SYMBOL(alloc_disk);
1246 
1247 struct gendisk *alloc_disk_node(int minors, int node_id)
1248 {
1249 	struct gendisk *disk;
1250 
1251 	disk = kmalloc_node(sizeof(struct gendisk),
1252 				GFP_KERNEL | __GFP_ZERO, node_id);
1253 	if (disk) {
1254 		if (!init_part_stats(&disk->part0)) {
1255 			kfree(disk);
1256 			return NULL;
1257 		}
1258 		disk->node_id = node_id;
1259 		if (disk_expand_part_tbl(disk, 0)) {
1260 			free_part_stats(&disk->part0);
1261 			kfree(disk);
1262 			return NULL;
1263 		}
1264 		disk->part_tbl->part[0] = &disk->part0;
1265 
1266 		hd_ref_init(&disk->part0);
1267 
1268 		disk->minors = minors;
1269 		rand_initialize_disk(disk);
1270 		disk_to_dev(disk)->class = &block_class;
1271 		disk_to_dev(disk)->type = &disk_type;
1272 		device_initialize(disk_to_dev(disk));
1273 	}
1274 	return disk;
1275 }
1276 EXPORT_SYMBOL(alloc_disk_node);
1277 
1278 struct kobject *get_disk(struct gendisk *disk)
1279 {
1280 	struct module *owner;
1281 	struct kobject *kobj;
1282 
1283 	if (!disk->fops)
1284 		return NULL;
1285 	owner = disk->fops->owner;
1286 	if (owner && !try_module_get(owner))
1287 		return NULL;
1288 	kobj = kobject_get(&disk_to_dev(disk)->kobj);
1289 	if (kobj == NULL) {
1290 		module_put(owner);
1291 		return NULL;
1292 	}
1293 	return kobj;
1294 
1295 }
1296 
1297 EXPORT_SYMBOL(get_disk);
1298 
1299 void put_disk(struct gendisk *disk)
1300 {
1301 	if (disk)
1302 		kobject_put(&disk_to_dev(disk)->kobj);
1303 }
1304 
1305 EXPORT_SYMBOL(put_disk);
1306 
1307 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1308 {
1309 	char event[] = "DISK_RO=1";
1310 	char *envp[] = { event, NULL };
1311 
1312 	if (!ro)
1313 		event[8] = '0';
1314 	kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1315 }
1316 
1317 void set_device_ro(struct block_device *bdev, int flag)
1318 {
1319 	bdev->bd_part->policy = flag;
1320 }
1321 
1322 EXPORT_SYMBOL(set_device_ro);
1323 
1324 void set_disk_ro(struct gendisk *disk, int flag)
1325 {
1326 	struct disk_part_iter piter;
1327 	struct hd_struct *part;
1328 
1329 	if (disk->part0.policy != flag) {
1330 		set_disk_ro_uevent(disk, flag);
1331 		disk->part0.policy = flag;
1332 	}
1333 
1334 	disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1335 	while ((part = disk_part_iter_next(&piter)))
1336 		part->policy = flag;
1337 	disk_part_iter_exit(&piter);
1338 }
1339 
1340 EXPORT_SYMBOL(set_disk_ro);
1341 
1342 int bdev_read_only(struct block_device *bdev)
1343 {
1344 	if (!bdev)
1345 		return 0;
1346 	return bdev->bd_part->policy;
1347 }
1348 
1349 EXPORT_SYMBOL(bdev_read_only);
1350 
1351 int invalidate_partition(struct gendisk *disk, int partno)
1352 {
1353 	int res = 0;
1354 	struct block_device *bdev = bdget_disk(disk, partno);
1355 	if (bdev) {
1356 		fsync_bdev(bdev);
1357 		res = __invalidate_device(bdev, true);
1358 		bdput(bdev);
1359 	}
1360 	return res;
1361 }
1362 
1363 EXPORT_SYMBOL(invalidate_partition);
1364 
1365 /*
1366  * Disk events - monitor disk events like media change and eject request.
1367  */
1368 struct disk_events {
1369 	struct list_head	node;		/* all disk_event's */
1370 	struct gendisk		*disk;		/* the associated disk */
1371 	spinlock_t		lock;
1372 
1373 	struct mutex		block_mutex;	/* protects blocking */
1374 	int			block;		/* event blocking depth */
1375 	unsigned int		pending;	/* events already sent out */
1376 	unsigned int		clearing;	/* events being cleared */
1377 
1378 	long			poll_msecs;	/* interval, -1 for default */
1379 	struct delayed_work	dwork;
1380 };
1381 
1382 static const char *disk_events_strs[] = {
1383 	[ilog2(DISK_EVENT_MEDIA_CHANGE)]	= "media_change",
1384 	[ilog2(DISK_EVENT_EJECT_REQUEST)]	= "eject_request",
1385 };
1386 
1387 static char *disk_uevents[] = {
1388 	[ilog2(DISK_EVENT_MEDIA_CHANGE)]	= "DISK_MEDIA_CHANGE=1",
1389 	[ilog2(DISK_EVENT_EJECT_REQUEST)]	= "DISK_EJECT_REQUEST=1",
1390 };
1391 
1392 /* list of all disk_events */
1393 static DEFINE_MUTEX(disk_events_mutex);
1394 static LIST_HEAD(disk_events);
1395 
1396 /* disable in-kernel polling by default */
1397 static unsigned long disk_events_dfl_poll_msecs	= 0;
1398 
1399 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
1400 {
1401 	struct disk_events *ev = disk->ev;
1402 	long intv_msecs = 0;
1403 
1404 	/*
1405 	 * If device-specific poll interval is set, always use it.  If
1406 	 * the default is being used, poll iff there are events which
1407 	 * can't be monitored asynchronously.
1408 	 */
1409 	if (ev->poll_msecs >= 0)
1410 		intv_msecs = ev->poll_msecs;
1411 	else if (disk->events & ~disk->async_events)
1412 		intv_msecs = disk_events_dfl_poll_msecs;
1413 
1414 	return msecs_to_jiffies(intv_msecs);
1415 }
1416 
1417 /**
1418  * disk_block_events - block and flush disk event checking
1419  * @disk: disk to block events for
1420  *
1421  * On return from this function, it is guaranteed that event checking
1422  * isn't in progress and won't happen until unblocked by
1423  * disk_unblock_events().  Events blocking is counted and the actual
1424  * unblocking happens after the matching number of unblocks are done.
1425  *
1426  * Note that this intentionally does not block event checking from
1427  * disk_clear_events().
1428  *
1429  * CONTEXT:
1430  * Might sleep.
1431  */
1432 void disk_block_events(struct gendisk *disk)
1433 {
1434 	struct disk_events *ev = disk->ev;
1435 	unsigned long flags;
1436 	bool cancel;
1437 
1438 	if (!ev)
1439 		return;
1440 
1441 	/*
1442 	 * Outer mutex ensures that the first blocker completes canceling
1443 	 * the event work before further blockers are allowed to finish.
1444 	 */
1445 	mutex_lock(&ev->block_mutex);
1446 
1447 	spin_lock_irqsave(&ev->lock, flags);
1448 	cancel = !ev->block++;
1449 	spin_unlock_irqrestore(&ev->lock, flags);
1450 
1451 	if (cancel)
1452 		cancel_delayed_work_sync(&disk->ev->dwork);
1453 
1454 	mutex_unlock(&ev->block_mutex);
1455 }
1456 
1457 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
1458 {
1459 	struct disk_events *ev = disk->ev;
1460 	unsigned long intv;
1461 	unsigned long flags;
1462 
1463 	spin_lock_irqsave(&ev->lock, flags);
1464 
1465 	if (WARN_ON_ONCE(ev->block <= 0))
1466 		goto out_unlock;
1467 
1468 	if (--ev->block)
1469 		goto out_unlock;
1470 
1471 	/*
1472 	 * Not exactly a latency critical operation, set poll timer
1473 	 * slack to 25% and kick event check.
1474 	 */
1475 	intv = disk_events_poll_jiffies(disk);
1476 	set_timer_slack(&ev->dwork.timer, intv / 4);
1477 	if (check_now)
1478 		queue_delayed_work(system_nrt_wq, &ev->dwork, 0);
1479 	else if (intv)
1480 		queue_delayed_work(system_nrt_wq, &ev->dwork, intv);
1481 out_unlock:
1482 	spin_unlock_irqrestore(&ev->lock, flags);
1483 }
1484 
1485 /**
1486  * disk_unblock_events - unblock disk event checking
1487  * @disk: disk to unblock events for
1488  *
1489  * Undo disk_block_events().  When the block count reaches zero, it
1490  * starts events polling if configured.
1491  *
1492  * CONTEXT:
1493  * Don't care.  Safe to call from irq context.
1494  */
1495 void disk_unblock_events(struct gendisk *disk)
1496 {
1497 	if (disk->ev)
1498 		__disk_unblock_events(disk, false);
1499 }
1500 
1501 /**
1502  * disk_flush_events - schedule immediate event checking and flushing
1503  * @disk: disk to check and flush events for
1504  * @mask: events to flush
1505  *
1506  * Schedule immediate event checking on @disk if not blocked.  Events in
1507  * @mask are scheduled to be cleared from the driver.  Note that this
1508  * doesn't clear the events from @disk->ev.
1509  *
1510  * CONTEXT:
1511  * If @mask is non-zero must be called with bdev->bd_mutex held.
1512  */
1513 void disk_flush_events(struct gendisk *disk, unsigned int mask)
1514 {
1515 	struct disk_events *ev = disk->ev;
1516 
1517 	if (!ev)
1518 		return;
1519 
1520 	spin_lock_irq(&ev->lock);
1521 	ev->clearing |= mask;
1522 	if (!ev->block) {
1523 		cancel_delayed_work(&ev->dwork);
1524 		queue_delayed_work(system_nrt_wq, &ev->dwork, 0);
1525 	}
1526 	spin_unlock_irq(&ev->lock);
1527 }
1528 
1529 /**
1530  * disk_clear_events - synchronously check, clear and return pending events
1531  * @disk: disk to fetch and clear events from
1532  * @mask: mask of events to be fetched and clearted
1533  *
1534  * Disk events are synchronously checked and pending events in @mask
1535  * are cleared and returned.  This ignores the block count.
1536  *
1537  * CONTEXT:
1538  * Might sleep.
1539  */
1540 unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
1541 {
1542 	const struct block_device_operations *bdops = disk->fops;
1543 	struct disk_events *ev = disk->ev;
1544 	unsigned int pending;
1545 
1546 	if (!ev) {
1547 		/* for drivers still using the old ->media_changed method */
1548 		if ((mask & DISK_EVENT_MEDIA_CHANGE) &&
1549 		    bdops->media_changed && bdops->media_changed(disk))
1550 			return DISK_EVENT_MEDIA_CHANGE;
1551 		return 0;
1552 	}
1553 
1554 	/* tell the workfn about the events being cleared */
1555 	spin_lock_irq(&ev->lock);
1556 	ev->clearing |= mask;
1557 	spin_unlock_irq(&ev->lock);
1558 
1559 	/* uncondtionally schedule event check and wait for it to finish */
1560 	disk_block_events(disk);
1561 	queue_delayed_work(system_nrt_wq, &ev->dwork, 0);
1562 	flush_delayed_work(&ev->dwork);
1563 	__disk_unblock_events(disk, false);
1564 
1565 	/* then, fetch and clear pending events */
1566 	spin_lock_irq(&ev->lock);
1567 	WARN_ON_ONCE(ev->clearing & mask);	/* cleared by workfn */
1568 	pending = ev->pending & mask;
1569 	ev->pending &= ~mask;
1570 	spin_unlock_irq(&ev->lock);
1571 
1572 	return pending;
1573 }
1574 
1575 static void disk_events_workfn(struct work_struct *work)
1576 {
1577 	struct delayed_work *dwork = to_delayed_work(work);
1578 	struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
1579 	struct gendisk *disk = ev->disk;
1580 	char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
1581 	unsigned int clearing = ev->clearing;
1582 	unsigned int events;
1583 	unsigned long intv;
1584 	int nr_events = 0, i;
1585 
1586 	/* check events */
1587 	events = disk->fops->check_events(disk, clearing);
1588 
1589 	/* accumulate pending events and schedule next poll if necessary */
1590 	spin_lock_irq(&ev->lock);
1591 
1592 	events &= ~ev->pending;
1593 	ev->pending |= events;
1594 	ev->clearing &= ~clearing;
1595 
1596 	intv = disk_events_poll_jiffies(disk);
1597 	if (!ev->block && intv)
1598 		queue_delayed_work(system_nrt_wq, &ev->dwork, intv);
1599 
1600 	spin_unlock_irq(&ev->lock);
1601 
1602 	/*
1603 	 * Tell userland about new events.  Only the events listed in
1604 	 * @disk->events are reported.  Unlisted events are processed the
1605 	 * same internally but never get reported to userland.
1606 	 */
1607 	for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
1608 		if (events & disk->events & (1 << i))
1609 			envp[nr_events++] = disk_uevents[i];
1610 
1611 	if (nr_events)
1612 		kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
1613 }
1614 
1615 /*
1616  * A disk events enabled device has the following sysfs nodes under
1617  * its /sys/block/X/ directory.
1618  *
1619  * events		: list of all supported events
1620  * events_async		: list of events which can be detected w/o polling
1621  * events_poll_msecs	: polling interval, 0: disable, -1: system default
1622  */
1623 static ssize_t __disk_events_show(unsigned int events, char *buf)
1624 {
1625 	const char *delim = "";
1626 	ssize_t pos = 0;
1627 	int i;
1628 
1629 	for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
1630 		if (events & (1 << i)) {
1631 			pos += sprintf(buf + pos, "%s%s",
1632 				       delim, disk_events_strs[i]);
1633 			delim = " ";
1634 		}
1635 	if (pos)
1636 		pos += sprintf(buf + pos, "\n");
1637 	return pos;
1638 }
1639 
1640 static ssize_t disk_events_show(struct device *dev,
1641 				struct device_attribute *attr, char *buf)
1642 {
1643 	struct gendisk *disk = dev_to_disk(dev);
1644 
1645 	return __disk_events_show(disk->events, buf);
1646 }
1647 
1648 static ssize_t disk_events_async_show(struct device *dev,
1649 				      struct device_attribute *attr, char *buf)
1650 {
1651 	struct gendisk *disk = dev_to_disk(dev);
1652 
1653 	return __disk_events_show(disk->async_events, buf);
1654 }
1655 
1656 static ssize_t disk_events_poll_msecs_show(struct device *dev,
1657 					   struct device_attribute *attr,
1658 					   char *buf)
1659 {
1660 	struct gendisk *disk = dev_to_disk(dev);
1661 
1662 	return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
1663 }
1664 
1665 static ssize_t disk_events_poll_msecs_store(struct device *dev,
1666 					    struct device_attribute *attr,
1667 					    const char *buf, size_t count)
1668 {
1669 	struct gendisk *disk = dev_to_disk(dev);
1670 	long intv;
1671 
1672 	if (!count || !sscanf(buf, "%ld", &intv))
1673 		return -EINVAL;
1674 
1675 	if (intv < 0 && intv != -1)
1676 		return -EINVAL;
1677 
1678 	disk_block_events(disk);
1679 	disk->ev->poll_msecs = intv;
1680 	__disk_unblock_events(disk, true);
1681 
1682 	return count;
1683 }
1684 
1685 static const DEVICE_ATTR(events, S_IRUGO, disk_events_show, NULL);
1686 static const DEVICE_ATTR(events_async, S_IRUGO, disk_events_async_show, NULL);
1687 static const DEVICE_ATTR(events_poll_msecs, S_IRUGO|S_IWUSR,
1688 			 disk_events_poll_msecs_show,
1689 			 disk_events_poll_msecs_store);
1690 
1691 static const struct attribute *disk_events_attrs[] = {
1692 	&dev_attr_events.attr,
1693 	&dev_attr_events_async.attr,
1694 	&dev_attr_events_poll_msecs.attr,
1695 	NULL,
1696 };
1697 
1698 /*
1699  * The default polling interval can be specified by the kernel
1700  * parameter block.events_dfl_poll_msecs which defaults to 0
1701  * (disable).  This can also be modified runtime by writing to
1702  * /sys/module/block/events_dfl_poll_msecs.
1703  */
1704 static int disk_events_set_dfl_poll_msecs(const char *val,
1705 					  const struct kernel_param *kp)
1706 {
1707 	struct disk_events *ev;
1708 	int ret;
1709 
1710 	ret = param_set_ulong(val, kp);
1711 	if (ret < 0)
1712 		return ret;
1713 
1714 	mutex_lock(&disk_events_mutex);
1715 
1716 	list_for_each_entry(ev, &disk_events, node)
1717 		disk_flush_events(ev->disk, 0);
1718 
1719 	mutex_unlock(&disk_events_mutex);
1720 
1721 	return 0;
1722 }
1723 
1724 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
1725 	.set	= disk_events_set_dfl_poll_msecs,
1726 	.get	= param_get_ulong,
1727 };
1728 
1729 #undef MODULE_PARAM_PREFIX
1730 #define MODULE_PARAM_PREFIX	"block."
1731 
1732 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
1733 		&disk_events_dfl_poll_msecs, 0644);
1734 
1735 /*
1736  * disk_{add|del|release}_events - initialize and destroy disk_events.
1737  */
1738 static void disk_add_events(struct gendisk *disk)
1739 {
1740 	struct disk_events *ev;
1741 
1742 	if (!disk->fops->check_events)
1743 		return;
1744 
1745 	ev = kzalloc(sizeof(*ev), GFP_KERNEL);
1746 	if (!ev) {
1747 		pr_warn("%s: failed to initialize events\n", disk->disk_name);
1748 		return;
1749 	}
1750 
1751 	if (sysfs_create_files(&disk_to_dev(disk)->kobj,
1752 			       disk_events_attrs) < 0) {
1753 		pr_warn("%s: failed to create sysfs files for events\n",
1754 			disk->disk_name);
1755 		kfree(ev);
1756 		return;
1757 	}
1758 
1759 	disk->ev = ev;
1760 
1761 	INIT_LIST_HEAD(&ev->node);
1762 	ev->disk = disk;
1763 	spin_lock_init(&ev->lock);
1764 	mutex_init(&ev->block_mutex);
1765 	ev->block = 1;
1766 	ev->poll_msecs = -1;
1767 	INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
1768 
1769 	mutex_lock(&disk_events_mutex);
1770 	list_add_tail(&ev->node, &disk_events);
1771 	mutex_unlock(&disk_events_mutex);
1772 
1773 	/*
1774 	 * Block count is initialized to 1 and the following initial
1775 	 * unblock kicks it into action.
1776 	 */
1777 	__disk_unblock_events(disk, true);
1778 }
1779 
1780 static void disk_del_events(struct gendisk *disk)
1781 {
1782 	if (!disk->ev)
1783 		return;
1784 
1785 	disk_block_events(disk);
1786 
1787 	mutex_lock(&disk_events_mutex);
1788 	list_del_init(&disk->ev->node);
1789 	mutex_unlock(&disk_events_mutex);
1790 
1791 	sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
1792 }
1793 
1794 static void disk_release_events(struct gendisk *disk)
1795 {
1796 	/* the block count should be 1 from disk_del_events() */
1797 	WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
1798 	kfree(disk->ev);
1799 }
1800