UPSTREAM: selinux: Remove unnecessary check of array base in selinux_set_mapping()
[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_bh(&ext_devt_lock);
432 idx = idr_alloc(&ext_devt_idr, part, 0, NR_EXT_DEVT, GFP_NOWAIT);
433 spin_unlock_bh(&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_bh(&ext_devt_lock);
459 idr_remove(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
460 spin_unlock_bh(&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 if (!sysfs_deprecated)
684 sysfs_remove_link(block_depr, dev_name(disk_to_dev(disk)));
685 pm_runtime_set_memalloc_noio(disk_to_dev(disk), false);
686 #ifdef CONFIG_BLOCK_SUPPORT_STLOG
687 dev = disk_to_dev(disk);
688 ST_LOG("<%s> KOBJ_REMOVE %d:%d %s",
689 __func__, MAJOR(dev->devt), MINOR(dev->devt), dev->kobj.name);
690 #endif
691
692 device_del(disk_to_dev(disk));
693 }
694 EXPORT_SYMBOL(del_gendisk);
695
696 /**
697 * get_gendisk - get partitioning information for a given device
698 * @devt: device to get partitioning information for
699 * @partno: returned partition index
700 *
701 * This function gets the structure containing partitioning
702 * information for the given device @devt.
703 */
704 struct gendisk *get_gendisk(dev_t devt, int *partno)
705 {
706 struct gendisk *disk = NULL;
707
708 if (MAJOR(devt) != BLOCK_EXT_MAJOR) {
709 struct kobject *kobj;
710
711 kobj = kobj_lookup(bdev_map, devt, partno);
712 if (kobj)
713 disk = dev_to_disk(kobj_to_dev(kobj));
714 } else {
715 struct hd_struct *part;
716
717 spin_lock_bh(&ext_devt_lock);
718 part = idr_find(&ext_devt_idr, blk_mangle_minor(MINOR(devt)));
719 if (part && get_disk(part_to_disk(part))) {
720 *partno = part->partno;
721 disk = part_to_disk(part);
722 }
723 spin_unlock_bh(&ext_devt_lock);
724 }
725
726 return disk;
727 }
728 EXPORT_SYMBOL(get_gendisk);
729
730 /**
731 * bdget_disk - do bdget() by gendisk and partition number
732 * @disk: gendisk of interest
733 * @partno: partition number
734 *
735 * Find partition @partno from @disk, do bdget() on it.
736 *
737 * CONTEXT:
738 * Don't care.
739 *
740 * RETURNS:
741 * Resulting block_device on success, NULL on failure.
742 */
743 struct block_device *bdget_disk(struct gendisk *disk, int partno)
744 {
745 struct hd_struct *part;
746 struct block_device *bdev = NULL;
747
748 part = disk_get_part(disk, partno);
749 if (part)
750 bdev = bdget(part_devt(part));
751 disk_put_part(part);
752
753 return bdev;
754 }
755 EXPORT_SYMBOL(bdget_disk);
756
757 /*
758 * print a full list of all partitions - intended for places where the root
759 * filesystem can't be mounted and thus to give the victim some idea of what
760 * went wrong
761 */
762 void __init printk_all_partitions(void)
763 {
764 struct class_dev_iter iter;
765 struct device *dev;
766
767 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
768 while ((dev = class_dev_iter_next(&iter))) {
769 struct gendisk *disk = dev_to_disk(dev);
770 struct disk_part_iter piter;
771 struct hd_struct *part;
772 char name_buf[BDEVNAME_SIZE];
773 char devt_buf[BDEVT_SIZE];
774
775 /*
776 * Don't show empty devices or things that have been
777 * suppressed
778 */
779 if (get_capacity(disk) == 0 ||
780 (disk->flags & GENHD_FL_SUPPRESS_PARTITION_INFO))
781 continue;
782
783 /*
784 * Note, unlike /proc/partitions, I am showing the
785 * numbers in hex - the same format as the root=
786 * option takes.
787 */
788 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_PART0);
789 while ((part = disk_part_iter_next(&piter))) {
790 bool is_part0 = part == &disk->part0;
791
792 printk("%s%s %10llu %s %s", is_part0 ? "" : " ",
793 bdevt_str(part_devt(part), devt_buf),
794 (unsigned long long)part_nr_sects_read(part) >> 1
795 , disk_name(disk, part->partno, name_buf),
796 part->info ? part->info->uuid : "");
797 if (is_part0) {
798 if (disk->driverfs_dev != NULL &&
799 disk->driverfs_dev->driver != NULL)
800 printk(" driver: %s\n",
801 disk->driverfs_dev->driver->name);
802 else
803 printk(" (driver?)\n");
804 } else
805 printk("\n");
806 }
807 disk_part_iter_exit(&piter);
808 }
809 class_dev_iter_exit(&iter);
810 }
811
812 #ifdef CONFIG_PROC_FS
813 /* iterator */
814 static void *disk_seqf_start(struct seq_file *seqf, loff_t *pos)
815 {
816 loff_t skip = *pos;
817 struct class_dev_iter *iter;
818 struct device *dev;
819
820 iter = kmalloc(sizeof(*iter), GFP_KERNEL);
821 if (!iter)
822 return ERR_PTR(-ENOMEM);
823
824 seqf->private = iter;
825 class_dev_iter_init(iter, &block_class, NULL, &disk_type);
826 do {
827 dev = class_dev_iter_next(iter);
828 if (!dev)
829 return NULL;
830 } while (skip--);
831
832 return dev_to_disk(dev);
833 }
834
835 static void *disk_seqf_next(struct seq_file *seqf, void *v, loff_t *pos)
836 {
837 struct device *dev;
838
839 (*pos)++;
840 dev = class_dev_iter_next(seqf->private);
841 if (dev)
842 return dev_to_disk(dev);
843
844 return NULL;
845 }
846
847 static void disk_seqf_stop(struct seq_file *seqf, void *v)
848 {
849 struct class_dev_iter *iter = seqf->private;
850
851 /* stop is called even after start failed :-( */
852 if (iter) {
853 class_dev_iter_exit(iter);
854 kfree(iter);
855 seqf->private = NULL;
856 }
857 }
858
859 static void *show_partition_start(struct seq_file *seqf, loff_t *pos)
860 {
861 void *p;
862
863 p = disk_seqf_start(seqf, pos);
864 if (!IS_ERR_OR_NULL(p) && !*pos)
865 seq_puts(seqf, "major minor #blocks name\n\n");
866 return p;
867 }
868
869 static int show_partition(struct seq_file *seqf, void *v)
870 {
871 struct gendisk *sgp = v;
872 struct disk_part_iter piter;
873 struct hd_struct *part;
874 char buf[BDEVNAME_SIZE];
875
876 /* Don't show non-partitionable removeable devices or empty devices */
877 if (!get_capacity(sgp) || (!disk_max_parts(sgp) &&
878 (sgp->flags & GENHD_FL_REMOVABLE)))
879 return 0;
880 if (sgp->flags & GENHD_FL_SUPPRESS_PARTITION_INFO)
881 return 0;
882
883 /* show the full disk and all non-0 size partitions of it */
884 disk_part_iter_init(&piter, sgp, DISK_PITER_INCL_PART0);
885 while ((part = disk_part_iter_next(&piter)))
886 seq_printf(seqf, "%4d %7d %10llu %s\n",
887 MAJOR(part_devt(part)), MINOR(part_devt(part)),
888 (unsigned long long)part_nr_sects_read(part) >> 1,
889 disk_name(sgp, part->partno, buf));
890 disk_part_iter_exit(&piter);
891
892 return 0;
893 }
894
895 static const struct seq_operations partitions_op = {
896 .start = show_partition_start,
897 .next = disk_seqf_next,
898 .stop = disk_seqf_stop,
899 .show = show_partition
900 };
901
902 static int partitions_open(struct inode *inode, struct file *file)
903 {
904 return seq_open(file, &partitions_op);
905 }
906
907 static const struct file_operations proc_partitions_operations = {
908 .open = partitions_open,
909 .read = seq_read,
910 .llseek = seq_lseek,
911 .release = seq_release,
912 };
913 #endif
914
915
916 static struct kobject *base_probe(dev_t devt, int *partno, void *data)
917 {
918 if (request_module("block-major-%d-%d", MAJOR(devt), MINOR(devt)) > 0)
919 /* Make old-style 2.4 aliases work */
920 request_module("block-major-%d", MAJOR(devt));
921 return NULL;
922 }
923
924 static int __init genhd_device_init(void)
925 {
926 int error;
927
928 block_class.dev_kobj = sysfs_dev_block_kobj;
929 error = class_register(&block_class);
930 if (unlikely(error))
931 return error;
932 bdev_map = kobj_map_init(base_probe, &block_class_lock);
933 blk_dev_init();
934
935 register_blkdev(BLOCK_EXT_MAJOR, "blkext");
936
937 /* create top-level block dir */
938 if (!sysfs_deprecated)
939 block_depr = kobject_create_and_add("block", NULL);
940 return 0;
941 }
942
943 subsys_initcall(genhd_device_init);
944
945 static ssize_t disk_range_show(struct device *dev,
946 struct device_attribute *attr, char *buf)
947 {
948 struct gendisk *disk = dev_to_disk(dev);
949
950 return sprintf(buf, "%d\n", disk->minors);
951 }
952
953 static ssize_t disk_ext_range_show(struct device *dev,
954 struct device_attribute *attr, char *buf)
955 {
956 struct gendisk *disk = dev_to_disk(dev);
957
958 return sprintf(buf, "%d\n", disk_max_parts(disk));
959 }
960
961 static ssize_t disk_removable_show(struct device *dev,
962 struct device_attribute *attr, char *buf)
963 {
964 struct gendisk *disk = dev_to_disk(dev);
965
966 return sprintf(buf, "%d\n",
967 (disk->flags & GENHD_FL_REMOVABLE ? 1 : 0));
968 }
969
970 static ssize_t disk_ro_show(struct device *dev,
971 struct device_attribute *attr, char *buf)
972 {
973 struct gendisk *disk = dev_to_disk(dev);
974
975 return sprintf(buf, "%d\n", get_disk_ro(disk) ? 1 : 0);
976 }
977
978 static ssize_t disk_capability_show(struct device *dev,
979 struct device_attribute *attr, char *buf)
980 {
981 struct gendisk *disk = dev_to_disk(dev);
982
983 return sprintf(buf, "%x\n", disk->flags);
984 }
985
986 static ssize_t disk_alignment_offset_show(struct device *dev,
987 struct device_attribute *attr,
988 char *buf)
989 {
990 struct gendisk *disk = dev_to_disk(dev);
991
992 return sprintf(buf, "%d\n", queue_alignment_offset(disk->queue));
993 }
994
995 static ssize_t disk_discard_alignment_show(struct device *dev,
996 struct device_attribute *attr,
997 char *buf)
998 {
999 struct gendisk *disk = dev_to_disk(dev);
1000
1001 return sprintf(buf, "%d\n", queue_discard_alignment(disk->queue));
1002 }
1003
1004 static DEVICE_ATTR(range, S_IRUGO, disk_range_show, NULL);
1005 static DEVICE_ATTR(ext_range, S_IRUGO, disk_ext_range_show, NULL);
1006 static DEVICE_ATTR(removable, S_IRUGO, disk_removable_show, NULL);
1007 static DEVICE_ATTR(ro, S_IRUGO, disk_ro_show, NULL);
1008 static DEVICE_ATTR(size, S_IRUGO, part_size_show, NULL);
1009 static DEVICE_ATTR(alignment_offset, S_IRUGO, disk_alignment_offset_show, NULL);
1010 static DEVICE_ATTR(discard_alignment, S_IRUGO, disk_discard_alignment_show,
1011 NULL);
1012 static DEVICE_ATTR(capability, S_IRUGO, disk_capability_show, NULL);
1013 static DEVICE_ATTR(stat, S_IRUGO, part_stat_show, NULL);
1014 static DEVICE_ATTR(inflight, S_IRUGO, part_inflight_show, NULL);
1015 #ifdef CONFIG_FAIL_MAKE_REQUEST
1016 static struct device_attribute dev_attr_fail =
1017 __ATTR(make-it-fail, S_IRUGO|S_IWUSR, part_fail_show, part_fail_store);
1018 #endif
1019 #ifdef CONFIG_FAIL_IO_TIMEOUT
1020 static struct device_attribute dev_attr_fail_timeout =
1021 __ATTR(io-timeout-fail, S_IRUGO|S_IWUSR, part_timeout_show,
1022 part_timeout_store);
1023 #endif
1024
1025 static struct attribute *disk_attrs[] = {
1026 &dev_attr_range.attr,
1027 &dev_attr_ext_range.attr,
1028 &dev_attr_removable.attr,
1029 &dev_attr_ro.attr,
1030 &dev_attr_size.attr,
1031 &dev_attr_alignment_offset.attr,
1032 &dev_attr_discard_alignment.attr,
1033 &dev_attr_capability.attr,
1034 &dev_attr_stat.attr,
1035 &dev_attr_inflight.attr,
1036 #ifdef CONFIG_FAIL_MAKE_REQUEST
1037 &dev_attr_fail.attr,
1038 #endif
1039 #ifdef CONFIG_FAIL_IO_TIMEOUT
1040 &dev_attr_fail_timeout.attr,
1041 #endif
1042 NULL
1043 };
1044
1045 static struct attribute_group disk_attr_group = {
1046 .attrs = disk_attrs,
1047 };
1048
1049 static const struct attribute_group *disk_attr_groups[] = {
1050 &disk_attr_group,
1051 NULL
1052 };
1053
1054 /**
1055 * disk_replace_part_tbl - replace disk->part_tbl in RCU-safe way
1056 * @disk: disk to replace part_tbl for
1057 * @new_ptbl: new part_tbl to install
1058 *
1059 * Replace disk->part_tbl with @new_ptbl in RCU-safe way. The
1060 * original ptbl is freed using RCU callback.
1061 *
1062 * LOCKING:
1063 * Matching bd_mutx locked.
1064 */
1065 static void disk_replace_part_tbl(struct gendisk *disk,
1066 struct disk_part_tbl *new_ptbl)
1067 {
1068 struct disk_part_tbl *old_ptbl = disk->part_tbl;
1069
1070 rcu_assign_pointer(disk->part_tbl, new_ptbl);
1071
1072 if (old_ptbl) {
1073 rcu_assign_pointer(old_ptbl->last_lookup, NULL);
1074 kfree_rcu(old_ptbl, rcu_head);
1075 }
1076 }
1077
1078 /**
1079 * disk_expand_part_tbl - expand disk->part_tbl
1080 * @disk: disk to expand part_tbl for
1081 * @partno: expand such that this partno can fit in
1082 *
1083 * Expand disk->part_tbl such that @partno can fit in. disk->part_tbl
1084 * uses RCU to allow unlocked dereferencing for stats and other stuff.
1085 *
1086 * LOCKING:
1087 * Matching bd_mutex locked, might sleep.
1088 *
1089 * RETURNS:
1090 * 0 on success, -errno on failure.
1091 */
1092 int disk_expand_part_tbl(struct gendisk *disk, int partno)
1093 {
1094 struct disk_part_tbl *old_ptbl = disk->part_tbl;
1095 struct disk_part_tbl *new_ptbl;
1096 int len = old_ptbl ? old_ptbl->len : 0;
1097 int i, target;
1098 size_t size;
1099
1100 /*
1101 * check for int overflow, since we can get here from blkpg_ioctl()
1102 * with a user passed 'partno'.
1103 */
1104 target = partno + 1;
1105 if (target < 0)
1106 return -EINVAL;
1107
1108 /* disk_max_parts() is zero during initialization, ignore if so */
1109 if (disk_max_parts(disk) && target > disk_max_parts(disk))
1110 return -EINVAL;
1111
1112 if (target <= len)
1113 return 0;
1114
1115 size = sizeof(*new_ptbl) + target * sizeof(new_ptbl->part[0]);
1116 new_ptbl = kzalloc_node(size, GFP_KERNEL, disk->node_id);
1117 if (!new_ptbl)
1118 return -ENOMEM;
1119
1120 new_ptbl->len = target;
1121
1122 for (i = 0; i < len; i++)
1123 rcu_assign_pointer(new_ptbl->part[i], old_ptbl->part[i]);
1124
1125 disk_replace_part_tbl(disk, new_ptbl);
1126 return 0;
1127 }
1128
1129 static void disk_release(struct device *dev)
1130 {
1131 struct gendisk *disk = dev_to_disk(dev);
1132
1133 blk_free_devt(dev->devt);
1134 disk_release_events(disk);
1135 kfree(disk->random);
1136 disk_replace_part_tbl(disk, NULL);
1137 free_part_stats(&disk->part0);
1138 free_part_info(&disk->part0);
1139 if (disk->queue)
1140 blk_put_queue(disk->queue);
1141 kfree(disk);
1142 }
1143
1144 static int disk_uevent(struct device *dev, struct kobj_uevent_env *env)
1145 {
1146 struct gendisk *disk = dev_to_disk(dev);
1147 struct disk_part_iter piter;
1148 struct hd_struct *part;
1149 int cnt = 0;
1150
1151 disk_part_iter_init(&piter, disk, 0);
1152 while((part = disk_part_iter_next(&piter)))
1153 cnt++;
1154 disk_part_iter_exit(&piter);
1155 add_uevent_var(env, "NPARTS=%u", cnt);
1156 #ifdef CONFIG_USB_STORAGE_DETECT
1157 if (disk->flags & GENHD_FL_IF_USB) {
1158 add_uevent_var(env, "MEDIAPRST=%d",
1159 (disk->flags & GENHD_FL_MEDIA_PRESENT) ? 1 : 0);
1160 pr_info("%s %d, disk flag media_present=%d, cnt=%d\n",
1161 __func__, __LINE__,
1162 (disk->flags & GENHD_FL_MEDIA_PRESENT), cnt);
1163 }
1164 #endif
1165 return 0;
1166 }
1167
1168 struct class block_class = {
1169 .name = "block",
1170 };
1171
1172 static char *block_devnode(struct device *dev, umode_t *mode,
1173 kuid_t *uid, kgid_t *gid)
1174 {
1175 struct gendisk *disk = dev_to_disk(dev);
1176
1177 if (disk->devnode)
1178 return disk->devnode(disk, mode);
1179 return NULL;
1180 }
1181
1182 static struct device_type disk_type = {
1183 .name = "disk",
1184 .groups = disk_attr_groups,
1185 .release = disk_release,
1186 .devnode = block_devnode,
1187 .uevent = disk_uevent,
1188 };
1189
1190 #ifdef CONFIG_PROC_FS
1191 /*
1192 * aggregate disk stat collector. Uses the same stats that the sysfs
1193 * entries do, above, but makes them available through one seq_file.
1194 *
1195 * The output looks suspiciously like /proc/partitions with a bunch of
1196 * extra fields.
1197 */
1198 static int diskstats_show(struct seq_file *seqf, void *v)
1199 {
1200 struct gendisk *gp = v;
1201 struct disk_part_iter piter;
1202 struct hd_struct *hd;
1203 char buf[BDEVNAME_SIZE];
1204 int cpu;
1205
1206 /*
1207 if (&disk_to_dev(gp)->kobj.entry == block_class.devices.next)
1208 seq_puts(seqf, "major minor name"
1209 " rio rmerge rsect ruse wio wmerge "
1210 "wsect wuse running use aveq"
1211 "\n\n");
1212 */
1213
1214 disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1215 while ((hd = disk_part_iter_next(&piter))) {
1216 cpu = part_stat_lock();
1217 part_round_stats(cpu, hd);
1218 part_stat_unlock();
1219 seq_printf(seqf, "%4d %7d %s %lu %lu %lu "
1220 "%u %lu %lu %lu %u %u %u %u\n",
1221 MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1222 disk_name(gp, hd->partno, buf),
1223 part_stat_read(hd, ios[READ]),
1224 part_stat_read(hd, merges[READ]),
1225 part_stat_read(hd, sectors[READ]),
1226 jiffies_to_msecs(part_stat_read(hd, ticks[READ])),
1227 part_stat_read(hd, ios[WRITE]),
1228 part_stat_read(hd, merges[WRITE]),
1229 part_stat_read(hd, sectors[WRITE]),
1230 jiffies_to_msecs(part_stat_read(hd, ticks[WRITE])),
1231 part_in_flight(hd),
1232 jiffies_to_msecs(part_stat_read(hd, io_ticks)),
1233 jiffies_to_msecs(part_stat_read(hd, time_in_queue))
1234 );
1235 }
1236 disk_part_iter_exit(&piter);
1237
1238 return 0;
1239 }
1240
1241 static const struct seq_operations diskstats_op = {
1242 .start = disk_seqf_start,
1243 .next = disk_seqf_next,
1244 .stop = disk_seqf_stop,
1245 .show = diskstats_show
1246 };
1247
1248 static int diskstats_open(struct inode *inode, struct file *file)
1249 {
1250 return seq_open(file, &diskstats_op);
1251 }
1252
1253 static const struct file_operations proc_diskstats_operations = {
1254 .open = diskstats_open,
1255 .read = seq_read,
1256 .llseek = seq_lseek,
1257 .release = seq_release,
1258 };
1259
1260 #define PG2KB(x) ((unsigned long)((x) << (PAGE_SHIFT - 10)))
1261 static int iostats_show(struct seq_file *seqf, void *v)
1262 {
1263 struct gendisk *gp = v;
1264 struct disk_part_iter piter;
1265 struct hd_struct *hd;
1266 char buf[BDEVNAME_SIZE];
1267 int cpu;
1268 u64 uptime;
1269 unsigned long thresh = 0;
1270 unsigned long bg_thresh = 0;
1271 struct backing_dev_info *bdi;
1272 unsigned int nread, nwrite;
1273
1274 /* Enhanced diskstats for IOD V 2.2 */
1275 global_dirty_limits(&bg_thresh, &thresh);
1276
1277 disk_part_iter_init(&piter, gp, DISK_PITER_INCL_EMPTY_PART0);
1278 while ((hd = disk_part_iter_next(&piter))) {
1279 cpu = part_stat_lock();
1280 part_round_stats(cpu, hd);
1281 part_stat_unlock();
1282 uptime = ktime_to_ns(ktime_get());
1283 uptime /= 1000000; /* in ms */
1284 bdi = &gp->queue->backing_dev_info;
1285 nread = part_in_flight_read(hd);
1286 nwrite = part_in_flight_write(hd);
1287 seq_printf(seqf, "%4d %7d %s %lu %lu %lu %u "
1288 "%lu %lu %lu %u %u %u %u "
1289 /* added */
1290 "%lu %lu %lu %lu "
1291 "%u %llu %lu %lu %lu %u "
1292 "%lu.%03lu\n",
1293 MAJOR(part_devt(hd)), MINOR(part_devt(hd)),
1294 disk_name(gp, hd->partno, buf),
1295 part_stat_read(hd, ios[READ]),
1296 part_stat_read(hd, merges[READ]),
1297 part_stat_read(hd, sectors[READ]),
1298 jiffies_to_msecs(part_stat_read(hd, ticks[READ])),
1299
1300 part_stat_read(hd, ios[WRITE]),
1301 part_stat_read(hd, merges[WRITE]),
1302 part_stat_read(hd, sectors[WRITE]),
1303 jiffies_to_msecs(part_stat_read(hd, ticks[WRITE])),
1304 /*part_in_flight(hd),*/
1305 nread + nwrite,
1306 jiffies_to_msecs(part_stat_read(hd, io_ticks)),
1307 jiffies_to_msecs(part_stat_read(hd, time_in_queue)),
1308 /* followings are added */
1309 part_stat_read(hd, discard_ios),
1310 part_stat_read(hd, discard_sectors),
1311 part_stat_read(hd, flush_ios),
1312 gp->queue->flush_ios,
1313
1314 nread,
1315 gp->queue->in_flight_time / USEC_PER_MSEC,
1316 PG2KB(thresh),
1317 PG2KB(bdi->last_thresh),
1318 PG2KB(bdi->last_nr_dirty),
1319 jiffies_to_msecs(bdi->paused_total),
1320
1321 (unsigned long)(uptime / 1000),
1322 (unsigned long)(uptime % 1000)
1323 );
1324 }
1325 disk_part_iter_exit(&piter);
1326
1327 return 0;
1328 }
1329
1330 static const struct seq_operations iostats_op = {
1331 .start = disk_seqf_start,
1332 .next = disk_seqf_next,
1333 .stop = disk_seqf_stop,
1334 .show = iostats_show
1335 };
1336
1337 static int iostats_open(struct inode *inode, struct file *file)
1338 {
1339 return seq_open(file, &iostats_op);
1340 }
1341
1342 static const struct file_operations proc_iostats_operations = {
1343 .open = iostats_open,
1344 .read = seq_read,
1345 .llseek = seq_lseek,
1346 .release = seq_release,
1347 };
1348
1349 static int __init proc_genhd_init(void)
1350 {
1351 proc_create("iostats", 0, NULL, &proc_iostats_operations);
1352 proc_create("diskstats", 0, NULL, &proc_diskstats_operations);
1353 proc_create("partitions", 0, NULL, &proc_partitions_operations);
1354 return 0;
1355 }
1356 module_init(proc_genhd_init);
1357 #endif /* CONFIG_PROC_FS */
1358
1359 dev_t blk_lookup_devt(const char *name, int partno)
1360 {
1361 dev_t devt = MKDEV(0, 0);
1362 struct class_dev_iter iter;
1363 struct device *dev;
1364
1365 class_dev_iter_init(&iter, &block_class, NULL, &disk_type);
1366 while ((dev = class_dev_iter_next(&iter))) {
1367 struct gendisk *disk = dev_to_disk(dev);
1368 struct hd_struct *part;
1369
1370 if (strcmp(dev_name(dev), name))
1371 continue;
1372
1373 if (partno < disk->minors) {
1374 /* We need to return the right devno, even
1375 * if the partition doesn't exist yet.
1376 */
1377 devt = MKDEV(MAJOR(dev->devt),
1378 MINOR(dev->devt) + partno);
1379 break;
1380 }
1381 part = disk_get_part(disk, partno);
1382 if (part) {
1383 devt = part_devt(part);
1384 disk_put_part(part);
1385 break;
1386 }
1387 disk_put_part(part);
1388 }
1389 class_dev_iter_exit(&iter);
1390 return devt;
1391 }
1392 EXPORT_SYMBOL(blk_lookup_devt);
1393
1394 struct gendisk *alloc_disk(int minors)
1395 {
1396 return alloc_disk_node(minors, NUMA_NO_NODE);
1397 }
1398 EXPORT_SYMBOL(alloc_disk);
1399
1400 struct gendisk *alloc_disk_node(int minors, int node_id)
1401 {
1402 struct gendisk *disk;
1403
1404 disk = kmalloc_node(sizeof(struct gendisk),
1405 GFP_KERNEL | __GFP_ZERO, node_id);
1406 if (disk) {
1407 if (!init_part_stats(&disk->part0)) {
1408 kfree(disk);
1409 return NULL;
1410 }
1411 disk->node_id = node_id;
1412 if (disk_expand_part_tbl(disk, 0)) {
1413 free_part_stats(&disk->part0);
1414 kfree(disk);
1415 return NULL;
1416 }
1417 disk->part_tbl->part[0] = &disk->part0;
1418
1419 /*
1420 * set_capacity() and get_capacity() currently don't use
1421 * seqcounter to read/update the part0->nr_sects. Still init
1422 * the counter as we can read the sectors in IO submission
1423 * patch using seqence counters.
1424 *
1425 * TODO: Ideally set_capacity() and get_capacity() should be
1426 * converted to make use of bd_mutex and sequence counters.
1427 */
1428 seqcount_init(&disk->part0.nr_sects_seq);
1429 hd_ref_init(&disk->part0);
1430
1431 disk->minors = minors;
1432 rand_initialize_disk(disk);
1433 disk_to_dev(disk)->class = &block_class;
1434 disk_to_dev(disk)->type = &disk_type;
1435 device_initialize(disk_to_dev(disk));
1436 }
1437 return disk;
1438 }
1439 EXPORT_SYMBOL(alloc_disk_node);
1440
1441 struct kobject *get_disk(struct gendisk *disk)
1442 {
1443 struct module *owner;
1444 struct kobject *kobj;
1445
1446 if (!disk->fops)
1447 return NULL;
1448 owner = disk->fops->owner;
1449 if (owner && !try_module_get(owner))
1450 return NULL;
1451 kobj = kobject_get(&disk_to_dev(disk)->kobj);
1452 if (kobj == NULL) {
1453 module_put(owner);
1454 return NULL;
1455 }
1456 return kobj;
1457
1458 }
1459
1460 EXPORT_SYMBOL(get_disk);
1461
1462 void put_disk(struct gendisk *disk)
1463 {
1464 if (disk)
1465 kobject_put(&disk_to_dev(disk)->kobj);
1466 }
1467
1468 EXPORT_SYMBOL(put_disk);
1469
1470 static void set_disk_ro_uevent(struct gendisk *gd, int ro)
1471 {
1472 char event[] = "DISK_RO=1";
1473 char *envp[] = { event, NULL };
1474
1475 if (!ro)
1476 event[8] = '0';
1477 kobject_uevent_env(&disk_to_dev(gd)->kobj, KOBJ_CHANGE, envp);
1478 }
1479
1480 void set_device_ro(struct block_device *bdev, int flag)
1481 {
1482 bdev->bd_part->policy = flag;
1483 }
1484
1485 EXPORT_SYMBOL(set_device_ro);
1486
1487 void set_disk_ro(struct gendisk *disk, int flag)
1488 {
1489 struct disk_part_iter piter;
1490 struct hd_struct *part;
1491
1492 if (disk->part0.policy != flag) {
1493 set_disk_ro_uevent(disk, flag);
1494 disk->part0.policy = flag;
1495 }
1496
1497 disk_part_iter_init(&piter, disk, DISK_PITER_INCL_EMPTY);
1498 while ((part = disk_part_iter_next(&piter)))
1499 part->policy = flag;
1500 disk_part_iter_exit(&piter);
1501 }
1502
1503 EXPORT_SYMBOL(set_disk_ro);
1504
1505 int bdev_read_only(struct block_device *bdev)
1506 {
1507 if (!bdev)
1508 return 0;
1509 return bdev->bd_part->policy;
1510 }
1511
1512 EXPORT_SYMBOL(bdev_read_only);
1513
1514 int invalidate_partition(struct gendisk *disk, int partno)
1515 {
1516 int res = 0;
1517 struct block_device *bdev = bdget_disk(disk, partno);
1518 if (bdev) {
1519 fsync_bdev(bdev);
1520 res = __invalidate_device(bdev, true);
1521 bdput(bdev);
1522 }
1523 return res;
1524 }
1525
1526 EXPORT_SYMBOL(invalidate_partition);
1527
1528 /*
1529 * Disk events - monitor disk events like media change and eject request.
1530 */
1531 struct disk_events {
1532 struct list_head node; /* all disk_event's */
1533 struct gendisk *disk; /* the associated disk */
1534 spinlock_t lock;
1535
1536 struct mutex block_mutex; /* protects blocking */
1537 int block; /* event blocking depth */
1538 unsigned int pending; /* events already sent out */
1539 unsigned int clearing; /* events being cleared */
1540
1541 long poll_msecs; /* interval, -1 for default */
1542 struct delayed_work dwork;
1543 };
1544
1545 static const char *disk_events_strs[] = {
1546 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "media_change",
1547 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "eject_request",
1548 };
1549
1550 static char *disk_uevents[] = {
1551 [ilog2(DISK_EVENT_MEDIA_CHANGE)] = "DISK_MEDIA_CHANGE=1",
1552 [ilog2(DISK_EVENT_EJECT_REQUEST)] = "DISK_EJECT_REQUEST=1",
1553 };
1554
1555 /* list of all disk_events */
1556 static DEFINE_MUTEX(disk_events_mutex);
1557 static LIST_HEAD(disk_events);
1558
1559 /* disable in-kernel polling by default */
1560 static unsigned long disk_events_dfl_poll_msecs = 0;
1561
1562 static unsigned long disk_events_poll_jiffies(struct gendisk *disk)
1563 {
1564 struct disk_events *ev = disk->ev;
1565 long intv_msecs = 0;
1566
1567 /*
1568 * If device-specific poll interval is set, always use it. If
1569 * the default is being used, poll iff there are events which
1570 * can't be monitored asynchronously.
1571 */
1572 if (ev->poll_msecs >= 0)
1573 intv_msecs = ev->poll_msecs;
1574 else if (disk->events & ~disk->async_events)
1575 intv_msecs = disk_events_dfl_poll_msecs;
1576
1577 return msecs_to_jiffies(intv_msecs);
1578 }
1579
1580 /**
1581 * disk_block_events - block and flush disk event checking
1582 * @disk: disk to block events for
1583 *
1584 * On return from this function, it is guaranteed that event checking
1585 * isn't in progress and won't happen until unblocked by
1586 * disk_unblock_events(). Events blocking is counted and the actual
1587 * unblocking happens after the matching number of unblocks are done.
1588 *
1589 * Note that this intentionally does not block event checking from
1590 * disk_clear_events().
1591 *
1592 * CONTEXT:
1593 * Might sleep.
1594 */
1595 void disk_block_events(struct gendisk *disk)
1596 {
1597 struct disk_events *ev = disk->ev;
1598 unsigned long flags;
1599 bool cancel;
1600
1601 if (!ev)
1602 return;
1603
1604 /*
1605 * Outer mutex ensures that the first blocker completes canceling
1606 * the event work before further blockers are allowed to finish.
1607 */
1608 mutex_lock(&ev->block_mutex);
1609
1610 spin_lock_irqsave(&ev->lock, flags);
1611 cancel = !ev->block++;
1612 spin_unlock_irqrestore(&ev->lock, flags);
1613
1614 if (cancel)
1615 cancel_delayed_work_sync(&disk->ev->dwork);
1616
1617 mutex_unlock(&ev->block_mutex);
1618 }
1619
1620 static void __disk_unblock_events(struct gendisk *disk, bool check_now)
1621 {
1622 struct disk_events *ev = disk->ev;
1623 unsigned long intv;
1624 unsigned long flags;
1625
1626 spin_lock_irqsave(&ev->lock, flags);
1627
1628 if (WARN_ON_ONCE(ev->block <= 0))
1629 goto out_unlock;
1630
1631 if (--ev->block)
1632 goto out_unlock;
1633
1634 /*
1635 * Not exactly a latency critical operation, set poll timer
1636 * slack to 25% and kick event check.
1637 */
1638 intv = disk_events_poll_jiffies(disk);
1639 set_timer_slack(&ev->dwork.timer, intv / 4);
1640 if (check_now)
1641 queue_delayed_work(system_freezable_power_efficient_wq,
1642 &ev->dwork, 0);
1643 else if (intv)
1644 queue_delayed_work(system_freezable_power_efficient_wq,
1645 &ev->dwork, intv);
1646 out_unlock:
1647 spin_unlock_irqrestore(&ev->lock, flags);
1648 }
1649
1650 /**
1651 * disk_unblock_events - unblock disk event checking
1652 * @disk: disk to unblock events for
1653 *
1654 * Undo disk_block_events(). When the block count reaches zero, it
1655 * starts events polling if configured.
1656 *
1657 * CONTEXT:
1658 * Don't care. Safe to call from irq context.
1659 */
1660 void disk_unblock_events(struct gendisk *disk)
1661 {
1662 if (disk->ev)
1663 __disk_unblock_events(disk, false);
1664 }
1665
1666 /**
1667 * disk_flush_events - schedule immediate event checking and flushing
1668 * @disk: disk to check and flush events for
1669 * @mask: events to flush
1670 *
1671 * Schedule immediate event checking on @disk if not blocked. Events in
1672 * @mask are scheduled to be cleared from the driver. Note that this
1673 * doesn't clear the events from @disk->ev.
1674 *
1675 * CONTEXT:
1676 * If @mask is non-zero must be called with bdev->bd_mutex held.
1677 */
1678 void disk_flush_events(struct gendisk *disk, unsigned int mask)
1679 {
1680 struct disk_events *ev = disk->ev;
1681
1682 if (!ev)
1683 return;
1684
1685 spin_lock_irq(&ev->lock);
1686 ev->clearing |= mask;
1687 if (!ev->block)
1688 mod_delayed_work(system_freezable_power_efficient_wq,
1689 &ev->dwork, 0);
1690 spin_unlock_irq(&ev->lock);
1691 }
1692
1693 /**
1694 * disk_clear_events - synchronously check, clear and return pending events
1695 * @disk: disk to fetch and clear events from
1696 * @mask: mask of events to be fetched and clearted
1697 *
1698 * Disk events are synchronously checked and pending events in @mask
1699 * are cleared and returned. This ignores the block count.
1700 *
1701 * CONTEXT:
1702 * Might sleep.
1703 */
1704 unsigned int disk_clear_events(struct gendisk *disk, unsigned int mask)
1705 {
1706 const struct block_device_operations *bdops = disk->fops;
1707 struct disk_events *ev = disk->ev;
1708 unsigned int pending;
1709 unsigned int clearing = mask;
1710
1711 if (!ev) {
1712 /* for drivers still using the old ->media_changed method */
1713 if ((mask & DISK_EVENT_MEDIA_CHANGE) &&
1714 bdops->media_changed && bdops->media_changed(disk))
1715 return DISK_EVENT_MEDIA_CHANGE;
1716 return 0;
1717 }
1718
1719 disk_block_events(disk);
1720
1721 /*
1722 * store the union of mask and ev->clearing on the stack so that the
1723 * race with disk_flush_events does not cause ambiguity (ev->clearing
1724 * can still be modified even if events are blocked).
1725 */
1726 spin_lock_irq(&ev->lock);
1727 clearing |= ev->clearing;
1728 ev->clearing = 0;
1729 spin_unlock_irq(&ev->lock);
1730
1731 disk_check_events(ev, &clearing);
1732 /*
1733 * if ev->clearing is not 0, the disk_flush_events got called in the
1734 * middle of this function, so we want to run the workfn without delay.
1735 */
1736 __disk_unblock_events(disk, ev->clearing ? true : false);
1737
1738 /* then, fetch and clear pending events */
1739 spin_lock_irq(&ev->lock);
1740 pending = ev->pending & mask;
1741 ev->pending &= ~mask;
1742 spin_unlock_irq(&ev->lock);
1743 WARN_ON_ONCE(clearing & mask);
1744
1745 return pending;
1746 }
1747
1748 /*
1749 * Separate this part out so that a different pointer for clearing_ptr can be
1750 * passed in for disk_clear_events.
1751 */
1752 static void disk_events_workfn(struct work_struct *work)
1753 {
1754 struct delayed_work *dwork = to_delayed_work(work);
1755 struct disk_events *ev = container_of(dwork, struct disk_events, dwork);
1756
1757 disk_check_events(ev, &ev->clearing);
1758 }
1759
1760 static void disk_check_events(struct disk_events *ev,
1761 unsigned int *clearing_ptr)
1762 {
1763 struct gendisk *disk = ev->disk;
1764 char *envp[ARRAY_SIZE(disk_uevents) + 1] = { };
1765 unsigned int clearing = *clearing_ptr;
1766 unsigned int events;
1767 unsigned long intv;
1768 int nr_events = 0, i;
1769
1770 #ifdef CONFIG_USB_STORAGE_DETECT
1771 if (!(disk->flags & GENHD_FL_IF_USB))
1772 /* check events */
1773 events = disk->fops->check_events(disk, clearing);
1774 else
1775 events = 0;
1776 #else
1777 events = disk->fops->check_events(disk, clearing);
1778 #endif
1779
1780 /* accumulate pending events and schedule next poll if necessary */
1781 spin_lock_irq(&ev->lock);
1782
1783 events &= ~ev->pending;
1784 ev->pending |= events;
1785 *clearing_ptr &= ~clearing;
1786
1787 intv = disk_events_poll_jiffies(disk);
1788 if (!ev->block && intv)
1789 queue_delayed_work(system_freezable_power_efficient_wq,
1790 &ev->dwork, intv);
1791
1792 spin_unlock_irq(&ev->lock);
1793
1794 /*
1795 * Tell userland about new events. Only the events listed in
1796 * @disk->events are reported. Unlisted events are processed the
1797 * same internally but never get reported to userland.
1798 */
1799 for (i = 0; i < ARRAY_SIZE(disk_uevents); i++)
1800 if (events & disk->events & (1 << i))
1801 envp[nr_events++] = disk_uevents[i];
1802
1803 #ifdef CONFIG_USB_STORAGE_DETECT
1804 if (!(disk->flags & GENHD_FL_IF_USB)) {
1805 if (nr_events)
1806 kobject_uevent_env(&disk_to_dev(disk)->kobj,
1807 KOBJ_CHANGE, envp);
1808 }
1809 #else
1810 if (nr_events)
1811 kobject_uevent_env(&disk_to_dev(disk)->kobj,
1812 KOBJ_CHANGE, envp);
1813 #endif
1814 }
1815
1816 /*
1817 * A disk events enabled device has the following sysfs nodes under
1818 * its /sys/block/X/ directory.
1819 *
1820 * events : list of all supported events
1821 * events_async : list of events which can be detected w/o polling
1822 * events_poll_msecs : polling interval, 0: disable, -1: system default
1823 */
1824 static ssize_t __disk_events_show(unsigned int events, char *buf)
1825 {
1826 const char *delim = "";
1827 ssize_t pos = 0;
1828 int i;
1829
1830 for (i = 0; i < ARRAY_SIZE(disk_events_strs); i++)
1831 if (events & (1 << i)) {
1832 pos += sprintf(buf + pos, "%s%s",
1833 delim, disk_events_strs[i]);
1834 delim = " ";
1835 }
1836 if (pos)
1837 pos += sprintf(buf + pos, "\n");
1838 return pos;
1839 }
1840
1841 static ssize_t disk_events_show(struct device *dev,
1842 struct device_attribute *attr, char *buf)
1843 {
1844 struct gendisk *disk = dev_to_disk(dev);
1845
1846 return __disk_events_show(disk->events, buf);
1847 }
1848
1849 static ssize_t disk_events_async_show(struct device *dev,
1850 struct device_attribute *attr, char *buf)
1851 {
1852 struct gendisk *disk = dev_to_disk(dev);
1853
1854 return __disk_events_show(disk->async_events, buf);
1855 }
1856
1857 static ssize_t disk_events_poll_msecs_show(struct device *dev,
1858 struct device_attribute *attr,
1859 char *buf)
1860 {
1861 struct gendisk *disk = dev_to_disk(dev);
1862
1863 return sprintf(buf, "%ld\n", disk->ev->poll_msecs);
1864 }
1865
1866 static ssize_t disk_events_poll_msecs_store(struct device *dev,
1867 struct device_attribute *attr,
1868 const char *buf, size_t count)
1869 {
1870 struct gendisk *disk = dev_to_disk(dev);
1871 long intv;
1872
1873 if (!count || !sscanf(buf, "%ld", &intv))
1874 return -EINVAL;
1875
1876 if (intv < 0 && intv != -1)
1877 return -EINVAL;
1878
1879 disk_block_events(disk);
1880 disk->ev->poll_msecs = intv;
1881 __disk_unblock_events(disk, true);
1882
1883 return count;
1884 }
1885
1886 static const DEVICE_ATTR(events, S_IRUGO, disk_events_show, NULL);
1887 static const DEVICE_ATTR(events_async, S_IRUGO, disk_events_async_show, NULL);
1888 static const DEVICE_ATTR(events_poll_msecs, S_IRUGO|S_IWUSR,
1889 disk_events_poll_msecs_show,
1890 disk_events_poll_msecs_store);
1891
1892 static const struct attribute *disk_events_attrs[] = {
1893 &dev_attr_events.attr,
1894 &dev_attr_events_async.attr,
1895 &dev_attr_events_poll_msecs.attr,
1896 NULL,
1897 };
1898
1899 /*
1900 * The default polling interval can be specified by the kernel
1901 * parameter block.events_dfl_poll_msecs which defaults to 0
1902 * (disable). This can also be modified runtime by writing to
1903 * /sys/module/block/events_dfl_poll_msecs.
1904 */
1905 static int disk_events_set_dfl_poll_msecs(const char *val,
1906 const struct kernel_param *kp)
1907 {
1908 struct disk_events *ev;
1909 int ret;
1910
1911 ret = param_set_ulong(val, kp);
1912 if (ret < 0)
1913 return ret;
1914
1915 mutex_lock(&disk_events_mutex);
1916
1917 list_for_each_entry(ev, &disk_events, node)
1918 disk_flush_events(ev->disk, 0);
1919
1920 mutex_unlock(&disk_events_mutex);
1921
1922 return 0;
1923 }
1924
1925 static const struct kernel_param_ops disk_events_dfl_poll_msecs_param_ops = {
1926 .set = disk_events_set_dfl_poll_msecs,
1927 .get = param_get_ulong,
1928 };
1929
1930 #undef MODULE_PARAM_PREFIX
1931 #define MODULE_PARAM_PREFIX "block."
1932
1933 module_param_cb(events_dfl_poll_msecs, &disk_events_dfl_poll_msecs_param_ops,
1934 &disk_events_dfl_poll_msecs, 0644);
1935
1936 /*
1937 * disk_{alloc|add|del|release}_events - initialize and destroy disk_events.
1938 */
1939 static void disk_alloc_events(struct gendisk *disk)
1940 {
1941 struct disk_events *ev;
1942
1943 if (!disk->fops->check_events)
1944 return;
1945
1946 ev = kzalloc(sizeof(*ev), GFP_KERNEL);
1947 if (!ev) {
1948 pr_warn("%s: failed to initialize events\n", disk->disk_name);
1949 return;
1950 }
1951
1952 INIT_LIST_HEAD(&ev->node);
1953 ev->disk = disk;
1954 spin_lock_init(&ev->lock);
1955 mutex_init(&ev->block_mutex);
1956 ev->block = 1;
1957 ev->poll_msecs = -1;
1958 INIT_DELAYED_WORK(&ev->dwork, disk_events_workfn);
1959
1960 disk->ev = ev;
1961 }
1962
1963 static void disk_add_events(struct gendisk *disk)
1964 {
1965 if (!disk->ev)
1966 return;
1967
1968 /* FIXME: error handling */
1969 if (sysfs_create_files(&disk_to_dev(disk)->kobj, disk_events_attrs) < 0)
1970 pr_warn("%s: failed to create sysfs files for events\n",
1971 disk->disk_name);
1972
1973 mutex_lock(&disk_events_mutex);
1974 list_add_tail(&disk->ev->node, &disk_events);
1975 mutex_unlock(&disk_events_mutex);
1976
1977 /*
1978 * Block count is initialized to 1 and the following initial
1979 * unblock kicks it into action.
1980 */
1981 __disk_unblock_events(disk, true);
1982 }
1983
1984 static void disk_del_events(struct gendisk *disk)
1985 {
1986 if (!disk->ev)
1987 return;
1988
1989 disk_block_events(disk);
1990
1991 mutex_lock(&disk_events_mutex);
1992 list_del_init(&disk->ev->node);
1993 mutex_unlock(&disk_events_mutex);
1994
1995 sysfs_remove_files(&disk_to_dev(disk)->kobj, disk_events_attrs);
1996 }
1997
1998 static void disk_release_events(struct gendisk *disk)
1999 {
2000 /* the block count should be 1 from disk_del_events() */
2001 WARN_ON_ONCE(disk->ev && disk->ev->block != 1);
2002 kfree(disk->ev);
2003 }