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