xref: /openbmc/linux/drivers/block/brd.c (revision 6486a57f)
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  * Insert a new page for a given sector, if one does not already exist.
82  */
83 static int brd_insert_page(struct brd_device *brd, sector_t sector, gfp_t gfp)
84 {
85 	pgoff_t idx;
86 	struct page *page;
87 	int ret = 0;
88 
89 	page = brd_lookup_page(brd, sector);
90 	if (page)
91 		return 0;
92 
93 	page = alloc_page(gfp | __GFP_ZERO | __GFP_HIGHMEM);
94 	if (!page)
95 		return -ENOMEM;
96 
97 	if (radix_tree_maybe_preload(gfp)) {
98 		__free_page(page);
99 		return -ENOMEM;
100 	}
101 
102 	spin_lock(&brd->brd_lock);
103 	idx = sector >> PAGE_SECTORS_SHIFT;
104 	page->index = idx;
105 	if (radix_tree_insert(&brd->brd_pages, idx, page)) {
106 		__free_page(page);
107 		page = radix_tree_lookup(&brd->brd_pages, idx);
108 		if (!page)
109 			ret = -ENOMEM;
110 		else if (page->index != idx)
111 			ret = -EIO;
112 	} else {
113 		brd->brd_nr_pages++;
114 	}
115 	spin_unlock(&brd->brd_lock);
116 
117 	radix_tree_preload_end();
118 	return ret;
119 }
120 
121 /*
122  * Free all backing store pages and radix tree. This must only be called when
123  * there are no other users of the device.
124  */
125 #define FREE_BATCH 16
126 static void brd_free_pages(struct brd_device *brd)
127 {
128 	unsigned long pos = 0;
129 	struct page *pages[FREE_BATCH];
130 	int nr_pages;
131 
132 	do {
133 		int i;
134 
135 		nr_pages = radix_tree_gang_lookup(&brd->brd_pages,
136 				(void **)pages, pos, FREE_BATCH);
137 
138 		for (i = 0; i < nr_pages; i++) {
139 			void *ret;
140 
141 			BUG_ON(pages[i]->index < pos);
142 			pos = pages[i]->index;
143 			ret = radix_tree_delete(&brd->brd_pages, pos);
144 			BUG_ON(!ret || ret != pages[i]);
145 			__free_page(pages[i]);
146 		}
147 
148 		pos++;
149 
150 		/*
151 		 * It takes 3.4 seconds to remove 80GiB ramdisk.
152 		 * So, we need cond_resched to avoid stalling the CPU.
153 		 */
154 		cond_resched();
155 
156 		/*
157 		 * This assumes radix_tree_gang_lookup always returns as
158 		 * many pages as possible. If the radix-tree code changes,
159 		 * so will this have to.
160 		 */
161 	} while (nr_pages == FREE_BATCH);
162 }
163 
164 /*
165  * copy_to_brd_setup must be called before copy_to_brd. It may sleep.
166  */
167 static int copy_to_brd_setup(struct brd_device *brd, sector_t sector, size_t n,
168 			     gfp_t gfp)
169 {
170 	unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
171 	size_t copy;
172 	int ret;
173 
174 	copy = min_t(size_t, n, PAGE_SIZE - offset);
175 	ret = brd_insert_page(brd, sector, gfp);
176 	if (ret)
177 		return ret;
178 	if (copy < n) {
179 		sector += copy >> SECTOR_SHIFT;
180 		ret = brd_insert_page(brd, sector, gfp);
181 	}
182 	return ret;
183 }
184 
185 /*
186  * Copy n bytes from src to the brd starting at sector. Does not sleep.
187  */
188 static void copy_to_brd(struct brd_device *brd, const void *src,
189 			sector_t sector, size_t n)
190 {
191 	struct page *page;
192 	void *dst;
193 	unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
194 	size_t copy;
195 
196 	copy = min_t(size_t, n, PAGE_SIZE - offset);
197 	page = brd_lookup_page(brd, sector);
198 	BUG_ON(!page);
199 
200 	dst = kmap_atomic(page);
201 	memcpy(dst + offset, src, copy);
202 	kunmap_atomic(dst);
203 
204 	if (copy < n) {
205 		src += copy;
206 		sector += copy >> SECTOR_SHIFT;
207 		copy = n - copy;
208 		page = brd_lookup_page(brd, sector);
209 		BUG_ON(!page);
210 
211 		dst = kmap_atomic(page);
212 		memcpy(dst, src, copy);
213 		kunmap_atomic(dst);
214 	}
215 }
216 
217 /*
218  * Copy n bytes to dst from the brd starting at sector. Does not sleep.
219  */
220 static void copy_from_brd(void *dst, struct brd_device *brd,
221 			sector_t sector, size_t n)
222 {
223 	struct page *page;
224 	void *src;
225 	unsigned int offset = (sector & (PAGE_SECTORS-1)) << SECTOR_SHIFT;
226 	size_t copy;
227 
228 	copy = min_t(size_t, n, PAGE_SIZE - offset);
229 	page = brd_lookup_page(brd, sector);
230 	if (page) {
231 		src = kmap_atomic(page);
232 		memcpy(dst, src + offset, copy);
233 		kunmap_atomic(src);
234 	} else
235 		memset(dst, 0, copy);
236 
237 	if (copy < n) {
238 		dst += copy;
239 		sector += copy >> SECTOR_SHIFT;
240 		copy = n - copy;
241 		page = brd_lookup_page(brd, sector);
242 		if (page) {
243 			src = kmap_atomic(page);
244 			memcpy(dst, src, copy);
245 			kunmap_atomic(src);
246 		} else
247 			memset(dst, 0, copy);
248 	}
249 }
250 
251 /*
252  * Process a single bvec of a bio.
253  */
254 static int brd_do_bvec(struct brd_device *brd, struct page *page,
255 			unsigned int len, unsigned int off, blk_opf_t opf,
256 			sector_t sector)
257 {
258 	void *mem;
259 	int err = 0;
260 
261 	if (op_is_write(opf)) {
262 		/*
263 		 * Must use NOIO because we don't want to recurse back into the
264 		 * block or filesystem layers from page reclaim.
265 		 */
266 		gfp_t gfp = opf & REQ_NOWAIT ? GFP_NOWAIT : GFP_NOIO;
267 
268 		err = copy_to_brd_setup(brd, sector, len, gfp);
269 		if (err)
270 			goto out;
271 	}
272 
273 	mem = kmap_atomic(page);
274 	if (!op_is_write(opf)) {
275 		copy_from_brd(mem + off, brd, sector, len);
276 		flush_dcache_page(page);
277 	} else {
278 		flush_dcache_page(page);
279 		copy_to_brd(brd, mem + off, sector, len);
280 	}
281 	kunmap_atomic(mem);
282 
283 out:
284 	return err;
285 }
286 
287 static void brd_submit_bio(struct bio *bio)
288 {
289 	struct brd_device *brd = bio->bi_bdev->bd_disk->private_data;
290 	sector_t sector = bio->bi_iter.bi_sector;
291 	struct bio_vec bvec;
292 	struct bvec_iter iter;
293 
294 	bio_for_each_segment(bvec, bio, iter) {
295 		unsigned int len = bvec.bv_len;
296 		int err;
297 
298 		/* Don't support un-aligned buffer */
299 		WARN_ON_ONCE((bvec.bv_offset & (SECTOR_SIZE - 1)) ||
300 				(len & (SECTOR_SIZE - 1)));
301 
302 		err = brd_do_bvec(brd, bvec.bv_page, len, bvec.bv_offset,
303 				  bio->bi_opf, sector);
304 		if (err) {
305 			if (err == -ENOMEM && bio->bi_opf & REQ_NOWAIT) {
306 				bio_wouldblock_error(bio);
307 				return;
308 			}
309 			bio_io_error(bio);
310 			return;
311 		}
312 		sector += len >> SECTOR_SHIFT;
313 	}
314 
315 	bio_endio(bio);
316 }
317 
318 static int brd_rw_page(struct block_device *bdev, sector_t sector,
319 		       struct page *page, enum req_op op)
320 {
321 	struct brd_device *brd = bdev->bd_disk->private_data;
322 	int err;
323 
324 	if (PageTransHuge(page))
325 		return -ENOTSUPP;
326 	err = brd_do_bvec(brd, page, PAGE_SIZE, 0, op, sector);
327 	page_endio(page, op_is_write(op), err);
328 	return err;
329 }
330 
331 static const struct block_device_operations brd_fops = {
332 	.owner =		THIS_MODULE,
333 	.submit_bio =		brd_submit_bio,
334 	.rw_page =		brd_rw_page,
335 };
336 
337 /*
338  * And now the modules code and kernel interface.
339  */
340 static int rd_nr = CONFIG_BLK_DEV_RAM_COUNT;
341 module_param(rd_nr, int, 0444);
342 MODULE_PARM_DESC(rd_nr, "Maximum number of brd devices");
343 
344 unsigned long rd_size = CONFIG_BLK_DEV_RAM_SIZE;
345 module_param(rd_size, ulong, 0444);
346 MODULE_PARM_DESC(rd_size, "Size of each RAM disk in kbytes.");
347 
348 static int max_part = 1;
349 module_param(max_part, int, 0444);
350 MODULE_PARM_DESC(max_part, "Num Minors to reserve between devices");
351 
352 MODULE_LICENSE("GPL");
353 MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR);
354 MODULE_ALIAS("rd");
355 
356 #ifndef MODULE
357 /* Legacy boot options - nonmodular */
358 static int __init ramdisk_size(char *str)
359 {
360 	rd_size = simple_strtol(str, NULL, 0);
361 	return 1;
362 }
363 __setup("ramdisk_size=", ramdisk_size);
364 #endif
365 
366 /*
367  * The device scheme is derived from loop.c. Keep them in synch where possible
368  * (should share code eventually).
369  */
370 static LIST_HEAD(brd_devices);
371 static struct dentry *brd_debugfs_dir;
372 
373 static int brd_alloc(int i)
374 {
375 	struct brd_device *brd;
376 	struct gendisk *disk;
377 	char buf[DISK_NAME_LEN];
378 	int err = -ENOMEM;
379 
380 	list_for_each_entry(brd, &brd_devices, brd_list)
381 		if (brd->brd_number == i)
382 			return -EEXIST;
383 	brd = kzalloc(sizeof(*brd), GFP_KERNEL);
384 	if (!brd)
385 		return -ENOMEM;
386 	brd->brd_number		= i;
387 	list_add_tail(&brd->brd_list, &brd_devices);
388 
389 	spin_lock_init(&brd->brd_lock);
390 	INIT_RADIX_TREE(&brd->brd_pages, GFP_ATOMIC);
391 
392 	snprintf(buf, DISK_NAME_LEN, "ram%d", i);
393 	if (!IS_ERR_OR_NULL(brd_debugfs_dir))
394 		debugfs_create_u64(buf, 0444, brd_debugfs_dir,
395 				&brd->brd_nr_pages);
396 
397 	disk = brd->brd_disk = blk_alloc_disk(NUMA_NO_NODE);
398 	if (!disk)
399 		goto out_free_dev;
400 
401 	disk->major		= RAMDISK_MAJOR;
402 	disk->first_minor	= i * max_part;
403 	disk->minors		= max_part;
404 	disk->fops		= &brd_fops;
405 	disk->private_data	= brd;
406 	strscpy(disk->disk_name, buf, DISK_NAME_LEN);
407 	set_capacity(disk, rd_size * 2);
408 
409 	/*
410 	 * This is so fdisk will align partitions on 4k, because of
411 	 * direct_access API needing 4k alignment, returning a PFN
412 	 * (This is only a problem on very small devices <= 4M,
413 	 *  otherwise fdisk will align on 1M. Regardless this call
414 	 *  is harmless)
415 	 */
416 	blk_queue_physical_block_size(disk->queue, PAGE_SIZE);
417 
418 	/* Tell the block layer that this is not a rotational device */
419 	blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
420 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
421 	blk_queue_flag_set(QUEUE_FLAG_NOWAIT, disk->queue);
422 	err = add_disk(disk);
423 	if (err)
424 		goto out_cleanup_disk;
425 
426 	return 0;
427 
428 out_cleanup_disk:
429 	put_disk(disk);
430 out_free_dev:
431 	list_del(&brd->brd_list);
432 	kfree(brd);
433 	return err;
434 }
435 
436 static void brd_probe(dev_t dev)
437 {
438 	brd_alloc(MINOR(dev) / max_part);
439 }
440 
441 static void brd_cleanup(void)
442 {
443 	struct brd_device *brd, *next;
444 
445 	debugfs_remove_recursive(brd_debugfs_dir);
446 
447 	list_for_each_entry_safe(brd, next, &brd_devices, brd_list) {
448 		del_gendisk(brd->brd_disk);
449 		put_disk(brd->brd_disk);
450 		brd_free_pages(brd);
451 		list_del(&brd->brd_list);
452 		kfree(brd);
453 	}
454 }
455 
456 static inline void brd_check_and_reset_par(void)
457 {
458 	if (unlikely(!max_part))
459 		max_part = 1;
460 
461 	/*
462 	 * make sure 'max_part' can be divided exactly by (1U << MINORBITS),
463 	 * otherwise, it is possiable to get same dev_t when adding partitions.
464 	 */
465 	if ((1U << MINORBITS) % max_part != 0)
466 		max_part = 1UL << fls(max_part);
467 
468 	if (max_part > DISK_MAX_PARTS) {
469 		pr_info("brd: max_part can't be larger than %d, reset max_part = %d.\n",
470 			DISK_MAX_PARTS, DISK_MAX_PARTS);
471 		max_part = DISK_MAX_PARTS;
472 	}
473 }
474 
475 static int __init brd_init(void)
476 {
477 	int err, i;
478 
479 	brd_check_and_reset_par();
480 
481 	brd_debugfs_dir = debugfs_create_dir("ramdisk_pages", NULL);
482 
483 	for (i = 0; i < rd_nr; i++) {
484 		err = brd_alloc(i);
485 		if (err)
486 			goto out_free;
487 	}
488 
489 	/*
490 	 * brd module now has a feature to instantiate underlying device
491 	 * structure on-demand, provided that there is an access dev node.
492 	 *
493 	 * (1) if rd_nr is specified, create that many upfront. else
494 	 *     it defaults to CONFIG_BLK_DEV_RAM_COUNT
495 	 * (2) User can further extend brd devices by create dev node themselves
496 	 *     and have kernel automatically instantiate actual device
497 	 *     on-demand. Example:
498 	 *		mknod /path/devnod_name b 1 X	# 1 is the rd major
499 	 *		fdisk -l /path/devnod_name
500 	 *	If (X / max_part) was not already created it will be created
501 	 *	dynamically.
502 	 */
503 
504 	if (__register_blkdev(RAMDISK_MAJOR, "ramdisk", brd_probe)) {
505 		err = -EIO;
506 		goto out_free;
507 	}
508 
509 	pr_info("brd: module loaded\n");
510 	return 0;
511 
512 out_free:
513 	brd_cleanup();
514 
515 	pr_info("brd: module NOT loaded !!!\n");
516 	return err;
517 }
518 
519 static void __exit brd_exit(void)
520 {
521 
522 	unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
523 	brd_cleanup();
524 
525 	pr_info("brd: module unloaded\n");
526 }
527 
528 module_init(brd_init);
529 module_exit(brd_exit);
530 
531