xref: /openbmc/linux/drivers/block/brd.c (revision 71de0a05)
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 const struct block_device_operations brd_fops = {
319 	.owner =		THIS_MODULE,
320 	.submit_bio =		brd_submit_bio,
321 };
322 
323 /*
324  * And now the modules code and kernel interface.
325  */
326 static int rd_nr = CONFIG_BLK_DEV_RAM_COUNT;
327 module_param(rd_nr, int, 0444);
328 MODULE_PARM_DESC(rd_nr, "Maximum number of brd devices");
329 
330 unsigned long rd_size = CONFIG_BLK_DEV_RAM_SIZE;
331 module_param(rd_size, ulong, 0444);
332 MODULE_PARM_DESC(rd_size, "Size of each RAM disk in kbytes.");
333 
334 static int max_part = 1;
335 module_param(max_part, int, 0444);
336 MODULE_PARM_DESC(max_part, "Num Minors to reserve between devices");
337 
338 MODULE_LICENSE("GPL");
339 MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR);
340 MODULE_ALIAS("rd");
341 
342 #ifndef MODULE
343 /* Legacy boot options - nonmodular */
344 static int __init ramdisk_size(char *str)
345 {
346 	rd_size = simple_strtol(str, NULL, 0);
347 	return 1;
348 }
349 __setup("ramdisk_size=", ramdisk_size);
350 #endif
351 
352 /*
353  * The device scheme is derived from loop.c. Keep them in synch where possible
354  * (should share code eventually).
355  */
356 static LIST_HEAD(brd_devices);
357 static struct dentry *brd_debugfs_dir;
358 
359 static int brd_alloc(int i)
360 {
361 	struct brd_device *brd;
362 	struct gendisk *disk;
363 	char buf[DISK_NAME_LEN];
364 	int err = -ENOMEM;
365 
366 	list_for_each_entry(brd, &brd_devices, brd_list)
367 		if (brd->brd_number == i)
368 			return -EEXIST;
369 	brd = kzalloc(sizeof(*brd), GFP_KERNEL);
370 	if (!brd)
371 		return -ENOMEM;
372 	brd->brd_number		= i;
373 	list_add_tail(&brd->brd_list, &brd_devices);
374 
375 	spin_lock_init(&brd->brd_lock);
376 	INIT_RADIX_TREE(&brd->brd_pages, GFP_ATOMIC);
377 
378 	snprintf(buf, DISK_NAME_LEN, "ram%d", i);
379 	if (!IS_ERR_OR_NULL(brd_debugfs_dir))
380 		debugfs_create_u64(buf, 0444, brd_debugfs_dir,
381 				&brd->brd_nr_pages);
382 
383 	disk = brd->brd_disk = blk_alloc_disk(NUMA_NO_NODE);
384 	if (!disk)
385 		goto out_free_dev;
386 
387 	disk->major		= RAMDISK_MAJOR;
388 	disk->first_minor	= i * max_part;
389 	disk->minors		= max_part;
390 	disk->fops		= &brd_fops;
391 	disk->private_data	= brd;
392 	strscpy(disk->disk_name, buf, DISK_NAME_LEN);
393 	set_capacity(disk, rd_size * 2);
394 
395 	/*
396 	 * This is so fdisk will align partitions on 4k, because of
397 	 * direct_access API needing 4k alignment, returning a PFN
398 	 * (This is only a problem on very small devices <= 4M,
399 	 *  otherwise fdisk will align on 1M. Regardless this call
400 	 *  is harmless)
401 	 */
402 	blk_queue_physical_block_size(disk->queue, PAGE_SIZE);
403 
404 	/* Tell the block layer that this is not a rotational device */
405 	blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
406 	blk_queue_flag_set(QUEUE_FLAG_SYNCHRONOUS, disk->queue);
407 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
408 	blk_queue_flag_set(QUEUE_FLAG_NOWAIT, disk->queue);
409 	err = add_disk(disk);
410 	if (err)
411 		goto out_cleanup_disk;
412 
413 	return 0;
414 
415 out_cleanup_disk:
416 	put_disk(disk);
417 out_free_dev:
418 	list_del(&brd->brd_list);
419 	kfree(brd);
420 	return err;
421 }
422 
423 static void brd_probe(dev_t dev)
424 {
425 	brd_alloc(MINOR(dev) / max_part);
426 }
427 
428 static void brd_cleanup(void)
429 {
430 	struct brd_device *brd, *next;
431 
432 	debugfs_remove_recursive(brd_debugfs_dir);
433 
434 	list_for_each_entry_safe(brd, next, &brd_devices, brd_list) {
435 		del_gendisk(brd->brd_disk);
436 		put_disk(brd->brd_disk);
437 		brd_free_pages(brd);
438 		list_del(&brd->brd_list);
439 		kfree(brd);
440 	}
441 }
442 
443 static inline void brd_check_and_reset_par(void)
444 {
445 	if (unlikely(!max_part))
446 		max_part = 1;
447 
448 	/*
449 	 * make sure 'max_part' can be divided exactly by (1U << MINORBITS),
450 	 * otherwise, it is possiable to get same dev_t when adding partitions.
451 	 */
452 	if ((1U << MINORBITS) % max_part != 0)
453 		max_part = 1UL << fls(max_part);
454 
455 	if (max_part > DISK_MAX_PARTS) {
456 		pr_info("brd: max_part can't be larger than %d, reset max_part = %d.\n",
457 			DISK_MAX_PARTS, DISK_MAX_PARTS);
458 		max_part = DISK_MAX_PARTS;
459 	}
460 }
461 
462 static int __init brd_init(void)
463 {
464 	int err, i;
465 
466 	brd_check_and_reset_par();
467 
468 	brd_debugfs_dir = debugfs_create_dir("ramdisk_pages", NULL);
469 
470 	for (i = 0; i < rd_nr; i++) {
471 		err = brd_alloc(i);
472 		if (err)
473 			goto out_free;
474 	}
475 
476 	/*
477 	 * brd module now has a feature to instantiate underlying device
478 	 * structure on-demand, provided that there is an access dev node.
479 	 *
480 	 * (1) if rd_nr is specified, create that many upfront. else
481 	 *     it defaults to CONFIG_BLK_DEV_RAM_COUNT
482 	 * (2) User can further extend brd devices by create dev node themselves
483 	 *     and have kernel automatically instantiate actual device
484 	 *     on-demand. Example:
485 	 *		mknod /path/devnod_name b 1 X	# 1 is the rd major
486 	 *		fdisk -l /path/devnod_name
487 	 *	If (X / max_part) was not already created it will be created
488 	 *	dynamically.
489 	 */
490 
491 	if (__register_blkdev(RAMDISK_MAJOR, "ramdisk", brd_probe)) {
492 		err = -EIO;
493 		goto out_free;
494 	}
495 
496 	pr_info("brd: module loaded\n");
497 	return 0;
498 
499 out_free:
500 	brd_cleanup();
501 
502 	pr_info("brd: module NOT loaded !!!\n");
503 	return err;
504 }
505 
506 static void __exit brd_exit(void)
507 {
508 
509 	unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
510 	brd_cleanup();
511 
512 	pr_info("brd: module unloaded\n");
513 }
514 
515 module_init(brd_init);
516 module_exit(brd_exit);
517 
518