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