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