nandsim.c 67.1 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5
/*
 * NAND flash simulator.
 *
 * Author: Artem B. Bityuckiy <dedekind@oktetlabs.ru>, <dedekind@infradead.org>
 *
6
 * Copyright (C) 2004 Nokia Corporation
L
Linus Torvalds 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 *
 * Note: NS means "NAND Simulator".
 * Note: Input means input TO flash chip, output means output FROM chip.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
 */

#include <linux/init.h>
#include <linux/types.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/vmalloc.h>
31
#include <linux/math64.h>
L
Linus Torvalds 已提交
32 33 34 35 36
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
37
#include <linux/mtd/nand_bch.h>
L
Linus Torvalds 已提交
38 39
#include <linux/mtd/partitions.h>
#include <linux/delay.h>
40
#include <linux/list.h>
41
#include <linux/random.h>
42
#include <linux/sched.h>
43 44
#include <linux/fs.h>
#include <linux/pagemap.h>
45 46
#include <linux/seq_file.h>
#include <linux/debugfs.h>
L
Linus Torvalds 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

/* Default simulator parameters values */
#if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE)  || \
    !defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
    !defined(CONFIG_NANDSIM_THIRD_ID_BYTE)  || \
    !defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
#define CONFIG_NANDSIM_FIRST_ID_BYTE  0x98
#define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
#define CONFIG_NANDSIM_THIRD_ID_BYTE  0xFF /* No byte */
#define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
#endif

#ifndef CONFIG_NANDSIM_ACCESS_DELAY
#define CONFIG_NANDSIM_ACCESS_DELAY 25
#endif
#ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
#define CONFIG_NANDSIM_PROGRAMM_DELAY 200
#endif
#ifndef CONFIG_NANDSIM_ERASE_DELAY
#define CONFIG_NANDSIM_ERASE_DELAY 2
#endif
#ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
#define CONFIG_NANDSIM_OUTPUT_CYCLE 40
#endif
#ifndef CONFIG_NANDSIM_INPUT_CYCLE
#define CONFIG_NANDSIM_INPUT_CYCLE  50
#endif
#ifndef CONFIG_NANDSIM_BUS_WIDTH
#define CONFIG_NANDSIM_BUS_WIDTH  8
#endif
#ifndef CONFIG_NANDSIM_DO_DELAYS
#define CONFIG_NANDSIM_DO_DELAYS  0
#endif
#ifndef CONFIG_NANDSIM_LOG
#define CONFIG_NANDSIM_LOG        0
#endif
#ifndef CONFIG_NANDSIM_DBG
#define CONFIG_NANDSIM_DBG        0
#endif
86 87 88
#ifndef CONFIG_NANDSIM_MAX_PARTS
#define CONFIG_NANDSIM_MAX_PARTS  32
#endif
L
Linus Torvalds 已提交
89 90 91 92 93 94 95 96 97 98

static uint access_delay   = CONFIG_NANDSIM_ACCESS_DELAY;
static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
static uint erase_delay    = CONFIG_NANDSIM_ERASE_DELAY;
static uint output_cycle   = CONFIG_NANDSIM_OUTPUT_CYCLE;
static uint input_cycle    = CONFIG_NANDSIM_INPUT_CYCLE;
static uint bus_width      = CONFIG_NANDSIM_BUS_WIDTH;
static uint do_delays      = CONFIG_NANDSIM_DO_DELAYS;
static uint log            = CONFIG_NANDSIM_LOG;
static uint dbg            = CONFIG_NANDSIM_DBG;
99
static unsigned long parts[CONFIG_NANDSIM_MAX_PARTS];
100
static unsigned int parts_num;
101 102 103 104 105
static char *badblocks = NULL;
static char *weakblocks = NULL;
static char *weakpages = NULL;
static unsigned int bitflips = 0;
static char *gravepages = NULL;
106
static unsigned int overridesize = 0;
107
static char *cache_file = NULL;
108
static unsigned int bbt;
109
static unsigned int bch;
110 111 112 113 114 115 116
static u_char id_bytes[8] = {
	[0] = CONFIG_NANDSIM_FIRST_ID_BYTE,
	[1] = CONFIG_NANDSIM_SECOND_ID_BYTE,
	[2] = CONFIG_NANDSIM_THIRD_ID_BYTE,
	[3] = CONFIG_NANDSIM_FOURTH_ID_BYTE,
	[4 ... 7] = 0xFF,
};
L
Linus Torvalds 已提交
117

118 119 120 121 122
module_param_array(id_bytes, byte, NULL, 0400);
module_param_named(first_id_byte, id_bytes[0], byte, 0400);
module_param_named(second_id_byte, id_bytes[1], byte, 0400);
module_param_named(third_id_byte, id_bytes[2], byte, 0400);
module_param_named(fourth_id_byte, id_bytes[3], byte, 0400);
L
Linus Torvalds 已提交
123 124 125 126 127 128 129 130 131
module_param(access_delay,   uint, 0400);
module_param(programm_delay, uint, 0400);
module_param(erase_delay,    uint, 0400);
module_param(output_cycle,   uint, 0400);
module_param(input_cycle,    uint, 0400);
module_param(bus_width,      uint, 0400);
module_param(do_delays,      uint, 0400);
module_param(log,            uint, 0400);
module_param(dbg,            uint, 0400);
132
module_param_array(parts, ulong, &parts_num, 0400);
133 134 135 136 137
module_param(badblocks,      charp, 0400);
module_param(weakblocks,     charp, 0400);
module_param(weakpages,      charp, 0400);
module_param(bitflips,       uint, 0400);
module_param(gravepages,     charp, 0400);
138
module_param(overridesize,   uint, 0400);
139
module_param(cache_file,     charp, 0400);
140
module_param(bbt,	     uint, 0400);
141
module_param(bch,	     uint, 0400);
L
Linus Torvalds 已提交
142

143 144 145 146 147
MODULE_PARM_DESC(id_bytes,       "The ID bytes returned by NAND Flash 'read ID' command");
MODULE_PARM_DESC(first_id_byte,  "The first byte returned by NAND Flash 'read ID' command (manufacturer ID) (obsolete)");
MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID) (obsolete)");
MODULE_PARM_DESC(third_id_byte,  "The third byte returned by NAND Flash 'read ID' command (obsolete)");
MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command (obsolete)");
148
MODULE_PARM_DESC(access_delay,   "Initial page access delay (microseconds)");
L
Linus Torvalds 已提交
149 150
MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
MODULE_PARM_DESC(erase_delay,    "Sector erase delay (milliseconds)");
A
Andrey Yurovsky 已提交
151 152
MODULE_PARM_DESC(output_cycle,   "Word output (from flash) time (nanoseconds)");
MODULE_PARM_DESC(input_cycle,    "Word input (to flash) time (nanoseconds)");
L
Linus Torvalds 已提交
153 154 155 156
MODULE_PARM_DESC(bus_width,      "Chip's bus width (8- or 16-bit)");
MODULE_PARM_DESC(do_delays,      "Simulate NAND delays using busy-waits if not zero");
MODULE_PARM_DESC(log,            "Perform logging if not zero");
MODULE_PARM_DESC(dbg,            "Output debug information if not zero");
157
MODULE_PARM_DESC(parts,          "Partition sizes (in erase blocks) separated by commas");
158 159 160 161 162 163 164 165 166 167 168 169
/* Page and erase block positions for the following parameters are independent of any partitions */
MODULE_PARM_DESC(badblocks,      "Erase blocks that are initially marked bad, separated by commas");
MODULE_PARM_DESC(weakblocks,     "Weak erase blocks [: remaining erase cycles (defaults to 3)]"
				 " separated by commas e.g. 113:2 means eb 113"
				 " can be erased only twice before failing");
MODULE_PARM_DESC(weakpages,      "Weak pages [: maximum writes (defaults to 3)]"
				 " separated by commas e.g. 1401:2 means page 1401"
				 " can be written only twice before failing");
MODULE_PARM_DESC(bitflips,       "Maximum number of random bit flips per page (zero by default)");
MODULE_PARM_DESC(gravepages,     "Pages that lose data [: maximum reads (defaults to 3)]"
				 " separated by commas e.g. 1401:2 means page 1401"
				 " can be read only twice before failing");
170 171 172
MODULE_PARM_DESC(overridesize,   "Specifies the NAND Flash size overriding the ID bytes. "
				 "The size is specified in erase blocks and as the exponent of a power of two"
				 " e.g. 5 means a size of 32 erase blocks");
173
MODULE_PARM_DESC(cache_file,     "File to use to cache nand pages instead of memory");
174
MODULE_PARM_DESC(bbt,		 "0 OOB, 1 BBT with marker in OOB, 2 BBT with marker in data area");
175 176
MODULE_PARM_DESC(bch,		 "Enable BCH ecc and set how many bits should "
				 "be correctable in 512-byte blocks");
L
Linus Torvalds 已提交
177 178

/* The largest possible page size */
179
#define NS_LARGEST_PAGE_SIZE	4096
180

L
Linus Torvalds 已提交
181 182 183 184 185 186 187 188 189
/* The prefix for simulator output */
#define NS_OUTPUT_PREFIX "[nandsim]"

/* Simulator's output macros (logging, debugging, warning, error) */
#define NS_LOG(args...) \
	do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
#define NS_DBG(args...) \
	do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
#define NS_WARN(args...) \
190
	do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warning: " args); } while(0)
L
Linus Torvalds 已提交
191
#define NS_ERR(args...) \
192
	do { printk(KERN_ERR NS_OUTPUT_PREFIX " error: " args); } while(0)
193 194
#define NS_INFO(args...) \
	do { printk(KERN_INFO NS_OUTPUT_PREFIX " " args); } while(0)
L
Linus Torvalds 已提交
195 196 197 198 199 200

/* Busy-wait delay macros (microseconds, milliseconds) */
#define NS_UDELAY(us) \
        do { if (do_delays) udelay(us); } while(0)
#define NS_MDELAY(us) \
        do { if (do_delays) mdelay(us); } while(0)
201

L
Linus Torvalds 已提交
202 203 204 205 206 207 208
/* Is the nandsim structure initialized ? */
#define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)

/* Good operation completion status */
#define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))

/* Operation failed completion status */
209
#define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
L
Linus Torvalds 已提交
210 211 212

/* Calculate the page offset in flash RAM image by (row, column) address */
#define NS_RAW_OFFSET(ns) \
213
	(((ns)->regs.row * (ns)->geom.pgszoob) + (ns)->regs.column)
214

L
Linus Torvalds 已提交
215 216 217 218 219 220
/* Calculate the OOB offset in flash RAM image by (row, column) address */
#define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)

/* After a command is input, the simulator goes to one of the following states */
#define STATE_CMD_READ0        0x00000001 /* read data from the beginning of page */
#define STATE_CMD_READ1        0x00000002 /* read data from the second half of page */
221
#define STATE_CMD_READSTART    0x00000003 /* read data second command (large page devices) */
222
#define STATE_CMD_PAGEPROG     0x00000004 /* start page program */
L
Linus Torvalds 已提交
223 224 225
#define STATE_CMD_READOOB      0x00000005 /* read OOB area */
#define STATE_CMD_ERASE1       0x00000006 /* sector erase first command */
#define STATE_CMD_STATUS       0x00000007 /* read status */
226
#define STATE_CMD_SEQIN        0x00000009 /* sequential data input */
L
Linus Torvalds 已提交
227 228 229
#define STATE_CMD_READID       0x0000000A /* read ID */
#define STATE_CMD_ERASE2       0x0000000B /* sector erase second command */
#define STATE_CMD_RESET        0x0000000C /* reset */
230 231
#define STATE_CMD_RNDOUT       0x0000000D /* random output command */
#define STATE_CMD_RNDOUTSTART  0x0000000E /* random output start command */
L
Linus Torvalds 已提交
232 233
#define STATE_CMD_MASK         0x0000000F /* command states mask */

J
Joe Perches 已提交
234
/* After an address is input, the simulator goes to one of these states */
L
Linus Torvalds 已提交
235 236
#define STATE_ADDR_PAGE        0x00000010 /* full (row, column) address is accepted */
#define STATE_ADDR_SEC         0x00000020 /* sector address was accepted */
237 238 239
#define STATE_ADDR_COLUMN      0x00000030 /* column address was accepted */
#define STATE_ADDR_ZERO        0x00000040 /* one byte zero address was accepted */
#define STATE_ADDR_MASK        0x00000070 /* address states mask */
L
Linus Torvalds 已提交
240

241
/* During data input/output the simulator is in these states */
L
Linus Torvalds 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
#define STATE_DATAIN           0x00000100 /* waiting for data input */
#define STATE_DATAIN_MASK      0x00000100 /* data input states mask */

#define STATE_DATAOUT          0x00001000 /* waiting for page data output */
#define STATE_DATAOUT_ID       0x00002000 /* waiting for ID bytes output */
#define STATE_DATAOUT_STATUS   0x00003000 /* waiting for status output */
#define STATE_DATAOUT_MASK     0x00007000 /* data output states mask */

/* Previous operation is done, ready to accept new requests */
#define STATE_READY            0x00000000

/* This state is used to mark that the next state isn't known yet */
#define STATE_UNKNOWN          0x10000000

/* Simulator's actions bit masks */
#define ACTION_CPY       0x00100000 /* copy page/OOB to the internal buffer */
258
#define ACTION_PRGPAGE   0x00200000 /* program the internal buffer to flash */
L
Linus Torvalds 已提交
259 260 261 262 263 264
#define ACTION_SECERASE  0x00300000 /* erase sector */
#define ACTION_ZEROOFF   0x00400000 /* don't add any offset to address */
#define ACTION_HALFOFF   0x00500000 /* add to address half of page */
#define ACTION_OOBOFF    0x00600000 /* add to address OOB offset */
#define ACTION_MASK      0x00700000 /* action mask */

265
#define NS_OPER_NUM      13 /* Number of operations supported by the simulator */
L
Linus Torvalds 已提交
266 267 268 269 270 271
#define NS_OPER_STATES   6  /* Maximum number of states in operation */

#define OPT_ANY          0xFFFFFFFF /* any chip supports this operation */
#define OPT_PAGE512      0x00000002 /* 512-byte  page chips */
#define OPT_PAGE2048     0x00000008 /* 2048-byte page chips */
#define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
272 273
#define OPT_PAGE4096     0x00000080 /* 4096-byte page chips */
#define OPT_LARGEPAGE    (OPT_PAGE2048 | OPT_PAGE4096) /* 2048 & 4096-byte page chips */
274
#define OPT_SMALLPAGE    (OPT_PAGE512) /* 512-byte page chips */
L
Linus Torvalds 已提交
275

276
/* Remove action bits from state */
L
Linus Torvalds 已提交
277
#define NS_STATE(x) ((x) & ~ACTION_MASK)
278 279

/*
L
Linus Torvalds 已提交
280
 * Maximum previous states which need to be saved. Currently saving is
281
 * only needed for page program operation with preceded read command
L
Linus Torvalds 已提交
282 283 284 285
 * (which is only valid for 512-byte pages).
 */
#define NS_MAX_PREVSTATES 1

286 287 288
/* Maximum page cache pages needed to read or write a NAND page to the cache_file */
#define NS_MAX_HELD_PAGES 16

289 290 291 292 293
struct nandsim_debug_info {
	struct dentry *dfs_root;
	struct dentry *dfs_wear_report;
};

294 295 296 297 298 299 300 301
/*
 * A union to represent flash memory contents and flash buffer.
 */
union ns_mem {
	u_char *byte;    /* for byte access */
	uint16_t *word;  /* for 16-bit word access */
};

302
/*
L
Linus Torvalds 已提交
303 304 305
 * The structure which describes all the internal simulator data.
 */
struct nandsim {
306
	struct mtd_partition partitions[CONFIG_NANDSIM_MAX_PARTS];
307
	unsigned int nbparts;
L
Linus Torvalds 已提交
308 309

	uint busw;              /* flash chip bus width (8 or 16) */
310
	u_char ids[8];          /* chip's ID bytes */
L
Linus Torvalds 已提交
311 312 313
	uint32_t options;       /* chip's characteristic bits */
	uint32_t state;         /* current chip state */
	uint32_t nxstate;       /* next expected state */
314

L
Linus Torvalds 已提交
315 316 317 318 319
	uint32_t *op;           /* current operation, NULL operations isn't known yet  */
	uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
	uint16_t npstates;      /* number of previous states saved */
	uint16_t stateidx;      /* current state index */

320 321
	/* The simulated NAND flash pages array */
	union ns_mem *pages;
L
Linus Torvalds 已提交
322

A
Alexey Korolev 已提交
323 324 325
	/* Slab allocator for nand pages */
	struct kmem_cache *nand_pages_slab;

L
Linus Torvalds 已提交
326
	/* Internal buffer of page + OOB size bytes */
327
	union ns_mem buf;
L
Linus Torvalds 已提交
328 329

	/* NAND flash "geometry" */
330
	struct {
331
		uint64_t totsz;     /* total flash size, bytes */
L
Linus Torvalds 已提交
332 333 334
		uint32_t secsz;     /* flash sector (erase block) size, bytes */
		uint pgsz;          /* NAND flash page size, bytes */
		uint oobsz;         /* page OOB area size, bytes */
335
		uint64_t totszoob;  /* total flash size including OOB, bytes */
L
Linus Torvalds 已提交
336 337 338 339 340 341 342 343 344 345 346 347
		uint pgszoob;       /* page size including OOB , bytes*/
		uint secszoob;      /* sector size including OOB, bytes */
		uint pgnum;         /* total number of pages */
		uint pgsec;         /* number of pages per sector */
		uint secshift;      /* bits number in sector size */
		uint pgshift;       /* bits number in page size */
		uint pgaddrbytes;   /* bytes per page address */
		uint secaddrbytes;  /* bytes per sector address */
		uint idbytes;       /* the number ID bytes that this chip outputs */
	} geom;

	/* NAND flash internal registers */
348
	struct {
L
Linus Torvalds 已提交
349 350 351 352 353 354 355 356 357 358
		unsigned command; /* the command register */
		u_char   status;  /* the status register */
		uint     row;     /* the page number */
		uint     column;  /* the offset within page */
		uint     count;   /* internal counter */
		uint     num;     /* number of bytes which must be processed */
		uint     off;     /* fixed page offset */
	} regs;

	/* NAND flash lines state */
359
        struct {
L
Linus Torvalds 已提交
360 361 362 363 364
                int ce;  /* chip Enable */
                int cle; /* command Latch Enable */
                int ale; /* address Latch Enable */
                int wp;  /* write Protect */
        } lines;
365 366 367

	/* Fields needed when using a cache file */
	struct file *cfile; /* Open file */
368
	unsigned long *pages_written; /* Which pages have been written */
369 370 371
	void *file_buf;
	struct page *held_pages[NS_MAX_HELD_PAGES];
	int held_cnt;
372 373

	struct nandsim_debug_info dbg;
L
Linus Torvalds 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
};

/*
 * Operations array. To perform any operation the simulator must pass
 * through the correspondent states chain.
 */
static struct nandsim_operations {
	uint32_t reqopts;  /* options which are required to perform the operation */
	uint32_t states[NS_OPER_STATES]; /* operation's states */
} ops[NS_OPER_NUM] = {
	/* Read page + OOB from the beginning */
	{OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
			STATE_DATAOUT, STATE_READY}},
	/* Read page + OOB from the second half */
	{OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
			STATE_DATAOUT, STATE_READY}},
	/* Read OOB */
	{OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
			STATE_DATAOUT, STATE_READY}},
393
	/* Program page starting from the beginning */
L
Linus Torvalds 已提交
394 395
	{OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
			STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
396
	/* Program page starting from the beginning */
L
Linus Torvalds 已提交
397 398
	{OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
			      STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
399
	/* Program page starting from the second half */
L
Linus Torvalds 已提交
400 401
	{OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
			      STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
402
	/* Program OOB */
L
Linus Torvalds 已提交
403 404 405 406 407 408 409 410 411 412
	{OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
			      STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
	/* Erase sector */
	{OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
	/* Read status */
	{OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
	/* Read ID */
	{OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
	/* Large page devices read page */
	{OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
413 414 415 416
			       STATE_DATAOUT, STATE_READY}},
	/* Large page devices random page read */
	{OPT_LARGEPAGE, {STATE_CMD_RNDOUT, STATE_ADDR_COLUMN, STATE_CMD_RNDOUTSTART | ACTION_CPY,
			       STATE_DATAOUT, STATE_READY}},
L
Linus Torvalds 已提交
417 418
};

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
struct weak_block {
	struct list_head list;
	unsigned int erase_block_no;
	unsigned int max_erases;
	unsigned int erases_done;
};

static LIST_HEAD(weak_blocks);

struct weak_page {
	struct list_head list;
	unsigned int page_no;
	unsigned int max_writes;
	unsigned int writes_done;
};

static LIST_HEAD(weak_pages);

struct grave_page {
	struct list_head list;
	unsigned int page_no;
	unsigned int max_reads;
	unsigned int reads_done;
};

static LIST_HEAD(grave_pages);

446 447 448 449
static unsigned long *erase_block_wear = NULL;
static unsigned int wear_eb_count = 0;
static unsigned long total_wear = 0;

L
Linus Torvalds 已提交
450 451 452
/* MTD structure for NAND controller */
static struct mtd_info *nsmtd;

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
static int nandsim_debugfs_show(struct seq_file *m, void *private)
{
	unsigned long wmin = -1, wmax = 0, avg;
	unsigned long deciles[10], decile_max[10], tot = 0;
	unsigned int i;

	/* Calc wear stats */
	for (i = 0; i < wear_eb_count; ++i) {
		unsigned long wear = erase_block_wear[i];
		if (wear < wmin)
			wmin = wear;
		if (wear > wmax)
			wmax = wear;
		tot += wear;
	}

	for (i = 0; i < 9; ++i) {
		deciles[i] = 0;
		decile_max[i] = (wmax * (i + 1) + 5) / 10;
	}
	deciles[9] = 0;
	decile_max[9] = wmax;
	for (i = 0; i < wear_eb_count; ++i) {
		int d;
		unsigned long wear = erase_block_wear[i];
		for (d = 0; d < 10; ++d)
			if (wear <= decile_max[d]) {
				deciles[d] += 1;
				break;
			}
	}
	avg = tot / wear_eb_count;

	/* Output wear report */
	seq_printf(m, "Total numbers of erases:  %lu\n", tot);
	seq_printf(m, "Number of erase blocks:   %u\n", wear_eb_count);
	seq_printf(m, "Average number of erases: %lu\n", avg);
	seq_printf(m, "Maximum number of erases: %lu\n", wmax);
	seq_printf(m, "Minimum number of erases: %lu\n", wmin);
	for (i = 0; i < 10; ++i) {
		unsigned long from = (i ? decile_max[i - 1] + 1 : 0);
		if (from > decile_max[i])
			continue;
		seq_printf(m, "Number of ebs with erase counts from %lu to %lu : %lu\n",
			from,
			decile_max[i],
			deciles[i]);
	}

	return 0;
}

static int nandsim_debugfs_open(struct inode *inode, struct file *file)
{
	return single_open(file, nandsim_debugfs_show, inode->i_private);
}

static const struct file_operations dfs_fops = {
	.open		= nandsim_debugfs_open,
	.read		= seq_read,
	.llseek		= seq_lseek,
	.release	= single_release,
};

/**
 * nandsim_debugfs_create - initialize debugfs
 * @dev: nandsim device description object
 *
 * This function creates all debugfs files for UBI device @ubi. Returns zero in
 * case of success and a negative error code in case of failure.
 */
static int nandsim_debugfs_create(struct nandsim *dev)
{
	struct nandsim_debug_info *dbg = &dev->dbg;
	struct dentry *dent;
	int err;

	if (!IS_ENABLED(CONFIG_DEBUG_FS))
		return 0;

	dent = debugfs_create_dir("nandsim", NULL);
	if (IS_ERR_OR_NULL(dent)) {
		int err = dent ? -ENODEV : PTR_ERR(dent);

		NS_ERR("cannot create \"nandsim\" debugfs directory, err %d\n",
			err);
		return err;
	}
	dbg->dfs_root = dent;

	dent = debugfs_create_file("wear_report", S_IRUSR,
				   dbg->dfs_root, dev, &dfs_fops);
	if (IS_ERR_OR_NULL(dent))
		goto out_remove;
	dbg->dfs_wear_report = dent;

	return 0;

out_remove:
	debugfs_remove_recursive(dbg->dfs_root);
	err = dent ? PTR_ERR(dent) : -ENODEV;
	return err;
}

/**
 * nandsim_debugfs_remove - destroy all debugfs files
 */
static void nandsim_debugfs_remove(struct nandsim *ns)
{
	if (IS_ENABLED(CONFIG_DEBUG_FS))
		debugfs_remove_recursive(ns->dbg.dfs_root);
}

566
/*
A
Alexey Korolev 已提交
567 568
 * Allocate array of page pointers, create slab allocation for an array
 * and initialize the array by NULL pointers.
569 570 571
 *
 * RETURNS: 0 if success, -ENOMEM if memory alloc fails.
 */
V
Vijay Kumar 已提交
572
static int alloc_device(struct nandsim *ns)
573
{
574 575 576 577 578 579 580
	struct file *cfile;
	int i, err;

	if (cache_file) {
		cfile = filp_open(cache_file, O_CREAT | O_RDWR | O_LARGEFILE, 0600);
		if (IS_ERR(cfile))
			return PTR_ERR(cfile);
581
		if (!(cfile->f_mode & FMODE_CAN_READ)) {
582 583 584 585
			NS_ERR("alloc_device: cache file not readable\n");
			err = -EINVAL;
			goto err_close;
		}
586
		if (!(cfile->f_mode & FMODE_CAN_WRITE)) {
587 588 589 590
			NS_ERR("alloc_device: cache file not writeable\n");
			err = -EINVAL;
			goto err_close;
		}
591 592
		ns->pages_written = vzalloc(BITS_TO_LONGS(ns->geom.pgnum) *
					    sizeof(unsigned long));
593 594 595 596 597 598 599 600 601 602 603 604 605 606
		if (!ns->pages_written) {
			NS_ERR("alloc_device: unable to allocate pages written array\n");
			err = -ENOMEM;
			goto err_close;
		}
		ns->file_buf = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
		if (!ns->file_buf) {
			NS_ERR("alloc_device: unable to allocate file buf\n");
			err = -ENOMEM;
			goto err_free;
		}
		ns->cfile = cfile;
		return 0;
	}
607 608 609

	ns->pages = vmalloc(ns->geom.pgnum * sizeof(union ns_mem));
	if (!ns->pages) {
610
		NS_ERR("alloc_device: unable to allocate page array\n");
611 612 613 614 615
		return -ENOMEM;
	}
	for (i = 0; i < ns->geom.pgnum; i++) {
		ns->pages[i].byte = NULL;
	}
A
Alexey Korolev 已提交
616 617 618 619 620 621
	ns->nand_pages_slab = kmem_cache_create("nandsim",
						ns->geom.pgszoob, 0, 0, NULL);
	if (!ns->nand_pages_slab) {
		NS_ERR("cache_create: unable to create kmem_cache\n");
		return -ENOMEM;
	}
622 623

	return 0;
624 625 626 627 628 629

err_free:
	vfree(ns->pages_written);
err_close:
	filp_close(cfile, NULL);
	return err;
630 631 632 633 634
}

/*
 * Free any allocated pages, and free the array of page pointers.
 */
V
Vijay Kumar 已提交
635
static void free_device(struct nandsim *ns)
636 637 638
{
	int i;

639 640 641 642 643 644 645
	if (ns->cfile) {
		kfree(ns->file_buf);
		vfree(ns->pages_written);
		filp_close(ns->cfile, NULL);
		return;
	}

646 647 648
	if (ns->pages) {
		for (i = 0; i < ns->geom.pgnum; i++) {
			if (ns->pages[i].byte)
A
Alexey Korolev 已提交
649 650
				kmem_cache_free(ns->nand_pages_slab,
						ns->pages[i].byte);
651
		}
652 653
		if (ns->nand_pages_slab)
			kmem_cache_destroy(ns->nand_pages_slab);
654 655 656 657
		vfree(ns->pages);
	}
}

658 659
static char *get_partition_name(int i)
{
A
Akinobu Mita 已提交
660
	return kasprintf(GFP_KERNEL, "NAND simulator partition %d", i);
661 662
}

L
Linus Torvalds 已提交
663 664 665 666 667
/*
 * Initialize the nandsim structure.
 *
 * RETURNS: 0 if success, -ERRNO if failure.
 */
V
Vijay Kumar 已提交
668
static int init_nandsim(struct mtd_info *mtd)
L
Linus Torvalds 已提交
669
{
670 671
	struct nand_chip *chip = mtd->priv;
	struct nandsim   *ns   = chip->priv;
672
	int i, ret = 0;
673 674
	uint64_t remains;
	uint64_t next_offset;
L
Linus Torvalds 已提交
675 676 677 678 679 680 681 682 683 684 685 686

	if (NS_IS_INITIALIZED(ns)) {
		NS_ERR("init_nandsim: nandsim is already initialized\n");
		return -EIO;
	}

	/* Force mtd to not do delays */
	chip->chip_delay = 0;

	/* Initialize the NAND flash parameters */
	ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
	ns->geom.totsz    = mtd->size;
J
Joern Engel 已提交
687
	ns->geom.pgsz     = mtd->writesize;
L
Linus Torvalds 已提交
688 689 690
	ns->geom.oobsz    = mtd->oobsize;
	ns->geom.secsz    = mtd->erasesize;
	ns->geom.pgszoob  = ns->geom.pgsz + ns->geom.oobsz;
691
	ns->geom.pgnum    = div_u64(ns->geom.totsz, ns->geom.pgsz);
692
	ns->geom.totszoob = ns->geom.totsz + (uint64_t)ns->geom.pgnum * ns->geom.oobsz;
L
Linus Torvalds 已提交
693 694 695 696 697 698
	ns->geom.secshift = ffs(ns->geom.secsz) - 1;
	ns->geom.pgshift  = chip->page_shift;
	ns->geom.pgsec    = ns->geom.secsz / ns->geom.pgsz;
	ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
	ns->options = 0;

699
	if (ns->geom.pgsz == 512) {
700
		ns->options |= OPT_PAGE512;
L
Linus Torvalds 已提交
701 702 703 704
		if (ns->busw == 8)
			ns->options |= OPT_PAGE512_8BIT;
	} else if (ns->geom.pgsz == 2048) {
		ns->options |= OPT_PAGE2048;
705 706
	} else if (ns->geom.pgsz == 4096) {
		ns->options |= OPT_PAGE4096;
L
Linus Torvalds 已提交
707 708 709 710 711 712
	} else {
		NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
		return -EIO;
	}

	if (ns->options & OPT_SMALLPAGE) {
713
		if (ns->geom.totsz <= (32 << 20)) {
L
Linus Torvalds 已提交
714 715 716 717 718 719 720 721
			ns->geom.pgaddrbytes  = 3;
			ns->geom.secaddrbytes = 2;
		} else {
			ns->geom.pgaddrbytes  = 4;
			ns->geom.secaddrbytes = 3;
		}
	} else {
		if (ns->geom.totsz <= (128 << 20)) {
722
			ns->geom.pgaddrbytes  = 4;
L
Linus Torvalds 已提交
723 724 725 726 727 728
			ns->geom.secaddrbytes = 2;
		} else {
			ns->geom.pgaddrbytes  = 5;
			ns->geom.secaddrbytes = 3;
		}
	}
729

730 731 732 733 734 735 736 737 738
	/* Fill the partition_info structure */
	if (parts_num > ARRAY_SIZE(ns->partitions)) {
		NS_ERR("too many partitions.\n");
		ret = -EINVAL;
		goto error;
	}
	remains = ns->geom.totsz;
	next_offset = 0;
	for (i = 0; i < parts_num; ++i) {
739
		uint64_t part_sz = (uint64_t)parts[i] * ns->geom.secsz;
740 741

		if (!part_sz || part_sz > remains) {
742 743 744 745 746
			NS_ERR("bad partition size.\n");
			ret = -EINVAL;
			goto error;
		}
		ns->partitions[i].name   = get_partition_name(i);
747 748 749 750 751
		if (!ns->partitions[i].name) {
			NS_ERR("unable to allocate memory.\n");
			ret = -ENOMEM;
			goto error;
		}
752
		ns->partitions[i].offset = next_offset;
753
		ns->partitions[i].size   = part_sz;
754 755 756 757 758 759 760 761 762 763 764
		next_offset += ns->partitions[i].size;
		remains -= ns->partitions[i].size;
	}
	ns->nbparts = parts_num;
	if (remains) {
		if (parts_num + 1 > ARRAY_SIZE(ns->partitions)) {
			NS_ERR("too many partitions.\n");
			ret = -EINVAL;
			goto error;
		}
		ns->partitions[i].name   = get_partition_name(i);
765 766 767 768 769
		if (!ns->partitions[i].name) {
			NS_ERR("unable to allocate memory.\n");
			ret = -ENOMEM;
			goto error;
		}
770 771 772 773 774
		ns->partitions[i].offset = next_offset;
		ns->partitions[i].size   = remains;
		ns->nbparts += 1;
	}

L
Linus Torvalds 已提交
775 776 777
	if (ns->busw == 16)
		NS_WARN("16-bit flashes support wasn't tested\n");

778 779
	printk("flash size: %llu MiB\n",
			(unsigned long long)ns->geom.totsz >> 20);
L
Linus Torvalds 已提交
780 781 782 783 784 785 786 787
	printk("page size: %u bytes\n",         ns->geom.pgsz);
	printk("OOB area size: %u bytes\n",     ns->geom.oobsz);
	printk("sector size: %u KiB\n",         ns->geom.secsz >> 10);
	printk("pages number: %u\n",            ns->geom.pgnum);
	printk("pages per sector: %u\n",        ns->geom.pgsec);
	printk("bus width: %u\n",               ns->busw);
	printk("bits in sector size: %u\n",     ns->geom.secshift);
	printk("bits in page size: %u\n",       ns->geom.pgshift);
788
	printk("bits in OOB size: %u\n",	ffs(ns->geom.oobsz) - 1);
789 790
	printk("flash size with OOB: %llu KiB\n",
			(unsigned long long)ns->geom.totszoob >> 10);
L
Linus Torvalds 已提交
791 792 793 794
	printk("page address bytes: %u\n",      ns->geom.pgaddrbytes);
	printk("sector address bytes: %u\n",    ns->geom.secaddrbytes);
	printk("options: %#x\n",                ns->options);

795
	if ((ret = alloc_device(ns)) != 0)
796
		goto error;
L
Linus Torvalds 已提交
797 798 799 800 801 802

	/* Allocate / initialize the internal buffer */
	ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
	if (!ns->buf.byte) {
		NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
			ns->geom.pgszoob);
803
		ret = -ENOMEM;
L
Linus Torvalds 已提交
804 805 806 807 808 809 810
		goto error;
	}
	memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);

	return 0;

error:
811
	free_device(ns);
L
Linus Torvalds 已提交
812

813
	return ret;
L
Linus Torvalds 已提交
814 815 816 817 818
}

/*
 * Free the nandsim structure.
 */
V
Vijay Kumar 已提交
819
static void free_nandsim(struct nandsim *ns)
L
Linus Torvalds 已提交
820 821
{
	kfree(ns->buf.byte);
822
	free_device(ns);
L
Linus Torvalds 已提交
823 824 825 826

	return;
}

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
{
	char *w;
	int zero_ok;
	unsigned int erase_block_no;
	loff_t offset;

	if (!badblocks)
		return 0;
	w = badblocks;
	do {
		zero_ok = (*w == '0' ? 1 : 0);
		erase_block_no = simple_strtoul(w, &w, 0);
		if (!zero_ok && !erase_block_no) {
			NS_ERR("invalid badblocks.\n");
			return -EINVAL;
		}
844
		offset = (loff_t)erase_block_no * ns->geom.secsz;
845
		if (mtd_block_markbad(mtd, offset)) {
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
			NS_ERR("invalid badblocks.\n");
			return -EINVAL;
		}
		if (*w == ',')
			w += 1;
	} while (*w);
	return 0;
}

static int parse_weakblocks(void)
{
	char *w;
	int zero_ok;
	unsigned int erase_block_no;
	unsigned int max_erases;
	struct weak_block *wb;

	if (!weakblocks)
		return 0;
	w = weakblocks;
	do {
		zero_ok = (*w == '0' ? 1 : 0);
		erase_block_no = simple_strtoul(w, &w, 0);
		if (!zero_ok && !erase_block_no) {
			NS_ERR("invalid weakblocks.\n");
			return -EINVAL;
		}
		max_erases = 3;
		if (*w == ':') {
			w += 1;
			max_erases = simple_strtoul(w, &w, 0);
		}
		if (*w == ',')
			w += 1;
		wb = kzalloc(sizeof(*wb), GFP_KERNEL);
		if (!wb) {
			NS_ERR("unable to allocate memory.\n");
			return -ENOMEM;
		}
		wb->erase_block_no = erase_block_no;
		wb->max_erases = max_erases;
		list_add(&wb->list, &weak_blocks);
	} while (*w);
	return 0;
}

static int erase_error(unsigned int erase_block_no)
{
	struct weak_block *wb;

	list_for_each_entry(wb, &weak_blocks, list)
		if (wb->erase_block_no == erase_block_no) {
			if (wb->erases_done >= wb->max_erases)
				return 1;
			wb->erases_done += 1;
			return 0;
		}
	return 0;
}

static int parse_weakpages(void)
{
	char *w;
	int zero_ok;
	unsigned int page_no;
	unsigned int max_writes;
	struct weak_page *wp;

	if (!weakpages)
		return 0;
	w = weakpages;
	do {
		zero_ok = (*w == '0' ? 1 : 0);
		page_no = simple_strtoul(w, &w, 0);
		if (!zero_ok && !page_no) {
			NS_ERR("invalid weakpagess.\n");
			return -EINVAL;
		}
		max_writes = 3;
		if (*w == ':') {
			w += 1;
			max_writes = simple_strtoul(w, &w, 0);
		}
		if (*w == ',')
			w += 1;
		wp = kzalloc(sizeof(*wp), GFP_KERNEL);
		if (!wp) {
			NS_ERR("unable to allocate memory.\n");
			return -ENOMEM;
		}
		wp->page_no = page_no;
		wp->max_writes = max_writes;
		list_add(&wp->list, &weak_pages);
	} while (*w);
	return 0;
}

static int write_error(unsigned int page_no)
{
	struct weak_page *wp;

	list_for_each_entry(wp, &weak_pages, list)
		if (wp->page_no == page_no) {
			if (wp->writes_done >= wp->max_writes)
				return 1;
			wp->writes_done += 1;
			return 0;
		}
	return 0;
}

static int parse_gravepages(void)
{
	char *g;
	int zero_ok;
	unsigned int page_no;
	unsigned int max_reads;
	struct grave_page *gp;

	if (!gravepages)
		return 0;
	g = gravepages;
	do {
		zero_ok = (*g == '0' ? 1 : 0);
		page_no = simple_strtoul(g, &g, 0);
		if (!zero_ok && !page_no) {
			NS_ERR("invalid gravepagess.\n");
			return -EINVAL;
		}
		max_reads = 3;
		if (*g == ':') {
			g += 1;
			max_reads = simple_strtoul(g, &g, 0);
		}
		if (*g == ',')
			g += 1;
		gp = kzalloc(sizeof(*gp), GFP_KERNEL);
		if (!gp) {
			NS_ERR("unable to allocate memory.\n");
			return -ENOMEM;
		}
		gp->page_no = page_no;
		gp->max_reads = max_reads;
		list_add(&gp->list, &grave_pages);
	} while (*g);
	return 0;
}

static int read_error(unsigned int page_no)
{
	struct grave_page *gp;

	list_for_each_entry(gp, &grave_pages, list)
		if (gp->page_no == page_no) {
			if (gp->reads_done >= gp->max_reads)
				return 1;
			gp->reads_done += 1;
			return 0;
		}
	return 0;
}

static void free_lists(void)
{
	struct list_head *pos, *n;
	list_for_each_safe(pos, n, &weak_blocks) {
		list_del(pos);
		kfree(list_entry(pos, struct weak_block, list));
	}
	list_for_each_safe(pos, n, &weak_pages) {
		list_del(pos);
		kfree(list_entry(pos, struct weak_page, list));
	}
	list_for_each_safe(pos, n, &grave_pages) {
		list_del(pos);
		kfree(list_entry(pos, struct grave_page, list));
	}
1023 1024 1025 1026 1027 1028 1029
	kfree(erase_block_wear);
}

static int setup_wear_reporting(struct mtd_info *mtd)
{
	size_t mem;

1030
	wear_eb_count = div_u64(mtd->size, mtd->erasesize);
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
	mem = wear_eb_count * sizeof(unsigned long);
	if (mem / sizeof(unsigned long) != wear_eb_count) {
		NS_ERR("Too many erase blocks for wear reporting\n");
		return -ENOMEM;
	}
	erase_block_wear = kzalloc(mem, GFP_KERNEL);
	if (!erase_block_wear) {
		NS_ERR("Too many erase blocks for wear reporting\n");
		return -ENOMEM;
	}
	return 0;
}

static void update_wear(unsigned int erase_block_no)
{
	if (!erase_block_wear)
		return;
	total_wear += 1;
1049 1050 1051 1052
	/*
	 * TODO: Notify this through a debugfs entry,
	 * instead of showing an error message.
	 */
1053 1054 1055 1056 1057
	if (total_wear == 0)
		NS_ERR("Erase counter total overflow\n");
	erase_block_wear[erase_block_no] += 1;
	if (erase_block_wear[erase_block_no] == 0)
		NS_ERR("Erase counter overflow for erase block %u\n", erase_block_no);
1058 1059
}

L
Linus Torvalds 已提交
1060 1061 1062
/*
 * Returns the string representation of 'state' state.
 */
V
Vijay Kumar 已提交
1063
static char *get_state_name(uint32_t state)
L
Linus Torvalds 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
{
	switch (NS_STATE(state)) {
		case STATE_CMD_READ0:
			return "STATE_CMD_READ0";
		case STATE_CMD_READ1:
			return "STATE_CMD_READ1";
		case STATE_CMD_PAGEPROG:
			return "STATE_CMD_PAGEPROG";
		case STATE_CMD_READOOB:
			return "STATE_CMD_READOOB";
		case STATE_CMD_READSTART:
			return "STATE_CMD_READSTART";
		case STATE_CMD_ERASE1:
			return "STATE_CMD_ERASE1";
		case STATE_CMD_STATUS:
			return "STATE_CMD_STATUS";
		case STATE_CMD_SEQIN:
			return "STATE_CMD_SEQIN";
		case STATE_CMD_READID:
			return "STATE_CMD_READID";
		case STATE_CMD_ERASE2:
			return "STATE_CMD_ERASE2";
		case STATE_CMD_RESET:
			return "STATE_CMD_RESET";
1088 1089 1090 1091
		case STATE_CMD_RNDOUT:
			return "STATE_CMD_RNDOUT";
		case STATE_CMD_RNDOUTSTART:
			return "STATE_CMD_RNDOUTSTART";
L
Linus Torvalds 已提交
1092 1093 1094 1095 1096 1097
		case STATE_ADDR_PAGE:
			return "STATE_ADDR_PAGE";
		case STATE_ADDR_SEC:
			return "STATE_ADDR_SEC";
		case STATE_ADDR_ZERO:
			return "STATE_ADDR_ZERO";
1098 1099
		case STATE_ADDR_COLUMN:
			return "STATE_ADDR_COLUMN";
L
Linus Torvalds 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
		case STATE_DATAIN:
			return "STATE_DATAIN";
		case STATE_DATAOUT:
			return "STATE_DATAOUT";
		case STATE_DATAOUT_ID:
			return "STATE_DATAOUT_ID";
		case STATE_DATAOUT_STATUS:
			return "STATE_DATAOUT_STATUS";
		case STATE_READY:
			return "STATE_READY";
		case STATE_UNKNOWN:
			return "STATE_UNKNOWN";
	}

	NS_ERR("get_state_name: unknown state, BUG\n");
	return NULL;
}

/*
 * Check if command is valid.
 *
 * RETURNS: 1 if wrong command, 0 if right.
 */
V
Vijay Kumar 已提交
1123
static int check_command(int cmd)
L
Linus Torvalds 已提交
1124 1125
{
	switch (cmd) {
1126

L
Linus Torvalds 已提交
1127
	case NAND_CMD_READ0:
1128
	case NAND_CMD_READ1:
L
Linus Torvalds 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137
	case NAND_CMD_READSTART:
	case NAND_CMD_PAGEPROG:
	case NAND_CMD_READOOB:
	case NAND_CMD_ERASE1:
	case NAND_CMD_STATUS:
	case NAND_CMD_SEQIN:
	case NAND_CMD_READID:
	case NAND_CMD_ERASE2:
	case NAND_CMD_RESET:
1138 1139
	case NAND_CMD_RNDOUT:
	case NAND_CMD_RNDOUTSTART:
L
Linus Torvalds 已提交
1140
		return 0;
1141

L
Linus Torvalds 已提交
1142 1143 1144 1145 1146 1147 1148 1149
	default:
		return 1;
	}
}

/*
 * Returns state after command is accepted by command number.
 */
V
Vijay Kumar 已提交
1150
static uint32_t get_state_by_command(unsigned command)
L
Linus Torvalds 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
{
	switch (command) {
		case NAND_CMD_READ0:
			return STATE_CMD_READ0;
		case NAND_CMD_READ1:
			return STATE_CMD_READ1;
		case NAND_CMD_PAGEPROG:
			return STATE_CMD_PAGEPROG;
		case NAND_CMD_READSTART:
			return STATE_CMD_READSTART;
		case NAND_CMD_READOOB:
			return STATE_CMD_READOOB;
		case NAND_CMD_ERASE1:
			return STATE_CMD_ERASE1;
		case NAND_CMD_STATUS:
			return STATE_CMD_STATUS;
		case NAND_CMD_SEQIN:
			return STATE_CMD_SEQIN;
		case NAND_CMD_READID:
			return STATE_CMD_READID;
		case NAND_CMD_ERASE2:
			return STATE_CMD_ERASE2;
		case NAND_CMD_RESET:
			return STATE_CMD_RESET;
1175 1176 1177 1178
		case NAND_CMD_RNDOUT:
			return STATE_CMD_RNDOUT;
		case NAND_CMD_RNDOUTSTART:
			return STATE_CMD_RNDOUTSTART;
L
Linus Torvalds 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187
	}

	NS_ERR("get_state_by_command: unknown command, BUG\n");
	return 0;
}

/*
 * Move an address byte to the correspondent internal register.
 */
V
Vijay Kumar 已提交
1188
static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
L
Linus Torvalds 已提交
1189 1190
{
	uint byte = (uint)bt;
1191

L
Linus Torvalds 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
	if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
		ns->regs.column |= (byte << 8 * ns->regs.count);
	else {
		ns->regs.row |= (byte << 8 * (ns->regs.count -
						ns->geom.pgaddrbytes +
						ns->geom.secaddrbytes));
	}

	return;
}
1202

L
Linus Torvalds 已提交
1203 1204 1205
/*
 * Switch to STATE_READY state.
 */
V
Vijay Kumar 已提交
1206
static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
L
Linus Torvalds 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
{
	NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));

	ns->state       = STATE_READY;
	ns->nxstate     = STATE_UNKNOWN;
	ns->op          = NULL;
	ns->npstates    = 0;
	ns->stateidx    = 0;
	ns->regs.num    = 0;
	ns->regs.count  = 0;
	ns->regs.off    = 0;
	ns->regs.row    = 0;
	ns->regs.column = 0;
	ns->regs.status = status;
}

/*
 * If the operation isn't known yet, try to find it in the global array
 * of supported operations.
 *
 * Operation can be unknown because of the following.
1228
 *   1. New command was accepted and this is the first call to find the
L
Linus Torvalds 已提交
1229
 *      correspondent states chain. In this case ns->npstates = 0;
1230
 *   2. There are several operations which begin with the same command(s)
L
Linus Torvalds 已提交
1231 1232 1233
 *      (for example program from the second half and read from the
 *      second half operations both begin with the READ1 command). In this
 *      case the ns->pstates[] array contains previous states.
1234
 *
L
Linus Torvalds 已提交
1235 1236 1237 1238 1239 1240 1241
 * Thus, the function tries to find operation containing the following
 * states (if the 'flag' parameter is 0):
 *    ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
 *
 * If (one and only one) matching operation is found, it is accepted (
 * ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
 * zeroed).
1242
 *
1243
 * If there are several matches, the current state is pushed to the
L
Linus Torvalds 已提交
1244 1245 1246 1247 1248 1249 1250
 * ns->pstates.
 *
 * The operation can be unknown only while commands are input to the chip.
 * As soon as address command is accepted, the operation must be known.
 * In such situation the function is called with 'flag' != 0, and the
 * operation is searched using the following pattern:
 *     ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
1251
 *
1252
 * It is supposed that this pattern must either match one operation or
L
Linus Torvalds 已提交
1253 1254
 * none. There can't be ambiguity in that case.
 *
1255
 * If no matches found, the function does the following:
L
Linus Torvalds 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264
 *   1. if there are saved states present, try to ignore them and search
 *      again only using the last command. If nothing was found, switch
 *      to the STATE_READY state.
 *   2. if there are no saved states, switch to the STATE_READY state.
 *
 * RETURNS: -2 - no matched operations found.
 *          -1 - several matches.
 *           0 - operation is found.
 */
V
Vijay Kumar 已提交
1265
static int find_operation(struct nandsim *ns, uint32_t flag)
L
Linus Torvalds 已提交
1266 1267 1268
{
	int opsfound = 0;
	int i, j, idx = 0;
1269

L
Linus Torvalds 已提交
1270 1271 1272
	for (i = 0; i < NS_OPER_NUM; i++) {

		int found = 1;
1273

L
Linus Torvalds 已提交
1274 1275 1276
		if (!(ns->options & ops[i].reqopts))
			/* Ignore operations we can't perform */
			continue;
1277

L
Linus Torvalds 已提交
1278 1279 1280 1281 1282 1283 1284 1285
		if (flag) {
			if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
				continue;
		} else {
			if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
				continue;
		}

1286
		for (j = 0; j < ns->npstates; j++)
L
Linus Torvalds 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
			if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
				&& (ns->options & ops[idx].reqopts)) {
				found = 0;
				break;
			}

		if (found) {
			idx = i;
			opsfound += 1;
		}
	}

	if (opsfound == 1) {
		/* Exact match */
		ns->op = &ops[idx].states[0];
		if (flag) {
1303
			/*
L
Linus Torvalds 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
			 * In this case the find_operation function was
			 * called when address has just began input. But it isn't
			 * yet fully input and the current state must
			 * not be one of STATE_ADDR_*, but the STATE_ADDR_*
			 * state must be the next state (ns->nxstate).
			 */
			ns->stateidx = ns->npstates - 1;
		} else {
			ns->stateidx = ns->npstates;
		}
		ns->npstates = 0;
		ns->state = ns->op[ns->stateidx];
		ns->nxstate = ns->op[ns->stateidx + 1];
		NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
				idx, get_state_name(ns->state), get_state_name(ns->nxstate));
		return 0;
	}
1321

L
Linus Torvalds 已提交
1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	if (opsfound == 0) {
		/* Nothing was found. Try to ignore previous commands (if any) and search again */
		if (ns->npstates != 0) {
			NS_DBG("find_operation: no operation found, try again with state %s\n",
					get_state_name(ns->state));
			ns->npstates = 0;
			return find_operation(ns, 0);

		}
		NS_DBG("find_operation: no operations found\n");
		switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
		return -2;
	}
1335

L
Linus Torvalds 已提交
1336 1337 1338 1339 1340
	if (flag) {
		/* This shouldn't happen */
		NS_DBG("find_operation: BUG, operation must be known if address is input\n");
		return -2;
	}
1341

L
Linus Torvalds 已提交
1342 1343 1344 1345 1346 1347 1348
	NS_DBG("find_operation: there is still ambiguity\n");

	ns->pstates[ns->npstates++] = ns->state;

	return -1;
}

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
static void put_pages(struct nandsim *ns)
{
	int i;

	for (i = 0; i < ns->held_cnt; i++)
		page_cache_release(ns->held_pages[i]);
}

/* Get page cache pages in advance to provide NOFS memory allocation */
static int get_pages(struct nandsim *ns, struct file *file, size_t count, loff_t pos)
{
	pgoff_t index, start_index, end_index;
	struct page *page;
	struct address_space *mapping = file->f_mapping;

	start_index = pos >> PAGE_CACHE_SHIFT;
	end_index = (pos + count - 1) >> PAGE_CACHE_SHIFT;
	if (end_index - start_index + 1 > NS_MAX_HELD_PAGES)
		return -EINVAL;
	ns->held_cnt = 0;
	for (index = start_index; index <= end_index; index++) {
		page = find_get_page(mapping, index);
		if (page == NULL) {
			page = find_or_create_page(mapping, index, GFP_NOFS);
			if (page == NULL) {
				write_inode_now(mapping->host, 1);
				page = find_or_create_page(mapping, index, GFP_NOFS);
			}
			if (page == NULL) {
				put_pages(ns);
				return -ENOMEM;
			}
			unlock_page(page);
		}
		ns->held_pages[ns->held_cnt++] = page;
	}
	return 0;
}

static int set_memalloc(void)
{
	if (current->flags & PF_MEMALLOC)
		return 0;
	current->flags |= PF_MEMALLOC;
	return 1;
}

static void clear_memalloc(int memalloc)
{
	if (memalloc)
		current->flags &= ~PF_MEMALLOC;
}

1402
static ssize_t read_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t pos)
1403 1404 1405 1406
{
	ssize_t tx;
	int err, memalloc;

1407
	err = get_pages(ns, file, count, pos);
1408 1409 1410
	if (err)
		return err;
	memalloc = set_memalloc();
1411
	tx = kernel_read(file, pos, buf, count);
1412 1413 1414 1415 1416
	clear_memalloc(memalloc);
	put_pages(ns);
	return tx;
}

1417
static ssize_t write_file(struct nandsim *ns, struct file *file, void *buf, size_t count, loff_t pos)
1418 1419 1420 1421
{
	ssize_t tx;
	int err, memalloc;

1422
	err = get_pages(ns, file, count, pos);
1423 1424 1425
	if (err)
		return err;
	memalloc = set_memalloc();
1426
	tx = kernel_write(file, buf, count, pos);
1427 1428 1429 1430 1431
	clear_memalloc(memalloc);
	put_pages(ns);
	return tx;
}

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
/*
 * Returns a pointer to the current page.
 */
static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
{
	return &(ns->pages[ns->regs.row]);
}

/*
 * Retuns a pointer to the current byte, within the current page.
 */
static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
{
	return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
}

1448
static int do_read_error(struct nandsim *ns, int num)
1449 1450 1451 1452
{
	unsigned int page_no = ns->regs.row;

	if (read_error(page_no)) {
A
Akinobu Mita 已提交
1453
		prandom_bytes(ns->buf.byte, num);
1454 1455 1456 1457 1458 1459
		NS_WARN("simulating read error in page %u\n", page_no);
		return 1;
	}
	return 0;
}

1460
static void do_bit_flips(struct nandsim *ns, int num)
1461
{
1462
	if (bitflips && prandom_u32() < (1 << 22)) {
1463 1464
		int flips = 1;
		if (bitflips > 1)
1465
			flips = (prandom_u32() % (int) bitflips) + 1;
1466
		while (flips--) {
1467
			int pos = prandom_u32() % (num * 8);
1468 1469 1470 1471 1472 1473 1474 1475 1476
			ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
			NS_WARN("read_page: flipping bit %d in page %d "
				"reading from %d ecc: corrected=%u failed=%u\n",
				pos, ns->regs.row, ns->regs.column + ns->regs.off,
				nsmtd->ecc_stats.corrected, nsmtd->ecc_stats.failed);
		}
	}
}

1477 1478 1479 1480 1481 1482 1483
/*
 * Fill the NAND buffer with data read from the specified page.
 */
static void read_page(struct nandsim *ns, int num)
{
	union ns_mem *mypage;

1484
	if (ns->cfile) {
1485
		if (!test_bit(ns->regs.row, ns->pages_written)) {
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
			NS_DBG("read_page: page %d not written\n", ns->regs.row);
			memset(ns->buf.byte, 0xFF, num);
		} else {
			loff_t pos;
			ssize_t tx;

			NS_DBG("read_page: page %d written, reading from %d\n",
				ns->regs.row, ns->regs.column + ns->regs.off);
			if (do_read_error(ns, num))
				return;
A
Akinobu Mita 已提交
1496
			pos = (loff_t)NS_RAW_OFFSET(ns) + ns->regs.off;
1497
			tx = read_file(ns, ns->cfile, ns->buf.byte, num, pos);
1498 1499 1500 1501 1502 1503 1504 1505 1506
			if (tx != num) {
				NS_ERR("read_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
				return;
			}
			do_bit_flips(ns, num);
		}
		return;
	}

1507 1508 1509 1510 1511 1512 1513
	mypage = NS_GET_PAGE(ns);
	if (mypage->byte == NULL) {
		NS_DBG("read_page: page %d not allocated\n", ns->regs.row);
		memset(ns->buf.byte, 0xFF, num);
	} else {
		NS_DBG("read_page: page %d allocated, reading from %d\n",
			ns->regs.row, ns->regs.column + ns->regs.off);
1514
		if (do_read_error(ns, num))
1515
			return;
1516
		memcpy(ns->buf.byte, NS_PAGE_BYTE_OFF(ns), num);
1517
		do_bit_flips(ns, num);
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	}
}

/*
 * Erase all pages in the specified sector.
 */
static void erase_sector(struct nandsim *ns)
{
	union ns_mem *mypage;
	int i;

1529 1530
	if (ns->cfile) {
		for (i = 0; i < ns->geom.pgsec; i++)
1531 1532
			if (__test_and_clear_bit(ns->regs.row + i,
						 ns->pages_written)) {
1533 1534 1535 1536 1537
				NS_DBG("erase_sector: freeing page %d\n", ns->regs.row + i);
			}
		return;
	}

1538 1539 1540 1541
	mypage = NS_GET_PAGE(ns);
	for (i = 0; i < ns->geom.pgsec; i++) {
		if (mypage->byte != NULL) {
			NS_DBG("erase_sector: freeing page %d\n", ns->regs.row+i);
A
Alexey Korolev 已提交
1542
			kmem_cache_free(ns->nand_pages_slab, mypage->byte);
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
			mypage->byte = NULL;
		}
		mypage++;
	}
}

/*
 * Program the specified page with the contents from the NAND buffer.
 */
static int prog_page(struct nandsim *ns, int num)
{
1554
	int i;
1555 1556 1557
	union ns_mem *mypage;
	u_char *pg_off;

1558
	if (ns->cfile) {
1559
		loff_t off;
1560 1561 1562 1563 1564
		ssize_t tx;
		int all;

		NS_DBG("prog_page: writing page %d\n", ns->regs.row);
		pg_off = ns->file_buf + ns->regs.column + ns->regs.off;
A
Akinobu Mita 已提交
1565
		off = (loff_t)NS_RAW_OFFSET(ns) + ns->regs.off;
1566
		if (!test_bit(ns->regs.row, ns->pages_written)) {
1567 1568 1569 1570
			all = 1;
			memset(ns->file_buf, 0xff, ns->geom.pgszoob);
		} else {
			all = 0;
1571
			tx = read_file(ns, ns->cfile, pg_off, num, off);
1572 1573 1574 1575 1576 1577 1578 1579
			if (tx != num) {
				NS_ERR("prog_page: read error for page %d ret %ld\n", ns->regs.row, (long)tx);
				return -1;
			}
		}
		for (i = 0; i < num; i++)
			pg_off[i] &= ns->buf.byte[i];
		if (all) {
1580 1581
			loff_t pos = (loff_t)ns->regs.row * ns->geom.pgszoob;
			tx = write_file(ns, ns->cfile, ns->file_buf, ns->geom.pgszoob, pos);
1582 1583 1584 1585
			if (tx != ns->geom.pgszoob) {
				NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
				return -1;
			}
1586
			__set_bit(ns->regs.row, ns->pages_written);
1587
		} else {
1588
			tx = write_file(ns, ns->cfile, pg_off, num, off);
1589 1590 1591 1592 1593 1594 1595 1596
			if (tx != num) {
				NS_ERR("prog_page: write error for page %d ret %ld\n", ns->regs.row, (long)tx);
				return -1;
			}
		}
		return 0;
	}

1597 1598 1599
	mypage = NS_GET_PAGE(ns);
	if (mypage->byte == NULL) {
		NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
1600 1601 1602
		/*
		 * We allocate memory with GFP_NOFS because a flash FS may
		 * utilize this. If it is holding an FS lock, then gets here,
A
Alexey Korolev 已提交
1603 1604
		 * then kernel memory alloc runs writeback which goes to the FS
		 * again and deadlocks. This was seen in practice.
1605
		 */
A
Alexey Korolev 已提交
1606
		mypage->byte = kmem_cache_alloc(ns->nand_pages_slab, GFP_NOFS);
1607 1608 1609 1610 1611 1612 1613 1614
		if (mypage->byte == NULL) {
			NS_ERR("prog_page: error allocating memory for page %d\n", ns->regs.row);
			return -1;
		}
		memset(mypage->byte, 0xFF, ns->geom.pgszoob);
	}

	pg_off = NS_PAGE_BYTE_OFF(ns);
1615 1616
	for (i = 0; i < num; i++)
		pg_off[i] &= ns->buf.byte[i];
1617 1618 1619 1620

	return 0;
}

L
Linus Torvalds 已提交
1621 1622 1623 1624 1625
/*
 * If state has any action bit, perform this action.
 *
 * RETURNS: 0 if success, -1 if error.
 */
V
Vijay Kumar 已提交
1626
static int do_state_action(struct nandsim *ns, uint32_t action)
L
Linus Torvalds 已提交
1627
{
1628
	int num;
L
Linus Torvalds 已提交
1629
	int busdiv = ns->busw == 8 ? 1 : 2;
1630
	unsigned int erase_block_no, page_no;
L
Linus Torvalds 已提交
1631 1632

	action &= ACTION_MASK;
1633

L
Linus Torvalds 已提交
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
	/* Check that page address input is correct */
	if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
		NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
		return -1;
	}

	switch (action) {

	case ACTION_CPY:
		/*
		 * Copy page data to the internal buffer.
		 */

		/* Column shouldn't be very large */
		if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
			NS_ERR("do_state_action: column number is too large\n");
			break;
		}
		num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1653
		read_page(ns, num);
L
Linus Torvalds 已提交
1654 1655 1656

		NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
			num, NS_RAW_OFFSET(ns) + ns->regs.off);
1657

L
Linus Torvalds 已提交
1658 1659 1660 1661 1662 1663
		if (ns->regs.off == 0)
			NS_LOG("read page %d\n", ns->regs.row);
		else if (ns->regs.off < ns->geom.pgsz)
			NS_LOG("read page %d (second half)\n", ns->regs.row);
		else
			NS_LOG("read OOB of page %d\n", ns->regs.row);
1664

L
Linus Torvalds 已提交
1665 1666 1667 1668 1669 1670 1671 1672 1673
		NS_UDELAY(access_delay);
		NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);

		break;

	case ACTION_SECERASE:
		/*
		 * Erase sector.
		 */
1674

L
Linus Torvalds 已提交
1675 1676 1677 1678
		if (ns->lines.wp) {
			NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
			return -1;
		}
1679

L
Linus Torvalds 已提交
1680 1681 1682 1683 1684
		if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
			|| (ns->regs.row & ~(ns->geom.secsz - 1))) {
			NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
			return -1;
		}
1685

L
Linus Torvalds 已提交
1686 1687 1688
		ns->regs.row = (ns->regs.row <<
				8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
		ns->regs.column = 0;
1689

1690 1691
		erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);

L
Linus Torvalds 已提交
1692 1693
		NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
				ns->regs.row, NS_RAW_OFFSET(ns));
1694
		NS_LOG("erase sector %u\n", erase_block_no);
L
Linus Torvalds 已提交
1695

1696
		erase_sector(ns);
1697

L
Linus Torvalds 已提交
1698
		NS_MDELAY(erase_delay);
1699

1700 1701 1702
		if (erase_block_wear)
			update_wear(erase_block_no);

1703 1704 1705 1706 1707
		if (erase_error(erase_block_no)) {
			NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
			return -1;
		}

L
Linus Torvalds 已提交
1708 1709 1710 1711
		break;

	case ACTION_PRGPAGE:
		/*
1712
		 * Program page - move internal buffer data to the page.
L
Linus Torvalds 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
		 */

		if (ns->lines.wp) {
			NS_WARN("do_state_action: device is write-protected, programm\n");
			return -1;
		}

		num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
		if (num != ns->regs.count) {
			NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
					ns->regs.count, num);
			return -1;
		}

1727 1728
		if (prog_page(ns, num) == -1)
			return -1;
L
Linus Torvalds 已提交
1729

1730 1731
		page_no = ns->regs.row;

L
Linus Torvalds 已提交
1732 1733 1734
		NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
			num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
		NS_LOG("programm page %d\n", ns->regs.row);
1735

L
Linus Torvalds 已提交
1736 1737
		NS_UDELAY(programm_delay);
		NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
1738

1739 1740 1741 1742 1743
		if (write_error(page_no)) {
			NS_WARN("simulating write failure in page %u\n", page_no);
			return -1;
		}

L
Linus Torvalds 已提交
1744
		break;
1745

L
Linus Torvalds 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
	case ACTION_ZEROOFF:
		NS_DBG("do_state_action: set internal offset to 0\n");
		ns->regs.off = 0;
		break;

	case ACTION_HALFOFF:
		if (!(ns->options & OPT_PAGE512_8BIT)) {
			NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
				"byte page size 8x chips\n");
			return -1;
		}
		NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
		ns->regs.off = ns->geom.pgsz/2;
		break;

	case ACTION_OOBOFF:
		NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
		ns->regs.off = ns->geom.pgsz;
		break;
1765

L
Linus Torvalds 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
	default:
		NS_DBG("do_state_action: BUG! unknown action\n");
	}

	return 0;
}

/*
 * Switch simulator's state.
 */
V
Vijay Kumar 已提交
1776
static void switch_state(struct nandsim *ns)
L
Linus Torvalds 已提交
1777 1778 1779 1780 1781 1782
{
	if (ns->op) {
		/*
		 * The current operation have already been identified.
		 * Just follow the states chain.
		 */
1783

L
Linus Torvalds 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
		ns->stateidx += 1;
		ns->state = ns->nxstate;
		ns->nxstate = ns->op[ns->stateidx + 1];

		NS_DBG("switch_state: operation is known, switch to the next state, "
			"state: %s, nxstate: %s\n",
			get_state_name(ns->state), get_state_name(ns->nxstate));

		/* See, whether we need to do some action */
		if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
			return;
		}
1797

L
Linus Torvalds 已提交
1798 1799 1800 1801 1802 1803
	} else {
		/*
		 * We don't yet know which operation we perform.
		 * Try to identify it.
		 */

1804
		/*
L
Linus Torvalds 已提交
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
		 *  The only event causing the switch_state function to
		 *  be called with yet unknown operation is new command.
		 */
		ns->state = get_state_by_command(ns->regs.command);

		NS_DBG("switch_state: operation is unknown, try to find it\n");

		if (find_operation(ns, 0) != 0)
			return;

		if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
			return;
		}
	}

	/* For 16x devices column means the page offset in words */
	if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
		NS_DBG("switch_state: double the column number for 16x device\n");
		ns->regs.column <<= 1;
	}

	if (NS_STATE(ns->nxstate) == STATE_READY) {
		/*
		 * The current state is the last. Return to STATE_READY
		 */

		u_char status = NS_STATUS_OK(ns);
1833

L
Linus Torvalds 已提交
1834 1835 1836 1837 1838 1839 1840
		/* In case of data states, see if all bytes were input/output */
		if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
			&& ns->regs.count != ns->regs.num) {
			NS_WARN("switch_state: not all bytes were processed, %d left\n",
					ns->regs.num - ns->regs.count);
			status = NS_STATUS_FAILED(ns);
		}
1841

L
Linus Torvalds 已提交
1842 1843 1844 1845 1846 1847
		NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");

		switch_to_ready_state(ns, status);

		return;
	} else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
1848
		/*
L
Linus Torvalds 已提交
1849 1850
		 * If the next state is data input/output, switch to it now
		 */
1851

L
Linus Torvalds 已提交
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
		ns->state      = ns->nxstate;
		ns->nxstate    = ns->op[++ns->stateidx + 1];
		ns->regs.num   = ns->regs.count = 0;

		NS_DBG("switch_state: the next state is data I/O, switch, "
			"state: %s, nxstate: %s\n",
			get_state_name(ns->state), get_state_name(ns->nxstate));

		/*
		 * Set the internal register to the count of bytes which
		 * are expected to be input or output
		 */
		switch (NS_STATE(ns->state)) {
			case STATE_DATAIN:
			case STATE_DATAOUT:
				ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
				break;
1869

L
Linus Torvalds 已提交
1870 1871 1872
			case STATE_DATAOUT_ID:
				ns->regs.num = ns->geom.idbytes;
				break;
1873

L
Linus Torvalds 已提交
1874 1875 1876
			case STATE_DATAOUT_STATUS:
				ns->regs.count = ns->regs.num = 0;
				break;
1877

L
Linus Torvalds 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
			default:
				NS_ERR("switch_state: BUG! unknown data state\n");
		}

	} else if (ns->nxstate & STATE_ADDR_MASK) {
		/*
		 * If the next state is address input, set the internal
		 * register to the number of expected address bytes
		 */

		ns->regs.count = 0;
1889

L
Linus Torvalds 已提交
1890 1891 1892
		switch (NS_STATE(ns->nxstate)) {
			case STATE_ADDR_PAGE:
				ns->regs.num = ns->geom.pgaddrbytes;
1893

L
Linus Torvalds 已提交
1894 1895 1896 1897
				break;
			case STATE_ADDR_SEC:
				ns->regs.num = ns->geom.secaddrbytes;
				break;
1898

L
Linus Torvalds 已提交
1899 1900 1901 1902
			case STATE_ADDR_ZERO:
				ns->regs.num = 1;
				break;

1903 1904 1905 1906 1907
			case STATE_ADDR_COLUMN:
				/* Column address is always 2 bytes */
				ns->regs.num = ns->geom.pgaddrbytes - ns->geom.secaddrbytes;
				break;

L
Linus Torvalds 已提交
1908 1909 1910 1911
			default:
				NS_ERR("switch_state: BUG! unknown address state\n");
		}
	} else {
1912
		/*
L
Linus Torvalds 已提交
1913 1914 1915 1916 1917 1918 1919 1920
		 * Just reset internal counters.
		 */

		ns->regs.num = 0;
		ns->regs.count = 0;
	}
}

V
Vijay Kumar 已提交
1921
static u_char ns_nand_read_byte(struct mtd_info *mtd)
L
Linus Torvalds 已提交
1922
{
1923
	struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
L
Linus Torvalds 已提交
1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
	u_char outb = 0x00;

	/* Sanity and correctness checks */
	if (!ns->lines.ce) {
		NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
		return outb;
	}
	if (ns->lines.ale || ns->lines.cle) {
		NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
		return outb;
	}
	if (!(ns->state & STATE_DATAOUT_MASK)) {
		NS_WARN("read_byte: unexpected data output cycle, state is %s "
			"return %#x\n", get_state_name(ns->state), (uint)outb);
		return outb;
	}

	/* Status register may be read as many times as it is wanted */
	if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
		NS_DBG("read_byte: return %#x status\n", ns->regs.status);
		return ns->regs.status;
	}

	/* Check if there is any data in the internal buffer which may be read */
	if (ns->regs.count == ns->regs.num) {
		NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
		return outb;
	}

	switch (NS_STATE(ns->state)) {
		case STATE_DATAOUT:
			if (ns->busw == 8) {
				outb = ns->buf.byte[ns->regs.count];
				ns->regs.count += 1;
			} else {
				outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
				ns->regs.count += 2;
			}
			break;
		case STATE_DATAOUT_ID:
			NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
			outb = ns->ids[ns->regs.count];
			ns->regs.count += 1;
			break;
		default:
			BUG();
	}
1971

L
Linus Torvalds 已提交
1972 1973 1974
	if (ns->regs.count == ns->regs.num) {
		NS_DBG("read_byte: all bytes were read\n");

1975
		if (NS_STATE(ns->nxstate) == STATE_READY)
L
Linus Torvalds 已提交
1976 1977
			switch_state(ns);
	}
1978

L
Linus Torvalds 已提交
1979 1980 1981
	return outb;
}

V
Vijay Kumar 已提交
1982
static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
L
Linus Torvalds 已提交
1983
{
1984
	struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
1985

L
Linus Torvalds 已提交
1986 1987 1988 1989 1990 1991 1992 1993 1994
	/* Sanity and correctness checks */
	if (!ns->lines.ce) {
		NS_ERR("write_byte: chip is disabled, ignore write\n");
		return;
	}
	if (ns->lines.ale && ns->lines.cle) {
		NS_ERR("write_byte: ALE and CLE pins are high simultaneously, ignore write\n");
		return;
	}
1995

L
Linus Torvalds 已提交
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
	if (ns->lines.cle == 1) {
		/*
		 * The byte written is a command.
		 */

		if (byte == NAND_CMD_RESET) {
			NS_LOG("reset chip\n");
			switch_to_ready_state(ns, NS_STATUS_OK(ns));
			return;
		}

2007 2008 2009 2010 2011 2012
		/* Check that the command byte is correct */
		if (check_command(byte)) {
			NS_ERR("write_byte: unknown command %#x\n", (uint)byte);
			return;
		}

L
Linus Torvalds 已提交
2013
		if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS
2014 2015 2016
			|| NS_STATE(ns->state) == STATE_DATAOUT) {
			int row = ns->regs.row;

L
Linus Torvalds 已提交
2017
			switch_state(ns);
2018 2019 2020
			if (byte == NAND_CMD_RNDOUT)
				ns->regs.row = row;
		}
L
Linus Torvalds 已提交
2021 2022 2023

		/* Check if chip is expecting command */
		if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
			/* Do not warn if only 2 id bytes are read */
			if (!(ns->regs.command == NAND_CMD_READID &&
			    NS_STATE(ns->state) == STATE_DATAOUT_ID && ns->regs.count == 2)) {
				/*
				 * We are in situation when something else (not command)
				 * was expected but command was input. In this case ignore
				 * previous command(s)/state(s) and accept the last one.
				 */
				NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
					"ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
			}
L
Linus Torvalds 已提交
2035 2036
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
		}
2037

L
Linus Torvalds 已提交
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
		NS_DBG("command byte corresponding to %s state accepted\n",
			get_state_name(get_state_by_command(byte)));
		ns->regs.command = byte;
		switch_state(ns);

	} else if (ns->lines.ale == 1) {
		/*
		 * The byte written is an address.
		 */

		if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {

			NS_DBG("write_byte: operation isn't known yet, identify it\n");

			if (find_operation(ns, 1) < 0)
				return;
2054

L
Linus Torvalds 已提交
2055 2056 2057 2058
			if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
				switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
				return;
			}
2059

L
Linus Torvalds 已提交
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
			ns->regs.count = 0;
			switch (NS_STATE(ns->nxstate)) {
				case STATE_ADDR_PAGE:
					ns->regs.num = ns->geom.pgaddrbytes;
					break;
				case STATE_ADDR_SEC:
					ns->regs.num = ns->geom.secaddrbytes;
					break;
				case STATE_ADDR_ZERO:
					ns->regs.num = 1;
					break;
				default:
					BUG();
			}
		}

		/* Check that chip is expecting address */
		if (!(ns->nxstate & STATE_ADDR_MASK)) {
			NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
				"switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
			return;
		}
2083

L
Linus Torvalds 已提交
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
		/* Check if this is expected byte */
		if (ns->regs.count == ns->regs.num) {
			NS_ERR("write_byte: no more address bytes expected\n");
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
			return;
		}

		accept_addr_byte(ns, byte);

		ns->regs.count += 1;

		NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
				(uint)byte, ns->regs.count, ns->regs.num);

		if (ns->regs.count == ns->regs.num) {
			NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
			switch_state(ns);
		}
2102

L
Linus Torvalds 已提交
2103 2104 2105 2106
	} else {
		/*
		 * The byte written is an input data.
		 */
2107

L
Linus Torvalds 已提交
2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
		/* Check that chip is expecting data input */
		if (!(ns->state & STATE_DATAIN_MASK)) {
			NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
				"switch to %s\n", (uint)byte,
				get_state_name(ns->state), get_state_name(STATE_READY));
			switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
			return;
		}

		/* Check if this is expected byte */
		if (ns->regs.count == ns->regs.num) {
			NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
					ns->regs.num);
			return;
		}

		if (ns->busw == 8) {
			ns->buf.byte[ns->regs.count] = byte;
			ns->regs.count += 1;
		} else {
			ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
			ns->regs.count += 2;
		}
	}

	return;
}

2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
{
	struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;

	ns->lines.cle = bitmask & NAND_CLE ? 1 : 0;
	ns->lines.ale = bitmask & NAND_ALE ? 1 : 0;
	ns->lines.ce = bitmask & NAND_NCE ? 1 : 0;

	if (cmd != NAND_CMD_NONE)
		ns_nand_write_byte(mtd, cmd);
}

V
Vijay Kumar 已提交
2148
static int ns_device_ready(struct mtd_info *mtd)
L
Linus Torvalds 已提交
2149 2150 2151 2152 2153
{
	NS_DBG("device_ready\n");
	return 1;
}

V
Vijay Kumar 已提交
2154
static uint16_t ns_nand_read_word(struct mtd_info *mtd)
L
Linus Torvalds 已提交
2155 2156 2157 2158
{
	struct nand_chip *chip = (struct nand_chip *)mtd->priv;

	NS_DBG("read_word\n");
2159

L
Linus Torvalds 已提交
2160 2161 2162
	return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
}

V
Vijay Kumar 已提交
2163
static void ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
L
Linus Torvalds 已提交
2164
{
2165
	struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
L
Linus Torvalds 已提交
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183

	/* Check that chip is expecting data input */
	if (!(ns->state & STATE_DATAIN_MASK)) {
		NS_ERR("write_buf: data input isn't expected, state is %s, "
			"switch to STATE_READY\n", get_state_name(ns->state));
		switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
		return;
	}

	/* Check if these are expected bytes */
	if (ns->regs.count + len > ns->regs.num) {
		NS_ERR("write_buf: too many input bytes\n");
		switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
		return;
	}

	memcpy(ns->buf.byte + ns->regs.count, buf, len);
	ns->regs.count += len;
2184

L
Linus Torvalds 已提交
2185 2186 2187 2188 2189
	if (ns->regs.count == ns->regs.num) {
		NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
	}
}

V
Vijay Kumar 已提交
2190
static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
L
Linus Torvalds 已提交
2191
{
2192
	struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
L
Linus Torvalds 已提交
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226

	/* Sanity and correctness checks */
	if (!ns->lines.ce) {
		NS_ERR("read_buf: chip is disabled\n");
		return;
	}
	if (ns->lines.ale || ns->lines.cle) {
		NS_ERR("read_buf: ALE or CLE pin is high\n");
		return;
	}
	if (!(ns->state & STATE_DATAOUT_MASK)) {
		NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
			get_state_name(ns->state));
		return;
	}

	if (NS_STATE(ns->state) != STATE_DATAOUT) {
		int i;

		for (i = 0; i < len; i++)
			buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);

		return;
	}

	/* Check if these are expected bytes */
	if (ns->regs.count + len > ns->regs.num) {
		NS_ERR("read_buf: too many bytes to read\n");
		switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
		return;
	}

	memcpy(buf, ns->buf.byte + ns->regs.count, len);
	ns->regs.count += len;
2227

L
Linus Torvalds 已提交
2228
	if (ns->regs.count == ns->regs.num) {
2229
		if (NS_STATE(ns->nxstate) == STATE_READY)
L
Linus Torvalds 已提交
2230 2231
			switch_state(ns);
	}
2232

L
Linus Torvalds 已提交
2233 2234 2235 2236 2237 2238
	return;
}

/*
 * Module initialization function
 */
2239
static int __init ns_init_module(void)
L
Linus Torvalds 已提交
2240 2241 2242
{
	struct nand_chip *chip;
	struct nandsim *nand;
2243
	int retval = -ENOMEM, i;
L
Linus Torvalds 已提交
2244 2245 2246 2247 2248

	if (bus_width != 8 && bus_width != 16) {
		NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
		return -EINVAL;
	}
2249

L
Linus Torvalds 已提交
2250
	/* Allocate and initialize mtd_info, nand_chip and nandsim structures */
2251
	nsmtd = kzalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip)
L
Linus Torvalds 已提交
2252 2253 2254 2255 2256 2257 2258 2259
				+ sizeof(struct nandsim), GFP_KERNEL);
	if (!nsmtd) {
		NS_ERR("unable to allocate core structures.\n");
		return -ENOMEM;
	}
	chip        = (struct nand_chip *)(nsmtd + 1);
        nsmtd->priv = (void *)chip;
	nand        = (struct nandsim *)(chip + 1);
2260
	chip->priv  = (void *)nand;
L
Linus Torvalds 已提交
2261 2262 2263 2264

	/*
	 * Register simulator's callbacks.
	 */
2265
	chip->cmd_ctrl	 = ns_hwcontrol;
L
Linus Torvalds 已提交
2266 2267 2268 2269 2270
	chip->read_byte  = ns_nand_read_byte;
	chip->dev_ready  = ns_device_ready;
	chip->write_buf  = ns_nand_write_buf;
	chip->read_buf   = ns_nand_read_buf;
	chip->read_word  = ns_nand_read_word;
T
Thomas Gleixner 已提交
2271
	chip->ecc.mode   = NAND_ECC_SOFT;
2272 2273
	/* The NAND_SKIP_BBTSCAN option is necessary for 'overridesize' */
	/* and 'badblocks' parameters to work */
2274
	chip->options   |= NAND_SKIP_BBTSCAN;
L
Linus Torvalds 已提交
2275

2276 2277
	switch (bbt) {
	case 2:
2278
		 chip->bbt_options |= NAND_BBT_NO_OOB;
2279
	case 1:
2280
		 chip->bbt_options |= NAND_BBT_USE_FLASH;
2281 2282 2283 2284 2285 2286 2287
	case 0:
		break;
	default:
		NS_ERR("bbt has to be 0..2\n");
		retval = -EINVAL;
		goto error;
	}
2288
	/*
L
Linus Torvalds 已提交
2289
	 * Perform minimum nandsim structure initialization to handle
2290
	 * the initial ID read command correctly
L
Linus Torvalds 已提交
2291
	 */
2292 2293 2294 2295 2296
	if (id_bytes[6] != 0xFF || id_bytes[7] != 0xFF)
		nand->geom.idbytes = 8;
	else if (id_bytes[4] != 0xFF || id_bytes[5] != 0xFF)
		nand->geom.idbytes = 6;
	else if (id_bytes[2] != 0xFF || id_bytes[3] != 0xFF)
L
Linus Torvalds 已提交
2297 2298 2299 2300 2301
		nand->geom.idbytes = 4;
	else
		nand->geom.idbytes = 2;
	nand->regs.status = NS_STATUS_OK(nand);
	nand->nxstate = STATE_UNKNOWN;
2302
	nand->options |= OPT_PAGE512; /* temporary value */
2303
	memcpy(nand->ids, id_bytes, sizeof(nand->ids));
L
Linus Torvalds 已提交
2304 2305 2306 2307 2308
	if (bus_width == 16) {
		nand->busw = 16;
		chip->options |= NAND_BUSWIDTH_16;
	}

2309 2310
	nsmtd->owner = THIS_MODULE;

2311 2312 2313 2314 2315 2316 2317 2318 2319
	if ((retval = parse_weakblocks()) != 0)
		goto error;

	if ((retval = parse_weakpages()) != 0)
		goto error;

	if ((retval = parse_gravepages()) != 0)
		goto error;

2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
	retval = nand_scan_ident(nsmtd, 1, NULL);
	if (retval) {
		NS_ERR("cannot scan NAND Simulator device\n");
		if (retval > 0)
			retval = -ENXIO;
		goto error;
	}

	if (bch) {
		unsigned int eccsteps, eccbytes;
		if (!mtd_nand_has_bch()) {
			NS_ERR("BCH ECC support is disabled\n");
			retval = -EINVAL;
			goto error;
		}
		/* use 512-byte ecc blocks */
		eccsteps = nsmtd->writesize/512;
		eccbytes = (bch*13+7)/8;
		/* do not bother supporting small page devices */
		if ((nsmtd->oobsize < 64) || !eccsteps) {
			NS_ERR("bch not available on small page devices\n");
			retval = -EINVAL;
			goto error;
		}
		if ((eccbytes*eccsteps+2) > nsmtd->oobsize) {
			NS_ERR("invalid bch value %u\n", bch);
			retval = -EINVAL;
			goto error;
		}
		chip->ecc.mode = NAND_ECC_SOFT_BCH;
		chip->ecc.size = 512;
2351
		chip->ecc.strength = bch;
2352 2353 2354 2355 2356 2357
		chip->ecc.bytes = eccbytes;
		NS_INFO("using %u-bit/%u bytes BCH ECC\n", bch, chip->ecc.size);
	}

	retval = nand_scan_tail(nsmtd);
	if (retval) {
L
Linus Torvalds 已提交
2358 2359 2360 2361 2362 2363
		NS_ERR("can't register NAND Simulator\n");
		if (retval > 0)
			retval = -ENXIO;
		goto error;
	}

2364
	if (overridesize) {
2365
		uint64_t new_size = (uint64_t)nsmtd->erasesize << overridesize;
2366 2367
		if (new_size >> overridesize != nsmtd->erasesize) {
			NS_ERR("overridesize is too big\n");
2368
			retval = -EINVAL;
2369 2370 2371 2372 2373
			goto err_exit;
		}
		/* N.B. This relies on nand_scan not doing anything with the size before we change it */
		nsmtd->size = new_size;
		chip->chipsize = new_size;
2374
		chip->chip_shift = ffs(nsmtd->erasesize) + overridesize - 1;
2375
		chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
2376 2377
	}

2378 2379 2380
	if ((retval = setup_wear_reporting(nsmtd)) != 0)
		goto err_exit;

2381 2382 2383
	if ((retval = nandsim_debugfs_create(nand)) != 0)
		goto err_exit;

2384 2385
	if ((retval = init_nandsim(nsmtd)) != 0)
		goto err_exit;
2386

2387
	if ((retval = chip->scan_bbt(nsmtd)) != 0)
2388 2389
		goto err_exit;

2390
	if ((retval = parse_badblocks(nand, nsmtd)) != 0)
2391
		goto err_exit;
2392

2393
	/* Register NAND partitions */
2394 2395 2396
	retval = mtd_device_register(nsmtd, &nand->partitions[0],
				     nand->nbparts);
	if (retval != 0)
2397
		goto err_exit;
L
Linus Torvalds 已提交
2398 2399 2400

        return 0;

2401 2402 2403 2404 2405
err_exit:
	free_nandsim(nand);
	nand_release(nsmtd);
	for (i = 0;i < ARRAY_SIZE(nand->partitions); ++i)
		kfree(nand->partitions[i].name);
L
Linus Torvalds 已提交
2406 2407
error:
	kfree(nsmtd);
2408
	free_lists();
L
Linus Torvalds 已提交
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419

	return retval;
}

module_init(ns_init_module);

/*
 * Module clean-up function
 */
static void __exit ns_cleanup_module(void)
{
2420
	struct nandsim *ns = ((struct nand_chip *)nsmtd->priv)->priv;
2421
	int i;
L
Linus Torvalds 已提交
2422

2423
	nandsim_debugfs_remove(ns);
L
Linus Torvalds 已提交
2424
	free_nandsim(ns);    /* Free nandsim private resources */
2425 2426 2427
	nand_release(nsmtd); /* Unregister driver */
	for (i = 0;i < ARRAY_SIZE(ns->partitions); ++i)
		kfree(ns->partitions[i].name);
L
Linus Torvalds 已提交
2428
	kfree(nsmtd);        /* Free other structures */
2429
	free_lists();
L
Linus Torvalds 已提交
2430 2431 2432 2433 2434 2435 2436
}

module_exit(ns_cleanup_module);

MODULE_LICENSE ("GPL");
MODULE_AUTHOR ("Artem B. Bityuckiy");
MODULE_DESCRIPTION ("The NAND flash simulator");