xref: /linux/drivers/block/brd.c (revision 9e4f11c1228cc8ebf236cfa51d44abafec80f326)
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/xarray.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 xarray brd_pages of pages that stores
32  * the pages containing the block device's contents.
33  */
34 struct brd_device {
35 	int			brd_number;
36 	struct gendisk		*brd_disk;
37 	struct list_head	brd_list;
38 
39 	/*
40 	 * Backing store of pages. This is the contents of the block device.
41 	 */
42 	struct xarray	        brd_pages;
43 	u64			brd_nr_pages;
44 };
45 
46 /*
47  * Look up and return a brd's page for a given sector.
48  */
49 static struct page *brd_lookup_page(struct brd_device *brd, sector_t sector)
50 {
51 	return xa_load(&brd->brd_pages, sector >> PAGE_SECTORS_SHIFT);
52 }
53 
54 /*
55  * Insert a new page for a given sector, if one does not already exist.
56  */
57 static int brd_insert_page(struct brd_device *brd, sector_t sector, gfp_t gfp)
58 {
59 	pgoff_t idx = sector >> PAGE_SECTORS_SHIFT;
60 	struct page *page;
61 	int ret = 0;
62 
63 	page = brd_lookup_page(brd, sector);
64 	if (page)
65 		return 0;
66 
67 	page = alloc_page(gfp | __GFP_ZERO | __GFP_HIGHMEM);
68 	if (!page)
69 		return -ENOMEM;
70 
71 	xa_lock(&brd->brd_pages);
72 	ret = __xa_insert(&brd->brd_pages, idx, page, gfp);
73 	if (!ret)
74 		brd->brd_nr_pages++;
75 	xa_unlock(&brd->brd_pages);
76 
77 	if (ret < 0) {
78 		__free_page(page);
79 		if (ret == -EBUSY)
80 			ret = 0;
81 	}
82 	return ret;
83 }
84 
85 /*
86  * Free all backing store pages and xarray. This must only be called when
87  * there are no other users of the device.
88  */
89 static void brd_free_pages(struct brd_device *brd)
90 {
91 	struct page *page;
92 	pgoff_t idx;
93 
94 	xa_for_each(&brd->brd_pages, idx, page) {
95 		__free_page(page);
96 		cond_resched();
97 	}
98 
99 	xa_destroy(&brd->brd_pages);
100 }
101 
102 /*
103  * Process a single segment.  The segment is capped to not cross page boundaries
104  * in both the bio and the brd backing memory.
105  */
106 static bool brd_rw_bvec(struct brd_device *brd, struct bio *bio)
107 {
108 	struct bio_vec bv = bio_iter_iovec(bio, bio->bi_iter);
109 	sector_t sector = bio->bi_iter.bi_sector;
110 	u32 offset = (sector & (PAGE_SECTORS - 1)) << SECTOR_SHIFT;
111 	blk_opf_t opf = bio->bi_opf;
112 	struct page *page;
113 	void *kaddr;
114 
115 	bv.bv_len = min_t(u32, bv.bv_len, PAGE_SIZE - offset);
116 
117 	if (op_is_write(opf)) {
118 		int err;
119 
120 		/*
121 		 * Must use NOIO because we don't want to recurse back into the
122 		 * block or filesystem layers from page reclaim.
123 		 */
124 		err = brd_insert_page(brd, sector,
125 				(opf & REQ_NOWAIT) ? GFP_NOWAIT : GFP_NOIO);
126 		if (err) {
127 			if (err == -ENOMEM && (opf & REQ_NOWAIT))
128 				bio_wouldblock_error(bio);
129 			else
130 				bio_io_error(bio);
131 			return false;
132 		}
133 	}
134 
135 	page = brd_lookup_page(brd, sector);
136 
137 	kaddr = bvec_kmap_local(&bv);
138 	if (op_is_write(opf)) {
139 		BUG_ON(!page);
140 		memcpy_to_page(page, offset, kaddr, bv.bv_len);
141 	} else {
142 		if (page)
143 			memcpy_from_page(kaddr, page, offset, bv.bv_len);
144 		else
145 			memset(kaddr, 0, bv.bv_len);
146 	}
147 	kunmap_local(kaddr);
148 
149 	bio_advance_iter_single(bio, &bio->bi_iter, bv.bv_len);
150 	return true;
151 }
152 
153 static void brd_do_discard(struct brd_device *brd, sector_t sector, u32 size)
154 {
155 	sector_t aligned_sector = (sector + PAGE_SECTORS) & ~PAGE_SECTORS;
156 	struct page *page;
157 
158 	size -= (aligned_sector - sector) * SECTOR_SIZE;
159 	xa_lock(&brd->brd_pages);
160 	while (size >= PAGE_SIZE && aligned_sector < rd_size * 2) {
161 		page = __xa_erase(&brd->brd_pages, aligned_sector >> PAGE_SECTORS_SHIFT);
162 		if (page) {
163 			__free_page(page);
164 			brd->brd_nr_pages--;
165 		}
166 		aligned_sector += PAGE_SECTORS;
167 		size -= PAGE_SIZE;
168 	}
169 	xa_unlock(&brd->brd_pages);
170 }
171 
172 static void brd_submit_bio(struct bio *bio)
173 {
174 	struct brd_device *brd = bio->bi_bdev->bd_disk->private_data;
175 
176 	if (unlikely(op_is_discard(bio->bi_opf))) {
177 		brd_do_discard(brd, bio->bi_iter.bi_sector,
178 				bio->bi_iter.bi_size);
179 		bio_endio(bio);
180 		return;
181 	}
182 
183 	do {
184 		if (!brd_rw_bvec(brd, bio))
185 			return;
186 	} while (bio->bi_iter.bi_size);
187 
188 	bio_endio(bio);
189 }
190 
191 static const struct block_device_operations brd_fops = {
192 	.owner =		THIS_MODULE,
193 	.submit_bio =		brd_submit_bio,
194 };
195 
196 /*
197  * And now the modules code and kernel interface.
198  */
199 static int rd_nr = CONFIG_BLK_DEV_RAM_COUNT;
200 module_param(rd_nr, int, 0444);
201 MODULE_PARM_DESC(rd_nr, "Maximum number of brd devices");
202 
203 unsigned long rd_size = CONFIG_BLK_DEV_RAM_SIZE;
204 module_param(rd_size, ulong, 0444);
205 MODULE_PARM_DESC(rd_size, "Size of each RAM disk in kbytes.");
206 
207 static int max_part = 1;
208 module_param(max_part, int, 0444);
209 MODULE_PARM_DESC(max_part, "Num Minors to reserve between devices");
210 
211 MODULE_DESCRIPTION("Ram backed block device driver");
212 MODULE_LICENSE("GPL");
213 MODULE_ALIAS_BLOCKDEV_MAJOR(RAMDISK_MAJOR);
214 MODULE_ALIAS("rd");
215 
216 #ifndef MODULE
217 /* Legacy boot options - nonmodular */
218 static int __init ramdisk_size(char *str)
219 {
220 	rd_size = simple_strtol(str, NULL, 0);
221 	return 1;
222 }
223 __setup("ramdisk_size=", ramdisk_size);
224 #endif
225 
226 /*
227  * The device scheme is derived from loop.c. Keep them in synch where possible
228  * (should share code eventually).
229  */
230 static LIST_HEAD(brd_devices);
231 static DEFINE_MUTEX(brd_devices_mutex);
232 static struct dentry *brd_debugfs_dir;
233 
234 static struct brd_device *brd_find_or_alloc_device(int i)
235 {
236 	struct brd_device *brd;
237 
238 	mutex_lock(&brd_devices_mutex);
239 	list_for_each_entry(brd, &brd_devices, brd_list) {
240 		if (brd->brd_number == i) {
241 			mutex_unlock(&brd_devices_mutex);
242 			return ERR_PTR(-EEXIST);
243 		}
244 	}
245 
246 	brd = kzalloc(sizeof(*brd), GFP_KERNEL);
247 	if (!brd) {
248 		mutex_unlock(&brd_devices_mutex);
249 		return ERR_PTR(-ENOMEM);
250 	}
251 	brd->brd_number	= i;
252 	list_add_tail(&brd->brd_list, &brd_devices);
253 	mutex_unlock(&brd_devices_mutex);
254 	return brd;
255 }
256 
257 static void brd_free_device(struct brd_device *brd)
258 {
259 	mutex_lock(&brd_devices_mutex);
260 	list_del(&brd->brd_list);
261 	mutex_unlock(&brd_devices_mutex);
262 	kfree(brd);
263 }
264 
265 static int brd_alloc(int i)
266 {
267 	struct brd_device *brd;
268 	struct gendisk *disk;
269 	char buf[DISK_NAME_LEN];
270 	int err = -ENOMEM;
271 	struct queue_limits lim = {
272 		/*
273 		 * This is so fdisk will align partitions on 4k, because of
274 		 * direct_access API needing 4k alignment, returning a PFN
275 		 * (This is only a problem on very small devices <= 4M,
276 		 *  otherwise fdisk will align on 1M. Regardless this call
277 		 *  is harmless)
278 		 */
279 		.physical_block_size	= PAGE_SIZE,
280 		.max_hw_discard_sectors	= UINT_MAX,
281 		.max_discard_segments	= 1,
282 		.discard_granularity	= PAGE_SIZE,
283 		.features		= BLK_FEAT_SYNCHRONOUS |
284 					  BLK_FEAT_NOWAIT,
285 	};
286 
287 	brd = brd_find_or_alloc_device(i);
288 	if (IS_ERR(brd))
289 		return PTR_ERR(brd);
290 
291 	xa_init(&brd->brd_pages);
292 
293 	snprintf(buf, DISK_NAME_LEN, "ram%d", i);
294 	if (!IS_ERR_OR_NULL(brd_debugfs_dir))
295 		debugfs_create_u64(buf, 0444, brd_debugfs_dir,
296 				&brd->brd_nr_pages);
297 
298 	disk = brd->brd_disk = blk_alloc_disk(&lim, NUMA_NO_NODE);
299 	if (IS_ERR(disk)) {
300 		err = PTR_ERR(disk);
301 		goto out_free_dev;
302 	}
303 	disk->major		= RAMDISK_MAJOR;
304 	disk->first_minor	= i * max_part;
305 	disk->minors		= max_part;
306 	disk->fops		= &brd_fops;
307 	disk->private_data	= brd;
308 	strscpy(disk->disk_name, buf, DISK_NAME_LEN);
309 	set_capacity(disk, rd_size * 2);
310 
311 	err = add_disk(disk);
312 	if (err)
313 		goto out_cleanup_disk;
314 
315 	return 0;
316 
317 out_cleanup_disk:
318 	put_disk(disk);
319 out_free_dev:
320 	brd_free_device(brd);
321 	return err;
322 }
323 
324 static void brd_probe(dev_t dev)
325 {
326 	brd_alloc(MINOR(dev) / max_part);
327 }
328 
329 static void brd_cleanup(void)
330 {
331 	struct brd_device *brd, *next;
332 
333 	debugfs_remove_recursive(brd_debugfs_dir);
334 
335 	list_for_each_entry_safe(brd, next, &brd_devices, brd_list) {
336 		del_gendisk(brd->brd_disk);
337 		put_disk(brd->brd_disk);
338 		brd_free_pages(brd);
339 		brd_free_device(brd);
340 	}
341 }
342 
343 static inline void brd_check_and_reset_par(void)
344 {
345 	if (unlikely(!max_part))
346 		max_part = 1;
347 
348 	/*
349 	 * make sure 'max_part' can be divided exactly by (1U << MINORBITS),
350 	 * otherwise, it is possiable to get same dev_t when adding partitions.
351 	 */
352 	if ((1U << MINORBITS) % max_part != 0)
353 		max_part = 1UL << fls(max_part);
354 
355 	if (max_part > DISK_MAX_PARTS) {
356 		pr_info("brd: max_part can't be larger than %d, reset max_part = %d.\n",
357 			DISK_MAX_PARTS, DISK_MAX_PARTS);
358 		max_part = DISK_MAX_PARTS;
359 	}
360 }
361 
362 static int __init brd_init(void)
363 {
364 	int err, i;
365 
366 	/*
367 	 * brd module now has a feature to instantiate underlying device
368 	 * structure on-demand, provided that there is an access dev node.
369 	 *
370 	 * (1) if rd_nr is specified, create that many upfront. else
371 	 *     it defaults to CONFIG_BLK_DEV_RAM_COUNT
372 	 * (2) User can further extend brd devices by create dev node themselves
373 	 *     and have kernel automatically instantiate actual device
374 	 *     on-demand. Example:
375 	 *		mknod /path/devnod_name b 1 X	# 1 is the rd major
376 	 *		fdisk -l /path/devnod_name
377 	 *	If (X / max_part) was not already created it will be created
378 	 *	dynamically.
379 	 */
380 
381 	brd_check_and_reset_par();
382 
383 	brd_debugfs_dir = debugfs_create_dir("ramdisk_pages", NULL);
384 
385 	if (__register_blkdev(RAMDISK_MAJOR, "ramdisk", brd_probe)) {
386 		err = -EIO;
387 		goto out_free;
388 	}
389 
390 	for (i = 0; i < rd_nr; i++)
391 		brd_alloc(i);
392 
393 	pr_info("brd: module loaded\n");
394 	return 0;
395 
396 out_free:
397 	brd_cleanup();
398 
399 	pr_info("brd: module NOT loaded !!!\n");
400 	return err;
401 }
402 
403 static void __exit brd_exit(void)
404 {
405 
406 	unregister_blkdev(RAMDISK_MAJOR, "ramdisk");
407 	brd_cleanup();
408 
409 	pr_info("brd: module unloaded\n");
410 }
411 
412 module_init(brd_init);
413 module_exit(brd_exit);
414 
415