2 * NAND flash simulator.
4 * Author: Artem B. Bityuckiy <dedekind@oktetlabs.ru>, <dedekind@infradead.org>
6 * Copyright (C) 2004 Nokia Corporation
8 * Note: NS means "NAND Simulator".
9 * Note: Input means input TO flash chip, output means output FROM chip.
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2, or (at your option) any later
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
26 #include <linux/init.h>
27 #include <linux/types.h>
28 #include <linux/module.h>
29 #include <linux/moduleparam.h>
30 #include <linux/vmalloc.h>
31 #include <linux/slab.h>
32 #include <linux/errno.h>
33 #include <linux/string.h>
34 #include <linux/mtd/mtd.h>
35 #include <linux/mtd/nand.h>
36 #include <linux/mtd/partitions.h>
37 #include <linux/delay.h>
38 #include <linux/list.h>
39 #include <linux/random.h>
40 #include <asm/div64.h>
42 /* Default simulator parameters values */
43 #if !defined(CONFIG_NANDSIM_FIRST_ID_BYTE) || \
44 !defined(CONFIG_NANDSIM_SECOND_ID_BYTE) || \
45 !defined(CONFIG_NANDSIM_THIRD_ID_BYTE) || \
46 !defined(CONFIG_NANDSIM_FOURTH_ID_BYTE)
47 #define CONFIG_NANDSIM_FIRST_ID_BYTE 0x98
48 #define CONFIG_NANDSIM_SECOND_ID_BYTE 0x39
49 #define CONFIG_NANDSIM_THIRD_ID_BYTE 0xFF /* No byte */
50 #define CONFIG_NANDSIM_FOURTH_ID_BYTE 0xFF /* No byte */
53 #ifndef CONFIG_NANDSIM_ACCESS_DELAY
54 #define CONFIG_NANDSIM_ACCESS_DELAY 25
56 #ifndef CONFIG_NANDSIM_PROGRAMM_DELAY
57 #define CONFIG_NANDSIM_PROGRAMM_DELAY 200
59 #ifndef CONFIG_NANDSIM_ERASE_DELAY
60 #define CONFIG_NANDSIM_ERASE_DELAY 2
62 #ifndef CONFIG_NANDSIM_OUTPUT_CYCLE
63 #define CONFIG_NANDSIM_OUTPUT_CYCLE 40
65 #ifndef CONFIG_NANDSIM_INPUT_CYCLE
66 #define CONFIG_NANDSIM_INPUT_CYCLE 50
68 #ifndef CONFIG_NANDSIM_BUS_WIDTH
69 #define CONFIG_NANDSIM_BUS_WIDTH 8
71 #ifndef CONFIG_NANDSIM_DO_DELAYS
72 #define CONFIG_NANDSIM_DO_DELAYS 0
74 #ifndef CONFIG_NANDSIM_LOG
75 #define CONFIG_NANDSIM_LOG 0
77 #ifndef CONFIG_NANDSIM_DBG
78 #define CONFIG_NANDSIM_DBG 0
81 static uint first_id_byte = CONFIG_NANDSIM_FIRST_ID_BYTE;
82 static uint second_id_byte = CONFIG_NANDSIM_SECOND_ID_BYTE;
83 static uint third_id_byte = CONFIG_NANDSIM_THIRD_ID_BYTE;
84 static uint fourth_id_byte = CONFIG_NANDSIM_FOURTH_ID_BYTE;
85 static uint access_delay = CONFIG_NANDSIM_ACCESS_DELAY;
86 static uint programm_delay = CONFIG_NANDSIM_PROGRAMM_DELAY;
87 static uint erase_delay = CONFIG_NANDSIM_ERASE_DELAY;
88 static uint output_cycle = CONFIG_NANDSIM_OUTPUT_CYCLE;
89 static uint input_cycle = CONFIG_NANDSIM_INPUT_CYCLE;
90 static uint bus_width = CONFIG_NANDSIM_BUS_WIDTH;
91 static uint do_delays = CONFIG_NANDSIM_DO_DELAYS;
92 static uint log = CONFIG_NANDSIM_LOG;
93 static uint dbg = CONFIG_NANDSIM_DBG;
94 static unsigned long parts[MAX_MTD_DEVICES];
95 static unsigned int parts_num;
96 static char *badblocks = NULL;
97 static char *weakblocks = NULL;
98 static char *weakpages = NULL;
99 static unsigned int bitflips = 0;
100 static char *gravepages = NULL;
101 static unsigned int rptwear = 0;
102 static unsigned int overridesize = 0;
104 module_param(first_id_byte, uint, 0400);
105 module_param(second_id_byte, uint, 0400);
106 module_param(third_id_byte, uint, 0400);
107 module_param(fourth_id_byte, uint, 0400);
108 module_param(access_delay, uint, 0400);
109 module_param(programm_delay, uint, 0400);
110 module_param(erase_delay, uint, 0400);
111 module_param(output_cycle, uint, 0400);
112 module_param(input_cycle, uint, 0400);
113 module_param(bus_width, uint, 0400);
114 module_param(do_delays, uint, 0400);
115 module_param(log, uint, 0400);
116 module_param(dbg, uint, 0400);
117 module_param_array(parts, ulong, &parts_num, 0400);
118 module_param(badblocks, charp, 0400);
119 module_param(weakblocks, charp, 0400);
120 module_param(weakpages, charp, 0400);
121 module_param(bitflips, uint, 0400);
122 module_param(gravepages, charp, 0400);
123 module_param(rptwear, uint, 0400);
124 module_param(overridesize, uint, 0400);
126 MODULE_PARM_DESC(first_id_byte, "The first byte returned by NAND Flash 'read ID' command (manufacturer ID)");
127 MODULE_PARM_DESC(second_id_byte, "The second byte returned by NAND Flash 'read ID' command (chip ID)");
128 MODULE_PARM_DESC(third_id_byte, "The third byte returned by NAND Flash 'read ID' command");
129 MODULE_PARM_DESC(fourth_id_byte, "The fourth byte returned by NAND Flash 'read ID' command");
130 MODULE_PARM_DESC(access_delay, "Initial page access delay (microiseconds)");
131 MODULE_PARM_DESC(programm_delay, "Page programm delay (microseconds");
132 MODULE_PARM_DESC(erase_delay, "Sector erase delay (milliseconds)");
133 MODULE_PARM_DESC(output_cycle, "Word output (from flash) time (nanodeconds)");
134 MODULE_PARM_DESC(input_cycle, "Word input (to flash) time (nanodeconds)");
135 MODULE_PARM_DESC(bus_width, "Chip's bus width (8- or 16-bit)");
136 MODULE_PARM_DESC(do_delays, "Simulate NAND delays using busy-waits if not zero");
137 MODULE_PARM_DESC(log, "Perform logging if not zero");
138 MODULE_PARM_DESC(dbg, "Output debug information if not zero");
139 MODULE_PARM_DESC(parts, "Partition sizes (in erase blocks) separated by commas");
140 /* Page and erase block positions for the following parameters are independent of any partitions */
141 MODULE_PARM_DESC(badblocks, "Erase blocks that are initially marked bad, separated by commas");
142 MODULE_PARM_DESC(weakblocks, "Weak erase blocks [: remaining erase cycles (defaults to 3)]"
143 " separated by commas e.g. 113:2 means eb 113"
144 " can be erased only twice before failing");
145 MODULE_PARM_DESC(weakpages, "Weak pages [: maximum writes (defaults to 3)]"
146 " separated by commas e.g. 1401:2 means page 1401"
147 " can be written only twice before failing");
148 MODULE_PARM_DESC(bitflips, "Maximum number of random bit flips per page (zero by default)");
149 MODULE_PARM_DESC(gravepages, "Pages that lose data [: maximum reads (defaults to 3)]"
150 " separated by commas e.g. 1401:2 means page 1401"
151 " can be read only twice before failing");
152 MODULE_PARM_DESC(rptwear, "Number of erases inbetween reporting wear, if not zero");
153 MODULE_PARM_DESC(overridesize, "Specifies the NAND Flash size overriding the ID bytes. "
154 "The size is specified in erase blocks and as the exponent of a power of two"
155 " e.g. 5 means a size of 32 erase blocks");
157 /* The largest possible page size */
158 #define NS_LARGEST_PAGE_SIZE 2048
160 /* The prefix for simulator output */
161 #define NS_OUTPUT_PREFIX "[nandsim]"
163 /* Simulator's output macros (logging, debugging, warning, error) */
164 #define NS_LOG(args...) \
165 do { if (log) printk(KERN_DEBUG NS_OUTPUT_PREFIX " log: " args); } while(0)
166 #define NS_DBG(args...) \
167 do { if (dbg) printk(KERN_DEBUG NS_OUTPUT_PREFIX " debug: " args); } while(0)
168 #define NS_WARN(args...) \
169 do { printk(KERN_WARNING NS_OUTPUT_PREFIX " warning: " args); } while(0)
170 #define NS_ERR(args...) \
171 do { printk(KERN_ERR NS_OUTPUT_PREFIX " error: " args); } while(0)
172 #define NS_INFO(args...) \
173 do { printk(KERN_INFO NS_OUTPUT_PREFIX " " args); } while(0)
175 /* Busy-wait delay macros (microseconds, milliseconds) */
176 #define NS_UDELAY(us) \
177 do { if (do_delays) udelay(us); } while(0)
178 #define NS_MDELAY(us) \
179 do { if (do_delays) mdelay(us); } while(0)
181 /* Is the nandsim structure initialized ? */
182 #define NS_IS_INITIALIZED(ns) ((ns)->geom.totsz != 0)
184 /* Good operation completion status */
185 #define NS_STATUS_OK(ns) (NAND_STATUS_READY | (NAND_STATUS_WP * ((ns)->lines.wp == 0)))
187 /* Operation failed completion status */
188 #define NS_STATUS_FAILED(ns) (NAND_STATUS_FAIL | NS_STATUS_OK(ns))
190 /* Calculate the page offset in flash RAM image by (row, column) address */
191 #define NS_RAW_OFFSET(ns) \
192 (((ns)->regs.row << (ns)->geom.pgshift) + ((ns)->regs.row * (ns)->geom.oobsz) + (ns)->regs.column)
194 /* Calculate the OOB offset in flash RAM image by (row, column) address */
195 #define NS_RAW_OFFSET_OOB(ns) (NS_RAW_OFFSET(ns) + ns->geom.pgsz)
197 /* After a command is input, the simulator goes to one of the following states */
198 #define STATE_CMD_READ0 0x00000001 /* read data from the beginning of page */
199 #define STATE_CMD_READ1 0x00000002 /* read data from the second half of page */
200 #define STATE_CMD_READSTART 0x00000003 /* read data second command (large page devices) */
201 #define STATE_CMD_PAGEPROG 0x00000004 /* start page programm */
202 #define STATE_CMD_READOOB 0x00000005 /* read OOB area */
203 #define STATE_CMD_ERASE1 0x00000006 /* sector erase first command */
204 #define STATE_CMD_STATUS 0x00000007 /* read status */
205 #define STATE_CMD_STATUS_M 0x00000008 /* read multi-plane status (isn't implemented) */
206 #define STATE_CMD_SEQIN 0x00000009 /* sequential data imput */
207 #define STATE_CMD_READID 0x0000000A /* read ID */
208 #define STATE_CMD_ERASE2 0x0000000B /* sector erase second command */
209 #define STATE_CMD_RESET 0x0000000C /* reset */
210 #define STATE_CMD_MASK 0x0000000F /* command states mask */
212 /* After an address is input, the simulator goes to one of these states */
213 #define STATE_ADDR_PAGE 0x00000010 /* full (row, column) address is accepted */
214 #define STATE_ADDR_SEC 0x00000020 /* sector address was accepted */
215 #define STATE_ADDR_ZERO 0x00000030 /* one byte zero address was accepted */
216 #define STATE_ADDR_MASK 0x00000030 /* address states mask */
218 /* Durind data input/output the simulator is in these states */
219 #define STATE_DATAIN 0x00000100 /* waiting for data input */
220 #define STATE_DATAIN_MASK 0x00000100 /* data input states mask */
222 #define STATE_DATAOUT 0x00001000 /* waiting for page data output */
223 #define STATE_DATAOUT_ID 0x00002000 /* waiting for ID bytes output */
224 #define STATE_DATAOUT_STATUS 0x00003000 /* waiting for status output */
225 #define STATE_DATAOUT_STATUS_M 0x00004000 /* waiting for multi-plane status output */
226 #define STATE_DATAOUT_MASK 0x00007000 /* data output states mask */
228 /* Previous operation is done, ready to accept new requests */
229 #define STATE_READY 0x00000000
231 /* This state is used to mark that the next state isn't known yet */
232 #define STATE_UNKNOWN 0x10000000
234 /* Simulator's actions bit masks */
235 #define ACTION_CPY 0x00100000 /* copy page/OOB to the internal buffer */
236 #define ACTION_PRGPAGE 0x00200000 /* programm the internal buffer to flash */
237 #define ACTION_SECERASE 0x00300000 /* erase sector */
238 #define ACTION_ZEROOFF 0x00400000 /* don't add any offset to address */
239 #define ACTION_HALFOFF 0x00500000 /* add to address half of page */
240 #define ACTION_OOBOFF 0x00600000 /* add to address OOB offset */
241 #define ACTION_MASK 0x00700000 /* action mask */
243 #define NS_OPER_NUM 12 /* Number of operations supported by the simulator */
244 #define NS_OPER_STATES 6 /* Maximum number of states in operation */
246 #define OPT_ANY 0xFFFFFFFF /* any chip supports this operation */
247 #define OPT_PAGE256 0x00000001 /* 256-byte page chips */
248 #define OPT_PAGE512 0x00000002 /* 512-byte page chips */
249 #define OPT_PAGE2048 0x00000008 /* 2048-byte page chips */
250 #define OPT_SMARTMEDIA 0x00000010 /* SmartMedia technology chips */
251 #define OPT_AUTOINCR 0x00000020 /* page number auto inctimentation is possible */
252 #define OPT_PAGE512_8BIT 0x00000040 /* 512-byte page chips with 8-bit bus width */
253 #define OPT_LARGEPAGE (OPT_PAGE2048) /* 2048-byte page chips */
254 #define OPT_SMALLPAGE (OPT_PAGE256 | OPT_PAGE512) /* 256 and 512-byte page chips */
256 /* Remove action bits ftom state */
257 #define NS_STATE(x) ((x) & ~ACTION_MASK)
260 * Maximum previous states which need to be saved. Currently saving is
261 * only needed for page programm operation with preceeded read command
262 * (which is only valid for 512-byte pages).
264 #define NS_MAX_PREVSTATES 1
267 * A union to represent flash memory contents and flash buffer.
270 u_char *byte; /* for byte access */
271 uint16_t *word; /* for 16-bit word access */
275 * The structure which describes all the internal simulator data.
278 struct mtd_partition partitions[MAX_MTD_DEVICES];
279 unsigned int nbparts;
281 uint busw; /* flash chip bus width (8 or 16) */
282 u_char ids[4]; /* chip's ID bytes */
283 uint32_t options; /* chip's characteristic bits */
284 uint32_t state; /* current chip state */
285 uint32_t nxstate; /* next expected state */
287 uint32_t *op; /* current operation, NULL operations isn't known yet */
288 uint32_t pstates[NS_MAX_PREVSTATES]; /* previous states */
289 uint16_t npstates; /* number of previous states saved */
290 uint16_t stateidx; /* current state index */
292 /* The simulated NAND flash pages array */
295 /* Internal buffer of page + OOB size bytes */
298 /* NAND flash "geometry" */
299 struct nandsin_geometry {
300 uint64_t totsz; /* total flash size, bytes */
301 uint32_t secsz; /* flash sector (erase block) size, bytes */
302 uint pgsz; /* NAND flash page size, bytes */
303 uint oobsz; /* page OOB area size, bytes */
304 uint64_t totszoob; /* total flash size including OOB, bytes */
305 uint pgszoob; /* page size including OOB , bytes*/
306 uint secszoob; /* sector size including OOB, bytes */
307 uint pgnum; /* total number of pages */
308 uint pgsec; /* number of pages per sector */
309 uint secshift; /* bits number in sector size */
310 uint pgshift; /* bits number in page size */
311 uint oobshift; /* bits number in OOB size */
312 uint pgaddrbytes; /* bytes per page address */
313 uint secaddrbytes; /* bytes per sector address */
314 uint idbytes; /* the number ID bytes that this chip outputs */
317 /* NAND flash internal registers */
318 struct nandsim_regs {
319 unsigned command; /* the command register */
320 u_char status; /* the status register */
321 uint row; /* the page number */
322 uint column; /* the offset within page */
323 uint count; /* internal counter */
324 uint num; /* number of bytes which must be processed */
325 uint off; /* fixed page offset */
328 /* NAND flash lines state */
329 struct ns_lines_status {
330 int ce; /* chip Enable */
331 int cle; /* command Latch Enable */
332 int ale; /* address Latch Enable */
333 int wp; /* write Protect */
338 * Operations array. To perform any operation the simulator must pass
339 * through the correspondent states chain.
341 static struct nandsim_operations {
342 uint32_t reqopts; /* options which are required to perform the operation */
343 uint32_t states[NS_OPER_STATES]; /* operation's states */
344 } ops[NS_OPER_NUM] = {
345 /* Read page + OOB from the beginning */
346 {OPT_SMALLPAGE, {STATE_CMD_READ0 | ACTION_ZEROOFF, STATE_ADDR_PAGE | ACTION_CPY,
347 STATE_DATAOUT, STATE_READY}},
348 /* Read page + OOB from the second half */
349 {OPT_PAGE512_8BIT, {STATE_CMD_READ1 | ACTION_HALFOFF, STATE_ADDR_PAGE | ACTION_CPY,
350 STATE_DATAOUT, STATE_READY}},
352 {OPT_SMALLPAGE, {STATE_CMD_READOOB | ACTION_OOBOFF, STATE_ADDR_PAGE | ACTION_CPY,
353 STATE_DATAOUT, STATE_READY}},
354 /* Programm page starting from the beginning */
355 {OPT_ANY, {STATE_CMD_SEQIN, STATE_ADDR_PAGE, STATE_DATAIN,
356 STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
357 /* Programm page starting from the beginning */
358 {OPT_SMALLPAGE, {STATE_CMD_READ0, STATE_CMD_SEQIN | ACTION_ZEROOFF, STATE_ADDR_PAGE,
359 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
360 /* Programm page starting from the second half */
361 {OPT_PAGE512, {STATE_CMD_READ1, STATE_CMD_SEQIN | ACTION_HALFOFF, STATE_ADDR_PAGE,
362 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
364 {OPT_SMALLPAGE, {STATE_CMD_READOOB, STATE_CMD_SEQIN | ACTION_OOBOFF, STATE_ADDR_PAGE,
365 STATE_DATAIN, STATE_CMD_PAGEPROG | ACTION_PRGPAGE, STATE_READY}},
367 {OPT_ANY, {STATE_CMD_ERASE1, STATE_ADDR_SEC, STATE_CMD_ERASE2 | ACTION_SECERASE, STATE_READY}},
369 {OPT_ANY, {STATE_CMD_STATUS, STATE_DATAOUT_STATUS, STATE_READY}},
370 /* Read multi-plane status */
371 {OPT_SMARTMEDIA, {STATE_CMD_STATUS_M, STATE_DATAOUT_STATUS_M, STATE_READY}},
373 {OPT_ANY, {STATE_CMD_READID, STATE_ADDR_ZERO, STATE_DATAOUT_ID, STATE_READY}},
374 /* Large page devices read page */
375 {OPT_LARGEPAGE, {STATE_CMD_READ0, STATE_ADDR_PAGE, STATE_CMD_READSTART | ACTION_CPY,
376 STATE_DATAOUT, STATE_READY}}
380 struct list_head list;
381 unsigned int erase_block_no;
382 unsigned int max_erases;
383 unsigned int erases_done;
386 static LIST_HEAD(weak_blocks);
389 struct list_head list;
390 unsigned int page_no;
391 unsigned int max_writes;
392 unsigned int writes_done;
395 static LIST_HEAD(weak_pages);
398 struct list_head list;
399 unsigned int page_no;
400 unsigned int max_reads;
401 unsigned int reads_done;
404 static LIST_HEAD(grave_pages);
406 static unsigned long *erase_block_wear = NULL;
407 static unsigned int wear_eb_count = 0;
408 static unsigned long total_wear = 0;
409 static unsigned int rptwear_cnt = 0;
411 /* MTD structure for NAND controller */
412 static struct mtd_info *nsmtd;
414 static u_char ns_verify_buf[NS_LARGEST_PAGE_SIZE];
417 * Allocate array of page pointers and initialize the array to NULL
420 * RETURNS: 0 if success, -ENOMEM if memory alloc fails.
422 static int alloc_device(struct nandsim *ns)
426 ns->pages = vmalloc(ns->geom.pgnum * sizeof(union ns_mem));
428 NS_ERR("alloc_map: unable to allocate page array\n");
431 for (i = 0; i < ns->geom.pgnum; i++) {
432 ns->pages[i].byte = NULL;
439 * Free any allocated pages, and free the array of page pointers.
441 static void free_device(struct nandsim *ns)
446 for (i = 0; i < ns->geom.pgnum; i++) {
447 if (ns->pages[i].byte)
448 kfree(ns->pages[i].byte);
454 static char *get_partition_name(int i)
457 sprintf(buf, "NAND simulator partition %d", i);
458 return kstrdup(buf, GFP_KERNEL);
461 static u_int64_t divide(u_int64_t n, u_int32_t d)
468 * Initialize the nandsim structure.
470 * RETURNS: 0 if success, -ERRNO if failure.
472 static int init_nandsim(struct mtd_info *mtd)
474 struct nand_chip *chip = (struct nand_chip *)mtd->priv;
475 struct nandsim *ns = (struct nandsim *)(chip->priv);
478 u_int64_t next_offset;
480 if (NS_IS_INITIALIZED(ns)) {
481 NS_ERR("init_nandsim: nandsim is already initialized\n");
485 /* Force mtd to not do delays */
486 chip->chip_delay = 0;
488 /* Initialize the NAND flash parameters */
489 ns->busw = chip->options & NAND_BUSWIDTH_16 ? 16 : 8;
490 ns->geom.totsz = mtd->size;
491 ns->geom.pgsz = mtd->writesize;
492 ns->geom.oobsz = mtd->oobsize;
493 ns->geom.secsz = mtd->erasesize;
494 ns->geom.pgszoob = ns->geom.pgsz + ns->geom.oobsz;
495 ns->geom.pgnum = divide(ns->geom.totsz, ns->geom.pgsz);
496 ns->geom.totszoob = ns->geom.totsz + (uint64_t)ns->geom.pgnum * ns->geom.oobsz;
497 ns->geom.secshift = ffs(ns->geom.secsz) - 1;
498 ns->geom.pgshift = chip->page_shift;
499 ns->geom.oobshift = ffs(ns->geom.oobsz) - 1;
500 ns->geom.pgsec = ns->geom.secsz / ns->geom.pgsz;
501 ns->geom.secszoob = ns->geom.secsz + ns->geom.oobsz * ns->geom.pgsec;
504 if (ns->geom.pgsz == 256) {
505 ns->options |= OPT_PAGE256;
507 else if (ns->geom.pgsz == 512) {
508 ns->options |= (OPT_PAGE512 | OPT_AUTOINCR);
510 ns->options |= OPT_PAGE512_8BIT;
511 } else if (ns->geom.pgsz == 2048) {
512 ns->options |= OPT_PAGE2048;
514 NS_ERR("init_nandsim: unknown page size %u\n", ns->geom.pgsz);
518 if (ns->options & OPT_SMALLPAGE) {
519 if (ns->geom.totsz <= (32 << 20)) {
520 ns->geom.pgaddrbytes = 3;
521 ns->geom.secaddrbytes = 2;
523 ns->geom.pgaddrbytes = 4;
524 ns->geom.secaddrbytes = 3;
527 if (ns->geom.totsz <= (128 << 20)) {
528 ns->geom.pgaddrbytes = 4;
529 ns->geom.secaddrbytes = 2;
531 ns->geom.pgaddrbytes = 5;
532 ns->geom.secaddrbytes = 3;
536 /* Fill the partition_info structure */
537 if (parts_num > ARRAY_SIZE(ns->partitions)) {
538 NS_ERR("too many partitions.\n");
542 remains = ns->geom.totsz;
544 for (i = 0; i < parts_num; ++i) {
545 u_int64_t part_sz = (u_int64_t)parts[i] * ns->geom.secsz;
547 if (!part_sz || part_sz > remains) {
548 NS_ERR("bad partition size.\n");
552 ns->partitions[i].name = get_partition_name(i);
553 ns->partitions[i].offset = next_offset;
554 ns->partitions[i].size = part_sz;
555 next_offset += ns->partitions[i].size;
556 remains -= ns->partitions[i].size;
558 ns->nbparts = parts_num;
560 if (parts_num + 1 > ARRAY_SIZE(ns->partitions)) {
561 NS_ERR("too many partitions.\n");
565 ns->partitions[i].name = get_partition_name(i);
566 ns->partitions[i].offset = next_offset;
567 ns->partitions[i].size = remains;
571 /* Detect how many ID bytes the NAND chip outputs */
572 for (i = 0; nand_flash_ids[i].name != NULL; i++) {
573 if (second_id_byte != nand_flash_ids[i].id)
575 if (!(nand_flash_ids[i].options & NAND_NO_AUTOINCR))
576 ns->options |= OPT_AUTOINCR;
580 NS_WARN("16-bit flashes support wasn't tested\n");
582 printk("flash size: %llu MiB\n", ns->geom.totsz >> 20);
583 printk("page size: %u bytes\n", ns->geom.pgsz);
584 printk("OOB area size: %u bytes\n", ns->geom.oobsz);
585 printk("sector size: %u KiB\n", ns->geom.secsz >> 10);
586 printk("pages number: %u\n", ns->geom.pgnum);
587 printk("pages per sector: %u\n", ns->geom.pgsec);
588 printk("bus width: %u\n", ns->busw);
589 printk("bits in sector size: %u\n", ns->geom.secshift);
590 printk("bits in page size: %u\n", ns->geom.pgshift);
591 printk("bits in OOB size: %u\n", ns->geom.oobshift);
592 printk("flash size with OOB: %llu KiB\n", ns->geom.totszoob >> 10);
593 printk("page address bytes: %u\n", ns->geom.pgaddrbytes);
594 printk("sector address bytes: %u\n", ns->geom.secaddrbytes);
595 printk("options: %#x\n", ns->options);
597 if ((ret = alloc_device(ns)) != 0)
600 /* Allocate / initialize the internal buffer */
601 ns->buf.byte = kmalloc(ns->geom.pgszoob, GFP_KERNEL);
603 NS_ERR("init_nandsim: unable to allocate %u bytes for the internal buffer\n",
608 memset(ns->buf.byte, 0xFF, ns->geom.pgszoob);
619 * Free the nandsim structure.
621 static void free_nandsim(struct nandsim *ns)
629 static int parse_badblocks(struct nandsim *ns, struct mtd_info *mtd)
633 unsigned int erase_block_no;
640 zero_ok = (*w == '0' ? 1 : 0);
641 erase_block_no = simple_strtoul(w, &w, 0);
642 if (!zero_ok && !erase_block_no) {
643 NS_ERR("invalid badblocks.\n");
646 offset = erase_block_no * ns->geom.secsz;
647 if (mtd->block_markbad(mtd, offset)) {
648 NS_ERR("invalid badblocks.\n");
657 static int parse_weakblocks(void)
661 unsigned int erase_block_no;
662 unsigned int max_erases;
663 struct weak_block *wb;
669 zero_ok = (*w == '0' ? 1 : 0);
670 erase_block_no = simple_strtoul(w, &w, 0);
671 if (!zero_ok && !erase_block_no) {
672 NS_ERR("invalid weakblocks.\n");
678 max_erases = simple_strtoul(w, &w, 0);
682 wb = kzalloc(sizeof(*wb), GFP_KERNEL);
684 NS_ERR("unable to allocate memory.\n");
687 wb->erase_block_no = erase_block_no;
688 wb->max_erases = max_erases;
689 list_add(&wb->list, &weak_blocks);
694 static int erase_error(unsigned int erase_block_no)
696 struct weak_block *wb;
698 list_for_each_entry(wb, &weak_blocks, list)
699 if (wb->erase_block_no == erase_block_no) {
700 if (wb->erases_done >= wb->max_erases)
702 wb->erases_done += 1;
708 static int parse_weakpages(void)
712 unsigned int page_no;
713 unsigned int max_writes;
714 struct weak_page *wp;
720 zero_ok = (*w == '0' ? 1 : 0);
721 page_no = simple_strtoul(w, &w, 0);
722 if (!zero_ok && !page_no) {
723 NS_ERR("invalid weakpagess.\n");
729 max_writes = simple_strtoul(w, &w, 0);
733 wp = kzalloc(sizeof(*wp), GFP_KERNEL);
735 NS_ERR("unable to allocate memory.\n");
738 wp->page_no = page_no;
739 wp->max_writes = max_writes;
740 list_add(&wp->list, &weak_pages);
745 static int write_error(unsigned int page_no)
747 struct weak_page *wp;
749 list_for_each_entry(wp, &weak_pages, list)
750 if (wp->page_no == page_no) {
751 if (wp->writes_done >= wp->max_writes)
753 wp->writes_done += 1;
759 static int parse_gravepages(void)
763 unsigned int page_no;
764 unsigned int max_reads;
765 struct grave_page *gp;
771 zero_ok = (*g == '0' ? 1 : 0);
772 page_no = simple_strtoul(g, &g, 0);
773 if (!zero_ok && !page_no) {
774 NS_ERR("invalid gravepagess.\n");
780 max_reads = simple_strtoul(g, &g, 0);
784 gp = kzalloc(sizeof(*gp), GFP_KERNEL);
786 NS_ERR("unable to allocate memory.\n");
789 gp->page_no = page_no;
790 gp->max_reads = max_reads;
791 list_add(&gp->list, &grave_pages);
796 static int read_error(unsigned int page_no)
798 struct grave_page *gp;
800 list_for_each_entry(gp, &grave_pages, list)
801 if (gp->page_no == page_no) {
802 if (gp->reads_done >= gp->max_reads)
810 static void free_lists(void)
812 struct list_head *pos, *n;
813 list_for_each_safe(pos, n, &weak_blocks) {
815 kfree(list_entry(pos, struct weak_block, list));
817 list_for_each_safe(pos, n, &weak_pages) {
819 kfree(list_entry(pos, struct weak_page, list));
821 list_for_each_safe(pos, n, &grave_pages) {
823 kfree(list_entry(pos, struct grave_page, list));
825 kfree(erase_block_wear);
828 static int setup_wear_reporting(struct mtd_info *mtd)
834 wear_eb_count = divide(mtd->size, mtd->erasesize);
835 mem = wear_eb_count * sizeof(unsigned long);
836 if (mem / sizeof(unsigned long) != wear_eb_count) {
837 NS_ERR("Too many erase blocks for wear reporting\n");
840 erase_block_wear = kzalloc(mem, GFP_KERNEL);
841 if (!erase_block_wear) {
842 NS_ERR("Too many erase blocks for wear reporting\n");
848 static void update_wear(unsigned int erase_block_no)
850 unsigned long wmin = -1, wmax = 0, avg;
851 unsigned long deciles[10], decile_max[10], tot = 0;
854 if (!erase_block_wear)
858 NS_ERR("Erase counter total overflow\n");
859 erase_block_wear[erase_block_no] += 1;
860 if (erase_block_wear[erase_block_no] == 0)
861 NS_ERR("Erase counter overflow for erase block %u\n", erase_block_no);
863 if (rptwear_cnt < rptwear)
866 /* Calc wear stats */
867 for (i = 0; i < wear_eb_count; ++i) {
868 unsigned long wear = erase_block_wear[i];
875 for (i = 0; i < 9; ++i) {
877 decile_max[i] = (wmax * (i + 1) + 5) / 10;
880 decile_max[9] = wmax;
881 for (i = 0; i < wear_eb_count; ++i) {
883 unsigned long wear = erase_block_wear[i];
884 for (d = 0; d < 10; ++d)
885 if (wear <= decile_max[d]) {
890 avg = tot / wear_eb_count;
891 /* Output wear report */
892 NS_INFO("*** Wear Report ***\n");
893 NS_INFO("Total numbers of erases: %lu\n", tot);
894 NS_INFO("Number of erase blocks: %u\n", wear_eb_count);
895 NS_INFO("Average number of erases: %lu\n", avg);
896 NS_INFO("Maximum number of erases: %lu\n", wmax);
897 NS_INFO("Minimum number of erases: %lu\n", wmin);
898 for (i = 0; i < 10; ++i) {
899 unsigned long from = (i ? decile_max[i - 1] + 1 : 0);
900 if (from > decile_max[i])
902 NS_INFO("Number of ebs with erase counts from %lu to %lu : %lu\n",
907 NS_INFO("*** End of Wear Report ***\n");
911 * Returns the string representation of 'state' state.
913 static char *get_state_name(uint32_t state)
915 switch (NS_STATE(state)) {
916 case STATE_CMD_READ0:
917 return "STATE_CMD_READ0";
918 case STATE_CMD_READ1:
919 return "STATE_CMD_READ1";
920 case STATE_CMD_PAGEPROG:
921 return "STATE_CMD_PAGEPROG";
922 case STATE_CMD_READOOB:
923 return "STATE_CMD_READOOB";
924 case STATE_CMD_READSTART:
925 return "STATE_CMD_READSTART";
926 case STATE_CMD_ERASE1:
927 return "STATE_CMD_ERASE1";
928 case STATE_CMD_STATUS:
929 return "STATE_CMD_STATUS";
930 case STATE_CMD_STATUS_M:
931 return "STATE_CMD_STATUS_M";
932 case STATE_CMD_SEQIN:
933 return "STATE_CMD_SEQIN";
934 case STATE_CMD_READID:
935 return "STATE_CMD_READID";
936 case STATE_CMD_ERASE2:
937 return "STATE_CMD_ERASE2";
938 case STATE_CMD_RESET:
939 return "STATE_CMD_RESET";
940 case STATE_ADDR_PAGE:
941 return "STATE_ADDR_PAGE";
943 return "STATE_ADDR_SEC";
944 case STATE_ADDR_ZERO:
945 return "STATE_ADDR_ZERO";
947 return "STATE_DATAIN";
949 return "STATE_DATAOUT";
950 case STATE_DATAOUT_ID:
951 return "STATE_DATAOUT_ID";
952 case STATE_DATAOUT_STATUS:
953 return "STATE_DATAOUT_STATUS";
954 case STATE_DATAOUT_STATUS_M:
955 return "STATE_DATAOUT_STATUS_M";
957 return "STATE_READY";
959 return "STATE_UNKNOWN";
962 NS_ERR("get_state_name: unknown state, BUG\n");
967 * Check if command is valid.
969 * RETURNS: 1 if wrong command, 0 if right.
971 static int check_command(int cmd)
976 case NAND_CMD_READSTART:
977 case NAND_CMD_PAGEPROG:
978 case NAND_CMD_READOOB:
979 case NAND_CMD_ERASE1:
980 case NAND_CMD_STATUS:
982 case NAND_CMD_READID:
983 case NAND_CMD_ERASE2:
988 case NAND_CMD_STATUS_MULTI:
995 * Returns state after command is accepted by command number.
997 static uint32_t get_state_by_command(unsigned command)
1000 case NAND_CMD_READ0:
1001 return STATE_CMD_READ0;
1002 case NAND_CMD_READ1:
1003 return STATE_CMD_READ1;
1004 case NAND_CMD_PAGEPROG:
1005 return STATE_CMD_PAGEPROG;
1006 case NAND_CMD_READSTART:
1007 return STATE_CMD_READSTART;
1008 case NAND_CMD_READOOB:
1009 return STATE_CMD_READOOB;
1010 case NAND_CMD_ERASE1:
1011 return STATE_CMD_ERASE1;
1012 case NAND_CMD_STATUS:
1013 return STATE_CMD_STATUS;
1014 case NAND_CMD_STATUS_MULTI:
1015 return STATE_CMD_STATUS_M;
1016 case NAND_CMD_SEQIN:
1017 return STATE_CMD_SEQIN;
1018 case NAND_CMD_READID:
1019 return STATE_CMD_READID;
1020 case NAND_CMD_ERASE2:
1021 return STATE_CMD_ERASE2;
1022 case NAND_CMD_RESET:
1023 return STATE_CMD_RESET;
1026 NS_ERR("get_state_by_command: unknown command, BUG\n");
1031 * Move an address byte to the correspondent internal register.
1033 static inline void accept_addr_byte(struct nandsim *ns, u_char bt)
1035 uint byte = (uint)bt;
1037 if (ns->regs.count < (ns->geom.pgaddrbytes - ns->geom.secaddrbytes))
1038 ns->regs.column |= (byte << 8 * ns->regs.count);
1040 ns->regs.row |= (byte << 8 * (ns->regs.count -
1041 ns->geom.pgaddrbytes +
1042 ns->geom.secaddrbytes));
1049 * Switch to STATE_READY state.
1051 static inline void switch_to_ready_state(struct nandsim *ns, u_char status)
1053 NS_DBG("switch_to_ready_state: switch to %s state\n", get_state_name(STATE_READY));
1055 ns->state = STATE_READY;
1056 ns->nxstate = STATE_UNKNOWN;
1064 ns->regs.column = 0;
1065 ns->regs.status = status;
1069 * If the operation isn't known yet, try to find it in the global array
1070 * of supported operations.
1072 * Operation can be unknown because of the following.
1073 * 1. New command was accepted and this is the firs call to find the
1074 * correspondent states chain. In this case ns->npstates = 0;
1075 * 2. There is several operations which begin with the same command(s)
1076 * (for example program from the second half and read from the
1077 * second half operations both begin with the READ1 command). In this
1078 * case the ns->pstates[] array contains previous states.
1080 * Thus, the function tries to find operation containing the following
1081 * states (if the 'flag' parameter is 0):
1082 * ns->pstates[0], ... ns->pstates[ns->npstates], ns->state
1084 * If (one and only one) matching operation is found, it is accepted (
1085 * ns->ops, ns->state, ns->nxstate are initialized, ns->npstate is
1088 * If there are several maches, the current state is pushed to the
1091 * The operation can be unknown only while commands are input to the chip.
1092 * As soon as address command is accepted, the operation must be known.
1093 * In such situation the function is called with 'flag' != 0, and the
1094 * operation is searched using the following pattern:
1095 * ns->pstates[0], ... ns->pstates[ns->npstates], <address input>
1097 * It is supposed that this pattern must either match one operation on
1098 * none. There can't be ambiguity in that case.
1100 * If no matches found, the functions does the following:
1101 * 1. if there are saved states present, try to ignore them and search
1102 * again only using the last command. If nothing was found, switch
1103 * to the STATE_READY state.
1104 * 2. if there are no saved states, switch to the STATE_READY state.
1106 * RETURNS: -2 - no matched operations found.
1107 * -1 - several matches.
1108 * 0 - operation is found.
1110 static int find_operation(struct nandsim *ns, uint32_t flag)
1115 for (i = 0; i < NS_OPER_NUM; i++) {
1119 if (!(ns->options & ops[i].reqopts))
1120 /* Ignore operations we can't perform */
1124 if (!(ops[i].states[ns->npstates] & STATE_ADDR_MASK))
1127 if (NS_STATE(ns->state) != NS_STATE(ops[i].states[ns->npstates]))
1131 for (j = 0; j < ns->npstates; j++)
1132 if (NS_STATE(ops[i].states[j]) != NS_STATE(ns->pstates[j])
1133 && (ns->options & ops[idx].reqopts)) {
1144 if (opsfound == 1) {
1146 ns->op = &ops[idx].states[0];
1149 * In this case the find_operation function was
1150 * called when address has just began input. But it isn't
1151 * yet fully input and the current state must
1152 * not be one of STATE_ADDR_*, but the STATE_ADDR_*
1153 * state must be the next state (ns->nxstate).
1155 ns->stateidx = ns->npstates - 1;
1157 ns->stateidx = ns->npstates;
1160 ns->state = ns->op[ns->stateidx];
1161 ns->nxstate = ns->op[ns->stateidx + 1];
1162 NS_DBG("find_operation: operation found, index: %d, state: %s, nxstate %s\n",
1163 idx, get_state_name(ns->state), get_state_name(ns->nxstate));
1167 if (opsfound == 0) {
1168 /* Nothing was found. Try to ignore previous commands (if any) and search again */
1169 if (ns->npstates != 0) {
1170 NS_DBG("find_operation: no operation found, try again with state %s\n",
1171 get_state_name(ns->state));
1173 return find_operation(ns, 0);
1176 NS_DBG("find_operation: no operations found\n");
1177 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1182 /* This shouldn't happen */
1183 NS_DBG("find_operation: BUG, operation must be known if address is input\n");
1187 NS_DBG("find_operation: there is still ambiguity\n");
1189 ns->pstates[ns->npstates++] = ns->state;
1195 * Returns a pointer to the current page.
1197 static inline union ns_mem *NS_GET_PAGE(struct nandsim *ns)
1199 return &(ns->pages[ns->regs.row]);
1203 * Retuns a pointer to the current byte, within the current page.
1205 static inline u_char *NS_PAGE_BYTE_OFF(struct nandsim *ns)
1207 return NS_GET_PAGE(ns)->byte + ns->regs.column + ns->regs.off;
1211 * Fill the NAND buffer with data read from the specified page.
1213 static void read_page(struct nandsim *ns, int num)
1215 union ns_mem *mypage;
1217 mypage = NS_GET_PAGE(ns);
1218 if (mypage->byte == NULL) {
1219 NS_DBG("read_page: page %d not allocated\n", ns->regs.row);
1220 memset(ns->buf.byte, 0xFF, num);
1222 unsigned int page_no = ns->regs.row;
1223 NS_DBG("read_page: page %d allocated, reading from %d\n",
1224 ns->regs.row, ns->regs.column + ns->regs.off);
1225 if (read_error(page_no)) {
1227 memset(ns->buf.byte, 0xFF, num);
1228 for (i = 0; i < num; ++i)
1229 ns->buf.byte[i] = random32();
1230 NS_WARN("simulating read error in page %u\n", page_no);
1233 memcpy(ns->buf.byte, NS_PAGE_BYTE_OFF(ns), num);
1234 if (bitflips && random32() < (1 << 22)) {
1237 flips = (random32() % (int) bitflips) + 1;
1239 int pos = random32() % (num * 8);
1240 ns->buf.byte[pos / 8] ^= (1 << (pos % 8));
1241 NS_WARN("read_page: flipping bit %d in page %d "
1242 "reading from %d ecc: corrected=%u failed=%u\n",
1243 pos, ns->regs.row, ns->regs.column + ns->regs.off,
1244 nsmtd->ecc_stats.corrected, nsmtd->ecc_stats.failed);
1251 * Erase all pages in the specified sector.
1253 static void erase_sector(struct nandsim *ns)
1255 union ns_mem *mypage;
1258 mypage = NS_GET_PAGE(ns);
1259 for (i = 0; i < ns->geom.pgsec; i++) {
1260 if (mypage->byte != NULL) {
1261 NS_DBG("erase_sector: freeing page %d\n", ns->regs.row+i);
1262 kfree(mypage->byte);
1263 mypage->byte = NULL;
1270 * Program the specified page with the contents from the NAND buffer.
1272 static int prog_page(struct nandsim *ns, int num)
1275 union ns_mem *mypage;
1278 mypage = NS_GET_PAGE(ns);
1279 if (mypage->byte == NULL) {
1280 NS_DBG("prog_page: allocating page %d\n", ns->regs.row);
1282 * We allocate memory with GFP_NOFS because a flash FS may
1283 * utilize this. If it is holding an FS lock, then gets here,
1284 * then kmalloc runs writeback which goes to the FS again
1285 * and deadlocks. This was seen in practice.
1287 mypage->byte = kmalloc(ns->geom.pgszoob, GFP_NOFS);
1288 if (mypage->byte == NULL) {
1289 NS_ERR("prog_page: error allocating memory for page %d\n", ns->regs.row);
1292 memset(mypage->byte, 0xFF, ns->geom.pgszoob);
1295 pg_off = NS_PAGE_BYTE_OFF(ns);
1296 for (i = 0; i < num; i++)
1297 pg_off[i] &= ns->buf.byte[i];
1303 * If state has any action bit, perform this action.
1305 * RETURNS: 0 if success, -1 if error.
1307 static int do_state_action(struct nandsim *ns, uint32_t action)
1310 int busdiv = ns->busw == 8 ? 1 : 2;
1311 unsigned int erase_block_no, page_no;
1313 action &= ACTION_MASK;
1315 /* Check that page address input is correct */
1316 if (action != ACTION_SECERASE && ns->regs.row >= ns->geom.pgnum) {
1317 NS_WARN("do_state_action: wrong page number (%#x)\n", ns->regs.row);
1325 * Copy page data to the internal buffer.
1328 /* Column shouldn't be very large */
1329 if (ns->regs.column >= (ns->geom.pgszoob - ns->regs.off)) {
1330 NS_ERR("do_state_action: column number is too large\n");
1333 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1336 NS_DBG("do_state_action: (ACTION_CPY:) copy %d bytes to int buf, raw offset %d\n",
1337 num, NS_RAW_OFFSET(ns) + ns->regs.off);
1339 if (ns->regs.off == 0)
1340 NS_LOG("read page %d\n", ns->regs.row);
1341 else if (ns->regs.off < ns->geom.pgsz)
1342 NS_LOG("read page %d (second half)\n", ns->regs.row);
1344 NS_LOG("read OOB of page %d\n", ns->regs.row);
1346 NS_UDELAY(access_delay);
1347 NS_UDELAY(input_cycle * ns->geom.pgsz / 1000 / busdiv);
1351 case ACTION_SECERASE:
1357 NS_ERR("do_state_action: device is write-protected, ignore sector erase\n");
1361 if (ns->regs.row >= ns->geom.pgnum - ns->geom.pgsec
1362 || (ns->regs.row & ~(ns->geom.secsz - 1))) {
1363 NS_ERR("do_state_action: wrong sector address (%#x)\n", ns->regs.row);
1367 ns->regs.row = (ns->regs.row <<
1368 8 * (ns->geom.pgaddrbytes - ns->geom.secaddrbytes)) | ns->regs.column;
1369 ns->regs.column = 0;
1371 erase_block_no = ns->regs.row >> (ns->geom.secshift - ns->geom.pgshift);
1373 NS_DBG("do_state_action: erase sector at address %#x, off = %d\n",
1374 ns->regs.row, NS_RAW_OFFSET(ns));
1375 NS_LOG("erase sector %u\n", erase_block_no);
1379 NS_MDELAY(erase_delay);
1381 if (erase_block_wear)
1382 update_wear(erase_block_no);
1384 if (erase_error(erase_block_no)) {
1385 NS_WARN("simulating erase failure in erase block %u\n", erase_block_no);
1391 case ACTION_PRGPAGE:
1393 * Programm page - move internal buffer data to the page.
1397 NS_WARN("do_state_action: device is write-protected, programm\n");
1401 num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1402 if (num != ns->regs.count) {
1403 NS_ERR("do_state_action: too few bytes were input (%d instead of %d)\n",
1404 ns->regs.count, num);
1408 if (prog_page(ns, num) == -1)
1411 page_no = ns->regs.row;
1413 NS_DBG("do_state_action: copy %d bytes from int buf to (%#x, %#x), raw off = %d\n",
1414 num, ns->regs.row, ns->regs.column, NS_RAW_OFFSET(ns) + ns->regs.off);
1415 NS_LOG("programm page %d\n", ns->regs.row);
1417 NS_UDELAY(programm_delay);
1418 NS_UDELAY(output_cycle * ns->geom.pgsz / 1000 / busdiv);
1420 if (write_error(page_no)) {
1421 NS_WARN("simulating write failure in page %u\n", page_no);
1427 case ACTION_ZEROOFF:
1428 NS_DBG("do_state_action: set internal offset to 0\n");
1432 case ACTION_HALFOFF:
1433 if (!(ns->options & OPT_PAGE512_8BIT)) {
1434 NS_ERR("do_state_action: BUG! can't skip half of page for non-512"
1435 "byte page size 8x chips\n");
1438 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz/2);
1439 ns->regs.off = ns->geom.pgsz/2;
1443 NS_DBG("do_state_action: set internal offset to %d\n", ns->geom.pgsz);
1444 ns->regs.off = ns->geom.pgsz;
1448 NS_DBG("do_state_action: BUG! unknown action\n");
1455 * Switch simulator's state.
1457 static void switch_state(struct nandsim *ns)
1461 * The current operation have already been identified.
1462 * Just follow the states chain.
1466 ns->state = ns->nxstate;
1467 ns->nxstate = ns->op[ns->stateidx + 1];
1469 NS_DBG("switch_state: operation is known, switch to the next state, "
1470 "state: %s, nxstate: %s\n",
1471 get_state_name(ns->state), get_state_name(ns->nxstate));
1473 /* See, whether we need to do some action */
1474 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1475 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1481 * We don't yet know which operation we perform.
1482 * Try to identify it.
1486 * The only event causing the switch_state function to
1487 * be called with yet unknown operation is new command.
1489 ns->state = get_state_by_command(ns->regs.command);
1491 NS_DBG("switch_state: operation is unknown, try to find it\n");
1493 if (find_operation(ns, 0) != 0)
1496 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1497 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1502 /* For 16x devices column means the page offset in words */
1503 if ((ns->nxstate & STATE_ADDR_MASK) && ns->busw == 16) {
1504 NS_DBG("switch_state: double the column number for 16x device\n");
1505 ns->regs.column <<= 1;
1508 if (NS_STATE(ns->nxstate) == STATE_READY) {
1510 * The current state is the last. Return to STATE_READY
1513 u_char status = NS_STATUS_OK(ns);
1515 /* In case of data states, see if all bytes were input/output */
1516 if ((ns->state & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK))
1517 && ns->regs.count != ns->regs.num) {
1518 NS_WARN("switch_state: not all bytes were processed, %d left\n",
1519 ns->regs.num - ns->regs.count);
1520 status = NS_STATUS_FAILED(ns);
1523 NS_DBG("switch_state: operation complete, switch to STATE_READY state\n");
1525 switch_to_ready_state(ns, status);
1528 } else if (ns->nxstate & (STATE_DATAIN_MASK | STATE_DATAOUT_MASK)) {
1530 * If the next state is data input/output, switch to it now
1533 ns->state = ns->nxstate;
1534 ns->nxstate = ns->op[++ns->stateidx + 1];
1535 ns->regs.num = ns->regs.count = 0;
1537 NS_DBG("switch_state: the next state is data I/O, switch, "
1538 "state: %s, nxstate: %s\n",
1539 get_state_name(ns->state), get_state_name(ns->nxstate));
1542 * Set the internal register to the count of bytes which
1543 * are expected to be input or output
1545 switch (NS_STATE(ns->state)) {
1548 ns->regs.num = ns->geom.pgszoob - ns->regs.off - ns->regs.column;
1551 case STATE_DATAOUT_ID:
1552 ns->regs.num = ns->geom.idbytes;
1555 case STATE_DATAOUT_STATUS:
1556 case STATE_DATAOUT_STATUS_M:
1557 ns->regs.count = ns->regs.num = 0;
1561 NS_ERR("switch_state: BUG! unknown data state\n");
1564 } else if (ns->nxstate & STATE_ADDR_MASK) {
1566 * If the next state is address input, set the internal
1567 * register to the number of expected address bytes
1572 switch (NS_STATE(ns->nxstate)) {
1573 case STATE_ADDR_PAGE:
1574 ns->regs.num = ns->geom.pgaddrbytes;
1577 case STATE_ADDR_SEC:
1578 ns->regs.num = ns->geom.secaddrbytes;
1581 case STATE_ADDR_ZERO:
1586 NS_ERR("switch_state: BUG! unknown address state\n");
1590 * Just reset internal counters.
1598 static u_char ns_nand_read_byte(struct mtd_info *mtd)
1600 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1603 /* Sanity and correctness checks */
1604 if (!ns->lines.ce) {
1605 NS_ERR("read_byte: chip is disabled, return %#x\n", (uint)outb);
1608 if (ns->lines.ale || ns->lines.cle) {
1609 NS_ERR("read_byte: ALE or CLE pin is high, return %#x\n", (uint)outb);
1612 if (!(ns->state & STATE_DATAOUT_MASK)) {
1613 NS_WARN("read_byte: unexpected data output cycle, state is %s "
1614 "return %#x\n", get_state_name(ns->state), (uint)outb);
1618 /* Status register may be read as many times as it is wanted */
1619 if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS) {
1620 NS_DBG("read_byte: return %#x status\n", ns->regs.status);
1621 return ns->regs.status;
1624 /* Check if there is any data in the internal buffer which may be read */
1625 if (ns->regs.count == ns->regs.num) {
1626 NS_WARN("read_byte: no more data to output, return %#x\n", (uint)outb);
1630 switch (NS_STATE(ns->state)) {
1632 if (ns->busw == 8) {
1633 outb = ns->buf.byte[ns->regs.count];
1634 ns->regs.count += 1;
1636 outb = (u_char)cpu_to_le16(ns->buf.word[ns->regs.count >> 1]);
1637 ns->regs.count += 2;
1640 case STATE_DATAOUT_ID:
1641 NS_DBG("read_byte: read ID byte %d, total = %d\n", ns->regs.count, ns->regs.num);
1642 outb = ns->ids[ns->regs.count];
1643 ns->regs.count += 1;
1649 if (ns->regs.count == ns->regs.num) {
1650 NS_DBG("read_byte: all bytes were read\n");
1653 * The OPT_AUTOINCR allows to read next conseqitive pages without
1654 * new read operation cycle.
1656 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
1658 if (ns->regs.row + 1 < ns->geom.pgnum)
1660 NS_DBG("read_byte: switch to the next page (%#x)\n", ns->regs.row);
1661 do_state_action(ns, ACTION_CPY);
1663 else if (NS_STATE(ns->nxstate) == STATE_READY)
1671 static void ns_nand_write_byte(struct mtd_info *mtd, u_char byte)
1673 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1675 /* Sanity and correctness checks */
1676 if (!ns->lines.ce) {
1677 NS_ERR("write_byte: chip is disabled, ignore write\n");
1680 if (ns->lines.ale && ns->lines.cle) {
1681 NS_ERR("write_byte: ALE and CLE pins are high simultaneously, ignore write\n");
1685 if (ns->lines.cle == 1) {
1687 * The byte written is a command.
1690 if (byte == NAND_CMD_RESET) {
1691 NS_LOG("reset chip\n");
1692 switch_to_ready_state(ns, NS_STATUS_OK(ns));
1697 * Chip might still be in STATE_DATAOUT
1698 * (if OPT_AUTOINCR feature is supported), STATE_DATAOUT_STATUS or
1699 * STATE_DATAOUT_STATUS_M state. If so, switch state.
1701 if (NS_STATE(ns->state) == STATE_DATAOUT_STATUS
1702 || NS_STATE(ns->state) == STATE_DATAOUT_STATUS_M
1703 || ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT))
1706 /* Check if chip is expecting command */
1707 if (NS_STATE(ns->nxstate) != STATE_UNKNOWN && !(ns->nxstate & STATE_CMD_MASK)) {
1709 * We are in situation when something else (not command)
1710 * was expected but command was input. In this case ignore
1711 * previous command(s)/state(s) and accept the last one.
1713 NS_WARN("write_byte: command (%#x) wasn't expected, expected state is %s, "
1714 "ignore previous states\n", (uint)byte, get_state_name(ns->nxstate));
1715 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1718 /* Check that the command byte is correct */
1719 if (check_command(byte)) {
1720 NS_ERR("write_byte: unknown command %#x\n", (uint)byte);
1724 NS_DBG("command byte corresponding to %s state accepted\n",
1725 get_state_name(get_state_by_command(byte)));
1726 ns->regs.command = byte;
1729 } else if (ns->lines.ale == 1) {
1731 * The byte written is an address.
1734 if (NS_STATE(ns->nxstate) == STATE_UNKNOWN) {
1736 NS_DBG("write_byte: operation isn't known yet, identify it\n");
1738 if (find_operation(ns, 1) < 0)
1741 if ((ns->state & ACTION_MASK) && do_state_action(ns, ns->state) < 0) {
1742 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1747 switch (NS_STATE(ns->nxstate)) {
1748 case STATE_ADDR_PAGE:
1749 ns->regs.num = ns->geom.pgaddrbytes;
1751 case STATE_ADDR_SEC:
1752 ns->regs.num = ns->geom.secaddrbytes;
1754 case STATE_ADDR_ZERO:
1762 /* Check that chip is expecting address */
1763 if (!(ns->nxstate & STATE_ADDR_MASK)) {
1764 NS_ERR("write_byte: address (%#x) isn't expected, expected state is %s, "
1765 "switch to STATE_READY\n", (uint)byte, get_state_name(ns->nxstate));
1766 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1770 /* Check if this is expected byte */
1771 if (ns->regs.count == ns->regs.num) {
1772 NS_ERR("write_byte: no more address bytes expected\n");
1773 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1777 accept_addr_byte(ns, byte);
1779 ns->regs.count += 1;
1781 NS_DBG("write_byte: address byte %#x was accepted (%d bytes input, %d expected)\n",
1782 (uint)byte, ns->regs.count, ns->regs.num);
1784 if (ns->regs.count == ns->regs.num) {
1785 NS_DBG("address (%#x, %#x) is accepted\n", ns->regs.row, ns->regs.column);
1791 * The byte written is an input data.
1794 /* Check that chip is expecting data input */
1795 if (!(ns->state & STATE_DATAIN_MASK)) {
1796 NS_ERR("write_byte: data input (%#x) isn't expected, state is %s, "
1797 "switch to %s\n", (uint)byte,
1798 get_state_name(ns->state), get_state_name(STATE_READY));
1799 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1803 /* Check if this is expected byte */
1804 if (ns->regs.count == ns->regs.num) {
1805 NS_WARN("write_byte: %u input bytes has already been accepted, ignore write\n",
1810 if (ns->busw == 8) {
1811 ns->buf.byte[ns->regs.count] = byte;
1812 ns->regs.count += 1;
1814 ns->buf.word[ns->regs.count >> 1] = cpu_to_le16((uint16_t)byte);
1815 ns->regs.count += 2;
1822 static void ns_hwcontrol(struct mtd_info *mtd, int cmd, unsigned int bitmask)
1824 struct nandsim *ns = ((struct nand_chip *)mtd->priv)->priv;
1826 ns->lines.cle = bitmask & NAND_CLE ? 1 : 0;
1827 ns->lines.ale = bitmask & NAND_ALE ? 1 : 0;
1828 ns->lines.ce = bitmask & NAND_NCE ? 1 : 0;
1830 if (cmd != NAND_CMD_NONE)
1831 ns_nand_write_byte(mtd, cmd);
1834 static int ns_device_ready(struct mtd_info *mtd)
1836 NS_DBG("device_ready\n");
1840 static uint16_t ns_nand_read_word(struct mtd_info *mtd)
1842 struct nand_chip *chip = (struct nand_chip *)mtd->priv;
1844 NS_DBG("read_word\n");
1846 return chip->read_byte(mtd) | (chip->read_byte(mtd) << 8);
1849 static void ns_nand_write_buf(struct mtd_info *mtd, const u_char *buf, int len)
1851 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1853 /* Check that chip is expecting data input */
1854 if (!(ns->state & STATE_DATAIN_MASK)) {
1855 NS_ERR("write_buf: data input isn't expected, state is %s, "
1856 "switch to STATE_READY\n", get_state_name(ns->state));
1857 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1861 /* Check if these are expected bytes */
1862 if (ns->regs.count + len > ns->regs.num) {
1863 NS_ERR("write_buf: too many input bytes\n");
1864 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1868 memcpy(ns->buf.byte + ns->regs.count, buf, len);
1869 ns->regs.count += len;
1871 if (ns->regs.count == ns->regs.num) {
1872 NS_DBG("write_buf: %d bytes were written\n", ns->regs.count);
1876 static void ns_nand_read_buf(struct mtd_info *mtd, u_char *buf, int len)
1878 struct nandsim *ns = (struct nandsim *)((struct nand_chip *)mtd->priv)->priv;
1880 /* Sanity and correctness checks */
1881 if (!ns->lines.ce) {
1882 NS_ERR("read_buf: chip is disabled\n");
1885 if (ns->lines.ale || ns->lines.cle) {
1886 NS_ERR("read_buf: ALE or CLE pin is high\n");
1889 if (!(ns->state & STATE_DATAOUT_MASK)) {
1890 NS_WARN("read_buf: unexpected data output cycle, current state is %s\n",
1891 get_state_name(ns->state));
1895 if (NS_STATE(ns->state) != STATE_DATAOUT) {
1898 for (i = 0; i < len; i++)
1899 buf[i] = ((struct nand_chip *)mtd->priv)->read_byte(mtd);
1904 /* Check if these are expected bytes */
1905 if (ns->regs.count + len > ns->regs.num) {
1906 NS_ERR("read_buf: too many bytes to read\n");
1907 switch_to_ready_state(ns, NS_STATUS_FAILED(ns));
1911 memcpy(buf, ns->buf.byte + ns->regs.count, len);
1912 ns->regs.count += len;
1914 if (ns->regs.count == ns->regs.num) {
1915 if ((ns->options & OPT_AUTOINCR) && NS_STATE(ns->state) == STATE_DATAOUT) {
1917 if (ns->regs.row + 1 < ns->geom.pgnum)
1919 NS_DBG("read_buf: switch to the next page (%#x)\n", ns->regs.row);
1920 do_state_action(ns, ACTION_CPY);
1922 else if (NS_STATE(ns->nxstate) == STATE_READY)
1929 static int ns_nand_verify_buf(struct mtd_info *mtd, const u_char *buf, int len)
1931 ns_nand_read_buf(mtd, (u_char *)&ns_verify_buf[0], len);
1933 if (!memcmp(buf, &ns_verify_buf[0], len)) {
1934 NS_DBG("verify_buf: the buffer is OK\n");
1937 NS_DBG("verify_buf: the buffer is wrong\n");
1943 * Module initialization function
1945 static int __init ns_init_module(void)
1947 struct nand_chip *chip;
1948 struct nandsim *nand;
1949 int retval = -ENOMEM, i;
1951 if (bus_width != 8 && bus_width != 16) {
1952 NS_ERR("wrong bus width (%d), use only 8 or 16\n", bus_width);
1956 /* Allocate and initialize mtd_info, nand_chip and nandsim structures */
1957 nsmtd = kzalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip)
1958 + sizeof(struct nandsim), GFP_KERNEL);
1960 NS_ERR("unable to allocate core structures.\n");
1963 chip = (struct nand_chip *)(nsmtd + 1);
1964 nsmtd->priv = (void *)chip;
1965 nand = (struct nandsim *)(chip + 1);
1966 chip->priv = (void *)nand;
1969 * Register simulator's callbacks.
1971 chip->cmd_ctrl = ns_hwcontrol;
1972 chip->read_byte = ns_nand_read_byte;
1973 chip->dev_ready = ns_device_ready;
1974 chip->write_buf = ns_nand_write_buf;
1975 chip->read_buf = ns_nand_read_buf;
1976 chip->verify_buf = ns_nand_verify_buf;
1977 chip->read_word = ns_nand_read_word;
1978 chip->ecc.mode = NAND_ECC_SOFT;
1979 /* The NAND_SKIP_BBTSCAN option is necessary for 'overridesize' */
1980 /* and 'badblocks' parameters to work */
1981 chip->options |= NAND_SKIP_BBTSCAN;
1984 * Perform minimum nandsim structure initialization to handle
1985 * the initial ID read command correctly
1987 if (third_id_byte != 0xFF || fourth_id_byte != 0xFF)
1988 nand->geom.idbytes = 4;
1990 nand->geom.idbytes = 2;
1991 nand->regs.status = NS_STATUS_OK(nand);
1992 nand->nxstate = STATE_UNKNOWN;
1993 nand->options |= OPT_PAGE256; /* temporary value */
1994 nand->ids[0] = first_id_byte;
1995 nand->ids[1] = second_id_byte;
1996 nand->ids[2] = third_id_byte;
1997 nand->ids[3] = fourth_id_byte;
1998 if (bus_width == 16) {
2000 chip->options |= NAND_BUSWIDTH_16;
2003 nsmtd->owner = THIS_MODULE;
2005 if ((retval = parse_weakblocks()) != 0)
2008 if ((retval = parse_weakpages()) != 0)
2011 if ((retval = parse_gravepages()) != 0)
2014 if ((retval = nand_scan(nsmtd, 1)) != 0) {
2015 NS_ERR("can't register NAND Simulator\n");
2022 u_int64_t new_size = (u_int64_t)nsmtd->erasesize << overridesize;
2023 if (new_size >> overridesize != nsmtd->erasesize) {
2024 NS_ERR("overridesize is too big\n");
2027 /* N.B. This relies on nand_scan not doing anything with the size before we change it */
2028 nsmtd->size = new_size;
2029 chip->chipsize = new_size;
2030 chip->chip_shift = ffs(nsmtd->erasesize) + overridesize - 1;
2031 chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
2034 if ((retval = setup_wear_reporting(nsmtd)) != 0)
2037 if ((retval = init_nandsim(nsmtd)) != 0)
2040 if ((retval = parse_badblocks(nand, nsmtd)) != 0)
2043 if ((retval = nand_default_bbt(nsmtd)) != 0)
2046 /* Register NAND partitions */
2047 if ((retval = add_mtd_partitions(nsmtd, &nand->partitions[0], nand->nbparts)) != 0)
2054 nand_release(nsmtd);
2055 for (i = 0;i < ARRAY_SIZE(nand->partitions); ++i)
2056 kfree(nand->partitions[i].name);
2064 module_init(ns_init_module);
2067 * Module clean-up function
2069 static void __exit ns_cleanup_module(void)
2071 struct nandsim *ns = (struct nandsim *)(((struct nand_chip *)nsmtd->priv)->priv);
2074 free_nandsim(ns); /* Free nandsim private resources */
2075 nand_release(nsmtd); /* Unregister driver */
2076 for (i = 0;i < ARRAY_SIZE(ns->partitions); ++i)
2077 kfree(ns->partitions[i].name);
2078 kfree(nsmtd); /* Free other structures */
2082 module_exit(ns_cleanup_module);
2084 MODULE_LICENSE ("GPL");
2085 MODULE_AUTHOR ("Artem B. Bityuckiy");
2086 MODULE_DESCRIPTION ("The NAND flash simulator");