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