1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2000 Silicon Integrated System Corporation
5  * Copyright (C) 2000 Ronald G. Minnich <rminnich@gmail.com>
6  * Copyright (C) 2005-2009 coresystems GmbH
7  * Copyright (C) 2006-2009 Carl-Daniel Hailfinger
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  */
19 
20 #ifndef __FLASH_H__
21 #define __FLASH_H__ 1
22 
23 #include "platform.h"
24 
25 #include <inttypes.h>
26 #include <stdio.h>
27 #include <stdint.h>
28 #include <stddef.h>
29 #include <stdarg.h>
30 #include <stdbool.h>
31 #if IS_WINDOWS
32 #include <windows.h>
33 #undef min
34 #undef max
35 #endif
36 
37 #include "libflashrom.h"
38 #include "layout.h"
39 
40 #define KiB (1024)
41 #define MiB (1024 * KiB)
42 
43 /* Assumes `n` and `a` are at most 64-bit wide (to avoid typeof() operator). */
44 #define ALIGN_DOWN(n, a) ((n) & ~((uint64_t)(a) - 1))
45 
46 #define ERROR_PTR ((void*)-1)
47 
48 /* Error codes */
49 #define ERROR_OOM	-100
50 #define TIMEOUT_ERROR	-101
51 
52 /* TODO: check using code for correct usage of types */
53 typedef uintptr_t chipaddr;
54 #define PRIxPTR_WIDTH ((int)(sizeof(uintptr_t)*2))
55 
56 int register_shutdown(int (*function) (void *data), void *data);
57 int shutdown_free(void *data);
58 void *programmer_map_flash_region(const char *descr, uintptr_t phys_addr, size_t len);
59 void programmer_unmap_flash_region(void *virt_addr, size_t len);
60 void programmer_delay(unsigned int usecs);
61 
62 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63 
64 enum chipbustype {
65 	BUS_NONE	= 0,
66 	BUS_PARALLEL	= 1 << 0,
67 	BUS_LPC		= 1 << 1,
68 	BUS_FWH		= 1 << 2,
69 	BUS_SPI		= 1 << 3,
70 	BUS_PROG	= 1 << 4,
71 	BUS_NONSPI	= BUS_PARALLEL | BUS_LPC | BUS_FWH,
72 };
73 
74 /*
75  * The following enum defines possible write granularities of flash chips. These tend to reflect the properties
76  * of the actual hardware not necesserily the write function(s) defined by the respective struct flashchip.
77  * The latter might (and should) be more precisely specified, e.g. they might bail out early if their execution
78  * would result in undefined chip contents.
79  */
80 enum write_granularity {
81 	/* We assume 256 byte granularity by default. */
82 	write_gran_256bytes = 0,/* If less than 256 bytes are written, the unwritten bytes are undefined. */
83 	write_gran_1bit,	/* Each bit can be cleared individually. */
84 	write_gran_1byte,	/* A byte can be written once. Further writes to an already written byte cause
85 				 * its contents to be either undefined or to stay unchanged. */
86 	write_gran_128bytes,	/* If less than 128 bytes are written, the unwritten bytes are undefined. */
87 	write_gran_264bytes,	/* If less than 264 bytes are written, the unwritten bytes are undefined. */
88 	write_gran_512bytes,	/* If less than 512 bytes are written, the unwritten bytes are undefined. */
89 	write_gran_528bytes,	/* If less than 528 bytes are written, the unwritten bytes are undefined. */
90 	write_gran_1024bytes,	/* If less than 1024 bytes are written, the unwritten bytes are undefined. */
91 	write_gran_1056bytes,	/* If less than 1056 bytes are written, the unwritten bytes are undefined. */
92 	write_gran_1byte_implicit_erase, /* EEPROMs and other chips with implicit erase and 1-byte writes. */
93 };
94 
95 /*
96  * How many different contiguous runs of erase blocks with one size each do
97  * we have for a given erase function?
98  */
99 #define NUM_ERASEREGIONS 5
100 
101 /*
102  * How many different erase functions do we have per chip?
103  * Macronix MX25L25635F has 8 different functions.
104  */
105 #define NUM_ERASEFUNCTIONS 8
106 
107 /* Feature bits used for non-SPI only */
108 #define FEATURE_REGISTERMAP	(1 << 0)
109 #define FEATURE_LONG_RESET	(0 << 4)
110 #define FEATURE_SHORT_RESET	(1 << 4)
111 #define FEATURE_EITHER_RESET	FEATURE_LONG_RESET
112 #define FEATURE_RESET_MASK	(FEATURE_LONG_RESET | FEATURE_SHORT_RESET)
113 #define FEATURE_ADDR_FULL	(0 << 2)
114 #define FEATURE_ADDR_MASK	(3 << 2)
115 #define FEATURE_ADDR_2AA	(1 << 2)
116 #define FEATURE_ADDR_AAA	(2 << 2)
117 #define FEATURE_ADDR_SHIFTED	(1 << 5)
118 /* Feature bits used for SPI only */
119 #define FEATURE_WRSR_EWSR	(1 << 6)
120 #define FEATURE_WRSR_WREN	(1 << 7)
121 #define FEATURE_WRSR_EITHER	(FEATURE_WRSR_EWSR | FEATURE_WRSR_WREN)
122 #define FEATURE_OTP		(1 << 8)
123 #define FEATURE_QPI		(1 << 9)
124 #define FEATURE_4BA_ENTER	(1 << 10) /**< Can enter/exit 4BA mode with instructions 0xb7/0xe9 w/o WREN */
125 #define FEATURE_4BA_ENTER_WREN	(1 << 11) /**< Can enter/exit 4BA mode with instructions 0xb7/0xe9 after WREN */
126 #define FEATURE_4BA_ENTER_EAR7	(1 << 12) /**< Can enter/exit 4BA mode by setting bit7 of the ext addr reg */
127 #define FEATURE_4BA_EXT_ADDR	(1 << 13) /**< Regular 3-byte operations can be used by writing the most
128 					       significant address byte into an extended address register. */
129 #define FEATURE_4BA_READ	(1 << 14) /**< Native 4BA read instruction (0x13) is supported. */
130 #define FEATURE_4BA_FAST_READ	(1 << 15) /**< Native 4BA fast read instruction (0x0c) is supported. */
131 #define FEATURE_4BA_WRITE	(1 << 16) /**< Native 4BA byte program (0x12) is supported. */
132 /* 4BA Shorthands */
133 #define FEATURE_4BA_NATIVE	(FEATURE_4BA_READ | FEATURE_4BA_FAST_READ | FEATURE_4BA_WRITE)
134 #define FEATURE_4BA		(FEATURE_4BA_ENTER | FEATURE_4BA_EXT_ADDR | FEATURE_4BA_NATIVE)
135 #define FEATURE_4BA_WREN	(FEATURE_4BA_ENTER_WREN | FEATURE_4BA_EXT_ADDR | FEATURE_4BA_NATIVE)
136 #define FEATURE_4BA_EAR7	(FEATURE_4BA_ENTER_EAR7 | FEATURE_4BA_EXT_ADDR | FEATURE_4BA_NATIVE)
137 /*
138  * Most flash chips are erased to ones and programmed to zeros. However, some
139  * other flash chips, such as the ENE KB9012 internal flash, work the opposite way.
140  */
141 #define FEATURE_ERASED_ZERO	(1 << 17)
142 #define FEATURE_NO_ERASE	(1 << 18)
143 
144 #define ERASED_VALUE(flash)	(((flash)->chip->feature_bits & FEATURE_ERASED_ZERO) ? 0x00 : 0xff)
145 
146 enum test_state {
147 	OK = 0,
148 	NT = 1,	/* Not tested */
149 	BAD,	/* Known to not work */
150 	DEP,	/* Support depends on configuration (e.g. Intel flash descriptor) */
151 	NA,	/* Not applicable (e.g. write support on ROM chips) */
152 };
153 
154 #define TEST_UNTESTED	(struct tested){ .probe = NT, .read = NT, .erase = NT, .write = NT }
155 
156 #define TEST_OK_PROBE	(struct tested){ .probe = OK, .read = NT, .erase = NT, .write = NT }
157 #define TEST_OK_PR	(struct tested){ .probe = OK, .read = OK, .erase = NT, .write = NT }
158 #define TEST_OK_PRE	(struct tested){ .probe = OK, .read = OK, .erase = OK, .write = NT }
159 #define TEST_OK_PREW	(struct tested){ .probe = OK, .read = OK, .erase = OK, .write = OK }
160 
161 #define TEST_BAD_PROBE	(struct tested){ .probe = BAD, .read = NT, .erase = NT, .write = NT }
162 #define TEST_BAD_PR	(struct tested){ .probe = BAD, .read = BAD, .erase = NT, .write = NT }
163 #define TEST_BAD_PRE	(struct tested){ .probe = BAD, .read = BAD, .erase = BAD, .write = NT }
164 #define TEST_BAD_PREW	(struct tested){ .probe = BAD, .read = BAD, .erase = BAD, .write = BAD }
165 
166 struct flashrom_flashctx;
167 #define flashctx flashrom_flashctx /* TODO: Agree on a name and convert all occurences. */
168 typedef int (erasefunc_t)(struct flashctx *flash, unsigned int addr, unsigned int blocklen);
169 
170 struct flashchip {
171 	const char *vendor;
172 	const char *name;
173 
174 	enum chipbustype bustype;
175 
176 	/*
177 	 * With 32bit manufacture_id and model_id we can cover IDs up to
178 	 * (including) the 4th bank of JEDEC JEP106W Standard Manufacturer's
179 	 * Identification code.
180 	 */
181 	uint32_t manufacture_id;
182 	uint32_t model_id;
183 
184 	/* Total chip size in kilobytes */
185 	unsigned int total_size;
186 	/* Chip page size in bytes */
187 	unsigned int page_size;
188 	int feature_bits;
189 
190 	/* Indicate how well flashrom supports different operations of this flash chip. */
191 	struct tested {
192 		enum test_state probe;
193 		enum test_state read;
194 		enum test_state erase;
195 		enum test_state write;
196 	} tested;
197 
198 	/*
199 	 * Group chips that have common command sets. This should ensure that
200 	 * no chip gets confused by a probing command for a very different class
201 	 * of chips.
202 	 */
203 	enum {
204 		/* SPI25 is very common. Keep it at zero so we don't have
205 		   to specify it for each and every chip in the database.*/
206 		SPI25 = 0,
207 		SPI_EDI = 1,
208 	} spi_cmd_set;
209 
210 	int (*probe) (struct flashctx *flash);
211 
212 	/* Delay after "enter/exit ID mode" commands in microseconds.
213 	 * NB: negative values have special meanings, see TIMING_* below.
214 	 */
215 	signed int probe_timing;
216 
217 	/*
218 	 * Erase blocks and associated erase function. Any chip erase function
219 	 * is stored as chip-sized virtual block together with said function.
220 	 * The first one that fits will be chosen. There is currently no way to
221 	 * influence that behaviour. For testing just comment out the other
222 	 * elements or set the function pointer to NULL.
223 	 */
224 	struct block_eraser {
225 		struct eraseblock {
226 			unsigned int size; /* Eraseblock size in bytes */
227 			unsigned int count; /* Number of contiguous blocks with that size */
228 		} eraseblocks[NUM_ERASEREGIONS];
229 		/* a block_erase function should try to erase one block of size
230 		 * 'blocklen' at address 'blockaddr' and return 0 on success. */
231 		int (*block_erase) (struct flashctx *flash, unsigned int blockaddr, unsigned int blocklen);
232 	} block_erasers[NUM_ERASEFUNCTIONS];
233 
234 	int (*printlock) (struct flashctx *flash);
235 	int (*unlock) (struct flashctx *flash);
236 	int (*write) (struct flashctx *flash, const uint8_t *buf, unsigned int start, unsigned int len);
237 	int (*read) (struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len);
238 	struct voltage {
239 		uint16_t min;
240 		uint16_t max;
241 	} voltage;
242 	enum write_granularity gran;
243 
244 	/* SPI specific options (TODO: Make it a union in case other bustypes get specific options.) */
245 	uint8_t wrea_override; /**< override opcode for write extended address register */
246 };
247 
248 struct flashrom_flashctx {
249 	struct flashchip *chip;
250 	/* FIXME: The memory mappings should be saved in a more structured way. */
251 	/* The physical_* fields store the respective addresses in the physical address space of the CPU. */
252 	uintptr_t physical_memory;
253 	/* The virtual_* fields store where the respective physical address is mapped into flashrom's address
254 	 * space. A value equivalent to (chipaddr)ERROR_PTR indicates an invalid mapping (or none at all). */
255 	chipaddr virtual_memory;
256 	/* Some flash devices have an additional register space; semantics are like above. */
257 	uintptr_t physical_registers;
258 	chipaddr virtual_registers;
259 	struct registered_master *mst;
260 	const struct flashrom_layout *layout;
261 	struct single_layout fallback_layout;
262 	struct {
263 		bool force;
264 		bool force_boardmismatch;
265 		bool verify_after_write;
266 		bool verify_whole_chip;
267 	} flags;
268 	/* We cache the state of the extended address register (highest byte
269            of a 4BA for 3BA instructions) and the state of the 4BA mode here.
270            If possible, we enter 4BA mode early. If that fails, we make use
271            of the extended address register. */
272 	int address_high_byte;
273 	bool in_4ba_mode;
274 };
275 
276 /* Timing used in probe routines. ZERO is -2 to differentiate between an unset
277  * field and zero delay.
278  *
279  * SPI devices will always have zero delay and ignore this field.
280  */
281 #define TIMING_FIXME	-1
282 /* this is intentionally same value as fixme */
283 #define TIMING_IGNORED	-1
284 #define TIMING_ZERO	-2
285 
286 extern const struct flashchip flashchips[];
287 extern const unsigned int flashchips_size;
288 
289 void chip_writeb(const struct flashctx *flash, uint8_t val, chipaddr addr);
290 void chip_writew(const struct flashctx *flash, uint16_t val, chipaddr addr);
291 void chip_writel(const struct flashctx *flash, uint32_t val, chipaddr addr);
292 void chip_writen(const struct flashctx *flash, const uint8_t *buf, chipaddr addr, size_t len);
293 uint8_t chip_readb(const struct flashctx *flash, const chipaddr addr);
294 uint16_t chip_readw(const struct flashctx *flash, const chipaddr addr);
295 uint32_t chip_readl(const struct flashctx *flash, const chipaddr addr);
296 void chip_readn(const struct flashctx *flash, uint8_t *buf, const chipaddr addr, size_t len);
297 
298 /* print.c */
299 int print_supported(void);
300 void print_supported_wiki(void);
301 
302 /* helpers.c */
303 uint32_t address_to_bits(uint32_t addr);
304 unsigned int bitcount(unsigned long a);
305 #undef MIN
306 #define MIN(a, b) ((a) < (b) ? (a) : (b))
307 #undef MAX
308 #define MAX(a, b) ((a) > (b) ? (a) : (b))
309 int max(int a, int b);
310 int min(int a, int b);
311 char *strcat_realloc(char *dest, const char *src);
312 void tolower_string(char *str);
313 uint8_t reverse_byte(uint8_t x);
314 void reverse_bytes(uint8_t *dst, const uint8_t *src, size_t length);
315 #ifdef __MINGW32__
316 char* strtok_r(char *str, const char *delim, char **nextp);
317 char *strndup(const char *str, size_t size);
318 #endif
319 #if defined(__DJGPP__) || (!defined(__LIBPAYLOAD__) && !defined(HAVE_STRNLEN))
320 size_t strnlen(const char *str, size_t n);
321 #endif
322 
323 /* flashrom.c */
324 extern const char flashrom_version[];
325 extern const char *chip_to_probe;
326 char *flashbuses_to_text(enum chipbustype bustype);
327 int map_flash(struct flashctx *flash);
328 void unmap_flash(struct flashctx *flash);
329 int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len);
330 int erase_flash(struct flashctx *flash);
331 int probe_flash(struct registered_master *mst, int startchip, struct flashctx *fill_flash, int force);
332 int read_flash_to_file(struct flashctx *flash, const char *filename);
333 char *extract_param(const char *const *haystack, const char *needle, const char *delim);
334 int verify_range(struct flashctx *flash, const uint8_t *cmpbuf, unsigned int start, unsigned int len);
335 int need_erase(const uint8_t *have, const uint8_t *want, unsigned int len, enum write_granularity gran, const uint8_t erased_value);
336 void print_version(void);
337 void print_buildinfo(void);
338 void print_banner(void);
339 void list_programmers_linebreak(int startcol, int cols, int paren);
340 int selfcheck(void);
341 int read_buf_from_file(unsigned char *buf, unsigned long size, const char *filename);
342 int write_buf_to_file(const unsigned char *buf, unsigned long size, const char *filename);
343 int prepare_flash_access(struct flashctx *, bool read_it, bool write_it, bool erase_it, bool verify_it);
344 void finalize_flash_access(struct flashctx *);
345 int do_read(struct flashctx *, const char *filename);
346 int do_erase(struct flashctx *);
347 int do_write(struct flashctx *, const char *const filename, const char *const referencefile);
348 int do_verify(struct flashctx *, const char *const filename);
349 
350 /* Something happened that shouldn't happen, but we can go on. */
351 #define ERROR_NONFATAL 0x100
352 
353 /* Something happened that shouldn't happen, we'll abort. */
354 #define ERROR_FATAL -0xee
355 #define ERROR_FLASHROM_BUG -200
356 /* We reached one of the hardcoded limits of flashrom. This can be fixed by
357  * increasing the limit of a compile-time allocation or by switching to dynamic
358  * allocation.
359  * Note: If this warning is triggered, check first for runaway registrations.
360  */
361 #define ERROR_FLASHROM_LIMIT -201
362 
363 /* cli_common.c */
364 void print_chip_support_status(const struct flashchip *chip);
365 
366 /* cli_output.c */
367 extern enum flashrom_log_level verbose_screen;
368 extern enum flashrom_log_level verbose_logfile;
369 #ifndef STANDALONE
370 int open_logfile(const char * const filename);
371 int close_logfile(void);
372 void start_logging(void);
373 #endif
374 int flashrom_print_cb(enum flashrom_log_level level, const char *fmt, va_list ap);
375 /* Let gcc and clang check for correct printf-style format strings. */
376 int print(enum flashrom_log_level level, const char *fmt, ...)
377 #ifdef __MINGW32__
378 #  ifndef __MINGW_PRINTF_FORMAT
379 #    define __MINGW_PRINTF_FORMAT gnu_printf
380 #  endif
381 __attribute__((format(__MINGW_PRINTF_FORMAT, 2, 3)));
382 #else
383 __attribute__((format(printf, 2, 3)));
384 #endif
385 #define msg_gerr(...)	print(FLASHROM_MSG_ERROR, __VA_ARGS__)	/* general errors */
386 #define msg_perr(...)	print(FLASHROM_MSG_ERROR, __VA_ARGS__)	/* programmer errors */
387 #define msg_cerr(...)	print(FLASHROM_MSG_ERROR, __VA_ARGS__)	/* chip errors */
388 #define msg_gwarn(...)	print(FLASHROM_MSG_WARN, __VA_ARGS__)	/* general warnings */
389 #define msg_pwarn(...)	print(FLASHROM_MSG_WARN, __VA_ARGS__)	/* programmer warnings */
390 #define msg_cwarn(...)	print(FLASHROM_MSG_WARN, __VA_ARGS__)	/* chip warnings */
391 #define msg_ginfo(...)	print(FLASHROM_MSG_INFO, __VA_ARGS__)	/* general info */
392 #define msg_pinfo(...)	print(FLASHROM_MSG_INFO, __VA_ARGS__)	/* programmer info */
393 #define msg_cinfo(...)	print(FLASHROM_MSG_INFO, __VA_ARGS__)	/* chip info */
394 #define msg_gdbg(...)	print(FLASHROM_MSG_DEBUG, __VA_ARGS__)	/* general debug */
395 #define msg_pdbg(...)	print(FLASHROM_MSG_DEBUG, __VA_ARGS__)	/* programmer debug */
396 #define msg_cdbg(...)	print(FLASHROM_MSG_DEBUG, __VA_ARGS__)	/* chip debug */
397 #define msg_gdbg2(...)	print(FLASHROM_MSG_DEBUG2, __VA_ARGS__)	/* general debug2 */
398 #define msg_pdbg2(...)	print(FLASHROM_MSG_DEBUG2, __VA_ARGS__)	/* programmer debug2 */
399 #define msg_cdbg2(...)	print(FLASHROM_MSG_DEBUG2, __VA_ARGS__)	/* chip debug2 */
400 #define msg_gspew(...)	print(FLASHROM_MSG_SPEW, __VA_ARGS__)	/* general debug spew  */
401 #define msg_pspew(...)	print(FLASHROM_MSG_SPEW, __VA_ARGS__)	/* programmer debug spew  */
402 #define msg_cspew(...)	print(FLASHROM_MSG_SPEW, __VA_ARGS__)	/* chip debug spew  */
403 
404 /* layout.c */
405 int register_include_arg(struct layout_include_args **args, char *name);
406 int read_romlayout(const char *name);
407 int normalize_romentries(const struct flashctx *flash);
408 void layout_cleanup(struct layout_include_args **args);
409 
410 /* spi.c */
411 struct spi_command {
412 	unsigned int writecnt;
413 	unsigned int readcnt;
414 	const unsigned char *writearr;
415 	unsigned char *readarr;
416 };
417 #define NULL_SPI_CMD { 0, 0, NULL, NULL, }
418 int spi_send_command(struct flashctx *flash, unsigned int writecnt, unsigned int readcnt, const unsigned char *writearr, unsigned char *readarr);
419 int spi_send_multicommand(struct flashctx *flash, struct spi_command *cmds);
420 
421 enum chipbustype get_buses_supported(void);
422 #endif				/* !__FLASH_H__ */
423