1 // SPDX-License-Identifier: GPL-2.0-only
3 * Ram backed block device driver.
5 * Copyright (C) 2007 Nick Piggin
6 * Copyright (C) 2007 Novell Inc.
8 * Parts derived from drivers/block/rd.c, and drivers/block/loop.c, copyright
9 * of their respective owners.
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>
24 #include <linux/slab.h>
25 #include <linux/backing-dev.h>
26 #include <linux/debugfs.h>
28 #include <linux/uaccess.h>
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
39 struct gendisk *brd_disk;
40 struct list_head brd_list;
43 * Backing store of pages and lock to protect it. This is the contents
44 * of the block device.
47 struct radix_tree_root brd_pages;
52 * Look up and return a brd's page for a given sector.
54 static struct page *brd_lookup_page(struct brd_device *brd, sector_t sector)
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.
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).
71 idx = sector >> PAGE_SECTORS_SHIFT; /* sector to page index */
72 page = radix_tree_lookup(&brd->brd_pages, idx);
75 BUG_ON(page && page->index != idx);
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
85 static struct page *brd_insert_page(struct brd_device *brd, sector_t sector)
91 page = brd_lookup_page(brd, sector);
96 * Must use NOIO because we don't want to recurse back into the
97 * block or filesystem layers from page reclaim.
99 gfp_flags = GFP_NOIO | __GFP_ZERO | __GFP_HIGHMEM;
100 page = alloc_page(gfp_flags);
104 if (radix_tree_preload(GFP_NOIO)) {
109 spin_lock(&brd->brd_lock);
110 idx = sector >> PAGE_SECTORS_SHIFT;
112 if (radix_tree_insert(&brd->brd_pages, idx, page)) {
114 page = radix_tree_lookup(&brd->brd_pages, idx);
116 BUG_ON(page->index != idx);
120 spin_unlock(&brd->brd_lock);
122 radix_tree_preload_end();
127 static void brd_free_page(struct brd_device *brd, sector_t sector)
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);
140 static void brd_zero_page(struct brd_device *brd, sector_t sector)
144 page = brd_lookup_page(brd, sector);
146 clear_highpage(page);
150 * Free all backing store pages and radix tree. This must only be called when
151 * there are no other users of the device.
153 #define FREE_BATCH 16
154 static void brd_free_pages(struct brd_device *brd)
156 unsigned long pos = 0;
157 struct page *pages[FREE_BATCH];
163 nr_pages = radix_tree_gang_lookup(&brd->brd_pages,
164 (void **)pages, pos, FREE_BATCH);
166 for (i = 0; i < nr_pages; i++) {
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]);
179 * It takes 3.4 seconds to remove 80GiB ramdisk.
180 * So, we need cond_resched to avoid stalling the CPU.
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.
189 } while (nr_pages == FREE_BATCH);
193 * copy_to_brd_setup must be called before copy_to_brd. It may sleep.
195 static int copy_to_brd_setup(struct brd_device *brd, sector_t sector, size_t n)
197 unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
200 copy = min_t(size_t, n, PAGE_SIZE - offset);
201 if (!brd_insert_page(brd, sector))
204 sector += copy >> SECTOR_SHIFT;
205 if (!brd_insert_page(brd, sector))
211 static void discard_from_brd(struct brd_device *brd,
212 sector_t sector, size_t n)
214 while (n >= PAGE_SIZE) {
216 * Don't want to actually discard pages here because
217 * re-allocating the pages can result in writeback
218 * deadlocks under heavy load.
221 brd_free_page(brd, sector);
223 brd_zero_page(brd, sector);
224 sector += PAGE_SIZE >> SECTOR_SHIFT;
230 * Copy n bytes from src to the brd starting at sector. Does not sleep.
232 static void copy_to_brd(struct brd_device *brd, const void *src,
233 sector_t sector, size_t n)
237 unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
240 copy = min_t(size_t, n, PAGE_SIZE - offset);
241 page = brd_lookup_page(brd, sector);
244 dst = kmap_atomic(page);
245 memcpy(dst + offset, src, copy);
250 sector += copy >> SECTOR_SHIFT;
252 page = brd_lookup_page(brd, sector);
255 dst = kmap_atomic(page);
256 memcpy(dst, src, copy);
262 * Copy n bytes to dst from the brd starting at sector. Does not sleep.
264 static void copy_from_brd(void *dst, struct brd_device *brd,
265 sector_t sector, size_t n)
269 unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
272 copy = min_t(size_t, n, PAGE_SIZE - offset);
273 page = brd_lookup_page(brd, sector);
275 src = kmap_atomic(page);
276 memcpy(dst, src + offset, copy);
279 memset(dst, 0, copy);
283 sector += copy >> SECTOR_SHIFT;
285 page = brd_lookup_page(brd, sector);
287 src = kmap_atomic(page);
288 memcpy(dst, src, copy);
291 memset(dst, 0, copy);
296 * Process a single bvec of a bio.
298 static int brd_do_bvec(struct brd_device *brd, struct page *page,
299 unsigned int len, unsigned int off, unsigned int op,
305 if (op_is_write(op)) {
306 err = copy_to_brd_setup(brd, sector, len);
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);
316 flush_dcache_page(page);
317 copy_to_brd(brd, mem + off, sector, len);
325 static blk_qc_t brd_submit_bio(struct bio *bio)
327 struct brd_device *brd = bio->bi_bdev->bd_disk->private_data;
328 sector_t sector = bio->bi_iter.bi_sector;
330 struct bvec_iter iter;
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)
336 discard_from_brd(brd, sector, bio->bi_iter.bi_size);
340 bio_for_each_segment(bvec, bio, iter) {
341 unsigned int len = bvec.bv_len;
344 /* Don't support un-aligned buffer */
345 WARN_ON_ONCE((bvec.bv_offset & (SECTOR_SIZE - 1)) ||
346 (len & (SECTOR_SIZE - 1)));
348 err = brd_do_bvec(brd, bvec.bv_page, len, bvec.bv_offset,
349 bio_op(bio), sector);
352 sector += len >> SECTOR_SHIFT;
357 return BLK_QC_T_NONE;
360 return BLK_QC_T_NONE;
363 static int brd_rw_page(struct block_device *bdev, sector_t sector,
364 struct page *page, unsigned int op)
366 struct brd_device *brd = bdev->bd_disk->private_data;
369 if (PageTransHuge(page))
371 err = brd_do_bvec(brd, page, PAGE_SIZE, 0, op, sector);
372 page_endio(page, op_is_write(op), err);
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)
381 struct brd_device *brd = bdev->bd_disk->private_data;
383 if (cmd != BLKFLSBUF)
387 * ram device BLKFLSBUF has special semantics, we want to actually
388 * release and destroy the ramdisk data.
390 mutex_lock(&brd_mutex);
391 mutex_lock(&bdev->bd_disk->open_mutex);
393 if (bdev->bd_openers <= 1) {
395 * Kill the cache first, so it isn't written back to the
398 * Another thread might instantiate more buffercache here,
399 * but there is not much we can do to close that race.
405 mutex_unlock(&bdev->bd_disk->open_mutex);
406 mutex_unlock(&brd_mutex);
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,
419 * And now the modules code and kernel interface.
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");
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.");
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");
433 MODULE_LICENSE("GPL");
434 MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR);
438 /* Legacy boot options - nonmodular */
439 static int __init ramdisk_size(char *str)
441 rd_size = simple_strtol(str, NULL, 0);
444 __setup("ramdisk_size=", ramdisk_size);
448 * The device scheme is derived from loop.c. Keep them in synch where possible
449 * (should share code eventually).
451 static LIST_HEAD(brd_devices);
452 static DEFINE_MUTEX(brd_devices_mutex);
453 static struct dentry *brd_debugfs_dir;
455 static int brd_alloc(int i)
457 struct brd_device *brd;
458 struct gendisk *disk;
459 char buf[DISK_NAME_LEN];
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);
468 brd = kzalloc(sizeof(*brd), GFP_KERNEL);
470 mutex_unlock(&brd_devices_mutex);
474 list_add_tail(&brd->brd_list, &brd_devices);
475 mutex_unlock(&brd_devices_mutex);
477 spin_lock_init(&brd->brd_lock);
478 INIT_RADIX_TREE(&brd->brd_pages, GFP_ATOMIC);
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,
485 disk = brd->brd_disk = blk_alloc_disk(NUMA_NO_NODE);
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);
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
505 blk_queue_physical_block_size(disk->queue, PAGE_SIZE);
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);
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);
519 mutex_lock(&brd_devices_mutex);
520 list_del(&brd->brd_list);
521 mutex_unlock(&brd_devices_mutex);
526 static void brd_probe(dev_t dev)
528 brd_alloc(MINOR(dev) / max_part);
531 static void brd_del_one(struct brd_device *brd)
533 del_gendisk(brd->brd_disk);
534 blk_cleanup_disk(brd->brd_disk);
536 mutex_lock(&brd_devices_mutex);
537 list_del(&brd->brd_list);
538 mutex_unlock(&brd_devices_mutex);
542 static inline void brd_check_and_reset_par(void)
544 if (unlikely(!max_part))
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.
551 if ((1U << MINORBITS) % max_part != 0)
552 max_part = 1UL << fls(max_part);
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;
561 static int __init brd_init(void)
563 struct brd_device *brd, *next;
567 * brd module now has a feature to instantiate underlying device
568 * structure on-demand, provided that there is an access dev node.
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
581 if (__register_blkdev(RAMDISK_MAJOR, "ramdisk", brd_probe))
584 brd_check_and_reset_par();
586 brd_debugfs_dir = debugfs_create_dir("ramdisk_pages", NULL);
588 for (i = 0; i < rd_nr; i++) {
594 pr_info("brd: module loaded\n");
598 unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
599 debugfs_remove_recursive(brd_debugfs_dir);
601 list_for_each_entry_safe(brd, next, &brd_devices, brd_list)
604 pr_info("brd: module NOT loaded !!!\n");
608 static void __exit brd_exit(void)
610 struct brd_device *brd, *next;
612 unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
613 debugfs_remove_recursive(brd_debugfs_dir);
615 list_for_each_entry_safe(brd, next, &brd_devices, brd_list)
618 pr_info("brd: module unloaded\n");
621 module_init(brd_init);
622 module_exit(brd_exit);