Merge tag 'nand/for-4.14' of git://git.infradead.org/l2-mtd into mtd/next
[sfrench/cifs-2.6.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 <linux/math64.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/rawnand.h>
37 #include <linux/mtd/nand_bch.h>
38 #include <linux/mtd/partitions.h>
39 #include <linux/delay.h>
40 #include <linux/list.h>
41 #include <linux/random.h>
42 #include <linux/sched.h>
43 #include <linux/sched/mm.h>
44 #include <linux/fs.h>
45 #include <linux/pagemap.h>
46 #include <linux/seq_file.h>
47 #include <linux/debugfs.h>
48
49 /* Default simulator parameters values */
50 #if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE)  || \
51     !defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
52     !defined(CONFIG_NANDSIM_THIRD_ID_BYTE)  || \
53     !defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
54 #define CONFIG_NANDSIM_FIRST_ID_BYTE  0x98
55 #define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
56 #define CONFIG_NANDSIM_THIRD_ID_BYTE  0xFF /* No byte */
57 #define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
58 #endif
59
60 #ifndef CONFIG_NANDSIM_ACCESS_DELAY
61 #define CONFIG_NANDSIM_ACCESS_DELAY 25
62 #endif
63 #ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
64 #define CONFIG_NANDSIM_PROGRAMM_DELAY 200
65 #endif
66 #ifndef CONFIG_NANDSIM_ERASE_DELAY
67 #define CONFIG_NANDSIM_ERASE_DELAY 2
68 #endif
69 #ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
70 #define CONFIG_NANDSIM_OUTPUT_CYCLE 40
71 #endif
72 #ifndef CONFIG_NANDSIM_INPUT_CYCLE
73 #define CONFIG_NANDSIM_INPUT_CYCLE  50
74 #endif
75 #ifndef CONFIG_NANDSIM_BUS_WIDTH
76 #define CONFIG_NANDSIM_BUS_WIDTH  8
77 #endif
78 #ifndef CONFIG_NANDSIM_DO_DELAYS
79 #define CONFIG_NANDSIM_DO_DELAYS  0
80 #endif
81 #ifndef CONFIG_NANDSIM_LOG
82 #define CONFIG_NANDSIM_LOG        0
83 #endif
84 #ifndef CONFIG_NANDSIM_DBG
85 #define CONFIG_NANDSIM_DBG        0
86 #endif
87 #ifndef CONFIG_NANDSIM_MAX_PARTS
88 #define CONFIG_NANDSIM_MAX_PARTS  32
89 #endif
90
91 static uint access_delay   = CONFIG_NANDSIM_ACCESS_DELAY;
92 static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
93 static uint erase_delay    = CONFIG_NANDSIM_ERASE_DELAY;
94 static uint output_cycle   = CONFIG_NANDSIM_OUTPUT_CYCLE;
95 static uint input_cycle    = CONFIG_NANDSIM_INPUT_CYCLE;
96 static uint bus_width      = CONFIG_NANDSIM_BUS_WIDTH;
97 static uint do_delays      = CONFIG_NANDSIM_DO_DELAYS;
98 static uint log            = CONFIG_NANDSIM_LOG;
99 static uint dbg            = CONFIG_NANDSIM_DBG;
100 static unsigned long parts[CONFIG_NANDSIM_MAX_PARTS];
101 static unsigned int parts_num;
102 static char *badblocks = NULL;
103 static char *weakblocks = NULL;
104 static char *weakpages = NULL;
105 static unsigned int bitflips = 0;
106 static char *gravepages = NULL;
107 static unsigned int overridesize = 0;
108 static char *cache_file = NULL;
109 static unsigned int bbt;
110 static unsigned int bch;
111 static u_char id_bytes[8] = {
112         [0] = CONFIG_NANDSIM_FIRST_ID_BYTE,
113         [1] = CONFIG_NANDSIM_SECOND_ID_BYTE,
114         [2] = CONFIG_NANDSIM_THIRD_ID_BYTE,
115         [3] = CONFIG_NANDSIM_FOURTH_ID_BYTE,
116         [4 ... 7] = 0xFF,
117 };
118
119 module_param_array(id_bytes, byte, NULL, 0400);
120 module_param_named(first_id_byte, id_bytes[0], byte, 0400);
121 module_param_named(second_id_byte, id_bytes[1], byte, 0400);
122 module_param_named(third_id_byte, id_bytes[2], byte, 0400);
123 module_param_named(fourth_id_byte, id_bytes[3], byte, 0400);
124 module_param(access_delay,   uint, 0400);
125 module_param(programm_delay, uint, 0400);
126 module_param(erase_delay,    uint, 0400);
127 module_param(output_cycle,   uint, 0400);
128 module_param(input_cycle,    uint, 0400);
129 module_param(bus_width,      uint, 0400);
130 module_param(do_delays,      uint, 0400);
131 module_param(log,            uint, 0400);
132 module_param(dbg,            uint, 0400);
133 module_param_array(parts, ulong, &parts_num, 0400);
134 module_param(badblocks,      charp, 0400);
135 module_param(weakblocks,     charp, 0400);
136 module_param(weakpages,      charp, 0400);
137 module_param(bitflips,       uint, 0400);
138 module_param(gravepages,     charp, 0400);
139 module_param(overridesize,   uint, 0400);
140 module_param(cache_file,     charp, 0400);
141 module_param(bbt,            uint, 0400);
142 module_param(bch,            uint, 0400);
143
144 MODULE_PARM_DESC(id_bytes,       "The ID bytes returned by NAND Flash 'read ID' command");
145 MODULE_PARM_DESC(first_id_byte,  "The first byte returned by NAND Flash 'read ID' command (manufacturer ID) (obsolete)");
146 MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID) (obsolete)");
147 MODULE_PARM_DESC(third_id_byte,  "The third byte returned by NAND Flash 'read ID' command (obsolete)");
148 MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command (obsolete)");
149 MODULE_PARM_DESC(access_delay,   "Initial page access delay (microseconds)");
150 MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
151 MODULE_PARM_DESC(erase_delay,    "Sector erase delay (milliseconds)");
152 MODULE_PARM_DESC(output_cycle,   "Word output (from flash) time (nanoseconds)");
153 MODULE_PARM_DESC(input_cycle,    "Word input (to flash) time (nanoseconds)");
154 MODULE_PARM_DESC(bus_width,      "Chip's bus width (8- or 16-bit)");
155 MODULE_PARM_DESC(do_delays,      "Simulate NAND delays using busy-waits if not zero");
156 MODULE_PARM_DESC(log,            "Perform logging if not zero");
157 MODULE_PARM_DESC(dbg,            "Output debug information if not zero");
158 MODULE_PARM_DESC(parts,          "Partition sizes (in erase blocks) separated by commas");
159 /* Page and erase block positions for the following parameters are independent of any partitions */
160 MODULE_PARM_DESC(badblocks,      "Erase blocks that are initially marked bad, separated by commas");
161 MODULE_PARM_DESC(weakblocks,     "Weak erase blocks [: remaining erase cycles (defaults to 3)]"
162                                  " separated by commas e.g. 113:2 means eb 113"
163                                  " can be erased only twice before failing");
164 MODULE_PARM_DESC(weakpages,      "Weak pages [: maximum writes (defaults to 3)]"
165                                  " separated by commas e.g. 1401:2 means page 1401"
166                                  " can be written only twice before failing");
167 MODULE_PARM_DESC(bitflips,       "Maximum number of random bit flips per page (zero by default)");
168 MODULE_PARM_DESC(gravepages,     "Pages that lose data [: maximum reads (defaults to 3)]"
169                                  " separated by commas e.g. 1401:2 means page 1401"
170                                  " can be read only twice before failing");
171 MODULE_PARM_DESC(overridesize,   "Specifies the NAND Flash size overriding the ID bytes. "
172                                  "The size is specified in erase blocks and as the exponent of a power of two"
173                                  " e.g. 5 means a size of 32 erase blocks");
174 MODULE_PARM_DESC(cache_file,     "File to use to cache nand pages instead of memory");
175 MODULE_PARM_DESC(bbt,            "0 OOB, 1 BBT with marker in OOB, 2 BBT with marker in data area");
176 MODULE_PARM_DESC(bch,            "Enable BCH ecc and set how many bits should "
177                                  "be correctable in 512-byte blocks");
178
179 /* The largest possible page size */
180 #define NS_LARGEST_PAGE_SIZE    4096
181
182 /* The prefix for simulator output */
183 #define NS_OUTPUT_PREFIX "[nandsim]"
184
185 /* Simulator's output macros (logging, debugging, warning, error) */
186 #define NS_LOG(args...) \
187         do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
188 #define NS_DBG(args...) \
189         do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
190 #define NS_WARN(args...) \
191         do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warning: " args); } while(0)
192 #define NS_ERR(args...) \
193         do { printk(KERN_ERR NS_OUTPUT_PREFIX " error: " args); } while(0)
194 #define NS_INFO(args...) \
195         do { printk(KERN_INFO NS_OUTPUT_PREFIX " " args); } while(0)
196
197 /* Busy-wait delay macros (microseconds, milliseconds) */
198 #define NS_UDELAY(us) \
199         do { if (do_delays) udelay(us); } while(0)
200 #define NS_MDELAY(us) \
201         do { if (do_delays) mdelay(us); } while(0)
202
203 /* Is the nandsim structure initialized ? */
204 #define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
205
206 /* Good operation completion status */
207 #define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
208
209 /* Operation failed completion status */
210 #define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
211
212 /* Calculate the page offset in flash RAM image by (row, column) address */
213 #define NS_RAW_OFFSET(ns) \
214         (((ns)->regs.row * (ns)->geom.pgszoob) + (ns)->regs.column)
215
216 /* Calculate the OOB offset in flash RAM image by (row, column) address */
217 #define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)
218
219 /* After a command is input, the simulator goes to one of the following states */
220 #define STATE_CMD_READ0        0x00000001 /* read data from the beginning of page */
221 #define STATE_CMD_READ1        0x00000002 /* read data from the second half of page */
222 #define STATE_CMD_READSTART    0x00000003 /* read data second command (large page devices) */
223 #define STATE_CMD_PAGEPROG     0x00000004 /* start page program */
224 #define STATE_CMD_READOOB      0x00000005 /* read OOB area */
225 #define STATE_CMD_ERASE1       0x00000006 /* sector erase first command */
226 #define STATE_CMD_STATUS       0x00000007 /* read status */
227 #define STATE_CMD_SEQIN        0x00000009 /* sequential data input */
228 #define STATE_CMD_READID       0x0000000A /* read ID */
229 #define STATE_CMD_ERASE2       0x0000000B /* sector erase second command */
230 #define STATE_CMD_RESET        0x0000000C /* reset */
231 #define STATE_CMD_RNDOUT       0x0000000D /* random output command */
232 #define STATE_CMD_RNDOUTSTART  0x0000000E /* random output start command */
233 #define STATE_CMD_MASK         0x0000000F /* command states mask */
234
235 /* After an address is input, the simulator goes to one of these states */
236 #define STATE_ADDR_PAGE        0x00000010 /* full (row, column) address is accepted */
237 #define STATE_ADDR_SEC         0x00000020 /* sector address was accepted */
238 #define STATE_ADDR_COLUMN      0x00000030 /* column address was accepted */
239 #define STATE_ADDR_ZERO        0x00000040 /* one byte zero address was accepted */
240 #define STATE_ADDR_MASK        0x00000070 /* address states mask */
241
242 /* During data input/output the simulator is in these states */
243 #define STATE_DATAIN           0x00000100 /* waiting for data input */
244 #define STATE_DATAIN_MASK      0x00000100 /* data input states mask */
245
246 #define STATE_DATAOUT          0x00001000 /* waiting for page data output */
247 #define STATE_DATAOUT_ID       0x00002000 /* waiting for ID bytes output */
248 #define STATE_DATAOUT_STATUS   0x00003000 /* waiting for status output */
249 #define STATE_DATAOUT_MASK     0x00007000 /* data output states mask */
250
251 /* Previous operation is done, ready to accept new requests */
252 #define STATE_READY            0x00000000
253
254 /* This state is used to mark that the next state isn't known yet */
255 #define STATE_UNKNOWN          0x10000000
256
257 /* Simulator's actions bit masks */
258 #define ACTION_CPY       0x00100000 /* copy page/OOB to the internal buffer */
259 #define ACTION_PRGPAGE   0x00200000 /* program the internal buffer to flash */
260 #define ACTION_SECERASE  0x00300000 /* erase sector */
261 #define ACTION_ZEROOFF   0x00400000 /* don't add any offset to address */
262 #define ACTION_HALFOFF   0x00500000 /* add to address half of page */
263 #define ACTION_OOBOFF    0x00600000 /* add to address OOB offset */
264 #define ACTION_MASK      0x00700000 /* action mask */
265
266 #define NS_OPER_NUM      13 /* Number of operations supported by the simulator */
267 #define NS_OPER_STATES   6  /* Maximum number of states in operation */
268
269 #define OPT_ANY          0xFFFFFFFF /* any chip supports this operation */
270 #define OPT_PAGE512      0x00000002 /* 512-byte  page chips */
271 #define OPT_PAGE2048     0x00000008 /* 2048-byte page chips */
272 #define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
273 #define OPT_PAGE4096     0x00000080 /* 4096-byte page chips */
274 #define OPT_LARGEPAGE    (OPT_PAGE2048 | OPT_PAGE4096) /* 2048 & 4096-byte page chips */
275 #define OPT_SMALLPAGE    (OPT_PAGE512) /* 512-byte page chips */
276
277 /* Remove action bits from state */
278 #define NS_STATE(x) ((x) & ~ACTION_MASK)
279
280 /*
281  * Maximum previous states which need to be saved. Currently saving is
282  * only needed for page program operation with preceded read command
283  * (which is only valid for 512-byte pages).
284  */
285 #define NS_MAX_PREVSTATES 1
286
287 /* Maximum page cache pages needed to read or write a NAND page to the cache_file */
288 #define NS_MAX_HELD_PAGES 16
289
290 /*
291  * A union to represent flash memory contents and flash buffer.
292  */
293 union ns_mem {
294         u_char *byte;    /* for byte access */
295         uint16_t *word;  /* for 16-bit word access */
296 };
297
298 /*
299  * The structure which describes all the internal simulator data.
300  */
301 struct nandsim {
302         struct mtd_partition partitions[CONFIG_NANDSIM_MAX_PARTS];
303         unsigned int nbparts;
304
305         uint busw;              /* flash chip bus width (8 or 16) */
306         u_char ids[8];          /* chip's ID bytes */
307         uint32_t options;       /* chip's characteristic bits */
308         uint32_t state;         /* current chip state */
309         uint32_t nxstate;       /* next expected state */
310
311         uint32_t *op;           /* current operation, NULL operations isn't known yet  */
312         uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
313         uint16_t npstates;      /* number of previous states saved */
314         uint16_t stateidx;      /* current state index */
315
316         /* The simulated NAND flash pages array */
317         union ns_mem *pages;
318
319         /* Slab allocator for nand pages */
320         struct kmem_cache *nand_pages_slab;
321
322         /* Internal buffer of page + OOB size bytes */
323         union ns_mem buf;
324
325         /* NAND flash "geometry" */
326         struct {
327                 uint64_t totsz;     /* total flash size, bytes */
328                 uint32_t secsz;     /* flash sector (erase block) size, bytes */
329                 uint pgsz;          /* NAND flash page size, bytes */
330                 uint oobsz;         /* page OOB area size, bytes */
331                 uint64_t totszoob;  /* total flash size including OOB, bytes */
332                 uint pgszoob;       /* page size including OOB , bytes*/
333                 uint secszoob;      /* sector size including OOB, bytes */
334                 uint pgnum;         /* total number of pages */
335                 uint pgsec;         /* number of pages per sector */
336                 uint secshift;      /* bits number in sector size */
337                 uint pgshift;       /* bits number in page size */
338                 uint pgaddrbytes;   /* bytes per page address */
339                 uint secaddrbytes;  /* bytes per sector address */
340                 uint idbytes;       /* the number ID bytes that this chip outputs */
341         } geom;
342
343         /* NAND flash internal registers */
344         struct {
345                 unsigned command; /* the command register */
346                 u_char   status;  /* the status register */
347                 uint     row;     /* the page number */
348                 uint     column;  /* the offset within page */
349                 uint     count;   /* internal counter */
350                 uint     num;     /* number of bytes which must be processed */
351                 uint     off;     /* fixed page offset */
352         } regs;
353
354         /* NAND flash lines state */
355         struct {
356                 int ce;  /* chip Enable */
357                 int cle; /* command Latch Enable */
358                 int ale; /* address Latch Enable */
359                 int wp;  /* write Protect */
360         } lines;
361
362         /* Fields needed when using a cache file */
363         struct file *cfile; /* Open file */
364         unsigned long *pages_written; /* Which pages have been written */
365         void *file_buf;
366         struct page *held_pages[NS_MAX_HELD_PAGES];
367         int held_cnt;
368 };
369
370 /*
371  * Operations array. To perform any operation the simulator must pass
372  * through the correspondent states chain.
373  */
374 static struct nandsim_operations {
375         uint32_t reqopts;  /* options which are required to perform the operation */
376         uint32_t states[NS_OPER_STATES]; /* operation's states */
377 } ops[NS_OPER_NUM] = {
378         /* Read page + OOB from the beginning */
379         {OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
380                         STATE_DATAOUT, STATE_READY}},
381         /* Read page + OOB from the second half */
382         {OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
383                         STATE_DATAOUT, STATE_READY}},
384         /* Read OOB */
385         {OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
386                         STATE_DATAOUT, STATE_READY}},
387         /* Program page starting from the beginning */
388         {OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
389                         STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
390         /* Program page starting from the beginning */
391         {OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
392                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
393         /* Program page starting from the second half */
394         {OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
395                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
396         /* Program OOB */
397         {OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
398                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
399         /* Erase sector */
400         {OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
401         /* Read status */
402         {OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
403         /* Read ID */
404         {OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
405         /* Large page devices read page */
406         {OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
407                                STATE_DATAOUT, STATE_READY}},
408         /* Large page devices random page read */
409         {OPT_LARGEPAGE, {STATE_CMD_RNDOUT, STATE_ADDR_COLUMN, STATE_CMD_RNDOUTSTART | ACTION_CPY,
410                                STATE_DATAOUT, STATE_READY}},
411 };
412
413 struct weak_block {
414         struct list_head list;
415         unsigned int erase_block_no;
416         unsigned int max_erases;
417         unsigned int erases_done;
418 };
419
420 static LIST_HEAD(weak_blocks);
421
422 struct weak_page {
423         struct list_head list;
424         unsigned int page_no;
425         unsigned int max_writes;
426         unsigned int writes_done;
427 };
428
429 static LIST_HEAD(weak_pages);
430
431 struct grave_page {
432         struct list_head list;
433         unsigned int page_no;
434         unsigned int max_reads;
435         unsigned int reads_done;
436 };
437
438 static LIST_HEAD(grave_pages);
439
440 static unsigned long *erase_block_wear = NULL;
441 static unsigned int wear_eb_count = 0;
442 static unsigned long total_wear = 0;
443
444 /* MTD structure for NAND controller */
445 static struct mtd_info *nsmtd;
446
447 static int nandsim_debugfs_show(struct seq_file *m, void *private)
448 {
449         unsigned long wmin = -1, wmax = 0, avg;
450         unsigned long deciles[10], decile_max[10], tot = 0;
451         unsigned int i;
452
453         /* Calc wear stats */
454         for (i = 0; i < wear_eb_count; ++i) {
455                 unsigned long wear = erase_block_wear[i];
456                 if (wear < wmin)
457                         wmin = wear;
458                 if (wear > wmax)
459                         wmax = wear;
460                 tot += wear;
461         }
462
463         for (i = 0; i < 9; ++i) {
464                 deciles[i] = 0;
465                 decile_max[i] = (wmax * (i + 1) + 5) / 10;
466         }
467         deciles[9] = 0;
468         decile_max[9] = wmax;
469         for (i = 0; i < wear_eb_count; ++i) {
470                 int d;
471                 unsigned long wear = erase_block_wear[i];
472                 for (d = 0; d < 10; ++d)
473                         if (wear <= decile_max[d]) {
474                                 deciles[d] += 1;
475                                 break;
476                         }
477         }
478         avg = tot / wear_eb_count;
479
480         /* Output wear report */
481         seq_printf(m, "Total numbers of erases:  %lu\n", tot);
482         seq_printf(m, "Number of erase blocks:   %u\n", wear_eb_count);
483         seq_printf(m, "Average number of erases: %lu\n", avg);
484         seq_printf(m, "Maximum number of erases: %lu\n", wmax);
485         seq_printf(m, "Minimum number of erases: %lu\n", wmin);
486         for (i = 0; i < 10; ++i) {
487                 unsigned long from = (i ? decile_max[i - 1] + 1 : 0);
488                 if (from > decile_max[i])
489                         continue;
490                 seq_printf(m, "Number of ebs with erase counts from %lu to %lu : %lu\n",
491                         from,
492                         decile_max[i],
493                         deciles[i]);
494         }
495
496         return 0;
497 }
498
499 static int nandsim_debugfs_open(struct inode *inode, struct file *file)
500 {
501         return single_open(file, nandsim_debugfs_show, inode->i_private);
502 }
503
504 static const struct file_operations dfs_fops = {
505         .open           = nandsim_debugfs_open,
506         .read           = seq_read,
507         .llseek         = seq_lseek,
508         .release        = single_release,
509 };
510
511 /**
512  * nandsim_debugfs_create - initialize debugfs
513  * @dev: nandsim device description object
514  *
515  * This function creates all debugfs files for UBI device @ubi. Returns zero in
516  * case of success and a negative error code in case of failure.
517  */
518 static int nandsim_debugfs_create(struct nandsim *dev)
519 {
520         struct dentry *root = nsmtd->dbg.dfs_dir;
521         struct dentry *dent;
522
523         if (!IS_ENABLED(CONFIG_DEBUG_FS))
524                 return 0;
525
526         if (IS_ERR_OR_NULL(root))
527                 return -1;
528
529         dent = debugfs_create_file("nandsim_wear_report", S_IRUSR,
530                                    root, dev, &dfs_fops);
531         if (IS_ERR_OR_NULL(dent)) {
532                 NS_ERR("cannot create \"nandsim_wear_report\" debugfs entry\n");
533                 return -1;
534         }
535
536         return 0;
537 }
538
539 /*
540  * Allocate array of page pointers, create slab allocation for an array
541  * and initialize the array by NULL pointers.
542  *
543  * RETURNS: 0 if success, -ENOMEM if memory alloc fails.
544  */
545 static int __init alloc_device(struct nandsim *ns)
546 {
547         struct file *cfile;
548         int i, err;
549
550         if (cache_file) {
551                 cfile = filp_open(cache_file, O_CREAT | O_RDWR | O_LARGEFILE, 0600);
552                 if (IS_ERR(cfile))
553                         return PTR_ERR(cfile);
554                 if (!(cfile->f_mode & FMODE_CAN_READ)) {
555                         NS_ERR("alloc_device: cache file not readable\n");
556                         err = -EINVAL;
557                         goto err_close;
558                 }
559                 if (!(cfile->f_mode & FMODE_CAN_WRITE)) {
560                         NS_ERR("alloc_device: cache file not writeable\n");
561                         err = -EINVAL;
562                         goto err_close;
563                 }
564                 ns->pages_written = vzalloc(BITS_TO_LONGS(ns->geom.pgnum) *
565                                             sizeof(unsigned long));
566                 if (!ns->pages_written) {
567                         NS_ERR("alloc_device: unable to allocate pages written array\n");
568                         err = -ENOMEM;
569                         goto err_close;
570                 }
571                 ns->file_buf = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
572                 if (!ns->file_buf) {
573                         NS_ERR("alloc_device: unable to allocate file buf\n");
574                         err = -ENOMEM;
575                         goto err_free;
576                 }
577                 ns->cfile = cfile;
578                 return 0;
579         }
580
581         ns->pages = vmalloc(ns->geom.pgnum * sizeof(union ns_mem));
582         if (!ns->pages) {
583                 NS_ERR("alloc_device: unable to allocate page array\n");
584                 return -ENOMEM;
585         }
586         for (i = 0; i < ns->geom.pgnum; i++) {
587                 ns->pages[i].byte = NULL;
588         }
589         ns->nand_pages_slab = kmem_cache_create("nandsim",
590                                                 ns->geom.pgszoob, 0, 0, NULL);
591         if (!ns->nand_pages_slab) {
592                 NS_ERR("cache_create: unable to create kmem_cache\n");
593                 return -ENOMEM;
594         }
595
596         return 0;
597
598 err_free:
599         vfree(ns->pages_written);
600 err_close:
601         filp_close(cfile, NULL);
602         return err;
603 }
604
605 /*
606  * Free any allocated pages, and free the array of page pointers.
607  */
608 static void free_device(struct nandsim *ns)
609 {
610         int i;
611
612         if (ns->cfile) {
613                 kfree(ns->file_buf);
614                 vfree(ns->pages_written);
615                 filp_close(ns->cfile, NULL);
616                 return;
617         }
618
619         if (ns->pages) {
620                 for (i = 0; i < ns->geom.pgnum; i++) {
621                         if (ns->pages[i].byte)
622                                 kmem_cache_free(ns->nand_pages_slab,
623                                                 ns->pages[i].byte);
624                 }
625                 kmem_cache_destroy(ns->nand_pages_slab);
626                 vfree(ns->pages);
627         }
628 }
629
630 static char __init *get_partition_name(int i)
631 {
632         return kasprintf(GFP_KERNEL, "NAND simulator partition %d", i);
633 }
634
635 /*
636  * Initialize the nandsim structure.
637  *
638  * RETURNS: 0 if success, -ERRNO if failure.
639  */
640 static int __init init_nandsim(struct mtd_info *mtd)
641 {
642         struct nand_chip *chip = mtd_to_nand(mtd);
643         struct nandsim   *ns   = nand_get_controller_data(chip);
644         int i, ret = 0;
645         uint64_t remains;
646         uint64_t next_offset;
647
648         if (NS_IS_INITIALIZED(ns)) {
649                 NS_ERR("init_nandsim: nandsim is already initialized\n");
650                 return -EIO;
651         }
652
653         /* Force mtd to not do delays */
654         chip->chip_delay = 0;
655
656         /* Initialize the NAND flash parameters */
657         ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
658         ns->geom.totsz    = mtd->size;
659         ns->geom.pgsz     = mtd->writesize;
660         ns->geom.oobsz    = mtd->oobsize;
661         ns->geom.secsz    = mtd->erasesize;
662         ns->geom.pgszoob  = ns->geom.pgsz + ns->geom.oobsz;
663         ns->geom.pgnum    = div_u64(ns->geom.totsz, ns->geom.pgsz);
664         ns->geom.totszoob = ns->geom.totsz + (uint64_t)ns->geom.pgnum * ns->geom.oobsz;
665         ns->geom.secshift = ffs(ns->geom.secsz) - 1;
666         ns->geom.pgshift  = chip->page_shift;
667         ns->geom.pgsec    = ns->geom.secsz / ns->geom.pgsz;
668         ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
669         ns->options = 0;
670
671         if (ns->geom.pgsz == 512) {
672                 ns->options |= OPT_PAGE512;
673                 if (ns->busw == 8)
674                         ns->options |= OPT_PAGE512_8BIT;
675         } else if (ns->geom.pgsz == 2048) {
676                 ns->options |= OPT_PAGE2048;
677         } else if (ns->geom.pgsz == 4096) {
678                 ns->options |= OPT_PAGE4096;
679         } else {
680                 NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
681                 return -EIO;
682         }
683
684         if (ns->options & OPT_SMALLPAGE) {
685                 if (ns->geom.totsz <= (32 << 20)) {
686                         ns->geom.pgaddrbytes  = 3;
687                         ns->geom.secaddrbytes = 2;
688                 } else {
689                         ns->geom.pgaddrbytes  = 4;
690                         ns->geom.secaddrbytes = 3;
691                 }
692         } else {
693                 if (ns->geom.totsz <= (128 << 20)) {
694                         ns->geom.pgaddrbytes  = 4;
695                         ns->geom.secaddrbytes = 2;
696                 } else {
697                         ns->geom.pgaddrbytes  = 5;
698                         ns->geom.secaddrbytes = 3;
699                 }
700         }
701
702         /* Fill the partition_info structure */
703         if (parts_num > ARRAY_SIZE(ns->partitions)) {
704                 NS_ERR("too many partitions.\n");
705                 return -EINVAL;
706         }
707         remains = ns->geom.totsz;
708         next_offset = 0;
709         for (i = 0; i < parts_num; ++i) {
710                 uint64_t part_sz = (uint64_t)parts[i] * ns->geom.secsz;
711
712                 if (!part_sz || part_sz > remains) {
713                         NS_ERR("bad partition size.\n");
714                         return -EINVAL;
715                 }
716                 ns->partitions[i].name   = get_partition_name(i);
717                 if (!ns->partitions[i].name) {
718                         NS_ERR("unable to allocate memory.\n");
719                         return -ENOMEM;
720                 }
721                 ns->partitions[i].offset = next_offset;
722                 ns->partitions[i].size   = part_sz;
723                 next_offset += ns->partitions[i].size;
724                 remains -= ns->partitions[i].size;
725         }
726         ns->nbparts = parts_num;
727         if (remains) {
728                 if (parts_num + 1 > ARRAY_SIZE(ns->partitions)) {
729                         NS_ERR("too many partitions.\n");
730                         return -EINVAL;
731                 }
732                 ns->partitions[i].name   = get_partition_name(i);
733                 if (!ns->partitions[i].name) {
734                         NS_ERR("unable to allocate memory.\n");
735                         return -ENOMEM;
736                 }
737                 ns->partitions[i].offset = next_offset;
738                 ns->partitions[i].size   = remains;
739                 ns->nbparts += 1;
740         }
741
742         if (ns->busw == 16)
743                 NS_WARN("16-bit flashes support wasn't tested\n");
744
745         printk("flash size: %llu MiB\n",
746                         (unsigned long long)ns->geom.totsz >> 20);
747         printk("page size: %u bytes\n",         ns->geom.pgsz);
748         printk("OOB area size: %u bytes\n",     ns->geom.oobsz);
749         printk("sector size: %u KiB\n",         ns->geom.secsz >> 10);
750         printk("pages number: %u\n",            ns->geom.pgnum);
751         printk("pages per sector: %u\n",        ns->geom.pgsec);
752         printk("bus width: %u\n",               ns->busw);
753         printk("bits in sector size: %u\n",     ns->geom.secshift);
754         printk("bits in page size: %u\n",       ns->geom.pgshift);
755         printk("bits in OOB size: %u\n",        ffs(ns->geom.oobsz) - 1);
756         printk("flash size with OOB: %llu KiB\n",
757                         (unsigned long long)ns->geom.totszoob >> 10);
758         printk("page address bytes: %u\n",      ns->geom.pgaddrbytes);
759         printk("sector address bytes: %u\n",    ns->geom.secaddrbytes);
760         printk("options: %#x\n",                ns->options);
761
762         if ((ret = alloc_device(ns)) != 0)
763                 return ret;
764
765         /* Allocate / initialize the internal buffer */
766         ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
767         if (!ns->buf.byte) {
768                 NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
769                         ns->geom.pgszoob);
770                 return -ENOMEM;
771         }
772         memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
773
774         return 0;
775 }
776
777 /*
778  * Free the nandsim structure.
779  */
780 static void free_nandsim(struct nandsim *ns)
781 {
782         kfree(ns->buf.byte);
783         free_device(ns);
784
785         return;
786 }
787
788 static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
789 {
790         char *w;
791         int zero_ok;
792         unsigned int erase_block_no;
793         loff_t offset;
794
795         if (!badblocks)
796                 return 0;
797         w = badblocks;
798         do {
799                 zero_ok = (*w == '0' ? 1 : 0);
800                 erase_block_no = simple_strtoul(w, &w, 0);
801                 if (!zero_ok && !erase_block_no) {
802                         NS_ERR("invalid badblocks.\n");
803                         return -EINVAL;
804                 }
805                 offset = (loff_t)erase_block_no * ns->geom.secsz;
806                 if (mtd_block_markbad(mtd, offset)) {
807                         NS_ERR("invalid badblocks.\n");
808                         return -EINVAL;
809                 }
810                 if (*w == ',')
811                         w += 1;
812         } while (*w);
813         return 0;
814 }
815
816 static int parse_weakblocks(void)
817 {
818         char *w;
819         int zero_ok;
820         unsigned int erase_block_no;
821         unsigned int max_erases;
822         struct weak_block *wb;
823
824         if (!weakblocks)
825                 return 0;
826         w = weakblocks;
827         do {
828                 zero_ok = (*w == '0' ? 1 : 0);
829                 erase_block_no = simple_strtoul(w, &w, 0);
830                 if (!zero_ok && !erase_block_no) {
831                         NS_ERR("invalid weakblocks.\n");
832                         return -EINVAL;
833                 }
834                 max_erases = 3;
835                 if (*w == ':') {
836                         w += 1;
837                         max_erases = simple_strtoul(w, &w, 0);
838                 }
839                 if (*w == ',')
840                         w += 1;
841                 wb = kzalloc(sizeof(*wb), GFP_KERNEL);
842                 if (!wb) {
843                         NS_ERR("unable to allocate memory.\n");
844                         return -ENOMEM;
845                 }
846                 wb->erase_block_no = erase_block_no;
847                 wb->max_erases = max_erases;
848                 list_add(&wb->list, &weak_blocks);
849         } while (*w);
850         return 0;
851 }
852
853 static int erase_error(unsigned int erase_block_no)
854 {
855         struct weak_block *wb;
856
857         list_for_each_entry(wb, &weak_blocks, list)
858                 if (wb->erase_block_no == erase_block_no) {
859                         if (wb->erases_done >= wb->max_erases)
860                                 return 1;
861                         wb->erases_done += 1;
862                         return 0;
863                 }
864         return 0;
865 }
866
867 static int parse_weakpages(void)
868 {
869         char *w;
870         int zero_ok;
871         unsigned int page_no;
872         unsigned int max_writes;
873         struct weak_page *wp;
874
875         if (!weakpages)
876                 return 0;
877         w = weakpages;
878         do {
879                 zero_ok = (*w == '0' ? 1 : 0);
880                 page_no = simple_strtoul(w, &w, 0);
881                 if (!zero_ok && !page_no) {
882                         NS_ERR("invalid weakpages.\n");
883                         return -EINVAL;
884                 }
885                 max_writes = 3;
886                 if (*w == ':') {
887                         w += 1;
888                         max_writes = simple_strtoul(w, &w, 0);
889                 }
890                 if (*w == ',')
891                         w += 1;
892                 wp = kzalloc(sizeof(*wp), GFP_KERNEL);
893                 if (!wp) {
894                         NS_ERR("unable to allocate memory.\n");
895                         return -ENOMEM;
896                 }
897                 wp->page_no = page_no;
898                 wp->max_writes = max_writes;
899                 list_add(&wp->list, &weak_pages);
900         } while (*w);
901         return 0;
902 }
903
904 static int write_error(unsigned int page_no)
905 {
906         struct weak_page *wp;
907
908         list_for_each_entry(wp, &weak_pages, list)
909                 if (wp->page_no == page_no) {
910                         if (wp->writes_done >= wp->max_writes)
911                                 return 1;
912                         wp->writes_done += 1;
913                         return 0;
914                 }
915         return 0;
916 }
917
918 static int parse_gravepages(void)
919 {
920         char *g;
921         int zero_ok;
922         unsigned int page_no;
923         unsigned int max_reads;
924         struct grave_page *gp;
925
926         if (!gravepages)
927                 return 0;
928         g = gravepages;
929         do {
930                 zero_ok = (*g == '0' ? 1 : 0);
931                 page_no = simple_strtoul(g, &g, 0);
932                 if (!zero_ok && !page_no) {
933                         NS_ERR("invalid gravepagess.\n");
934                         return -EINVAL;
935                 }
936                 max_reads = 3;
937                 if (*g == ':') {
938                         g += 1;
939                         max_reads = simple_strtoul(g, &g, 0);
940                 }
941                 if (*g == ',')
942                         g += 1;
943                 gp = kzalloc(sizeof(*gp), GFP_KERNEL);
944                 if (!gp) {
945                         NS_ERR("unable to allocate memory.\n");
946                         return -ENOMEM;
947                 }
948                 gp->page_no = page_no;
949                 gp->max_reads = max_reads;
950                 list_add(&gp->list, &grave_pages);
951         } while (*g);
952         return 0;
953 }
954
955 static int read_error(unsigned int page_no)
956 {
957         struct grave_page *gp;
958
959         list_for_each_entry(gp, &grave_pages, list)
960                 if (gp->page_no == page_no) {
961                         if (gp->reads_done >= gp->max_reads)
962                                 return 1;
963                         gp->reads_done += 1;
964                         return 0;
965                 }
966         return 0;
967 }
968
969 static void free_lists(void)
970 {
971         struct list_head *pos, *n;
972         list_for_each_safe(pos, n, &weak_blocks) {
973                 list_del(pos);
974                 kfree(list_entry(pos, struct weak_block, list));
975         }
976         list_for_each_safe(pos, n, &weak_pages) {
977                 list_del(pos);
978                 kfree(list_entry(pos, struct weak_page, list));
979         }
980         list_for_each_safe(pos, n, &grave_pages) {
981                 list_del(pos);
982                 kfree(list_entry(pos, struct grave_page, list));
983         }
984         kfree(erase_block_wear);
985 }
986
987 static int setup_wear_reporting(struct mtd_info *mtd)
988 {
989         size_t mem;
990
991         wear_eb_count = div_u64(mtd->size, mtd->erasesize);
992         mem = wear_eb_count * sizeof(unsigned long);
993         if (mem / sizeof(unsigned long) != wear_eb_count) {
994                 NS_ERR("Too many erase blocks for wear reporting\n");
995                 return -ENOMEM;
996         }
997         erase_block_wear = kzalloc(mem, GFP_KERNEL);
998         if (!erase_block_wear) {
999                 NS_ERR("Too many erase blocks for wear reporting\n");
1000                 return -ENOMEM;
1001         }
1002         return 0;
1003 }
1004
1005 static void update_wear(unsigned int erase_block_no)
1006 {
1007         if (!erase_block_wear)
1008                 return;
1009         total_wear += 1;
1010         /*
1011          * TODO: Notify this through a debugfs entry,
1012          * instead of showing an error message.
1013          */
1014         if (total_wear == 0)
1015                 NS_ERR("Erase counter total overflow\n");
1016         erase_block_wear[erase_block_no] += 1;
1017         if (erase_block_wear[erase_block_no] == 0)
1018                 NS_ERR("Erase counter overflow for erase block %u\n", erase_block_no);
1019 }
1020
1021 /*
1022  * Returns the string representation of 'state' state.
1023  */
1024 static char *get_state_name(uint32_t state)
1025 {
1026         switch (NS_STATE(state)) {
1027                 case STATE_CMD_READ0:
1028                         return "STATE_CMD_READ0";
1029                 case STATE_CMD_READ1:
1030                         return "STATE_CMD_READ1";
1031                 case STATE_CMD_PAGEPROG:
1032                         return "STATE_CMD_PAGEPROG";
1033                 case STATE_CMD_READOOB:
1034                         return "STATE_CMD_READOOB";
1035                 case STATE_CMD_READSTART:
1036                         return "STATE_CMD_READSTART";
1037                 case STATE_CMD_ERASE1:
1038                         return "STATE_CMD_ERASE1";
1039                 case STATE_CMD_STATUS:
1040                         return "STATE_CMD_STATUS";
1041                 case STATE_CMD_SEQIN:
1042                         return "STATE_CMD_SEQIN";
1043                 case STATE_CMD_READID:
1044                         return "STATE_CMD_READID";
1045                 case STATE_CMD_ERASE2:
1046                         return "STATE_CMD_ERASE2";
1047                 case STATE_CMD_RESET:
1048                         return "STATE_CMD_RESET";
1049                 case STATE_CMD_RNDOUT:
1050                         return "STATE_CMD_RNDOUT";
1051                 case STATE_CMD_RNDOUTSTART:
1052                         return "STATE_CMD_RNDOUTSTART";
1053                 case STATE_ADDR_PAGE:
1054                         return "STATE_ADDR_PAGE";
1055                 case STATE_ADDR_SEC:
1056                         return "STATE_ADDR_SEC";
1057                 case STATE_ADDR_ZERO:
1058                         return "STATE_ADDR_ZERO";
1059                 case STATE_ADDR_COLUMN:
1060                         return "STATE_ADDR_COLUMN";
1061                 case STATE_DATAIN:
1062                         return "STATE_DATAIN";
1063                 case STATE_DATAOUT:
1064                         return "STATE_DATAOUT";
1065                 case STATE_DATAOUT_ID:
1066                         return "STATE_DATAOUT_ID";
1067                 case STATE_DATAOUT_STATUS:
1068                         return "STATE_DATAOUT_STATUS";
1069                 case STATE_READY:
1070                         return "STATE_READY";
1071                 case STATE_UNKNOWN:
1072                         return "STATE_UNKNOWN";
1073         }
1074
1075         NS_ERR("get_state_name: unknown state, BUG\n");
1076         return NULL;
1077 }
1078
1079 /*
1080  * Check if command is valid.
1081  *
1082  * RETURNS: 1 if wrong command, 0 if right.
1083  */
1084 static int check_command(int cmd)
1085 {
1086         switch (cmd) {
1087
1088         case NAND_CMD_READ0:
1089         case NAND_CMD_READ1:
1090         case NAND_CMD_READSTART:
1091         case NAND_CMD_PAGEPROG:
1092         case NAND_CMD_READOOB:
1093         case NAND_CMD_ERASE1:
1094         case NAND_CMD_STATUS:
1095         case NAND_CMD_SEQIN:
1096         case NAND_CMD_READID:
1097         case NAND_CMD_ERASE2:
1098         case NAND_CMD_RESET:
1099         case NAND_CMD_RNDOUT:
1100         case NAND_CMD_RNDOUTSTART:
1101                 return 0;
1102
1103         default:
1104                 return 1;
1105         }
1106 }
1107
1108 /*
1109  * Returns state after command is accepted by command number.
1110  */
1111 static uint32_t get_state_by_command(unsigned command)
1112 {
1113         switch (command) {
1114                 case NAND_CMD_READ0:
1115                         return STATE_CMD_READ0;
1116                 case NAND_CMD_READ1:
1117                         return STATE_CMD_READ1;
1118                 case NAND_CMD_PAGEPROG:
1119                         return STATE_CMD_PAGEPROG;
1120                 case NAND_CMD_READSTART:
1121                         return STATE_CMD_READSTART;
1122                 case NAND_CMD_READOOB:
1123                         return STATE_CMD_READOOB;
1124                 case NAND_CMD_ERASE1:
1125                         return STATE_CMD_ERASE1;
1126                 case NAND_CMD_STATUS:
1127                         return STATE_CMD_STATUS;
1128                 case NAND_CMD_SEQIN:
1129                         return STATE_CMD_SEQIN;
1130                 case NAND_CMD_READID:
1131                         return STATE_CMD_READID;
1132                 case NAND_CMD_ERASE2:
1133                         return STATE_CMD_ERASE2;
1134                 case NAND_CMD_RESET:
1135                         return STATE_CMD_RESET;
1136                 case NAND_CMD_RNDOUT:
1137                         return STATE_CMD_RNDOUT;
1138                 case NAND_CMD_RNDOUTSTART:
1139                         return STATE_CMD_RNDOUTSTART;
1140         }
1141
1142         NS_ERR("get_state_by_command: unknown command, BUG\n");
1143         return 0;
1144 }
1145
1146 /*
1147  * Move an address byte to the correspondent internal register.
1148  */
1149 static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
1150 {
1151         uint byte = (uint)bt;
1152
1153         if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
1154                 ns->regs.column |= (byte << 8 * ns->regs.count);
1155         else {
1156                 ns->regs.row |= (byte << 8 * (ns->regs.count -
1157                                                 ns->geom.pgaddrbytes +
1158                                                 ns->geom.secaddrbytes));
1159         }
1160
1161         return;
1162 }
1163
1164 /*
1165  * Switch to STATE_READY state.
1166  */
1167 static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
1168 {
1169         NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
1170
1171         ns->state       = STATE_READY;
1172         ns->nxstate     = STATE_UNKNOWN;
1173         ns->op          = NULL;
1174         ns->npstates    = 0;
1175         ns->stateidx    = 0;
1176         ns->regs.num    = 0;
1177         ns->regs.count  = 0;
1178         ns->regs.off    = 0;
1179         ns->regs.row    = 0;
1180         ns->regs.column = 0;
1181         ns->regs.status = status;
1182 }
1183
1184 /*
1185  * If the operation isn't known yet, try to find it in the global array
1186  * of supported operations.
1187  *
1188  * Operation can be unknown because of the following.
1189  *   1. New command was accepted and this is the first call to find the
1190  *      correspondent states chain. In this case ns->npstates = 0;
1191  *   2. There are several operations which begin with the same command(s)
1192  *      (for example program from the second half and read from the
1193  *      second half operations both begin with the READ1 command). In this
1194  *      case the ns->pstates[] array contains previous states.
1195  *
1196  * Thus, the function tries to find operation containing the following
1197  * states (if the 'flag' parameter is 0):
1198  *    ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
1199  *
1200  * If (one and only one) matching operation is found, it is accepted (
1201  * ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
1202  * zeroed).
1203  *
1204  * If there are several matches, the current state is pushed to the
1205  * ns->pstates.
1206  *
1207  * The operation can be unknown only while commands are input to the chip.
1208  * As soon as address command is accepted, the operation must be known.
1209  * In such situation the function is called with 'flag' != 0, and the
1210  * operation is searched using the following pattern:
1211  *     ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
1212  *
1213  * It is supposed that this pattern must either match one operation or
1214  * none. There can't be ambiguity in that case.
1215  *
1216  * If no matches found, the function does the following:
1217  *   1. if there are saved states present, try to ignore them and search
1218  *      again only using the last command. If nothing was found, switch
1219  *      to the STATE_READY state.
1220  *   2. if there are no saved states, switch to the STATE_READY state.
1221  *
1222  * RETURNS: -2 - no matched operations found.
1223  *          -1 - several matches.
1224  *           0 - operation is found.
1225  */
1226 static int find_operation(struct nandsim *ns, uint32_t flag)
1227 {
1228         int opsfound = 0;
1229         int i, j, idx = 0;
1230
1231         for (i = 0; i < NS_OPER_NUM; i++) {
1232
1233                 int found = 1;
1234
1235                 if (!(ns->options & ops[i].reqopts))
1236                         /* Ignore operations we can't perform */
1237                         continue;
1238
1239                 if (flag) {
1240                         if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
1241                                 continue;
1242                 } else {
1243                         if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
1244                                 continue;
1245                 }
1246
1247                 for (j = 0; j < ns->npstates; j++)
1248                         if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
1249                                 && (ns->options & ops[idx].reqopts)) {
1250                                 found = 0;
1251                                 break;
1252                         }
1253
1254                 if (found) {
1255                         idx = i;
1256                         opsfound += 1;
1257                 }
1258         }
1259
1260         if (opsfound == 1) {
1261                 /* Exact match */
1262                 ns->op = &ops[idx].states[0];
1263                 if (flag) {
1264                         /*
1265                          * In this case the find_operation function was
1266                          * called when address has just began input. But it isn't
1267                          * yet fully input and the current state must
1268                          * not be one of STATE_ADDR_*, but the STATE_ADDR_*
1269                          * state must be the next state (ns->nxstate).
1270                          */
1271                         ns->stateidx = ns->npstates - 1;
1272                 } else {
1273                         ns->stateidx = ns->npstates;
1274                 }
1275                 ns->npstates = 0;
1276                 ns->state = ns->op[ns->stateidx];
1277                 ns->nxstate = ns->op[ns->stateidx + 1];
1278                 NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
1279                                 idx, get_state_name(ns->state), get_state_name(ns->nxstate));
1280                 return 0;
1281         }
1282
1283         if (opsfound == 0) {
1284                 /* Nothing was found. Try to ignore previous commands (if any) and search again */
1285                 if (ns->npstates != 0) {
1286                         NS_DBG("find_operation: no operation found, try again with state %s\n",
1287                                         get_state_name(ns->state));
1288                         ns->npstates = 0;
1289                         return find_operation(ns, 0);
1290
1291                 }
1292                 NS_DBG("find_operation: no operations found\n");
1293                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1294                 return -2;
1295         }
1296
1297         if (flag) {
1298                 /* This shouldn't happen */
1299                 NS_DBG("find_operation: BUG, operation must be known if address is input\n");
1300                 return -2;
1301         }
1302
1303         NS_DBG("find_operation: there is still ambiguity\n");
1304
1305         ns->pstates[ns->npstates++] = ns->state;
1306
1307         return -1;
1308 }
1309
1310 static void put_pages(struct nandsim *ns)
1311 {
1312         int i;
1313
1314         for (i = 0; i < ns->held_cnt; i++)
1315                 put_page(ns->held_pages[i]);
1316 }
1317
1318 /* Get page cache pages in advance to provide NOFS memory allocation */
1319 static int get_pages(struct nandsim *ns, struct file *file, size_t count, loff_t pos)
1320 {
1321         pgoff_t index, start_index, end_index;
1322         struct page *page;
1323         struct address_space *mapping = file->f_mapping;
1324
1325         start_index = pos >> PAGE_SHIFT;
1326         end_index = (pos + count - 1) >> PAGE_SHIFT;
1327         if (end_index - start_index + 1 > NS_MAX_HELD_PAGES)
1328                 return -EINVAL;
1329         ns->held_cnt = 0;
1330         for (index = start_index; index <= end_index; index++) {
1331                 page = find_get_page(mapping, index);
1332                 if (page == NULL) {
1333                         page = find_or_create_page(mapping, index, GFP_NOFS);
1334                         if (page == NULL) {
1335                                 write_inode_now(mapping->host, 1);
1336                                 page = find_or_create_page(mapping, index, GFP_NOFS);
1337                         }
1338                         if (page == NULL) {
1339                                 put_pages(ns);
1340                                 return -ENOMEM;
1341                         }
1342                         unlock_page(page);
1343                 }
1344                 ns->held_pages[ns->held_cnt++] = page;
1345         }
1346         return 0;
1347 }
1348
1349 static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t pos)
1350 {
1351         ssize_t tx;
1352         int err;
1353         unsigned int noreclaim_flag;
1354
1355         err = get_pages(ns, file, count, pos);
1356         if (err)
1357                 return err;
1358         noreclaim_flag = memalloc_noreclaim_save();
1359         tx = kernel_read(file, pos, buf, count);
1360         memalloc_noreclaim_restore(noreclaim_flag);
1361         put_pages(ns);
1362         return tx;
1363 }
1364
1365 static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t pos)
1366 {
1367         ssize_t tx;
1368         int err;
1369         unsigned int noreclaim_flag;
1370
1371         err = get_pages(ns, file, count, pos);
1372         if (err)
1373                 return err;
1374         noreclaim_flag = memalloc_noreclaim_save();
1375         tx = kernel_write(file, buf, count, pos);
1376         memalloc_noreclaim_restore(noreclaim_flag);
1377         put_pages(ns);
1378         return tx;
1379 }
1380
1381 /*
1382  * Returns a pointer to the current page.
1383  */
1384 static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
1385 {
1386         return &(ns->pages[ns->regs.row]);
1387 }
1388
1389 /*
1390  * Retuns a pointer to the current byte, within the current page.
1391  */
1392 static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
1393 {
1394         return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
1395 }
1396
1397 static int do_read_error(struct nandsim *ns, int num)
1398 {
1399         unsigned int page_no = ns->regs.row;
1400
1401         if (read_error(page_no)) {
1402                 prandom_bytes(ns->buf.byte, num);
1403                 NS_WARN("simulating read error in page %u\n", page_no);
1404                 return 1;
1405         }
1406         return 0;
1407 }
1408
1409 static void do_bit_flips(struct nandsim *ns, int num)
1410 {
1411         if (bitflips && prandom_u32() < (1 << 22)) {
1412                 int flips = 1;
1413                 if (bitflips > 1)
1414                         flips = (prandom_u32() % (int) bitflips) + 1;
1415                 while (flips--) {
1416                         int pos = prandom_u32() % (num * 8);
1417                         ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
1418                         NS_WARN("read_page: flipping bit %d in page %d "
1419                                 "reading from %d ecc: corrected=%u failed=%u\n",
1420                                 pos, ns->regs.row, ns->regs.column + ns->regs.off,
1421                                 nsmtd->ecc_stats.corrected, nsmtd->ecc_stats.failed);
1422                 }
1423         }
1424 }
1425
1426 /*
1427  * Fill the NAND buffer with data read from the specified page.
1428  */
1429 static void read_page(struct nandsim *ns, int num)
1430 {
1431         union ns_mem *mypage;
1432
1433         if (ns->cfile) {
1434                 if (!test_bit(ns->regs.row, ns->pages_written)) {
1435                         NS_DBG("read_page: page %d not written\n", ns->regs.row);
1436                         memset(ns->buf.byte, 0xFF, num);
1437                 } else {
1438                         loff_t pos;
1439                         ssize_t tx;
1440
1441                         NS_DBG("read_page: page %d written, reading from %d\n",
1442                                 ns->regs.row, ns->regs.column + ns->regs.off);
1443                         if (do_read_error(ns, num))
1444                                 return;
1445                         pos = (loff_t)NS_RAW_OFFSET(ns) + ns->regs.off;
1446                         tx = read_file(ns, ns->cfile, ns->buf.byte, num, pos);
1447                         if (tx != num) {
1448                                 NS_ERR("read_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
1449                                 return;
1450                         }
1451                         do_bit_flips(ns, num);
1452                 }
1453                 return;
1454         }
1455
1456         mypage = NS_GET_PAGE(ns);
1457         if (mypage->byte == NULL) {
1458                 NS_DBG("read_page: page %d not allocated\n", ns->regs.row);
1459                 memset(ns->buf.byte, 0xFF, num);
1460         } else {
1461                 NS_DBG("read_page: page %d allocated, reading from %d\n",
1462                         ns->regs.row, ns->regs.column + ns->regs.off);
1463                 if (do_read_error(ns, num))
1464                         return;
1465                 memcpy(ns->buf.byte, NS_PAGE_BYTE_OFF(ns), num);
1466                 do_bit_flips(ns, num);
1467         }
1468 }
1469
1470 /*
1471  * Erase all pages in the specified sector.
1472  */
1473 static void erase_sector(struct nandsim *ns)
1474 {
1475         union ns_mem *mypage;
1476         int i;
1477
1478         if (ns->cfile) {
1479                 for (i = 0; i < ns->geom.pgsec; i++)
1480                         if (__test_and_clear_bit(ns->regs.row + i,
1481                                                  ns->pages_written)) {
1482                                 NS_DBG("erase_sector: freeing page %d\n", ns->regs.row + i);
1483                         }
1484                 return;
1485         }
1486
1487         mypage = NS_GET_PAGE(ns);
1488         for (i = 0; i < ns->geom.pgsec; i++) {
1489                 if (mypage->byte != NULL) {
1490                         NS_DBG("erase_sector: freeing page %d\n", ns->regs.row+i);
1491                         kmem_cache_free(ns->nand_pages_slab, mypage->byte);
1492                         mypage->byte = NULL;
1493                 }
1494                 mypage++;
1495         }
1496 }
1497
1498 /*
1499  * Program the specified page with the contents from the NAND buffer.
1500  */
1501 static int prog_page(struct nandsim *ns, int num)
1502 {
1503         int i;
1504         union ns_mem *mypage;
1505         u_char *pg_off;
1506
1507         if (ns->cfile) {
1508                 loff_t off;
1509                 ssize_t tx;
1510                 int all;
1511
1512                 NS_DBG("prog_page: writing page %d\n", ns->regs.row);
1513                 pg_off = ns->file_buf + ns->regs.column + ns->regs.off;
1514                 off = (loff_t)NS_RAW_OFFSET(ns) + ns->regs.off;
1515                 if (!test_bit(ns->regs.row, ns->pages_written)) {
1516                         all = 1;
1517                         memset(ns->file_buf, 0xff, ns->geom.pgszoob);
1518                 } else {
1519                         all = 0;
1520                         tx = read_file(ns, ns->cfile, pg_off, num, off);
1521                         if (tx != num) {
1522                                 NS_ERR("prog_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
1523                                 return -1;
1524                         }
1525                 }
1526                 for (i = 0; i < num; i++)
1527                         pg_off[i] &= ns->buf.byte[i];
1528                 if (all) {
1529                         loff_t pos = (loff_t)ns->regs.row * ns->geom.pgszoob;
1530                         tx = write_file(ns, ns->cfile, ns->file_buf, ns->geom.pgszoob, pos);
1531                         if (tx != ns->geom.pgszoob) {
1532                                 NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
1533                                 return -1;
1534                         }
1535                         __set_bit(ns->regs.row, ns->pages_written);
1536                 } else {
1537                         tx = write_file(ns, ns->cfile, pg_off, num, off);
1538                         if (tx != num) {
1539                                 NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
1540                                 return -1;
1541                         }
1542                 }
1543                 return 0;
1544         }
1545
1546         mypage = NS_GET_PAGE(ns);
1547         if (mypage->byte == NULL) {
1548                 NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
1549                 /*
1550                  * We allocate memory with GFP_NOFS because a flash FS may
1551                  * utilize this. If it is holding an FS lock, then gets here,
1552                  * then kernel memory alloc runs writeback which goes to the FS
1553                  * again and deadlocks. This was seen in practice.
1554                  */
1555                 mypage->byte = kmem_cache_alloc(ns->nand_pages_slab, GFP_NOFS);
1556                 if (mypage->byte == NULL) {
1557                         NS_ERR("prog_page: error allocating memory for page %d\n", ns->regs.row);
1558                         return -1;
1559                 }
1560                 memset(mypage->byte, 0xFF, ns->geom.pgszoob);
1561         }
1562
1563         pg_off = NS_PAGE_BYTE_OFF(ns);
1564         for (i = 0; i < num; i++)
1565                 pg_off[i] &= ns->buf.byte[i];
1566
1567         return 0;
1568 }
1569
1570 /*
1571  * If state has any action bit, perform this action.
1572  *
1573  * RETURNS: 0 if success, -1 if error.
1574  */
1575 static int do_state_action(struct nandsim *ns, uint32_t action)
1576 {
1577         int num;
1578         int busdiv = ns->busw == 8 ? 1 : 2;
1579         unsigned int erase_block_no, page_no;
1580
1581         action &= ACTION_MASK;
1582
1583         /* Check that page address input is correct */
1584         if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
1585                 NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
1586                 return -1;
1587         }
1588
1589         switch (action) {
1590
1591         case ACTION_CPY:
1592                 /*
1593                  * Copy page data to the internal buffer.
1594                  */
1595
1596                 /* Column shouldn't be very large */
1597                 if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
1598                         NS_ERR("do_state_action: column number is too large\n");
1599                         break;
1600                 }
1601                 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1602                 read_page(ns, num);
1603
1604                 NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
1605                         num, NS_RAW_OFFSET(ns) + ns->regs.off);
1606
1607                 if (ns->regs.off == 0)
1608                         NS_LOG("read page %d\n", ns->regs.row);
1609                 else if (ns->regs.off < ns->geom.pgsz)
1610                         NS_LOG("read page %d (second half)\n", ns->regs.row);
1611                 else
1612                         NS_LOG("read OOB of page %d\n", ns->regs.row);
1613
1614                 NS_UDELAY(access_delay);
1615                 NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
1616
1617                 break;
1618
1619         case ACTION_SECERASE:
1620                 /*
1621                  * Erase sector.
1622                  */
1623
1624                 if (ns->lines.wp) {
1625                         NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
1626                         return -1;
1627                 }
1628
1629                 if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
1630                         || (ns->regs.row & ~(ns->geom.secsz - 1))) {
1631                         NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
1632                         return -1;
1633                 }
1634
1635                 ns->regs.row = (ns->regs.row <<
1636                                 8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
1637                 ns->regs.column = 0;
1638
1639                 erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);
1640
1641                 NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
1642                                 ns->regs.row, NS_RAW_OFFSET(ns));
1643                 NS_LOG("erase sector %u\n", erase_block_no);
1644
1645                 erase_sector(ns);
1646
1647                 NS_MDELAY(erase_delay);
1648
1649                 if (erase_block_wear)
1650                         update_wear(erase_block_no);
1651
1652                 if (erase_error(erase_block_no)) {
1653                         NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
1654                         return -1;
1655                 }
1656
1657                 break;
1658
1659         case ACTION_PRGPAGE:
1660                 /*
1661                  * Program page - move internal buffer data to the page.
1662                  */
1663
1664                 if (ns->lines.wp) {
1665                         NS_WARN("do_state_action: device is write-protected, programm\n");
1666                         return -1;
1667                 }
1668
1669                 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1670                 if (num != ns->regs.count) {
1671                         NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
1672                                         ns->regs.count, num);
1673                         return -1;
1674                 }
1675
1676                 if (prog_page(ns, num) == -1)
1677                         return -1;
1678
1679                 page_no = ns->regs.row;
1680
1681                 NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
1682                         num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
1683                 NS_LOG("programm page %d\n", ns->regs.row);
1684
1685                 NS_UDELAY(programm_delay);
1686                 NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
1687
1688                 if (write_error(page_no)) {
1689                         NS_WARN("simulating write failure in page %u\n", page_no);
1690                         return -1;
1691                 }
1692
1693                 break;
1694
1695         case ACTION_ZEROOFF:
1696                 NS_DBG("do_state_action: set internal offset to 0\n");
1697                 ns->regs.off = 0;
1698                 break;
1699
1700         case ACTION_HALFOFF:
1701                 if (!(ns->options & OPT_PAGE512_8BIT)) {
1702                         NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
1703                                 "byte page size 8x chips\n");
1704                         return -1;
1705                 }
1706                 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
1707                 ns->regs.off = ns->geom.pgsz/2;
1708                 break;
1709
1710         case ACTION_OOBOFF:
1711                 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
1712                 ns->regs.off = ns->geom.pgsz;
1713                 break;
1714
1715         default:
1716                 NS_DBG("do_state_action: BUG! unknown action\n");
1717         }
1718
1719         return 0;
1720 }
1721
1722 /*
1723  * Switch simulator's state.
1724  */
1725 static void switch_state(struct nandsim *ns)
1726 {
1727         if (ns->op) {
1728                 /*
1729                  * The current operation have already been identified.
1730                  * Just follow the states chain.
1731                  */
1732
1733                 ns->stateidx += 1;
1734                 ns->state = ns->nxstate;
1735                 ns->nxstate = ns->op[ns->stateidx + 1];
1736
1737                 NS_DBG("switch_state: operation is known, switch to the next state, "
1738                         "state: %s, nxstate: %s\n",
1739                         get_state_name(ns->state), get_state_name(ns->nxstate));
1740
1741                 /* See, whether we need to do some action */
1742                 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1743                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1744                         return;
1745                 }
1746
1747         } else {
1748                 /*
1749                  * We don't yet know which operation we perform.
1750                  * Try to identify it.
1751                  */
1752
1753                 /*
1754                  *  The only event causing the switch_state function to
1755                  *  be called with yet unknown operation is new command.
1756                  */
1757                 ns->state = get_state_by_command(ns->regs.command);
1758
1759                 NS_DBG("switch_state: operation is unknown, try to find it\n");
1760
1761                 if (find_operation(ns, 0) != 0)
1762                         return;
1763
1764                 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1765                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1766                         return;
1767                 }
1768         }
1769
1770         /* For 16x devices column means the page offset in words */
1771         if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
1772                 NS_DBG("switch_state: double the column number for 16x device\n");
1773                 ns->regs.column <<= 1;
1774         }
1775
1776         if (NS_STATE(ns->nxstate) == STATE_READY) {
1777                 /*
1778                  * The current state is the last. Return to STATE_READY
1779                  */
1780
1781                 u_char status = NS_STATUS_OK(ns);
1782
1783                 /* In case of data states, see if all bytes were input/output */
1784                 if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
1785                         && ns->regs.count != ns->regs.num) {
1786                         NS_WARN("switch_state: not all bytes were processed, %d left\n",
1787                                         ns->regs.num - ns->regs.count);
1788                         status = NS_STATUS_FAILED(ns);
1789                 }
1790
1791                 NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
1792
1793                 switch_to_ready_state(ns, status);
1794
1795                 return;
1796         } else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
1797                 /*
1798                  * If the next state is data input/output, switch to it now
1799                  */
1800
1801                 ns->state      = ns->nxstate;
1802                 ns->nxstate    = ns->op[++ns->stateidx + 1];
1803                 ns->regs.num   = ns->regs.count = 0;
1804
1805                 NS_DBG("switch_state: the next state is data I/O, switch, "
1806                         "state: %s, nxstate: %s\n",
1807                         get_state_name(ns->state), get_state_name(ns->nxstate));
1808
1809                 /*
1810                  * Set the internal register to the count of bytes which
1811                  * are expected to be input or output
1812                  */
1813                 switch (NS_STATE(ns->state)) {
1814                         case STATE_DATAIN:
1815                         case STATE_DATAOUT:
1816                                 ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1817                                 break;
1818
1819                         case STATE_DATAOUT_ID:
1820                                 ns->regs.num = ns->geom.idbytes;
1821                                 break;
1822
1823                         case STATE_DATAOUT_STATUS:
1824                                 ns->regs.count = ns->regs.num = 0;
1825                                 break;
1826
1827                         default:
1828                                 NS_ERR("switch_state: BUG! unknown data state\n");
1829                 }
1830
1831         } else if (ns->nxstate & STATE_ADDR_MASK) {
1832                 /*
1833                  * If the next state is address input, set the internal
1834                  * register to the number of expected address bytes
1835                  */
1836
1837                 ns->regs.count = 0;
1838
1839                 switch (NS_STATE(ns->nxstate)) {
1840                         case STATE_ADDR_PAGE:
1841                                 ns->regs.num = ns->geom.pgaddrbytes;
1842
1843                                 break;
1844                         case STATE_ADDR_SEC:
1845                                 ns->regs.num = ns->geom.secaddrbytes;
1846                                 break;
1847
1848                         case STATE_ADDR_ZERO:
1849                                 ns->regs.num = 1;
1850                                 break;
1851
1852                         case STATE_ADDR_COLUMN:
1853                                 /* Column address is always 2 bytes */
1854                                 ns->regs.num = ns->geom.pgaddrbytes - ns->geom.secaddrbytes;
1855                                 break;
1856
1857                         default:
1858                                 NS_ERR("switch_state: BUG! unknown address state\n");
1859                 }
1860         } else {
1861                 /*
1862                  * Just reset internal counters.
1863                  */
1864
1865                 ns->regs.num = 0;
1866                 ns->regs.count = 0;
1867         }
1868 }
1869
1870 static u_char ns_nand_read_byte(struct mtd_info *mtd)
1871 {
1872         struct nand_chip *chip = mtd_to_nand(mtd);
1873         struct nandsim *ns = nand_get_controller_data(chip);
1874         u_char outb = 0x00;
1875
1876         /* Sanity and correctness checks */
1877         if (!ns->lines.ce) {
1878                 NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
1879                 return outb;
1880         }
1881         if (ns->lines.ale || ns->lines.cle) {
1882                 NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
1883                 return outb;
1884         }
1885         if (!(ns->state & STATE_DATAOUT_MASK)) {
1886                 NS_WARN("read_byte: unexpected data output cycle, state is %s "
1887                         "return %#x\n", get_state_name(ns->state), (uint)outb);
1888                 return outb;
1889         }
1890
1891         /* Status register may be read as many times as it is wanted */
1892         if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
1893                 NS_DBG("read_byte: return %#x status\n", ns->regs.status);
1894                 return ns->regs.status;
1895         }
1896
1897         /* Check if there is any data in the internal buffer which may be read */
1898         if (ns->regs.count == ns->regs.num) {
1899                 NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
1900                 return outb;
1901         }
1902
1903         switch (NS_STATE(ns->state)) {
1904                 case STATE_DATAOUT:
1905                         if (ns->busw == 8) {
1906                                 outb = ns->buf.byte[ns->regs.count];
1907                                 ns->regs.count += 1;
1908                         } else {
1909                                 outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
1910                                 ns->regs.count += 2;
1911                         }
1912                         break;
1913                 case STATE_DATAOUT_ID:
1914                         NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
1915                         outb = ns->ids[ns->regs.count];
1916                         ns->regs.count += 1;
1917                         break;
1918                 default:
1919                         BUG();
1920         }
1921
1922         if (ns->regs.count == ns->regs.num) {
1923                 NS_DBG("read_byte: all bytes were read\n");
1924
1925                 if (NS_STATE(ns->nxstate) == STATE_READY)
1926                         switch_state(ns);
1927         }
1928
1929         return outb;
1930 }
1931
1932 static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
1933 {
1934         struct nand_chip *chip = mtd_to_nand(mtd);
1935         struct nandsim *ns = nand_get_controller_data(chip);
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) {
1966                         int row = ns->regs.row;
1967
1968                         switch_state(ns);
1969                         if (byte == NAND_CMD_RNDOUT)
1970                                 ns->regs.row = row;
1971                 }
1972
1973                 /* Check if chip is expecting command */
1974                 if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
1975                         /* Do not warn if only 2 id bytes are read */
1976                         if (!(ns->regs.command == NAND_CMD_READID &&
1977                             NS_STATE(ns->state) == STATE_DATAOUT_ID && ns->regs.count == 2)) {
1978                                 /*
1979                                  * We are in situation when something else (not command)
1980                                  * was expected but command was input. In this case ignore
1981                                  * previous command(s)/state(s) and accept the last one.
1982                                  */
1983                                 NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
1984                                         "ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
1985                         }
1986                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1987                 }
1988
1989                 NS_DBG("command byte corresponding to %s state accepted\n",
1990                         get_state_name(get_state_by_command(byte)));
1991                 ns->regs.command = byte;
1992                 switch_state(ns);
1993
1994         } else if (ns->lines.ale == 1) {
1995                 /*
1996                  * The byte written is an address.
1997                  */
1998
1999                 if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
2000
2001                         NS_DBG("write_byte: operation isn't known yet, identify it\n");
2002
2003                         if (find_operation(ns, 1) < 0)
2004                                 return;
2005
2006                         if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
2007                                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2008                                 return;
2009                         }
2010
2011                         ns->regs.count = 0;
2012                         switch (NS_STATE(ns->nxstate)) {
2013                                 case STATE_ADDR_PAGE:
2014                                         ns->regs.num = ns->geom.pgaddrbytes;
2015                                         break;
2016                                 case STATE_ADDR_SEC:
2017                                         ns->regs.num = ns->geom.secaddrbytes;
2018                                         break;
2019                                 case STATE_ADDR_ZERO:
2020                                         ns->regs.num = 1;
2021                                         break;
2022                                 default:
2023                                         BUG();
2024                         }
2025                 }
2026
2027                 /* Check that chip is expecting address */
2028                 if (!(ns->nxstate & STATE_ADDR_MASK)) {
2029                         NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
2030                                 "switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
2031                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2032                         return;
2033                 }
2034
2035                 /* Check if this is expected byte */
2036                 if (ns->regs.count == ns->regs.num) {
2037                         NS_ERR("write_byte: no more address bytes expected\n");
2038                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2039                         return;
2040                 }
2041
2042                 accept_addr_byte(ns, byte);
2043
2044                 ns->regs.count += 1;
2045
2046                 NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
2047                                 (uint)byte, ns->regs.count, ns->regs.num);
2048
2049                 if (ns->regs.count == ns->regs.num) {
2050                         NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
2051                         switch_state(ns);
2052                 }
2053
2054         } else {
2055                 /*
2056                  * The byte written is an input data.
2057                  */
2058
2059                 /* Check that chip is expecting data input */
2060                 if (!(ns->state & STATE_DATAIN_MASK)) {
2061                         NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
2062                                 "switch to %s\n", (uint)byte,
2063                                 get_state_name(ns->state), get_state_name(STATE_READY));
2064                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2065                         return;
2066                 }
2067
2068                 /* Check if this is expected byte */
2069                 if (ns->regs.count == ns->regs.num) {
2070                         NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
2071                                         ns->regs.num);
2072                         return;
2073                 }
2074
2075                 if (ns->busw == 8) {
2076                         ns->buf.byte[ns->regs.count] = byte;
2077                         ns->regs.count += 1;
2078                 } else {
2079                         ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
2080                         ns->regs.count += 2;
2081                 }
2082         }
2083
2084         return;
2085 }
2086
2087 static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
2088 {
2089         struct nand_chip *chip = mtd_to_nand(mtd);
2090         struct nandsim *ns = nand_get_controller_data(chip);
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 = mtd_to_nand(mtd);
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 nand_chip *chip = mtd_to_nand(mtd);
2118         struct nandsim *ns = nand_get_controller_data(chip);
2119
2120         /* Check that chip is expecting data input */
2121         if (!(ns->state & STATE_DATAIN_MASK)) {
2122                 NS_ERR("write_buf: data input isn't expected, state is %s, "
2123                         "switch to STATE_READY\n", get_state_name(ns->state));
2124                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2125                 return;
2126         }
2127
2128         /* Check if these are expected bytes */
2129         if (ns->regs.count + len > ns->regs.num) {
2130                 NS_ERR("write_buf: too many input bytes\n");
2131                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2132                 return;
2133         }
2134
2135         memcpy(ns->buf.byte + ns->regs.count, buf, len);
2136         ns->regs.count += len;
2137
2138         if (ns->regs.count == ns->regs.num) {
2139                 NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
2140         }
2141 }
2142
2143 static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
2144 {
2145         struct nand_chip *chip = mtd_to_nand(mtd);
2146         struct nandsim *ns = nand_get_controller_data(chip);
2147
2148         /* Sanity and correctness checks */
2149         if (!ns->lines.ce) {
2150                 NS_ERR("read_buf: chip is disabled\n");
2151                 return;
2152         }
2153         if (ns->lines.ale || ns->lines.cle) {
2154                 NS_ERR("read_buf: ALE or CLE pin is high\n");
2155                 return;
2156         }
2157         if (!(ns->state & STATE_DATAOUT_MASK)) {
2158                 NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
2159                         get_state_name(ns->state));
2160                 return;
2161         }
2162
2163         if (NS_STATE(ns->state) != STATE_DATAOUT) {
2164                 int i;
2165
2166                 for (i = 0; i < len; i++)
2167                         buf[i] = mtd_to_nand(mtd)->read_byte(mtd);
2168
2169                 return;
2170         }
2171
2172         /* Check if these are expected bytes */
2173         if (ns->regs.count + len > ns->regs.num) {
2174                 NS_ERR("read_buf: too many bytes to read\n");
2175                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
2176                 return;
2177         }
2178
2179         memcpy(buf, ns->buf.byte + ns->regs.count, len);
2180         ns->regs.count += len;
2181
2182         if (ns->regs.count == ns->regs.num) {
2183                 if (NS_STATE(ns->nxstate) == STATE_READY)
2184                         switch_state(ns);
2185         }
2186
2187         return;
2188 }
2189
2190 /*
2191  * Module initialization function
2192  */
2193 static int __init ns_init_module(void)
2194 {
2195         struct nand_chip *chip;
2196         struct nandsim *nand;
2197         int retval = -ENOMEM, i;
2198
2199         if (bus_width != 8 && bus_width != 16) {
2200                 NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
2201                 return -EINVAL;
2202         }
2203
2204         /* Allocate and initialize mtd_info, nand_chip and nandsim structures */
2205         chip = kzalloc(sizeof(struct nand_chip) + sizeof(struct nandsim),
2206                        GFP_KERNEL);
2207         if (!chip) {
2208                 NS_ERR("unable to allocate core structures.\n");
2209                 return -ENOMEM;
2210         }
2211         nsmtd       = nand_to_mtd(chip);
2212         nand        = (struct nandsim *)(chip + 1);
2213         nand_set_controller_data(chip, (void *)nand);
2214
2215         /*
2216          * Register simulator's callbacks.
2217          */
2218         chip->cmd_ctrl   = ns_hwcontrol;
2219         chip->read_byte  = ns_nand_read_byte;
2220         chip->dev_ready  = ns_device_ready;
2221         chip->write_buf  = ns_nand_write_buf;
2222         chip->read_buf   = ns_nand_read_buf;
2223         chip->read_word  = ns_nand_read_word;
2224         chip->ecc.mode   = NAND_ECC_SOFT;
2225         chip->ecc.algo   = NAND_ECC_HAMMING;
2226         /* The NAND_SKIP_BBTSCAN option is necessary for 'overridesize' */
2227         /* and 'badblocks' parameters to work */
2228         chip->options   |= NAND_SKIP_BBTSCAN;
2229
2230         switch (bbt) {
2231         case 2:
2232                  chip->bbt_options |= NAND_BBT_NO_OOB;
2233         case 1:
2234                  chip->bbt_options |= NAND_BBT_USE_FLASH;
2235         case 0:
2236                 break;
2237         default:
2238                 NS_ERR("bbt has to be 0..2\n");
2239                 retval = -EINVAL;
2240                 goto error;
2241         }
2242         /*
2243          * Perform minimum nandsim structure initialization to handle
2244          * the initial ID read command correctly
2245          */
2246         if (id_bytes[6] != 0xFF || id_bytes[7] != 0xFF)
2247                 nand->geom.idbytes = 8;
2248         else if (id_bytes[4] != 0xFF || id_bytes[5] != 0xFF)
2249                 nand->geom.idbytes = 6;
2250         else if (id_bytes[2] != 0xFF || id_bytes[3] != 0xFF)
2251                 nand->geom.idbytes = 4;
2252         else
2253                 nand->geom.idbytes = 2;
2254         nand->regs.status = NS_STATUS_OK(nand);
2255         nand->nxstate = STATE_UNKNOWN;
2256         nand->options |= OPT_PAGE512; /* temporary value */
2257         memcpy(nand->ids, id_bytes, sizeof(nand->ids));
2258         if (bus_width == 16) {
2259                 nand->busw = 16;
2260                 chip->options |= NAND_BUSWIDTH_16;
2261         }
2262
2263         nsmtd->owner = THIS_MODULE;
2264
2265         if ((retval = parse_weakblocks()) != 0)
2266                 goto error;
2267
2268         if ((retval = parse_weakpages()) != 0)
2269                 goto error;
2270
2271         if ((retval = parse_gravepages()) != 0)
2272                 goto error;
2273
2274         retval = nand_scan_ident(nsmtd, 1, NULL);
2275         if (retval) {
2276                 NS_ERR("cannot scan NAND Simulator device\n");
2277                 goto error;
2278         }
2279
2280         if (bch) {
2281                 unsigned int eccsteps, eccbytes;
2282                 if (!mtd_nand_has_bch()) {
2283                         NS_ERR("BCH ECC support is disabled\n");
2284                         retval = -EINVAL;
2285                         goto error;
2286                 }
2287                 /* use 512-byte ecc blocks */
2288                 eccsteps = nsmtd->writesize/512;
2289                 eccbytes = (bch*13+7)/8;
2290                 /* do not bother supporting small page devices */
2291                 if ((nsmtd->oobsize < 64) || !eccsteps) {
2292                         NS_ERR("bch not available on small page devices\n");
2293                         retval = -EINVAL;
2294                         goto error;
2295                 }
2296                 if ((eccbytes*eccsteps+2) > nsmtd->oobsize) {
2297                         NS_ERR("invalid bch value %u\n", bch);
2298                         retval = -EINVAL;
2299                         goto error;
2300                 }
2301                 chip->ecc.mode = NAND_ECC_SOFT;
2302                 chip->ecc.algo = NAND_ECC_BCH;
2303                 chip->ecc.size = 512;
2304                 chip->ecc.strength = bch;
2305                 chip->ecc.bytes = eccbytes;
2306                 NS_INFO("using %u-bit/%u bytes BCH ECC\n", bch, chip->ecc.size);
2307         }
2308
2309         retval = nand_scan_tail(nsmtd);
2310         if (retval) {
2311                 NS_ERR("can't register NAND Simulator\n");
2312                 goto error;
2313         }
2314
2315         if (overridesize) {
2316                 uint64_t new_size = (uint64_t)nsmtd->erasesize << overridesize;
2317                 if (new_size >> overridesize != nsmtd->erasesize) {
2318                         NS_ERR("overridesize is too big\n");
2319                         retval = -EINVAL;
2320                         goto err_exit;
2321                 }
2322                 /* N.B. This relies on nand_scan not doing anything with the size before we change it */
2323                 nsmtd->size = new_size;
2324                 chip->chipsize = new_size;
2325                 chip->chip_shift = ffs(nsmtd->erasesize) + overridesize - 1;
2326                 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
2327         }
2328
2329         if ((retval = setup_wear_reporting(nsmtd)) != 0)
2330                 goto err_exit;
2331
2332         if ((retval = init_nandsim(nsmtd)) != 0)
2333                 goto err_exit;
2334
2335         if ((retval = chip->scan_bbt(nsmtd)) != 0)
2336                 goto err_exit;
2337
2338         if ((retval = parse_badblocks(nand, nsmtd)) != 0)
2339                 goto err_exit;
2340
2341         /* Register NAND partitions */
2342         retval = mtd_device_register(nsmtd, &nand->partitions[0],
2343                                      nand->nbparts);
2344         if (retval != 0)
2345                 goto err_exit;
2346
2347         if ((retval = nandsim_debugfs_create(nand)) != 0)
2348                 goto err_exit;
2349
2350         return 0;
2351
2352 err_exit:
2353         free_nandsim(nand);
2354         nand_release(nsmtd);
2355         for (i = 0;i < ARRAY_SIZE(nand->partitions); ++i)
2356                 kfree(nand->partitions[i].name);
2357 error:
2358         kfree(chip);
2359         free_lists();
2360
2361         return retval;
2362 }
2363
2364 module_init(ns_init_module);
2365
2366 /*
2367  * Module clean-up function
2368  */
2369 static void __exit ns_cleanup_module(void)
2370 {
2371         struct nand_chip *chip = mtd_to_nand(nsmtd);
2372         struct nandsim *ns = nand_get_controller_data(chip);
2373         int i;
2374
2375         free_nandsim(ns);    /* Free nandsim private resources */
2376         nand_release(nsmtd); /* Unregister driver */
2377         for (i = 0;i < ARRAY_SIZE(ns->partitions); ++i)
2378                 kfree(ns->partitions[i].name);
2379         kfree(mtd_to_nand(nsmtd));        /* Free other structures */
2380         free_lists();
2381 }
2382
2383 module_exit(ns_cleanup_module);
2384
2385 MODULE_LICENSE ("GPL");
2386 MODULE_AUTHOR ("Artem B. Bityuckiy");
2387 MODULE_DESCRIPTION ("The NAND flash simulator");