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