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