1/*
2 * block2mtd.c - create an mtd from a block device
3 *
4 * Copyright (C) 2001,2002	Simon Evans <spse@secret.org.uk>
5 * Copyright (C) 2004-2006	Joern Engel <joern@wh.fh-wedel.de>
6 *
7 * Licence: GPL
8 */
9
10#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11
12/*
13 * When the first attempt at device initialization fails, we may need to
14 * wait a little bit and retry. This timeout, by default 3 seconds, gives
15 * device time to start up. Required on BCM2708 and a few other chipsets.
16 */
17#define MTD_DEFAULT_TIMEOUT	3
18
19#include <linux/module.h>
20#include <linux/delay.h>
21#include <linux/fs.h>
22#include <linux/blkdev.h>
23#include <linux/bio.h>
24#include <linux/pagemap.h>
25#include <linux/list.h>
26#include <linux/init.h>
27#include <linux/mtd/mtd.h>
28#include <linux/mutex.h>
29#include <linux/mount.h>
30#include <linux/slab.h>
31#include <linux/major.h>
32
33/* Info for the block device */
34struct block2mtd_dev {
35	struct list_head list;
36	struct block_device *blkdev;
37	struct mtd_info mtd;
38	struct mutex write_mutex;
39};
40
41
42/* Static info about the MTD, used in cleanup_module */
43static LIST_HEAD(blkmtd_device_list);
44
45
46static struct page *page_read(struct address_space *mapping, int index)
47{
48	return read_mapping_page(mapping, index, NULL);
49}
50
51/* erase a specified part of the device */
52static int _block2mtd_erase(struct block2mtd_dev *dev, loff_t to, size_t len)
53{
54	struct address_space *mapping = dev->blkdev->bd_inode->i_mapping;
55	struct page *page;
56	int index = to >> PAGE_SHIFT;	// page index
57	int pages = len >> PAGE_SHIFT;
58	u_long *p;
59	u_long *max;
60
61	while (pages) {
62		page = page_read(mapping, index);
63		if (IS_ERR(page))
64			return PTR_ERR(page);
65
66		max = page_address(page) + PAGE_SIZE;
67		for (p=page_address(page); p<max; p++)
68			if (*p != -1UL) {
69				lock_page(page);
70				memset(page_address(page), 0xff, PAGE_SIZE);
71				set_page_dirty(page);
72				unlock_page(page);
73				balance_dirty_pages_ratelimited(mapping);
74				break;
75			}
76
77		page_cache_release(page);
78		pages--;
79		index++;
80	}
81	return 0;
82}
83static int block2mtd_erase(struct mtd_info *mtd, struct erase_info *instr)
84{
85	struct block2mtd_dev *dev = mtd->priv;
86	size_t from = instr->addr;
87	size_t len = instr->len;
88	int err;
89
90	instr->state = MTD_ERASING;
91	mutex_lock(&dev->write_mutex);
92	err = _block2mtd_erase(dev, from, len);
93	mutex_unlock(&dev->write_mutex);
94	if (err) {
95		pr_err("erase failed err = %d\n", err);
96		instr->state = MTD_ERASE_FAILED;
97	} else
98		instr->state = MTD_ERASE_DONE;
99
100	mtd_erase_callback(instr);
101	return err;
102}
103
104
105static int block2mtd_read(struct mtd_info *mtd, loff_t from, size_t len,
106		size_t *retlen, u_char *buf)
107{
108	struct block2mtd_dev *dev = mtd->priv;
109	struct page *page;
110	int index = from >> PAGE_SHIFT;
111	int offset = from & (PAGE_SIZE-1);
112	int cpylen;
113
114	while (len) {
115		if ((offset + len) > PAGE_SIZE)
116			cpylen = PAGE_SIZE - offset;	// multiple pages
117		else
118			cpylen = len;	// this page
119		len = len - cpylen;
120
121		page = page_read(dev->blkdev->bd_inode->i_mapping, index);
122		if (IS_ERR(page))
123			return PTR_ERR(page);
124
125		memcpy(buf, page_address(page) + offset, cpylen);
126		page_cache_release(page);
127
128		if (retlen)
129			*retlen += cpylen;
130		buf += cpylen;
131		offset = 0;
132		index++;
133	}
134	return 0;
135}
136
137
138/* write data to the underlying device */
139static int _block2mtd_write(struct block2mtd_dev *dev, const u_char *buf,
140		loff_t to, size_t len, size_t *retlen)
141{
142	struct page *page;
143	struct address_space *mapping = dev->blkdev->bd_inode->i_mapping;
144	int index = to >> PAGE_SHIFT;	// page index
145	int offset = to & ~PAGE_MASK;	// page offset
146	int cpylen;
147
148	while (len) {
149		if ((offset+len) > PAGE_SIZE)
150			cpylen = PAGE_SIZE - offset;	// multiple pages
151		else
152			cpylen = len;			// this page
153		len = len - cpylen;
154
155		page = page_read(mapping, index);
156		if (IS_ERR(page))
157			return PTR_ERR(page);
158
159		if (memcmp(page_address(page)+offset, buf, cpylen)) {
160			lock_page(page);
161			memcpy(page_address(page) + offset, buf, cpylen);
162			set_page_dirty(page);
163			unlock_page(page);
164			balance_dirty_pages_ratelimited(mapping);
165		}
166		page_cache_release(page);
167
168		if (retlen)
169			*retlen += cpylen;
170
171		buf += cpylen;
172		offset = 0;
173		index++;
174	}
175	return 0;
176}
177
178
179static int block2mtd_write(struct mtd_info *mtd, loff_t to, size_t len,
180		size_t *retlen, const u_char *buf)
181{
182	struct block2mtd_dev *dev = mtd->priv;
183	int err;
184
185	mutex_lock(&dev->write_mutex);
186	err = _block2mtd_write(dev, buf, to, len, retlen);
187	mutex_unlock(&dev->write_mutex);
188	if (err > 0)
189		err = 0;
190	return err;
191}
192
193
194/* sync the device - wait until the write queue is empty */
195static void block2mtd_sync(struct mtd_info *mtd)
196{
197	struct block2mtd_dev *dev = mtd->priv;
198	sync_blockdev(dev->blkdev);
199	return;
200}
201
202
203static void block2mtd_free_device(struct block2mtd_dev *dev)
204{
205	if (!dev)
206		return;
207
208	kfree(dev->mtd.name);
209
210	if (dev->blkdev) {
211		invalidate_mapping_pages(dev->blkdev->bd_inode->i_mapping,
212					0, -1);
213		blkdev_put(dev->blkdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
214	}
215
216	kfree(dev);
217}
218
219
220static struct block2mtd_dev *add_device(char *devname, int erase_size,
221		int timeout)
222{
223#ifndef MODULE
224	int i;
225#endif
226	const fmode_t mode = FMODE_READ | FMODE_WRITE | FMODE_EXCL;
227	struct block_device *bdev = ERR_PTR(-ENODEV);
228	struct block2mtd_dev *dev;
229	char *name;
230
231	if (!devname)
232		return NULL;
233
234	dev = kzalloc(sizeof(struct block2mtd_dev), GFP_KERNEL);
235	if (!dev)
236		return NULL;
237
238	/* Get a handle on the device */
239	bdev = blkdev_get_by_path(devname, mode, dev);
240
241#ifndef MODULE
242	/*
243	 * We might not have the root device mounted at this point.
244	 * Try to resolve the device name by other means.
245	 */
246	for (i = 0; IS_ERR(bdev) && i <= timeout; i++) {
247		dev_t devt;
248
249		if (i)
250			/*
251			 * Calling wait_for_device_probe in the first loop
252			 * was not enough, sleep for a bit in subsequent
253			 * go-arounds.
254			 */
255			msleep(1000);
256		wait_for_device_probe();
257
258		devt = name_to_dev_t(devname);
259		if (!devt)
260			continue;
261		bdev = blkdev_get_by_dev(devt, mode, dev);
262	}
263#endif
264
265	if (IS_ERR(bdev)) {
266		pr_err("error: cannot open device %s\n", devname);
267		goto err_free_block2mtd;
268	}
269	dev->blkdev = bdev;
270
271	if (MAJOR(bdev->bd_dev) == MTD_BLOCK_MAJOR) {
272		pr_err("attempting to use an MTD device as a block device\n");
273		goto err_free_block2mtd;
274	}
275
276	if ((long)dev->blkdev->bd_inode->i_size % erase_size) {
277		pr_err("erasesize must be a divisor of device size\n");
278		goto err_free_block2mtd;
279	}
280
281	mutex_init(&dev->write_mutex);
282
283	/* Setup the MTD structure */
284	/* make the name contain the block device in */
285	name = kasprintf(GFP_KERNEL, "block2mtd: %s", devname);
286	if (!name)
287		goto err_destroy_mutex;
288
289	dev->mtd.name = name;
290
291	dev->mtd.size = dev->blkdev->bd_inode->i_size & PAGE_MASK;
292	dev->mtd.erasesize = erase_size;
293	dev->mtd.writesize = 1;
294	dev->mtd.writebufsize = PAGE_SIZE;
295	dev->mtd.type = MTD_RAM;
296	dev->mtd.flags = MTD_CAP_RAM;
297	dev->mtd._erase = block2mtd_erase;
298	dev->mtd._write = block2mtd_write;
299	dev->mtd._sync = block2mtd_sync;
300	dev->mtd._read = block2mtd_read;
301	dev->mtd.priv = dev;
302	dev->mtd.owner = THIS_MODULE;
303
304	if (mtd_device_register(&dev->mtd, NULL, 0)) {
305		/* Device didn't get added, so free the entry */
306		goto err_destroy_mutex;
307	}
308
309	list_add(&dev->list, &blkmtd_device_list);
310	pr_info("mtd%d: [%s] erase_size = %dKiB [%d]\n",
311		dev->mtd.index,
312		dev->mtd.name + strlen("block2mtd: "),
313		dev->mtd.erasesize >> 10, dev->mtd.erasesize);
314	return dev;
315
316err_destroy_mutex:
317	mutex_destroy(&dev->write_mutex);
318err_free_block2mtd:
319	block2mtd_free_device(dev);
320	return NULL;
321}
322
323
324/* This function works similar to reguler strtoul.  In addition, it
325 * allows some suffixes for a more human-readable number format:
326 * ki, Ki, kiB, KiB	- multiply result with 1024
327 * Mi, MiB		- multiply result with 1024^2
328 * Gi, GiB		- multiply result with 1024^3
329 */
330static int ustrtoul(const char *cp, char **endp, unsigned int base)
331{
332	unsigned long result = simple_strtoul(cp, endp, base);
333	switch (**endp) {
334	case 'G' :
335		result *= 1024;
336	case 'M':
337		result *= 1024;
338	case 'K':
339	case 'k':
340		result *= 1024;
341	/* By dwmw2 editorial decree, "ki", "Mi" or "Gi" are to be used. */
342		if ((*endp)[1] == 'i') {
343			if ((*endp)[2] == 'B')
344				(*endp) += 3;
345			else
346				(*endp) += 2;
347		}
348	}
349	return result;
350}
351
352
353static int parse_num(size_t *num, const char *token)
354{
355	char *endp;
356	size_t n;
357
358	n = (size_t) ustrtoul(token, &endp, 0);
359	if (*endp)
360		return -EINVAL;
361
362	*num = n;
363	return 0;
364}
365
366
367static inline void kill_final_newline(char *str)
368{
369	char *newline = strrchr(str, '\n');
370	if (newline && !newline[1])
371		*newline = 0;
372}
373
374
375#ifndef MODULE
376static int block2mtd_init_called = 0;
377/* 80 for device, 12 for erase size */
378static char block2mtd_paramline[80 + 12];
379#endif
380
381static int block2mtd_setup2(const char *val)
382{
383	/* 80 for device, 12 for erase size, 80 for name, 8 for timeout */
384	char buf[80 + 12 + 80 + 8];
385	char *str = buf;
386	char *token[2];
387	char *name;
388	size_t erase_size = PAGE_SIZE;
389	unsigned long timeout = MTD_DEFAULT_TIMEOUT;
390	int i, ret;
391
392	if (strnlen(val, sizeof(buf)) >= sizeof(buf)) {
393		pr_err("parameter too long\n");
394		return 0;
395	}
396
397	strcpy(str, val);
398	kill_final_newline(str);
399
400	for (i = 0; i < 2; i++)
401		token[i] = strsep(&str, ",");
402
403	if (str) {
404		pr_err("too many arguments\n");
405		return 0;
406	}
407
408	if (!token[0]) {
409		pr_err("no argument\n");
410		return 0;
411	}
412
413	name = token[0];
414	if (strlen(name) + 1 > 80) {
415		pr_err("device name too long\n");
416		return 0;
417	}
418
419	if (token[1]) {
420		ret = parse_num(&erase_size, token[1]);
421		if (ret) {
422			pr_err("illegal erase size\n");
423			return 0;
424		}
425	}
426
427	add_device(name, erase_size, timeout);
428
429	return 0;
430}
431
432
433static int block2mtd_setup(const char *val, struct kernel_param *kp)
434{
435#ifdef MODULE
436	return block2mtd_setup2(val);
437#else
438	/* If more parameters are later passed in via
439	   /sys/module/block2mtd/parameters/block2mtd
440	   and block2mtd_init() has already been called,
441	   we can parse the argument now. */
442
443	if (block2mtd_init_called)
444		return block2mtd_setup2(val);
445
446	/* During early boot stage, we only save the parameters
447	   here. We must parse them later: if the param passed
448	   from kernel boot command line, block2mtd_setup() is
449	   called so early that it is not possible to resolve
450	   the device (even kmalloc() fails). Deter that work to
451	   block2mtd_setup2(). */
452
453	strlcpy(block2mtd_paramline, val, sizeof(block2mtd_paramline));
454
455	return 0;
456#endif
457}
458
459
460module_param_call(block2mtd, block2mtd_setup, NULL, NULL, 0200);
461MODULE_PARM_DESC(block2mtd, "Device to use. \"block2mtd=<dev>[,<erasesize>]\"");
462
463static int __init block2mtd_init(void)
464{
465	int ret = 0;
466
467#ifndef MODULE
468	if (strlen(block2mtd_paramline))
469		ret = block2mtd_setup2(block2mtd_paramline);
470	block2mtd_init_called = 1;
471#endif
472
473	return ret;
474}
475
476
477static void block2mtd_exit(void)
478{
479	struct list_head *pos, *next;
480
481	/* Remove the MTD devices */
482	list_for_each_safe(pos, next, &blkmtd_device_list) {
483		struct block2mtd_dev *dev = list_entry(pos, typeof(*dev), list);
484		block2mtd_sync(&dev->mtd);
485		mtd_device_unregister(&dev->mtd);
486		mutex_destroy(&dev->write_mutex);
487		pr_info("mtd%d: [%s] removed\n",
488			dev->mtd.index,
489			dev->mtd.name + strlen("block2mtd: "));
490		list_del(&dev->list);
491		block2mtd_free_device(dev);
492	}
493}
494
495late_initcall(block2mtd_init);
496module_exit(block2mtd_exit);
497
498MODULE_LICENSE("GPL");
499MODULE_AUTHOR("Joern Engel <joern@lazybastard.org>");
500MODULE_DESCRIPTION("Emulate an MTD using a block device");
501