MTD: nandsim: add option to use a file to cache pages
[linux-2.6/mini2440.git] / drivers / mtd / nand / nandsim.c
blobbaa6f95e962148a76642e4d6426dff599e5083dd
1 /*
2 * NAND flash simulator.
4 * Author: Artem B. Bityuckiy <dedekind@oktetlabs.ru>, <dedekind@infradead.org>
6 * Copyright (C) 2004 Nokia Corporation
8 * Note: NS means "NAND Simulator".
9 * Note: Input means input TO flash chip, output means output FROM chip.
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2, or (at your option) any later
14 * version.
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
26 #include <linux/init.h>
27 #include <linux/types.h>
28 #include <linux/module.h>
29 #include <linux/moduleparam.h>
30 #include <linux/vmalloc.h>
31 #include <asm/div64.h>
32 #include <linux/slab.h>
33 #include <linux/errno.h>
34 #include <linux/string.h>
35 #include <linux/mtd/mtd.h>
36 #include <linux/mtd/nand.h>
37 #include <linux/mtd/partitions.h>
38 #include <linux/delay.h>
39 #include <linux/list.h>
40 #include <linux/random.h>
41 #include <linux/fs.h>
42 #include <linux/pagemap.h>
44 /* Default simulator parameters values */
45 #if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE) || \
46 !defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
47 !defined(CONFIG_NANDSIM_THIRD_ID_BYTE) || \
48 !defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
49 #define CONFIG_NANDSIM_FIRST_ID_BYTE 0x98
50 #define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
51 #define CONFIG_NANDSIM_THIRD_ID_BYTE 0xFF /* No byte */
52 #define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
53 #endif
55 #ifndef CONFIG_NANDSIM_ACCESS_DELAY
56 #define CONFIG_NANDSIM_ACCESS_DELAY 25
57 #endif
58 #ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
59 #define CONFIG_NANDSIM_PROGRAMM_DELAY 200
60 #endif
61 #ifndef CONFIG_NANDSIM_ERASE_DELAY
62 #define CONFIG_NANDSIM_ERASE_DELAY 2
63 #endif
64 #ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
65 #define CONFIG_NANDSIM_OUTPUT_CYCLE 40
66 #endif
67 #ifndef CONFIG_NANDSIM_INPUT_CYCLE
68 #define CONFIG_NANDSIM_INPUT_CYCLE 50
69 #endif
70 #ifndef CONFIG_NANDSIM_BUS_WIDTH
71 #define CONFIG_NANDSIM_BUS_WIDTH 8
72 #endif
73 #ifndef CONFIG_NANDSIM_DO_DELAYS
74 #define CONFIG_NANDSIM_DO_DELAYS 0
75 #endif
76 #ifndef CONFIG_NANDSIM_LOG
77 #define CONFIG_NANDSIM_LOG 0
78 #endif
79 #ifndef CONFIG_NANDSIM_DBG
80 #define CONFIG_NANDSIM_DBG 0
81 #endif
83 static uint first_id_byte = CONFIG_NANDSIM_FIRST_ID_BYTE;
84 static uint second_id_byte = CONFIG_NANDSIM_SECOND_ID_BYTE;
85 static uint third_id_byte = CONFIG_NANDSIM_THIRD_ID_BYTE;
86 static uint fourth_id_byte = CONFIG_NANDSIM_FOURTH_ID_BYTE;
87 static uint access_delay = CONFIG_NANDSIM_ACCESS_DELAY;
88 static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
89 static uint erase_delay = CONFIG_NANDSIM_ERASE_DELAY;
90 static uint output_cycle = CONFIG_NANDSIM_OUTPUT_CYCLE;
91 static uint input_cycle = CONFIG_NANDSIM_INPUT_CYCLE;
92 static uint bus_width = CONFIG_NANDSIM_BUS_WIDTH;
93 static uint do_delays = CONFIG_NANDSIM_DO_DELAYS;
94 static uint log = CONFIG_NANDSIM_LOG;
95 static uint dbg = CONFIG_NANDSIM_DBG;
96 static unsigned long parts[MAX_MTD_DEVICES];
97 static unsigned int parts_num;
98 static char *badblocks = NULL;
99 static char *weakblocks = NULL;
100 static char *weakpages = NULL;
101 static unsigned int bitflips = 0;
102 static char *gravepages = NULL;
103 static unsigned int rptwear = 0;
104 static unsigned int overridesize = 0;
105 static char *cache_file = NULL;
107 module_param(first_id_byte, uint, 0400);
108 module_param(second_id_byte, uint, 0400);
109 module_param(third_id_byte, uint, 0400);
110 module_param(fourth_id_byte, uint, 0400);
111 module_param(access_delay, uint, 0400);
112 module_param(programm_delay, uint, 0400);
113 module_param(erase_delay, uint, 0400);
114 module_param(output_cycle, uint, 0400);
115 module_param(input_cycle, uint, 0400);
116 module_param(bus_width, uint, 0400);
117 module_param(do_delays, uint, 0400);
118 module_param(log, uint, 0400);
119 module_param(dbg, uint, 0400);
120 module_param_array(parts, ulong, &parts_num, 0400);
121 module_param(badblocks, charp, 0400);
122 module_param(weakblocks, charp, 0400);
123 module_param(weakpages, charp, 0400);
124 module_param(bitflips, uint, 0400);
125 module_param(gravepages, charp, 0400);
126 module_param(rptwear, uint, 0400);
127 module_param(overridesize, uint, 0400);
128 module_param(cache_file, charp, 0400);
130 MODULE_PARM_DESC(first_id_byte, "The first byte returned by NAND Flash 'read ID' command (manufacturer ID)");
131 MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID)");
132 MODULE_PARM_DESC(third_id_byte, "The third byte returned by NAND Flash 'read ID' command");
133 MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command");
134 MODULE_PARM_DESC(access_delay, "Initial page access delay (microseconds)");
135 MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
136 MODULE_PARM_DESC(erase_delay, "Sector erase delay (milliseconds)");
137 MODULE_PARM_DESC(output_cycle, "Word output (from flash) time (nanodeconds)");
138 MODULE_PARM_DESC(input_cycle, "Word input (to flash) time (nanodeconds)");
139 MODULE_PARM_DESC(bus_width, "Chip's bus width (8- or 16-bit)");
140 MODULE_PARM_DESC(do_delays, "Simulate NAND delays using busy-waits if not zero");
141 MODULE_PARM_DESC(log, "Perform logging if not zero");
142 MODULE_PARM_DESC(dbg, "Output debug information if not zero");
143 MODULE_PARM_DESC(parts, "Partition sizes (in erase blocks) separated by commas");
144 /* Page and erase block positions for the following parameters are independent of any partitions */
145 MODULE_PARM_DESC(badblocks, "Erase blocks that are initially marked bad, separated by commas");
146 MODULE_PARM_DESC(weakblocks, "Weak erase blocks [: remaining erase cycles (defaults to 3)]"
147 " separated by commas e.g. 113:2 means eb 113"
148 " can be erased only twice before failing");
149 MODULE_PARM_DESC(weakpages, "Weak pages [: maximum writes (defaults to 3)]"
150 " separated by commas e.g. 1401:2 means page 1401"
151 " can be written only twice before failing");
152 MODULE_PARM_DESC(bitflips, "Maximum number of random bit flips per page (zero by default)");
153 MODULE_PARM_DESC(gravepages, "Pages that lose data [: maximum reads (defaults to 3)]"
154 " separated by commas e.g. 1401:2 means page 1401"
155 " can be read only twice before failing");
156 MODULE_PARM_DESC(rptwear, "Number of erases inbetween reporting wear, if not zero");
157 MODULE_PARM_DESC(overridesize, "Specifies the NAND Flash size overriding the ID bytes. "
158 "The size is specified in erase blocks and as the exponent of a power of two"
159 " e.g. 5 means a size of 32 erase blocks");
160 MODULE_PARM_DESC(cache_file, "File to use to cache nand pages instead of memory");
162 /* The largest possible page size */
163 #define NS_LARGEST_PAGE_SIZE 2048
165 /* The prefix for simulator output */
166 #define NS_OUTPUT_PREFIX "[nandsim]"
168 /* Simulator's output macros (logging, debugging, warning, error) */
169 #define NS_LOG(args...) \
170 do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
171 #define NS_DBG(args...) \
172 do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
173 #define NS_WARN(args...) \
174 do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warning: " args); } while(0)
175 #define NS_ERR(args...) \
176 do { printk(KERN_ERR NS_OUTPUT_PREFIX " error: " args); } while(0)
177 #define NS_INFO(args...) \
178 do { printk(KERN_INFO NS_OUTPUT_PREFIX " " args); } while(0)
180 /* Busy-wait delay macros (microseconds, milliseconds) */
181 #define NS_UDELAY(us) \
182 do { if (do_delays) udelay(us); } while(0)
183 #define NS_MDELAY(us) \
184 do { if (do_delays) mdelay(us); } while(0)
186 /* Is the nandsim structure initialized ? */
187 #define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
189 /* Good operation completion status */
190 #define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
192 /* Operation failed completion status */
193 #define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
195 /* Calculate the page offset in flash RAM image by (row, column) address */
196 #define NS_RAW_OFFSET(ns) \
197 (((ns)->regs.row << (ns)->geom.pgshift) + ((ns)->regs.row * (ns)->geom.oobsz) + (ns)->regs.column)
199 /* Calculate the OOB offset in flash RAM image by (row, column) address */
200 #define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)
202 /* After a command is input, the simulator goes to one of the following states */
203 #define STATE_CMD_READ0 0x00000001 /* read data from the beginning of page */
204 #define STATE_CMD_READ1 0x00000002 /* read data from the second half of page */
205 #define STATE_CMD_READSTART 0x00000003 /* read data second command (large page devices) */
206 #define STATE_CMD_PAGEPROG 0x00000004 /* start page programm */
207 #define STATE_CMD_READOOB 0x00000005 /* read OOB area */
208 #define STATE_CMD_ERASE1 0x00000006 /* sector erase first command */
209 #define STATE_CMD_STATUS 0x00000007 /* read status */
210 #define STATE_CMD_STATUS_M 0x00000008 /* read multi-plane status (isn't implemented) */
211 #define STATE_CMD_SEQIN 0x00000009 /* sequential data imput */
212 #define STATE_CMD_READID 0x0000000A /* read ID */
213 #define STATE_CMD_ERASE2 0x0000000B /* sector erase second command */
214 #define STATE_CMD_RESET 0x0000000C /* reset */
215 #define STATE_CMD_RNDOUT 0x0000000D /* random output command */
216 #define STATE_CMD_RNDOUTSTART 0x0000000E /* random output start command */
217 #define STATE_CMD_MASK 0x0000000F /* command states mask */
219 /* After an address is input, the simulator goes to one of these states */
220 #define STATE_ADDR_PAGE 0x00000010 /* full (row, column) address is accepted */
221 #define STATE_ADDR_SEC 0x00000020 /* sector address was accepted */
222 #define STATE_ADDR_COLUMN 0x00000030 /* column address was accepted */
223 #define STATE_ADDR_ZERO 0x00000040 /* one byte zero address was accepted */
224 #define STATE_ADDR_MASK 0x00000070 /* address states mask */
226 /* Durind data input/output the simulator is in these states */
227 #define STATE_DATAIN 0x00000100 /* waiting for data input */
228 #define STATE_DATAIN_MASK 0x00000100 /* data input states mask */
230 #define STATE_DATAOUT 0x00001000 /* waiting for page data output */
231 #define STATE_DATAOUT_ID 0x00002000 /* waiting for ID bytes output */
232 #define STATE_DATAOUT_STATUS 0x00003000 /* waiting for status output */
233 #define STATE_DATAOUT_STATUS_M 0x00004000 /* waiting for multi-plane status output */
234 #define STATE_DATAOUT_MASK 0x00007000 /* data output states mask */
236 /* Previous operation is done, ready to accept new requests */
237 #define STATE_READY 0x00000000
239 /* This state is used to mark that the next state isn't known yet */
240 #define STATE_UNKNOWN 0x10000000
242 /* Simulator's actions bit masks */
243 #define ACTION_CPY 0x00100000 /* copy page/OOB to the internal buffer */
244 #define ACTION_PRGPAGE 0x00200000 /* programm the internal buffer to flash */
245 #define ACTION_SECERASE 0x00300000 /* erase sector */
246 #define ACTION_ZEROOFF 0x00400000 /* don't add any offset to address */
247 #define ACTION_HALFOFF 0x00500000 /* add to address half of page */
248 #define ACTION_OOBOFF 0x00600000 /* add to address OOB offset */
249 #define ACTION_MASK 0x00700000 /* action mask */
251 #define NS_OPER_NUM 13 /* Number of operations supported by the simulator */
252 #define NS_OPER_STATES 6 /* Maximum number of states in operation */
254 #define OPT_ANY 0xFFFFFFFF /* any chip supports this operation */
255 #define OPT_PAGE256 0x00000001 /* 256-byte page chips */
256 #define OPT_PAGE512 0x00000002 /* 512-byte page chips */
257 #define OPT_PAGE2048 0x00000008 /* 2048-byte page chips */
258 #define OPT_SMARTMEDIA 0x00000010 /* SmartMedia technology chips */
259 #define OPT_AUTOINCR 0x00000020 /* page number auto inctimentation is possible */
260 #define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
261 #define OPT_LARGEPAGE (OPT_PAGE2048) /* 2048-byte page chips */
262 #define OPT_SMALLPAGE (OPT_PAGE256 | OPT_PAGE512) /* 256 and 512-byte page chips */
264 /* Remove action bits ftom state */
265 #define NS_STATE(x) ((x) & ~ACTION_MASK)
268 * Maximum previous states which need to be saved. Currently saving is
269 * only needed for page programm operation with preceeded read command
270 * (which is only valid for 512-byte pages).
272 #define NS_MAX_PREVSTATES 1
274 /* Maximum page cache pages needed to read or write a NAND page to the cache_file */
275 #define NS_MAX_HELD_PAGES 16
278 * A union to represent flash memory contents and flash buffer.
280 union ns_mem {
281 u_char *byte; /* for byte access */
282 uint16_t *word; /* for 16-bit word access */
286 * The structure which describes all the internal simulator data.
288 struct nandsim {
289 struct mtd_partition partitions[MAX_MTD_DEVICES];
290 unsigned int nbparts;
292 uint busw; /* flash chip bus width (8 or 16) */
293 u_char ids[4]; /* chip's ID bytes */
294 uint32_t options; /* chip's characteristic bits */
295 uint32_t state; /* current chip state */
296 uint32_t nxstate; /* next expected state */
298 uint32_t *op; /* current operation, NULL operations isn't known yet */
299 uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
300 uint16_t npstates; /* number of previous states saved */
301 uint16_t stateidx; /* current state index */
303 /* The simulated NAND flash pages array */
304 union ns_mem *pages;
306 /* Internal buffer of page + OOB size bytes */
307 union ns_mem buf;
309 /* NAND flash "geometry" */
310 struct nandsin_geometry {
311 uint64_t totsz; /* total flash size, bytes */
312 uint32_t secsz; /* flash sector (erase block) size, bytes */
313 uint pgsz; /* NAND flash page size, bytes */
314 uint oobsz; /* page OOB area size, bytes */
315 uint64_t totszoob; /* total flash size including OOB, bytes */
316 uint pgszoob; /* page size including OOB , bytes*/
317 uint secszoob; /* sector size including OOB, bytes */
318 uint pgnum; /* total number of pages */
319 uint pgsec; /* number of pages per sector */
320 uint secshift; /* bits number in sector size */
321 uint pgshift; /* bits number in page size */
322 uint oobshift; /* bits number in OOB size */
323 uint pgaddrbytes; /* bytes per page address */
324 uint secaddrbytes; /* bytes per sector address */
325 uint idbytes; /* the number ID bytes that this chip outputs */
326 } geom;
328 /* NAND flash internal registers */
329 struct nandsim_regs {
330 unsigned command; /* the command register */
331 u_char status; /* the status register */
332 uint row; /* the page number */
333 uint column; /* the offset within page */
334 uint count; /* internal counter */
335 uint num; /* number of bytes which must be processed */
336 uint off; /* fixed page offset */
337 } regs;
339 /* NAND flash lines state */
340 struct ns_lines_status {
341 int ce; /* chip Enable */
342 int cle; /* command Latch Enable */
343 int ale; /* address Latch Enable */
344 int wp; /* write Protect */
345 } lines;
347 /* Fields needed when using a cache file */
348 struct file *cfile; /* Open file */
349 unsigned char *pages_written; /* Which pages have been written */
350 void *file_buf;
351 struct page *held_pages[NS_MAX_HELD_PAGES];
352 int held_cnt;
356 * Operations array. To perform any operation the simulator must pass
357 * through the correspondent states chain.
359 static struct nandsim_operations {
360 uint32_t reqopts; /* options which are required to perform the operation */
361 uint32_t states[NS_OPER_STATES]; /* operation's states */
362 } ops[NS_OPER_NUM] = {
363 /* Read page + OOB from the beginning */
364 {OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
365 STATE_DATAOUT, STATE_READY}},
366 /* Read page + OOB from the second half */
367 {OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
368 STATE_DATAOUT, STATE_READY}},
369 /* Read OOB */
370 {OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
371 STATE_DATAOUT, STATE_READY}},
372 /* Programm page starting from the beginning */
373 {OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
374 STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
375 /* Programm page starting from the beginning */
376 {OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
377 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
378 /* Programm page starting from the second half */
379 {OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
380 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
381 /* Programm OOB */
382 {OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
383 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
384 /* Erase sector */
385 {OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
386 /* Read status */
387 {OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
388 /* Read multi-plane status */
389 {OPT_SMARTMEDIA, {STATE_CMD_STATUS_M, STATE_DATAOUT_STATUS_M, STATE_READY}},
390 /* Read ID */
391 {OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
392 /* Large page devices read page */
393 {OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
394 STATE_DATAOUT, STATE_READY}},
395 /* Large page devices random page read */
396 {OPT_LARGEPAGE, {STATE_CMD_RNDOUT, STATE_ADDR_COLUMN, STATE_CMD_RNDOUTSTART | ACTION_CPY,
397 STATE_DATAOUT, STATE_READY}},
400 struct weak_block {
401 struct list_head list;
402 unsigned int erase_block_no;
403 unsigned int max_erases;
404 unsigned int erases_done;
407 static LIST_HEAD(weak_blocks);
409 struct weak_page {
410 struct list_head list;
411 unsigned int page_no;
412 unsigned int max_writes;
413 unsigned int writes_done;
416 static LIST_HEAD(weak_pages);
418 struct grave_page {
419 struct list_head list;
420 unsigned int page_no;
421 unsigned int max_reads;
422 unsigned int reads_done;
425 static LIST_HEAD(grave_pages);
427 static unsigned long *erase_block_wear = NULL;
428 static unsigned int wear_eb_count = 0;
429 static unsigned long total_wear = 0;
430 static unsigned int rptwear_cnt = 0;
432 /* MTD structure for NAND controller */
433 static struct mtd_info *nsmtd;
435 static u_char ns_verify_buf[NS_LARGEST_PAGE_SIZE];
438 * Allocate array of page pointers and initialize the array to NULL
439 * pointers.
441 * RETURNS: 0 if success, -ENOMEM if memory alloc fails.
443 static int alloc_device(struct nandsim *ns)
445 struct file *cfile;
446 int i, err;
448 if (cache_file) {
449 cfile = filp_open(cache_file, O_CREAT | O_RDWR | O_LARGEFILE, 0600);
450 if (IS_ERR(cfile))
451 return PTR_ERR(cfile);
452 if (!cfile->f_op || (!cfile->f_op->read && !cfile->f_op->aio_read)) {
453 NS_ERR("alloc_device: cache file not readable\n");
454 err = -EINVAL;
455 goto err_close;
457 if (!cfile->f_op->write && !cfile->f_op->aio_write) {
458 NS_ERR("alloc_device: cache file not writeable\n");
459 err = -EINVAL;
460 goto err_close;
462 ns->pages_written = vmalloc(ns->geom.pgnum);
463 if (!ns->pages_written) {
464 NS_ERR("alloc_device: unable to allocate pages written array\n");
465 err = -ENOMEM;
466 goto err_close;
468 ns->file_buf = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
469 if (!ns->file_buf) {
470 NS_ERR("alloc_device: unable to allocate file buf\n");
471 err = -ENOMEM;
472 goto err_free;
474 ns->cfile = cfile;
475 memset(ns->pages_written, 0, ns->geom.pgnum);
476 return 0;
479 ns->pages = vmalloc(ns->geom.pgnum * sizeof(union ns_mem));
480 if (!ns->pages) {
481 NS_ERR("alloc_device: unable to allocate page array\n");
482 return -ENOMEM;
484 for (i = 0; i < ns->geom.pgnum; i++) {
485 ns->pages[i].byte = NULL;
488 return 0;
490 err_free:
491 vfree(ns->pages_written);
492 err_close:
493 filp_close(cfile, NULL);
494 return err;
498 * Free any allocated pages, and free the array of page pointers.
500 static void free_device(struct nandsim *ns)
502 int i;
504 if (ns->cfile) {
505 kfree(ns->file_buf);
506 vfree(ns->pages_written);
507 filp_close(ns->cfile, NULL);
508 return;
511 if (ns->pages) {
512 for (i = 0; i < ns->geom.pgnum; i++) {
513 if (ns->pages[i].byte)
514 kfree(ns->pages[i].byte);
516 vfree(ns->pages);
520 static char *get_partition_name(int i)
522 char buf[64];
523 sprintf(buf, "NAND simulator partition %d", i);
524 return kstrdup(buf, GFP_KERNEL);
527 static u_int64_t divide(u_int64_t n, u_int32_t d)
529 do_div(n, d);
530 return n;
534 * Initialize the nandsim structure.
536 * RETURNS: 0 if success, -ERRNO if failure.
538 static int init_nandsim(struct mtd_info *mtd)
540 struct nand_chip *chip = (struct nand_chip *)mtd->priv;
541 struct nandsim *ns = (struct nandsim *)(chip->priv);
542 int i, ret = 0;
543 u_int64_t remains;
544 u_int64_t next_offset;
546 if (NS_IS_INITIALIZED(ns)) {
547 NS_ERR("init_nandsim: nandsim is already initialized\n");
548 return -EIO;
551 /* Force mtd to not do delays */
552 chip->chip_delay = 0;
554 /* Initialize the NAND flash parameters */
555 ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
556 ns->geom.totsz = mtd->size;
557 ns->geom.pgsz = mtd->writesize;
558 ns->geom.oobsz = mtd->oobsize;
559 ns->geom.secsz = mtd->erasesize;
560 ns->geom.pgszoob = ns->geom.pgsz + ns->geom.oobsz;
561 ns->geom.pgnum = divide(ns->geom.totsz, ns->geom.pgsz);
562 ns->geom.totszoob = ns->geom.totsz + (uint64_t)ns->geom.pgnum * ns->geom.oobsz;
563 ns->geom.secshift = ffs(ns->geom.secsz) - 1;
564 ns->geom.pgshift = chip->page_shift;
565 ns->geom.oobshift = ffs(ns->geom.oobsz) - 1;
566 ns->geom.pgsec = ns->geom.secsz / ns->geom.pgsz;
567 ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
568 ns->options = 0;
570 if (ns->geom.pgsz == 256) {
571 ns->options |= OPT_PAGE256;
573 else if (ns->geom.pgsz == 512) {
574 ns->options |= (OPT_PAGE512 | OPT_AUTOINCR);
575 if (ns->busw == 8)
576 ns->options |= OPT_PAGE512_8BIT;
577 } else if (ns->geom.pgsz == 2048) {
578 ns->options |= OPT_PAGE2048;
579 } else {
580 NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
581 return -EIO;
584 if (ns->options & OPT_SMALLPAGE) {
585 if (ns->geom.totsz <= (32 << 20)) {
586 ns->geom.pgaddrbytes = 3;
587 ns->geom.secaddrbytes = 2;
588 } else {
589 ns->geom.pgaddrbytes = 4;
590 ns->geom.secaddrbytes = 3;
592 } else {
593 if (ns->geom.totsz <= (128 << 20)) {
594 ns->geom.pgaddrbytes = 4;
595 ns->geom.secaddrbytes = 2;
596 } else {
597 ns->geom.pgaddrbytes = 5;
598 ns->geom.secaddrbytes = 3;
602 /* Fill the partition_info structure */
603 if (parts_num > ARRAY_SIZE(ns->partitions)) {
604 NS_ERR("too many partitions.\n");
605 ret = -EINVAL;
606 goto error;
608 remains = ns->geom.totsz;
609 next_offset = 0;
610 for (i = 0; i < parts_num; ++i) {
611 u_int64_t part_sz = (u_int64_t)parts[i] * ns->geom.secsz;
613 if (!part_sz || part_sz > remains) {
614 NS_ERR("bad partition size.\n");
615 ret = -EINVAL;
616 goto error;
618 ns->partitions[i].name = get_partition_name(i);
619 ns->partitions[i].offset = next_offset;
620 ns->partitions[i].size = part_sz;
621 next_offset += ns->partitions[i].size;
622 remains -= ns->partitions[i].size;
624 ns->nbparts = parts_num;
625 if (remains) {
626 if (parts_num + 1 > ARRAY_SIZE(ns->partitions)) {
627 NS_ERR("too many partitions.\n");
628 ret = -EINVAL;
629 goto error;
631 ns->partitions[i].name = get_partition_name(i);
632 ns->partitions[i].offset = next_offset;
633 ns->partitions[i].size = remains;
634 ns->nbparts += 1;
637 /* Detect how many ID bytes the NAND chip outputs */
638 for (i = 0; nand_flash_ids[i].name != NULL; i++) {
639 if (second_id_byte != nand_flash_ids[i].id)
640 continue;
641 if (!(nand_flash_ids[i].options & NAND_NO_AUTOINCR))
642 ns->options |= OPT_AUTOINCR;
645 if (ns->busw == 16)
646 NS_WARN("16-bit flashes support wasn't tested\n");
648 printk("flash size: %llu MiB\n",
649 (unsigned long long)ns->geom.totsz >> 20);
650 printk("page size: %u bytes\n", ns->geom.pgsz);
651 printk("OOB area size: %u bytes\n", ns->geom.oobsz);
652 printk("sector size: %u KiB\n", ns->geom.secsz >> 10);
653 printk("pages number: %u\n", ns->geom.pgnum);
654 printk("pages per sector: %u\n", ns->geom.pgsec);
655 printk("bus width: %u\n", ns->busw);
656 printk("bits in sector size: %u\n", ns->geom.secshift);
657 printk("bits in page size: %u\n", ns->geom.pgshift);
658 printk("bits in OOB size: %u\n", ns->geom.oobshift);
659 printk("flash size with OOB: %llu KiB\n",
660 (unsigned long long)ns->geom.totszoob >> 10);
661 printk("page address bytes: %u\n", ns->geom.pgaddrbytes);
662 printk("sector address bytes: %u\n", ns->geom.secaddrbytes);
663 printk("options: %#x\n", ns->options);
665 if ((ret = alloc_device(ns)) != 0)
666 goto error;
668 /* Allocate / initialize the internal buffer */
669 ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
670 if (!ns->buf.byte) {
671 NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
672 ns->geom.pgszoob);
673 ret = -ENOMEM;
674 goto error;
676 memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
678 return 0;
680 error:
681 free_device(ns);
683 return ret;
687 * Free the nandsim structure.
689 static void free_nandsim(struct nandsim *ns)
691 kfree(ns->buf.byte);
692 free_device(ns);
694 return;
697 static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
699 char *w;
700 int zero_ok;
701 unsigned int erase_block_no;
702 loff_t offset;
704 if (!badblocks)
705 return 0;
706 w = badblocks;
707 do {
708 zero_ok = (*w == '0' ? 1 : 0);
709 erase_block_no = simple_strtoul(w, &w, 0);
710 if (!zero_ok && !erase_block_no) {
711 NS_ERR("invalid badblocks.\n");
712 return -EINVAL;
714 offset = erase_block_no * ns->geom.secsz;
715 if (mtd->block_markbad(mtd, offset)) {
716 NS_ERR("invalid badblocks.\n");
717 return -EINVAL;
719 if (*w == ',')
720 w += 1;
721 } while (*w);
722 return 0;
725 static int parse_weakblocks(void)
727 char *w;
728 int zero_ok;
729 unsigned int erase_block_no;
730 unsigned int max_erases;
731 struct weak_block *wb;
733 if (!weakblocks)
734 return 0;
735 w = weakblocks;
736 do {
737 zero_ok = (*w == '0' ? 1 : 0);
738 erase_block_no = simple_strtoul(w, &w, 0);
739 if (!zero_ok && !erase_block_no) {
740 NS_ERR("invalid weakblocks.\n");
741 return -EINVAL;
743 max_erases = 3;
744 if (*w == ':') {
745 w += 1;
746 max_erases = simple_strtoul(w, &w, 0);
748 if (*w == ',')
749 w += 1;
750 wb = kzalloc(sizeof(*wb), GFP_KERNEL);
751 if (!wb) {
752 NS_ERR("unable to allocate memory.\n");
753 return -ENOMEM;
755 wb->erase_block_no = erase_block_no;
756 wb->max_erases = max_erases;
757 list_add(&wb->list, &weak_blocks);
758 } while (*w);
759 return 0;
762 static int erase_error(unsigned int erase_block_no)
764 struct weak_block *wb;
766 list_for_each_entry(wb, &weak_blocks, list)
767 if (wb->erase_block_no == erase_block_no) {
768 if (wb->erases_done >= wb->max_erases)
769 return 1;
770 wb->erases_done += 1;
771 return 0;
773 return 0;
776 static int parse_weakpages(void)
778 char *w;
779 int zero_ok;
780 unsigned int page_no;
781 unsigned int max_writes;
782 struct weak_page *wp;
784 if (!weakpages)
785 return 0;
786 w = weakpages;
787 do {
788 zero_ok = (*w == '0' ? 1 : 0);
789 page_no = simple_strtoul(w, &w, 0);
790 if (!zero_ok && !page_no) {
791 NS_ERR("invalid weakpagess.\n");
792 return -EINVAL;
794 max_writes = 3;
795 if (*w == ':') {
796 w += 1;
797 max_writes = simple_strtoul(w, &w, 0);
799 if (*w == ',')
800 w += 1;
801 wp = kzalloc(sizeof(*wp), GFP_KERNEL);
802 if (!wp) {
803 NS_ERR("unable to allocate memory.\n");
804 return -ENOMEM;
806 wp->page_no = page_no;
807 wp->max_writes = max_writes;
808 list_add(&wp->list, &weak_pages);
809 } while (*w);
810 return 0;
813 static int write_error(unsigned int page_no)
815 struct weak_page *wp;
817 list_for_each_entry(wp, &weak_pages, list)
818 if (wp->page_no == page_no) {
819 if (wp->writes_done >= wp->max_writes)
820 return 1;
821 wp->writes_done += 1;
822 return 0;
824 return 0;
827 static int parse_gravepages(void)
829 char *g;
830 int zero_ok;
831 unsigned int page_no;
832 unsigned int max_reads;
833 struct grave_page *gp;
835 if (!gravepages)
836 return 0;
837 g = gravepages;
838 do {
839 zero_ok = (*g == '0' ? 1 : 0);
840 page_no = simple_strtoul(g, &g, 0);
841 if (!zero_ok && !page_no) {
842 NS_ERR("invalid gravepagess.\n");
843 return -EINVAL;
845 max_reads = 3;
846 if (*g == ':') {
847 g += 1;
848 max_reads = simple_strtoul(g, &g, 0);
850 if (*g == ',')
851 g += 1;
852 gp = kzalloc(sizeof(*gp), GFP_KERNEL);
853 if (!gp) {
854 NS_ERR("unable to allocate memory.\n");
855 return -ENOMEM;
857 gp->page_no = page_no;
858 gp->max_reads = max_reads;
859 list_add(&gp->list, &grave_pages);
860 } while (*g);
861 return 0;
864 static int read_error(unsigned int page_no)
866 struct grave_page *gp;
868 list_for_each_entry(gp, &grave_pages, list)
869 if (gp->page_no == page_no) {
870 if (gp->reads_done >= gp->max_reads)
871 return 1;
872 gp->reads_done += 1;
873 return 0;
875 return 0;
878 static void free_lists(void)
880 struct list_head *pos, *n;
881 list_for_each_safe(pos, n, &weak_blocks) {
882 list_del(pos);
883 kfree(list_entry(pos, struct weak_block, list));
885 list_for_each_safe(pos, n, &weak_pages) {
886 list_del(pos);
887 kfree(list_entry(pos, struct weak_page, list));
889 list_for_each_safe(pos, n, &grave_pages) {
890 list_del(pos);
891 kfree(list_entry(pos, struct grave_page, list));
893 kfree(erase_block_wear);
896 static int setup_wear_reporting(struct mtd_info *mtd)
898 size_t mem;
900 if (!rptwear)
901 return 0;
902 wear_eb_count = divide(mtd->size, mtd->erasesize);
903 mem = wear_eb_count * sizeof(unsigned long);
904 if (mem / sizeof(unsigned long) != wear_eb_count) {
905 NS_ERR("Too many erase blocks for wear reporting\n");
906 return -ENOMEM;
908 erase_block_wear = kzalloc(mem, GFP_KERNEL);
909 if (!erase_block_wear) {
910 NS_ERR("Too many erase blocks for wear reporting\n");
911 return -ENOMEM;
913 return 0;
916 static void update_wear(unsigned int erase_block_no)
918 unsigned long wmin = -1, wmax = 0, avg;
919 unsigned long deciles[10], decile_max[10], tot = 0;
920 unsigned int i;
922 if (!erase_block_wear)
923 return;
924 total_wear += 1;
925 if (total_wear == 0)
926 NS_ERR("Erase counter total overflow\n");
927 erase_block_wear[erase_block_no] += 1;
928 if (erase_block_wear[erase_block_no] == 0)
929 NS_ERR("Erase counter overflow for erase block %u\n", erase_block_no);
930 rptwear_cnt += 1;
931 if (rptwear_cnt < rptwear)
932 return;
933 rptwear_cnt = 0;
934 /* Calc wear stats */
935 for (i = 0; i < wear_eb_count; ++i) {
936 unsigned long wear = erase_block_wear[i];
937 if (wear < wmin)
938 wmin = wear;
939 if (wear > wmax)
940 wmax = wear;
941 tot += wear;
943 for (i = 0; i < 9; ++i) {
944 deciles[i] = 0;
945 decile_max[i] = (wmax * (i + 1) + 5) / 10;
947 deciles[9] = 0;
948 decile_max[9] = wmax;
949 for (i = 0; i < wear_eb_count; ++i) {
950 int d;
951 unsigned long wear = erase_block_wear[i];
952 for (d = 0; d < 10; ++d)
953 if (wear <= decile_max[d]) {
954 deciles[d] += 1;
955 break;
958 avg = tot / wear_eb_count;
959 /* Output wear report */
960 NS_INFO("*** Wear Report ***\n");
961 NS_INFO("Total numbers of erases: %lu\n", tot);
962 NS_INFO("Number of erase blocks: %u\n", wear_eb_count);
963 NS_INFO("Average number of erases: %lu\n", avg);
964 NS_INFO("Maximum number of erases: %lu\n", wmax);
965 NS_INFO("Minimum number of erases: %lu\n", wmin);
966 for (i = 0; i < 10; ++i) {
967 unsigned long from = (i ? decile_max[i - 1] + 1 : 0);
968 if (from > decile_max[i])
969 continue;
970 NS_INFO("Number of ebs with erase counts from %lu to %lu : %lu\n",
971 from,
972 decile_max[i],
973 deciles[i]);
975 NS_INFO("*** End of Wear Report ***\n");
979 * Returns the string representation of 'state' state.
981 static char *get_state_name(uint32_t state)
983 switch (NS_STATE(state)) {
984 case STATE_CMD_READ0:
985 return "STATE_CMD_READ0";
986 case STATE_CMD_READ1:
987 return "STATE_CMD_READ1";
988 case STATE_CMD_PAGEPROG:
989 return "STATE_CMD_PAGEPROG";
990 case STATE_CMD_READOOB:
991 return "STATE_CMD_READOOB";
992 case STATE_CMD_READSTART:
993 return "STATE_CMD_READSTART";
994 case STATE_CMD_ERASE1:
995 return "STATE_CMD_ERASE1";
996 case STATE_CMD_STATUS:
997 return "STATE_CMD_STATUS";
998 case STATE_CMD_STATUS_M:
999 return "STATE_CMD_STATUS_M";
1000 case STATE_CMD_SEQIN:
1001 return "STATE_CMD_SEQIN";
1002 case STATE_CMD_READID:
1003 return "STATE_CMD_READID";
1004 case STATE_CMD_ERASE2:
1005 return "STATE_CMD_ERASE2";
1006 case STATE_CMD_RESET:
1007 return "STATE_CMD_RESET";
1008 case STATE_CMD_RNDOUT:
1009 return "STATE_CMD_RNDOUT";
1010 case STATE_CMD_RNDOUTSTART:
1011 return "STATE_CMD_RNDOUTSTART";
1012 case STATE_ADDR_PAGE:
1013 return "STATE_ADDR_PAGE";
1014 case STATE_ADDR_SEC:
1015 return "STATE_ADDR_SEC";
1016 case STATE_ADDR_ZERO:
1017 return "STATE_ADDR_ZERO";
1018 case STATE_ADDR_COLUMN:
1019 return "STATE_ADDR_COLUMN";
1020 case STATE_DATAIN:
1021 return "STATE_DATAIN";
1022 case STATE_DATAOUT:
1023 return "STATE_DATAOUT";
1024 case STATE_DATAOUT_ID:
1025 return "STATE_DATAOUT_ID";
1026 case STATE_DATAOUT_STATUS:
1027 return "STATE_DATAOUT_STATUS";
1028 case STATE_DATAOUT_STATUS_M:
1029 return "STATE_DATAOUT_STATUS_M";
1030 case STATE_READY:
1031 return "STATE_READY";
1032 case STATE_UNKNOWN:
1033 return "STATE_UNKNOWN";
1036 NS_ERR("get_state_name: unknown state, BUG\n");
1037 return NULL;
1041 * Check if command is valid.
1043 * RETURNS: 1 if wrong command, 0 if right.
1045 static int check_command(int cmd)
1047 switch (cmd) {
1049 case NAND_CMD_READ0:
1050 case NAND_CMD_READ1:
1051 case NAND_CMD_READSTART:
1052 case NAND_CMD_PAGEPROG:
1053 case NAND_CMD_READOOB:
1054 case NAND_CMD_ERASE1:
1055 case NAND_CMD_STATUS:
1056 case NAND_CMD_SEQIN:
1057 case NAND_CMD_READID:
1058 case NAND_CMD_ERASE2:
1059 case NAND_CMD_RESET:
1060 case NAND_CMD_RNDOUT:
1061 case NAND_CMD_RNDOUTSTART:
1062 return 0;
1064 case NAND_CMD_STATUS_MULTI:
1065 default:
1066 return 1;
1071 * Returns state after command is accepted by command number.
1073 static uint32_t get_state_by_command(unsigned command)
1075 switch (command) {
1076 case NAND_CMD_READ0:
1077 return STATE_CMD_READ0;
1078 case NAND_CMD_READ1:
1079 return STATE_CMD_READ1;
1080 case NAND_CMD_PAGEPROG:
1081 return STATE_CMD_PAGEPROG;
1082 case NAND_CMD_READSTART:
1083 return STATE_CMD_READSTART;
1084 case NAND_CMD_READOOB:
1085 return STATE_CMD_READOOB;
1086 case NAND_CMD_ERASE1:
1087 return STATE_CMD_ERASE1;
1088 case NAND_CMD_STATUS:
1089 return STATE_CMD_STATUS;
1090 case NAND_CMD_STATUS_MULTI:
1091 return STATE_CMD_STATUS_M;
1092 case NAND_CMD_SEQIN:
1093 return STATE_CMD_SEQIN;
1094 case NAND_CMD_READID:
1095 return STATE_CMD_READID;
1096 case NAND_CMD_ERASE2:
1097 return STATE_CMD_ERASE2;
1098 case NAND_CMD_RESET:
1099 return STATE_CMD_RESET;
1100 case NAND_CMD_RNDOUT:
1101 return STATE_CMD_RNDOUT;
1102 case NAND_CMD_RNDOUTSTART:
1103 return STATE_CMD_RNDOUTSTART;
1106 NS_ERR("get_state_by_command: unknown command, BUG\n");
1107 return 0;
1111 * Move an address byte to the correspondent internal register.
1113 static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
1115 uint byte = (uint)bt;
1117 if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
1118 ns->regs.column |= (byte << 8 * ns->regs.count);
1119 else {
1120 ns->regs.row |= (byte << 8 * (ns->regs.count -
1121 ns->geom.pgaddrbytes +
1122 ns->geom.secaddrbytes));
1125 return;
1129 * Switch to STATE_READY state.
1131 static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
1133 NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
1135 ns->state = STATE_READY;
1136 ns->nxstate = STATE_UNKNOWN;
1137 ns->op = NULL;
1138 ns->npstates = 0;
1139 ns->stateidx = 0;
1140 ns->regs.num = 0;
1141 ns->regs.count = 0;
1142 ns->regs.off = 0;
1143 ns->regs.row = 0;
1144 ns->regs.column = 0;
1145 ns->regs.status = status;
1149 * If the operation isn't known yet, try to find it in the global array
1150 * of supported operations.
1152 * Operation can be unknown because of the following.
1153 * 1. New command was accepted and this is the firs call to find the
1154 * correspondent states chain. In this case ns->npstates = 0;
1155 * 2. There is several operations which begin with the same command(s)
1156 * (for example program from the second half and read from the
1157 * second half operations both begin with the READ1 command). In this
1158 * case the ns->pstates[] array contains previous states.
1160 * Thus, the function tries to find operation containing the following
1161 * states (if the 'flag' parameter is 0):
1162 * ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
1164 * If (one and only one) matching operation is found, it is accepted (
1165 * ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
1166 * zeroed).
1168 * If there are several maches, the current state is pushed to the
1169 * ns->pstates.
1171 * The operation can be unknown only while commands are input to the chip.
1172 * As soon as address command is accepted, the operation must be known.
1173 * In such situation the function is called with 'flag' != 0, and the
1174 * operation is searched using the following pattern:
1175 * ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
1177 * It is supposed that this pattern must either match one operation on
1178 * none. There can't be ambiguity in that case.
1180 * If no matches found, the functions does the following:
1181 * 1. if there are saved states present, try to ignore them and search
1182 * again only using the last command. If nothing was found, switch
1183 * to the STATE_READY state.
1184 * 2. if there are no saved states, switch to the STATE_READY state.
1186 * RETURNS: -2 - no matched operations found.
1187 * -1 - several matches.
1188 * 0 - operation is found.
1190 static int find_operation(struct nandsim *ns, uint32_t flag)
1192 int opsfound = 0;
1193 int i, j, idx = 0;
1195 for (i = 0; i < NS_OPER_NUM; i++) {
1197 int found = 1;
1199 if (!(ns->options & ops[i].reqopts))
1200 /* Ignore operations we can't perform */
1201 continue;
1203 if (flag) {
1204 if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
1205 continue;
1206 } else {
1207 if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
1208 continue;
1211 for (j = 0; j < ns->npstates; j++)
1212 if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
1213 && (ns->options & ops[idx].reqopts)) {
1214 found = 0;
1215 break;
1218 if (found) {
1219 idx = i;
1220 opsfound += 1;
1224 if (opsfound == 1) {
1225 /* Exact match */
1226 ns->op = &ops[idx].states[0];
1227 if (flag) {
1229 * In this case the find_operation function was
1230 * called when address has just began input. But it isn't
1231 * yet fully input and the current state must
1232 * not be one of STATE_ADDR_*, but the STATE_ADDR_*
1233 * state must be the next state (ns->nxstate).
1235 ns->stateidx = ns->npstates - 1;
1236 } else {
1237 ns->stateidx = ns->npstates;
1239 ns->npstates = 0;
1240 ns->state = ns->op[ns->stateidx];
1241 ns->nxstate = ns->op[ns->stateidx + 1];
1242 NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
1243 idx, get_state_name(ns->state), get_state_name(ns->nxstate));
1244 return 0;
1247 if (opsfound == 0) {
1248 /* Nothing was found. Try to ignore previous commands (if any) and search again */
1249 if (ns->npstates != 0) {
1250 NS_DBG("find_operation: no operation found, try again with state %s\n",
1251 get_state_name(ns->state));
1252 ns->npstates = 0;
1253 return find_operation(ns, 0);
1256 NS_DBG("find_operation: no operations found\n");
1257 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1258 return -2;
1261 if (flag) {
1262 /* This shouldn't happen */
1263 NS_DBG("find_operation: BUG, operation must be known if address is input\n");
1264 return -2;
1267 NS_DBG("find_operation: there is still ambiguity\n");
1269 ns->pstates[ns->npstates++] = ns->state;
1271 return -1;
1274 static void put_pages(struct nandsim *ns)
1276 int i;
1278 for (i = 0; i < ns->held_cnt; i++)
1279 page_cache_release(ns->held_pages[i]);
1282 /* Get page cache pages in advance to provide NOFS memory allocation */
1283 static int get_pages(struct nandsim *ns, struct file *file, size_t count, loff_t pos)
1285 pgoff_t index, start_index, end_index;
1286 struct page *page;
1287 struct address_space *mapping = file->f_mapping;
1289 start_index = pos >> PAGE_CACHE_SHIFT;
1290 end_index = (pos + count - 1) >> PAGE_CACHE_SHIFT;
1291 if (end_index - start_index + 1 > NS_MAX_HELD_PAGES)
1292 return -EINVAL;
1293 ns->held_cnt = 0;
1294 for (index = start_index; index <= end_index; index++) {
1295 page = find_get_page(mapping, index);
1296 if (page == NULL) {
1297 page = find_or_create_page(mapping, index, GFP_NOFS);
1298 if (page == NULL) {
1299 write_inode_now(mapping->host, 1);
1300 page = find_or_create_page(mapping, index, GFP_NOFS);
1302 if (page == NULL) {
1303 put_pages(ns);
1304 return -ENOMEM;
1306 unlock_page(page);
1308 ns->held_pages[ns->held_cnt++] = page;
1310 return 0;
1313 static int set_memalloc(void)
1315 if (current->flags & PF_MEMALLOC)
1316 return 0;
1317 current->flags |= PF_MEMALLOC;
1318 return 1;
1321 static void clear_memalloc(int memalloc)
1323 if (memalloc)
1324 current->flags &= ~PF_MEMALLOC;
1327 static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
1329 mm_segment_t old_fs;
1330 ssize_t tx;
1331 int err, memalloc;
1333 err = get_pages(ns, file, count, *pos);
1334 if (err)
1335 return err;
1336 old_fs = get_fs();
1337 set_fs(get_ds());
1338 memalloc = set_memalloc();
1339 tx = vfs_read(file, (char __user *)buf, count, pos);
1340 clear_memalloc(memalloc);
1341 set_fs(old_fs);
1342 put_pages(ns);
1343 return tx;
1346 static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
1348 mm_segment_t old_fs;
1349 ssize_t tx;
1350 int err, memalloc;
1352 err = get_pages(ns, file, count, *pos);
1353 if (err)
1354 return err;
1355 old_fs = get_fs();
1356 set_fs(get_ds());
1357 memalloc = set_memalloc();
1358 tx = vfs_write(file, (char __user *)buf, count, pos);
1359 clear_memalloc(memalloc);
1360 set_fs(old_fs);
1361 put_pages(ns);
1362 return tx;
1366 * Returns a pointer to the current page.
1368 static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
1370 return &(ns->pages[ns->regs.row]);
1374 * Retuns a pointer to the current byte, within the current page.
1376 static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
1378 return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
1381 int do_read_error(struct nandsim *ns, int num)
1383 unsigned int page_no = ns->regs.row;
1385 if (read_error(page_no)) {
1386 int i;
1387 memset(ns->buf.byte, 0xFF, num);
1388 for (i = 0; i < num; ++i)
1389 ns->buf.byte[i] = random32();
1390 NS_WARN("simulating read error in page %u\n", page_no);
1391 return 1;
1393 return 0;
1396 void do_bit_flips(struct nandsim *ns, int num)
1398 if (bitflips && random32() < (1 << 22)) {
1399 int flips = 1;
1400 if (bitflips > 1)
1401 flips = (random32() % (int) bitflips) + 1;
1402 while (flips--) {
1403 int pos = random32() % (num * 8);
1404 ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
1405 NS_WARN("read_page: flipping bit %d in page %d "
1406 "reading from %d ecc: corrected=%u failed=%u\n",
1407 pos, ns->regs.row, ns->regs.column + ns->regs.off,
1408 nsmtd->ecc_stats.corrected, nsmtd->ecc_stats.failed);
1414 * Fill the NAND buffer with data read from the specified page.
1416 static void read_page(struct nandsim *ns, int num)
1418 union ns_mem *mypage;
1420 if (ns->cfile) {
1421 if (!ns->pages_written[ns->regs.row]) {
1422 NS_DBG("read_page: page %d not written\n", ns->regs.row);
1423 memset(ns->buf.byte, 0xFF, num);
1424 } else {
1425 loff_t pos;
1426 ssize_t tx;
1428 NS_DBG("read_page: page %d written, reading from %d\n",
1429 ns->regs.row, ns->regs.column + ns->regs.off);
1430 if (do_read_error(ns, num))
1431 return;
1432 pos = (loff_t)ns->regs.row * ns->geom.pgszoob + ns->regs.column + ns->regs.off;
1433 tx = read_file(ns, ns->cfile, ns->buf.byte, num, &pos);
1434 if (tx != num) {
1435 NS_ERR("read_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
1436 return;
1438 do_bit_flips(ns, num);
1440 return;
1443 mypage = NS_GET_PAGE(ns);
1444 if (mypage->byte == NULL) {
1445 NS_DBG("read_page: page %d not allocated\n", ns->regs.row);
1446 memset(ns->buf.byte, 0xFF, num);
1447 } else {
1448 NS_DBG("read_page: page %d allocated, reading from %d\n",
1449 ns->regs.row, ns->regs.column + ns->regs.off);
1450 if (do_read_error(ns, num))
1451 return;
1452 memcpy(ns->buf.byte, NS_PAGE_BYTE_OFF(ns), num);
1453 do_bit_flips(ns, num);
1458 * Erase all pages in the specified sector.
1460 static void erase_sector(struct nandsim *ns)
1462 union ns_mem *mypage;
1463 int i;
1465 if (ns->cfile) {
1466 for (i = 0; i < ns->geom.pgsec; i++)
1467 if (ns->pages_written[ns->regs.row + i]) {
1468 NS_DBG("erase_sector: freeing page %d\n", ns->regs.row + i);
1469 ns->pages_written[ns->regs.row + i] = 0;
1471 return;
1474 mypage = NS_GET_PAGE(ns);
1475 for (i = 0; i < ns->geom.pgsec; i++) {
1476 if (mypage->byte != NULL) {
1477 NS_DBG("erase_sector: freeing page %d\n", ns->regs.row+i);
1478 kfree(mypage->byte);
1479 mypage->byte = NULL;
1481 mypage++;
1486 * Program the specified page with the contents from the NAND buffer.
1488 static int prog_page(struct nandsim *ns, int num)
1490 int i;
1491 union ns_mem *mypage;
1492 u_char *pg_off;
1494 if (ns->cfile) {
1495 loff_t off, pos;
1496 ssize_t tx;
1497 int all;
1499 NS_DBG("prog_page: writing page %d\n", ns->regs.row);
1500 pg_off = ns->file_buf + ns->regs.column + ns->regs.off;
1501 off = (loff_t)ns->regs.row * ns->geom.pgszoob + ns->regs.column + ns->regs.off;
1502 if (!ns->pages_written[ns->regs.row]) {
1503 all = 1;
1504 memset(ns->file_buf, 0xff, ns->geom.pgszoob);
1505 } else {
1506 all = 0;
1507 pos = off;
1508 tx = read_file(ns, ns->cfile, pg_off, num, &pos);
1509 if (tx != num) {
1510 NS_ERR("prog_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
1511 return -1;
1514 for (i = 0; i < num; i++)
1515 pg_off[i] &= ns->buf.byte[i];
1516 if (all) {
1517 pos = (loff_t)ns->regs.row * ns->geom.pgszoob;
1518 tx = write_file(ns, ns->cfile, ns->file_buf, ns->geom.pgszoob, &pos);
1519 if (tx != ns->geom.pgszoob) {
1520 NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
1521 return -1;
1523 ns->pages_written[ns->regs.row] = 1;
1524 } else {
1525 pos = off;
1526 tx = write_file(ns, ns->cfile, pg_off, num, &pos);
1527 if (tx != num) {
1528 NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
1529 return -1;
1532 return 0;
1535 mypage = NS_GET_PAGE(ns);
1536 if (mypage->byte == NULL) {
1537 NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
1539 * We allocate memory with GFP_NOFS because a flash FS may
1540 * utilize this. If it is holding an FS lock, then gets here,
1541 * then kmalloc runs writeback which goes to the FS again
1542 * and deadlocks. This was seen in practice.
1544 mypage->byte = kmalloc(ns->geom.pgszoob, GFP_NOFS);
1545 if (mypage->byte == NULL) {
1546 NS_ERR("prog_page: error allocating memory for page %d\n", ns->regs.row);
1547 return -1;
1549 memset(mypage->byte, 0xFF, ns->geom.pgszoob);
1552 pg_off = NS_PAGE_BYTE_OFF(ns);
1553 for (i = 0; i < num; i++)
1554 pg_off[i] &= ns->buf.byte[i];
1556 return 0;
1560 * If state has any action bit, perform this action.
1562 * RETURNS: 0 if success, -1 if error.
1564 static int do_state_action(struct nandsim *ns, uint32_t action)
1566 int num;
1567 int busdiv = ns->busw == 8 ? 1 : 2;
1568 unsigned int erase_block_no, page_no;
1570 action &= ACTION_MASK;
1572 /* Check that page address input is correct */
1573 if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
1574 NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
1575 return -1;
1578 switch (action) {
1580 case ACTION_CPY:
1582 * Copy page data to the internal buffer.
1585 /* Column shouldn't be very large */
1586 if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
1587 NS_ERR("do_state_action: column number is too large\n");
1588 break;
1590 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1591 read_page(ns, num);
1593 NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
1594 num, NS_RAW_OFFSET(ns) + ns->regs.off);
1596 if (ns->regs.off == 0)
1597 NS_LOG("read page %d\n", ns->regs.row);
1598 else if (ns->regs.off < ns->geom.pgsz)
1599 NS_LOG("read page %d (second half)\n", ns->regs.row);
1600 else
1601 NS_LOG("read OOB of page %d\n", ns->regs.row);
1603 NS_UDELAY(access_delay);
1604 NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
1606 break;
1608 case ACTION_SECERASE:
1610 * Erase sector.
1613 if (ns->lines.wp) {
1614 NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
1615 return -1;
1618 if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
1619 || (ns->regs.row & ~(ns->geom.secsz - 1))) {
1620 NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
1621 return -1;
1624 ns->regs.row = (ns->regs.row <<
1625 8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
1626 ns->regs.column = 0;
1628 erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);
1630 NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
1631 ns->regs.row, NS_RAW_OFFSET(ns));
1632 NS_LOG("erase sector %u\n", erase_block_no);
1634 erase_sector(ns);
1636 NS_MDELAY(erase_delay);
1638 if (erase_block_wear)
1639 update_wear(erase_block_no);
1641 if (erase_error(erase_block_no)) {
1642 NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
1643 return -1;
1646 break;
1648 case ACTION_PRGPAGE:
1650 * Programm page - move internal buffer data to the page.
1653 if (ns->lines.wp) {
1654 NS_WARN("do_state_action: device is write-protected, programm\n");
1655 return -1;
1658 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1659 if (num != ns->regs.count) {
1660 NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
1661 ns->regs.count, num);
1662 return -1;
1665 if (prog_page(ns, num) == -1)
1666 return -1;
1668 page_no = ns->regs.row;
1670 NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
1671 num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
1672 NS_LOG("programm page %d\n", ns->regs.row);
1674 NS_UDELAY(programm_delay);
1675 NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
1677 if (write_error(page_no)) {
1678 NS_WARN("simulating write failure in page %u\n", page_no);
1679 return -1;
1682 break;
1684 case ACTION_ZEROOFF:
1685 NS_DBG("do_state_action: set internal offset to 0\n");
1686 ns->regs.off = 0;
1687 break;
1689 case ACTION_HALFOFF:
1690 if (!(ns->options & OPT_PAGE512_8BIT)) {
1691 NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
1692 "byte page size 8x chips\n");
1693 return -1;
1695 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
1696 ns->regs.off = ns->geom.pgsz/2;
1697 break;
1699 case ACTION_OOBOFF:
1700 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
1701 ns->regs.off = ns->geom.pgsz;
1702 break;
1704 default:
1705 NS_DBG("do_state_action: BUG! unknown action\n");
1708 return 0;
1712 * Switch simulator's state.
1714 static void switch_state(struct nandsim *ns)
1716 if (ns->op) {
1718 * The current operation have already been identified.
1719 * Just follow the states chain.
1722 ns->stateidx += 1;
1723 ns->state = ns->nxstate;
1724 ns->nxstate = ns->op[ns->stateidx + 1];
1726 NS_DBG("switch_state: operation is known, switch to the next state, "
1727 "state: %s, nxstate: %s\n",
1728 get_state_name(ns->state), get_state_name(ns->nxstate));
1730 /* See, whether we need to do some action */
1731 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1732 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1733 return;
1736 } else {
1738 * We don't yet know which operation we perform.
1739 * Try to identify it.
1743 * The only event causing the switch_state function to
1744 * be called with yet unknown operation is new command.
1746 ns->state = get_state_by_command(ns->regs.command);
1748 NS_DBG("switch_state: operation is unknown, try to find it\n");
1750 if (find_operation(ns, 0) != 0)
1751 return;
1753 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1754 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1755 return;
1759 /* For 16x devices column means the page offset in words */
1760 if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
1761 NS_DBG("switch_state: double the column number for 16x device\n");
1762 ns->regs.column <<= 1;
1765 if (NS_STATE(ns->nxstate) == STATE_READY) {
1767 * The current state is the last. Return to STATE_READY
1770 u_char status = NS_STATUS_OK(ns);
1772 /* In case of data states, see if all bytes were input/output */
1773 if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
1774 && ns->regs.count != ns->regs.num) {
1775 NS_WARN("switch_state: not all bytes were processed, %d left\n",
1776 ns->regs.num - ns->regs.count);
1777 status = NS_STATUS_FAILED(ns);
1780 NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
1782 switch_to_ready_state(ns, status);
1784 return;
1785 } else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
1787 * If the next state is data input/output, switch to it now
1790 ns->state = ns->nxstate;
1791 ns->nxstate = ns->op[++ns->stateidx + 1];
1792 ns->regs.num = ns->regs.count = 0;
1794 NS_DBG("switch_state: the next state is data I/O, switch, "
1795 "state: %s, nxstate: %s\n",
1796 get_state_name(ns->state), get_state_name(ns->nxstate));
1799 * Set the internal register to the count of bytes which
1800 * are expected to be input or output
1802 switch (NS_STATE(ns->state)) {
1803 case STATE_DATAIN:
1804 case STATE_DATAOUT:
1805 ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1806 break;
1808 case STATE_DATAOUT_ID:
1809 ns->regs.num = ns->geom.idbytes;
1810 break;
1812 case STATE_DATAOUT_STATUS:
1813 case STATE_DATAOUT_STATUS_M:
1814 ns->regs.count = ns->regs.num = 0;
1815 break;
1817 default:
1818 NS_ERR("switch_state: BUG! unknown data state\n");
1821 } else if (ns->nxstate & STATE_ADDR_MASK) {
1823 * If the next state is address input, set the internal
1824 * register to the number of expected address bytes
1827 ns->regs.count = 0;
1829 switch (NS_STATE(ns->nxstate)) {
1830 case STATE_ADDR_PAGE:
1831 ns->regs.num = ns->geom.pgaddrbytes;
1833 break;
1834 case STATE_ADDR_SEC:
1835 ns->regs.num = ns->geom.secaddrbytes;
1836 break;
1838 case STATE_ADDR_ZERO:
1839 ns->regs.num = 1;
1840 break;
1842 case STATE_ADDR_COLUMN:
1843 /* Column address is always 2 bytes */
1844 ns->regs.num = ns->geom.pgaddrbytes - ns->geom.secaddrbytes;
1845 break;
1847 default:
1848 NS_ERR("switch_state: BUG! unknown address state\n");
1850 } else {
1852 * Just reset internal counters.
1855 ns->regs.num = 0;
1856 ns->regs.count = 0;
1860 static u_char ns_nand_read_byte(struct mtd_info *mtd)
1862 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1863 u_char outb = 0x00;
1865 /* Sanity and correctness checks */
1866 if (!ns->lines.ce) {
1867 NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
1868 return outb;
1870 if (ns->lines.ale || ns->lines.cle) {
1871 NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
1872 return outb;
1874 if (!(ns->state & STATE_DATAOUT_MASK)) {
1875 NS_WARN("read_byte: unexpected data output cycle, state is %s "
1876 "return %#x\n", get_state_name(ns->state), (uint)outb);
1877 return outb;
1880 /* Status register may be read as many times as it is wanted */
1881 if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
1882 NS_DBG("read_byte: return %#x status\n", ns->regs.status);
1883 return ns->regs.status;
1886 /* Check if there is any data in the internal buffer which may be read */
1887 if (ns->regs.count == ns->regs.num) {
1888 NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
1889 return outb;
1892 switch (NS_STATE(ns->state)) {
1893 case STATE_DATAOUT:
1894 if (ns->busw == 8) {
1895 outb = ns->buf.byte[ns->regs.count];
1896 ns->regs.count += 1;
1897 } else {
1898 outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
1899 ns->regs.count += 2;
1901 break;
1902 case STATE_DATAOUT_ID:
1903 NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
1904 outb = ns->ids[ns->regs.count];
1905 ns->regs.count += 1;
1906 break;
1907 default:
1908 BUG();
1911 if (ns->regs.count == ns->regs.num) {
1912 NS_DBG("read_byte: all bytes were read\n");
1915 * The OPT_AUTOINCR allows to read next conseqitive pages without
1916 * new read operation cycle.
1918 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
1919 ns->regs.count = 0;
1920 if (ns->regs.row + 1 < ns->geom.pgnum)
1921 ns->regs.row += 1;
1922 NS_DBG("read_byte: switch to the next page (%#x)\n", ns->regs.row);
1923 do_state_action(ns, ACTION_CPY);
1925 else if (NS_STATE(ns->nxstate) == STATE_READY)
1926 switch_state(ns);
1930 return outb;
1933 static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
1935 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1937 /* Sanity and correctness checks */
1938 if (!ns->lines.ce) {
1939 NS_ERR("write_byte: chip is disabled, ignore write\n");
1940 return;
1942 if (ns->lines.ale && ns->lines.cle) {
1943 NS_ERR("write_byte: ALE and CLE pins are high simultaneously, ignore write\n");
1944 return;
1947 if (ns->lines.cle == 1) {
1949 * The byte written is a command.
1952 if (byte == NAND_CMD_RESET) {
1953 NS_LOG("reset chip\n");
1954 switch_to_ready_state(ns, NS_STATUS_OK(ns));
1955 return;
1958 /* Check that the command byte is correct */
1959 if (check_command(byte)) {
1960 NS_ERR("write_byte: unknown command %#x\n", (uint)byte);
1961 return;
1964 if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS
1965 || NS_STATE(ns->state) == STATE_DATAOUT_STATUS_M
1966 || NS_STATE(ns->state) == STATE_DATAOUT) {
1967 int row = ns->regs.row;
1969 switch_state(ns);
1970 if (byte == NAND_CMD_RNDOUT)
1971 ns->regs.row = row;
1974 /* Check if chip is expecting command */
1975 if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
1976 /* Do not warn if only 2 id bytes are read */
1977 if (!(ns->regs.command == NAND_CMD_READID &&
1978 NS_STATE(ns->state) == STATE_DATAOUT_ID && ns->regs.count == 2)) {
1980 * We are in situation when something else (not command)
1981 * was expected but command was input. In this case ignore
1982 * previous command(s)/state(s) and accept the last one.
1984 NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
1985 "ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
1987 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1990 NS_DBG("command byte corresponding to %s state accepted\n",
1991 get_state_name(get_state_by_command(byte)));
1992 ns->regs.command = byte;
1993 switch_state(ns);
1995 } else if (ns->lines.ale == 1) {
1997 * The byte written is an address.
2000 if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
2002 NS_DBG("write_byte: operation isn't known yet, identify it\n");
2004 if (find_operation(ns, 1) < 0)
2005 return;
2007 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
2008 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2009 return;
2012 ns->regs.count = 0;
2013 switch (NS_STATE(ns->nxstate)) {
2014 case STATE_ADDR_PAGE:
2015 ns->regs.num = ns->geom.pgaddrbytes;
2016 break;
2017 case STATE_ADDR_SEC:
2018 ns->regs.num = ns->geom.secaddrbytes;
2019 break;
2020 case STATE_ADDR_ZERO:
2021 ns->regs.num = 1;
2022 break;
2023 default:
2024 BUG();
2028 /* Check that chip is expecting address */
2029 if (!(ns->nxstate & STATE_ADDR_MASK)) {
2030 NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
2031 "switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
2032 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2033 return;
2036 /* Check if this is expected byte */
2037 if (ns->regs.count == ns->regs.num) {
2038 NS_ERR("write_byte: no more address bytes expected\n");
2039 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2040 return;
2043 accept_addr_byte(ns, byte);
2045 ns->regs.count += 1;
2047 NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
2048 (uint)byte, ns->regs.count, ns->regs.num);
2050 if (ns->regs.count == ns->regs.num) {
2051 NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
2052 switch_state(ns);
2055 } else {
2057 * The byte written is an input data.
2060 /* Check that chip is expecting data input */
2061 if (!(ns->state & STATE_DATAIN_MASK)) {
2062 NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
2063 "switch to %s\n", (uint)byte,
2064 get_state_name(ns->state), get_state_name(STATE_READY));
2065 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2066 return;
2069 /* Check if this is expected byte */
2070 if (ns->regs.count == ns->regs.num) {
2071 NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
2072 ns->regs.num);
2073 return;
2076 if (ns->busw == 8) {
2077 ns->buf.byte[ns->regs.count] = byte;
2078 ns->regs.count += 1;
2079 } else {
2080 ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
2081 ns->regs.count += 2;
2085 return;
2088 static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
2090 struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
2092 ns->lines.cle = bitmask & NAND_CLE ? 1 : 0;
2093 ns->lines.ale = bitmask & NAND_ALE ? 1 : 0;
2094 ns->lines.ce = bitmask & NAND_NCE ? 1 : 0;
2096 if (cmd != NAND_CMD_NONE)
2097 ns_nand_write_byte(mtd, cmd);
2100 static int ns_device_ready(struct mtd_info *mtd)
2102 NS_DBG("device_ready\n");
2103 return 1;
2106 static uint16_t ns_nand_read_word(struct mtd_info *mtd)
2108 struct nand_chip *chip = (struct nand_chip *)mtd->priv;
2110 NS_DBG("read_word\n");
2112 return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
2115 static void ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
2117 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
2119 /* Check that chip is expecting data input */
2120 if (!(ns->state & STATE_DATAIN_MASK)) {
2121 NS_ERR("write_buf: data input isn't expected, state is %s, "
2122 "switch to STATE_READY\n", get_state_name(ns->state));
2123 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2124 return;
2127 /* Check if these are expected bytes */
2128 if (ns->regs.count + len > ns->regs.num) {
2129 NS_ERR("write_buf: too many input bytes\n");
2130 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2131 return;
2134 memcpy(ns->buf.byte + ns->regs.count, buf, len);
2135 ns->regs.count += len;
2137 if (ns->regs.count == ns->regs.num) {
2138 NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
2142 static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
2144 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
2146 /* Sanity and correctness checks */
2147 if (!ns->lines.ce) {
2148 NS_ERR("read_buf: chip is disabled\n");
2149 return;
2151 if (ns->lines.ale || ns->lines.cle) {
2152 NS_ERR("read_buf: ALE or CLE pin is high\n");
2153 return;
2155 if (!(ns->state & STATE_DATAOUT_MASK)) {
2156 NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
2157 get_state_name(ns->state));
2158 return;
2161 if (NS_STATE(ns->state) != STATE_DATAOUT) {
2162 int i;
2164 for (i = 0; i < len; i++)
2165 buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);
2167 return;
2170 /* Check if these are expected bytes */
2171 if (ns->regs.count + len > ns->regs.num) {
2172 NS_ERR("read_buf: too many bytes to read\n");
2173 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2174 return;
2177 memcpy(buf, ns->buf.byte + ns->regs.count, len);
2178 ns->regs.count += len;
2180 if (ns->regs.count == ns->regs.num) {
2181 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
2182 ns->regs.count = 0;
2183 if (ns->regs.row + 1 < ns->geom.pgnum)
2184 ns->regs.row += 1;
2185 NS_DBG("read_buf: switch to the next page (%#x)\n", ns->regs.row);
2186 do_state_action(ns, ACTION_CPY);
2188 else if (NS_STATE(ns->nxstate) == STATE_READY)
2189 switch_state(ns);
2192 return;
2195 static int ns_nand_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
2197 ns_nand_read_buf(mtd, (u_char *)&ns_verify_buf[0], len);
2199 if (!memcmp(buf, &ns_verify_buf[0], len)) {
2200 NS_DBG("verify_buf: the buffer is OK\n");
2201 return 0;
2202 } else {
2203 NS_DBG("verify_buf: the buffer is wrong\n");
2204 return -EFAULT;
2209 * Module initialization function
2211 static int __init ns_init_module(void)
2213 struct nand_chip *chip;
2214 struct nandsim *nand;
2215 int retval = -ENOMEM, i;
2217 if (bus_width != 8 && bus_width != 16) {
2218 NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
2219 return -EINVAL;
2222 /* Allocate and initialize mtd_info, nand_chip and nandsim structures */
2223 nsmtd = kzalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip)
2224 + sizeof(struct nandsim), GFP_KERNEL);
2225 if (!nsmtd) {
2226 NS_ERR("unable to allocate core structures.\n");
2227 return -ENOMEM;
2229 chip = (struct nand_chip *)(nsmtd + 1);
2230 nsmtd->priv = (void *)chip;
2231 nand = (struct nandsim *)(chip + 1);
2232 chip->priv = (void *)nand;
2235 * Register simulator's callbacks.
2237 chip->cmd_ctrl = ns_hwcontrol;
2238 chip->read_byte = ns_nand_read_byte;
2239 chip->dev_ready = ns_device_ready;
2240 chip->write_buf = ns_nand_write_buf;
2241 chip->read_buf = ns_nand_read_buf;
2242 chip->verify_buf = ns_nand_verify_buf;
2243 chip->read_word = ns_nand_read_word;
2244 chip->ecc.mode = NAND_ECC_SOFT;
2245 /* The NAND_SKIP_BBTSCAN option is necessary for 'overridesize' */
2246 /* and 'badblocks' parameters to work */
2247 chip->options |= NAND_SKIP_BBTSCAN;
2250 * Perform minimum nandsim structure initialization to handle
2251 * the initial ID read command correctly
2253 if (third_id_byte != 0xFF || fourth_id_byte != 0xFF)
2254 nand->geom.idbytes = 4;
2255 else
2256 nand->geom.idbytes = 2;
2257 nand->regs.status = NS_STATUS_OK(nand);
2258 nand->nxstate = STATE_UNKNOWN;
2259 nand->options |= OPT_PAGE256; /* temporary value */
2260 nand->ids[0] = first_id_byte;
2261 nand->ids[1] = second_id_byte;
2262 nand->ids[2] = third_id_byte;
2263 nand->ids[3] = fourth_id_byte;
2264 if (bus_width == 16) {
2265 nand->busw = 16;
2266 chip->options |= NAND_BUSWIDTH_16;
2269 nsmtd->owner = THIS_MODULE;
2271 if ((retval = parse_weakblocks()) != 0)
2272 goto error;
2274 if ((retval = parse_weakpages()) != 0)
2275 goto error;
2277 if ((retval = parse_gravepages()) != 0)
2278 goto error;
2280 if ((retval = nand_scan(nsmtd, 1)) != 0) {
2281 NS_ERR("can't register NAND Simulator\n");
2282 if (retval > 0)
2283 retval = -ENXIO;
2284 goto error;
2287 if (overridesize) {
2288 u_int64_t new_size = (u_int64_t)nsmtd->erasesize << overridesize;
2289 if (new_size >> overridesize != nsmtd->erasesize) {
2290 NS_ERR("overridesize is too big\n");
2291 goto err_exit;
2293 /* N.B. This relies on nand_scan not doing anything with the size before we change it */
2294 nsmtd->size = new_size;
2295 chip->chipsize = new_size;
2296 chip->chip_shift = ffs(nsmtd->erasesize) + overridesize - 1;
2297 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
2300 if ((retval = setup_wear_reporting(nsmtd)) != 0)
2301 goto err_exit;
2303 if ((retval = init_nandsim(nsmtd)) != 0)
2304 goto err_exit;
2306 if ((retval = parse_badblocks(nand, nsmtd)) != 0)
2307 goto err_exit;
2309 if ((retval = nand_default_bbt(nsmtd)) != 0)
2310 goto err_exit;
2312 /* Register NAND partitions */
2313 if ((retval = add_mtd_partitions(nsmtd, &nand->partitions[0], nand->nbparts)) != 0)
2314 goto err_exit;
2316 return 0;
2318 err_exit:
2319 free_nandsim(nand);
2320 nand_release(nsmtd);
2321 for (i = 0;i < ARRAY_SIZE(nand->partitions); ++i)
2322 kfree(nand->partitions[i].name);
2323 error:
2324 kfree(nsmtd);
2325 free_lists();
2327 return retval;
2330 module_init(ns_init_module);
2333 * Module clean-up function
2335 static void __exit ns_cleanup_module(void)
2337 struct nandsim *ns = (struct nandsim *)(((struct nand_chip *)nsmtd->priv)->priv);
2338 int i;
2340 free_nandsim(ns); /* Free nandsim private resources */
2341 nand_release(nsmtd); /* Unregister driver */
2342 for (i = 0;i < ARRAY_SIZE(ns->partitions); ++i)
2343 kfree(ns->partitions[i].name);
2344 kfree(nsmtd); /* Free other structures */
2345 free_lists();
2348 module_exit(ns_cleanup_module);
2350 MODULE_LICENSE ("GPL");
2351 MODULE_AUTHOR ("Artem B. Bityuckiy");
2352 MODULE_DESCRIPTION ("The NAND flash simulator");