1 /*
2  * $Id: blkmtd.c,v 1.17 2003/01/24 13:00:24 dwmw2 Exp $
3  *
4  * blkmtd.c - use a block device as a fake MTD
5  *
6  * Author: Simon Evans <spse@secret.org.uk>
7  *
8  * Copyright (C) 2001,2002 Simon Evans
9  *
10  * Licence: GPL
11  *
12  * How it works:
13  *	The driver uses raw/io to read/write the device and the page
14  *	cache to cache access. Writes update the page cache with the
15  *	new data and mark it dirty and add the page into a kiobuf.
16  *	When the kiobuf becomes full or the next extry is to an earlier
17  *	block in the kiobuf then it is flushed to disk. This allows
18  *	writes to remained ordered and gives a small and simple outgoing
19  *	write cache.
20  *
21  *	It can be loaded Read-Only to prevent erases and writes to the
22  *	medium.
23  *
24  */
25 
26 #include <linux/config.h>
27 #include <linux/module.h>
28 #include <linux/fs.h>
29 #include <linux/blkdev.h>
30 #include <linux/iobuf.h>
31 #include <linux/slab.h>
32 #include <linux/pagemap.h>
33 #include <linux/list.h>
34 #include <linux/mtd/mtd.h>
35 
36 #ifdef CONFIG_MTD_DEBUG
37 #ifdef CONFIG_PROC_FS
38 #  include <linux/proc_fs.h>
39 #  define BLKMTD_PROC_DEBUG
40    static struct proc_dir_entry *blkmtd_proc;
41 #endif
42 #endif
43 
44 
45 #define err(format, arg...) printk(KERN_ERR "blkmtd: " format "\n" , ## arg)
46 #define info(format, arg...) printk(KERN_INFO "blkmtd: " format "\n" , ## arg)
47 #define warn(format, arg...) printk(KERN_WARNING "blkmtd: " format "\n" , ## arg)
48 #define crit(format, arg...) printk(KERN_CRIT "blkmtd: " format "\n" , ## arg)
49 
50 
51 /* Default erase size in KiB, always make it a multiple of PAGE_SIZE */
52 #define CONFIG_MTD_BLKDEV_ERASESIZE (128 << 10)	/* 128KiB */
53 #define VERSION "1.10"
54 
55 /* Info for the block device */
56 struct blkmtd_dev {
57 	struct list_head list;
58 	struct block_device *binding;
59 	struct mtd_info mtd_info;
60 	struct kiobuf *rd_buf, *wr_buf;
61 	long iobuf_locks;
62 	struct semaphore wrbuf_mutex;
63 };
64 
65 
66 /* Static info about the MTD, used in cleanup_module */
67 static LIST_HEAD(blkmtd_device_list);
68 
69 
70 static void blkmtd_sync(struct mtd_info *mtd);
71 
72 #define MAX_DEVICES 4
73 
74 /* Module parameters passed by insmod/modprobe */
75 char *device[MAX_DEVICES];    /* the block device to use */
76 int erasesz[MAX_DEVICES];     /* optional default erase size */
77 int ro[MAX_DEVICES];          /* optional read only flag */
78 int sync;
79 
80 
81 MODULE_LICENSE("GPL");
82 MODULE_AUTHOR("Simon Evans <spse@secret.org.uk>");
83 MODULE_DESCRIPTION("Emulate an MTD using a block device");
84 MODULE_PARM(device, "1-4s");
85 MODULE_PARM_DESC(device, "block device to use");
86 MODULE_PARM(erasesz, "1-4i");
87 MODULE_PARM_DESC(erasesz, "optional erase size to use in KiB. eg 4=4KiB.");
88 MODULE_PARM(ro, "1-4i");
89 MODULE_PARM_DESC(ro, "1=Read only, writes and erases cause errors");
90 MODULE_PARM(sync, "i");
91 MODULE_PARM_DESC(sync, "1=Synchronous writes");
92 
93 
94 /**
95  * read_pages - read in pages via the page cache
96  * @dev: device to read from
97  * @pagenrs: list of page numbers wanted
98  * @pagelst: storage for struce page * pointers
99  * @pages: count of pages wanted
100  *
101  * Read pages, getting them from the page cache if available
102  * else reading them in from disk if not. pagelst must be preallocated
103  * to hold the page count.
104  */
read_pages(struct blkmtd_dev * dev,int pagenrs[],struct page ** pagelst,int pages)105 static int read_pages(struct blkmtd_dev *dev, int pagenrs[], struct page **pagelst, int pages)
106 {
107 	kdev_t kdev;
108 	struct page *page;
109 	int cnt = 0;
110 	struct kiobuf *iobuf;
111 	int err = 0;
112 
113 	if(!dev) {
114 		err("read_pages: PANIC dev == NULL");
115 		return -EIO;
116 	}
117 	kdev = to_kdev_t(dev->binding->bd_dev);
118 
119 	DEBUG(2, "read_pages: reading %d pages\n", pages);
120 	if(test_and_set_bit(0, &dev->iobuf_locks)) {
121 		err = alloc_kiovec(1, &iobuf);
122 		if (err) {
123 			crit("cant allocate kiobuf");
124 			return -ENOMEM;
125 		}
126 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
127 		iobuf->blocks = kmalloc(KIO_MAX_SECTORS * sizeof(unsigned long), GFP_KERNEL);
128 		if(iobuf->blocks == NULL) {
129 			crit("cant allocate iobuf blocks");
130 			free_kiovec(1, &iobuf);
131 			return -ENOMEM;
132 		}
133 #endif
134 	} else {
135 		iobuf = dev->rd_buf;
136 	}
137 
138 	iobuf->nr_pages = 0;
139 	iobuf->length = 0;
140 	iobuf->offset = 0;
141 	iobuf->locked = 1;
142 
143 	for(cnt = 0; cnt < pages; cnt++) {
144 		page = grab_cache_page(dev->binding->bd_inode->i_mapping, pagenrs[cnt]);
145 		pagelst[cnt] = page;
146 		if(!PageUptodate(page)) {
147 				iobuf->blocks[iobuf->nr_pages] = pagenrs[cnt];
148 				iobuf->maplist[iobuf->nr_pages++] = page;
149 		}
150 	}
151 
152 	if(iobuf->nr_pages) {
153 		iobuf->length = iobuf->nr_pages << PAGE_SHIFT;
154 		err = brw_kiovec(READ, 1, &iobuf, kdev, iobuf->blocks, PAGE_SIZE);
155 		DEBUG(3, "blkmtd: read_pages: finished, err = %d\n", err);
156 		if(err < 0) {
157 			while(pages--) {
158 				ClearPageUptodate(pagelst[pages]);
159 				unlock_page(pagelst[pages]);
160 				page_cache_release(pagelst[pages]);
161 			}
162 		} else {
163 			while(iobuf->nr_pages--) {
164 				SetPageUptodate(iobuf->maplist[iobuf->nr_pages]);
165 			}
166 			err = 0;
167 		}
168 	}
169 
170 
171 	if(iobuf != dev->rd_buf) {
172 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
173 		kfree(iobuf->blocks);
174 #endif
175 		free_kiovec(1, &iobuf);
176 	} else {
177 		clear_bit(0, &dev->iobuf_locks);
178 	}
179 	DEBUG(2, "read_pages: done, err = %d\n", err);
180 	return err;
181 }
182 
183 
184 /**
185  * commit_pages - commit pages in the writeout kiobuf to disk
186  * @dev: device to write to
187  *
188  * If the current dev has pages in the dev->wr_buf kiobuf,
189  * they are written to disk using brw_kiovec()
190  */
commit_pages(struct blkmtd_dev * dev)191 static int commit_pages(struct blkmtd_dev *dev)
192 {
193 	struct kiobuf *iobuf = dev->wr_buf;
194 	kdev_t kdev = to_kdev_t(dev->binding->bd_dev);
195 	int err = 0;
196 
197 	iobuf->length = iobuf->nr_pages << PAGE_SHIFT;
198 	iobuf->offset = 0;	/* all pages are aligned */
199 	iobuf->locked = 1;
200 	if(iobuf->length) {
201 		int i;
202 		DEBUG(2, "blkmtd: commit_pages: nrpages = %d\n", iobuf->nr_pages);
203 		/* Check all the pages are dirty and lock them */
204 		for(i = 0; i < iobuf->nr_pages; i++) {
205 			struct page *page = iobuf->maplist[i];
206 			BUG_ON(!PageDirty(page));
207 			lock_page(page);
208 		}
209 		err = brw_kiovec(WRITE, 1, &iobuf, kdev, iobuf->blocks, PAGE_SIZE);
210 		DEBUG(3, "commit_write: committed %d pages err = %d\n", iobuf->nr_pages, err);
211 		while(iobuf->nr_pages) {
212 			struct page *page = iobuf->maplist[--iobuf->nr_pages];
213 			ClearPageDirty(page);
214 			SetPageUptodate(page);
215 			unlock_page(page);
216 			page_cache_release(page);
217 		}
218 	}
219 
220 	DEBUG(2, "blkmtd: sync: end, err = %d\n", err);
221 	iobuf->offset = 0;
222 	iobuf->nr_pages = 0;
223 	iobuf->length = 0;
224 	return err;
225 }
226 
227 
228 /**
229  * write_pages - write block of data to device via the page cache
230  * @dev: device to write to
231  * @buf: data source or NULL if erase (output is set to 0xff)
232  * @to: offset into output device
233  * @len: amount to data to write
234  * @retlen: amount of data written
235  *
236  * Grab pages from the page cache and fill them with the source data.
237  * Non page aligned start and end result in a readin of the page and
238  * part of the page being modified. Pages are added to the wr_buf kiobuf
239  * until this becomes full or the next page written to has a lower pagenr
240  * then the current max pagenr in the kiobuf.
241  */
write_pages(struct blkmtd_dev * dev,const u_char * buf,loff_t to,size_t len,int * retlen)242 static int write_pages(struct blkmtd_dev *dev, const u_char *buf, loff_t to,
243 		    size_t len, int *retlen)
244 {
245 	int pagenr, offset;
246 	size_t start_len = 0, end_len;
247 	int pagecnt = 0;
248 	struct kiobuf *iobuf = dev->wr_buf;
249 	int err = 0;
250 	struct page *pagelst[2];
251 	int pagenrs[2];
252 	int readpages = 0;
253 	int ignorepage = -1;
254 
255 	pagenr = to >> PAGE_SHIFT;
256 	offset = to & ~PAGE_MASK;
257 
258 	DEBUG(2, "blkmtd: write_pages: buf = %p to = %ld len = %d pagenr = %d offset = %d\n",
259 	      buf, (long)to, len, pagenr, offset);
260 
261 	*retlen = 0;
262 	/* see if we have to do a partial write at the start */
263 	if(offset) {
264 		start_len = ((offset + len) > PAGE_SIZE) ? PAGE_SIZE - offset : len;
265 		len -= start_len;
266 	}
267 
268 	/* calculate the length of the other two regions */
269 	end_len = len & ~PAGE_MASK;
270 	len -= end_len;
271 
272 	if(start_len) {
273 		pagenrs[0] = pagenr;
274 		readpages++;
275 		pagecnt++;
276 	}
277 	if(len)
278 		pagecnt += len >> PAGE_SHIFT;
279 	if(end_len) {
280 		pagenrs[readpages] = pagenr + pagecnt;
281 		readpages++;
282 		pagecnt++;
283 	}
284 
285 	DEBUG(3, "blkmtd: write: start_len = %d len = %d end_len = %d pagecnt = %d\n",
286 	      start_len, len, end_len, pagecnt);
287 
288 	down(&dev->wrbuf_mutex);
289 
290 	if(iobuf->nr_pages && ((pagenr <= iobuf->blocks[iobuf->nr_pages-1])
291 			       || (iobuf->nr_pages + pagecnt) >= KIO_STATIC_PAGES)) {
292 
293 		if((pagenr == iobuf->blocks[iobuf->nr_pages-1])
294 		   && ((iobuf->nr_pages + pagecnt) < KIO_STATIC_PAGES)) {
295 			iobuf->nr_pages--;
296 			ignorepage = pagenr;
297 		} else {
298 			DEBUG(3, "blkmtd: doing writeout pagenr = %d max_pagenr = %ld pagecnt = %d idx = %d\n",
299 			      pagenr, iobuf->blocks[iobuf->nr_pages-1],
300 			      pagecnt, iobuf->nr_pages);
301 			commit_pages(dev);
302 		}
303 	}
304 
305 	if(readpages) {
306 		err = read_pages(dev, pagenrs, pagelst, readpages);
307 		if(err < 0)
308 			goto readin_err;
309 	}
310 
311 	if(start_len) {
312 		/* do partial start region */
313 		struct page *page;
314 
315 		DEBUG(3, "blkmtd: write: doing partial start, page = %d len = %d offset = %d\n",
316 		      pagenr, start_len, offset);
317 		page = pagelst[0];
318 		BUG_ON(!buf);
319 		if(PageDirty(page) && pagenr != ignorepage) {
320 			err("to = %lld start_len = %d len = %d end_len = %d pagenr = %d ignorepage = %d\n",
321 			    to, start_len, len, end_len, pagenr, ignorepage);
322 			BUG();
323 		}
324 		memcpy(page_address(page)+offset, buf, start_len);
325 		SetPageDirty(page);
326 		SetPageUptodate(page);
327 		unlock_page(page);
328 		buf += start_len;
329 		*retlen = start_len;
330 		err = 0;
331 		iobuf->blocks[iobuf->nr_pages] = pagenr++;
332 		iobuf->maplist[iobuf->nr_pages] = page;
333 		iobuf->nr_pages++;
334 	}
335 
336 	/* Now do the main loop to a page aligned, n page sized output */
337 	if(len) {
338 		int pagesc = len >> PAGE_SHIFT;
339 		DEBUG(3, "blkmtd: write: whole pages start = %d, count = %d\n",
340 		      pagenr, pagesc);
341 		while(pagesc) {
342 			struct page *page;
343 
344 			/* see if page is in the page cache */
345 			DEBUG(3, "blkmtd: write: grabbing page %d from page cache\n", pagenr);
346 			page = grab_cache_page(dev->binding->bd_inode->i_mapping, pagenr);
347 			if(PageDirty(page) && pagenr != ignorepage) {
348 				BUG();
349 			}
350 			if(!page) {
351 				warn("write: cant grab cache page %d", pagenr);
352 				err = -ENOMEM;
353 				goto write_err;
354 			}
355 			if(!buf) {
356 				memset(page_address(page), 0xff, PAGE_SIZE);
357 			} else {
358 				memcpy(page_address(page), buf, PAGE_SIZE);
359 				buf += PAGE_SIZE;
360 			}
361 			iobuf->blocks[iobuf->nr_pages] = pagenr++;
362 			iobuf->maplist[iobuf->nr_pages] = page;
363 			iobuf->nr_pages++;
364 			SetPageDirty(page);
365 			SetPageUptodate(page);
366 			unlock_page(page);
367 			pagesc--;
368 			*retlen += PAGE_SIZE;
369 		}
370 	}
371 
372 	if(end_len) {
373 		/* do the third region */
374 		struct page *page;
375 		DEBUG(3, "blkmtd: write: doing partial end, page = %d len = %d\n",
376 		      pagenr, end_len);
377 		page = pagelst[readpages-1];
378 		BUG_ON(!buf);
379 		if(PageDirty(page) && pagenr != ignorepage) {
380 			err("to = %lld start_len = %d len = %d end_len = %d pagenr = %d ignorepage = %d\n",
381 			    to, start_len, len, end_len, pagenr, ignorepage);
382 			BUG();
383 		}
384 		memcpy(page_address(page), buf, end_len);
385 		SetPageDirty(page);
386 		SetPageUptodate(page);
387 		unlock_page(page);
388 		DEBUG(3, "blkmtd: write: writing out partial end\n");
389 		*retlen += end_len;
390 		err = 0;
391 		iobuf->blocks[iobuf->nr_pages] = pagenr;
392 		iobuf->maplist[iobuf->nr_pages] = page;
393 		iobuf->nr_pages++;
394 	}
395 
396 	DEBUG(2, "blkmtd: write: end, retlen = %d, err = %d\n", *retlen, err);
397 
398 	if(sync) {
399 write_err:
400 		commit_pages(dev);
401 	}
402 
403 readin_err:
404 	up(&dev->wrbuf_mutex);
405 	return err;
406 }
407 
408 
409 /* erase a specified part of the device */
blkmtd_erase(struct mtd_info * mtd,struct erase_info * instr)410 static int blkmtd_erase(struct mtd_info *mtd, struct erase_info *instr)
411 {
412 	struct blkmtd_dev *dev = mtd->priv;
413 	struct mtd_erase_region_info *einfo = mtd->eraseregions;
414 	int numregions = mtd->numeraseregions;
415 	size_t from;
416 	u_long len;
417 	int err = -EIO;
418 	int retlen;
419 
420 	/* check readonly */
421 	if(!dev->wr_buf) {
422 		err("error: mtd%d trying to erase readonly device %s",
423 		    mtd->index, mtd->name);
424 		instr->state = MTD_ERASE_FAILED;
425 		goto erase_callback;
426 	}
427 
428 	instr->state = MTD_ERASING;
429 	from = instr->addr;
430 	len = instr->len;
431 
432 	/* check erase region has valid start and length */
433 	DEBUG(2, "blkmtd: erase: dev = `%s' from = 0x%x len = 0x%lx\n",
434 	      bdevname(dev->binding->bd_dev), from, len);
435 	while(numregions) {
436 		DEBUG(3, "blkmtd: checking erase region = 0x%08X size = 0x%X num = 0x%x\n",
437 		      einfo->offset, einfo->erasesize, einfo->numblocks);
438 		if(from >= einfo->offset
439 		   && from < einfo->offset + (einfo->erasesize * einfo->numblocks)) {
440 			if(len == einfo->erasesize
441 			   && ( (from - einfo->offset) % einfo->erasesize == 0))
442 				break;
443 		}
444 		numregions--;
445 		einfo++;
446 	}
447 
448 	if(!numregions) {
449 		/* Not a valid erase block */
450 		err("erase: invalid erase request 0x%lX @ 0x%08X", len, from);
451 		instr->state = MTD_ERASE_FAILED;
452 		err = -EIO;
453 	}
454 
455 	if(instr->state != MTD_ERASE_FAILED) {
456 		/* do the erase */
457 		DEBUG(3, "Doing erase from = %d len = %ld\n", from, len);
458 		err = write_pages(dev, NULL, from, len, &retlen);
459 		if(err < 0) {
460 			err("erase failed err = %d", err);
461 			instr->state = MTD_ERASE_FAILED;
462 		} else {
463 			instr->state = MTD_ERASE_DONE;
464 			err = 0;
465 		}
466 	}
467 
468 	DEBUG(3, "blkmtd: erase: checking callback\n");
469  erase_callback:
470 	if (instr->callback) {
471 		(*(instr->callback))(instr);
472 	}
473 	DEBUG(2, "blkmtd: erase: finished (err = %d)\n", err);
474 	return err;
475 }
476 
477 
478 /* read a range of the data via the page cache */
blkmtd_read(struct mtd_info * mtd,loff_t from,size_t len,size_t * retlen,u_char * buf)479 static int blkmtd_read(struct mtd_info *mtd, loff_t from, size_t len,
480 		       size_t *retlen, u_char *buf)
481 {
482 	struct blkmtd_dev *dev = mtd->priv;
483 	int err = 0;
484 	int offset;
485 	int pagenr, pages;
486 	struct page **pagelst;
487 	int *pagenrs;
488 	int i;
489 
490 	*retlen = 0;
491 
492 	DEBUG(2, "blkmtd: read: dev = `%s' from = %ld len = %d buf = %p\n",
493 	      bdevname(dev->binding->bd_dev), (long int)from, len, buf);
494 
495 	pagenr = from >> PAGE_SHIFT;
496 	offset = from - (pagenr << PAGE_SHIFT);
497 
498 	pages = (offset+len+PAGE_SIZE-1) >> PAGE_SHIFT;
499 	DEBUG(3, "blkmtd: read: pagenr = %d offset = %d, pages = %d\n",
500 	      pagenr, offset, pages);
501 
502 	pagelst = kmalloc(sizeof(struct page *) * pages, GFP_KERNEL);
503 	if(!pagelst)
504 		return -ENOMEM;
505 	pagenrs = kmalloc(sizeof(int) * pages, GFP_KERNEL);
506 	if(!pagenrs) {
507 		kfree(pagelst);
508 		return -ENOMEM;
509 	}
510 	for(i = 0; i < pages; i++)
511 		pagenrs[i] = pagenr+i;
512 
513 	err = read_pages(dev, pagenrs, pagelst, pages);
514 	if(err)
515 		goto readerr;
516 
517 	pagenr = 0;
518 	while(pages) {
519 		struct page *page;
520 		int cpylen;
521 
522 		DEBUG(3, "blkmtd: read: looking for page: %d\n", pagenr);
523 		page = pagelst[pagenr];
524 
525 		cpylen = (PAGE_SIZE > len) ? len : PAGE_SIZE;
526 		if(offset+cpylen > PAGE_SIZE)
527 			cpylen = PAGE_SIZE-offset;
528 
529 		memcpy(buf + *retlen, page_address(page) + offset, cpylen);
530 		offset = 0;
531 		len -= cpylen;
532 		*retlen += cpylen;
533 		pagenr++;
534 		pages--;
535 		unlock_page(page);
536 		if(!PageDirty(page))
537 			page_cache_release(page);
538 	}
539 
540  readerr:
541 	kfree(pagelst);
542 	kfree(pagenrs);
543 	DEBUG(2, "blkmtd: end read: retlen = %d, err = %d\n", *retlen, err);
544 	return err;
545 }
546 
547 
548 /* write data to the underlying device */
blkmtd_write(struct mtd_info * mtd,loff_t to,size_t len,size_t * retlen,const u_char * buf)549 static int blkmtd_write(struct mtd_info *mtd, loff_t to, size_t len,
550 			size_t *retlen, const u_char *buf)
551 {
552 	struct blkmtd_dev *dev = mtd->priv;
553 	int err;
554 
555 	*retlen = 0;
556 	if(!len)
557 		return 0;
558 
559 	DEBUG(2, "blkmtd: write: dev = `%s' to = %ld len = %d buf = %p\n",
560 	      bdevname(dev->binding->bd_dev), (long int)to, len, buf);
561 
562 	/* handle readonly and out of range numbers */
563 
564 	if(!dev->wr_buf) {
565 		err("error: trying to write to a readonly device %s", mtd->name);
566 		return -EROFS;
567 	}
568 
569 	if(to >= mtd->size) {
570 		return -ENOSPC;
571 	}
572 
573 	if(to + len > mtd->size) {
574 		len = (mtd->size - to);
575 	}
576 
577 	err = write_pages(dev, buf, to, len, retlen);
578 	if(err < 0)
579 		*retlen = 0;
580 	else
581 		err = 0;
582 	DEBUG(2, "blkmtd: write: end, err = %d\n", err);
583 	return err;
584 }
585 
586 
587 /* sync the device - wait until the write queue is empty */
blkmtd_sync(struct mtd_info * mtd)588 static void blkmtd_sync(struct mtd_info *mtd)
589 {
590 	struct blkmtd_dev *dev = mtd->priv;
591 	struct kiobuf *iobuf = dev->wr_buf;
592 
593 	DEBUG(2, "blkmtd: sync: called\n");
594 	if(iobuf == NULL)
595 		return;
596 
597 	DEBUG(3, "blkmtd: kiovec: length = %d nr_pages = %d\n",
598 	      iobuf->length, iobuf->nr_pages);
599 	down(&dev->wrbuf_mutex);
600 	if(iobuf->nr_pages)
601 		commit_pages(dev);
602 	up(&dev->wrbuf_mutex);
603 }
604 
605 
606 #ifdef BLKMTD_PROC_DEBUG
607 /* procfs stuff */
blkmtd_proc_read(char * page,char ** start,off_t off,int count,int * eof,void * data)608 static int blkmtd_proc_read(char *page, char **start, off_t off,
609 			    int count, int *eof, void *data)
610 {
611 	int len;
612 	struct list_head *temp1, *temp2;
613 
614 	MOD_INC_USE_COUNT;
615 
616 	/* Count the size of the page lists */
617 
618 	len = sprintf(page, "dev\twr_idx\tmax_idx\tnrpages\tclean\tdirty\tlocked\tlru\n");
619 	list_for_each_safe(temp1, temp2, &blkmtd_device_list) {
620 		struct blkmtd_dev *dev = list_entry(temp1,  struct blkmtd_dev,
621 						    list);
622 		struct list_head *temp;
623 		struct page *pagei;
624 
625 		int clean = 0, dirty = 0, locked = 0, lru = 0;
626 		/* Count the size of the page lists */
627 		list_for_each(temp, &dev->binding->bd_inode->i_mapping->clean_pages) {
628 			pagei = list_entry(temp, struct page, list);
629 			clean++;
630 			if(PageLocked(pagei))
631 				locked++;
632 			if(PageDirty(pagei))
633 				dirty++;
634 			if(PageLRU(pagei))
635 				lru++;
636 		}
637 		list_for_each(temp, &dev->binding->bd_inode->i_mapping->dirty_pages) {
638 			pagei = list_entry(temp, struct page, list);
639 			if(PageLocked(pagei))
640 				locked++;
641 			if(PageDirty(pagei))
642 				dirty++;
643 			if(PageLRU(pagei))
644 				lru++;
645 		}
646 		list_for_each(temp, &dev->binding->bd_inode->i_mapping->locked_pages) {
647 			pagei = list_entry(temp, struct page, list);
648 			if(PageLocked(pagei))
649 				locked++;
650 			if(PageDirty(pagei))
651 				dirty++;
652 			if(PageLRU(pagei))
653 				lru++;
654 		}
655 
656 		len += sprintf(page+len, "mtd%d:\t%ld\t%d\t%ld\t%d\t%d\t%d\t%d\n",
657 			       dev->mtd_info.index,
658 			       (dev->wr_buf && dev->wr_buf->nr_pages) ?
659 			       dev->wr_buf->blocks[dev->wr_buf->nr_pages-1] : 0,
660 			       (dev->wr_buf) ? dev->wr_buf->nr_pages : 0,
661 			       dev->binding->bd_inode->i_mapping->nrpages,
662 			       clean, dirty, locked, lru);
663 	}
664 
665 	if(len <= count)
666 		*eof = 1;
667 
668 	MOD_DEC_USE_COUNT;
669 	return len;
670 }
671 #endif
672 
673 
free_device(struct blkmtd_dev * dev)674 static void free_device(struct blkmtd_dev *dev)
675 {
676 	DEBUG(2, "blkmtd: free_device() dev = %p\n", dev);
677 	if(dev) {
678 		del_mtd_device(&dev->mtd_info);
679 		info("mtd%d: [%s] removed", dev->mtd_info.index,
680 		     dev->mtd_info.name + strlen("blkmtd: "));
681 		if(dev->mtd_info.eraseregions)
682 			kfree(dev->mtd_info.eraseregions);
683 		if(dev->mtd_info.name)
684 			kfree(dev->mtd_info.name);
685 
686 		if(dev->rd_buf) {
687 			dev->rd_buf->locked = 0;
688 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
689 			if(dev->rd_buf->blocks)
690 				kfree(dev->rd_buf->blocks);
691 #endif
692 			free_kiovec(1, &dev->rd_buf);
693 		}
694 		if(dev->wr_buf) {
695 			dev->wr_buf->locked = 0;
696 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
697 			if(dev->wr_buf->blocks)
698 				kfree(dev->rw_buf->blocks);
699 #endif
700 			free_kiovec(1, &dev->wr_buf);
701 		}
702 
703 		if(dev->binding) {
704 			kdev_t kdev = to_kdev_t(dev->binding->bd_dev);
705 			invalidate_inode_pages(dev->binding->bd_inode);
706 			set_blocksize(kdev, 1 << 10);
707 			blkdev_put(dev->binding, BDEV_RAW);
708 		}
709 		kfree(dev);
710 	}
711 }
712 
713 
714 /* For a given size and initial erase size, calculate the number
715  * and size of each erase region. Goes round the loop twice,
716  * once to find out how many regions, then allocates space,
717  * then round the loop again to fill it in.
718  */
calc_erase_regions(size_t erase_size,size_t total_size,int * regions)719 static struct mtd_erase_region_info *calc_erase_regions(
720 	size_t erase_size, size_t total_size, int *regions)
721 {
722 	struct mtd_erase_region_info *info = NULL;
723 
724 	DEBUG(2, "calc_erase_regions, es = %d size = %d regions = %d\n",
725 	      erase_size, total_size, *regions);
726 	/* Make any user specified erasesize be a power of 2
727 	   and at least PAGE_SIZE */
728 	if(erase_size) {
729 		int es = erase_size;
730 		erase_size = 1;
731 		while(es != 1) {
732 			es >>= 1;
733 			erase_size <<= 1;
734 		}
735 		if(erase_size < PAGE_SIZE)
736 			erase_size = PAGE_SIZE;
737 	} else {
738 		erase_size = CONFIG_MTD_BLKDEV_ERASESIZE;
739 	}
740 
741 	*regions = 0;
742 
743 	do {
744 		int tot_size = total_size;
745 		int er_size = erase_size;
746 		int count = 0, offset = 0, regcnt = 0;
747 
748 		while(tot_size) {
749 			count = tot_size / er_size;
750 			if(count) {
751 				tot_size = tot_size % er_size;
752 				if(info) {
753 					DEBUG(2, "adding to erase info off=%d er=%d cnt=%d\n",
754 					      offset, er_size, count);
755 					(info+regcnt)->offset = offset;
756 					(info+regcnt)->erasesize = er_size;
757 					(info+regcnt)->numblocks = count;
758 					(*regions)++;
759 				}
760 				regcnt++;
761 				offset += (count * er_size);
762 			}
763 			while(er_size > tot_size)
764 				er_size >>= 1;
765 		}
766 		if(info == NULL) {
767 			info = kmalloc(regcnt * sizeof(struct mtd_erase_region_info), GFP_KERNEL);
768 			if(!info)
769 				break;
770 		}
771 	} while(!(*regions));
772 	DEBUG(2, "calc_erase_regions done, es = %d size = %d regions = %d\n",
773 	      erase_size, total_size, *regions);
774 	return info;
775 }
776 
777 
778 extern kdev_t name_to_kdev_t(char *line) __init;
779 
780 
add_device(char * devname,int readonly,int erase_size)781 static struct blkmtd_dev *add_device(char *devname, int readonly, int erase_size)
782 {
783 	int maj, min;
784 	kdev_t kdev;
785 	int mode;
786 	struct blkmtd_dev *dev;
787 
788 #ifdef MODULE
789 	struct file *file = NULL;
790 	struct inode *inode;
791 #endif
792 
793 	if(!devname)
794 		return NULL;
795 
796 	/* Get a handle on the device */
797 	mode = (readonly) ? O_RDONLY : O_RDWR;
798 
799 #ifdef MODULE
800 
801 	file = filp_open(devname, mode, 0);
802 	if(IS_ERR(file)) {
803 		err("error: cant open device %s", devname);
804 		DEBUG(2, "blkmtd: filp_open returned %ld\n", PTR_ERR(file));
805 		return NULL;
806 	}
807 
808 	/* determine is this is a block device and
809 	 * if so get its major and minor numbers
810 	 */
811 	inode = file->f_dentry->d_inode;
812 	if(!S_ISBLK(inode->i_mode)) {
813 		err("%s not a block device", devname);
814 		filp_close(file, NULL);
815 		return NULL;
816 	}
817 	kdev = inode->i_rdev;
818 	filp_close(file, NULL);
819 #else
820 	kdev = name_to_kdev_t(devname);
821 #endif	/* MODULE */
822 
823 	if(!kdev) {
824 		err("bad block device: `%s'", devname);
825 		return NULL;
826 	}
827 
828 	maj = MAJOR(kdev);
829 	min = MINOR(kdev);
830 	DEBUG(1, "blkmtd: found a block device major = %d, minor = %d\n",
831 	      maj, min);
832 
833 	if(maj == MTD_BLOCK_MAJOR) {
834 		err("attempting to use an MTD device as a block device");
835 		return NULL;
836 	}
837 
838 	DEBUG(1, "blkmtd: devname = %s\n", bdevname(kdev));
839 
840 	dev = kmalloc(sizeof(struct blkmtd_dev), GFP_KERNEL);
841 	if(dev == NULL)
842 		return NULL;
843 
844 	memset(dev, 0, sizeof(struct blkmtd_dev));
845 	if(alloc_kiovec(1, &dev->rd_buf)) {
846 		err("cant allocate read iobuf");
847 		goto devinit_err;
848 	}
849 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
850 	dev->rd_buf->blocks = kmalloc(KIO_MAX_SECTORS * sizeof(unsigned long), GFP_KERNEL);
851 	if(dev->rd_buf->blocks == NULL) {
852 		crit("cant allocate rd_buf blocks");
853 		goto devinit_err;
854 	}
855 #endif
856 
857 	if(!readonly) {
858 		if(alloc_kiovec(1, &dev->wr_buf)) {
859 			err("cant allocate kiobuf - readonly enabled");
860 
861 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,4,4)
862 		} else {
863 			dev->wr_buf->blocks = kmalloc(KIO_MAX_SECTORS * sizeof(unsigned long), GFP_KERNEL);
864 			if(dev->wr_buf->blocks == NULL) {
865 				crit("cant allocate wr_buf blocks - readonly enabled");
866 				free_kiovec(1, &iobuf);
867 			}
868 #endif
869 		}
870 		if(dev->wr_buf)
871 			init_MUTEX(&dev->wrbuf_mutex);
872 	}
873 
874 	/* get the block device */
875 	dev->binding = bdget(kdev_t_to_nr(MKDEV(maj, min)));
876 	if(blkdev_get(dev->binding, mode, 0, BDEV_RAW))
877 		goto devinit_err;
878 
879 	if(set_blocksize(kdev, PAGE_SIZE)) {
880 		err("cant set block size to PAGE_SIZE on %s", bdevname(kdev));
881 		goto devinit_err;
882 	}
883 
884 	dev->mtd_info.size = dev->binding->bd_inode->i_size & PAGE_MASK;
885 
886 	/* Setup the MTD structure */
887 	/* make the name contain the block device in */
888 	dev->mtd_info.name = kmalloc(sizeof("blkmtd: ") + strlen(devname), GFP_KERNEL);
889 	if(dev->mtd_info.name == NULL)
890 		goto devinit_err;
891 
892 	sprintf(dev->mtd_info.name, "blkmtd: %s", devname);
893 	dev->mtd_info.eraseregions = calc_erase_regions(erase_size, dev->mtd_info.size,
894 							&dev->mtd_info.numeraseregions);
895 	if(dev->mtd_info.eraseregions == NULL)
896 		goto devinit_err;
897 
898 	dev->mtd_info.erasesize = dev->mtd_info.eraseregions->erasesize;
899 	DEBUG(1, "blkmtd: init: found %d erase regions\n",
900 	      dev->mtd_info.numeraseregions);
901 
902 	if(readonly) {
903 		dev->mtd_info.type = MTD_ROM;
904 		dev->mtd_info.flags = MTD_CAP_ROM;
905 	} else {
906 		dev->mtd_info.type = MTD_RAM;
907 		dev->mtd_info.flags = MTD_CAP_RAM;
908 	}
909 	dev->mtd_info.erase = blkmtd_erase;
910 	dev->mtd_info.read = blkmtd_read;
911 	dev->mtd_info.write = blkmtd_write;
912 	dev->mtd_info.sync = blkmtd_sync;
913 	dev->mtd_info.point = 0;
914 	dev->mtd_info.unpoint = 0;
915 	dev->mtd_info.priv = dev;
916 	dev->mtd_info.module = THIS_MODULE;
917 
918 	list_add(&dev->list, &blkmtd_device_list);
919 	if (add_mtd_device(&dev->mtd_info)) {
920 		/* Device didnt get added, so free the entry */
921 		list_del(&dev->list);
922 		free_device(dev);
923 		return NULL;
924 	} else {
925 		info("mtd%d: [%s] erase_size = %dKiB %s",
926 		     dev->mtd_info.index, dev->mtd_info.name + strlen("blkmtd: "),
927 		     dev->mtd_info.erasesize >> 10,
928 		     (dev->wr_buf) ? "" : "(read-only)");
929 	}
930 
931 	return dev;
932 
933  devinit_err:
934 	free_device(dev);
935 	return NULL;
936 }
937 
938 
939 /* Cleanup and exit - sync the device and kill of the kernel thread */
cleanup_blkmtd(void)940 static void __devexit cleanup_blkmtd(void)
941 {
942 	struct list_head *temp1, *temp2;
943 #ifdef BLKMTD_PROC_DEBUG
944 	if(blkmtd_proc) {
945 		remove_proc_entry("blkmtd_debug", NULL);
946 	}
947 #endif
948 
949 	/* Remove the MTD devices */
950 	list_for_each_safe(temp1, temp2, &blkmtd_device_list) {
951 		struct blkmtd_dev *dev = list_entry(temp1, struct blkmtd_dev,
952 						    list);
953 		blkmtd_sync(&dev->mtd_info);
954 		free_device(dev);
955 	}
956 }
957 
958 #ifndef MODULE
959 
960 /* Handle kernel boot params */
961 
962 
param_blkmtd_device(char * str)963 static int __init param_blkmtd_device(char *str)
964 {
965 	int i;
966 
967 	for(i = 0; i < MAX_DEVICES; i++) {
968 		device[i] = str;
969 		DEBUG(2, "blkmtd: device setup: %d = %s\n", i, device[i]);
970 		strsep(&str, ",");
971 	}
972 	return 1;
973 }
974 
975 
param_blkmtd_erasesz(char * str)976 static int __init param_blkmtd_erasesz(char *str)
977 {
978 	int i;
979 	for(i = 0; i < MAX_DEVICES; i++) {
980 		char *val = strsep(&str, ",");
981 		if(val)
982 			erasesz[i] = simple_strtoul(val, NULL, 0);
983 		DEBUG(2, "blkmtd: erasesz setup: %d = %d\n", i, erasesz[i]);
984 	}
985 
986 	return 1;
987 }
988 
989 
param_blkmtd_ro(char * str)990 static int __init param_blkmtd_ro(char *str)
991 {
992 	int i;
993 	for(i = 0; i < MAX_DEVICES; i++) {
994 		char *val = strsep(&str, ",");
995 		if(val)
996 			ro[i] = simple_strtoul(val, NULL, 0);
997 		DEBUG(2, "blkmtd: ro setup: %d = %d\n", i, ro[i]);
998 	}
999 
1000 	return 1;
1001 }
1002 
1003 
param_blkmtd_sync(char * str)1004 static int __init param_blkmtd_sync(char *str)
1005 {
1006 	if(str[0] == '1')
1007 		sync = 1;
1008 	return 1;
1009 }
1010 
1011 __setup("blkmtd_device=", param_blkmtd_device);
1012 __setup("blkmtd_erasesz=", param_blkmtd_erasesz);
1013 __setup("blkmtd_ro=", param_blkmtd_ro);
1014 __setup("blkmtd_sync=", param_blkmtd_sync);
1015 
1016 #endif
1017 
1018 
1019 /* Startup */
init_blkmtd(void)1020 static int __init init_blkmtd(void)
1021 {
1022 	int i;
1023 
1024 	/* Check args - device[0] is the bare minimum*/
1025 	if(!device[0]) {
1026 		err("error: missing `device' name\n");
1027 		return -EINVAL;
1028 	}
1029 
1030 	for(i = 0; i < MAX_DEVICES; i++)
1031 		add_device(device[i], ro[i], erasesz[i] << 10);
1032 
1033 	if(list_empty(&blkmtd_device_list))
1034 		goto init_err;
1035 
1036 	info("version " VERSION);
1037 
1038 #ifdef BLKMTD_PROC_DEBUG
1039 	/* create proc entry */
1040 	DEBUG(2, "Creating /proc/blkmtd_debug\n");
1041 	blkmtd_proc = create_proc_read_entry("blkmtd_debug", 0444,
1042 					     NULL, blkmtd_proc_read, NULL);
1043 	if(blkmtd_proc == NULL) {
1044 		err("Cant create /proc/blkmtd_debug");
1045 	} else {
1046 		blkmtd_proc->owner = THIS_MODULE;
1047 	}
1048 #endif
1049 
1050 	if(!list_empty(&blkmtd_device_list))
1051 		/* Everything is ok if we got here */
1052 		return 0;
1053 
1054  init_err:
1055 	return -EINVAL;
1056 }
1057 
1058 module_init(init_blkmtd);
1059 module_exit(cleanup_blkmtd);
1060