brd: Support for BLKFLSBUF
[platform/kernel/linux-rpi.git] / drivers / block / brd.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Ram backed block device driver.
4  *
5  * Copyright (C) 2007 Nick Piggin
6  * Copyright (C) 2007 Novell Inc.
7  *
8  * Parts derived from drivers/block/rd.c, and drivers/block/loop.c, copyright
9  * of their respective owners.
10  */
11
12 #include <linux/init.h>
13 #include <linux/initrd.h>
14 #include <linux/module.h>
15 #include <linux/moduleparam.h>
16 #include <linux/major.h>
17 #include <linux/blkdev.h>
18 #include <linux/bio.h>
19 #include <linux/highmem.h>
20 #include <linux/mutex.h>
21 #include <linux/pagemap.h>
22 #include <linux/radix-tree.h>
23 #include <linux/fs.h>
24 #include <linux/slab.h>
25 #include <linux/backing-dev.h>
26 #include <linux/debugfs.h>
27
28 #include <linux/uaccess.h>
29
30 /*
31  * Each block ramdisk device has a radix_tree brd_pages of pages that stores
32  * the pages containing the block device's contents. A brd page's ->index is
33  * its offset in PAGE_SIZE units. This is similar to, but in no way connected
34  * with, the kernel's pagecache or buffer cache (which sit above our block
35  * device).
36  */
37 struct brd_device {
38         int                     brd_number;
39         struct gendisk          *brd_disk;
40         struct list_head        brd_list;
41
42         /*
43          * Backing store of pages and lock to protect it. This is the contents
44          * of the block device.
45          */
46         spinlock_t              brd_lock;
47         struct radix_tree_root  brd_pages;
48         u64                     brd_nr_pages;
49 };
50
51 /*
52  * Look up and return a brd's page for a given sector.
53  */
54 static struct page *brd_lookup_page(struct brd_device *brd, sector_t sector)
55 {
56         pgoff_t idx;
57         struct page *page;
58
59         /*
60          * The page lifetime is protected by the fact that we have opened the
61          * device node -- brd pages will never be deleted under us, so we
62          * don't need any further locking or refcounting.
63          *
64          * This is strictly true for the radix-tree nodes as well (ie. we
65          * don't actually need the rcu_read_lock()), however that is not a
66          * documented feature of the radix-tree API so it is better to be
67          * safe here (we don't have total exclusion from radix tree updates
68          * here, only deletes).
69          */
70         rcu_read_lock();
71         idx = sector >> PAGE_SECTORS_SHIFT; /* sector to page index */
72         page = radix_tree_lookup(&brd->brd_pages, idx);
73         rcu_read_unlock();
74
75         BUG_ON(page && page->index != idx);
76
77         return page;
78 }
79
80 /*
81  * Look up and return a brd's page for a given sector.
82  * If one does not exist, allocate an empty page, and insert that. Then
83  * return it.
84  */
85 static struct page *brd_insert_page(struct brd_device *brd, sector_t sector)
86 {
87         pgoff_t idx;
88         struct page *page;
89         gfp_t gfp_flags;
90
91         page = brd_lookup_page(brd, sector);
92         if (page)
93                 return page;
94
95         /*
96          * Must use NOIO because we don't want to recurse back into the
97          * block or filesystem layers from page reclaim.
98          */
99         gfp_flags = GFP_NOIO | __GFP_ZERO | __GFP_HIGHMEM;
100         page = alloc_page(gfp_flags);
101         if (!page)
102                 return NULL;
103
104         if (radix_tree_preload(GFP_NOIO)) {
105                 __free_page(page);
106                 return NULL;
107         }
108
109         spin_lock(&brd->brd_lock);
110         idx = sector >> PAGE_SECTORS_SHIFT;
111         page->index = idx;
112         if (radix_tree_insert(&brd->brd_pages, idx, page)) {
113                 __free_page(page);
114                 page = radix_tree_lookup(&brd->brd_pages, idx);
115                 BUG_ON(!page);
116                 BUG_ON(page->index != idx);
117         } else {
118                 brd->brd_nr_pages++;
119         }
120         spin_unlock(&brd->brd_lock);
121
122         radix_tree_preload_end();
123
124         return page;
125 }
126
127 static void brd_free_page(struct brd_device *brd, sector_t sector)
128 {
129         struct page *page;
130         pgoff_t idx;
131
132         spin_lock(&brd->brd_lock);
133         idx = sector >> PAGE_SECTORS_SHIFT;
134         page = radix_tree_delete(&brd->brd_pages, idx);
135         spin_unlock(&brd->brd_lock);
136         if (page)
137                 __free_page(page);
138 }
139
140 static void brd_zero_page(struct brd_device *brd, sector_t sector)
141 {
142         struct page *page;
143
144         page = brd_lookup_page(brd, sector);
145         if (page)
146                 clear_highpage(page);
147 }
148
149 /*
150  * Free all backing store pages and radix tree. This must only be called when
151  * there are no other users of the device.
152  */
153 #define FREE_BATCH 16
154 static void brd_free_pages(struct brd_device *brd)
155 {
156         unsigned long pos = 0;
157         struct page *pages[FREE_BATCH];
158         int nr_pages;
159
160         do {
161                 int i;
162
163                 nr_pages = radix_tree_gang_lookup(&brd->brd_pages,
164                                 (void **)pages, pos, FREE_BATCH);
165
166                 for (i = 0; i < nr_pages; i++) {
167                         void *ret;
168
169                         BUG_ON(pages[i]->index < pos);
170                         pos = pages[i]->index;
171                         ret = radix_tree_delete(&brd->brd_pages, pos);
172                         BUG_ON(!ret || ret != pages[i]);
173                         __free_page(pages[i]);
174                 }
175
176                 pos++;
177
178                 /*
179                  * It takes 3.4 seconds to remove 80GiB ramdisk.
180                  * So, we need cond_resched to avoid stalling the CPU.
181                  */
182                 cond_resched();
183
184                 /*
185                  * This assumes radix_tree_gang_lookup always returns as
186                  * many pages as possible. If the radix-tree code changes,
187                  * so will this have to.
188                  */
189         } while (nr_pages == FREE_BATCH);
190 }
191
192 /*
193  * copy_to_brd_setup must be called before copy_to_brd. It may sleep.
194  */
195 static int copy_to_brd_setup(struct brd_device *brd, sector_t sector, size_t n)
196 {
197         unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
198         size_t copy;
199
200         copy = min_t(size_t, n, PAGE_SIZE - offset);
201         if (!brd_insert_page(brd, sector))
202                 return -ENOSPC;
203         if (copy < n) {
204                 sector += copy >> SECTOR_SHIFT;
205                 if (!brd_insert_page(brd, sector))
206                         return -ENOSPC;
207         }
208         return 0;
209 }
210
211 static void discard_from_brd(struct brd_device *brd,
212                 sector_t sector, size_t n)
213 {
214         while (n >= PAGE_SIZE) {
215                 /*
216                  * Don't want to actually discard pages here because
217                  * re-allocating the pages can result in writeback
218                  * deadlocks under heavy load.
219                  */
220                 if (0)
221                         brd_free_page(brd, sector);
222                 else
223                         brd_zero_page(brd, sector);
224                 sector += PAGE_SIZE >> SECTOR_SHIFT;
225                 n -= PAGE_SIZE;
226         }
227 }
228
229 /*
230  * Copy n bytes from src to the brd starting at sector. Does not sleep.
231  */
232 static void copy_to_brd(struct brd_device *brd, const void *src,
233                         sector_t sector, size_t n)
234 {
235         struct page *page;
236         void *dst;
237         unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
238         size_t copy;
239
240         copy = min_t(size_t, n, PAGE_SIZE - offset);
241         page = brd_lookup_page(brd, sector);
242         BUG_ON(!page);
243
244         dst = kmap_atomic(page);
245         memcpy(dst + offset, src, copy);
246         kunmap_atomic(dst);
247
248         if (copy < n) {
249                 src += copy;
250                 sector += copy >> SECTOR_SHIFT;
251                 copy = n - copy;
252                 page = brd_lookup_page(brd, sector);
253                 BUG_ON(!page);
254
255                 dst = kmap_atomic(page);
256                 memcpy(dst, src, copy);
257                 kunmap_atomic(dst);
258         }
259 }
260
261 /*
262  * Copy n bytes to dst from the brd starting at sector. Does not sleep.
263  */
264 static void copy_from_brd(void *dst, struct brd_device *brd,
265                         sector_t sector, size_t n)
266 {
267         struct page *page;
268         void *src;
269         unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
270         size_t copy;
271
272         copy = min_t(size_t, n, PAGE_SIZE - offset);
273         page = brd_lookup_page(brd, sector);
274         if (page) {
275                 src = kmap_atomic(page);
276                 memcpy(dst, src + offset, copy);
277                 kunmap_atomic(src);
278         } else
279                 memset(dst, 0, copy);
280
281         if (copy < n) {
282                 dst += copy;
283                 sector += copy >> SECTOR_SHIFT;
284                 copy = n - copy;
285                 page = brd_lookup_page(brd, sector);
286                 if (page) {
287                         src = kmap_atomic(page);
288                         memcpy(dst, src, copy);
289                         kunmap_atomic(src);
290                 } else
291                         memset(dst, 0, copy);
292         }
293 }
294
295 /*
296  * Process a single bvec of a bio.
297  */
298 static int brd_do_bvec(struct brd_device *brd, struct page *page,
299                         unsigned int len, unsigned int off, unsigned int op,
300                         sector_t sector)
301 {
302         void *mem;
303         int err = 0;
304
305         if (op_is_write(op)) {
306                 err = copy_to_brd_setup(brd, sector, len);
307                 if (err)
308                         goto out;
309         }
310
311         mem = kmap_atomic(page);
312         if (!op_is_write(op)) {
313                 copy_from_brd(mem + off, brd, sector, len);
314                 flush_dcache_page(page);
315         } else {
316                 flush_dcache_page(page);
317                 copy_to_brd(brd, mem + off, sector, len);
318         }
319         kunmap_atomic(mem);
320
321 out:
322         return err;
323 }
324
325 static blk_qc_t brd_submit_bio(struct bio *bio)
326 {
327         struct brd_device *brd = bio->bi_bdev->bd_disk->private_data;
328         sector_t sector = bio->bi_iter.bi_sector;
329         struct bio_vec bvec;
330         struct bvec_iter iter;
331
332         if (unlikely(bio_op(bio) == REQ_OP_DISCARD)) {
333                 if (sector & ((PAGE_SIZE >> SECTOR_SHIFT) - 1) ||
334                                 bio->bi_iter.bi_size & ~PAGE_MASK)
335                         goto io_error;
336                 discard_from_brd(brd, sector, bio->bi_iter.bi_size);
337                 goto out;
338         }
339
340         bio_for_each_segment(bvec, bio, iter) {
341                 unsigned int len = bvec.bv_len;
342                 int err;
343
344                 /* Don't support un-aligned buffer */
345                 WARN_ON_ONCE((bvec.bv_offset & (SECTOR_SIZE - 1)) ||
346                                 (len & (SECTOR_SIZE - 1)));
347
348                 err = brd_do_bvec(brd, bvec.bv_page, len, bvec.bv_offset,
349                                   bio_op(bio), sector);
350                 if (err)
351                         goto io_error;
352                 sector += len >> SECTOR_SHIFT;
353         }
354
355 out:
356         bio_endio(bio);
357         return BLK_QC_T_NONE;
358 io_error:
359         bio_io_error(bio);
360         return BLK_QC_T_NONE;
361 }
362
363 static int brd_rw_page(struct block_device *bdev, sector_t sector,
364                        struct page *page, unsigned int op)
365 {
366         struct brd_device *brd = bdev->bd_disk->private_data;
367         int err;
368
369         if (PageTransHuge(page))
370                 return -ENOTSUPP;
371         err = brd_do_bvec(brd, page, PAGE_SIZE, 0, op, sector);
372         page_endio(page, op_is_write(op), err);
373         return err;
374 }
375
376 static DEFINE_MUTEX(brd_mutex);
377 static int brd_ioctl(struct block_device *bdev, fmode_t mode,
378                 unsigned int cmd, unsigned long arg)
379 {
380         int error;
381         struct brd_device *brd = bdev->bd_disk->private_data;
382
383         if (cmd != BLKFLSBUF)
384                 return -ENOTTY;
385
386         /*
387          * ram device BLKFLSBUF has special semantics, we want to actually
388          * release and destroy the ramdisk data.
389          */
390         mutex_lock(&brd_mutex);
391         mutex_lock(&bdev->bd_disk->open_mutex);
392         error = -EBUSY;
393         if (bdev->bd_openers <= 1) {
394                 /*
395                  * Kill the cache first, so it isn't written back to the
396                  * device.
397                  *
398                  * Another thread might instantiate more buffercache here,
399                  * but there is not much we can do to close that race.
400                  */
401                 kill_bdev(bdev);
402                 brd_free_pages(brd);
403                 error = 0;
404         }
405         mutex_unlock(&bdev->bd_disk->open_mutex);
406         mutex_unlock(&brd_mutex);
407
408         return error;
409 }
410
411 static const struct block_device_operations brd_fops = {
412         .owner =                THIS_MODULE,
413         .submit_bio =           brd_submit_bio,
414         .rw_page =              brd_rw_page,
415         .ioctl =                brd_ioctl,
416 };
417
418 /*
419  * And now the modules code and kernel interface.
420  */
421 static int rd_nr = CONFIG_BLK_DEV_RAM_COUNT;
422 module_param(rd_nr, int, 0444);
423 MODULE_PARM_DESC(rd_nr, "Maximum number of brd devices");
424
425 unsigned long rd_size = CONFIG_BLK_DEV_RAM_SIZE;
426 module_param(rd_size, ulong, 0444);
427 MODULE_PARM_DESC(rd_size, "Size of each RAM disk in kbytes.");
428
429 static int max_part = 1;
430 module_param(max_part, int, 0444);
431 MODULE_PARM_DESC(max_part, "Num Minors to reserve between devices");
432
433 MODULE_LICENSE("GPL");
434 MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR);
435 MODULE_ALIAS("rd");
436
437 #ifndef MODULE
438 /* Legacy boot options - nonmodular */
439 static int __init ramdisk_size(char *str)
440 {
441         rd_size = simple_strtol(str, NULL, 0);
442         return 1;
443 }
444 __setup("ramdisk_size=", ramdisk_size);
445 #endif
446
447 /*
448  * The device scheme is derived from loop.c. Keep them in synch where possible
449  * (should share code eventually).
450  */
451 static LIST_HEAD(brd_devices);
452 static DEFINE_MUTEX(brd_devices_mutex);
453 static struct dentry *brd_debugfs_dir;
454
455 static int brd_alloc(int i)
456 {
457         struct brd_device *brd;
458         struct gendisk *disk;
459         char buf[DISK_NAME_LEN];
460
461         mutex_lock(&brd_devices_mutex);
462         list_for_each_entry(brd, &brd_devices, brd_list) {
463                 if (brd->brd_number == i) {
464                         mutex_unlock(&brd_devices_mutex);
465                         return -EEXIST;
466                 }
467         }
468         brd = kzalloc(sizeof(*brd), GFP_KERNEL);
469         if (!brd) {
470                 mutex_unlock(&brd_devices_mutex);
471                 return -ENOMEM;
472         }
473         brd->brd_number         = i;
474         list_add_tail(&brd->brd_list, &brd_devices);
475         mutex_unlock(&brd_devices_mutex);
476
477         spin_lock_init(&brd->brd_lock);
478         INIT_RADIX_TREE(&brd->brd_pages, GFP_ATOMIC);
479
480         snprintf(buf, DISK_NAME_LEN, "ram%d", i);
481         if (!IS_ERR_OR_NULL(brd_debugfs_dir))
482                 debugfs_create_u64(buf, 0444, brd_debugfs_dir,
483                                 &brd->brd_nr_pages);
484
485         disk = brd->brd_disk = blk_alloc_disk(NUMA_NO_NODE);
486         if (!disk)
487                 goto out_free_dev;
488
489         disk->major             = RAMDISK_MAJOR;
490         disk->first_minor       = i * max_part;
491         disk->minors            = max_part;
492         disk->fops              = &brd_fops;
493         disk->private_data      = brd;
494         disk->flags             = GENHD_FL_EXT_DEVT;
495         strlcpy(disk->disk_name, buf, DISK_NAME_LEN);
496         set_capacity(disk, rd_size * 2);
497         
498         /*
499          * This is so fdisk will align partitions on 4k, because of
500          * direct_access API needing 4k alignment, returning a PFN
501          * (This is only a problem on very small devices <= 4M,
502          *  otherwise fdisk will align on 1M. Regardless this call
503          *  is harmless)
504          */
505         blk_queue_physical_block_size(disk->queue, PAGE_SIZE);
506
507         disk->queue->limits.discard_granularity = PAGE_SIZE;
508         blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
509         blk_queue_flag_set(QUEUE_FLAG_DISCARD, disk->queue);
510
511         /* Tell the block layer that this is not a rotational device */
512         blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
513         blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
514         add_disk(disk);
515
516         return 0;
517
518 out_free_dev:
519         mutex_lock(&brd_devices_mutex);
520         list_del(&brd->brd_list);
521         mutex_unlock(&brd_devices_mutex);
522         kfree(brd);
523         return -ENOMEM;
524 }
525
526 static void brd_probe(dev_t dev)
527 {
528         brd_alloc(MINOR(dev) / max_part);
529 }
530
531 static void brd_del_one(struct brd_device *brd)
532 {
533         del_gendisk(brd->brd_disk);
534         blk_cleanup_disk(brd->brd_disk);
535         brd_free_pages(brd);
536         mutex_lock(&brd_devices_mutex);
537         list_del(&brd->brd_list);
538         mutex_unlock(&brd_devices_mutex);
539         kfree(brd);
540 }
541
542 static inline void brd_check_and_reset_par(void)
543 {
544         if (unlikely(!max_part))
545                 max_part = 1;
546
547         /*
548          * make sure 'max_part' can be divided exactly by (1U << MINORBITS),
549          * otherwise, it is possiable to get same dev_t when adding partitions.
550          */
551         if ((1U << MINORBITS) % max_part != 0)
552                 max_part = 1UL << fls(max_part);
553
554         if (max_part > DISK_MAX_PARTS) {
555                 pr_info("brd: max_part can't be larger than %d, reset max_part = %d.\n",
556                         DISK_MAX_PARTS, DISK_MAX_PARTS);
557                 max_part = DISK_MAX_PARTS;
558         }
559 }
560
561 static int __init brd_init(void)
562 {
563         struct brd_device *brd, *next;
564         int err, i;
565
566         /*
567          * brd module now has a feature to instantiate underlying device
568          * structure on-demand, provided that there is an access dev node.
569          *
570          * (1) if rd_nr is specified, create that many upfront. else
571          *     it defaults to CONFIG_BLK_DEV_RAM_COUNT
572          * (2) User can further extend brd devices by create dev node themselves
573          *     and have kernel automatically instantiate actual device
574          *     on-demand. Example:
575          *              mknod /path/devnod_name b 1 X   # 1 is the rd major
576          *              fdisk -l /path/devnod_name
577          *      If (X / max_part) was not already created it will be created
578          *      dynamically.
579          */
580
581         if (__register_blkdev(RAMDISK_MAJOR, "ramdisk", brd_probe))
582                 return -EIO;
583
584         brd_check_and_reset_par();
585
586         brd_debugfs_dir = debugfs_create_dir("ramdisk_pages", NULL);
587
588         for (i = 0; i < rd_nr; i++) {
589                 err = brd_alloc(i);
590                 if (err)
591                         goto out_free;
592         }
593
594         pr_info("brd: module loaded\n");
595         return 0;
596
597 out_free:
598         unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
599         debugfs_remove_recursive(brd_debugfs_dir);
600
601         list_for_each_entry_safe(brd, next, &brd_devices, brd_list)
602                 brd_del_one(brd);
603
604         pr_info("brd: module NOT loaded !!!\n");
605         return err;
606 }
607
608 static void __exit brd_exit(void)
609 {
610         struct brd_device *brd, *next;
611
612         unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
613         debugfs_remove_recursive(brd_debugfs_dir);
614
615         list_for_each_entry_safe(brd, next, &brd_devices, brd_list)
616                 brd_del_one(brd);
617
618         pr_info("brd: module unloaded\n");
619 }
620
621 module_init(brd_init);
622 module_exit(brd_exit);
623