5dd3c4eb4f01cd4b9df9d5c0fc38ae34cbdea6cf
[pandora-kernel.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  * $Id: nandsim.c,v 1.8 2005/03/19 15:33:56 dedekind Exp $
26  */
27
28 #include <linux/init.h>
29 #include <linux/types.h>
30 #include <linux/module.h>
31 #include <linux/moduleparam.h>
32 #include <linux/vmalloc.h>
33 #include <linux/slab.h>
34 #include <linux/errno.h>
35 #include <linux/string.h>
36 #include <linux/mtd/mtd.h>
37 #include <linux/mtd/nand.h>
38 #include <linux/mtd/partitions.h>
39 #include <linux/delay.h>
40
41 /* Default simulator parameters values */
42 #if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE)  || \
43     !defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
44     !defined(CONFIG_NANDSIM_THIRD_ID_BYTE)  || \
45     !defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
46 #define CONFIG_NANDSIM_FIRST_ID_BYTE  0x98
47 #define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
48 #define CONFIG_NANDSIM_THIRD_ID_BYTE  0xFF /* No byte */
49 #define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
50 #endif
51
52 #ifndef CONFIG_NANDSIM_ACCESS_DELAY
53 #define CONFIG_NANDSIM_ACCESS_DELAY 25
54 #endif
55 #ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
56 #define CONFIG_NANDSIM_PROGRAMM_DELAY 200
57 #endif
58 #ifndef CONFIG_NANDSIM_ERASE_DELAY
59 #define CONFIG_NANDSIM_ERASE_DELAY 2
60 #endif
61 #ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
62 #define CONFIG_NANDSIM_OUTPUT_CYCLE 40
63 #endif
64 #ifndef CONFIG_NANDSIM_INPUT_CYCLE
65 #define CONFIG_NANDSIM_INPUT_CYCLE  50
66 #endif
67 #ifndef CONFIG_NANDSIM_BUS_WIDTH
68 #define CONFIG_NANDSIM_BUS_WIDTH  8
69 #endif
70 #ifndef CONFIG_NANDSIM_DO_DELAYS
71 #define CONFIG_NANDSIM_DO_DELAYS  0
72 #endif
73 #ifndef CONFIG_NANDSIM_LOG
74 #define CONFIG_NANDSIM_LOG        0
75 #endif
76 #ifndef CONFIG_NANDSIM_DBG
77 #define CONFIG_NANDSIM_DBG        0
78 #endif
79
80 static uint first_id_byte  = CONFIG_NANDSIM_FIRST_ID_BYTE;
81 static uint second_id_byte = CONFIG_NANDSIM_SECOND_ID_BYTE;
82 static uint third_id_byte  = CONFIG_NANDSIM_THIRD_ID_BYTE;
83 static uint fourth_id_byte = CONFIG_NANDSIM_FOURTH_ID_BYTE;
84 static uint access_delay   = CONFIG_NANDSIM_ACCESS_DELAY;
85 static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
86 static uint erase_delay    = CONFIG_NANDSIM_ERASE_DELAY;
87 static uint output_cycle   = CONFIG_NANDSIM_OUTPUT_CYCLE;
88 static uint input_cycle    = CONFIG_NANDSIM_INPUT_CYCLE;
89 static uint bus_width      = CONFIG_NANDSIM_BUS_WIDTH;
90 static uint do_delays      = CONFIG_NANDSIM_DO_DELAYS;
91 static uint log            = CONFIG_NANDSIM_LOG;
92 static uint dbg            = CONFIG_NANDSIM_DBG;
93
94 module_param(first_id_byte,  uint, 0400);
95 module_param(second_id_byte, uint, 0400);
96 module_param(third_id_byte,  uint, 0400);
97 module_param(fourth_id_byte, uint, 0400);
98 module_param(access_delay,   uint, 0400);
99 module_param(programm_delay, uint, 0400);
100 module_param(erase_delay,    uint, 0400);
101 module_param(output_cycle,   uint, 0400);
102 module_param(input_cycle,    uint, 0400);
103 module_param(bus_width,      uint, 0400);
104 module_param(do_delays,      uint, 0400);
105 module_param(log,            uint, 0400);
106 module_param(dbg,            uint, 0400);
107
108 MODULE_PARM_DESC(first_id_byte,  "The fist byte returned by NAND Flash 'read ID' command (manufaturer ID)");
109 MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID)");
110 MODULE_PARM_DESC(third_id_byte,  "The third byte returned by NAND Flash 'read ID' command");
111 MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command");
112 MODULE_PARM_DESC(access_delay,   "Initial page access delay (microiseconds)");
113 MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
114 MODULE_PARM_DESC(erase_delay,    "Sector erase delay (milliseconds)");
115 MODULE_PARM_DESC(output_cycle,   "Word output (from flash) time (nanodeconds)");
116 MODULE_PARM_DESC(input_cycle,    "Word input (to flash) time (nanodeconds)");
117 MODULE_PARM_DESC(bus_width,      "Chip's bus width (8- or 16-bit)");
118 MODULE_PARM_DESC(do_delays,      "Simulate NAND delays using busy-waits if not zero");
119 MODULE_PARM_DESC(log,            "Perform logging if not zero");
120 MODULE_PARM_DESC(dbg,            "Output debug information if not zero");
121
122 /* The largest possible page size */
123 #define NS_LARGEST_PAGE_SIZE    2048
124
125 /* The prefix for simulator output */
126 #define NS_OUTPUT_PREFIX "[nandsim]"
127
128 /* Simulator's output macros (logging, debugging, warning, error) */
129 #define NS_LOG(args...) \
130         do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
131 #define NS_DBG(args...) \
132         do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
133 #define NS_WARN(args...) \
134         do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warnig: " args); } while(0)
135 #define NS_ERR(args...) \
136         do { printk(KERN_ERR NS_OUTPUT_PREFIX " errorr: " args); } while(0)
137
138 /* Busy-wait delay macros (microseconds, milliseconds) */
139 #define NS_UDELAY(us) \
140         do { if (do_delays) udelay(us); } while(0)
141 #define NS_MDELAY(us) \
142         do { if (do_delays) mdelay(us); } while(0)
143
144 /* Is the nandsim structure initialized ? */
145 #define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
146
147 /* Good operation completion status */
148 #define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
149
150 /* Operation failed completion status */
151 #define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
152
153 /* Calculate the page offset in flash RAM image by (row, column) address */
154 #define NS_RAW_OFFSET(ns) \
155         (((ns)->regs.row << (ns)->geom.pgshift) + ((ns)->regs.row * (ns)->geom.oobsz) + (ns)->regs.column)
156
157 /* Calculate the OOB offset in flash RAM image by (row, column) address */
158 #define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)
159
160 /* After a command is input, the simulator goes to one of the following states */
161 #define STATE_CMD_READ0        0x00000001 /* read data from the beginning of page */
162 #define STATE_CMD_READ1        0x00000002 /* read data from the second half of page */
163 #define STATE_CMD_READSTART      0x00000003 /* read data second command (large page devices) */
164 #define STATE_CMD_PAGEPROG     0x00000004 /* start page programm */
165 #define STATE_CMD_READOOB      0x00000005 /* read OOB area */
166 #define STATE_CMD_ERASE1       0x00000006 /* sector erase first command */
167 #define STATE_CMD_STATUS       0x00000007 /* read status */
168 #define STATE_CMD_STATUS_M     0x00000008 /* read multi-plane status (isn't implemented) */
169 #define STATE_CMD_SEQIN        0x00000009 /* sequential data imput */
170 #define STATE_CMD_READID       0x0000000A /* read ID */
171 #define STATE_CMD_ERASE2       0x0000000B /* sector erase second command */
172 #define STATE_CMD_RESET        0x0000000C /* reset */
173 #define STATE_CMD_MASK         0x0000000F /* command states mask */
174
175 /* After an addres is input, the simulator goes to one of these states */
176 #define STATE_ADDR_PAGE        0x00000010 /* full (row, column) address is accepted */
177 #define STATE_ADDR_SEC         0x00000020 /* sector address was accepted */
178 #define STATE_ADDR_ZERO        0x00000030 /* one byte zero address was accepted */
179 #define STATE_ADDR_MASK        0x00000030 /* address states mask */
180
181 /* Durind data input/output the simulator is in these states */
182 #define STATE_DATAIN           0x00000100 /* waiting for data input */
183 #define STATE_DATAIN_MASK      0x00000100 /* data input states mask */
184
185 #define STATE_DATAOUT          0x00001000 /* waiting for page data output */
186 #define STATE_DATAOUT_ID       0x00002000 /* waiting for ID bytes output */
187 #define STATE_DATAOUT_STATUS   0x00003000 /* waiting for status output */
188 #define STATE_DATAOUT_STATUS_M 0x00004000 /* waiting for multi-plane status output */
189 #define STATE_DATAOUT_MASK     0x00007000 /* data output states mask */
190
191 /* Previous operation is done, ready to accept new requests */
192 #define STATE_READY            0x00000000
193
194 /* This state is used to mark that the next state isn't known yet */
195 #define STATE_UNKNOWN          0x10000000
196
197 /* Simulator's actions bit masks */
198 #define ACTION_CPY       0x00100000 /* copy page/OOB to the internal buffer */
199 #define ACTION_PRGPAGE   0x00200000 /* programm the internal buffer to flash */
200 #define ACTION_SECERASE  0x00300000 /* erase sector */
201 #define ACTION_ZEROOFF   0x00400000 /* don't add any offset to address */
202 #define ACTION_HALFOFF   0x00500000 /* add to address half of page */
203 #define ACTION_OOBOFF    0x00600000 /* add to address OOB offset */
204 #define ACTION_MASK      0x00700000 /* action mask */
205
206 #define NS_OPER_NUM      12 /* Number of operations supported by the simulator */
207 #define NS_OPER_STATES   6  /* Maximum number of states in operation */
208
209 #define OPT_ANY          0xFFFFFFFF /* any chip supports this operation */
210 #define OPT_PAGE256      0x00000001 /* 256-byte  page chips */
211 #define OPT_PAGE512      0x00000002 /* 512-byte  page chips */
212 #define OPT_PAGE2048     0x00000008 /* 2048-byte page chips */
213 #define OPT_SMARTMEDIA   0x00000010 /* SmartMedia technology chips */
214 #define OPT_AUTOINCR     0x00000020 /* page number auto inctimentation is possible */
215 #define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
216 #define OPT_LARGEPAGE    (OPT_PAGE2048) /* 2048-byte page chips */
217 #define OPT_SMALLPAGE    (OPT_PAGE256  | OPT_PAGE512)  /* 256 and 512-byte page chips */
218
219 /* Remove action bits ftom state */
220 #define NS_STATE(x) ((x) & ~ACTION_MASK)
221
222 /*
223  * Maximum previous states which need to be saved. Currently saving is
224  * only needed for page programm operation with preceeded read command
225  * (which is only valid for 512-byte pages).
226  */
227 #define NS_MAX_PREVSTATES 1
228
229 /*
230  * The structure which describes all the internal simulator data.
231  */
232 struct nandsim {
233         struct mtd_partition part;
234
235         uint busw;              /* flash chip bus width (8 or 16) */
236         u_char ids[4];          /* chip's ID bytes */
237         uint32_t options;       /* chip's characteristic bits */
238         uint32_t state;         /* current chip state */
239         uint32_t nxstate;       /* next expected state */
240
241         uint32_t *op;           /* current operation, NULL operations isn't known yet  */
242         uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
243         uint16_t npstates;      /* number of previous states saved */
244         uint16_t stateidx;      /* current state index */
245
246         /* The simulated NAND flash image */
247         union flash_media {
248                 u_char *byte;
249                 uint16_t    *word;
250         } mem;
251
252         /* Internal buffer of page + OOB size bytes */
253         union internal_buffer {
254                 u_char *byte;    /* for byte access */
255                 uint16_t *word;  /* for 16-bit word access */
256         } buf;
257
258         /* NAND flash "geometry" */
259         struct nandsin_geometry {
260                 uint32_t totsz;     /* total flash size, bytes */
261                 uint32_t secsz;     /* flash sector (erase block) size, bytes */
262                 uint pgsz;          /* NAND flash page size, bytes */
263                 uint oobsz;         /* page OOB area size, bytes */
264                 uint32_t totszoob;  /* total flash size including OOB, bytes */
265                 uint pgszoob;       /* page size including OOB , bytes*/
266                 uint secszoob;      /* sector size including OOB, bytes */
267                 uint pgnum;         /* total number of pages */
268                 uint pgsec;         /* number of pages per sector */
269                 uint secshift;      /* bits number in sector size */
270                 uint pgshift;       /* bits number in page size */
271                 uint oobshift;      /* bits number in OOB size */
272                 uint pgaddrbytes;   /* bytes per page address */
273                 uint secaddrbytes;  /* bytes per sector address */
274                 uint idbytes;       /* the number ID bytes that this chip outputs */
275         } geom;
276
277         /* NAND flash internal registers */
278         struct nandsim_regs {
279                 unsigned command; /* the command register */
280                 u_char   status;  /* the status register */
281                 uint     row;     /* the page number */
282                 uint     column;  /* the offset within page */
283                 uint     count;   /* internal counter */
284                 uint     num;     /* number of bytes which must be processed */
285                 uint     off;     /* fixed page offset */
286         } regs;
287
288         /* NAND flash lines state */
289         struct ns_lines_status {
290                 int ce;  /* chip Enable */
291                 int cle; /* command Latch Enable */
292                 int ale; /* address Latch Enable */
293                 int wp;  /* write Protect */
294         } lines;
295 };
296
297 /*
298  * Operations array. To perform any operation the simulator must pass
299  * through the correspondent states chain.
300  */
301 static struct nandsim_operations {
302         uint32_t reqopts;  /* options which are required to perform the operation */
303         uint32_t states[NS_OPER_STATES]; /* operation's states */
304 } ops[NS_OPER_NUM] = {
305         /* Read page + OOB from the beginning */
306         {OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
307                         STATE_DATAOUT, STATE_READY}},
308         /* Read page + OOB from the second half */
309         {OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
310                         STATE_DATAOUT, STATE_READY}},
311         /* Read OOB */
312         {OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
313                         STATE_DATAOUT, STATE_READY}},
314         /* Programm page starting from the beginning */
315         {OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
316                         STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
317         /* Programm page starting from the beginning */
318         {OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
319                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
320         /* Programm page starting from the second half */
321         {OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
322                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
323         /* Programm OOB */
324         {OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
325                               STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
326         /* Erase sector */
327         {OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
328         /* Read status */
329         {OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
330         /* Read multi-plane status */
331         {OPT_SMARTMEDIA, {STATE_CMD_STATUS_M, STATE_DATAOUT_STATUS_M, STATE_READY}},
332         /* Read ID */
333         {OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
334         /* Large page devices read page */
335         {OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
336                                STATE_DATAOUT, STATE_READY}}
337 };
338
339 /* MTD structure for NAND controller */
340 static struct mtd_info *nsmtd;
341
342 static u_char ns_verify_buf[NS_LARGEST_PAGE_SIZE];
343
344 /*
345  * Initialize the nandsim structure.
346  *
347  * RETURNS: 0 if success, -ERRNO if failure.
348  */
349 static int
350 init_nandsim(struct mtd_info *mtd)
351 {
352         struct nand_chip *chip = (struct nand_chip *)mtd->priv;
353         struct nandsim   *ns   = (struct nandsim *)(chip->priv);
354         int i;
355
356         if (NS_IS_INITIALIZED(ns)) {
357                 NS_ERR("init_nandsim: nandsim is already initialized\n");
358                 return -EIO;
359         }
360
361         /* Force mtd to not do delays */
362         chip->chip_delay = 0;
363
364         /* Initialize the NAND flash parameters */
365         ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
366         ns->geom.totsz    = mtd->size;
367         ns->geom.pgsz     = mtd->writesize;
368         ns->geom.oobsz    = mtd->oobsize;
369         ns->geom.secsz    = mtd->erasesize;
370         ns->geom.pgszoob  = ns->geom.pgsz + ns->geom.oobsz;
371         ns->geom.pgnum    = ns->geom.totsz / ns->geom.pgsz;
372         ns->geom.totszoob = ns->geom.totsz + ns->geom.pgnum * ns->geom.oobsz;
373         ns->geom.secshift = ffs(ns->geom.secsz) - 1;
374         ns->geom.pgshift  = chip->page_shift;
375         ns->geom.oobshift = ffs(ns->geom.oobsz) - 1;
376         ns->geom.pgsec    = ns->geom.secsz / ns->geom.pgsz;
377         ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
378         ns->options = 0;
379
380         if (ns->geom.pgsz == 256) {
381                 ns->options |= OPT_PAGE256;
382         }
383         else if (ns->geom.pgsz == 512) {
384                 ns->options |= (OPT_PAGE512 | OPT_AUTOINCR);
385                 if (ns->busw == 8)
386                         ns->options |= OPT_PAGE512_8BIT;
387         } else if (ns->geom.pgsz == 2048) {
388                 ns->options |= OPT_PAGE2048;
389         } else {
390                 NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
391                 return -EIO;
392         }
393
394         if (ns->options & OPT_SMALLPAGE) {
395                 if (ns->geom.totsz < (64 << 20)) {
396                         ns->geom.pgaddrbytes  = 3;
397                         ns->geom.secaddrbytes = 2;
398                 } else {
399                         ns->geom.pgaddrbytes  = 4;
400                         ns->geom.secaddrbytes = 3;
401                 }
402         } else {
403                 if (ns->geom.totsz <= (128 << 20)) {
404                         ns->geom.pgaddrbytes  = 5;
405                         ns->geom.secaddrbytes = 2;
406                 } else {
407                         ns->geom.pgaddrbytes  = 5;
408                         ns->geom.secaddrbytes = 3;
409                 }
410         }
411
412         /* Detect how many ID bytes the NAND chip outputs */
413         for (i = 0; nand_flash_ids[i].name != NULL; i++) {
414                 if (second_id_byte != nand_flash_ids[i].id)
415                         continue;
416                 if (!(nand_flash_ids[i].options & NAND_NO_AUTOINCR))
417                         ns->options |= OPT_AUTOINCR;
418         }
419
420         if (ns->busw == 16)
421                 NS_WARN("16-bit flashes support wasn't tested\n");
422
423         printk("flash size: %u MiB\n",          ns->geom.totsz >> 20);
424         printk("page size: %u bytes\n",         ns->geom.pgsz);
425         printk("OOB area size: %u bytes\n",     ns->geom.oobsz);
426         printk("sector size: %u KiB\n",         ns->geom.secsz >> 10);
427         printk("pages number: %u\n",            ns->geom.pgnum);
428         printk("pages per sector: %u\n",        ns->geom.pgsec);
429         printk("bus width: %u\n",               ns->busw);
430         printk("bits in sector size: %u\n",     ns->geom.secshift);
431         printk("bits in page size: %u\n",       ns->geom.pgshift);
432         printk("bits in OOB size: %u\n",        ns->geom.oobshift);
433         printk("flash size with OOB: %u KiB\n", ns->geom.totszoob >> 10);
434         printk("page address bytes: %u\n",      ns->geom.pgaddrbytes);
435         printk("sector address bytes: %u\n",    ns->geom.secaddrbytes);
436         printk("options: %#x\n",                ns->options);
437
438         /* Map / allocate and initialize the flash image */
439         ns->mem.byte = vmalloc(ns->geom.totszoob);
440         if (!ns->mem.byte) {
441                 NS_ERR("init_nandsim: unable to allocate %u bytes for flash image\n",
442                         ns->geom.totszoob);
443                 return -ENOMEM;
444         }
445         memset(ns->mem.byte, 0xFF, ns->geom.totszoob);
446
447         /* Allocate / initialize the internal buffer */
448         ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
449         if (!ns->buf.byte) {
450                 NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
451                         ns->geom.pgszoob);
452                 goto error;
453         }
454         memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
455
456         /* Fill the partition_info structure */
457         ns->part.name   = "NAND simulator partition";
458         ns->part.offset = 0;
459         ns->part.size   = ns->geom.totsz;
460
461         return 0;
462
463 error:
464         vfree(ns->mem.byte);
465
466         return -ENOMEM;
467 }
468
469 /*
470  * Free the nandsim structure.
471  */
472 static void
473 free_nandsim(struct nandsim *ns)
474 {
475         kfree(ns->buf.byte);
476         vfree(ns->mem.byte);
477
478         return;
479 }
480
481 /*
482  * Returns the string representation of 'state' state.
483  */
484 static char *
485 get_state_name(uint32_t state)
486 {
487         switch (NS_STATE(state)) {
488                 case STATE_CMD_READ0:
489                         return "STATE_CMD_READ0";
490                 case STATE_CMD_READ1:
491                         return "STATE_CMD_READ1";
492                 case STATE_CMD_PAGEPROG:
493                         return "STATE_CMD_PAGEPROG";
494                 case STATE_CMD_READOOB:
495                         return "STATE_CMD_READOOB";
496                 case STATE_CMD_READSTART:
497                         return "STATE_CMD_READSTART";
498                 case STATE_CMD_ERASE1:
499                         return "STATE_CMD_ERASE1";
500                 case STATE_CMD_STATUS:
501                         return "STATE_CMD_STATUS";
502                 case STATE_CMD_STATUS_M:
503                         return "STATE_CMD_STATUS_M";
504                 case STATE_CMD_SEQIN:
505                         return "STATE_CMD_SEQIN";
506                 case STATE_CMD_READID:
507                         return "STATE_CMD_READID";
508                 case STATE_CMD_ERASE2:
509                         return "STATE_CMD_ERASE2";
510                 case STATE_CMD_RESET:
511                         return "STATE_CMD_RESET";
512                 case STATE_ADDR_PAGE:
513                         return "STATE_ADDR_PAGE";
514                 case STATE_ADDR_SEC:
515                         return "STATE_ADDR_SEC";
516                 case STATE_ADDR_ZERO:
517                         return "STATE_ADDR_ZERO";
518                 case STATE_DATAIN:
519                         return "STATE_DATAIN";
520                 case STATE_DATAOUT:
521                         return "STATE_DATAOUT";
522                 case STATE_DATAOUT_ID:
523                         return "STATE_DATAOUT_ID";
524                 case STATE_DATAOUT_STATUS:
525                         return "STATE_DATAOUT_STATUS";
526                 case STATE_DATAOUT_STATUS_M:
527                         return "STATE_DATAOUT_STATUS_M";
528                 case STATE_READY:
529                         return "STATE_READY";
530                 case STATE_UNKNOWN:
531                         return "STATE_UNKNOWN";
532         }
533
534         NS_ERR("get_state_name: unknown state, BUG\n");
535         return NULL;
536 }
537
538 /*
539  * Check if command is valid.
540  *
541  * RETURNS: 1 if wrong command, 0 if right.
542  */
543 static int
544 check_command(int cmd)
545 {
546         switch (cmd) {
547
548         case NAND_CMD_READ0:
549         case NAND_CMD_READSTART:
550         case NAND_CMD_PAGEPROG:
551         case NAND_CMD_READOOB:
552         case NAND_CMD_ERASE1:
553         case NAND_CMD_STATUS:
554         case NAND_CMD_SEQIN:
555         case NAND_CMD_READID:
556         case NAND_CMD_ERASE2:
557         case NAND_CMD_RESET:
558         case NAND_CMD_READ1:
559                 return 0;
560
561         case NAND_CMD_STATUS_MULTI:
562         default:
563                 return 1;
564         }
565 }
566
567 /*
568  * Returns state after command is accepted by command number.
569  */
570 static uint32_t
571 get_state_by_command(unsigned command)
572 {
573         switch (command) {
574                 case NAND_CMD_READ0:
575                         return STATE_CMD_READ0;
576                 case NAND_CMD_READ1:
577                         return STATE_CMD_READ1;
578                 case NAND_CMD_PAGEPROG:
579                         return STATE_CMD_PAGEPROG;
580                 case NAND_CMD_READSTART:
581                         return STATE_CMD_READSTART;
582                 case NAND_CMD_READOOB:
583                         return STATE_CMD_READOOB;
584                 case NAND_CMD_ERASE1:
585                         return STATE_CMD_ERASE1;
586                 case NAND_CMD_STATUS:
587                         return STATE_CMD_STATUS;
588                 case NAND_CMD_STATUS_MULTI:
589                         return STATE_CMD_STATUS_M;
590                 case NAND_CMD_SEQIN:
591                         return STATE_CMD_SEQIN;
592                 case NAND_CMD_READID:
593                         return STATE_CMD_READID;
594                 case NAND_CMD_ERASE2:
595                         return STATE_CMD_ERASE2;
596                 case NAND_CMD_RESET:
597                         return STATE_CMD_RESET;
598         }
599
600         NS_ERR("get_state_by_command: unknown command, BUG\n");
601         return 0;
602 }
603
604 /*
605  * Move an address byte to the correspondent internal register.
606  */
607 static inline void
608 accept_addr_byte(struct nandsim *ns, u_char bt)
609 {
610         uint byte = (uint)bt;
611
612         if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
613                 ns->regs.column |= (byte << 8 * ns->regs.count);
614         else {
615                 ns->regs.row |= (byte << 8 * (ns->regs.count -
616                                                 ns->geom.pgaddrbytes +
617                                                 ns->geom.secaddrbytes));
618         }
619
620         return;
621 }
622
623 /*
624  * Switch to STATE_READY state.
625  */
626 static inline void
627 switch_to_ready_state(struct nandsim *ns, u_char status)
628 {
629         NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
630
631         ns->state       = STATE_READY;
632         ns->nxstate     = STATE_UNKNOWN;
633         ns->op          = NULL;
634         ns->npstates    = 0;
635         ns->stateidx    = 0;
636         ns->regs.num    = 0;
637         ns->regs.count  = 0;
638         ns->regs.off    = 0;
639         ns->regs.row    = 0;
640         ns->regs.column = 0;
641         ns->regs.status = status;
642 }
643
644 /*
645  * If the operation isn't known yet, try to find it in the global array
646  * of supported operations.
647  *
648  * Operation can be unknown because of the following.
649  *   1. New command was accepted and this is the firs call to find the
650  *      correspondent states chain. In this case ns->npstates = 0;
651  *   2. There is several operations which begin with the same command(s)
652  *      (for example program from the second half and read from the
653  *      second half operations both begin with the READ1 command). In this
654  *      case the ns->pstates[] array contains previous states.
655  *
656  * Thus, the function tries to find operation containing the following
657  * states (if the 'flag' parameter is 0):
658  *    ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
659  *
660  * If (one and only one) matching operation is found, it is accepted (
661  * ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
662  * zeroed).
663  *
664  * If there are several maches, the current state is pushed to the
665  * ns->pstates.
666  *
667  * The operation can be unknown only while commands are input to the chip.
668  * As soon as address command is accepted, the operation must be known.
669  * In such situation the function is called with 'flag' != 0, and the
670  * operation is searched using the following pattern:
671  *     ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
672  *
673  * It is supposed that this pattern must either match one operation on
674  * none. There can't be ambiguity in that case.
675  *
676  * If no matches found, the functions does the following:
677  *   1. if there are saved states present, try to ignore them and search
678  *      again only using the last command. If nothing was found, switch
679  *      to the STATE_READY state.
680  *   2. if there are no saved states, switch to the STATE_READY state.
681  *
682  * RETURNS: -2 - no matched operations found.
683  *          -1 - several matches.
684  *           0 - operation is found.
685  */
686 static int
687 find_operation(struct nandsim *ns, uint32_t flag)
688 {
689         int opsfound = 0;
690         int i, j, idx = 0;
691
692         for (i = 0; i < NS_OPER_NUM; i++) {
693
694                 int found = 1;
695
696                 if (!(ns->options & ops[i].reqopts))
697                         /* Ignore operations we can't perform */
698                         continue;
699
700                 if (flag) {
701                         if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
702                                 continue;
703                 } else {
704                         if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
705                                 continue;
706                 }
707
708                 for (j = 0; j < ns->npstates; j++)
709                         if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
710                                 && (ns->options & ops[idx].reqopts)) {
711                                 found = 0;
712                                 break;
713                         }
714
715                 if (found) {
716                         idx = i;
717                         opsfound += 1;
718                 }
719         }
720
721         if (opsfound == 1) {
722                 /* Exact match */
723                 ns->op = &ops[idx].states[0];
724                 if (flag) {
725                         /*
726                          * In this case the find_operation function was
727                          * called when address has just began input. But it isn't
728                          * yet fully input and the current state must
729                          * not be one of STATE_ADDR_*, but the STATE_ADDR_*
730                          * state must be the next state (ns->nxstate).
731                          */
732                         ns->stateidx = ns->npstates - 1;
733                 } else {
734                         ns->stateidx = ns->npstates;
735                 }
736                 ns->npstates = 0;
737                 ns->state = ns->op[ns->stateidx];
738                 ns->nxstate = ns->op[ns->stateidx + 1];
739                 NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
740                                 idx, get_state_name(ns->state), get_state_name(ns->nxstate));
741                 return 0;
742         }
743
744         if (opsfound == 0) {
745                 /* Nothing was found. Try to ignore previous commands (if any) and search again */
746                 if (ns->npstates != 0) {
747                         NS_DBG("find_operation: no operation found, try again with state %s\n",
748                                         get_state_name(ns->state));
749                         ns->npstates = 0;
750                         return find_operation(ns, 0);
751
752                 }
753                 NS_DBG("find_operation: no operations found\n");
754                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
755                 return -2;
756         }
757
758         if (flag) {
759                 /* This shouldn't happen */
760                 NS_DBG("find_operation: BUG, operation must be known if address is input\n");
761                 return -2;
762         }
763
764         NS_DBG("find_operation: there is still ambiguity\n");
765
766         ns->pstates[ns->npstates++] = ns->state;
767
768         return -1;
769 }
770
771 /*
772  * If state has any action bit, perform this action.
773  *
774  * RETURNS: 0 if success, -1 if error.
775  */
776 static int
777 do_state_action(struct nandsim *ns, uint32_t action)
778 {
779         int i, num;
780         int busdiv = ns->busw == 8 ? 1 : 2;
781
782         action &= ACTION_MASK;
783
784         /* Check that page address input is correct */
785         if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
786                 NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
787                 return -1;
788         }
789
790         switch (action) {
791
792         case ACTION_CPY:
793                 /*
794                  * Copy page data to the internal buffer.
795                  */
796
797                 /* Column shouldn't be very large */
798                 if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
799                         NS_ERR("do_state_action: column number is too large\n");
800                         break;
801                 }
802                 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
803                 memcpy(ns->buf.byte, ns->mem.byte + NS_RAW_OFFSET(ns) + ns->regs.off, num);
804
805                 NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
806                         num, NS_RAW_OFFSET(ns) + ns->regs.off);
807
808                 if (ns->regs.off == 0)
809                         NS_LOG("read page %d\n", ns->regs.row);
810                 else if (ns->regs.off < ns->geom.pgsz)
811                         NS_LOG("read page %d (second half)\n", ns->regs.row);
812                 else
813                         NS_LOG("read OOB of page %d\n", ns->regs.row);
814
815                 NS_UDELAY(access_delay);
816                 NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
817
818                 break;
819
820         case ACTION_SECERASE:
821                 /*
822                  * Erase sector.
823                  */
824
825                 if (ns->lines.wp) {
826                         NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
827                         return -1;
828                 }
829
830                 if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
831                         || (ns->regs.row & ~(ns->geom.secsz - 1))) {
832                         NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
833                         return -1;
834                 }
835
836                 ns->regs.row = (ns->regs.row <<
837                                 8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
838                 ns->regs.column = 0;
839
840                 NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
841                                 ns->regs.row, NS_RAW_OFFSET(ns));
842                 NS_LOG("erase sector %d\n", ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift));
843
844                 memset(ns->mem.byte + NS_RAW_OFFSET(ns), 0xFF, ns->geom.secszoob);
845
846                 NS_MDELAY(erase_delay);
847
848                 break;
849
850         case ACTION_PRGPAGE:
851                 /*
852                  * Programm page - move internal buffer data to the page.
853                  */
854
855                 if (ns->lines.wp) {
856                         NS_WARN("do_state_action: device is write-protected, programm\n");
857                         return -1;
858                 }
859
860                 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
861                 if (num != ns->regs.count) {
862                         NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
863                                         ns->regs.count, num);
864                         return -1;
865                 }
866
867                 for (i = 0; i < num; i++)
868                         ns->mem.byte[NS_RAW_OFFSET(ns) + ns->regs.off + i] &= ns->buf.byte[i];
869
870                 NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
871                         num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
872                 NS_LOG("programm page %d\n", ns->regs.row);
873
874                 NS_UDELAY(programm_delay);
875                 NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
876
877                 break;
878
879         case ACTION_ZEROOFF:
880                 NS_DBG("do_state_action: set internal offset to 0\n");
881                 ns->regs.off = 0;
882                 break;
883
884         case ACTION_HALFOFF:
885                 if (!(ns->options & OPT_PAGE512_8BIT)) {
886                         NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
887                                 "byte page size 8x chips\n");
888                         return -1;
889                 }
890                 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
891                 ns->regs.off = ns->geom.pgsz/2;
892                 break;
893
894         case ACTION_OOBOFF:
895                 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
896                 ns->regs.off = ns->geom.pgsz;
897                 break;
898
899         default:
900                 NS_DBG("do_state_action: BUG! unknown action\n");
901         }
902
903         return 0;
904 }
905
906 /*
907  * Switch simulator's state.
908  */
909 static void
910 switch_state(struct nandsim *ns)
911 {
912         if (ns->op) {
913                 /*
914                  * The current operation have already been identified.
915                  * Just follow the states chain.
916                  */
917
918                 ns->stateidx += 1;
919                 ns->state = ns->nxstate;
920                 ns->nxstate = ns->op[ns->stateidx + 1];
921
922                 NS_DBG("switch_state: operation is known, switch to the next state, "
923                         "state: %s, nxstate: %s\n",
924                         get_state_name(ns->state), get_state_name(ns->nxstate));
925
926                 /* See, whether we need to do some action */
927                 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
928                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
929                         return;
930                 }
931
932         } else {
933                 /*
934                  * We don't yet know which operation we perform.
935                  * Try to identify it.
936                  */
937
938                 /*
939                  *  The only event causing the switch_state function to
940                  *  be called with yet unknown operation is new command.
941                  */
942                 ns->state = get_state_by_command(ns->regs.command);
943
944                 NS_DBG("switch_state: operation is unknown, try to find it\n");
945
946                 if (find_operation(ns, 0) != 0)
947                         return;
948
949                 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
950                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
951                         return;
952                 }
953         }
954
955         /* For 16x devices column means the page offset in words */
956         if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
957                 NS_DBG("switch_state: double the column number for 16x device\n");
958                 ns->regs.column <<= 1;
959         }
960
961         if (NS_STATE(ns->nxstate) == STATE_READY) {
962                 /*
963                  * The current state is the last. Return to STATE_READY
964                  */
965
966                 u_char status = NS_STATUS_OK(ns);
967
968                 /* In case of data states, see if all bytes were input/output */
969                 if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
970                         && ns->regs.count != ns->regs.num) {
971                         NS_WARN("switch_state: not all bytes were processed, %d left\n",
972                                         ns->regs.num - ns->regs.count);
973                         status = NS_STATUS_FAILED(ns);
974                 }
975
976                 NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
977
978                 switch_to_ready_state(ns, status);
979
980                 return;
981         } else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
982                 /*
983                  * If the next state is data input/output, switch to it now
984                  */
985
986                 ns->state      = ns->nxstate;
987                 ns->nxstate    = ns->op[++ns->stateidx + 1];
988                 ns->regs.num   = ns->regs.count = 0;
989
990                 NS_DBG("switch_state: the next state is data I/O, switch, "
991                         "state: %s, nxstate: %s\n",
992                         get_state_name(ns->state), get_state_name(ns->nxstate));
993
994                 /*
995                  * Set the internal register to the count of bytes which
996                  * are expected to be input or output
997                  */
998                 switch (NS_STATE(ns->state)) {
999                         case STATE_DATAIN:
1000                         case STATE_DATAOUT:
1001                                 ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1002                                 break;
1003
1004                         case STATE_DATAOUT_ID:
1005                                 ns->regs.num = ns->geom.idbytes;
1006                                 break;
1007
1008                         case STATE_DATAOUT_STATUS:
1009                         case STATE_DATAOUT_STATUS_M:
1010                                 ns->regs.count = ns->regs.num = 0;
1011                                 break;
1012
1013                         default:
1014                                 NS_ERR("switch_state: BUG! unknown data state\n");
1015                 }
1016
1017         } else if (ns->nxstate & STATE_ADDR_MASK) {
1018                 /*
1019                  * If the next state is address input, set the internal
1020                  * register to the number of expected address bytes
1021                  */
1022
1023                 ns->regs.count = 0;
1024
1025                 switch (NS_STATE(ns->nxstate)) {
1026                         case STATE_ADDR_PAGE:
1027                                 ns->regs.num = ns->geom.pgaddrbytes;
1028
1029                                 break;
1030                         case STATE_ADDR_SEC:
1031                                 ns->regs.num = ns->geom.secaddrbytes;
1032                                 break;
1033
1034                         case STATE_ADDR_ZERO:
1035                                 ns->regs.num = 1;
1036                                 break;
1037
1038                         default:
1039                                 NS_ERR("switch_state: BUG! unknown address state\n");
1040                 }
1041         } else {
1042                 /*
1043                  * Just reset internal counters.
1044                  */
1045
1046                 ns->regs.num = 0;
1047                 ns->regs.count = 0;
1048         }
1049 }
1050
1051 static u_char
1052 ns_nand_read_byte(struct mtd_info *mtd)
1053 {
1054         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1055         u_char outb = 0x00;
1056
1057         /* Sanity and correctness checks */
1058         if (!ns->lines.ce) {
1059                 NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
1060                 return outb;
1061         }
1062         if (ns->lines.ale || ns->lines.cle) {
1063                 NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
1064                 return outb;
1065         }
1066         if (!(ns->state & STATE_DATAOUT_MASK)) {
1067                 NS_WARN("read_byte: unexpected data output cycle, state is %s "
1068                         "return %#x\n", get_state_name(ns->state), (uint)outb);
1069                 return outb;
1070         }
1071
1072         /* Status register may be read as many times as it is wanted */
1073         if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
1074                 NS_DBG("read_byte: return %#x status\n", ns->regs.status);
1075                 return ns->regs.status;
1076         }
1077
1078         /* Check if there is any data in the internal buffer which may be read */
1079         if (ns->regs.count == ns->regs.num) {
1080                 NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
1081                 return outb;
1082         }
1083
1084         switch (NS_STATE(ns->state)) {
1085                 case STATE_DATAOUT:
1086                         if (ns->busw == 8) {
1087                                 outb = ns->buf.byte[ns->regs.count];
1088                                 ns->regs.count += 1;
1089                         } else {
1090                                 outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
1091                                 ns->regs.count += 2;
1092                         }
1093                         break;
1094                 case STATE_DATAOUT_ID:
1095                         NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
1096                         outb = ns->ids[ns->regs.count];
1097                         ns->regs.count += 1;
1098                         break;
1099                 default:
1100                         BUG();
1101         }
1102
1103         if (ns->regs.count == ns->regs.num) {
1104                 NS_DBG("read_byte: all bytes were read\n");
1105
1106                 /*
1107                  * The OPT_AUTOINCR allows to read next conseqitive pages without
1108                  * new read operation cycle.
1109                  */
1110                 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
1111                         ns->regs.count = 0;
1112                         if (ns->regs.row + 1 < ns->geom.pgnum)
1113                                 ns->regs.row += 1;
1114                         NS_DBG("read_byte: switch to the next page (%#x)\n", ns->regs.row);
1115                         do_state_action(ns, ACTION_CPY);
1116                 }
1117                 else if (NS_STATE(ns->nxstate) == STATE_READY)
1118                         switch_state(ns);
1119
1120         }
1121
1122         return outb;
1123 }
1124
1125 static void
1126 ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
1127 {
1128         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1129
1130         /* Sanity and correctness checks */
1131         if (!ns->lines.ce) {
1132                 NS_ERR("write_byte: chip is disabled, ignore write\n");
1133                 return;
1134         }
1135         if (ns->lines.ale && ns->lines.cle) {
1136                 NS_ERR("write_byte: ALE and CLE pins are high simultaneously, ignore write\n");
1137                 return;
1138         }
1139
1140         if (ns->lines.cle == 1) {
1141                 /*
1142                  * The byte written is a command.
1143                  */
1144
1145                 if (byte == NAND_CMD_RESET) {
1146                         NS_LOG("reset chip\n");
1147                         switch_to_ready_state(ns, NS_STATUS_OK(ns));
1148                         return;
1149                 }
1150
1151                 /*
1152                  * Chip might still be in STATE_DATAOUT
1153                  * (if OPT_AUTOINCR feature is supported), STATE_DATAOUT_STATUS or
1154                  * STATE_DATAOUT_STATUS_M state. If so, switch state.
1155                  */
1156                 if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS
1157                         || NS_STATE(ns->state) == STATE_DATAOUT_STATUS_M
1158                         || ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT))
1159                         switch_state(ns);
1160
1161                 /* Check if chip is expecting command */
1162                 if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
1163                         /*
1164                          * We are in situation when something else (not command)
1165                          * was expected but command was input. In this case ignore
1166                          * previous command(s)/state(s) and accept the last one.
1167                          */
1168                         NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
1169                                 "ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
1170                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1171                 }
1172
1173                 /* Check that the command byte is correct */
1174                 if (check_command(byte)) {
1175                         NS_ERR("write_byte: unknown command %#x\n", (uint)byte);
1176                         return;
1177                 }
1178
1179                 NS_DBG("command byte corresponding to %s state accepted\n",
1180                         get_state_name(get_state_by_command(byte)));
1181                 ns->regs.command = byte;
1182                 switch_state(ns);
1183
1184         } else if (ns->lines.ale == 1) {
1185                 /*
1186                  * The byte written is an address.
1187                  */
1188
1189                 if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
1190
1191                         NS_DBG("write_byte: operation isn't known yet, identify it\n");
1192
1193                         if (find_operation(ns, 1) < 0)
1194                                 return;
1195
1196                         if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1197                                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1198                                 return;
1199                         }
1200
1201                         ns->regs.count = 0;
1202                         switch (NS_STATE(ns->nxstate)) {
1203                                 case STATE_ADDR_PAGE:
1204                                         ns->regs.num = ns->geom.pgaddrbytes;
1205                                         break;
1206                                 case STATE_ADDR_SEC:
1207                                         ns->regs.num = ns->geom.secaddrbytes;
1208                                         break;
1209                                 case STATE_ADDR_ZERO:
1210                                         ns->regs.num = 1;
1211                                         break;
1212                                 default:
1213                                         BUG();
1214                         }
1215                 }
1216
1217                 /* Check that chip is expecting address */
1218                 if (!(ns->nxstate & STATE_ADDR_MASK)) {
1219                         NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
1220                                 "switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
1221                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1222                         return;
1223                 }
1224
1225                 /* Check if this is expected byte */
1226                 if (ns->regs.count == ns->regs.num) {
1227                         NS_ERR("write_byte: no more address bytes expected\n");
1228                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1229                         return;
1230                 }
1231
1232                 accept_addr_byte(ns, byte);
1233
1234                 ns->regs.count += 1;
1235
1236                 NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
1237                                 (uint)byte, ns->regs.count, ns->regs.num);
1238
1239                 if (ns->regs.count == ns->regs.num) {
1240                         NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
1241                         switch_state(ns);
1242                 }
1243
1244         } else {
1245                 /*
1246                  * The byte written is an input data.
1247                  */
1248
1249                 /* Check that chip is expecting data input */
1250                 if (!(ns->state & STATE_DATAIN_MASK)) {
1251                         NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
1252                                 "switch to %s\n", (uint)byte,
1253                                 get_state_name(ns->state), get_state_name(STATE_READY));
1254                         switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1255                         return;
1256                 }
1257
1258                 /* Check if this is expected byte */
1259                 if (ns->regs.count == ns->regs.num) {
1260                         NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
1261                                         ns->regs.num);
1262                         return;
1263                 }
1264
1265                 if (ns->busw == 8) {
1266                         ns->buf.byte[ns->regs.count] = byte;
1267                         ns->regs.count += 1;
1268                 } else {
1269                         ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
1270                         ns->regs.count += 2;
1271                 }
1272         }
1273
1274         return;
1275 }
1276
1277 static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
1278 {
1279         struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
1280
1281         ns->lines.cle = bitmask & NAND_CLE ? 1 : 0;
1282         ns->lines.ale = bitmask & NAND_ALE ? 1 : 0;
1283         ns->lines.ce = bitmask & NAND_NCE ? 1 : 0;
1284
1285         if (cmd != NAND_CMD_NONE)
1286                 ns_nand_write_byte(mtd, cmd);
1287 }
1288
1289 static int
1290 ns_device_ready(struct mtd_info *mtd)
1291 {
1292         NS_DBG("device_ready\n");
1293         return 1;
1294 }
1295
1296 static uint16_t
1297 ns_nand_read_word(struct mtd_info *mtd)
1298 {
1299         struct nand_chip *chip = (struct nand_chip *)mtd->priv;
1300
1301         NS_DBG("read_word\n");
1302
1303         return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
1304 }
1305
1306 static void
1307 ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
1308 {
1309         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1310
1311         /* Check that chip is expecting data input */
1312         if (!(ns->state & STATE_DATAIN_MASK)) {
1313                 NS_ERR("write_buf: data input isn't expected, state is %s, "
1314                         "switch to STATE_READY\n", get_state_name(ns->state));
1315                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1316                 return;
1317         }
1318
1319         /* Check if these are expected bytes */
1320         if (ns->regs.count + len > ns->regs.num) {
1321                 NS_ERR("write_buf: too many input bytes\n");
1322                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1323                 return;
1324         }
1325
1326         memcpy(ns->buf.byte + ns->regs.count, buf, len);
1327         ns->regs.count += len;
1328
1329         if (ns->regs.count == ns->regs.num) {
1330                 NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
1331         }
1332 }
1333
1334 static void
1335 ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
1336 {
1337         struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1338
1339         /* Sanity and correctness checks */
1340         if (!ns->lines.ce) {
1341                 NS_ERR("read_buf: chip is disabled\n");
1342                 return;
1343         }
1344         if (ns->lines.ale || ns->lines.cle) {
1345                 NS_ERR("read_buf: ALE or CLE pin is high\n");
1346                 return;
1347         }
1348         if (!(ns->state & STATE_DATAOUT_MASK)) {
1349                 NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
1350                         get_state_name(ns->state));
1351                 return;
1352         }
1353
1354         if (NS_STATE(ns->state) != STATE_DATAOUT) {
1355                 int i;
1356
1357                 for (i = 0; i < len; i++)
1358                         buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);
1359
1360                 return;
1361         }
1362
1363         /* Check if these are expected bytes */
1364         if (ns->regs.count + len > ns->regs.num) {
1365                 NS_ERR("read_buf: too many bytes to read\n");
1366                 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1367                 return;
1368         }
1369
1370         memcpy(buf, ns->buf.byte + ns->regs.count, len);
1371         ns->regs.count += len;
1372
1373         if (ns->regs.count == ns->regs.num) {
1374                 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
1375                         ns->regs.count = 0;
1376                         if (ns->regs.row + 1 < ns->geom.pgnum)
1377                                 ns->regs.row += 1;
1378                         NS_DBG("read_buf: switch to the next page (%#x)\n", ns->regs.row);
1379                         do_state_action(ns, ACTION_CPY);
1380                 }
1381                 else if (NS_STATE(ns->nxstate) == STATE_READY)
1382                         switch_state(ns);
1383         }
1384
1385         return;
1386 }
1387
1388 static int
1389 ns_nand_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
1390 {
1391         ns_nand_read_buf(mtd, (u_char *)&ns_verify_buf[0], len);
1392
1393         if (!memcmp(buf, &ns_verify_buf[0], len)) {
1394                 NS_DBG("verify_buf: the buffer is OK\n");
1395                 return 0;
1396         } else {
1397                 NS_DBG("verify_buf: the buffer is wrong\n");
1398                 return -EFAULT;
1399         }
1400 }
1401
1402 /*
1403  * Module initialization function
1404  */
1405 static int __init ns_init_module(void)
1406 {
1407         struct nand_chip *chip;
1408         struct nandsim *nand;
1409         int retval = -ENOMEM;
1410
1411         if (bus_width != 8 && bus_width != 16) {
1412                 NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
1413                 return -EINVAL;
1414         }
1415
1416         /* Allocate and initialize mtd_info, nand_chip and nandsim structures */
1417         nsmtd = kmalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip)
1418                                 + sizeof(struct nandsim), GFP_KERNEL);
1419         if (!nsmtd) {
1420                 NS_ERR("unable to allocate core structures.\n");
1421                 return -ENOMEM;
1422         }
1423         memset(nsmtd, 0, sizeof(struct mtd_info) + sizeof(struct nand_chip) +
1424                         sizeof(struct nandsim));
1425         chip        = (struct nand_chip *)(nsmtd + 1);
1426         nsmtd->priv = (void *)chip;
1427         nand        = (struct nandsim *)(chip + 1);
1428         chip->priv  = (void *)nand;
1429
1430         /*
1431          * Register simulator's callbacks.
1432          */
1433         chip->cmd_ctrl   = ns_hwcontrol;
1434         chip->read_byte  = ns_nand_read_byte;
1435         chip->dev_ready  = ns_device_ready;
1436         chip->write_buf  = ns_nand_write_buf;
1437         chip->read_buf   = ns_nand_read_buf;
1438         chip->verify_buf = ns_nand_verify_buf;
1439         chip->read_word  = ns_nand_read_word;
1440         chip->ecc.mode   = NAND_ECC_SOFT;
1441         chip->options   |= NAND_SKIP_BBTSCAN;
1442
1443         /*
1444          * Perform minimum nandsim structure initialization to handle
1445          * the initial ID read command correctly
1446          */
1447         if (third_id_byte != 0xFF || fourth_id_byte != 0xFF)
1448                 nand->geom.idbytes = 4;
1449         else
1450                 nand->geom.idbytes = 2;
1451         nand->regs.status = NS_STATUS_OK(nand);
1452         nand->nxstate = STATE_UNKNOWN;
1453         nand->options |= OPT_PAGE256; /* temporary value */
1454         nand->ids[0] = first_id_byte;
1455         nand->ids[1] = second_id_byte;
1456         nand->ids[2] = third_id_byte;
1457         nand->ids[3] = fourth_id_byte;
1458         if (bus_width == 16) {
1459                 nand->busw = 16;
1460                 chip->options |= NAND_BUSWIDTH_16;
1461         }
1462
1463         nsmtd->owner = THIS_MODULE;
1464
1465         if ((retval = nand_scan(nsmtd, 1)) != 0) {
1466                 NS_ERR("can't register NAND Simulator\n");
1467                 if (retval > 0)
1468                         retval = -ENXIO;
1469                 goto error;
1470         }
1471
1472         if ((retval = init_nandsim(nsmtd)) != 0) {
1473                 NS_ERR("scan_bbt: can't initialize the nandsim structure\n");
1474                 goto error;
1475         }
1476
1477         if ((retval = nand_default_bbt(nsmtd)) != 0) {
1478                 free_nandsim(nand);
1479                 goto error;
1480         }
1481
1482         /* Register NAND as one big partition */
1483         add_mtd_partitions(nsmtd, &nand->part, 1);
1484
1485         return 0;
1486
1487 error:
1488         kfree(nsmtd);
1489
1490         return retval;
1491 }
1492
1493 module_init(ns_init_module);
1494
1495 /*
1496  * Module clean-up function
1497  */
1498 static void __exit ns_cleanup_module(void)
1499 {
1500         struct nandsim *ns = (struct nandsim *)(((struct nand_chip *)nsmtd->priv)->priv);
1501
1502         free_nandsim(ns);    /* Free nandsim private resources */
1503         nand_release(nsmtd); /* Unregisterd drived */
1504         kfree(nsmtd);        /* Free other structures */
1505 }
1506
1507 module_exit(ns_cleanup_module);
1508
1509 MODULE_LICENSE ("GPL");
1510 MODULE_AUTHOR ("Artem B. Bityuckiy");
1511 MODULE_DESCRIPTION ("The NAND flash simulator");
1512