]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/mtd/nand/nandsim.c
MTD: nandsim: add option to use a file to cache pages
[linux-2.6-omap-h63xx.git] / drivers / mtd / nand / nandsim.c
1 /*
2  * NAND flash simulator.
3  *
4  * Author: Artem B. Bityuckiy <dedekind@oktetlabs.ru>, <dedekind@infradead.org>
5  *
6  * Copyright (C) 2004 Nokia Corporation
7  *
8  * Note: NS means "NAND Simulator".
9  * Note: Input means input TO flash chip, output means output FROM chip.
10  *
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.
15  *
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.
20  *
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
24  */
25
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>
43
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
54
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
82
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;
106
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);
129
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");
161
162 /* The largest possible page size */
163 #define NS_LARGEST_PAGE_SIZE    2048
164
165 /* The prefix for simulator output */
166 #define NS_OUTPUT_PREFIX "[nandsim]"
167
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)
179
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)
185
186 /* Is the nandsim structure initialized ? */
187 #define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
188
189 /* Good operation completion status */
190 #define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
191
192 /* Operation failed completion status */
193 #define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
194
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)
198
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)
201
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 */
218
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 */
225
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 */
229
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 */
235
236 /* Previous operation is done, ready to accept new requests */
237 #define STATE_READY            0x00000000
238
239 /* This state is used to mark that the next state isn't known yet */
240 #define STATE_UNKNOWN          0x10000000
241
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 */
250
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 */
253
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 */
263
264 /* Remove action bits ftom state */
265 #define NS_STATE(x) ((x) & ~ACTION_MASK)
266
267 /*
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).
271  */
272 #define NS_MAX_PREVSTATES 1
273
274 /* Maximum page cache pages needed to read or write a NAND page to the cache_file */
275 #define NS_MAX_HELD_PAGES 16
276
277 /*
278  * A union to represent flash memory contents and flash buffer.
279  */
280 union ns_mem {
281         u_char *byte;    /* for byte access */
282         uint16_t *word;  /* for 16-bit word access */
283 };
284
285 /*
286  * The structure which describes all the internal simulator data.
287  */
288 struct nandsim {
289         struct mtd_partition partitions[MAX_MTD_DEVICES];
290         unsigned int nbparts;
291
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 */
297
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 */
302
303         /* The simulated NAND flash pages array */
304         union ns_mem *pages;
305
306         /* Internal buffer of page + OOB size bytes */
307         union ns_mem buf;
308
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;
327
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;
338
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;
346
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;
353 };
354
355 /*
356  * Operations array. To perform any operation the simulator must pass
357  * through the correspondent states chain.
358  */
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}},
398 };
399
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;
405 };
406
407 static LIST_HEAD(weak_blocks);
408
409 struct weak_page {
410         struct list_head list;
411         unsigned int page_no;
412         unsigned int max_writes;
413         unsigned int writes_done;
414 };
415
416 static LIST_HEAD(weak_pages);
417
418 struct grave_page {
419         struct list_head list;
420         unsigned int page_no;
421         unsigned int max_reads;
422         unsigned int reads_done;
423 };
424
425 static LIST_HEAD(grave_pages);
426
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;
431
432 /* MTD structure for NAND controller */
433 static struct mtd_info *nsmtd;
434
435 static u_char ns_verify_buf[NS_LARGEST_PAGE_SIZE];
436
437 /*
438  * Allocate array of page pointers and initialize the array to NULL
439  * pointers.
440  *
441  * RETURNS: 0 if success, -ENOMEM if memory alloc fails.
442  */
443 static int alloc_device(struct nandsim *ns)
444 {
445         struct file *cfile;
446         int i, err;
447
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;
456                 }
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;
461                 }
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;
467                 }
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;
473                 }
474                 ns->cfile = cfile;
475                 memset(ns->pages_written, 0, ns->geom.pgnum);
476                 return 0;
477         }
478
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;
483         }
484         for (i = 0; i < ns->geom.pgnum; i++) {
485                 ns->pages[i].byte = NULL;
486         }
487
488         return 0;
489
490 err_free:
491         vfree(ns->pages_written);
492 err_close:
493         filp_close(cfile, NULL);
494         return err;
495 }
496
497 /*
498  * Free any allocated pages, and free the array of page pointers.
499  */
500 static void free_device(struct nandsim *ns)
501 {
502         int i;
503
504         if (ns->cfile) {
505                 kfree(ns->file_buf);
506                 vfree(ns->pages_written);
507                 filp_close(ns->cfile, NULL);
508                 return;
509         }
510
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);
515                 }
516                 vfree(ns->pages);
517         }
518 }
519
520 static char *get_partition_name(int i)
521 {
522         char buf[64];
523         sprintf(buf, "NAND simulator partition %d", i);
524         return kstrdup(buf, GFP_KERNEL);
525 }
526
527 static u_int64_t divide(u_int64_t n, u_int32_t d)
528 {
529         do_div(n, d);
530         return n;
531 }
532
533 /*
534  * Initialize the nandsim structure.
535  *
536  * RETURNS: 0 if success, -ERRNO if failure.
537  */
538 static int init_nandsim(struct mtd_info *mtd)
539 {
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;
545
546         if (NS_IS_INITIALIZED(ns)) {
547                 NS_ERR("init_nandsim: nandsim is already initialized\n");
548                 return -EIO;
549         }
550
551         /* Force mtd to not do delays */
552         chip->chip_delay = 0;
553
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;
569
570         if (ns->geom.pgsz == 256) {
571                 ns->options |= OPT_PAGE256;
572         }
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;
582         }
583
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;
591                 }
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;
599                 }
600         }
601
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;
607         }
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;
612
613                 if (!part_sz || part_sz > remains) {
614                         NS_ERR("bad partition size.\n");
615                         ret = -EINVAL;
616                         goto error;
617                 }
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;
623         }
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;
630                 }
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;
635         }
636
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;
643         }
644
645         if (ns->busw == 16)
646                 NS_WARN("16-bit flashes support wasn't tested\n");
647
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);
664
665         if ((ret = alloc_device(ns)) != 0)
666                 goto error;
667
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;
675         }
676         memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
677
678         return 0;
679
680 error:
681         free_device(ns);
682
683         return ret;
684 }
685
686 /*
687  * Free the nandsim structure.
688  */
689 static void free_nandsim(struct nandsim *ns)
690 {
691         kfree(ns->buf.byte);
692         free_device(ns);
693
694         return;
695 }
696
697 static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
698 {
699         char *w;
700         int zero_ok;
701         unsigned int erase_block_no;
702         loff_t offset;
703
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;
713                 }
714                 offset = erase_block_no * ns->geom.secsz;
715                 if (mtd->block_markbad(mtd, offset)) {
716                         NS_ERR("invalid badblocks.\n");
717                         return -EINVAL;
718                 }
719                 if (*w == ',')
720                         w += 1;
721         } while (*w);
722         return 0;
723 }
724
725 static int parse_weakblocks(void)
726 {
727         char *w;
728         int zero_ok;
729         unsigned int erase_block_no;
730         unsigned int max_erases;
731         struct weak_block *wb;
732
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;
742                 }
743                 max_erases = 3;
744                 if (*w == ':') {
745                         w += 1;
746                         max_erases = simple_strtoul(w, &w, 0);
747                 }
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;
754                 }
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;
760 }
761
762 static int erase_error(unsigned int erase_block_no)
763 {
764         struct weak_block *wb;
765
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;
772                 }
773         return 0;
774 }
775
776 static int parse_weakpages(void)
777 {
778         char *w;
779         int zero_ok;
780         unsigned int page_no;
781         unsigned int max_writes;
782         struct weak_page *wp;
783
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;
793                 }
794                 max_writes = 3;
795                 if (*w == ':') {
796                         w += 1;
797                         max_writes = simple_strtoul(w, &w, 0);
798                 }
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;
805                 }
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;
811 }
812
813 static int write_error(unsigned int page_no)
814 {
815         struct weak_page *wp;
816
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;
823                 }
824         return 0;
825 }
826
827 static int parse_gravepages(void)
828 {
829         char *g;
830         int zero_ok;
831         unsigned int page_no;
832         unsigned int max_reads;
833         struct grave_page *gp;
834
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;
844                 }
845                 max_reads = 3;
846                 if (*g == ':') {
847                         g += 1;
848                         max_reads = simple_strtoul(g, &g, 0);
849                 }
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;
856                 }
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;
862 }
863
864 static int read_error(unsigned int page_no)
865 {
866         struct grave_page *gp;
867
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;
874                 }
875         return 0;
876 }
877
878 static void free_lists(void)
879 {
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));
884         }
885         list_for_each_safe(pos, n, &weak_pages) {
886                 list_del(pos);
887                 kfree(list_entry(pos, struct weak_page, list));
888         }
889         list_for_each_safe(pos, n, &grave_pages) {
890                 list_del(pos);
891                 kfree(list_entry(pos, struct grave_page, list));
892         }
893         kfree(erase_block_wear);
894 }
895
896 static int setup_wear_reporting(struct mtd_info *mtd)
897 {
898         size_t mem;
899
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;
907         }
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;
912         }
913         return 0;
914 }
915
916 static void update_wear(unsigned int erase_block_no)
917 {
918         unsigned long wmin = -1, wmax = 0, avg;
919         unsigned long deciles[10], decile_max[10], tot = 0;
920         unsigned int i;
921
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;
942         }
943         for (i = 0; i < 9; ++i) {
944                 deciles[i] = 0;
945                 decile_max[i] = (wmax * (i + 1) + 5) / 10;
946         }
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;
956                         }
957         }
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]);
974         }
975         NS_INFO("*** End of Wear Report ***\n");
976 }
977
978 /*
979  * Returns the string representation of 'state' state.
980  */
981 static char *get_state_name(uint32_t state)
982 {
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";
1034         }
1035
1036         NS_ERR("get_state_name: unknown state, BUG\n");
1037         return NULL;
1038 }
1039
1040 /*
1041  * Check if command is valid.
1042  *
1043  * RETURNS: 1 if wrong command, 0 if right.
1044  */
1045 static int check_command(int cmd)
1046 {
1047         switch (cmd) {
1048
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;
1063
1064         case NAND_CMD_STATUS_MULTI:
1065         default:
1066                 return 1;
1067         }
1068 }
1069
1070 /*
1071  * Returns state after command is accepted by command number.
1072  */
1073 static uint32_t get_state_by_command(unsigned command)
1074 {
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;
1104         }
1105
1106         NS_ERR("get_state_by_command: unknown command, BUG\n");
1107         return 0;
1108 }
1109
1110 /*
1111  * Move an address byte to the correspondent internal register.
1112  */
1113 static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
1114 {
1115         uint byte = (uint)bt;
1116
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));
1123         }
1124
1125         return;
1126 }
1127
1128 /*
1129  * Switch to STATE_READY state.
1130  */
1131 static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
1132 {
1133         NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
1134
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;
1146 }
1147
1148 /*
1149  * If the operation isn't known yet, try to find it in the global array
1150  * of supported operations.
1151  *
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.
1159  *
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
1163  *
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).
1167  *
1168  * If there are several maches, the current state is pushed to the
1169  * ns->pstates.
1170  *
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>
1176  *
1177  * It is supposed that this pattern must either match one operation on
1178  * none. There can't be ambiguity in that case.
1179  *
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.
1185  *
1186  * RETURNS: -2 - no matched operations found.
1187  *          -1 - several matches.
1188  *           0 - operation is found.
1189  */
1190 static int find_operation(struct nandsim *ns, uint32_t flag)
1191 {
1192         int opsfound = 0;
1193         int i, j, idx = 0;
1194
1195         for (i = 0; i < NS_OPER_NUM; i++) {
1196
1197                 int found = 1;
1198
1199                 if (!(ns->options & ops[i].reqopts))
1200                         /* Ignore operations we can't perform */
1201                         continue;
1202
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;
1209                 }
1210
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;
1216                         }
1217
1218                 if (found) {
1219                         idx = i;
1220                         opsfound += 1;
1221                 }
1222         }
1223
1224         if (opsfound == 1) {
1225                 /* Exact match */
1226                 ns->op = &ops[idx].states[0];
1227                 if (flag) {
1228                         /*
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).
1234                          */
1235                         ns->stateidx = ns->npstates - 1;
1236                 } else {
1237                         ns->stateidx = ns->npstates;
1238                 }
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;
1245         }
1246
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);
1254
1255                 }
1256                 NS_DBG("find_operation: no operations found\n");
1257                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1258                 return -2;
1259         }
1260
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;
1265         }
1266
1267         NS_DBG("find_operation: there is still ambiguity\n");
1268
1269         ns->pstates[ns->npstates++] = ns->state;
1270
1271         return -1;
1272 }
1273
1274 static void put_pages(struct nandsim *ns)
1275 {
1276         int i;
1277
1278         for (i = 0; i < ns->held_cnt; i++)
1279                 page_cache_release(ns->held_pages[i]);
1280 }
1281
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)
1284 {
1285         pgoff_t index, start_index, end_index;
1286         struct page *page;
1287         struct address_space *mapping = file->f_mapping;
1288
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);
1301                         }
1302                         if (page == NULL) {
1303                                 put_pages(ns);
1304                                 return -ENOMEM;
1305                         }
1306                         unlock_page(page);
1307                 }
1308                 ns->held_pages[ns->held_cnt++] = page;
1309         }
1310         return 0;
1311 }
1312
1313 static int set_memalloc(void)
1314 {
1315         if (current->flags & PF_MEMALLOC)
1316                 return 0;
1317         current->flags |= PF_MEMALLOC;
1318         return 1;
1319 }
1320
1321 static void clear_memalloc(int memalloc)
1322 {
1323         if (memalloc)
1324                 current->flags &= ~PF_MEMALLOC;
1325 }
1326
1327 static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
1328 {
1329         mm_segment_t old_fs;
1330         ssize_t tx;
1331         int err, memalloc;
1332
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;
1344 }
1345
1346 static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t *pos)
1347 {
1348         mm_segment_t old_fs;
1349         ssize_t tx;
1350         int err, memalloc;
1351
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;
1363 }
1364
1365 /*
1366  * Returns a pointer to the current page.
1367  */
1368 static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
1369 {
1370         return &(ns->pages[ns->regs.row]);
1371 }
1372
1373 /*
1374  * Retuns a pointer to the current byte, within the current page.
1375  */
1376 static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
1377 {
1378         return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
1379 }
1380
1381 int do_read_error(struct nandsim *ns, int num)
1382 {
1383         unsigned int page_no = ns->regs.row;
1384
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;
1392         }
1393         return 0;
1394 }
1395
1396 void do_bit_flips(struct nandsim *ns, int num)
1397 {
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);
1409                 }
1410         }
1411 }
1412
1413 /*
1414  * Fill the NAND buffer with data read from the specified page.
1415  */
1416 static void read_page(struct nandsim *ns, int num)
1417 {
1418         union ns_mem *mypage;
1419
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;
1427
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;
1437                         }
1438                         do_bit_flips(ns, num);
1439                 }
1440                 return;
1441         }
1442
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);
1454         }
1455 }
1456
1457 /*
1458  * Erase all pages in the specified sector.
1459  */
1460 static void erase_sector(struct nandsim *ns)
1461 {
1462         union ns_mem *mypage;
1463         int i;
1464
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;
1470                         }
1471                 return;
1472         }
1473
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;
1480                 }
1481                 mypage++;
1482         }
1483 }
1484
1485 /*
1486  * Program the specified page with the contents from the NAND buffer.
1487  */
1488 static int prog_page(struct nandsim *ns, int num)
1489 {
1490         int i;
1491         union ns_mem *mypage;
1492         u_char *pg_off;
1493
1494         if (ns->cfile) {
1495                 loff_t off, pos;
1496                 ssize_t tx;
1497                 int all;
1498
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;
1512                         }
1513                 }
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;
1522                         }
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;
1530                         }
1531                 }
1532                 return 0;
1533         }
1534
1535         mypage = NS_GET_PAGE(ns);
1536         if (mypage->byte == NULL) {
1537                 NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
1538                 /*
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.
1543                  */
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;
1548                 }
1549                 memset(mypage->byte, 0xFF, ns->geom.pgszoob);
1550         }
1551
1552         pg_off = NS_PAGE_BYTE_OFF(ns);
1553         for (i = 0; i < num; i++)
1554                 pg_off[i] &= ns->buf.byte[i];
1555
1556         return 0;
1557 }
1558
1559 /*
1560  * If state has any action bit, perform this action.
1561  *
1562  * RETURNS: 0 if success, -1 if error.
1563  */
1564 static int do_state_action(struct nandsim *ns, uint32_t action)
1565 {
1566         int num;
1567         int busdiv = ns->busw == 8 ? 1 : 2;
1568         unsigned int erase_block_no, page_no;
1569
1570         action &= ACTION_MASK;
1571
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;
1576         }
1577
1578         switch (action) {
1579
1580         case ACTION_CPY:
1581                 /*
1582                  * Copy page data to the internal buffer.
1583                  */
1584
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;
1589                 }
1590                 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1591                 read_page(ns, num);
1592
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);
1595
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);
1602
1603                 NS_UDELAY(access_delay);
1604                 NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
1605
1606                 break;
1607
1608         case ACTION_SECERASE:
1609                 /*
1610                  * Erase sector.
1611                  */
1612
1613                 if (ns->lines.wp) {
1614                         NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
1615                         return -1;
1616                 }
1617
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;
1622                 }
1623
1624                 ns->regs.row = (ns->regs.row <<
1625                                 8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
1626                 ns->regs.column = 0;
1627
1628                 erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);
1629
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);
1633
1634                 erase_sector(ns);
1635
1636                 NS_MDELAY(erase_delay);
1637
1638                 if (erase_block_wear)
1639                         update_wear(erase_block_no);
1640
1641                 if (erase_error(erase_block_no)) {
1642                         NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
1643                         return -1;
1644                 }
1645
1646                 break;
1647
1648         case ACTION_PRGPAGE:
1649                 /*
1650                  * Programm page - move internal buffer data to the page.
1651                  */
1652
1653                 if (ns->lines.wp) {
1654                         NS_WARN("do_state_action: device is write-protected, programm\n");
1655                         return -1;
1656                 }
1657
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;
1663                 }
1664
1665                 if (prog_page(ns, num) == -1)
1666                         return -1;
1667
1668                 page_no = ns->regs.row;
1669
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);
1673
1674                 NS_UDELAY(programm_delay);
1675                 NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
1676
1677                 if (write_error(page_no)) {
1678                         NS_WARN("simulating write failure in page %u\n", page_no);
1679                         return -1;
1680                 }
1681
1682                 break;
1683
1684         case ACTION_ZEROOFF:
1685                 NS_DBG("do_state_action: set internal offset to 0\n");
1686                 ns->regs.off = 0;
1687                 break;
1688
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;
1694                 }
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;
1698
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;
1703
1704         default:
1705                 NS_DBG("do_state_action: BUG! unknown action\n");
1706         }
1707
1708         return 0;
1709 }
1710
1711 /*
1712  * Switch simulator's state.
1713  */
1714 static void switch_state(struct nandsim *ns)
1715 {
1716         if (ns->op) {
1717                 /*
1718                  * The current operation have already been identified.
1719                  * Just follow the states chain.
1720                  */
1721
1722                 ns->stateidx += 1;
1723                 ns->state = ns->nxstate;
1724                 ns->nxstate = ns->op[ns->stateidx + 1];
1725
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));
1729
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;
1734                 }
1735
1736         } else {
1737                 /*
1738                  * We don't yet know which operation we perform.
1739                  * Try to identify it.
1740                  */
1741
1742                 /*
1743                  *  The only event causing the switch_state function to
1744                  *  be called with yet unknown operation is new command.
1745                  */
1746                 ns->state = get_state_by_command(ns->regs.command);
1747
1748                 NS_DBG("switch_state: operation is unknown, try to find it\n");
1749
1750                 if (find_operation(ns, 0) != 0)
1751                         return;
1752
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;
1756                 }
1757         }
1758
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;
1763         }
1764
1765         if (NS_STATE(ns->nxstate) == STATE_READY) {
1766                 /*
1767                  * The current state is the last. Return to STATE_READY
1768                  */
1769
1770                 u_char status = NS_STATUS_OK(ns);
1771
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);
1778                 }
1779
1780                 NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
1781
1782                 switch_to_ready_state(ns, status);
1783
1784                 return;
1785         } else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
1786                 /*
1787                  * If the next state is data input/output, switch to it now
1788                  */
1789
1790                 ns->state      = ns->nxstate;
1791                 ns->nxstate    = ns->op[++ns->stateidx + 1];
1792                 ns->regs.num   = ns->regs.count = 0;
1793
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));
1797
1798                 /*
1799                  * Set the internal register to the count of bytes which
1800                  * are expected to be input or output
1801                  */
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;
1807
1808                         case STATE_DATAOUT_ID:
1809                                 ns->regs.num = ns->geom.idbytes;
1810                                 break;
1811
1812                         case STATE_DATAOUT_STATUS:
1813                         case STATE_DATAOUT_STATUS_M:
1814                                 ns->regs.count = ns->regs.num = 0;
1815                                 break;
1816
1817                         default:
1818                                 NS_ERR("switch_state: BUG! unknown data state\n");
1819                 }
1820
1821         } else if (ns->nxstate & STATE_ADDR_MASK) {
1822                 /*
1823                  * If the next state is address input, set the internal
1824                  * register to the number of expected address bytes
1825                  */
1826
1827                 ns->regs.count = 0;
1828
1829                 switch (NS_STATE(ns->nxstate)) {
1830                         case STATE_ADDR_PAGE:
1831                                 ns->regs.num = ns->geom.pgaddrbytes;
1832
1833                                 break;
1834                         case STATE_ADDR_SEC:
1835                                 ns->regs.num = ns->geom.secaddrbytes;
1836                                 break;
1837
1838                         case STATE_ADDR_ZERO:
1839                                 ns->regs.num = 1;
1840                                 break;
1841
1842                         case STATE_ADDR_COLUMN:
1843                                 /* Column address is always 2 bytes */
1844                                 ns->regs.num = ns->geom.pgaddrbytes - ns->geom.secaddrbytes;
1845                                 break;
1846
1847                         default:
1848                                 NS_ERR("switch_state: BUG! unknown address state\n");
1849                 }
1850         } else {
1851                 /*
1852                  * Just reset internal counters.
1853                  */
1854
1855                 ns->regs.num = 0;
1856                 ns->regs.count = 0;
1857         }
1858 }
1859
1860 static u_char ns_nand_read_byte(struct mtd_info *mtd)
1861 {
1862         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1863         u_char outb = 0x00;
1864
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;
1869         }
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;
1873         }
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;
1878         }
1879
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;
1884         }
1885
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;
1890         }
1891
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;
1900                         }
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();
1909         }
1910
1911         if (ns->regs.count == ns->regs.num) {
1912                 NS_DBG("read_byte: all bytes were read\n");
1913
1914                 /*
1915                  * The OPT_AUTOINCR allows to read next conseqitive pages without
1916                  * new read operation cycle.
1917                  */
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);
1924                 }
1925                 else if (NS_STATE(ns->nxstate) == STATE_READY)
1926                         switch_state(ns);
1927
1928         }
1929
1930         return outb;
1931 }
1932
1933 static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
1934 {
1935         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1936
1937         /* Sanity and correctness checks */
1938         if (!ns->lines.ce) {
1939                 NS_ERR("write_byte: chip is disabled, ignore write\n");
1940                 return;
1941         }
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;
1945         }
1946
1947         if (ns->lines.cle == 1) {
1948                 /*
1949                  * The byte written is a command.
1950                  */
1951
1952                 if (byte == NAND_CMD_RESET) {
1953                         NS_LOG("reset chip\n");
1954                         switch_to_ready_state(ns, NS_STATUS_OK(ns));
1955                         return;
1956                 }
1957
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;
1962                 }
1963
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;
1968
1969                         switch_state(ns);
1970                         if (byte == NAND_CMD_RNDOUT)
1971                                 ns->regs.row = row;
1972                 }
1973
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)) {
1979                                 /*
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.
1983                                  */
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));
1986                         }
1987                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1988                 }
1989
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);
1994
1995         } else if (ns->lines.ale == 1) {
1996                 /*
1997                  * The byte written is an address.
1998                  */
1999
2000                 if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
2001
2002                         NS_DBG("write_byte: operation isn't known yet, identify it\n");
2003
2004                         if (find_operation(ns, 1) < 0)
2005                                 return;
2006
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;
2010                         }
2011
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();
2025                         }
2026                 }
2027
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;
2034                 }
2035
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;
2041                 }
2042
2043                 accept_addr_byte(ns, byte);
2044
2045                 ns->regs.count += 1;
2046
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);
2049
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);
2053                 }
2054
2055         } else {
2056                 /*
2057                  * The byte written is an input data.
2058                  */
2059
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;
2067                 }
2068
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;
2074                 }
2075
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;
2082                 }
2083         }
2084
2085         return;
2086 }
2087
2088 static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
2089 {
2090         struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
2091
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;
2095
2096         if (cmd != NAND_CMD_NONE)
2097                 ns_nand_write_byte(mtd, cmd);
2098 }
2099
2100 static int ns_device_ready(struct mtd_info *mtd)
2101 {
2102         NS_DBG("device_ready\n");
2103         return 1;
2104 }
2105
2106 static uint16_t ns_nand_read_word(struct mtd_info *mtd)
2107 {
2108         struct nand_chip *chip = (struct nand_chip *)mtd->priv;
2109
2110         NS_DBG("read_word\n");
2111
2112         return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
2113 }
2114
2115 static void ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
2116 {
2117         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
2118
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;
2125         }
2126
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;
2132         }
2133
2134         memcpy(ns->buf.byte + ns->regs.count, buf, len);
2135         ns->regs.count += len;
2136
2137         if (ns->regs.count == ns->regs.num) {
2138                 NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
2139         }
2140 }
2141
2142 static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
2143 {
2144         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
2145
2146         /* Sanity and correctness checks */
2147         if (!ns->lines.ce) {
2148                 NS_ERR("read_buf: chip is disabled\n");
2149                 return;
2150         }
2151         if (ns->lines.ale || ns->lines.cle) {
2152                 NS_ERR("read_buf: ALE or CLE pin is high\n");
2153                 return;
2154         }
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;
2159         }
2160
2161         if (NS_STATE(ns->state) != STATE_DATAOUT) {
2162                 int i;
2163
2164                 for (i = 0; i < len; i++)
2165                         buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);
2166
2167                 return;
2168         }
2169
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;
2175         }
2176
2177         memcpy(buf, ns->buf.byte + ns->regs.count, len);
2178         ns->regs.count += len;
2179
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);
2187                 }
2188                 else if (NS_STATE(ns->nxstate) == STATE_READY)
2189                         switch_state(ns);
2190         }
2191
2192         return;
2193 }
2194
2195 static int ns_nand_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
2196 {
2197         ns_nand_read_buf(mtd, (u_char *)&ns_verify_buf[0], len);
2198
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;
2205         }
2206 }
2207
2208 /*
2209  * Module initialization function
2210  */
2211 static int __init ns_init_module(void)
2212 {
2213         struct nand_chip *chip;
2214         struct nandsim *nand;
2215         int retval = -ENOMEM, i;
2216
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;
2220         }
2221
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;
2228         }
2229         chip        = (struct nand_chip *)(nsmtd + 1);
2230         nsmtd->priv = (void *)chip;
2231         nand        = (struct nandsim *)(chip + 1);
2232         chip->priv  = (void *)nand;
2233
2234         /*
2235          * Register simulator's callbacks.
2236          */
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;
2248
2249         /*
2250          * Perform minimum nandsim structure initialization to handle
2251          * the initial ID read command correctly
2252          */
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;
2267         }
2268
2269         nsmtd->owner = THIS_MODULE;
2270
2271         if ((retval = parse_weakblocks()) != 0)
2272                 goto error;
2273
2274         if ((retval = parse_weakpages()) != 0)
2275                 goto error;
2276
2277         if ((retval = parse_gravepages()) != 0)
2278                 goto error;
2279
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;
2285         }
2286
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;
2292                 }
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;
2298         }
2299
2300         if ((retval = setup_wear_reporting(nsmtd)) != 0)
2301                 goto err_exit;
2302
2303         if ((retval = init_nandsim(nsmtd)) != 0)
2304                 goto err_exit;
2305
2306         if ((retval = parse_badblocks(nand, nsmtd)) != 0)
2307                 goto err_exit;
2308
2309         if ((retval = nand_default_bbt(nsmtd)) != 0)
2310                 goto err_exit;
2311
2312         /* Register NAND partitions */
2313         if ((retval = add_mtd_partitions(nsmtd, &nand->partitions[0], nand->nbparts)) != 0)
2314                 goto err_exit;
2315
2316         return 0;
2317
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();
2326
2327         return retval;
2328 }
2329
2330 module_init(ns_init_module);
2331
2332 /*
2333  * Module clean-up function
2334  */
2335 static void __exit ns_cleanup_module(void)
2336 {
2337         struct nandsim *ns = (struct nandsim *)(((struct nand_chip *)nsmtd->priv)->priv);
2338         int i;
2339
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();
2346 }
2347
2348 module_exit(ns_cleanup_module);
2349
2350 MODULE_LICENSE ("GPL");
2351 MODULE_AUTHOR ("Artem B. Bityuckiy");
2352 MODULE_DESCRIPTION ("The NAND flash simulator");