xref: /linux/block/genhd.c (revision 8c22eb3a77373c616f141b56f44ef225ee15c96b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  gendisk handling
4  */
5 
6 #include <linux/module.h>
7 #include <linux/ctype.h>
8 #include <linux/fs.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/kobj_map.h>
21 #include <linux/mutex.h>
22 #include <linux/idr.h>
23 #include <linux/log2.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/badblocks.h>
26 
27 #include "blk.h"
28 
29 static DEFINE_MUTEX(block_class_lock);
30 static struct kobject *block_depr;
31 
32 /* for extended dynamic devt allocation, currently only one major is used */
33 #define NR_EXT_DEVT		(1 << MINORBITS)
34 
35 /* For extended devt allocation.  ext_devt_lock prevents look up
36  * results from going away underneath its user.
37  */
38 static DEFINE_SPINLOCK(ext_devt_lock);
39 static DEFINE_IDR(ext_devt_idr);
40 
41 static const struct device_type disk_type;
42 
43 static void disk_check_events(struct disk_events *ev,
44 			      unsigned int *clearing_ptr);
45 static void disk_alloc_events(struct gendisk *disk);
46 static void disk_add_events(struct gendisk *disk);
47 static void disk_del_events(struct gendisk *disk);
48 static void disk_release_events(struct gendisk *disk);
49 
50 /*
51  * Set disk capacity and notify if the size is not currently
52  * zero and will not be set to zero
53  */
54 void set_capacity_revalidate_and_notify(struct gendisk *disk, sector_t size,
55 					bool revalidate)
56 {
57 	sector_t capacity = get_capacity(disk);
58 
59 	set_capacity(disk, size);
60 
61 	if (revalidate)
62 		revalidate_disk(disk);
63 
64 	if (capacity != size && capacity != 0 && size != 0) {
65 		char *envp[] = { "RESIZE=1", NULL };
66 
67 		kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
68 	}
69 }
70 
71 EXPORT_SYMBOL_GPL(set_capacity_revalidate_and_notify);
72 
73 /*
74  * Format the device name of the indicated disk into the supplied buffer and
75  * return a pointer to that same buffer for convenience.
76  */
77 char *disk_name(struct gendisk *hd, int partno, char *buf)
78 {
79 	if (!partno)
80 		snprintf(buf, BDEVNAME_SIZE, "%s", hd->disk_name);
81 	else if (isdigit(hd->disk_name[strlen(hd->disk_name)-1]))
82 		snprintf(buf, BDEVNAME_SIZE, "%sp%d", hd->disk_name, partno);
83 	else
84 		snprintf(buf, BDEVNAME_SIZE, "%s%d", hd->disk_name, partno);
85 
86 	return buf;
87 }
88 
89 const char *bdevname(struct block_device *bdev, char *buf)
90 {
91 	return disk_name(bdev->bd_disk, bdev->bd_part->partno, buf);
92 }
93 EXPORT_SYMBOL(bdevname);
94 
95 static void part_stat_read_all(struct hd_struct *part, struct disk_stats *stat)
96 {
97 	int cpu;
98 
99 	memset(stat, 0, sizeof(struct disk_stats));
100 	for_each_possible_cpu(cpu) {
101 		struct disk_stats *ptr = per_cpu_ptr(part->dkstats, cpu);
102 		int group;
103 
104 		for (group = 0; group < NR_STAT_GROUPS; group++) {
105 			stat->nsecs[group] += ptr->nsecs[group];
106 			stat->sectors[group] += ptr->sectors[group];
107 			stat->ios[group] += ptr->ios[group];
108 			stat->merges[group] += ptr->merges[group];
109 		}
110 
111 		stat->io_ticks += ptr->io_ticks;
112 	}
113 }
114 
115 static unsigned int part_in_flight(struct request_queue *q,
116 		struct hd_struct *part)
117 {
118 	unsigned int inflight = 0;
119 	int cpu;
120 
121 	for_each_possible_cpu(cpu) {
122 		inflight += part_stat_local_read_cpu(part, in_flight[0], cpu) +
123 			    part_stat_local_read_cpu(part, in_flight[1], cpu);
124 	}
125 	if ((int)inflight < 0)
126 		inflight = 0;
127 
128 	return inflight;
129 }
130 
131 static void part_in_flight_rw(struct request_queue *q, struct hd_struct *part,
132 		unsigned int inflight[2])
133 {
134 	int cpu;
135 
136 	inflight[0] = 0;
137 	inflight[1] = 0;
138 	for_each_possible_cpu(cpu) {
139 		inflight[0] += part_stat_local_read_cpu(part, in_flight[0], cpu);
140 		inflight[1] += part_stat_local_read_cpu(part, in_flight[1], cpu);
141 	}
142 	if ((int)inflight[0] < 0)
143 		inflight[0] = 0;
144 	if ((int)inflight[1] < 0)
145 		inflight[1] = 0;
146 }
147 
148 struct hd_struct *__disk_get_part(struct gendisk *disk, int partno)
149 {
150 	struct disk_part_tbl *ptbl = rcu_dereference(disk->part_tbl);
151 
152 	if (unlikely(partno < 0 || partno >= ptbl->len))
153 		return NULL;
154 	return rcu_dereference(ptbl->part[partno]);
155 }
156 
157 /**
158  * disk_get_part - get partition
159  * @disk: disk to look partition from
160  * @partno: partition number
161  *
162  * Look for partition @partno from @disk.  If found, increment
163  * reference count and return it.
164  *
165  * CONTEXT:
166  * Don't care.
167  *
168  * RETURNS:
169  * Pointer to the found partition on success, NULL if not found.
170  */
171 struct hd_struct *disk_get_part(struct gendisk *disk, int partno)
172 {
173 	struct hd_struct *part;
174 
175 	rcu_read_lock();
176 	part = __disk_get_part(disk, partno);
177 	if (part)
178 		get_device(part_to_dev(part));
179 	rcu_read_unlock();
180 
181 	return part;
182 }
183 
184 /**
185  * disk_part_iter_init - initialize partition iterator
186  * @piter: iterator to initialize
187  * @disk: disk to iterate over
188  * @flags: DISK_PITER_* flags
189  *
190  * Initialize @piter so that it iterates over partitions of @disk.
191  *
192  * CONTEXT:
193  * Don't care.
194  */
195 void disk_part_iter_init(struct disk_part_iter *piter, struct gendisk *disk,
196 			  unsigned int flags)
197 {
198 	struct disk_part_tbl *ptbl;
199 
200 	rcu_read_lock();
201 	ptbl = rcu_dereference(disk->part_tbl);
202 
203 	piter->disk = disk;
204 	piter->part = NULL;
205 
206 	if (flags & DISK_PITER_REVERSE)
207 		piter->idx = ptbl->len - 1;
208 	else if (flags & (DISK_PITER_INCL_PART0 | DISK_PITER_INCL_EMPTY_PART0))
209 		piter->idx = 0;
210 	else
211 		piter->idx = 1;
212 
213 	piter->flags = flags;
214 
215 	rcu_read_unlock();
216 }
217 EXPORT_SYMBOL_GPL(disk_part_iter_init);
218 
219 /**
220  * disk_part_iter_next - proceed iterator to the next partition and return it
221  * @piter: iterator of interest
222  *
223  * Proceed @piter to the next partition and return it.
224  *
225  * CONTEXT:
226  * Don't care.
227  */
228 struct hd_struct *disk_part_iter_next(struct disk_part_iter *piter)
229 {
230 	struct disk_part_tbl *ptbl;
231 	int inc, end;
232 
233 	/* put the last partition */
234 	disk_put_part(piter->part);
235 	piter->part = NULL;
236 
237 	/* get part_tbl */
238 	rcu_read_lock();
239 	ptbl = rcu_dereference(piter->disk->part_tbl);
240 
241 	/* determine iteration parameters */
242 	if (piter->flags & DISK_PITER_REVERSE) {
243 		inc = -1;
244 		if (piter->flags & (DISK_PITER_INCL_PART0 |
245 				    DISK_PITER_INCL_EMPTY_PART0))
246 			end = -1;
247 		else
248 			end = 0;
249 	} else {
250 		inc = 1;
251 		end = ptbl->len;
252 	}
253 
254 	/* iterate to the next partition */
255 	for (; piter->idx != end; piter->idx += inc) {
256 		struct hd_struct *part;
257 
258 		part = rcu_dereference(ptbl->part[piter->idx]);
259 		if (!part)
260 			continue;
261 		if (!part_nr_sects_read(part) &&
262 		    !(piter->flags & DISK_PITER_INCL_EMPTY) &&
263 		    !(piter->flags & DISK_PITER_INCL_EMPTY_PART0 &&
264 		      piter->idx == 0))
265 			continue;
266 
267 		get_device(part_to_dev(part));
268 		piter->part = part;
269 		piter->idx += inc;
270 		break;
271 	}
272 
273 	rcu_read_unlock();
274 
275 	return piter->part;
276 }
277 EXPORT_SYMBOL_GPL(disk_part_iter_next);
278 
279 /**
280  * disk_part_iter_exit - finish up partition iteration
281  * @piter: iter of interest
282  *
283  * Called when iteration is over.  Cleans up @piter.
284  *
285  * CONTEXT:
286  * Don't care.
287  */
288 void disk_part_iter_exit(struct disk_part_iter *piter)
289 {
290 	disk_put_part(piter->part);
291 	piter->part = NULL;
292 }
293 EXPORT_SYMBOL_GPL(disk_part_iter_exit);
294 
295 static inline int sector_in_part(struct hd_struct *part, sector_t sector)
296 {
297 	return part->start_sect <= sector &&
298 		sector < part->start_sect + part_nr_sects_read(part);
299 }
300 
301 /**
302  * disk_map_sector_rcu - map sector to partition
303  * @disk: gendisk of interest
304  * @sector: sector to map
305  *
306  * Find out which partition @sector maps to on @disk.  This is
307  * primarily used for stats accounting.
308  *
309  * CONTEXT:
310  * RCU read locked.  The returned partition pointer is always valid
311  * because its refcount is grabbed except for part0, which lifetime
312  * is same with the disk.
313  *
314  * RETURNS:
315  * Found partition on success, part0 is returned if no partition matches
316  * or the matched partition is being deleted.
317  */
318 struct hd_struct *disk_map_sector_rcu(struct gendisk *disk, sector_t sector)
319 {
320 	struct disk_part_tbl *ptbl;
321 	struct hd_struct *part;
322 	int i;
323 
324 	rcu_read_lock();
325 	ptbl = rcu_dereference(disk->part_tbl);
326 
327 	part = rcu_dereference(ptbl->last_lookup);
328 	if (part && sector_in_part(part, sector) && hd_struct_try_get(part))
329 		goto out_unlock;
330 
331 	for (i = 1; i < ptbl->len; i++) {
332 		part = rcu_dereference(ptbl->part[i]);
333 
334 		if (part && sector_in_part(part, sector)) {
335 			/*
336 			 * only live partition can be cached for lookup,
337 			 * so use-after-free on cached & deleting partition
338 			 * can be avoided
339 			 */
340 			if (!hd_struct_try_get(part))
341 				break;
342 			rcu_assign_pointer(ptbl->last_lookup, part);
343 			goto out_unlock;
344 		}
345 	}
346 
347 	part = &disk->part0;
348 out_unlock:
349 	rcu_read_unlock();
350 	return part;
351 }
352 
353 /**
354  * disk_has_partitions
355  * @disk: gendisk of interest
356  *
357  * Walk through the partition table and check if valid partition exists.
358  *
359  * CONTEXT:
360  * Don't care.
361  *
362  * RETURNS:
363  * True if the gendisk has at least one valid non-zero size partition.
364  * Otherwise false.
365  */
366 bool disk_has_partitions(struct gendisk *disk)
367 {
368 	struct disk_part_tbl *ptbl;
369 	int i;
370 	bool ret = false;
371 
372 	rcu_read_lock();
373 	ptbl = rcu_dereference(disk->part_tbl);
374 
375 	/* Iterate partitions skipping the whole device at index 0 */
376 	for (i = 1; i < ptbl->len; i++) {
377 		if (rcu_dereference(ptbl->part[i])) {
378 			ret = true;
379 			break;
380 		}
381 	}
382 
383 	rcu_read_unlock();
384 
385 	return ret;
386 }
387 EXPORT_SYMBOL_GPL(disk_has_partitions);
388 
389 /*
390  * Can be deleted altogether. Later.
391  *
392  */
393 #define BLKDEV_MAJOR_HASH_SIZE 255
394 static struct blk_major_name {
395 	struct blk_major_name *next;
396 	int major;
397 	char name[16];
398 } *major_names[BLKDEV_MAJOR_HASH_SIZE];
399 
400 /* index in the above - for now: assume no multimajor ranges */
401 static inline int major_to_index(unsigned major)
402 {
403 	return major % BLKDEV_MAJOR_HASH_SIZE;
404 }
405 
406 #ifdef CONFIG_PROC_FS
407 void blkdev_show(struct seq_file *seqf, off_t offset)
408 {
409 	struct blk_major_name *dp;
410 
411 	mutex_lock(&block_class_lock);
412 	for (dp = major_names[major_to_index(offset)]; dp; dp = dp->next)
413 		if (dp->major == offset)
414 			seq_printf(seqf, "%3d %s\n", dp->major, dp->name);
415 	mutex_unlock(&block_class_lock);
416 }
417 #endif /* CONFIG_PROC_FS */
418 
419 /**
420  * register_blkdev - register a new block device
421  *
422  * @major: the requested major device number [1..BLKDEV_MAJOR_MAX-1]. If
423  *         @major = 0, try to allocate any unused major number.
424  * @name: the name of the new block device as a zero terminated string
425  *
426  * The @name must be unique within the system.
427  *
428  * The return value depends on the @major input parameter:
429  *
430  *  - if a major device number was requested in range [1..BLKDEV_MAJOR_MAX-1]
431  *    then the function returns zero on success, or a negative error code
432  *  - if any unused major number was requested with @major = 0 parameter
433  *    then the return value is the allocated major number in range
434  *    [1..BLKDEV_MAJOR_MAX-1] or a negative error code otherwise
435  *
436  * See Documentation/admin-guide/devices.txt for the list of allocated
437  * major numbers.
438  */
439 int register_blkdev(unsigned int major, const char *name)
440 {
441 	struct blk_major_name **n, *p;
442 	int index, ret = 0;
443 
444 	mutex_lock(&block_class_lock);
445 
446 	/* temporary */
447 	if (major == 0) {
448 		for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {
449 			if (major_names[index] == NULL)
450 				break;
451 		}
452 
453 		if (index == 0) {
454 			printk("%s: failed to get major for %s\n",
455 			       __func__, name);
456 			ret = -EBUSY;
457 			goto out;
458 		}
459 		major = index;
460 		ret = major;
461 	}
462 
463 	if (major >= BLKDEV_MAJOR_MAX) {
464 		pr_err("%s: major requested (%u) is greater than the maximum (%u) for %s\n",
465 		       __func__, major, BLKDEV_MAJOR_MAX-1, name);
466 
467 		ret = -EINVAL;
468 		goto out;
469 	}
470 
471 	p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);
472 	if (p == NULL) {
473 		ret = -ENOMEM;
474 		goto out;
475 	}
476 
477 	p->major = major;
478 	strlcpy(p->name, name, sizeof(p->name));
479 	p->next = NULL;
480 	index = major_to_index(major);
481 
482 	for (n = &major_names[index]; *n; n = &(*n)->next) {
483 		if ((*n)->major == major)
484 			break;
485 	}
486 	if (!*n)
487 		*n = p;
488 	else
489 		ret = -EBUSY;
490 
491 	if (ret < 0) {
492 		printk("register_blkdev: cannot get major %u for %s\n",
493 		       major, name);
494 		kfree(p);
495 	}
496 out:
497 	mutex_unlock(&block_class_lock);
498 	return ret;
499 }
500 
501 EXPORT_SYMBOL(register_blkdev);
502 
503 void unregister_blkdev(unsigned int major, const char *name)
504 {
505 	struct blk_major_name **n;
506 	struct blk_major_name *p = NULL;
507 	int index = major_to_index(major);
508 
509 	mutex_lock(&block_class_lock);
510 	for (n = &major_names[index]; *n; n = &(*n)->next)
511 		if ((*n)->major == major)
512 			break;
513 	if (!*n || strcmp((*n)->name, name)) {
514 		WARN_ON(1);
515 	} else {
516 		p = *n;
517 		*n = p->next;
518 	}
519 	mutex_unlock(&block_class_lock);
520 	kfree(p);
521 }
522 
523 EXPORT_SYMBOL(unregister_blkdev);
524 
525 static struct kobj_map *bdev_map;
526 
527 /**
528  * blk_mangle_minor - scatter minor numbers apart
529  * @minor: minor number to mangle
530  *
531  * Scatter consecutively allocated @minor number apart if MANGLE_DEVT
532  * is enabled.  Mangling twice gives the original value.
533  *
534  * RETURNS:
535  * Mangled value.
536  *
537  * CONTEXT:
538  * Don't care.
539  */
540 static int blk_mangle_minor(int minor)
541 {
542 #ifdef CONFIG_DEBUG_BLOCK_EXT_DEVT
543 	int i;
544 
545 	for (i = 0; i < MINORBITS / 2; i++) {
546 		int low = minor & (1 << i);
547 		int high = minor & (1 << (MINORBITS - 1 - i));
548 		int distance = MINORBITS - 1 - 2 * i;
549 
550 		minor ^= low | high;	/* clear both bits */
551 		low <<= distance;	/* swap the positions */
552 		high >>= distance;
553 		minor |= low | high;	/* and set */
554 	}
555 #endif
556 	return minor;
557 }
558 
559 /**
560  * blk_alloc_devt - allocate a dev_t for a partition
561  * @part: partition to allocate dev_t for
562  * @devt: out parameter for resulting dev_t
563  *
564  * Allocate a dev_t for block device.
565  *
566  * RETURNS:
567  * 0 on success, allocated dev_t is returned in *@devt.  -errno on
568  * failure.
569  *
570  * CONTEXT:
571  * Might sleep.
572  */
573 int blk_alloc_devt(struct hd_struct *part, dev_t *devt)
574 {
575 	struct gendisk *disk = part_to_disk(part);
576 	int idx;
577 
578 	/* in consecutive minor range? */
579 	if (part->partno < disk->minors) {
580 		*devt = MKDEV(disk->major, disk->first_minor + part->partno);
581 		return 0;
582 	}
583 
584 	/* allocate ext devt */
585 	idr_preload(GFP_KERNEL);
586 
587 	spin_lock_bh(&ext_devt_lock);
588 	idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
589 	spin_unlock_bh(&ext_devt_lock);
590 
591 	idr_preload_end();
592 	if (idx < 0)
593 		return idx == -ENOSPC ? -EBUSY : idx;
594 
595 	*devt = MKDEV(BLOCK_EXT_MAJOR, blk_mangle_minor(idx));
596 	return 0;
597 }
598 
599 /**
600  * blk_free_devt - free a dev_t
601  * @devt: dev_t to free
602  *
603  * Free @devt which was allocated using blk_alloc_devt().
604  *
605  * CONTEXT:
606  * Might sleep.
607  */
608 void blk_free_devt(dev_t devt)
609 {
610 	if (devt == MKDEV(0, 0))
611 		return;
612 
613 	if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
614 		spin_lock_bh(&ext_devt_lock);
615 		idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
616 		spin_unlock_bh(&ext_devt_lock);
617 	}
618 }
619 
620 /*
621  * We invalidate devt by assigning NULL pointer for devt in idr.
622  */
623 void blk_invalidate_devt(dev_t devt)
624 {
625 	if (MAJOR(devt) == BLOCK_EXT_MAJOR) {
626 		spin_lock_bh(&ext_devt_lock);
627 		idr_replace(&ext_devt_idr, NULL, blk_mangle_minor(MINOR(devt)));
628 		spin_unlock_bh(&ext_devt_lock);
629 	}
630 }
631 
632 static char *bdevt_str(dev_t devt, char *buf)
633 {
634 	if (MAJOR(devt) <= 0xff && MINOR(devt) <= 0xff) {
635 		char tbuf[BDEVT_SIZE];
636 		snprintf(tbuf, BDEVT_SIZE, "%02x%02x", MAJOR(devt), MINOR(devt));
637 		snprintf(buf, BDEVT_SIZE, "%-9s", tbuf);
638 	} else
639 		snprintf(buf, BDEVT_SIZE, "%03x:%05x", MAJOR(devt), MINOR(devt));
640 
641 	return buf;
642 }
643 
644 /*
645  * Register device numbers dev..(dev+range-1)
646  * range must be nonzero
647  * The hash chain is sorted on range, so that subranges can override.
648  */
649 void blk_register_region(dev_t devt, unsigned long range, struct module *module,
650 			 struct kobject *(*probe)(dev_t, int *, void *),
651 			 int (*lock)(dev_t, void *), void *data)
652 {
653 	kobj_map(bdev_map, devt, range, module, probe, lock, data);
654 }
655 
656 EXPORT_SYMBOL(blk_register_region);
657 
658 void blk_unregister_region(dev_t devt, unsigned long range)
659 {
660 	kobj_unmap(bdev_map, devt, range);
661 }
662 
663 EXPORT_SYMBOL(blk_unregister_region);
664 
665 static struct kobject *exact_match(dev_t devt, int *partno, void *data)
666 {
667 	struct gendisk *p = data;
668 
669 	return &disk_to_dev(p)->kobj;
670 }
671 
672 static int exact_lock(dev_t devt, void *data)
673 {
674 	struct gendisk *p = data;
675 
676 	if (!get_disk_and_module(p))
677 		return -1;
678 	return 0;
679 }
680 
681 static void register_disk(struct device *parent, struct gendisk *disk,
682 			  const struct attribute_group **groups)
683 {
684 	struct device *ddev = disk_to_dev(disk);
685 	struct block_device *bdev;
686 	struct disk_part_iter piter;
687 	struct hd_struct *part;
688 	int err;
689 
690 	ddev->parent = parent;
691 
692 	dev_set_name(ddev, "%s", disk->disk_name);
693 
694 	/* delay uevents, until we scanned partition table */
695 	dev_set_uevent_suppress(ddev, 1);
696 
697 	if (groups) {
698 		WARN_ON(ddev->groups);
699 		ddev->groups = groups;
700 	}
701 	if (device_add(ddev))
702 		return;
703 	if (!sysfs_deprecated) {
704 		err = sysfs_create_link(block_depr, &ddev->kobj,
705 					kobject_name(&ddev->kobj));
706 		if (err) {
707 			device_del(ddev);
708 			return;
709 		}
710 	}
711 
712 	/*
713 	 * avoid probable deadlock caused by allocating memory with
714 	 * GFP_KERNEL in runtime_resume callback of its all ancestor
715 	 * devices
716 	 */
717 	pm_runtime_set_memalloc_noio(ddev, true);
718 
719 	disk->part0.holder_dir = kobject_create_and_add("holders", &ddev->kobj);
720 	disk->slave_dir = kobject_create_and_add("slaves", &ddev->kobj);
721 
722 	if (disk->flags & GENHD_FL_HIDDEN) {
723 		dev_set_uevent_suppress(ddev, 0);
724 		return;
725 	}
726 
727 	/* No minors to use for partitions */
728 	if (!disk_part_scan_enabled(disk))
729 		goto exit;
730 
731 	/* No such device (e.g., media were just removed) */
732 	if (!get_capacity(disk))
733 		goto exit;
734 
735 	bdev = bdget_disk(disk, 0);
736 	if (!bdev)
737 		goto exit;
738 
739 	bdev->bd_invalidated = 1;
740 	err = blkdev_get(bdev, FMODE_READ, NULL);
741 	if (err < 0)
742 		goto exit;
743 	blkdev_put(bdev, FMODE_READ);
744 
745 exit:
746 	/* announce disk after possible partitions are created */
747 	dev_set_uevent_suppress(ddev, 0);
748 	kobject_uevent(&ddev->kobj, KOBJ_ADD);
749 
750 	/* announce possible partitions */
751 	disk_part_iter_init(&piter, disk, 0);
752 	while ((part = disk_part_iter_next(&piter)))
753 		kobject_uevent(&part_to_dev(part)->kobj, KOBJ_ADD);
754 	disk_part_iter_exit(&piter);
755 
756 	if (disk->queue->backing_dev_info->dev) {
757 		err = sysfs_create_link(&ddev->kobj,
758 			  &disk->queue->backing_dev_info->dev->kobj,
759 			  "bdi");
760 		WARN_ON(err);
761 	}
762 }
763 
764 /**
765  * __device_add_disk - add disk information to kernel list
766  * @parent: parent device for the disk
767  * @disk: per-device partitioning information
768  * @groups: Additional per-device sysfs groups
769  * @register_queue: register the queue if set to true
770  *
771  * This function registers the partitioning information in @disk
772  * with the kernel.
773  *
774  * FIXME: error handling
775  */
776 static void __device_add_disk(struct device *parent, struct gendisk *disk,
777 			      const struct attribute_group **groups,
778 			      bool register_queue)
779 {
780 	dev_t devt;
781 	int retval;
782 
783 	/*
784 	 * The disk queue should now be all set with enough information about
785 	 * the device for the elevator code to pick an adequate default
786 	 * elevator if one is needed, that is, for devices requesting queue
787 	 * registration.
788 	 */
789 	if (register_queue)
790 		elevator_init_mq(disk->queue);
791 
792 	/* minors == 0 indicates to use ext devt from part0 and should
793 	 * be accompanied with EXT_DEVT flag.  Make sure all
794 	 * parameters make sense.
795 	 */
796 	WARN_ON(disk->minors && !(disk->major || disk->first_minor));
797 	WARN_ON(!disk->minors &&
798 		!(disk->flags & (GENHD_FL_EXT_DEVT | GENHD_FL_HIDDEN)));
799 
800 	disk->flags |= GENHD_FL_UP;
801 
802 	retval = blk_alloc_devt(&disk->part0, &devt);
803 	if (retval) {
804 		WARN_ON(1);
805 		return;
806 	}
807 	disk->major = MAJOR(devt);
808 	disk->first_minor = MINOR(devt);
809 
810 	disk_alloc_events(disk);
811 
812 	if (disk->flags & GENHD_FL_HIDDEN) {
813 		/*
814 		 * Don't let hidden disks show up in /proc/partitions,
815 		 * and don't bother scanning for partitions either.
816 		 */
817 		disk->flags |= GENHD_FL_SUPPRESS_PARTITION_INFO;
818 		disk->flags |= GENHD_FL_NO_PART_SCAN;
819 	} else {
820 		struct backing_dev_info *bdi = disk->queue->backing_dev_info;
821 		struct device *dev = disk_to_dev(disk);
822 		int ret;
823 
824 		/* Register BDI before referencing it from bdev */
825 		dev->devt = devt;
826 		ret = bdi_register(bdi, "%u:%u", MAJOR(devt), MINOR(devt));
827 		WARN_ON(ret);
828 		bdi_set_owner(bdi, dev);
829 		blk_register_region(disk_devt(disk), disk->minors, NULL,
830 				    exact_match, exact_lock, disk);
831 	}
832 	register_disk(parent, disk, groups);
833 	if (register_queue)
834 		blk_register_queue(disk);
835 
836 	/*
837 	 * Take an extra ref on queue which will be put on disk_release()
838 	 * so that it sticks around as long as @disk is there.
839 	 */
840 	WARN_ON_ONCE(!blk_get_queue(disk->queue));
841 
842 	disk_add_events(disk);
843 	blk_integrity_add(disk);
844 }
845 
846 void device_add_disk(struct device *parent, struct gendisk *disk,
847 		     const struct attribute_group **groups)
848 
849 {
850 	__device_add_disk(parent, disk, groups, true);
851 }
852 EXPORT_SYMBOL(device_add_disk);
853 
854 void device_add_disk_no_queue_reg(struct device *parent, struct gendisk *disk)
855 {
856 	__device_add_disk(parent, disk, NULL, false);
857 }
858 EXPORT_SYMBOL(device_add_disk_no_queue_reg);
859 
860 static void invalidate_partition(struct gendisk *disk, int partno)
861 {
862 	struct block_device *bdev;
863 
864 	bdev = bdget_disk(disk, partno);
865 	if (!bdev)
866 		return;
867 
868 	fsync_bdev(bdev);
869 	__invalidate_device(bdev, true);
870 
871 	/*
872 	 * Unhash the bdev inode for this device so that it gets evicted as soon
873 	 * as last inode reference is dropped.
874 	 */
875 	remove_inode_hash(bdev->bd_inode);
876 	bdput(bdev);
877 }
878 
879 /**
880  * del_gendisk - remove the gendisk
881  * @disk: the struct gendisk to remove
882  *
883  * Removes the gendisk and all its associated resources. This deletes the
884  * partitions associated with the gendisk, and unregisters the associated
885  * request_queue.
886  *
887  * This is the counter to the respective __device_add_disk() call.
888  *
889  * The final removal of the struct gendisk happens when its refcount reaches 0
890  * with put_disk(), which should be called after del_gendisk(), if
891  * __device_add_disk() was used.
892  *
893  * Drivers exist which depend on the release of the gendisk to be synchronous,
894  * it should not be deferred.
895  *
896  * Context: can sleep
897  */
898 void del_gendisk(struct gendisk *disk)
899 {
900 	struct disk_part_iter piter;
901 	struct hd_struct *part;
902 
903 	might_sleep();
904 
905 	blk_integrity_del(disk);
906 	disk_del_events(disk);
907 
908 	/*
909 	 * Block lookups of the disk until all bdevs are unhashed and the
910 	 * disk is marked as dead (GENHD_FL_UP cleared).
911 	 */
912 	down_write(&disk->lookup_sem);
913 	/* invalidate stuff */
914 	disk_part_iter_init(&piter, disk,
915 			     DISK_PITER_INCL_EMPTY | DISK_PITER_REVERSE);
916 	while ((part = disk_part_iter_next(&piter))) {
917 		invalidate_partition(disk, part->partno);
918 		delete_partition(disk, part);
919 	}
920 	disk_part_iter_exit(&piter);
921 
922 	invalidate_partition(disk, 0);
923 	set_capacity(disk, 0);
924 	disk->flags &= ~GENHD_FL_UP;
925 	up_write(&disk->lookup_sem);
926 
927 	if (!(disk->flags & GENHD_FL_HIDDEN))
928 		sysfs_remove_link(&disk_to_dev(disk)->kobj, "bdi");
929 	if (disk->queue) {
930 		/*
931 		 * Unregister bdi before releasing device numbers (as they can
932 		 * get reused and we'd get clashes in sysfs).
933 		 */
934 		if (!(disk->flags & GENHD_FL_HIDDEN))
935 			bdi_unregister(disk->queue->backing_dev_info);
936 		blk_unregister_queue(disk);
937 	} else {
938 		WARN_ON(1);
939 	}
940 
941 	if (!(disk->flags & GENHD_FL_HIDDEN))
942 		blk_unregister_region(disk_devt(disk), disk->minors);
943 	/*
944 	 * Remove gendisk pointer from idr so that it cannot be looked up
945 	 * while RCU period before freeing gendisk is running to prevent
946 	 * use-after-free issues. Note that the device number stays
947 	 * "in-use" until we really free the gendisk.
948 	 */
949 	blk_invalidate_devt(disk_devt(disk));
950 
951 	kobject_put(disk->part0.holder_dir);
952 	kobject_put(disk->slave_dir);
953 
954 	part_stat_set_all(&disk->part0, 0);
955 	disk->part0.stamp = 0;
956 	if (!sysfs_deprecated)
957 		sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
958 	pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
959 	device_del(disk_to_dev(disk));
960 }
961 EXPORT_SYMBOL(del_gendisk);
962 
963 /* sysfs access to bad-blocks list. */
964 static ssize_t disk_badblocks_show(struct device *dev,
965 					struct device_attribute *attr,
966 					char *page)
967 {
968 	struct gendisk *disk = dev_to_disk(dev);
969 
970 	if (!disk->bb)
971 		return sprintf(page, "\n");
972 
973 	return badblocks_show(disk->bb, page, 0);
974 }
975 
976 static ssize_t disk_badblocks_store(struct device *dev,
977 					struct device_attribute *attr,
978 					const char *page, size_t len)
979 {
980 	struct gendisk *disk = dev_to_disk(dev);
981 
982 	if (!disk->bb)
983 		return -ENXIO;
984 
985 	return badblocks_store(disk->bb, page, len, 0);
986 }
987 
988 /**
989  * get_gendisk - get partitioning information for a given device
990  * @devt: device to get partitioning information for
991  * @partno: returned partition index
992  *
993  * This function gets the structure containing partitioning
994  * information for the given device @devt.
995  *
996  * Context: can sleep
997  */
998 struct gendisk *get_gendisk(dev_t devt, int *partno)
999 {
1000 	struct gendisk *disk = NULL;
1001 
1002 	might_sleep();
1003 
1004 	if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
1005 		struct kobject *kobj;
1006 
1007 		kobj = kobj_lookup(bdev_map, devt, partno);
1008 		if (kobj)
1009 			disk = dev_to_disk(kobj_to_dev(kobj));
1010 	} else {
1011 		struct hd_struct *part;
1012 
1013 		spin_lock_bh(&ext_devt_lock);
1014 		part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
1015 		if (part && get_disk_and_module(part_to_disk(part))) {
1016 			*partno = part->partno;
1017 			disk = part_to_disk(part);
1018 		}
1019 		spin_unlock_bh(&ext_devt_lock);
1020 	}
1021 
1022 	if (!disk)
1023 		return NULL;
1024 
1025 	/*
1026 	 * Synchronize with del_gendisk() to not return disk that is being
1027 	 * destroyed.
1028 	 */
1029 	down_read(&disk->lookup_sem);
1030 	if (unlikely((disk->flags & GENHD_FL_HIDDEN) ||
1031 		     !(disk->flags & GENHD_FL_UP))) {
1032 		up_read(&disk->lookup_sem);
1033 		put_disk_and_module(disk);
1034 		disk = NULL;
1035 	} else {
1036 		up_read(&disk->lookup_sem);
1037 	}
1038 	return disk;
1039 }
1040 
1041 /**
1042  * bdget_disk - do bdget() by gendisk and partition number
1043  * @disk: gendisk of interest
1044  * @partno: partition number
1045  *
1046  * Find partition @partno from @disk, do bdget() on it.
1047  *
1048  * CONTEXT:
1049  * Don't care.
1050  *
1051  * RETURNS:
1052  * Resulting block_device on success, NULL on failure.
1053  */
1054 struct block_device *bdget_disk(struct gendisk *disk, int partno)
1055 {
1056 	struct hd_struct *part;
1057 	struct block_device *bdev = NULL;
1058 
1059 	part = disk_get_part(disk, partno);
1060 	if (part)
1061 		bdev = bdget(part_devt(part));
1062 	disk_put_part(part);
1063 
1064 	return bdev;
1065 }
1066 EXPORT_SYMBOL(bdget_disk);
1067 
1068 /*
1069  * print a full list of all partitions - intended for places where the root
1070  * filesystem can't be mounted and thus to give the victim some idea of what
1071  * went wrong
1072  */
1073 void __init printk_all_partitions(void)
1074 {
1075 	struct class_dev_iter iter;
1076 	struct device *dev;
1077 
1078 	class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1079 	while ((dev = class_dev_iter_next(&iter))) {
1080 		struct gendisk *disk = dev_to_disk(dev);
1081 		struct disk_part_iter piter;
1082 		struct hd_struct *part;
1083 		char name_buf[BDEVNAME_SIZE];
1084 		char devt_buf[BDEVT_SIZE];
1085 
1086 		/*
1087 		 * Don't show empty devices or things that have been
1088 		 * suppressed
1089 		 */
1090 		if (get_capacity(disk) == 0 ||
1091 		    (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
1092 			continue;
1093 
1094 		/*
1095 		 * Note, unlike /proc/partitions, I am showing the
1096 		 * numbers in hex - the same format as the root=
1097 		 * option takes.
1098 		 */
1099 		disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
1100 		while ((part = disk_part_iter_next(&piter))) {
1101 			bool is_part0 = part == &disk->part0;
1102 
1103 			printk("%s%s %10llu %s %s", is_part0 ? "" : "  ",
1104 			       bdevt_str(part_devt(part), devt_buf),
1105 			       (unsigned long long)part_nr_sects_read(part) >> 1
1106 			       , disk_name(disk, part->partno, name_buf),
1107 			       part->info ? part->info->uuid : "");
1108 			if (is_part0) {
1109 				if (dev->parent && dev->parent->driver)
1110 					printk(" driver: %s\n",
1111 					      dev->parent->driver->name);
1112 				else
1113 					printk(" (driver?)\n");
1114 			} else
1115 				printk("\n");
1116 		}
1117 		disk_part_iter_exit(&piter);
1118 	}
1119 	class_dev_iter_exit(&iter);
1120 }
1121 
1122 #ifdef CONFIG_PROC_FS
1123 /* iterator */
1124 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
1125 {
1126 	loff_t skip = *pos;
1127 	struct class_dev_iter *iter;
1128 	struct device *dev;
1129 
1130 	iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1131 	if (!iter)
1132 		return ERR_PTR(-ENOMEM);
1133 
1134 	seqf->private = iter;
1135 	class_dev_iter_init(iter, &block_class, NULL, &disk_type);
1136 	do {
1137 		dev = class_dev_iter_next(iter);
1138 		if (!dev)
1139 			return NULL;
1140 	} while (skip--);
1141 
1142 	return dev_to_disk(dev);
1143 }
1144 
1145 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
1146 {
1147 	struct device *dev;
1148 
1149 	(*pos)++;
1150 	dev = class_dev_iter_next(seqf->private);
1151 	if (dev)
1152 		return dev_to_disk(dev);
1153 
1154 	return NULL;
1155 }
1156 
1157 static void disk_seqf_stop(struct seq_file *seqf, void *v)
1158 {
1159 	struct class_dev_iter *iter = seqf->private;
1160 
1161 	/* stop is called even after start failed :-( */
1162 	if (iter) {
1163 		class_dev_iter_exit(iter);
1164 		kfree(iter);
1165 		seqf->private = NULL;
1166 	}
1167 }
1168 
1169 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
1170 {
1171 	void *p;
1172 
1173 	p = disk_seqf_start(seqf, pos);
1174 	if (!IS_ERR_OR_NULL(p) && !*pos)
1175 		seq_puts(seqf, "major minor  #blocks  name\n\n");
1176 	return p;
1177 }
1178 
1179 static int show_partition(struct seq_file *seqf, void *v)
1180 {
1181 	struct gendisk *sgp = v;
1182 	struct disk_part_iter piter;
1183 	struct hd_struct *part;
1184 	char buf[BDEVNAME_SIZE];
1185 
1186 	/* Don't show non-partitionable removeable devices or empty devices */
1187 	if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
1188 				   (sgp->flags & GENHD_FL_REMOVABLE)))
1189 		return 0;
1190 	if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
1191 		return 0;
1192 
1193 	/* show the full disk and all non-0 size partitions of it */
1194 	disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
1195 	while ((part = disk_part_iter_next(&piter)))
1196 		seq_printf(seqf, "%4d  %7d %10llu %s\n",
1197 			   MAJOR(part_devt(part)), MINOR(part_devt(part)),
1198 			   (unsigned long long)part_nr_sects_read(part) >> 1,
1199 			   disk_name(sgp, part->partno, buf));
1200 	disk_part_iter_exit(&piter);
1201 
1202 	return 0;
1203 }
1204 
1205 static const struct seq_operations partitions_op = {
1206 	.start	= show_partition_start,
1207 	.next	= disk_seqf_next,
1208 	.stop	= disk_seqf_stop,
1209 	.show	= show_partition
1210 };
1211 #endif
1212 
1213 
1214 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
1215 {
1216 	if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
1217 		/* Make old-style 2.4 aliases work */
1218 		request_module("block-major-%d", MAJOR(devt));
1219 	return NULL;
1220 }
1221 
1222 static int __init genhd_device_init(void)
1223 {
1224 	int error;
1225 
1226 	block_class.dev_kobj = sysfs_dev_block_kobj;
1227 	error = class_register(&block_class);
1228 	if (unlikely(error))
1229 		return error;
1230 	bdev_map = kobj_map_init(base_probe, &block_class_lock);
1231 	blk_dev_init();
1232 
1233 	register_blkdev(BLOCK_EXT_MAJOR, "blkext");
1234 
1235 	/* create top-level block dir */
1236 	if (!sysfs_deprecated)
1237 		block_depr = kobject_create_and_add("block", NULL);
1238 	return 0;
1239 }
1240 
1241 subsys_initcall(genhd_device_init);
1242 
1243 static ssize_t disk_range_show(struct device *dev,
1244 			       struct device_attribute *attr, char *buf)
1245 {
1246 	struct gendisk *disk = dev_to_disk(dev);
1247 
1248 	return sprintf(buf, "%d\n", disk->minors);
1249 }
1250 
1251 static ssize_t disk_ext_range_show(struct device *dev,
1252 				   struct device_attribute *attr, char *buf)
1253 {
1254 	struct gendisk *disk = dev_to_disk(dev);
1255 
1256 	return sprintf(buf, "%d\n", disk_max_parts(disk));
1257 }
1258 
1259 static ssize_t disk_removable_show(struct device *dev,
1260 				   struct device_attribute *attr, char *buf)
1261 {
1262 	struct gendisk *disk = dev_to_disk(dev);
1263 
1264 	return sprintf(buf, "%d\n",
1265 		       (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
1266 }
1267 
1268 static ssize_t disk_hidden_show(struct device *dev,
1269 				   struct device_attribute *attr, char *buf)
1270 {
1271 	struct gendisk *disk = dev_to_disk(dev);
1272 
1273 	return sprintf(buf, "%d\n",
1274 		       (disk->flags & GENHD_FL_HIDDEN ? 1 : 0));
1275 }
1276 
1277 static ssize_t disk_ro_show(struct device *dev,
1278 				   struct device_attribute *attr, char *buf)
1279 {
1280 	struct gendisk *disk = dev_to_disk(dev);
1281 
1282 	return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
1283 }
1284 
1285 ssize_t part_size_show(struct device *dev,
1286 		       struct device_attribute *attr, char *buf)
1287 {
1288 	struct hd_struct *p = dev_to_part(dev);
1289 
1290 	return sprintf(buf, "%llu\n",
1291 		(unsigned long long)part_nr_sects_read(p));
1292 }
1293 
1294 ssize_t part_stat_show(struct device *dev,
1295 		       struct device_attribute *attr, char *buf)
1296 {
1297 	struct hd_struct *p = dev_to_part(dev);
1298 	struct request_queue *q = part_to_disk(p)->queue;
1299 	struct disk_stats stat;
1300 	unsigned int inflight;
1301 
1302 	part_stat_read_all(p, &stat);
1303 	if (queue_is_mq(q))
1304 		inflight = blk_mq_in_flight(q, p);
1305 	else
1306 		inflight = part_in_flight(q, p);
1307 
1308 	return sprintf(buf,
1309 		"%8lu %8lu %8llu %8u "
1310 		"%8lu %8lu %8llu %8u "
1311 		"%8u %8u %8u "
1312 		"%8lu %8lu %8llu %8u "
1313 		"%8lu %8u"
1314 		"\n",
1315 		stat.ios[STAT_READ],
1316 		stat.merges[STAT_READ],
1317 		(unsigned long long)stat.sectors[STAT_READ],
1318 		(unsigned int)div_u64(stat.nsecs[STAT_READ], NSEC_PER_MSEC),
1319 		stat.ios[STAT_WRITE],
1320 		stat.merges[STAT_WRITE],
1321 		(unsigned long long)stat.sectors[STAT_WRITE],
1322 		(unsigned int)div_u64(stat.nsecs[STAT_WRITE], NSEC_PER_MSEC),
1323 		inflight,
1324 		jiffies_to_msecs(stat.io_ticks),
1325 		(unsigned int)div_u64(stat.nsecs[STAT_READ] +
1326 				      stat.nsecs[STAT_WRITE] +
1327 				      stat.nsecs[STAT_DISCARD] +
1328 				      stat.nsecs[STAT_FLUSH],
1329 						NSEC_PER_MSEC),
1330 		stat.ios[STAT_DISCARD],
1331 		stat.merges[STAT_DISCARD],
1332 		(unsigned long long)stat.sectors[STAT_DISCARD],
1333 		(unsigned int)div_u64(stat.nsecs[STAT_DISCARD], NSEC_PER_MSEC),
1334 		stat.ios[STAT_FLUSH],
1335 		(unsigned int)div_u64(stat.nsecs[STAT_FLUSH], NSEC_PER_MSEC));
1336 }
1337 
1338 ssize_t part_inflight_show(struct device *dev, struct device_attribute *attr,
1339 			   char *buf)
1340 {
1341 	struct hd_struct *p = dev_to_part(dev);
1342 	struct request_queue *q = part_to_disk(p)->queue;
1343 	unsigned int inflight[2];
1344 
1345 	if (queue_is_mq(q))
1346 		blk_mq_in_flight_rw(q, p, inflight);
1347 	else
1348 		part_in_flight_rw(q, p, inflight);
1349 
1350 	return sprintf(buf, "%8u %8u\n", inflight[0], inflight[1]);
1351 }
1352 
1353 static ssize_t disk_capability_show(struct device *dev,
1354 				    struct device_attribute *attr, char *buf)
1355 {
1356 	struct gendisk *disk = dev_to_disk(dev);
1357 
1358 	return sprintf(buf, "%x\n", disk->flags);
1359 }
1360 
1361 static ssize_t disk_alignment_offset_show(struct device *dev,
1362 					  struct device_attribute *attr,
1363 					  char *buf)
1364 {
1365 	struct gendisk *disk = dev_to_disk(dev);
1366 
1367 	return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
1368 }
1369 
1370 static ssize_t disk_discard_alignment_show(struct device *dev,
1371 					   struct device_attribute *attr,
1372 					   char *buf)
1373 {
1374 	struct gendisk *disk = dev_to_disk(dev);
1375 
1376 	return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
1377 }
1378 
1379 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
1380 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
1381 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
1382 static DEVICE_ATTR(hidden, 0444, disk_hidden_show, NULL);
1383 static DEVICE_ATTR(ro, 0444, disk_ro_show, NULL);
1384 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
1385 static DEVICE_ATTR(alignment_offset, 0444, disk_alignment_offset_show, NULL);
1386 static DEVICE_ATTR(discard_alignment, 0444, disk_discard_alignment_show, NULL);
1387 static DEVICE_ATTR(capability, 0444, disk_capability_show, NULL);
1388 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
1389 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
1390 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
1391 
1392 #ifdef CONFIG_FAIL_MAKE_REQUEST
1393 ssize_t part_fail_show(struct device *dev,
1394 		       struct device_attribute *attr, char *buf)
1395 {
1396 	struct hd_struct *p = dev_to_part(dev);
1397 
1398 	return sprintf(buf, "%d\n", p->make_it_fail);
1399 }
1400 
1401 ssize_t part_fail_store(struct device *dev,
1402 			struct device_attribute *attr,
1403 			const char *buf, size_t count)
1404 {
1405 	struct hd_struct *p = dev_to_part(dev);
1406 	int i;
1407 
1408 	if (count > 0 && sscanf(buf, "%d", &i) > 0)
1409 		p->make_it_fail = (i == 0) ? 0 : 1;
1410 
1411 	return count;
1412 }
1413 
1414 static struct device_attribute dev_attr_fail =
1415 	__ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
1416 #endif /* CONFIG_FAIL_MAKE_REQUEST */
1417 
1418 #ifdef CONFIG_FAIL_IO_TIMEOUT
1419 static struct device_attribute dev_attr_fail_timeout =
1420 	__ATTR(io-timeout-fail, 0644, part_timeout_show, part_timeout_store);
1421 #endif
1422 
1423 static struct attribute *disk_attrs[] = {
1424 	&dev_attr_range.attr,
1425 	&dev_attr_ext_range.attr,
1426 	&dev_attr_removable.attr,
1427 	&dev_attr_hidden.attr,
1428 	&dev_attr_ro.attr,
1429 	&dev_attr_size.attr,
1430 	&dev_attr_alignment_offset.attr,
1431 	&dev_attr_discard_alignment.attr,
1432 	&dev_attr_capability.attr,
1433 	&dev_attr_stat.attr,
1434 	&dev_attr_inflight.attr,
1435 	&dev_attr_badblocks.attr,
1436 #ifdef CONFIG_FAIL_MAKE_REQUEST
1437 	&dev_attr_fail.attr,
1438 #endif
1439 #ifdef CONFIG_FAIL_IO_TIMEOUT
1440 	&dev_attr_fail_timeout.attr,
1441 #endif
1442 	NULL
1443 };
1444 
1445 static umode_t disk_visible(struct kobject *kobj, struct attribute *a, int n)
1446 {
1447 	struct device *dev = container_of(kobj, typeof(*dev), kobj);
1448 	struct gendisk *disk = dev_to_disk(dev);
1449 
1450 	if (a == &dev_attr_badblocks.attr && !disk->bb)
1451 		return 0;
1452 	return a->mode;
1453 }
1454 
1455 static struct attribute_group disk_attr_group = {
1456 	.attrs = disk_attrs,
1457 	.is_visible = disk_visible,
1458 };
1459 
1460 static const struct attribute_group *disk_attr_groups[] = {
1461 	&disk_attr_group,
1462 	NULL
1463 };
1464 
1465 /**
1466  * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1467  * @disk: disk to replace part_tbl for
1468  * @new_ptbl: new part_tbl to install
1469  *
1470  * Replace disk->part_tbl with @new_ptbl in RCU-safe way.  The
1471  * original ptbl is freed using RCU callback.
1472  *
1473  * LOCKING:
1474  * Matching bd_mutex locked or the caller is the only user of @disk.
1475  */
1476 static void disk_replace_part_tbl(struct gendisk *disk,
1477 				  struct disk_part_tbl *new_ptbl)
1478 {
1479 	struct disk_part_tbl *old_ptbl =
1480 		rcu_dereference_protected(disk->part_tbl, 1);
1481 
1482 	rcu_assign_pointer(disk->part_tbl, new_ptbl);
1483 
1484 	if (old_ptbl) {
1485 		rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1486 		kfree_rcu(old_ptbl, rcu_head);
1487 	}
1488 }
1489 
1490 /**
1491  * disk_expand_part_tbl - expand disk->part_tbl
1492  * @disk: disk to expand part_tbl for
1493  * @partno: expand such that this partno can fit in
1494  *
1495  * Expand disk->part_tbl such that @partno can fit in.  disk->part_tbl
1496  * uses RCU to allow unlocked dereferencing for stats and other stuff.
1497  *
1498  * LOCKING:
1499  * Matching bd_mutex locked or the caller is the only user of @disk.
1500  * Might sleep.
1501  *
1502  * RETURNS:
1503  * 0 on success, -errno on failure.
1504  */
1505 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1506 {
1507 	struct disk_part_tbl *old_ptbl =
1508 		rcu_dereference_protected(disk->part_tbl, 1);
1509 	struct disk_part_tbl *new_ptbl;
1510 	int len = old_ptbl ? old_ptbl->len : 0;
1511 	int i, target;
1512 
1513 	/*
1514 	 * check for int overflow, since we can get here from blkpg_ioctl()
1515 	 * with a user passed 'partno'.
1516 	 */
1517 	target = partno + 1;
1518 	if (target < 0)
1519 		return -EINVAL;
1520 
1521 	/* disk_max_parts() is zero during initialization, ignore if so */
1522 	if (disk_max_parts(disk) && target > disk_max_parts(disk))
1523 		return -EINVAL;
1524 
1525 	if (target <= len)
1526 		return 0;
1527 
1528 	new_ptbl = kzalloc_node(struct_size(new_ptbl, part, target), GFP_KERNEL,
1529 				disk->node_id);
1530 	if (!new_ptbl)
1531 		return -ENOMEM;
1532 
1533 	new_ptbl->len = target;
1534 
1535 	for (i = 0; i < len; i++)
1536 		rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1537 
1538 	disk_replace_part_tbl(disk, new_ptbl);
1539 	return 0;
1540 }
1541 
1542 /**
1543  * disk_release - releases all allocated resources of the gendisk
1544  * @dev: the device representing this disk
1545  *
1546  * This function releases all allocated resources of the gendisk.
1547  *
1548  * The struct gendisk refcount is incremented with get_gendisk() or
1549  * get_disk_and_module(), and its refcount is decremented with
1550  * put_disk_and_module() or put_disk(). Once the refcount reaches 0 this
1551  * function is called.
1552  *
1553  * Drivers which used __device_add_disk() have a gendisk with a request_queue
1554  * assigned. Since the request_queue sits on top of the gendisk for these
1555  * drivers we also call blk_put_queue() for them, and we expect the
1556  * request_queue refcount to reach 0 at this point, and so the request_queue
1557  * will also be freed prior to the disk.
1558  *
1559  * Context: can sleep
1560  */
1561 static void disk_release(struct device *dev)
1562 {
1563 	struct gendisk *disk = dev_to_disk(dev);
1564 
1565 	might_sleep();
1566 
1567 	blk_free_devt(dev->devt);
1568 	disk_release_events(disk);
1569 	kfree(disk->random);
1570 	disk_replace_part_tbl(disk, NULL);
1571 	hd_free_part(&disk->part0);
1572 	if (disk->queue)
1573 		blk_put_queue(disk->queue);
1574 	kfree(disk);
1575 }
1576 struct class block_class = {
1577 	.name		= "block",
1578 };
1579 
1580 static char *block_devnode(struct device *dev, umode_t *mode,
1581 			   kuid_t *uid, kgid_t *gid)
1582 {
1583 	struct gendisk *disk = dev_to_disk(dev);
1584 
1585 	if (disk->fops->devnode)
1586 		return disk->fops->devnode(disk, mode);
1587 	return NULL;
1588 }
1589 
1590 static const struct device_type disk_type = {
1591 	.name		= "disk",
1592 	.groups		= disk_attr_groups,
1593 	.release	= disk_release,
1594 	.devnode	= block_devnode,
1595 };
1596 
1597 #ifdef CONFIG_PROC_FS
1598 /*
1599  * aggregate disk stat collector.  Uses the same stats that the sysfs
1600  * entries do, above, but makes them available through one seq_file.
1601  *
1602  * The output looks suspiciously like /proc/partitions with a bunch of
1603  * extra fields.
1604  */
1605 static int diskstats_show(struct seq_file *seqf, void *v)
1606 {
1607 	struct gendisk *gp = v;
1608 	struct disk_part_iter piter;
1609 	struct hd_struct *hd;
1610 	char buf[BDEVNAME_SIZE];
1611 	unsigned int inflight;
1612 	struct disk_stats stat;
1613 
1614 	/*
1615 	if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1616 		seq_puts(seqf,	"major minor name"
1617 				"     rio rmerge rsect ruse wio wmerge "
1618 				"wsect wuse running use aveq"
1619 				"\n\n");
1620 	*/
1621 
1622 	disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1623 	while ((hd = disk_part_iter_next(&piter))) {
1624 		part_stat_read_all(hd, &stat);
1625 		if (queue_is_mq(gp->queue))
1626 			inflight = blk_mq_in_flight(gp->queue, hd);
1627 		else
1628 			inflight = part_in_flight(gp->queue, hd);
1629 
1630 		seq_printf(seqf, "%4d %7d %s "
1631 			   "%lu %lu %lu %u "
1632 			   "%lu %lu %lu %u "
1633 			   "%u %u %u "
1634 			   "%lu %lu %lu %u "
1635 			   "%lu %u"
1636 			   "\n",
1637 			   MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1638 			   disk_name(gp, hd->partno, buf),
1639 			   stat.ios[STAT_READ],
1640 			   stat.merges[STAT_READ],
1641 			   stat.sectors[STAT_READ],
1642 			   (unsigned int)div_u64(stat.nsecs[STAT_READ],
1643 							NSEC_PER_MSEC),
1644 			   stat.ios[STAT_WRITE],
1645 			   stat.merges[STAT_WRITE],
1646 			   stat.sectors[STAT_WRITE],
1647 			   (unsigned int)div_u64(stat.nsecs[STAT_WRITE],
1648 							NSEC_PER_MSEC),
1649 			   inflight,
1650 			   jiffies_to_msecs(stat.io_ticks),
1651 			   (unsigned int)div_u64(stat.nsecs[STAT_READ] +
1652 						 stat.nsecs[STAT_WRITE] +
1653 						 stat.nsecs[STAT_DISCARD] +
1654 						 stat.nsecs[STAT_FLUSH],
1655 							NSEC_PER_MSEC),
1656 			   stat.ios[STAT_DISCARD],
1657 			   stat.merges[STAT_DISCARD],
1658 			   stat.sectors[STAT_DISCARD],
1659 			   (unsigned int)div_u64(stat.nsecs[STAT_DISCARD],
1660 						 NSEC_PER_MSEC),
1661 			   stat.ios[STAT_FLUSH],
1662 			   (unsigned int)div_u64(stat.nsecs[STAT_FLUSH],
1663 						 NSEC_PER_MSEC)
1664 			);
1665 	}
1666 	disk_part_iter_exit(&piter);
1667 
1668 	return 0;
1669 }
1670 
1671 static const struct seq_operations diskstats_op = {
1672 	.start	= disk_seqf_start,
1673 	.next	= disk_seqf_next,
1674 	.stop	= disk_seqf_stop,
1675 	.show	= diskstats_show
1676 };
1677 
1678 static int __init proc_genhd_init(void)
1679 {
1680 	proc_create_seq("diskstats", 0, NULL, &diskstats_op);
1681 	proc_create_seq("partitions", 0, NULL, &partitions_op);
1682 	return 0;
1683 }
1684 module_init(proc_genhd_init);
1685 #endif /* CONFIG_PROC_FS */
1686 
1687 dev_t blk_lookup_devt(const char *name, int partno)
1688 {
1689 	dev_t devt = MKDEV(0, 0);
1690 	struct class_dev_iter iter;
1691 	struct device *dev;
1692 
1693 	class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1694 	while ((dev = class_dev_iter_next(&iter))) {
1695 		struct gendisk *disk = dev_to_disk(dev);
1696 		struct hd_struct *part;
1697 
1698 		if (strcmp(dev_name(dev), name))
1699 			continue;
1700 
1701 		if (partno < disk->minors) {
1702 			/* We need to return the right devno, even
1703 			 * if the partition doesn't exist yet.
1704 			 */
1705 			devt = MKDEV(MAJOR(dev->devt),
1706 				     MINOR(dev->devt) + partno);
1707 			break;
1708 		}
1709 		part = disk_get_part(disk, partno);
1710 		if (part) {
1711 			devt = part_devt(part);
1712 			disk_put_part(part);
1713 			break;
1714 		}
1715 		disk_put_part(part);
1716 	}
1717 	class_dev_iter_exit(&iter);
1718 	return devt;
1719 }
1720 
1721 struct gendisk *__alloc_disk_node(int minors, int node_id)
1722 {
1723 	struct gendisk *disk;
1724 	struct disk_part_tbl *ptbl;
1725 
1726 	if (minors > DISK_MAX_PARTS) {
1727 		printk(KERN_ERR
1728 			"block: can't allocate more than %d partitions\n",
1729 			DISK_MAX_PARTS);
1730 		minors = DISK_MAX_PARTS;
1731 	}
1732 
1733 	disk = kzalloc_node(sizeof(struct gendisk), GFP_KERNEL, node_id);
1734 	if (disk) {
1735 		disk->part0.dkstats = alloc_percpu(struct disk_stats);
1736 		if (!disk->part0.dkstats) {
1737 			kfree(disk);
1738 			return NULL;
1739 		}
1740 		init_rwsem(&disk->lookup_sem);
1741 		disk->node_id = node_id;
1742 		if (disk_expand_part_tbl(disk, 0)) {
1743 			free_percpu(disk->part0.dkstats);
1744 			kfree(disk);
1745 			return NULL;
1746 		}
1747 		ptbl = rcu_dereference_protected(disk->part_tbl, 1);
1748 		rcu_assign_pointer(ptbl->part[0], &disk->part0);
1749 
1750 		/*
1751 		 * set_capacity() and get_capacity() currently don't use
1752 		 * seqcounter to read/update the part0->nr_sects. Still init
1753 		 * the counter as we can read the sectors in IO submission
1754 		 * patch using seqence counters.
1755 		 *
1756 		 * TODO: Ideally set_capacity() and get_capacity() should be
1757 		 * converted to make use of bd_mutex and sequence counters.
1758 		 */
1759 		hd_sects_seq_init(&disk->part0);
1760 		if (hd_ref_init(&disk->part0)) {
1761 			hd_free_part(&disk->part0);
1762 			kfree(disk);
1763 			return NULL;
1764 		}
1765 
1766 		disk->minors = minors;
1767 		rand_initialize_disk(disk);
1768 		disk_to_dev(disk)->class = &block_class;
1769 		disk_to_dev(disk)->type = &disk_type;
1770 		device_initialize(disk_to_dev(disk));
1771 	}
1772 	return disk;
1773 }
1774 EXPORT_SYMBOL(__alloc_disk_node);
1775 
1776 /**
1777  * get_disk_and_module - increments the gendisk and gendisk fops module refcount
1778  * @disk: the struct gendisk to to increment the refcount for
1779  *
1780  * This increments the refcount for the struct gendisk, and the gendisk's
1781  * fops module owner.
1782  *
1783  * Context: Any context.
1784  */
1785 struct kobject *get_disk_and_module(struct gendisk *disk)
1786 {
1787 	struct module *owner;
1788 	struct kobject *kobj;
1789 
1790 	if (!disk->fops)
1791 		return NULL;
1792 	owner = disk->fops->owner;
1793 	if (owner && !try_module_get(owner))
1794 		return NULL;
1795 	kobj = kobject_get_unless_zero(&disk_to_dev(disk)->kobj);
1796 	if (kobj == NULL) {
1797 		module_put(owner);
1798 		return NULL;
1799 	}
1800 	return kobj;
1801 
1802 }
1803 EXPORT_SYMBOL(get_disk_and_module);
1804 
1805 /**
1806  * put_disk - decrements the gendisk refcount
1807  * @disk: the struct gendisk to to decrement the refcount for
1808  *
1809  * This decrements the refcount for the struct gendisk. When this reaches 0
1810  * we'll have disk_release() called.
1811  *
1812  * Context: Any context, but the last reference must not be dropped from
1813  *          atomic context.
1814  */
1815 void put_disk(struct gendisk *disk)
1816 {
1817 	if (disk)
1818 		kobject_put(&disk_to_dev(disk)->kobj);
1819 }
1820 EXPORT_SYMBOL(put_disk);
1821 
1822 /**
1823  * put_disk_and_module - decrements the module and gendisk refcount
1824  * @disk: the struct gendisk to to decrement the refcount for
1825  *
1826  * This is a counterpart of get_disk_and_module() and thus also of
1827  * get_gendisk().
1828  *
1829  * Context: Any context, but the last reference must not be dropped from
1830  *          atomic context.
1831  */
1832 void put_disk_and_module(struct gendisk *disk)
1833 {
1834 	if (disk) {
1835 		struct module *owner = disk->fops->owner;
1836 
1837 		put_disk(disk);
1838 		module_put(owner);
1839 	}
1840 }
1841 EXPORT_SYMBOL(put_disk_and_module);
1842 
1843 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1844 {
1845 	char event[] = "DISK_RO=1";
1846 	char *envp[] = { event, NULL };
1847 
1848 	if (!ro)
1849 		event[8] = '0';
1850 	kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1851 }
1852 
1853 void set_device_ro(struct block_device *bdev, int flag)
1854 {
1855 	bdev->bd_part->policy = flag;
1856 }
1857 
1858 EXPORT_SYMBOL(set_device_ro);
1859 
1860 void set_disk_ro(struct gendisk *disk, int flag)
1861 {
1862 	struct disk_part_iter piter;
1863 	struct hd_struct *part;
1864 
1865 	if (disk->part0.policy != flag) {
1866 		set_disk_ro_uevent(disk, flag);
1867 		disk->part0.policy = flag;
1868 	}
1869 
1870 	disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1871 	while ((part = disk_part_iter_next(&piter)))
1872 		part->policy = flag;
1873 	disk_part_iter_exit(&piter);
1874 }
1875 
1876 EXPORT_SYMBOL(set_disk_ro);
1877 
1878 int bdev_read_only(struct block_device *bdev)
1879 {
1880 	if (!bdev)
1881 		return 0;
1882 	return bdev->bd_part->policy;
1883 }
1884 
1885 EXPORT_SYMBOL(bdev_read_only);
1886 
1887 /*
1888  * Disk events - monitor disk events like media change and eject request.
1889  */
1890 struct disk_events {
1891 	struct list_head	node;		/* all disk_event's */
1892 	struct gendisk		*disk;		/* the associated disk */
1893 	spinlock_t		lock;
1894 
1895 	struct mutex		block_mutex;	/* protects blocking */
1896 	int			block;		/* event blocking depth */
1897 	unsigned int		pending;	/* events already sent out */
1898 	unsigned int		clearing;	/* events being cleared */
1899 
1900 	long			poll_msecs;	/* interval, -1 for default */
1901 	struct delayed_work	dwork;
1902 };
1903 
1904 static const char *disk_events_strs[] = {
1905 	[ilog2(DISK_EVENT_MEDIA_CHANGE)]	= "media_change",
1906 	[ilog2(DISK_EVENT_EJECT_REQUEST)]	= "eject_request",
1907 };
1908 
1909 static char *disk_uevents[] = {
1910 	[ilog2(DISK_EVENT_MEDIA_CHANGE)]	= "DISK_MEDIA_CHANGE=1",
1911 	[ilog2(DISK_EVENT_EJECT_REQUEST)]	= "DISK_EJECT_REQUEST=1",
1912 };
1913 
1914 /* list of all disk_events */
1915 static DEFINE_MUTEX(disk_events_mutex);
1916 static LIST_HEAD(disk_events);
1917 
1918 /* disable in-kernel polling by default */
1919 static unsigned long disk_events_dfl_poll_msecs;
1920 
1921 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
1922 {
1923 	struct disk_events *ev = disk->ev;
1924 	long intv_msecs = 0;
1925 
1926 	/*
1927 	 * If device-specific poll interval is set, always use it.  If
1928 	 * the default is being used, poll if the POLL flag is set.
1929 	 */
1930 	if (ev->poll_msecs >= 0)
1931 		intv_msecs = ev->poll_msecs;
1932 	else if (disk->event_flags & DISK_EVENT_FLAG_POLL)
1933 		intv_msecs = disk_events_dfl_poll_msecs;
1934 
1935 	return msecs_to_jiffies(intv_msecs);
1936 }
1937 
1938 /**
1939  * disk_block_events - block and flush disk event checking
1940  * @disk: disk to block events for
1941  *
1942  * On return from this function, it is guaranteed that event checking
1943  * isn't in progress and won't happen until unblocked by
1944  * disk_unblock_events().  Events blocking is counted and the actual
1945  * unblocking happens after the matching number of unblocks are done.
1946  *
1947  * Note that this intentionally does not block event checking from
1948  * disk_clear_events().
1949  *
1950  * CONTEXT:
1951  * Might sleep.
1952  */
1953 void disk_block_events(struct gendisk *disk)
1954 {
1955 	struct disk_events *ev = disk->ev;
1956 	unsigned long flags;
1957 	bool cancel;
1958 
1959 	if (!ev)
1960 		return;
1961 
1962 	/*
1963 	 * Outer mutex ensures that the first blocker completes canceling
1964 	 * the event work before further blockers are allowed to finish.
1965 	 */
1966 	mutex_lock(&ev->block_mutex);
1967 
1968 	spin_lock_irqsave(&ev->lock, flags);
1969 	cancel = !ev->block++;
1970 	spin_unlock_irqrestore(&ev->lock, flags);
1971 
1972 	if (cancel)
1973 		cancel_delayed_work_sync(&disk->ev->dwork);
1974 
1975 	mutex_unlock(&ev->block_mutex);
1976 }
1977 
1978 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
1979 {
1980 	struct disk_events *ev = disk->ev;
1981 	unsigned long intv;
1982 	unsigned long flags;
1983 
1984 	spin_lock_irqsave(&ev->lock, flags);
1985 
1986 	if (WARN_ON_ONCE(ev->block <= 0))
1987 		goto out_unlock;
1988 
1989 	if (--ev->block)
1990 		goto out_unlock;
1991 
1992 	intv = disk_events_poll_jiffies(disk);
1993 	if (check_now)
1994 		queue_delayed_work(system_freezable_power_efficient_wq,
1995 				&ev->dwork, 0);
1996 	else if (intv)
1997 		queue_delayed_work(system_freezable_power_efficient_wq,
1998 				&ev->dwork, intv);
1999 out_unlock:
2000 	spin_unlock_irqrestore(&ev->lock, flags);
2001 }
2002 
2003 /**
2004  * disk_unblock_events - unblock disk event checking
2005  * @disk: disk to unblock events for
2006  *
2007  * Undo disk_block_events().  When the block count reaches zero, it
2008  * starts events polling if configured.
2009  *
2010  * CONTEXT:
2011  * Don't care.  Safe to call from irq context.
2012  */
2013 void disk_unblock_events(struct gendisk *disk)
2014 {
2015 	if (disk->ev)
2016 		__disk_unblock_events(disk, false);
2017 }
2018 
2019 /**
2020  * disk_flush_events - schedule immediate event checking and flushing
2021  * @disk: disk to check and flush events for
2022  * @mask: events to flush
2023  *
2024  * Schedule immediate event checking on @disk if not blocked.  Events in
2025  * @mask are scheduled to be cleared from the driver.  Note that this
2026  * doesn't clear the events from @disk->ev.
2027  *
2028  * CONTEXT:
2029  * If @mask is non-zero must be called with bdev->bd_mutex held.
2030  */
2031 void disk_flush_events(struct gendisk *disk, unsigned int mask)
2032 {
2033 	struct disk_events *ev = disk->ev;
2034 
2035 	if (!ev)
2036 		return;
2037 
2038 	spin_lock_irq(&ev->lock);
2039 	ev->clearing |= mask;
2040 	if (!ev->block)
2041 		mod_delayed_work(system_freezable_power_efficient_wq,
2042 				&ev->dwork, 0);
2043 	spin_unlock_irq(&ev->lock);
2044 }
2045 
2046 /**
2047  * disk_clear_events - synchronously check, clear and return pending events
2048  * @disk: disk to fetch and clear events from
2049  * @mask: mask of events to be fetched and cleared
2050  *
2051  * Disk events are synchronously checked and pending events in @mask
2052  * are cleared and returned.  This ignores the block count.
2053  *
2054  * CONTEXT:
2055  * Might sleep.
2056  */
2057 unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
2058 {
2059 	struct disk_events *ev = disk->ev;
2060 	unsigned int pending;
2061 	unsigned int clearing = mask;
2062 
2063 	if (!ev)
2064 		return 0;
2065 
2066 	disk_block_events(disk);
2067 
2068 	/*
2069 	 * store the union of mask and ev->clearing on the stack so that the
2070 	 * race with disk_flush_events does not cause ambiguity (ev->clearing
2071 	 * can still be modified even if events are blocked).
2072 	 */
2073 	spin_lock_irq(&ev->lock);
2074 	clearing |= ev->clearing;
2075 	ev->clearing = 0;
2076 	spin_unlock_irq(&ev->lock);
2077 
2078 	disk_check_events(ev, &clearing);
2079 	/*
2080 	 * if ev->clearing is not 0, the disk_flush_events got called in the
2081 	 * middle of this function, so we want to run the workfn without delay.
2082 	 */
2083 	__disk_unblock_events(disk, ev->clearing ? true : false);
2084 
2085 	/* then, fetch and clear pending events */
2086 	spin_lock_irq(&ev->lock);
2087 	pending = ev->pending & mask;
2088 	ev->pending &= ~mask;
2089 	spin_unlock_irq(&ev->lock);
2090 	WARN_ON_ONCE(clearing & mask);
2091 
2092 	return pending;
2093 }
2094 
2095 /*
2096  * Separate this part out so that a different pointer for clearing_ptr can be
2097  * passed in for disk_clear_events.
2098  */
2099 static void disk_events_workfn(struct work_struct *work)
2100 {
2101 	struct delayed_work *dwork = to_delayed_work(work);
2102 	struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
2103 
2104 	disk_check_events(ev, &ev->clearing);
2105 }
2106 
2107 static void disk_check_events(struct disk_events *ev,
2108 			      unsigned int *clearing_ptr)
2109 {
2110 	struct gendisk *disk = ev->disk;
2111 	char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
2112 	unsigned int clearing = *clearing_ptr;
2113 	unsigned int events;
2114 	unsigned long intv;
2115 	int nr_events = 0, i;
2116 
2117 	/* check events */
2118 	events = disk->fops->check_events(disk, clearing);
2119 
2120 	/* accumulate pending events and schedule next poll if necessary */
2121 	spin_lock_irq(&ev->lock);
2122 
2123 	events &= ~ev->pending;
2124 	ev->pending |= events;
2125 	*clearing_ptr &= ~clearing;
2126 
2127 	intv = disk_events_poll_jiffies(disk);
2128 	if (!ev->block && intv)
2129 		queue_delayed_work(system_freezable_power_efficient_wq,
2130 				&ev->dwork, intv);
2131 
2132 	spin_unlock_irq(&ev->lock);
2133 
2134 	/*
2135 	 * Tell userland about new events.  Only the events listed in
2136 	 * @disk->events are reported, and only if DISK_EVENT_FLAG_UEVENT
2137 	 * is set. Otherwise, events are processed internally but never
2138 	 * get reported to userland.
2139 	 */
2140 	for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
2141 		if ((events & disk->events & (1 << i)) &&
2142 		    (disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2143 			envp[nr_events++] = disk_uevents[i];
2144 
2145 	if (nr_events)
2146 		kobject_uevent_env(&disk_to_dev(disk)->kobj, KOBJ_CHANGE, envp);
2147 }
2148 
2149 /*
2150  * A disk events enabled device has the following sysfs nodes under
2151  * its /sys/block/X/ directory.
2152  *
2153  * events		: list of all supported events
2154  * events_async		: list of events which can be detected w/o polling
2155  *			  (always empty, only for backwards compatibility)
2156  * events_poll_msecs	: polling interval, 0: disable, -1: system default
2157  */
2158 static ssize_t __disk_events_show(unsigned int events, char *buf)
2159 {
2160 	const char *delim = "";
2161 	ssize_t pos = 0;
2162 	int i;
2163 
2164 	for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
2165 		if (events & (1 << i)) {
2166 			pos += sprintf(buf + pos, "%s%s",
2167 				       delim, disk_events_strs[i]);
2168 			delim = " ";
2169 		}
2170 	if (pos)
2171 		pos += sprintf(buf + pos, "\n");
2172 	return pos;
2173 }
2174 
2175 static ssize_t disk_events_show(struct device *dev,
2176 				struct device_attribute *attr, char *buf)
2177 {
2178 	struct gendisk *disk = dev_to_disk(dev);
2179 
2180 	if (!(disk->event_flags & DISK_EVENT_FLAG_UEVENT))
2181 		return 0;
2182 
2183 	return __disk_events_show(disk->events, buf);
2184 }
2185 
2186 static ssize_t disk_events_async_show(struct device *dev,
2187 				      struct device_attribute *attr, char *buf)
2188 {
2189 	return 0;
2190 }
2191 
2192 static ssize_t disk_events_poll_msecs_show(struct device *dev,
2193 					   struct device_attribute *attr,
2194 					   char *buf)
2195 {
2196 	struct gendisk *disk = dev_to_disk(dev);
2197 
2198 	if (!disk->ev)
2199 		return sprintf(buf, "-1\n");
2200 
2201 	return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
2202 }
2203 
2204 static ssize_t disk_events_poll_msecs_store(struct device *dev,
2205 					    struct device_attribute *attr,
2206 					    const char *buf, size_t count)
2207 {
2208 	struct gendisk *disk = dev_to_disk(dev);
2209 	long intv;
2210 
2211 	if (!count || !sscanf(buf, "%ld", &intv))
2212 		return -EINVAL;
2213 
2214 	if (intv < 0 && intv != -1)
2215 		return -EINVAL;
2216 
2217 	if (!disk->ev)
2218 		return -ENODEV;
2219 
2220 	disk_block_events(disk);
2221 	disk->ev->poll_msecs = intv;
2222 	__disk_unblock_events(disk, true);
2223 
2224 	return count;
2225 }
2226 
2227 static const DEVICE_ATTR(events, 0444, disk_events_show, NULL);
2228 static const DEVICE_ATTR(events_async, 0444, disk_events_async_show, NULL);
2229 static const DEVICE_ATTR(events_poll_msecs, 0644,
2230 			 disk_events_poll_msecs_show,
2231 			 disk_events_poll_msecs_store);
2232 
2233 static const struct attribute *disk_events_attrs[] = {
2234 	&dev_attr_events.attr,
2235 	&dev_attr_events_async.attr,
2236 	&dev_attr_events_poll_msecs.attr,
2237 	NULL,
2238 };
2239 
2240 /*
2241  * The default polling interval can be specified by the kernel
2242  * parameter block.events_dfl_poll_msecs which defaults to 0
2243  * (disable).  This can also be modified runtime by writing to
2244  * /sys/module/block/parameters/events_dfl_poll_msecs.
2245  */
2246 static int disk_events_set_dfl_poll_msecs(const char *val,
2247 					  const struct kernel_param *kp)
2248 {
2249 	struct disk_events *ev;
2250 	int ret;
2251 
2252 	ret = param_set_ulong(val, kp);
2253 	if (ret < 0)
2254 		return ret;
2255 
2256 	mutex_lock(&disk_events_mutex);
2257 
2258 	list_for_each_entry(ev, &disk_events, node)
2259 		disk_flush_events(ev->disk, 0);
2260 
2261 	mutex_unlock(&disk_events_mutex);
2262 
2263 	return 0;
2264 }
2265 
2266 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
2267 	.set	= disk_events_set_dfl_poll_msecs,
2268 	.get	= param_get_ulong,
2269 };
2270 
2271 #undef MODULE_PARAM_PREFIX
2272 #define MODULE_PARAM_PREFIX	"block."
2273 
2274 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
2275 		&disk_events_dfl_poll_msecs, 0644);
2276 
2277 /*
2278  * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
2279  */
2280 static void disk_alloc_events(struct gendisk *disk)
2281 {
2282 	struct disk_events *ev;
2283 
2284 	if (!disk->fops->check_events || !disk->events)
2285 		return;
2286 
2287 	ev = kzalloc(sizeof(*ev), GFP_KERNEL);
2288 	if (!ev) {
2289 		pr_warn("%s: failed to initialize events\n", disk->disk_name);
2290 		return;
2291 	}
2292 
2293 	INIT_LIST_HEAD(&ev->node);
2294 	ev->disk = disk;
2295 	spin_lock_init(&ev->lock);
2296 	mutex_init(&ev->block_mutex);
2297 	ev->block = 1;
2298 	ev->poll_msecs = -1;
2299 	INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
2300 
2301 	disk->ev = ev;
2302 }
2303 
2304 static void disk_add_events(struct gendisk *disk)
2305 {
2306 	/* FIXME: error handling */
2307 	if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
2308 		pr_warn("%s: failed to create sysfs files for events\n",
2309 			disk->disk_name);
2310 
2311 	if (!disk->ev)
2312 		return;
2313 
2314 	mutex_lock(&disk_events_mutex);
2315 	list_add_tail(&disk->ev->node, &disk_events);
2316 	mutex_unlock(&disk_events_mutex);
2317 
2318 	/*
2319 	 * Block count is initialized to 1 and the following initial
2320 	 * unblock kicks it into action.
2321 	 */
2322 	__disk_unblock_events(disk, true);
2323 }
2324 
2325 static void disk_del_events(struct gendisk *disk)
2326 {
2327 	if (disk->ev) {
2328 		disk_block_events(disk);
2329 
2330 		mutex_lock(&disk_events_mutex);
2331 		list_del_init(&disk->ev->node);
2332 		mutex_unlock(&disk_events_mutex);
2333 	}
2334 
2335 	sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
2336 }
2337 
2338 static void disk_release_events(struct gendisk *disk)
2339 {
2340 	/* the block count should be 1 from disk_del_events() */
2341 	WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
2342 	kfree(disk->ev);
2343 }
2344