xref: /aosp_15_r20/external/flashrom/flashrom.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2000 Silicon Integrated System Corporation
5  * Copyright (C) 2004 Tyan Corp <[email protected]>
6  * Copyright (C) 2005-2008 coresystems GmbH
7  * Copyright (C) 2008,2009 Carl-Daniel Hailfinger
8  * Copyright (C) 2016 secunet Security Networks AG
9  * (Written by Nico Huber <[email protected]> for secunet)
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  */
21 
22 #include <stdbool.h>
23 #include <stdio.h>
24 #include <stdint.h>
25 #include <sys/types.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <ctype.h>
31 
32 #include "flash.h"
33 #include "flashchips.h"
34 #include "programmer.h"
35 #include "hwaccess_physmap.h"
36 #include "chipdrivers.h"
37 #include "erasure_layout.h"
38 
39 #include "action_descriptor.h"
40 #include "spi.h"
41 #include "power.h"
42 #include "big_lock.h"
43 
44 static bool use_legacy_erase_path = false;
45 
46 const char flashrom_version[] = FLASHROM_VERSION;
47 
48 #ifndef USE_BIG_LOCK
49 #define USE_BIG_LOCK 0
50 #endif
51 
52 #define LOCK_TIMEOUT_SECS 180
53 
54 static const struct programmer_entry *programmer = NULL;
55 
56 /*
57  * Programmers supporting multiple buses can have differing size limits on
58  * each bus. Store the limits for each bus in a common struct.
59  */
60 struct decode_sizes max_rom_decode;
61 
62 /* If nonzero, used as the start address of bottom-aligned flash. */
63 uintptr_t flashbase;
64 
65 /* Is writing allowed with this programmer? */
66 bool programmer_may_write;
67 
68 #define SHUTDOWN_MAXFN 32
69 static int shutdown_fn_count = 0;
70 /** @private */
71 static struct shutdown_func_data {
72 	int (*func) (void *data);
73 	void *data;
74 } shutdown_fn[SHUTDOWN_MAXFN];
75 /* Initialize to 0 to make sure nobody registers a shutdown function before
76  * programmer init.
77  */
78 static bool may_register_shutdown = false;
79 
80 static struct bus_type_info {
81 	enum chipbustype type;
82 	const char *name;
83 } bustypes[] = {
84 	{ BUS_PARALLEL, "Parallel, " },
85 	{ BUS_LPC, "LPC, " },
86 	{ BUS_FWH, "FWH, " },
87 	{ BUS_SPI, "SPI, " },
88 	{ BUS_PROG, "Programmer-specific, " },
89 };
90 
91 /* Register a function to be executed on programmer shutdown.
92  * The advantage over atexit() is that you can supply a void pointer which will
93  * be used as parameter to the registered function upon programmer shutdown.
94  * This pointer can point to arbitrary data used by said function, e.g. undo
95  * information for GPIO settings etc. If unneeded, set data=NULL.
96  * Please note that the first (void *data) belongs to the function signature of
97  * the function passed as first parameter.
98  */
register_shutdown(int (* function)(void * data),void * data)99 int register_shutdown(int (*function) (void *data), void *data)
100 {
101 	if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
102 		msg_perr("Tried to register more than %i shutdown functions.\n",
103 			 SHUTDOWN_MAXFN);
104 		return 1;
105 	}
106 	if (!may_register_shutdown) {
107 		msg_perr("Tried to register a shutdown function before "
108 			 "programmer init.\n");
109 		return 1;
110 	}
111 	shutdown_fn[shutdown_fn_count].func = function;
112 	shutdown_fn[shutdown_fn_count].data = data;
113 	shutdown_fn_count++;
114 
115 	return 0;
116 }
117 
register_chip_restore(chip_restore_fn_cb_t func,struct flashctx * flash,void * data)118 int register_chip_restore(chip_restore_fn_cb_t func,
119 			  struct flashctx *flash, void *data)
120 {
121 	if (flash->chip_restore_fn_count >= MAX_CHIP_RESTORE_FUNCTIONS) {
122 		msg_perr("Tried to register more than %i chip restore"
123 		         " functions.\n", MAX_CHIP_RESTORE_FUNCTIONS);
124 		return 1;
125 	}
126 	flash->chip_restore_fn[flash->chip_restore_fn_count].func = func;
127 	flash->chip_restore_fn[flash->chip_restore_fn_count].data = data;
128 	flash->chip_restore_fn_count++;
129 
130 	return 0;
131 }
132 
deregister_chip_restore(struct flashctx * flash)133 static int deregister_chip_restore(struct flashctx *flash)
134 {
135 	int rc = 0;
136 
137 	while (flash->chip_restore_fn_count > 0) {
138 		int i = --flash->chip_restore_fn_count;
139 		rc |= flash->chip_restore_fn[i].func(
140 			flash, flash->chip_restore_fn[i].data);
141 	}
142 
143 	return rc;
144 }
145 
programmer_init(const struct programmer_entry * prog,const char * param)146 int programmer_init(const struct programmer_entry *prog, const char *param)
147 {
148 	int ret;
149 #if CONFIG_DUMMY == 1
150 	const struct programmer_entry *dummy_programmer = &programmer_dummy;
151 #else
152 	const struct programmer_entry *dummy_programmer = NULL;
153 #endif
154 
155 	if (prog == NULL) {
156 		msg_perr("Invalid programmer specified!\n");
157 		return -1;
158 	}
159 
160 	/* Only acquire the big lock for non-dummy programmer. */
161 	if (USE_BIG_LOCK && prog != dummy_programmer) {
162 		/* Get big lock before doing any work that touches hardware. */
163 		if (acquire_big_lock(LOCK_TIMEOUT_SECS) < 0)
164 			return 1;
165 	}
166 
167 	programmer = prog;
168 	/* Initialize all programmer specific data. */
169 	/* Default to unlimited decode sizes. */
170 	max_rom_decode = (const struct decode_sizes) {
171 		.parallel	= 0xffffffff,
172 		.lpc		= 0xffffffff,
173 		.fwh		= 0xffffffff,
174 		.spi		= 0xffffffff,
175 	};
176 	/* Default to top aligned flash at 4 GB. */
177 	flashbase = 0;
178 	/* Registering shutdown functions is now allowed. */
179 	may_register_shutdown = true;
180 	/* Default to allowing writes. Broken programmers set this to 0. */
181 	programmer_may_write = true;
182 
183 	struct programmer_cfg cfg;
184 
185 	if (param) {
186 		cfg.params = strdup(param);
187 		if (!cfg.params) {
188 			msg_perr("Out of memory!\n");
189 			return ERROR_FLASHROM_FATAL;
190 		}
191 	} else {
192 		cfg.params = NULL;
193 	}
194 
195 	msg_pdbg("Initializing %s programmer\n", prog->name);
196 	ret = prog->init(&cfg);
197 	if (cfg.params && strlen(cfg.params)) {
198 		if (ret != 0) {
199 			/* It is quite possible that any unhandled programmer parameter would have been valid,
200 			 * but an error in actual programmer init happened before the parameter was evaluated.
201 			 */
202 			msg_pwarn("Unhandled programmer parameters (possibly due to another failure): %s\n",
203 				  cfg.params);
204 		} else {
205 			/* Actual programmer init was successful, but the user specified an invalid or unusable
206 			 * (for the current programmer configuration) parameter.
207 			 */
208 			msg_perr("Unhandled programmer parameters: %s\n", cfg.params);
209 			msg_perr("Aborting.\n");
210 			ret = ERROR_FLASHROM_FATAL;
211 		}
212 	}
213 	free(cfg.params);
214 
215 	/* Release lock if initialization is not succseeful. */
216 	if (USE_BIG_LOCK && ret != 0)
217 		release_big_lock();
218 
219 	return ret;
220 }
221 
222 /** Calls registered shutdown functions and resets internal programmer-related variables.
223  * Calling it is safe even without previous initialization, but further interactions with programmer support
224  * require a call to programmer_init() (afterwards).
225  *
226  * @return The OR-ed result values of all shutdown functions (i.e. 0 on success). */
programmer_shutdown(void)227 int programmer_shutdown(void)
228 {
229 	int ret = 0;
230 
231 	/* Registering shutdown functions is no longer allowed. */
232 	may_register_shutdown = false;
233 	while (shutdown_fn_count > 0) {
234 		int i = --shutdown_fn_count;
235 		ret |= shutdown_fn[i].func(shutdown_fn[i].data);
236 	}
237 	registered_master_count = 0;
238 
239 	if (USE_BIG_LOCK)
240 		release_big_lock();
241 
242 	return ret;
243 }
244 
master_map_flash_region(const struct registered_master * mst,const char * descr,uintptr_t phys_addr,size_t len)245 void *master_map_flash_region(const struct registered_master *mst,
246 			      const char *descr, uintptr_t phys_addr,
247 			      size_t len)
248 {
249 	/* Check the bus master for a specialized map_flash_region; default to
250 	 * fallback if it does not specialize it
251 	 */
252 	void *(*map_flash_region) (const char *descr, uintptr_t phys_addr, size_t len) = NULL;
253 	if (mst->buses_supported & BUS_SPI)
254 		map_flash_region = mst->spi.map_flash_region;
255 	else if (mst->buses_supported & BUS_NONSPI)
256 		map_flash_region = mst->par.map_flash_region;
257 
258 	/* A result of NULL causes mapped addresses to be chip physical
259 	 * addresses, assuming only a single region is mapped (the entire flash
260 	 * space).  Chips with a second region (like a register map) require a
261 	 * real memory mapping to distinguish the different ranges.  Those chips
262 	 * are FWH/LPC, so the bus master provides a real mapping.
263 	 */
264 	void *ret = NULL;
265 	if (map_flash_region)
266 		ret = map_flash_region(descr, phys_addr, len);
267 	msg_gspew("%s: mapping %s from 0x%0*" PRIxPTR " to 0x%0*" PRIxPTR "\n",
268 		__func__, descr, PRIxPTR_WIDTH, phys_addr, PRIxPTR_WIDTH, (uintptr_t) ret);
269 	return ret;
270 }
271 
master_unmap_flash_region(const struct registered_master * mst,void * virt_addr,size_t len)272 void master_unmap_flash_region(const struct registered_master *mst,
273 			       void *virt_addr, size_t len)
274 {
275 	void (*unmap_flash_region) (void *virt_addr, size_t len) = NULL;
276 	if (mst->buses_supported & BUS_SPI)
277 		unmap_flash_region = mst->spi.unmap_flash_region;
278 	else if (mst->buses_supported & BUS_NONSPI)
279 		unmap_flash_region = mst->par.unmap_flash_region;
280 
281 	if (unmap_flash_region)
282 		unmap_flash_region(virt_addr, len);
283 	msg_gspew("%s: unmapped 0x%0*" PRIxPTR "\n", __func__, PRIxPTR_WIDTH, (uintptr_t)virt_addr);
284 }
285 
master_uses_physmap(const struct registered_master * mst)286 static bool master_uses_physmap(const struct registered_master *mst)
287 {
288 #if CONFIG_INTERNAL == 1
289 	if (mst->buses_supported & BUS_SPI)
290 		return mst->spi.map_flash_region == physmap;
291 	else if (mst->buses_supported & BUS_NONSPI)
292 		return mst->par.map_flash_region == physmap;
293 #endif
294 	return false;
295 }
296 
programmer_delay(const struct flashctx * flash,unsigned int usecs)297 void programmer_delay(const struct flashctx *flash, unsigned int usecs)
298 {
299 	if (usecs == 0)
300 		return;
301 
302 	/**
303 	 * Drivers should either use default_delay() directly or their
304 	 * own custom delay. Only core flashrom logic calls programmer_delay()
305 	 * which should always have a valid flash context. A NULL context
306 	 * more than likely indicates a layering violation or BUG however
307 	 * for now dispatch a default_delay() as a safe default for the NULL
308 	 * base case.
309 	 */
310 	if (!flash) {
311 		msg_perr("%s called with NULL flash context. "
312 			 "Please report a bug at [email protected]\n",
313 			 __func__);
314 		return default_delay(usecs);
315 	}
316 
317 	if (flash->mst->buses_supported & BUS_SPI) {
318 		if (flash->mst->spi.delay)
319 			return flash->mst->spi.delay(flash, usecs);
320 	} else if (flash->mst->buses_supported & BUS_PARALLEL) {
321 		if (flash->mst->par.delay)
322 			return flash->mst->par.delay(flash, usecs);
323 	} else if (flash->mst->buses_supported & BUS_PROG) {
324 		if (flash->mst->opaque.delay)
325 			return flash->mst->opaque.delay(flash, usecs);
326 	}
327 
328 	return default_delay(usecs);
329 }
330 
read_memmapped(struct flashctx * flash,uint8_t * buf,unsigned int start,int unsigned len)331 int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start,
332 		   int unsigned len)
333 {
334 	chip_readn(flash, buf, flash->virtual_memory + start, len);
335 
336 	return 0;
337 }
338 
339 /* This is a somewhat hacked function similar in some ways to strtok().
340  * It will look for needle with a subsequent '=' in haystack, return a copy of
341  * needle and remove everything from the first occurrence of needle to the next
342  * delimiter from haystack.
343  */
extract_param(char * const * haystack,const char * needle,const char * delim)344 static char *extract_param(char *const *haystack, const char *needle, const char *delim)
345 {
346 	char *param_pos, *opt_pos, *rest;
347 	char *opt = NULL;
348 	int optlen;
349 	int needlelen;
350 
351 	needlelen = strlen(needle);
352 	if (!needlelen) {
353 		msg_gerr("%s: empty needle! Please report a bug at "
354 			 "[email protected]\n", __func__);
355 		return NULL;
356 	}
357 	/* No programmer parameters given. */
358 	if (*haystack == NULL)
359 		return NULL;
360 	param_pos = strstr(*haystack, needle);
361 	do {
362 		if (!param_pos)
363 			return NULL;
364 		/* Needle followed by '='? */
365 		if (param_pos[needlelen] == '=') {
366 			/* Beginning of the string? */
367 			if (param_pos == *haystack)
368 				break;
369 			/* After a delimiter? */
370 			if (strchr(delim, *(param_pos - 1)))
371 				break;
372 		}
373 		/* Continue searching. */
374 		param_pos++;
375 		param_pos = strstr(param_pos, needle);
376 	} while (1);
377 
378 	if (param_pos) {
379 		/* Get the string after needle and '='. */
380 		opt_pos = param_pos + needlelen + 1;
381 		optlen = strcspn(opt_pos, delim);
382 		/* Return an empty string if the parameter was empty. */
383 		opt = malloc(optlen + 1);
384 		if (!opt) {
385 			msg_gerr("Out of memory!\n");
386 			return NULL;
387 		}
388 		strncpy(opt, opt_pos, optlen);
389 		opt[optlen] = '\0';
390 		rest = opt_pos + optlen;
391 		/* Skip all delimiters after the current parameter. */
392 		rest += strspn(rest, delim);
393 		memmove(param_pos, rest, strlen(rest) + 1);
394 		/* We could shrink haystack, but the effort is not worth it. */
395 	}
396 
397 	return opt;
398 }
399 
extract_programmer_param_str(const struct programmer_cfg * cfg,const char * param_name)400 char *extract_programmer_param_str(const struct programmer_cfg *cfg, const char *param_name)
401 {
402 	return extract_param(&cfg->params, param_name, ",");
403 }
404 
get_flash_region(const struct flashctx * flash,int addr,struct flash_region * region)405 void get_flash_region(const struct flashctx *flash, int addr, struct flash_region *region)
406 {
407 	if ((flash->mst->buses_supported & BUS_PROG) && flash->mst->opaque.get_region) {
408 		flash->mst->opaque.get_region(flash, addr, region);
409 	} else if (flash->mst->buses_supported & BUS_SPI && flash->mst->spi.get_region) {
410 		flash->mst->spi.get_region(flash, addr, region);
411 	} else {
412 		region->name = strdup("");
413 		region->start = 0;
414 		region->end = flashrom_flash_getsize(flash);
415 		region->read_prot = false;
416 		region->write_prot = false;
417 	}
418 }
419 
check_for_unwritable_regions(const struct flashctx * flash,unsigned int start,unsigned int len)420 int check_for_unwritable_regions(const struct flashctx *flash, unsigned int start, unsigned int len)
421 {
422 	struct flash_region region;
423 	for (unsigned int addr = start; addr < start + len; addr = region.end) {
424 		get_flash_region(flash, addr, &region);
425 
426 		if (region.write_prot) {
427 			msg_gerr("%s: cannot write/erase inside %s region (%#08"PRIx32"..%#08"PRIx32").\n",
428 				 __func__, region.name, region.start, region.end - 1);
429 			free(region.name);
430 			return -1;
431 		}
432 		free(region.name);
433 	}
434 	return 0;
435 }
436 
437 /* special unit-test hook */
438 erasefunc_t *g_test_erase_injector;
439 
lookup_erase_func_ptr(const struct block_eraser * const eraser)440 erasefunc_t *lookup_erase_func_ptr(const struct block_eraser *const eraser)
441 {
442 	switch (eraser->block_erase) {
443 		case SPI_BLOCK_ERASE_EMULATION: return &spi_block_erase_emulation;
444 		case SPI_BLOCK_ERASE_20: return &spi_block_erase_20;
445 		case SPI_BLOCK_ERASE_21: return &spi_block_erase_21;
446 		case SPI_BLOCK_ERASE_40: return NULL; // FIXME unhandled &spi_block_erase_40;
447 		case SPI_BLOCK_ERASE_50: return &spi_block_erase_50;
448 		case SPI_BLOCK_ERASE_52: return &spi_block_erase_52;
449 		case SPI_BLOCK_ERASE_53: return &spi_block_erase_53;
450 		case SPI_BLOCK_ERASE_5C: return &spi_block_erase_5c;
451 		case SPI_BLOCK_ERASE_60: return &spi_block_erase_60;
452 		case SPI_BLOCK_ERASE_62: return &spi_block_erase_62;
453 		case SPI_BLOCK_ERASE_81: return &spi_block_erase_81;
454 		case SPI_BLOCK_ERASE_C4: return &spi_block_erase_c4;
455 		case SPI_BLOCK_ERASE_C7: return &spi_block_erase_c7;
456 		case SPI_BLOCK_ERASE_D7: return &spi_block_erase_d7;
457 		case SPI_BLOCK_ERASE_D8: return &spi_block_erase_d8;
458 		case SPI_BLOCK_ERASE_DB: return &spi_block_erase_db;
459 		case SPI_BLOCK_ERASE_DC: return &spi_block_erase_dc;
460 		case S25FL_BLOCK_ERASE: return &s25fl_block_erase;
461 		case S25FS_BLOCK_ERASE_D8: return &s25fs_block_erase_d8;
462 		case JEDEC_SECTOR_ERASE: return &erase_sector_jedec; // TODO rename to &jedec_sector_erase;
463 		case JEDEC_BLOCK_ERASE: return &erase_block_jedec; // TODO rename to &jedec_block_erase;
464 		case JEDEC_CHIP_BLOCK_ERASE: return &erase_chip_block_jedec; // TODO rename to &jedec_chip_block_erase;
465 		case OPAQUE_ERASE: return &erase_opaque; // TODO rename to &opqaue_erase;
466 		case SPI_ERASE_AT45CS_SECTOR: return &spi_erase_at45cs_sector;
467 		case SPI_ERASE_AT45DB_BLOCK: return &spi_erase_at45db_block;
468 		case SPI_ERASE_AT45DB_CHIP: return &spi_erase_at45db_chip;
469 		case SPI_ERASE_AT45DB_PAGE: return &spi_erase_at45db_page;
470 		case SPI_ERASE_AT45DB_SECTOR: return &spi_erase_at45db_sector;
471 		case ERASE_CHIP_28SF040: return &erase_chip_28sf040;
472 		case ERASE_SECTOR_28SF040: return &erase_sector_28sf040;
473 		case ERASE_BLOCK_82802AB: return &erase_block_82802ab;
474 		case ERASE_SECTOR_49LFXXXC: return &erase_sector_49lfxxxc;
475 		case STM50_SECTOR_ERASE: return &erase_sector_stm50; // TODO rename to &stm50_sector_erase;
476 		case EDI_CHIP_BLOCK_ERASE: return &edi_chip_block_erase;
477 		case CROS_EC_BLOCK_ERASE: return &cros_ec_block_erase;
478 		case TEST_ERASE_INJECTOR: return g_test_erase_injector;
479 	/* default: total function, 0 indicates no erase function set.
480 	 * We explicitly do not want a default catch-all case in the switch
481 	 * to ensure unhandled enum's are compiler warnings.
482 	 */
483 		case NO_BLOCK_ERASE_FUNC: return NULL;
484 	};
485 
486 	return NULL;
487 }
488 
check_block_eraser(const struct flashctx * flash,int k,int log)489 int check_block_eraser(const struct flashctx *flash, int k, int log)
490 {
491 	struct block_eraser eraser = flash->chip->block_erasers[k];
492 
493 	if (eraser.block_erase == NO_BLOCK_ERASE_FUNC && !eraser.eraseblocks[0].count) {
494 		if (log)
495 			msg_cdbg("not defined. ");
496 		return 1;
497 	}
498 	if (eraser.block_erase == NO_BLOCK_ERASE_FUNC && eraser.eraseblocks[0].count) {
499 		if (log)
500 			msg_cdbg("eraseblock layout is known, but matching "
501 				 "block erase function is not implemented. ");
502 		return 1;
503 	}
504 	if (eraser.block_erase != NO_BLOCK_ERASE_FUNC && !eraser.eraseblocks[0].count) {
505 		if (log)
506 			msg_cdbg("block erase function found, but "
507 				 "eraseblock layout is not defined. ");
508 		return 1;
509 	}
510 
511 	if (flash->mst->buses_supported & BUS_SPI) {
512 		const uint8_t *opcode = spi_get_opcode_from_erasefn(eraser.block_erase);
513 		if (opcode)
514 			for (int i = 0; opcode[i]; i++) {
515 				if (!spi_probe_opcode(flash, opcode[i])) {
516 					if (log)
517 						msg_cdbg("block erase function and layout found "
518 							 "but SPI master doesn't support the function. ");
519 					return 1;
520 				}
521 			}
522 	}
523 	// TODO: Once erase functions are annotated with allowed buses, check that as well.
524 	return 0;
525 }
526 
527 /* Returns the number of well-defined erasers for a chip. */
count_usable_erasers(const struct flashctx * flash)528 unsigned int count_usable_erasers(const struct flashctx *flash)
529 {
530 	unsigned int usable_erasefunctions = 0;
531 	int k;
532 	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
533 		if (!check_block_eraser(flash, k, 0))
534 			usable_erasefunctions++;
535 	}
536 	return usable_erasefunctions;
537 }
538 
compare_range(const uint8_t * wantbuf,const uint8_t * havebuf,unsigned int start,unsigned int len)539 static int compare_range(const uint8_t *wantbuf, const uint8_t *havebuf, unsigned int start, unsigned int len)
540 {
541 	int ret = 0, failcount = 0;
542 	unsigned int i;
543 	for (i = 0; i < len; i++) {
544 		if (wantbuf[i] != havebuf[i]) {
545 			/* Only print the first failure. */
546 			if (!failcount++)
547 				msg_cerr("FAILED at 0x%08x! Expected=0x%02x, Found=0x%02x,",
548 					 start + i, wantbuf[i], havebuf[i]);
549 		}
550 	}
551 	if (failcount) {
552 		msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
553 			 start, start + len - 1, failcount);
554 		ret = -1;
555 	}
556 	return ret;
557 }
558 
559 /* start is an offset to the base address of the flash chip */
check_erased_range(struct flashctx * flash,unsigned int start,unsigned int len)560 int check_erased_range(struct flashctx *flash, unsigned int start, unsigned int len)
561 {
562 	int ret;
563 	const uint8_t erased_value = ERASED_VALUE(flash);
564 
565 	uint8_t *cmpbuf = malloc(len);
566 	if (!cmpbuf) {
567 		msg_gerr("Out of memory!\n");
568 		return -1;
569 	}
570 	memset(cmpbuf, erased_value, len);
571 	ret = verify_range(flash, cmpbuf, start, len);
572 
573 	free(cmpbuf);
574 	return ret;
575 }
576 
577 /* special unit-test hook */
578 read_func_t *g_test_read_injector;
579 
lookup_read_func_ptr(const struct flashchip * chip)580 static read_func_t *lookup_read_func_ptr(const struct flashchip *chip)
581 {
582 	switch (chip->read) {
583 		case SPI_CHIP_READ: return &spi_chip_read;
584 		case READ_OPAQUE: return &read_opaque;
585 		case READ_MEMMAPPED: return &read_memmapped;
586 		case EDI_CHIP_READ: return &edi_chip_read;
587 		case SPI_READ_AT45DB: return spi_read_at45db;
588 		case SPI_READ_AT45DB_E8: return spi_read_at45db_e8;
589 		case TEST_READ_INJECTOR: return g_test_read_injector;
590 	/* default: total function, 0 indicates no read function set.
591 	 * We explicitly do not want a default catch-all case in the switch
592 	 * to ensure unhandled enum's are compiler warnings.
593 	 */
594 		case NO_READ_FUNC: return NULL;
595 	};
596 
597 	return NULL;
598 }
599 
600 /*
601  * @brief Wrapper for flash->read() with additional high-level policy.
602  *
603  * @param flash flash chip
604  * @param buf   buffer to store data in
605  * @param start start address
606  * @param len   number of bytes to read
607  * @return      0 on success,
608  *              -1 if any read fails.
609  *
610  * This wrapper simplifies most cases when the flash chip needs to be read
611  * since policy decisions such as non-fatal error handling is centralized.
612  */
read_flash(struct flashctx * flash,uint8_t * buf,unsigned int start,unsigned int len)613 int read_flash(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
614 {
615 	unsigned int read_len;
616 	for (unsigned int addr = start; addr < start + len; addr += read_len) {
617 		struct flash_region region;
618 		get_flash_region(flash, addr, &region);
619 
620 		read_len = min(start + len, region.end) - addr;
621 		uint8_t *rbuf = buf + addr - start;
622 
623 		if (region.read_prot) {
624 			if (flash->flags.skip_unreadable_regions) {
625 				msg_gdbg("%s: cannot read inside %s region (%#08"PRIx32"..%#08"PRIx32"), "
626 					 "filling (%#08x..%#08x) with erased value instead.\n",
627 					 __func__, region.name, region.start, region.end - 1,
628 					 addr, addr + read_len - 1);
629 				free(region.name);
630 
631 				memset(rbuf, ERASED_VALUE(flash), read_len);
632 				continue;
633 			}
634 
635 			msg_gerr("%s: cannot read inside %s region (%#08"PRIx32"..%#08"PRIx32").\n",
636 				 __func__, region.name, region.start, region.end - 1);
637 			free(region.name);
638 			return -1;
639 		}
640 		msg_gdbg("%s: %s region (%#08"PRIx32"..%#08"PRIx32") is readable, reading range (%#08x..%#08x).\n",
641 			 __func__, region.name, region.start, region.end - 1, addr, addr + read_len - 1);
642 		free(region.name);
643 
644 		read_func_t *read_func = lookup_read_func_ptr(flash->chip);
645 		int ret = read_func(flash, rbuf, addr, read_len);
646 		if (ret) {
647 			msg_gerr("%s: failed to read (%#08x..%#08x).\n", __func__, addr, addr + read_len - 1);
648 			return -1;
649 		}
650 
651 	}
652 
653 	return 0;
654 }
655 
656 /*
657  * @cmpbuf	buffer to compare against, cmpbuf[0] is expected to match the
658  *		flash content at location start
659  * @start	offset to the base address of the flash chip
660  * @len		length of the verified area
661  * @return	0 for success, -1 for failure
662  */
verify_range(struct flashctx * flash,const uint8_t * cmpbuf,unsigned int start,unsigned int len)663 int verify_range(struct flashctx *flash, const uint8_t *cmpbuf, unsigned int start, unsigned int len)
664 {
665 	if (!len)
666 		return -1;
667 
668 	if (start + len > flash->chip->total_size * 1024) {
669 		msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
670 			" total_size 0x%x\n", __func__, start, len,
671 			flash->chip->total_size * 1024);
672 		return -1;
673 	}
674 
675 	uint8_t *readbuf = malloc(len);
676 	if (!readbuf) {
677 		msg_gerr("Out of memory!\n");
678 		return -1;
679 	}
680 
681 	int ret = 0;
682 
683 	msg_gdbg("%#06x..%#06x ", start, start + len - 1);
684 
685 	unsigned int read_len;
686 	for (size_t addr = start; addr < start + len; addr += read_len) {
687 		struct flash_region region;
688 		get_flash_region(flash, addr, &region);
689 		read_len = min(start + len, region.end) - addr;
690 
691 		if ((region.write_prot && flash->flags.skip_unwritable_regions) ||
692 		    (region.read_prot  && flash->flags.skip_unreadable_regions)) {
693 			msg_gdbg("%s: Skipping verification of %s region (%#08"PRIx32"..%#08"PRIx32")\n",
694 				 __func__, region.name, region.start, region.end - 1);
695 			free(region.name);
696 			continue;
697 		}
698 
699 		if (region.read_prot) {
700 			msg_gerr("%s: Verification imposible because %s region (%#08"PRIx32"..%#08"PRIx32") is unreadable.\n",
701 				 __func__, region.name, region.start, region.end - 1);
702 			free(region.name);
703 			goto out_free;
704 		}
705 
706 		msg_gdbg("%s: Verifying %s region (%#08"PRIx32"..%#08"PRIx32")\n",
707 			 __func__, region.name, region.start, region.end - 1);
708 		free(region.name);
709 
710 		ret = read_flash(flash, readbuf, addr, read_len);
711 		if (ret) {
712 			msg_gerr("Verification impossible because read failed "
713 				 "at 0x%x (len 0x%x)\n", start, len);
714 			ret = -1;
715 			goto out_free;
716 		}
717 
718 		ret = compare_range(cmpbuf + (addr - start), readbuf, addr, read_len);
719 		if (ret)
720 			goto out_free;
721 
722 	}
723 
724 out_free:
725 	free(readbuf);
726 	return ret;
727 }
728 
729 /* Helper function for need_erase() that focuses on granularities of gran bytes. */
need_erase_gran_bytes(const uint8_t * have,const uint8_t * want,unsigned int len,unsigned int gran,const uint8_t erased_value)730 static int need_erase_gran_bytes(const uint8_t *have, const uint8_t *want, unsigned int len,
731                                  unsigned int gran, const uint8_t erased_value)
732 {
733 	unsigned int i, j, limit;
734 	for (j = 0; j < len / gran; j++) {
735 		limit = min (gran, len - j * gran);
736 		/* Are 'have' and 'want' identical? */
737 		if (!memcmp(have + j * gran, want + j * gran, limit))
738 			continue;
739 		/* have needs to be in erased state. */
740 		for (i = 0; i < limit; i++)
741 			if (have[j * gran + i] != erased_value)
742 				return 1;
743 	}
744 	return 0;
745 }
746 
747 /*
748  * Check if the buffer @have can be programmed to the content of @want without
749  * erasing. This is only possible if all chunks of size @gran are either kept
750  * as-is or changed from an all-ones state to any other state.
751  *
752  * Warning: This function assumes that @have and @want point to naturally
753  * aligned regions.
754  *
755  * @have        buffer with current content
756  * @want        buffer with desired content
757  * @len		length of the checked area
758  * @gran	write granularity (enum, not count)
759  * @return      0 if no erase is needed, 1 otherwise
760  */
need_erase(const uint8_t * have,const uint8_t * want,unsigned int len,enum write_granularity gran,const uint8_t erased_value)761 int need_erase(const uint8_t *have, const uint8_t *want, unsigned int len,
762                enum write_granularity gran, const uint8_t erased_value)
763 {
764 	int result = 0;
765 	unsigned int i;
766 
767 	switch (gran) {
768 	case WRITE_GRAN_1BIT:
769 		for (i = 0; i < len; i++)
770 			if ((have[i] & want[i]) != want[i]) {
771 				result = 1;
772 				break;
773 			}
774 		break;
775 	case WRITE_GRAN_1BYTE:
776 		for (i = 0; i < len; i++)
777 			if ((have[i] != want[i]) && (have[i] != erased_value)) {
778 				result = 1;
779 				break;
780 			}
781 		break;
782 	case WRITE_GRAN_128BYTES:
783 		result = need_erase_gran_bytes(have, want, len, 128, erased_value);
784 		break;
785 	case WRITE_GRAN_256BYTES:
786 		result = need_erase_gran_bytes(have, want, len, 256, erased_value);
787 		break;
788 	case WRITE_GRAN_264BYTES:
789 		result = need_erase_gran_bytes(have, want, len, 264, erased_value);
790 		break;
791 	case WRITE_GRAN_512BYTES:
792 		result = need_erase_gran_bytes(have, want, len, 512, erased_value);
793 		break;
794 	case WRITE_GRAN_528BYTES:
795 		result = need_erase_gran_bytes(have, want, len, 528, erased_value);
796 		break;
797 	case WRITE_GRAN_1024BYTES:
798 		result = need_erase_gran_bytes(have, want, len, 1024, erased_value);
799 		break;
800 	case WRITE_GRAN_1056BYTES:
801 		result = need_erase_gran_bytes(have, want, len, 1056, erased_value);
802 		break;
803 	case WRITE_GRAN_1BYTE_IMPLICIT_ERASE:
804 		/* Do not erase, handle content changes from anything->0xff by writing 0xff. */
805 		result = 0;
806 		break;
807 	default:
808 		msg_cerr("%s: Unsupported granularity! Please report a bug at "
809 			 "[email protected]\n", __func__);
810 	}
811 	return result;
812 }
813 
814 /**
815  * Check if the buffer @have needs to be programmed to get the content of @want.
816  * If yes, return 1 and fill in first_start with the start address of the
817  * write operation and first_len with the length of the first to-be-written
818  * chunk. If not, return 0 and leave first_start and first_len undefined.
819  *
820  * Warning: This function assumes that @have and @want point to naturally
821  * aligned regions.
822  *
823  * @have	buffer with current content
824  * @want	buffer with desired content
825  * @len		length of the checked area
826  * @gran	write granularity (enum, not count)
827  * @first_start	offset of the first byte which needs to be written (passed in
828  *		value is increased by the offset of the first needed write
829  *		relative to have/want or unchanged if no write is needed)
830  * @return	length of the first contiguous area which needs to be written
831  *		0 if no write is needed
832  *
833  * FIXME: This function needs a parameter which tells it about coalescing
834  * in relation to the max write length of the programmer and the max write
835  * length of the chip.
836  */
get_next_write(const uint8_t * have,const uint8_t * want,unsigned int len,unsigned int * first_start,enum write_granularity gran)837 unsigned int get_next_write(const uint8_t *have, const uint8_t *want, unsigned int len,
838 			  unsigned int *first_start,
839 			  enum write_granularity gran)
840 {
841 	bool need_write = false;
842 	unsigned int rel_start = 0, first_len = 0;
843 	unsigned int i, limit, stride;
844 
845 	switch (gran) {
846 	case WRITE_GRAN_1BIT:
847 	case WRITE_GRAN_1BYTE:
848 	case WRITE_GRAN_1BYTE_IMPLICIT_ERASE:
849 		stride = 1;
850 		break;
851 	case WRITE_GRAN_128BYTES:
852 		stride = 128;
853 		break;
854 	case WRITE_GRAN_256BYTES:
855 		stride = 256;
856 		break;
857 	case WRITE_GRAN_264BYTES:
858 		stride = 264;
859 		break;
860 	case WRITE_GRAN_512BYTES:
861 		stride = 512;
862 		break;
863 	case WRITE_GRAN_528BYTES:
864 		stride = 528;
865 		break;
866 	case WRITE_GRAN_1024BYTES:
867 		stride = 1024;
868 		break;
869 	case WRITE_GRAN_1056BYTES:
870 		stride = 1056;
871 		break;
872 	default:
873 		msg_cerr("%s: Unsupported granularity! Please report a bug at "
874 			 "[email protected]\n", __func__);
875 		/* Claim that no write was needed. A write with unknown
876 		 * granularity is too dangerous to try.
877 		 */
878 		return 0;
879 	}
880 	for (i = 0; i < len / stride; i++) {
881 		limit = min(stride, len - i * stride);
882 		/* Are 'have' and 'want' identical? */
883 		if (memcmp(have + i * stride, want + i * stride, limit)) {
884 			if (!need_write) {
885 				/* First location where have and want differ. */
886 				need_write = true;
887 				rel_start = i * stride;
888 			}
889 		} else {
890 			if (need_write) {
891 				/* First location where have and want
892 				 * do not differ anymore.
893 				 */
894 				break;
895 			}
896 		}
897 	}
898 	if (need_write)
899 		first_len = min(i * stride - rel_start, len);
900 	*first_start += rel_start;
901 	return first_len;
902 }
903 
unmap_flash(struct flashctx * flash)904 void unmap_flash(struct flashctx *flash)
905 {
906 	if (flash->virtual_registers != (chipaddr)ERROR_PTR) {
907 		master_unmap_flash_region(flash->mst, (void *)flash->virtual_registers, flash->chip->total_size * 1024);
908 		flash->physical_registers = 0;
909 		flash->virtual_registers = (chipaddr)ERROR_PTR;
910 	}
911 
912 	if (flash->virtual_memory != (chipaddr)ERROR_PTR) {
913 		master_unmap_flash_region(flash->mst, (void *)flash->virtual_memory, flash->chip->total_size * 1024);
914 		flash->physical_memory = 0;
915 		flash->virtual_memory = (chipaddr)ERROR_PTR;
916 	}
917 }
918 
map_flash(struct flashctx * flash)919 int map_flash(struct flashctx *flash)
920 {
921 	/* Init pointers to the fail-safe state to distinguish them later from legit values. */
922 	flash->virtual_memory = (chipaddr)ERROR_PTR;
923 	flash->virtual_registers = (chipaddr)ERROR_PTR;
924 
925 	/* FIXME: This avoids mapping (and unmapping) of flash chip definitions with size 0.
926 	 * These are used for various probing-related hacks that would not map successfully anyway and should be
927 	 * removed ASAP. */
928 	if (flash->chip->total_size == 0)
929 		return 0;
930 
931 	const chipsize_t size = flash->chip->total_size * 1024;
932 	uintptr_t base = flashbase ? flashbase : (0xffffffff - size + 1);
933 	void *addr = master_map_flash_region(flash->mst, flash->chip->name, base, size);
934 	if (addr == ERROR_PTR) {
935 		msg_perr("Could not map flash chip %s at 0x%0*" PRIxPTR ".\n",
936 			 flash->chip->name, PRIxPTR_WIDTH, base);
937 		return 1;
938 	}
939 	flash->physical_memory = base;
940 	flash->virtual_memory = (chipaddr)addr;
941 
942 	/* FIXME: Special function registers normally live 4 MByte below flash space, but it might be somewhere
943 	 * completely different on some chips and programmers, or not mappable at all.
944 	 * Ignore these problems for now and always report success. */
945 	if (flash->chip->feature_bits & FEATURE_REGISTERMAP) {
946 		base = 0xffffffff - size - 0x400000 + 1;
947 		addr = master_map_flash_region(flash->mst, "flash chip registers", base, size);
948 		if (addr == ERROR_PTR) {
949 			msg_pdbg2("Could not map flash chip registers %s at 0x%0*" PRIxPTR ".\n",
950 				 flash->chip->name, PRIxPTR_WIDTH, base);
951 			return 0;
952 		}
953 		flash->physical_registers = base;
954 		flash->virtual_registers = (chipaddr)addr;
955 	}
956 	return 0;
957 }
958 
959 /*
960  * Return a string corresponding to the bustype parameter.
961  * Memory to store the string is allocated. The caller is responsible to free memory.
962  * If there is not enough memory remaining, then NULL is returned.
963  */
flashbuses_to_text(enum chipbustype bustype)964 char *flashbuses_to_text(enum chipbustype bustype)
965 {
966 	char *ret, *ptr;
967 
968 	/*
969 	 * FIXME: Once all chipsets and flash chips have been updated, NONSPI
970 	 * will cease to exist and should be eliminated here as well.
971 	 */
972 	if (bustype == BUS_NONSPI)
973 		return strdup("Non-SPI");
974 	if (bustype == BUS_NONE)
975 		return strdup("None");
976 
977 	ret = calloc(1, 1);
978 	if (!ret)
979 		return NULL;
980 
981 	for (unsigned int i = 0; i < ARRAY_SIZE(bustypes); i++)
982 	{
983 		if (bustype & bustypes[i].type) {
984 			ptr = strcat_realloc(ret, bustypes[i].name);
985 			if (!ptr) {
986 				free(ret);
987 				return NULL;
988 			}
989 			ret = ptr;
990 		}
991 	}
992 
993 	/* Kill last comma. */
994 	ret[strlen(ret) - 2] = '\0';
995 	ptr = realloc(ret, strlen(ret) + 1);
996 	if (!ptr)
997 		free(ret);
998 	return ptr;
999 }
1000 
init_default_layout(struct flashctx * flash)1001 static int init_default_layout(struct flashctx *flash)
1002 {
1003 	/* Fill default layout covering the whole chip. */
1004 	if (flashrom_layout_new(&flash->default_layout) ||
1005 	    flashrom_layout_add_region(flash->default_layout,
1006 			0, flash->chip->total_size * 1024 - 1, "complete flash") ||
1007 	    flashrom_layout_include_region(flash->default_layout, "complete flash"))
1008 	        return -1;
1009 	return 0;
1010 }
1011 
1012 /* special unit-test hook */
1013 write_func_t *g_test_write_injector;
1014 
lookup_write_func_ptr(const struct flashchip * chip)1015 static write_func_t *lookup_write_func_ptr(const struct flashchip *chip)
1016 {
1017 	switch (chip->write) {
1018 		case WRITE_JEDEC: return &write_jedec;
1019 		case WRITE_JEDEC1: return &write_jedec_1;
1020 		case WRITE_OPAQUE: return &write_opaque;
1021 		case SPI_CHIP_WRITE1: return &spi_chip_write_1;
1022 		case SPI_CHIP_WRITE256: return &spi_chip_write_256;
1023 		case SPI_WRITE_AAI: return &spi_aai_write;
1024 		case SPI_WRITE_AT45DB: return &spi_write_at45db;
1025 		case WRITE_28SF040: return &write_28sf040;
1026 		case WRITE_82802AB: return &write_82802ab;
1027 		case WRITE_EN29LV640B: return &write_en29lv640b;
1028 		case EDI_CHIP_WRITE: return &edi_chip_write;
1029 		case TEST_WRITE_INJECTOR: return g_test_write_injector;
1030 	/* default: total function, 0 indicates no write function set.
1031 	 * We explicitly do not want a default catch-all case in the switch
1032 	 * to ensure unhandled enum's are compiler warnings.
1033 	 */
1034 		case NO_WRITE_FUNC: return NULL;
1035 	};
1036 
1037 	return NULL;
1038 }
1039 
1040 /*
1041  * write_flash - wrapper for flash->write() with additional high-level policy
1042  *
1043  * @param flash flash chip
1044  * @param buf   buffer to write to flash
1045  * @param start start address in flash
1046  * @param len   number of bytes to write
1047  * @return      0 on success,
1048  *              -1 if any write fails.
1049  *
1050  * This wrapper simplifies most cases when the flash chip needs to be written
1051  * since policy decisions such as non-fatal error handling is centralized.
1052  */
write_flash(struct flashctx * flash,const uint8_t * buf,unsigned int start,unsigned int len)1053 int write_flash(struct flashctx *flash, const uint8_t *buf,
1054 		       unsigned int start, unsigned int len)
1055 {
1056 	if (!flash->flags.skip_unwritable_regions) {
1057 		if (check_for_unwritable_regions(flash, start, len))
1058 			return -1;
1059 	}
1060 
1061 	unsigned int write_len;
1062 	for (unsigned int addr = start; addr < start + len; addr += write_len) {
1063 		struct flash_region region;
1064 		get_flash_region(flash, addr, &region);
1065 
1066 		write_len = min(start + len, region.end) - addr;
1067 		const uint8_t *rbuf = buf + addr - start;
1068 
1069 		if (region.write_prot) {
1070 			msg_gdbg("%s: cannot write inside %s region (%#08"PRIx32"..%#08"PRIx32"), skipping (%#08x..%#08x).\n",
1071 				 __func__, region.name, region.start, region.end - 1, addr, addr + write_len - 1);
1072 			free(region.name);
1073 			continue;
1074 		}
1075 
1076 		msg_gdbg("%s: %s region (%#08"PRIx32"..%#08"PRIx32") is writable, writing range (%#08x..%#08x).\n",
1077 			 __func__, region.name, region.start, region.end - 1, addr, addr + write_len - 1);
1078 
1079 		write_func_t *write_func = lookup_write_func_ptr(flash->chip);
1080 		int ret = write_func(flash, rbuf, addr, write_len);
1081 		if (ret) {
1082 			msg_gerr("%s: failed to write (%#08x..%#08x).\n", __func__, addr, addr + write_len - 1);
1083 			free(region.name);
1084 			return -1;
1085 		}
1086 
1087 		free(region.name);
1088 	}
1089 
1090 	return 0;
1091 }
1092 
1093 typedef int (probe_func_t)(struct flashctx *flash);
1094 
lookup_probe_func_ptr(const struct flashchip * chip)1095 static probe_func_t *lookup_probe_func_ptr(const struct flashchip *chip)
1096 {
1097 	switch (chip->probe) {
1098 		case PROBE_JEDEC: return &probe_jedec;
1099 		case PROBE_JEDEC_29GL: return &probe_jedec_29gl;
1100 		case PROBE_OPAQUE: return &probe_opaque;
1101 		case PROBE_EDI_KB9012: return &edi_probe_kb9012;
1102 		case PROBE_AT82802AB: return &probe_82802ab;
1103 		case PROBE_W29EE011: return &probe_w29ee011;
1104 		case PROBE_EN29LV640B: return &probe_en29lv640b;
1105 		case PROBE_SPI_AT25F: return &probe_spi_at25f;
1106 		case PROBE_SPI_AT45DB: return &probe_spi_at45db;
1107 		case PROBE_SPI_BIG_SPANSION: return &probe_spi_big_spansion;
1108 		case PROBE_SPI_RDID: return &probe_spi_rdid;
1109 		case PROBE_SPI_RDID4: return &probe_spi_rdid4;
1110 		case PROBE_SPI_REMS: return &probe_spi_rems;
1111 		case PROBE_SPI_RES1: return &probe_spi_res1;
1112 		case PROBE_SPI_RES2: return &probe_spi_res2;
1113 		case PROBE_SPI_SFDP: return &probe_spi_sfdp;
1114 		case PROBE_SPI_ST95: return &probe_spi_st95;
1115 		/* default: total function, 0 indicates no probe function set.
1116 		 * We explicitly do not want a default catch-all case in the switch
1117 		 * to ensure unhandled enum's are compiler warnings.
1118 		 */
1119 		case NO_PROBE_FUNC: return NULL;
1120 	};
1121 
1122 	return NULL;
1123 }
1124 
probe_flash(struct registered_master * mst,int startchip,struct flashctx * flash,int force,const char * const chip_to_probe)1125 int probe_flash(struct registered_master *mst, int startchip, struct flashctx *flash, int force, const char *const chip_to_probe)
1126 {
1127 	const struct flashchip *chip;
1128 	enum chipbustype buses_common;
1129 	char *tmp;
1130 
1131 	for (chip = flashchips + startchip; chip && chip->name; chip++) {
1132 		if (is_chipname_duplicate(chip))
1133 			continue;
1134 
1135 		if (chip_to_probe && strcmp(chip->name, chip_to_probe) != 0)
1136 			continue;
1137 		buses_common = mst->buses_supported & chip->bustype;
1138 		if (!buses_common)
1139 			continue;
1140 		/* Only probe for SPI25 chips by default. */
1141 		if (chip->bustype == BUS_SPI && !chip_to_probe && chip->spi_cmd_set != SPI25)
1142 			continue;
1143 		msg_gdbg("Probing for %s %s, %d kB: ", chip->vendor, chip->name, chip->total_size);
1144 		probe_func_t *probe_func = lookup_probe_func_ptr(chip);
1145 		if (!probe_func && !force) {
1146 			msg_gdbg("failed! flashrom has no probe function for this flash chip.\n");
1147 			continue;
1148 		}
1149 
1150 		/* Start filling in the dynamic data. */
1151 		flash->chip = calloc(1, sizeof(*flash->chip));
1152 		if (!flash->chip) {
1153 			msg_gerr("Out of memory!\n");
1154 			return -1;
1155 		}
1156 		*flash->chip = *chip;
1157 		flash->mst = mst;
1158 
1159 		if (map_flash(flash) != 0)
1160 			goto notfound;
1161 
1162 		/* We handle a forced match like a real match, we just avoid probing. Note that probe_flash()
1163 		 * is only called with force=1 after normal probing failed.
1164 		 */
1165 		if (force)
1166 			break;
1167 
1168 		if (probe_func == &probe_w29ee011)
1169 			if (!w29ee011_can_override(flash->chip->name, chip_to_probe))
1170 				goto notfound;
1171 
1172 		if (probe_func(flash) != 1)
1173 			goto notfound;
1174 
1175 		/* If this is the first chip found, accept it.
1176 		 * If this is not the first chip found, accept it only if it is
1177 		 * a non-generic match. SFDP and CFI are generic matches.
1178 		 * startchip==0 means this call to probe_flash() is the first
1179 		 * one for this programmer interface (master) and thus no other chip has
1180 		 * been found on this interface.
1181 		 */
1182 		if (startchip == 0 && flash->chip->model_id == SFDP_DEVICE_ID) {
1183 			msg_cinfo("===\n"
1184 				  "SFDP has autodetected a flash chip which is "
1185 				  "not natively supported by flashrom yet.\n");
1186 			if (count_usable_erasers(flash) == 0)
1187 				msg_cinfo("The standard operations read and "
1188 					  "verify should work, but to support "
1189 					  "erase, write and all other "
1190 					  "possible features");
1191 			else
1192 				msg_cinfo("All standard operations (read, "
1193 					  "verify, erase and write) should "
1194 					  "work, but to support all possible "
1195 					  "features");
1196 
1197 			msg_cinfo(" we need to add them manually.\n"
1198 				  "You can help us by mailing us the output of the following command to "
1199 				  "[email protected]:\n"
1200 				  "'flashrom -VV [plus the -p/--programmer parameter]'\n"
1201 				  "Thanks for your help!\n"
1202 				  "===\n");
1203 		}
1204 
1205 		/* First flash chip detected on this bus. */
1206 		if (startchip == 0)
1207 			break;
1208 		/* Not the first flash chip detected on this bus, but not a generic match either. */
1209 		if ((flash->chip->model_id != GENERIC_DEVICE_ID) && (flash->chip->model_id != SFDP_DEVICE_ID))
1210 			break;
1211 		/* Not the first flash chip detected on this bus, and it's just a generic match. Ignore it. */
1212 notfound:
1213 		unmap_flash(flash);
1214 		free(flash->chip);
1215 		flash->chip = NULL;
1216 	}
1217 
1218 	if (!flash->chip)
1219 		return -1;
1220 
1221 	if (init_default_layout(flash) < 0)
1222 		return -1;
1223 
1224 	tmp = flashbuses_to_text(flash->chip->bustype);
1225 	msg_cinfo("%s %s flash chip \"%s\" (%d kB, %s) ", force ? "Assuming" : "Found",
1226 		  flash->chip->vendor, flash->chip->name, flash->chip->total_size, tmp ? tmp : "?");
1227 	free(tmp);
1228 	if (master_uses_physmap(mst))
1229 		msg_cinfo("mapped at physical address 0x%0*" PRIxPTR ".\n",
1230 			  PRIxPTR_WIDTH, flash->physical_memory);
1231 	else
1232 		msg_cinfo("on %s.\n", programmer->name);
1233 
1234 	/* Flash registers may more likely not be mapped if the chip was forced.
1235 	 * Lock info may be stored in registers, so avoid lock info printing. */
1236 	if (!force) {
1237 		printlockfunc_t *printlock = lookup_printlock_func_ptr(flash);
1238 		if (printlock)
1239 			printlock(flash);
1240 	}
1241 
1242 	/* Get out of the way for later runs. */
1243 	unmap_flash(flash);
1244 
1245 	/* Return position of matching chip. */
1246 	return chip - flashchips;
1247 }
1248 
1249 /*
1250  * Gets the lowest erase granularity; it is used when
1251  * deciding if the layout map needs to be adjusted such that erase boundaries
1252  * match this granularity. Returns -1 if unsuccessful.
1253  */
get_required_erase_size(struct flashctx * flash)1254 static int get_required_erase_size(struct flashctx *flash)
1255 {
1256 	int i, erase_size_found = 0;
1257 	unsigned int required_erase_size;
1258 
1259 	/*
1260 	 * Find eraseable block size for read alignment.
1261 	 * FIXME: This assumes the smallest block erase size is useable
1262 	 * by erase_and_write_flash().
1263 	 */
1264 	required_erase_size = ~0;
1265 	for (i = 0; i < NUM_ERASEFUNCTIONS; i++) {
1266 		struct block_eraser eraser = flash->chip->block_erasers[i];
1267 		int j;
1268 
1269 		for (j = 0; j < NUM_ERASEREGIONS; j++) {
1270 			unsigned int size = eraser.eraseblocks[j].size;
1271 
1272 			if (size && (size < required_erase_size)) {
1273 				required_erase_size = size;
1274 				erase_size_found = 1;
1275 			}
1276 		}
1277 	}
1278 
1279 	/* likely an error in flashchips[] */
1280 	if (!erase_size_found) {
1281 		msg_cerr("%s: No usable erase size found.\n", __func__);
1282 		return -1;
1283 	}
1284 
1285 	return required_erase_size;
1286 }
1287 
round_to_erasable_block_boundary(const int required_erase_size,const struct romentry * entry,chipoff_t * rounded_start,chipsize_t * rounded_len)1288 static int round_to_erasable_block_boundary(const int required_erase_size,
1289 					    const struct romentry *entry,
1290 					    chipoff_t *rounded_start,
1291 					    chipsize_t* rounded_len) {
1292 	unsigned int start_align, len_align;
1293 	const struct flash_region *region = &entry->region;
1294 
1295 	if (required_erase_size < 0)
1296 		return 1;
1297 
1298 	/* round down to nearest eraseable block boundary */
1299 	start_align = region->start % required_erase_size;
1300 	*rounded_start = region->start - start_align;
1301 
1302 	/* round up to nearest eraseable block boundary */
1303 	*rounded_len = region->end - *rounded_start + 1;
1304 	len_align = *rounded_len % required_erase_size;
1305 	if (len_align)
1306 		*rounded_len = *rounded_len + required_erase_size - len_align;
1307 
1308 	if (start_align || len_align) {
1309 		msg_gdbg("\n%s: Re-aligned partial read due to eraseable "
1310 			 "block size requirement:\n\tstart: 0x%06x, "
1311 			 "len: 0x%06x, aligned start: 0x%06x, len: 0x%06x\n",
1312 			 __func__, region->start, region->end - region->start + 1,
1313 			 *rounded_start, *rounded_len);
1314 	}
1315 
1316 	return 0;
1317 }
1318 
1319 /**
1320  * @brief Reads the included layout regions into a buffer.
1321  *
1322  * If there is no layout set in the given flash context, the whole chip will
1323  * be read.
1324  *
1325  * @param flashctx Flash context to be used.
1326  * @param buffer   Buffer of full chip size to read into.
1327  * @return 0 on success,
1328  *	   1 if any read fails.
1329  */
read_by_layout(struct flashctx * const flashctx,uint8_t * const buffer,bool align_to_erasable_block_boundary)1330 static int read_by_layout(struct flashctx *const flashctx, uint8_t *const buffer,
1331 			  bool align_to_erasable_block_boundary)
1332 {
1333 	const struct flashrom_layout *const layout = get_layout(flashctx);
1334 	const struct romentry *entry = NULL;
1335 	int required_erase_size = get_required_erase_size(flashctx);
1336 
1337 	while ((entry = layout_next_included(layout, entry))) {
1338 		const struct flash_region *region = &entry->region;
1339 		chipoff_t region_start	= region->start;
1340 		chipsize_t region_len	= region->end - region->start + 1;
1341 
1342 		if (align_to_erasable_block_boundary &&
1343 		    round_to_erasable_block_boundary(required_erase_size, entry,
1344 						     &region_start, &region_len))
1345 			return 1;
1346 		if (read_flash(flashctx, buffer + region_start, region_start, region_len))
1347 			return 1;
1348 	}
1349 	return 0;
1350 }
1351 
1352 /* Even if an error is found, the function will keep going and check the rest. */
selfcheck_eraseblocks(const struct flashchip * chip)1353 static int selfcheck_eraseblocks(const struct flashchip *chip)
1354 {
1355 	int i, j, k;
1356 	int ret = 0;
1357 	unsigned int prev_eraseblock_count = chip->total_size * 1024;
1358 
1359 	for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1360 		unsigned int done = 0;
1361 		struct block_eraser eraser = chip->block_erasers[k];
1362 		unsigned int curr_eraseblock_count = 0;
1363 
1364 		for (i = 0; i < NUM_ERASEREGIONS; i++) {
1365 			/* Blocks with zero size are bugs in flashchips.c. */
1366 			if (eraser.eraseblocks[i].count &&
1367 			    !eraser.eraseblocks[i].size) {
1368 				msg_gerr("ERROR: Flash chip %s erase function "
1369 					"%i region %i has size 0. Please report"
1370 					" a bug at [email protected]\n",
1371 					chip->name, k, i);
1372 				ret = 1;
1373 			}
1374 			/* Blocks with zero count are bugs in flashchips.c. */
1375 			if (!eraser.eraseblocks[i].count &&
1376 			    eraser.eraseblocks[i].size) {
1377 				msg_gerr("ERROR: Flash chip %s erase function "
1378 					"%i region %i has count 0. Please report"
1379 					" a bug at [email protected]\n",
1380 					chip->name, k, i);
1381 				ret = 1;
1382 			}
1383 			done += eraser.eraseblocks[i].count *
1384 				eraser.eraseblocks[i].size;
1385 			curr_eraseblock_count += eraser.eraseblocks[i].count;
1386 		}
1387 		/* Empty eraseblock definition with erase function.  */
1388 		if (!done && eraser.block_erase)
1389 			msg_gspew("Strange: Empty eraseblock definition with "
1390 				  "non-empty erase function. Not an error.\n");
1391 		if (!done)
1392 			continue;
1393 		if (done != chip->total_size * 1024) {
1394 			msg_gerr("ERROR: Flash chip %s erase function %i "
1395 				"region walking resulted in 0x%06x bytes total,"
1396 				" expected 0x%06x bytes. Please report a bug at"
1397 				" [email protected]\n", chip->name, k,
1398 				done, chip->total_size * 1024);
1399 			ret = 1;
1400 		}
1401 		if (!eraser.block_erase)
1402 			continue;
1403 		/* Check if there are identical erase functions for different
1404 		 * layouts. That would imply "magic" erase functions. The
1405 		 * easiest way to check this is with function pointers.
1406 		 */
1407 		for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1408 			if (eraser.block_erase ==
1409 			    chip->block_erasers[j].block_erase) {
1410 				msg_gerr("ERROR: Flash chip %s erase function "
1411 					"%i and %i are identical. Please report"
1412 					" a bug at [email protected]\n",
1413 					chip->name, k, j);
1414 				ret = 1;
1415 			}
1416 		}
1417 		if (curr_eraseblock_count > prev_eraseblock_count) {
1418 			msg_gerr("ERROR: Flash chip %s erase function %i is not "
1419 					"in order. Please report a bug at [email protected]\n",
1420 					chip->name, k);
1421 			ret = 1;
1422 		}
1423 		prev_eraseblock_count = curr_eraseblock_count;
1424 	}
1425 	return ret;
1426 }
1427 
1428 typedef int (*erasefn_t)(struct flashctx *, unsigned int addr, unsigned int len);
1429 /**
1430  * @private
1431  *
1432  * For read-erase-write, `curcontents` and `newcontents` shall point
1433  * to buffers of the chip's size. Both are supposed to be prefilled
1434  * with at least the included layout regions of the current flash
1435  * contents (`curcontents`) and the data to be written to the flash
1436  * (`newcontents`).
1437  *
1438  * For erase, `curcontents` and `newcontents` shall be NULL-pointers.
1439  *
1440  * The `chipoff_t` values are used internally by `walk_by_layout()`.
1441  */
1442 struct walk_info {
1443 	uint8_t *curcontents;
1444 	const uint8_t *newcontents;
1445 	chipoff_t region_start;
1446 	chipoff_t region_end;
1447 	chipoff_t erase_start;
1448 	chipoff_t erase_end;
1449 };
1450 /* returns 0 on success, 1 to retry with another erase function, 2 for immediate abort */
1451 typedef int (*per_blockfn_t)(struct flashctx *, const struct walk_info *, erasefn_t, bool *);
1452 
walk_eraseblocks(struct flashctx * const flashctx,struct walk_info * const info,const size_t erasefunction,const per_blockfn_t per_blockfn,bool * all_skipped)1453 static int walk_eraseblocks(struct flashctx *const flashctx,
1454 			    struct walk_info *const info,
1455 			    const size_t erasefunction, const per_blockfn_t per_blockfn,
1456 			    bool *all_skipped)
1457 {
1458 	int ret;
1459 	size_t i, j;
1460 	bool first = true;
1461 	struct block_eraser *const eraser = &flashctx->chip->block_erasers[erasefunction];
1462 
1463 	info->erase_start = 0;
1464 	for (i = 0; i < NUM_ERASEREGIONS; ++i) {
1465 		/* count==0 for all automatically initialized array
1466 		   members so the loop below won't be executed for them. */
1467 		for (j = 0; j < eraser->eraseblocks[i].count; ++j, info->erase_start = info->erase_end + 1) {
1468 			info->erase_end = info->erase_start + eraser->eraseblocks[i].size - 1;
1469 
1470 			/* Skip any eraseblock that is completely outside the current region. */
1471 			if (info->erase_end < info->region_start)
1472 				continue;
1473 			if (info->region_end < info->erase_start)
1474 				break;
1475 
1476 			/* Print this for every block except the first one. */
1477 			if (first)
1478 				first = false;
1479 			else
1480 				msg_cdbg(", ");
1481 			msg_cdbg("0x%06"PRIx32"-0x%06"PRIx32":", info->erase_start, info->erase_end);
1482 
1483 			erasefunc_t *erase_func = lookup_erase_func_ptr(eraser);
1484 			ret = per_blockfn(flashctx, info, erase_func, all_skipped);
1485 			if (ret)
1486 				return ret;
1487 		}
1488 		if (info->region_end < info->erase_start)
1489 			break;
1490 	}
1491 	msg_cdbg("\n");
1492 	return 0;
1493 }
1494 
walk_by_layout(struct flashctx * const flashctx,struct walk_info * const info,const per_blockfn_t per_blockfn,bool * all_skipped)1495 static int walk_by_layout(struct flashctx *const flashctx, struct walk_info *const info,
1496 			  const per_blockfn_t per_blockfn, bool *all_skipped)
1497 {
1498 	const struct flashrom_layout *const layout = get_layout(flashctx);
1499 	const struct romentry *entry = NULL;
1500 
1501 	*all_skipped = true;
1502 	msg_cinfo("Erasing and writing flash chip... ");
1503 
1504 	while ((entry = layout_next_included(layout, entry))) {
1505 		const struct flash_region *region = &entry->region;
1506 		info->region_start = region->start;
1507 		info->region_end   = region->end;
1508 
1509 		size_t j;
1510 		int error = 1; /* retry as long as it's 1 */
1511 		for (j = 0; j < NUM_ERASEFUNCTIONS; ++j) {
1512 			if (j != 0)
1513 				msg_cinfo("Looking for another erase function.\n");
1514 			msg_cdbg("Trying erase function %zi... ", j);
1515 			if (check_block_eraser(flashctx, j, 1))
1516 				continue;
1517 
1518 			error = walk_eraseblocks(flashctx, info, j, per_blockfn, all_skipped);
1519 			if (error != 1)
1520 				break;
1521 
1522 			if (info->curcontents) {
1523 				msg_cinfo("Reading current flash chip contents... ");
1524 				if (read_by_layout(flashctx, info->curcontents, false)) {
1525 					/* Now we are truly screwed. Read failed as well. */
1526 					msg_cerr("Can't read anymore! Aborting.\n");
1527 					/* We have no idea about the flash chip contents, so
1528 					   retrying with another erase function is pointless. */
1529 					error = 2;
1530 					break;
1531 				}
1532 				msg_cinfo("done. ");
1533 			}
1534 		}
1535 		if (error == 1)
1536 			msg_cinfo("No usable erase functions left.\n");
1537 		if (error) {
1538 			msg_cerr("FAILED!\n");
1539 			return 1;
1540 		}
1541 	}
1542 	if (*all_skipped)
1543 		msg_cinfo("\nWarning: Chip content is identical to the requested image.\n");
1544 	msg_cinfo("Erase/write done.\n");
1545 	return 0;
1546 }
1547 
erase_block(struct flashctx * const flashctx,const struct walk_info * const info,const erasefn_t erasefn,bool * all_skipped)1548 static int erase_block(struct flashctx *const flashctx,
1549 		       const struct walk_info *const info, const erasefn_t erasefn,
1550 		       bool *all_skipped)
1551 {
1552 	const unsigned int erase_len = info->erase_end + 1 - info->erase_start;
1553 	const bool region_unaligned = info->region_start > info->erase_start ||
1554 				      info->erase_end > info->region_end;
1555 	uint8_t *backup_contents = NULL, *erased_contents = NULL;
1556 	int ret = 2;
1557 
1558 	/*
1559 	 * If the region is not erase-block aligned, merge current flash con-
1560 	 * tents into a new buffer `backup_contents`.
1561 	 */
1562 	if (region_unaligned) {
1563 		backup_contents = malloc(erase_len);
1564 		erased_contents = malloc(erase_len);
1565 		if (!backup_contents || !erased_contents) {
1566 			msg_cerr("Out of memory!\n");
1567 			ret = 1;
1568 			goto _free_ret;
1569 		}
1570 		memset(backup_contents, ERASED_VALUE(flashctx), erase_len);
1571 		memset(erased_contents, ERASED_VALUE(flashctx), erase_len);
1572 
1573 		msg_cdbg("R");
1574 		/* Merge data preceding the current region. */
1575 		if (info->region_start > info->erase_start) {
1576 			const chipoff_t start	= info->erase_start;
1577 			const chipsize_t len	= info->region_start - info->erase_start;
1578 			if (read_flash(flashctx, backup_contents, start, len)) {
1579 				msg_cerr("Can't read! Aborting.\n");
1580 				goto _free_ret;
1581 			}
1582 		}
1583 		/* Merge data following the current region. */
1584 		if (info->erase_end > info->region_end) {
1585 			const chipoff_t start     = info->region_end + 1;
1586 			const chipoff_t rel_start = start - info->erase_start; /* within this erase block */
1587 			const chipsize_t len      = info->erase_end - info->region_end;
1588 			if (read_flash(flashctx, backup_contents + rel_start, start, len)) {
1589 				msg_cerr("Can't read! Aborting.\n");
1590 				goto _free_ret;
1591 			}
1592 		}
1593 	}
1594 
1595 	ret = 1;
1596 	*all_skipped = false;
1597 
1598 	msg_cdbg("E");
1599 
1600 	if (!flashctx->flags.skip_unwritable_regions) {
1601 		if (check_for_unwritable_regions(flashctx, info->erase_start, erase_len))
1602 			goto _free_ret;
1603 	}
1604 
1605 	unsigned int len;
1606 	for (unsigned int addr = info->erase_start; addr < info->erase_start + erase_len; addr += len) {
1607 		struct flash_region region;
1608 		get_flash_region(flashctx, addr, &region);
1609 
1610 		len = min(info->erase_start + erase_len, region.end) - addr;
1611 
1612 		if (region.write_prot) {
1613 			msg_gdbg("%s: cannot erase inside %s region (%#08"PRIx32"..%#08"PRIx32"), skipping range (%#08x..%#08x).\n",
1614 				 __func__, region.name, region.start, region.end - 1, addr, addr + len - 1);
1615 			free(region.name);
1616 			continue;
1617 		}
1618 
1619 		msg_gdbg("%s: %s region (%#08"PRIx32"..%#08"PRIx32") is writable, erasing range (%#08x..%#08x).\n",
1620 			 __func__, region.name, region.start, region.end - 1, addr, addr + len - 1);
1621 		free(region.name);
1622 
1623 		if (erasefn(flashctx, addr, len))
1624 			goto _free_ret;
1625 		if (check_erased_range(flashctx, addr, len)) {
1626 			msg_cerr("ERASE FAILED!\n");
1627 			goto _free_ret;
1628 		}
1629 	}
1630 
1631 
1632 	if (region_unaligned) {
1633 		unsigned int starthere = 0, lenhere = 0, writecount = 0;
1634 		/* get_next_write() sets starthere to a new value after the call. */
1635 		while ((lenhere = get_next_write(erased_contents + starthere, backup_contents + starthere,
1636 						 erase_len - starthere, &starthere, flashctx->chip->gran))) {
1637 			if (!writecount++)
1638 				msg_cdbg("W");
1639 			/* Needs the partial write function signature. */
1640 			if (write_flash(flashctx, backup_contents + starthere,
1641 						  info->erase_start + starthere, lenhere))
1642 				goto _free_ret;
1643 			starthere += lenhere;
1644 		}
1645 	}
1646 
1647 	ret = 0;
1648 
1649 _free_ret:
1650 	free(erased_contents);
1651 	free(backup_contents);
1652 	return ret;
1653 }
1654 
1655 /**
1656  * @brief Erases the included layout regions.
1657  *
1658  * If there is no layout set in the given flash context, the whole chip will
1659  * be erased.
1660  *
1661  * @param flashctx Flash context to be used.
1662  * @return 0 on success,
1663  *	   1 if all available erase functions failed.
1664  */
erase_by_layout_legacy(struct flashctx * const flashctx)1665 static int erase_by_layout_legacy(struct flashctx *const flashctx)
1666 {
1667 	struct walk_info info = { 0 };
1668 	bool all_skipped = true;
1669 	return walk_by_layout(flashctx, &info, &erase_block, &all_skipped);
1670 }
1671 
erase_by_layout_new(struct flashctx * const flashctx)1672 static int erase_by_layout_new(struct flashctx *const flashctx)
1673 {
1674 	bool all_skipped = true;
1675 	const uint32_t flash_size = flashctx->chip->total_size * 1024;
1676 	uint8_t* curcontents = malloc(flash_size);
1677 	uint8_t* newcontents = malloc(flash_size);
1678 	struct erase_layout *erase_layout;
1679 	create_erase_layout(flashctx, &erase_layout);
1680 	int ret = 0;
1681 
1682 	//erase layout creation failed
1683 	if (!erase_layout) {
1684 		ret = 1;
1685 		goto _ret;
1686 	}
1687 
1688 	//not enough memory
1689 	if (!curcontents || !newcontents) {
1690 		ret = 1;
1691 		goto _ret;
1692 	}
1693 
1694 	memset(curcontents, ~ERASED_VALUE(flashctx), flash_size);
1695 	memset(newcontents, ERASED_VALUE(flashctx), flash_size);
1696 
1697 	const struct flashrom_layout *const flash_layout = get_layout(flashctx);
1698 	const struct romentry *entry = NULL;
1699 	while ((entry = layout_next_included(flash_layout, entry))) {
1700 		ret = erase_write(flashctx, entry->region.start, entry->region.end, curcontents, newcontents, erase_layout, &all_skipped);
1701 		if (ret) {
1702 			ret = 1;
1703 			msg_cerr("Erase Failed");
1704 			goto _ret;
1705 		}
1706 	}
1707 
1708 _ret:
1709 	free(curcontents);
1710 	free(newcontents);
1711 	free_erase_layout(erase_layout, count_usable_erasers(flashctx));
1712 	return ret;
1713 }
1714 
erase_by_layout(struct flashctx * const flashctx)1715 static int erase_by_layout(struct flashctx *const flashctx)
1716 {
1717 	if (use_legacy_erase_path)
1718 		return erase_by_layout_legacy(flashctx);
1719 	return erase_by_layout_new(flashctx);
1720 }
1721 
read_erase_write_block(struct flashctx * const flashctx,const struct walk_info * const info,const erasefn_t erasefn,bool * all_skipped)1722 static int read_erase_write_block(struct flashctx *const flashctx,
1723 				  const struct walk_info *const info, const erasefn_t erasefn,
1724 				  bool *all_skipped)
1725 {
1726 	const chipsize_t erase_len = info->erase_end + 1 - info->erase_start;
1727 	const bool region_unaligned = info->region_start > info->erase_start ||
1728 				      info->erase_end > info->region_end;
1729 	const uint8_t *newcontents = NULL;
1730 	int ret = 2;
1731 
1732 	/*
1733 	 * If the region is not erase-block aligned, merge current flash con-
1734 	 * tents into `info->curcontents` and a new buffer `newc`. The former
1735 	 * is necessary since we have no guarantee that the full erase block
1736 	 * was already read into `info->curcontents`. For the latter a new
1737 	 * buffer is used since `info->newcontents` might contain data for
1738 	 * other unaligned regions that touch this erase block too.
1739 	 */
1740 	if (region_unaligned) {
1741 		msg_cdbg("R");
1742 		uint8_t *const newc = malloc(erase_len);
1743 		if (!newc) {
1744 			msg_cerr("Out of memory!\n");
1745 			return 1;
1746 		}
1747 		memcpy(newc, info->newcontents + info->erase_start, erase_len);
1748 
1749 		/* Merge data preceding the current region. */
1750 		if (info->region_start > info->erase_start) {
1751 			const chipoff_t start	= info->erase_start;
1752 			const chipsize_t len	= info->region_start - info->erase_start;
1753 			if (read_flash(flashctx, newc, start, len)) {
1754 				msg_cerr("Can't read! Aborting.\n");
1755 				goto _free_ret;
1756 			}
1757 			memcpy(info->curcontents + start, newc, len);
1758 		}
1759 		/* Merge data following the current region. */
1760 		if (info->erase_end > info->region_end) {
1761 			const chipoff_t start     = info->region_end + 1;
1762 			const chipoff_t rel_start = start - info->erase_start; /* within this erase block */
1763 			const chipsize_t len      = info->erase_end - info->region_end;
1764 			if (read_flash(flashctx, newc + rel_start, start, len)) {
1765 				msg_cerr("Can't read! Aborting.\n");
1766 				goto _free_ret;
1767 			}
1768 			memcpy(info->curcontents + start, newc + rel_start, len);
1769 		}
1770 
1771 		newcontents = newc;
1772 	} else {
1773 		newcontents = info->newcontents + info->erase_start;
1774 	}
1775 
1776 	ret = 1;
1777 	bool skipped = true;
1778 	uint8_t *const curcontents = info->curcontents + info->erase_start;
1779 	const uint8_t erased_value = ERASED_VALUE(flashctx);
1780 	if (!(flashctx->chip->feature_bits & FEATURE_NO_ERASE) &&
1781 			need_erase(curcontents, newcontents, erase_len, flashctx->chip->gran, erased_value)) {
1782 		if (erase_block(flashctx, info, erasefn, all_skipped))
1783 			goto _free_ret;
1784 		/* Erase was successful. Adjust curcontents. */
1785 		memset(curcontents, erased_value, erase_len);
1786 		skipped = false;
1787 	}
1788 
1789 	unsigned int starthere = 0, lenhere = 0, writecount = 0;
1790 	/* get_next_write() sets starthere to a new value after the call. */
1791 	while ((lenhere = get_next_write(curcontents + starthere, newcontents + starthere,
1792 					 erase_len - starthere, &starthere, flashctx->chip->gran))) {
1793 		if (!writecount++)
1794 			msg_cdbg("W");
1795 		/* Needs the partial write function signature. */
1796 		if (write_flash(flashctx, newcontents + starthere,
1797 					  info->erase_start + starthere, lenhere))
1798 			goto _free_ret;
1799 		starthere += lenhere;
1800 		skipped = false;
1801 	}
1802 	if (skipped)
1803 		msg_cdbg("S");
1804 	else
1805 		*all_skipped = false;
1806 
1807 	/* Update curcontents, other regions with overlapping erase blocks
1808 	   might rely on this. */
1809 	memcpy(curcontents, newcontents, erase_len);
1810 	ret = 0;
1811 
1812 _free_ret:
1813 	if (region_unaligned)
1814 		free((void *)newcontents);
1815 	return ret;
1816 }
1817 
1818 /**
1819  * @brief Writes the included layout regions from a given image.
1820  *
1821  * If there is no layout set in the given flash context, the whole image
1822  * will be written.
1823  *
1824  * @param flashctx    Flash context to be used.
1825  * @param curcontents A buffer of full chip size with current chip contents of included regions.
1826  * @param newcontents The new image to be written.
1827  * @return 0 on success,
1828  *	   1 if anything has gone wrong.
1829  */
write_by_layout_legacy(struct flashctx * const flashctx,void * const curcontents,const void * const newcontents,bool * all_skipped)1830 static int write_by_layout_legacy(struct flashctx *const flashctx,
1831 			   void *const curcontents, const void *const newcontents,
1832 			   bool *all_skipped)
1833 {
1834 	struct walk_info info;
1835 	info.curcontents = curcontents;
1836 	info.newcontents = newcontents;
1837 	return walk_by_layout(flashctx, &info, read_erase_write_block, all_skipped);
1838 }
1839 
1840 /*
1841  * Function to process processing units accumulated in the action descriptor.
1842  *
1843  * @flash         pointer to the flash context to operate on
1844  * @per_blockfn   helper function which can erase and program a section of the
1845  *                flash chip. It receives the flash context, offset and length
1846  *                of the area to erase/program, before and after contents (to
1847  *                decide what exactly needs to be erased and or programmed)
1848  *                and a pointer to the erase function which can operate on the
1849  *                proper granularity.
1850  * @descriptor    action descriptor including pointers to before and after
1851  *		  contents and an array of processing actions to take.
1852  *
1853  * Returns zero on success or an error code.
1854  */
walk_eraseregions(struct flashctx * flash,const per_blockfn_t per_blockfn,struct action_descriptor * descriptor,bool * all_skipped)1855 static int walk_eraseregions(struct flashctx *flash,
1856 			     const per_blockfn_t per_blockfn,
1857 			     struct action_descriptor *descriptor, bool *all_skipped)
1858 {
1859 	struct processing_unit *pu;
1860 	int rc = 0;
1861 	static int print_comma;
1862 
1863 	for (pu = descriptor->processing_units; pu->num_blocks; pu++) {
1864 		unsigned base = pu->offset;
1865 		unsigned top = pu->offset + pu->block_size * pu->num_blocks;
1866 		struct block_eraser *const eraser = &flash->chip->block_erasers[pu->block_eraser_index];
1867 
1868 		while (base < top) {
1869 
1870 			if (print_comma)
1871 				msg_cdbg(", ");
1872 			else
1873 				print_comma = 1;
1874 
1875 			msg_cdbg("0x%06x-0x%06zx", base, base + pu->block_size - 1);
1876 
1877 			struct walk_info info = {
1878 				.curcontents = descriptor->oldcontents + base,
1879 				.newcontents = descriptor->newcontents + base,
1880 				.erase_start = base,
1881 				.erase_end   = base + pu->block_size - 1,
1882 			};
1883 			erasefunc_t *erase_func = lookup_erase_func_ptr(eraser);
1884 			rc = per_blockfn(flash, &info, erase_func, all_skipped);
1885 			if (rc)
1886 				return rc;
1887 
1888 			base += pu->block_size;
1889 		}
1890 	}
1891 	msg_cdbg("\n");
1892 	return rc;
1893 }
1894 
1895 /*
1896  * Helper function called on each block to be erased and written.
1897  *
1898  * Returns 0 if erase and write operations succeed or if they are skipped
1899  *         because the block is in a non-writable region.
1900  * Returns non-0 error code if erase or write operations fail unexpectedly.
1901  */
erase_and_write_block_helper(struct flashctx * const flash,const struct walk_info * const info,const erasefn_t erasefn,bool * all_skipped)1902 static int erase_and_write_block_helper(struct flashctx *const flash,
1903 					const struct walk_info *const info,
1904 					const erasefn_t erasefn, bool *all_skipped)
1905 {
1906 	const unsigned int erase_len = info->erase_end + 1 - info->erase_start;
1907 	unsigned int starthere = 0, lenhere = 0;
1908 	int ret = 0, writecount = 0;
1909 	enum write_granularity gran = flash->chip->gran;
1910 	bool skipped = true;
1911 	msg_cdbg(":");
1912 	if (need_erase(info->curcontents, info->newcontents, erase_len, gran, 0xff)) {
1913 		*all_skipped = false;
1914 		msg_cdbg(" E");
1915 
1916 		if (!flash->flags.skip_unwritable_regions) {
1917 			if (check_for_unwritable_regions(flash, info->erase_start, erase_len))
1918 				return -1;
1919 		}
1920 
1921 		unsigned int len;
1922 		for (unsigned int addr = info->erase_start; addr < info->erase_start + erase_len; addr += len) {
1923 			struct flash_region region;
1924 			get_flash_region(flash, addr, &region);
1925 
1926 			len = min(info->erase_start + erase_len, region.end) - addr;
1927 
1928 			if (region.write_prot) {
1929 				msg_gdbg("%s: cannot erase inside %s region (%#08x..%#08x), skipping range (%#08x..%#08x).\n",
1930 					 __func__, region.name, region.start, region.end - 1, addr, addr + len - 1);
1931 				free(region.name);
1932 				continue;
1933 			}
1934 
1935 			msg_gdbg("%s: %s region (%#08x..%#08x) is writable, erasing range (%#08x..%#08x).\n",
1936 				 __func__, region.name, region.start, region.end - 1, addr, addr + len - 1);
1937 			free(region.name);
1938 
1939 			ret = erasefn(flash, addr, len);
1940 			if (ret) {
1941 				msg_cerr(" ERASE_FAILED\n");
1942 				return ret;
1943 			}
1944 			if (!ret && cros_ec_erasure_failed()) { /* from cros_ec erase path. */
1945 				msg_cdbg(" DENIED");
1946 				return ret;
1947 			}
1948 			if (flash->flags.verify_after_write) { /* FIXME(b/263909055): replace with upstream. */
1949 				if (check_erased_range(flash, info->erase_start, erase_len)) {
1950 					msg_cerr(" ERASE_FAILED\n");
1951 					return -1;
1952 				}
1953 			}
1954 		}
1955 
1956 		/* Erase was successful. Adjust curcontents. */
1957 		memset(info->curcontents, ERASED_VALUE(flash), erase_len);
1958 		skipped = false;
1959 	}
1960 	/* get_next_write() sets starthere to a new value after the call. */
1961 	while ((lenhere = get_next_write(info->curcontents + starthere,
1962 					 info->newcontents + starthere,
1963 					 erase_len - starthere, &starthere, gran))) {
1964 		*all_skipped = false;
1965 		if (!writecount++)
1966 			msg_cdbg(" W");
1967 
1968 		/* Needs the partial write function signature. */
1969 		ret = write_flash(flash, (uint8_t *)info->newcontents + starthere,
1970 				   info->erase_start + starthere, lenhere);
1971 		if (ret) {
1972 			return ret;
1973 		}
1974 
1975 		starthere += lenhere;
1976 		skipped = false;
1977 	}
1978 	if (skipped)
1979 		msg_cdbg("S");
1980 	return ret;
1981 }
1982 
erase_and_write_flash(struct flashctx * flash,void * const curcontents,void * const newcontents,bool * all_skipped)1983 static int erase_and_write_flash(struct flashctx *flash,
1984 				 void *const curcontents, void *const newcontents, bool *all_skipped)
1985 {
1986 	int ret = 1;
1987 	struct action_descriptor *descriptor =
1988 		prepare_action_descriptor(flash, curcontents, newcontents);
1989 
1990 	msg_cinfo("Erasing and writing flash chip... ");
1991 
1992 	ret = walk_eraseregions(flash, &erase_and_write_block_helper, descriptor, all_skipped);
1993 
1994 	if (ret) {
1995 		msg_cerr("FAILED!\n");
1996 	} else {
1997 		msg_cinfo("SUCCESS.\n");
1998 	}
1999 
2000 	free(descriptor);
2001 	return ret;
2002 }
2003 
write_by_layout_new(struct flashctx * const flashctx,void * const curcontents,const void * const newcontents,bool * all_skipped)2004 static int write_by_layout_new(struct flashctx *const flashctx,
2005 			   void *const curcontents, const void *const newcontents,
2006 			   bool *all_skipped)
2007 {
2008 	const int erasefn_count = count_usable_erasers(flashctx);
2009 	int ret = 1;
2010 
2011 	const struct flashrom_layout *const flash_layout = get_layout(flashctx);
2012 	struct erase_layout *erase_layout;
2013 	create_erase_layout(flashctx, &erase_layout);
2014 
2015 	if (!flash_layout) {
2016 		goto _ret;
2017 	}
2018 	if (!erase_layout) {
2019 		goto _ret;
2020 	}
2021 
2022 	const struct romentry *entry = NULL;
2023 	while ((entry = layout_next_included(flash_layout, entry))) {
2024 		ret = erase_write(flashctx, entry->region.start,
2025 						entry->region.end,
2026 						curcontents,
2027 						(uint8_t *)newcontents,
2028 						erase_layout, all_skipped);
2029 		if (ret) {
2030 			msg_cerr("Write Failed!");
2031 			goto _ret;
2032 		}
2033 	}
2034 _ret:
2035 	free_erase_layout(erase_layout, erasefn_count);
2036 	return ret;
2037 }
2038 
write_by_layout(struct flashctx * const flashctx,uint8_t * const curcontents,const uint8_t * const newcontents,bool * all_skipped)2039 static int write_by_layout(struct flashctx *const flashctx,
2040 			   uint8_t *const curcontents, const uint8_t *const newcontents,
2041 			   bool *all_skipped)
2042 {
2043 	if (use_legacy_erase_path)
2044 		return write_by_layout_legacy(flashctx, curcontents, newcontents, all_skipped);
2045 	return write_by_layout_new(flashctx, curcontents, newcontents, all_skipped);
2046 }
2047 
2048 /**
2049  * @brief Compares the included layout regions with content from a buffer.
2050  *
2051  * If there is no layout set in the given flash context, the whole chip's
2052  * contents will be compared.
2053  *
2054  * @param flashctx    Flash context to be used.
2055  * @param layout      Flash layout information.
2056  * @param curcontents A buffer of full chip size to read current chip contents into.
2057  * @param newcontents The new image to compare to.
2058  * @return 0 on success,
2059  *	   1 if reading failed,
2060  *	   3 if the contents don't match.
2061  */
verify_by_layout(struct flashctx * const flashctx,const struct flashrom_layout * const layout,void * const curcontents,const uint8_t * const newcontents)2062 static int verify_by_layout(
2063 		struct flashctx *const flashctx,
2064 		const struct flashrom_layout *const layout,
2065 		void *const curcontents, const uint8_t *const newcontents)
2066 {
2067 	const struct romentry *entry = NULL;
2068 	int ret = 0;
2069 
2070 	while ((entry = layout_next_included(layout, entry))) {
2071 		const struct flash_region *region = &entry->region;
2072 		const chipoff_t region_start	= region->start;
2073 		const chipsize_t region_len	= region->end - region->start + 1;
2074 
2075 		if ((ret = verify_range(flashctx, newcontents + region_start,
2076 					region_start, region_len)))
2077 			break;
2078 	}
2079 
2080 	if (ret)
2081 		msg_gerr("Could not fully verify due to error, aborting\n");
2082 	return ret;
2083 }
2084 
is_internal_programmer()2085 static bool is_internal_programmer()
2086 {
2087 #if CONFIG_INTERNAL == 1
2088 	return programmer == &programmer_internal;
2089 #else
2090 	return false;
2091 #endif
2092 }
2093 
nonfatal_help_message(void)2094 static void nonfatal_help_message(void)
2095 {
2096 	msg_gerr("Good, writing to the flash chip apparently didn't do anything.\n");
2097 	if (is_internal_programmer())
2098 		msg_gerr("This means we have to add special support for your board, programmer or flash\n"
2099 			 "chip. Please report this to the mailing list at [email protected] or on\n"
2100 			 "IRC (see https://www.flashrom.org/Contact for details), thanks!\n"
2101 			 "-------------------------------------------------------------------------------\n"
2102 			 "You may now reboot or simply leave the machine running.\n");
2103 	else
2104 		msg_gerr("Please check the connections (especially those to write protection pins) between\n"
2105 			 "the programmer and the flash chip. If you think the error is caused by flashrom\n"
2106 			 "please report this to the mailing list at [email protected] or on IRC (see\n"
2107 			 "https://www.flashrom.org/Contact for details), thanks!\n");
2108 }
2109 
emergency_help_message(void)2110 void emergency_help_message(void)
2111 {
2112 	msg_gerr("Your flash chip is in an unknown state.\n");
2113 	if (is_internal_programmer())
2114 		msg_gerr("Get help on IRC (see https://www.flashrom.org/Contact) or mail\n"
2115 			"[email protected] with the subject \"FAILED: <your board name>\"!"
2116 			"-------------------------------------------------------------------------------\n"
2117 			"DO NOT REBOOT OR POWEROFF!\n");
2118 	else
2119 		msg_gerr("Please report this to the mailing list at [email protected] or\n"
2120 			 "on IRC (see https://www.flashrom.org/Contact for details), thanks!\n");
2121 }
2122 
list_programmers_linebreak(int startcol,int cols,int paren)2123 void list_programmers_linebreak(int startcol, int cols, int paren)
2124 {
2125 	const char *pname;
2126 	int pnamelen;
2127 	int remaining = 0, firstline = 1;
2128 	size_t p;
2129 	int i;
2130 
2131 	for (p = 0; p < programmer_table_size; p++) {
2132 		pname = programmer_table[p]->name;
2133 		pnamelen = strlen(pname);
2134 		if (remaining - pnamelen - 2 < 0) {
2135 			if (firstline)
2136 				firstline = 0;
2137 			else
2138 				msg_ginfo("\n");
2139 			for (i = 0; i < startcol; i++)
2140 				msg_ginfo(" ");
2141 			remaining = cols - startcol;
2142 		} else {
2143 			msg_ginfo(" ");
2144 			remaining--;
2145 		}
2146 		if (paren && (p == 0)) {
2147 			msg_ginfo("(");
2148 			remaining--;
2149 		}
2150 		msg_ginfo("%s", pname);
2151 		remaining -= pnamelen;
2152 		if (p < programmer_table_size - 1) {
2153 			msg_ginfo(",");
2154 			remaining--;
2155 		} else {
2156 			if (paren)
2157 				msg_ginfo(")");
2158 		}
2159 	}
2160 }
2161 
selfcheck(void)2162 int selfcheck(void)
2163 {
2164 	unsigned int i;
2165 	int ret = 0;
2166 
2167 	for (i = 0; i < programmer_table_size; i++) {
2168 		const struct programmer_entry *const p = programmer_table[i];
2169 		if (p == NULL) {
2170 			msg_gerr("Programmer with index %d is NULL instead of a valid pointer!\n", i);
2171 			ret = 1;
2172 			continue;
2173 		}
2174 		if (p->name == NULL) {
2175 			msg_gerr("All programmers need a valid name, but the one with index %d does not!\n", i);
2176 			ret = 1;
2177 			/* This might hide other problems with this programmer, but allows for better error
2178 			 * messages below without jumping through hoops. */
2179 			continue;
2180 		}
2181 		switch (p->type) {
2182 		case USB:
2183 		case PCI:
2184 		case OTHER:
2185 			if (p->devs.note == NULL) {
2186 				if (strcmp("internal", p->name) == 0)
2187 					break; /* This one has its device list stored separately. */
2188 				msg_gerr("Programmer %s has neither a device list nor a textual description!\n",
2189 					 p->name);
2190 				ret = 1;
2191 			}
2192 			break;
2193 		default:
2194 			msg_gerr("Programmer %s does not have a valid type set!\n", p->name);
2195 			ret = 1;
2196 			break;
2197 		}
2198 		if (p->init == NULL) {
2199 			msg_gerr("Programmer %s does not have a valid init function!\n", p->name);
2200 			ret = 1;
2201 		}
2202 	}
2203 
2204 	/* It would be favorable if we could check for the correct layout (especially termination) of various
2205 	 * constant arrays: flashchips, chipset_enables, board_matches, boards_known, laptops_known.
2206 	 * They are all defined as externs in this compilation unit so we don't know their sizes which vary
2207 	 * depending on compiler flags, e.g. the target architecture, and can sometimes be 0.
2208 	 * For 'flashchips' we export the size explicitly to work around this and to be able to implement the
2209 	 * checks below. */
2210 	if (flashchips_size <= 1 || flashchips[flashchips_size - 1].name != NULL) {
2211 		msg_gerr("Flashchips table miscompilation!\n");
2212 		ret = 1;
2213 	} else {
2214 		for (i = 0; i < flashchips_size - 1; i++) {
2215 			const struct flashchip *chip = &flashchips[i];
2216 			if (chip->vendor == NULL || chip->name == NULL || chip->bustype == BUS_NONE) {
2217 				ret = 1;
2218 				msg_gerr("ERROR: Some field of flash chip #%d (%s) is misconfigured.\n"
2219 					 "Please report a bug at [email protected]\n", i,
2220 					 chip->name == NULL ? "unnamed" : chip->name);
2221 			}
2222 			if (selfcheck_eraseblocks(chip)) {
2223 				ret = 1;
2224 			}
2225 		}
2226 	}
2227 
2228 #if CONFIG_INTERNAL == 1
2229 	ret |= selfcheck_board_enables();
2230 #endif
2231 
2232 	/* TODO: implement similar sanity checks for other arrays where deemed necessary. */
2233 	return ret;
2234 }
2235 
2236 /* FIXME: This function signature needs to be improved once prepare_flash_access()
2237  * has a better function signature.
2238  */
chip_safety_check(const struct flashctx * flash,int force,int read_it,int write_it,int erase_it,int verify_it)2239 static int chip_safety_check(const struct flashctx *flash, int force,
2240 			     int read_it, int write_it, int erase_it, int verify_it)
2241 {
2242 	const struct flashchip *chip = flash->chip;
2243 
2244 	if (!programmer_may_write && (write_it || erase_it)) {
2245 		msg_perr("Write/erase is not working yet on your programmer in "
2246 			 "its current configuration.\n");
2247 		/* --force is the wrong approach, but it's the best we can do
2248 		 * until the generic programmer parameter parser is merged.
2249 		 */
2250 		if (!force)
2251 			return 1;
2252 		msg_cerr("Continuing anyway.\n");
2253 	}
2254 
2255 	if (read_it || erase_it || write_it || verify_it) {
2256 		/* Everything needs read. */
2257 		if (chip->tested.read == BAD) {
2258 			msg_cerr("Read is not working on this chip. ");
2259 			if (!force)
2260 				return 1;
2261 			msg_cerr("Continuing anyway.\n");
2262 		}
2263 		if (!lookup_read_func_ptr(chip)) {
2264 			msg_cerr("flashrom has no read function for this "
2265 				 "flash chip.\n");
2266 			return 1;
2267 		}
2268 	}
2269 	if (erase_it || write_it) {
2270 		/* Write needs erase. */
2271 		if (chip->tested.erase == NA) {
2272 			msg_cerr("Erase is not possible on this chip.\n");
2273 			return 1;
2274 		}
2275 		if (chip->tested.erase == BAD) {
2276 			msg_cerr("Erase is not working on this chip. ");
2277 			if (!force)
2278 				return 1;
2279 			msg_cerr("Continuing anyway.\n");
2280 		}
2281 		if(count_usable_erasers(flash) == 0) {
2282 			msg_cerr("flashrom has no erase function for this "
2283 				 "flash chip.\n");
2284 			return 1;
2285 		}
2286 	}
2287 	if (write_it) {
2288 		if (chip->tested.write == NA) {
2289 			msg_cerr("Write is not possible on this chip.\n");
2290 			return 1;
2291 		}
2292 		if (chip->tested.write == BAD) {
2293 			msg_cerr("Write is not working on this chip. ");
2294 			if (!force)
2295 				return 1;
2296 			msg_cerr("Continuing anyway.\n");
2297 		}
2298 		if (!lookup_write_func_ptr(chip)) {
2299 			msg_cerr("flashrom has no write function for this "
2300 				 "flash chip.\n");
2301 			return 1;
2302 		}
2303 	}
2304 	return 0;
2305 }
2306 
restore_flash_wp(struct flashctx * const flash,void * data)2307 static int restore_flash_wp(struct flashctx *const flash, void *data)
2308 {
2309 	struct flashrom_wp_cfg *wp_cfg = data;
2310 	enum flashrom_wp_result ret = flashrom_wp_write_cfg(flash, wp_cfg);
2311 	flashrom_wp_cfg_release(wp_cfg);
2312 
2313 	return (ret == FLASHROM_WP_OK) ? 0 : -1;
2314 }
2315 
save_initial_flash_wp(struct flashctx * const flash)2316 static int save_initial_flash_wp(struct flashctx *const flash)
2317 {
2318 	struct flashrom_wp_cfg *initial_wp_cfg;
2319 	if (flashrom_wp_cfg_new(&initial_wp_cfg) != FLASHROM_WP_OK)
2320 		return -1;
2321 
2322 	if (flashrom_wp_read_cfg(initial_wp_cfg, flash) != FLASHROM_WP_OK) {
2323 		flashrom_wp_cfg_release(initial_wp_cfg);
2324 		return -1;
2325 	}
2326 
2327 	if (register_chip_restore(restore_flash_wp, flash, initial_wp_cfg)) {
2328 		flashrom_wp_cfg_release(initial_wp_cfg);
2329 		return -1;
2330 	}
2331 	return 0;
2332 }
2333 
unlock_flash_wp(struct flashctx * const flash,const bool write_it,const bool erase_it)2334 static int unlock_flash_wp(struct flashctx *const flash,
2335 			   const bool write_it, const bool erase_it)
2336 
2337 {
2338 	int ret = 0;
2339 
2340 	/* WP only disables write protection, so only use WP to unlock
2341 	 * for write/erase operations.
2342 	 *
2343 	 * For read/verify operations, we still call the chip's unlock
2344 	 * function, which may disable read locks if the chip has them.
2345 	 */
2346 	if (!write_it && !erase_it) {
2347 		msg_cdbg("Skipping writeprotect-based unlocking for read/verify operations.\n");
2348 		return -1;
2349 	}
2350 
2351 	/* Save original WP state to be restored later */
2352 	if (save_initial_flash_wp(flash)) {
2353 		ret = -1;
2354 		goto warn_out;
2355 	}
2356 
2357 	/* Disable WP */
2358 	struct flashrom_wp_cfg *unlocked_wp_cfg;
2359 	if (flashrom_wp_cfg_new(&unlocked_wp_cfg) != FLASHROM_WP_OK) {
2360 		ret = -1;
2361 		goto warn_out;
2362 	}
2363 
2364 	flashrom_wp_set_range(unlocked_wp_cfg, 0, 0);
2365 	flashrom_wp_set_mode(unlocked_wp_cfg, FLASHROM_WP_MODE_DISABLED);
2366 	if (flashrom_wp_write_cfg(flash, unlocked_wp_cfg) != FLASHROM_WP_OK) {
2367 		ret = -1;
2368 	}
2369 
2370 	flashrom_wp_cfg_release(unlocked_wp_cfg);
2371 
2372 warn_out:
2373 	if (ret)
2374 		msg_cwarn("Failed to unlock flash status reg with wp support.\n");
2375 
2376 	return ret;
2377 }
2378 
prepare_flash_access(struct flashctx * const flash,const bool read_it,const bool write_it,const bool erase_it,const bool verify_it)2379 int prepare_flash_access(struct flashctx *const flash,
2380 			 const bool read_it, const bool write_it,
2381 			 const bool erase_it, const bool verify_it)
2382 {
2383 	if (chip_safety_check(flash, flash->flags.force, read_it, write_it, erase_it, verify_it)) {
2384 		msg_cerr("Aborting.\n");
2385 		return 1;
2386 	}
2387 
2388 	if (layout_sanity_checks(flash)) {
2389 		msg_cerr("Requested regions can not be handled. Aborting.\n");
2390 		return 1;
2391 	}
2392 
2393 	/* FIXME(b/207787495): replace this with locking in futility. */
2394 	/* Let powerd know that we're updating firmware so machine stays awake. */
2395 	if (write_it || erase_it) {
2396 		if (disable_power_management() == 2) /* FIXME(b:314677563): check ret */
2397 			return 1;
2398 	}
2399 
2400 	if (map_flash(flash) != 0)
2401 		return 1;
2402 
2403 	/* Initialize chip_restore_fn_count before chip unlock calls. */
2404 	flash->chip_restore_fn_count = 0;
2405 
2406 	int ret = 1;
2407 	if (flash->chip->decode_range != NO_DECODE_RANGE_FUNC ||
2408 	   (flash->mst->buses_supported & BUS_PROG && flash->mst->opaque.wp_write_cfg)) {
2409 		ret = unlock_flash_wp(flash, write_it, erase_it);
2410 	}
2411 	/*
2412 	 * Fall back to chip unlock function if we haven't already successfully
2413 	 * unlocked using WP (e.g. WP unlocking failed, chip had no WP support,
2414 	 * WP was skipped for read/verify ops).
2415 	 *
2416 	 * Given the existence of read locks, we want to unlock for read,
2417 	 * erase, write, and verify.
2418 	 */
2419 	blockprotect_func_t *bp_func = lookup_blockprotect_func_ptr(flash->chip);
2420 	if (ret && bp_func)
2421 		bp_func(flash);
2422 
2423 	flash->address_high_byte = -1;
2424 	flash->in_4ba_mode = false;
2425 
2426 	/* Be careful about 4BA chips and broken masters */
2427 	if (flash->chip->total_size > 16 * 1024 && spi_master_no_4ba_modes(flash)) {
2428 		/* If we can't use native instructions, bail out */
2429 		if ((flash->chip->feature_bits & FEATURE_4BA_NATIVE) != FEATURE_4BA_NATIVE
2430 		    || !spi_master_4ba(flash)) {
2431 			msg_cerr("Programmer doesn't support this chip. Aborting.\n");
2432 			return 1;
2433 		}
2434 	}
2435 
2436 	/* Enable/disable 4-byte addressing mode if flash chip supports it */
2437 	if (spi_chip_4ba(flash)) {
2438 		if (spi_master_4ba(flash))
2439 			ret = spi_enter_4ba(flash);
2440 		else
2441 			ret = spi_exit_4ba(flash);
2442 		if (ret) {
2443 			msg_cerr("Failed to set correct 4BA mode! Aborting.\n");
2444 			return 1;
2445 		}
2446 	}
2447 
2448 	return 0;
2449 }
2450 
finalize_flash_access(struct flashctx * const flash)2451 void finalize_flash_access(struct flashctx *const flash)
2452 {
2453 	deregister_chip_restore(flash);
2454 	unmap_flash(flash);
2455 
2456 	/* FIXME(b/207787495): replace this with locking in futility. */
2457 	if (restore_power_management()) {
2458 		msg_gerr("Unable to re-enable power management\n");
2459 	}
2460 }
2461 
setup_curcontents(struct flashctx * flashctx,void * curcontents,const void * const refcontents)2462 static int setup_curcontents(struct flashctx *flashctx, void *curcontents,
2463 			     const void *const refcontents)
2464 {
2465 	const size_t flash_size = flashctx->chip->total_size * 1024;
2466 	const bool verify_all = flashctx->flags.verify_whole_chip;
2467 
2468 	memset(curcontents, UNERASED_VALUE(flashctx), flash_size);
2469 
2470 	/* If given, assume flash chip contains same data as `refcontents`. */
2471 	if (refcontents) {
2472 		msg_cinfo("Assuming old flash chip contents as ref-file...\n");
2473 		memcpy(curcontents, refcontents, flash_size);
2474 	} else {
2475 		/*
2476 		 * Read the whole chip to be able to check whether regions need to be
2477 		 * erased and to give better diagnostics in case write fails.
2478 		 * The alternative is to read only the regions which are to be
2479 		 * preserved, but in that case we might perform unneeded erase which
2480 		 * takes time as well.
2481 		 */
2482 		msg_cinfo("Reading old flash chip contents... ");
2483 		if (verify_all) {
2484 			if (read_flash(flashctx, curcontents, 0, flash_size)) {
2485 				msg_cinfo("FAILED.\n");
2486 				return 1;
2487 			}
2488 		} else {
2489 			/* WARNING: See FIXME on get_required_erase_size() */
2490 			if (read_by_layout(flashctx, curcontents, true)) {
2491 				msg_cinfo("FAILED.\n");
2492 				return 1;
2493 			}
2494 		}
2495 		msg_cinfo("done.\n");
2496 	}
2497 	return 0;
2498 }
2499 
2500 static void combine_image_by_layout(const struct flashctx *const flashctx,
2501 				    uint8_t *const newcontents, const uint8_t *const oldcontents);
2502 
2503 /**
2504  * @brief Erases the included layout regions.
2505  *
2506  * If there is no layout set in the given flash context, the whole chip will
2507  * be erased.
2508  *
2509  * @param flashctx Flash context to be used.
2510  * @return 0 on success,
2511  *	   1 if all available erase functions failed.
2512  */
erase_by_layout_downstream(struct flashctx * const flashctx)2513 static int erase_by_layout_downstream(struct flashctx *const flashctx)
2514 {
2515 	const size_t flash_size = flashctx->chip->total_size * 1024;
2516 	int ret = 1;
2517 
2518 	uint8_t *curcontents = malloc(flash_size);
2519 	uint8_t *newcontents = malloc(flash_size);
2520 	if (!curcontents || !newcontents) {
2521 		msg_gerr("Out of memory!\n");
2522 		goto _free_ret;
2523 	}
2524 
2525 	if (setup_curcontents(flashctx, curcontents, NULL))
2526 		goto _free_ret;
2527 
2528 	memset(newcontents, ERASED_VALUE(flashctx), flash_size);
2529 	combine_image_by_layout(flashctx, newcontents, curcontents);
2530 
2531 	bool all_skipped = true;
2532 	ret = erase_and_write_flash(flashctx, curcontents, newcontents, &all_skipped);
2533 
2534 _free_ret:
2535 	free(curcontents);
2536 	free(newcontents);
2537 	return ret;
2538 }
2539 static bool g_use_upstream_erase_path = false;
2540 
flashrom_flash_erase(struct flashctx * const flashctx)2541 int flashrom_flash_erase(struct flashctx *const flashctx)
2542 {
2543 	int ret;
2544 	if (prepare_flash_access(flashctx, false, false, true, false))
2545 		return 1;
2546 
2547 	if (g_use_upstream_erase_path)
2548 		ret = erase_by_layout(flashctx);
2549 	else
2550 		ret = erase_by_layout_downstream(flashctx);
2551 
2552 	finalize_flash_access(flashctx);
2553 
2554 	return ret;
2555 }
2556 
flashrom_image_read(struct flashctx * const flashctx,void * const buffer,const size_t buffer_len)2557 int flashrom_image_read(struct flashctx *const flashctx, void *const buffer, const size_t buffer_len)
2558 {
2559 	const size_t flash_size = flashctx->chip->total_size * 1024;
2560 
2561 	if (flash_size > buffer_len)
2562 		return 2;
2563 
2564 	if (prepare_flash_access(flashctx, true, false, false, false))
2565 		return 1;
2566 
2567 	msg_cinfo("Reading flash... ");
2568 
2569 	int ret = 1;
2570 	if (read_by_layout(flashctx, buffer, false)) {
2571 		msg_cerr("Read operation failed!\n");
2572 		msg_cinfo("FAILED.\n");
2573 		goto _finalize_ret;
2574 	}
2575 	msg_cinfo("done.\n");
2576 	ret = 0;
2577 
2578 _finalize_ret:
2579 	finalize_flash_access(flashctx);
2580 	return ret;
2581 }
2582 
combine_image_by_layout(const struct flashctx * const flashctx,uint8_t * const newcontents,const uint8_t * const oldcontents)2583 static void combine_image_by_layout(const struct flashctx *const flashctx,
2584 				    uint8_t *const newcontents, const uint8_t *const oldcontents)
2585 {
2586 	const struct flashrom_layout *const layout = get_layout(flashctx);
2587 	const struct romentry *included;
2588 	chipoff_t start = 0;
2589 
2590 	while ((included = layout_next_included_region(layout, start))) {
2591 		const struct flash_region *region = &included->region;
2592 		if (region->start > start) {
2593 			/* copy everything up to the start of this included region */
2594 			memcpy(newcontents + start, oldcontents + start, region->start - start);
2595 		}
2596 		/* skip this included region */
2597 		start = region->end + 1;
2598 		if (start == 0)
2599 			return;
2600 	}
2601 
2602 	/* copy the rest of the chip */
2603 	const chipsize_t copy_len = flashctx->chip->total_size * 1024 - start;
2604 	memcpy(newcontents + start, oldcontents + start, copy_len);
2605 }
2606 
2607 static bool g_use_upstream_erasewrite_path = false;
2608 
flashrom_image_write(struct flashctx * const flashctx,void * const buffer,const size_t buffer_len,const void * const refbuffer)2609 int flashrom_image_write(struct flashctx *const flashctx, void *const buffer, const size_t buffer_len,
2610                          const void *const refbuffer)
2611 {
2612 	const size_t flash_size = flashctx->chip->total_size * 1024;
2613 	const bool verify_all = flashctx->flags.verify_whole_chip;
2614 	const bool verify = flashctx->flags.verify_after_write;
2615 	const struct flashrom_layout *const verify_layout =
2616 		verify_all ? get_default_layout(flashctx) : get_layout(flashctx);
2617 
2618 	if (buffer_len != flash_size)
2619 		return 4;
2620 
2621 	int ret = 1;
2622 	int tmp = 0;
2623 
2624 	uint8_t *curcontents = malloc(flash_size);
2625 	uint8_t *newcontents = malloc(flash_size);
2626 	uint8_t *oldcontents = NULL;
2627 	if (verify_all)
2628 		oldcontents = malloc(flash_size);
2629 	if (!curcontents || !newcontents || (verify_all && !oldcontents)) {
2630 		msg_gerr("Out of memory!\n");
2631 		goto _free_ret;
2632 	}
2633 
2634 #if CONFIG_INTERNAL == 1
2635 	if (is_internal_programmer() && cb_check_image(newcontents, flash_size) < 0) {
2636 		if (flashctx->flags.force_boardmismatch) {
2637 			msg_pinfo("Proceeding anyway because user forced us to.\n");
2638 		} else {
2639 			msg_perr("Aborting. You can override this with "
2640 				 "-p internal:boardmismatch=force.\n");
2641 			goto _free_ret;
2642 		}
2643 	}
2644 #endif
2645 
2646 	if (prepare_flash_access(flashctx, false, true, false, verify))
2647 		goto _free_ret;
2648 
2649 	if (setup_curcontents(flashctx, curcontents, refbuffer))
2650 		goto _finalize_ret;
2651 	if (oldcontents)
2652 		memcpy(oldcontents, curcontents, flash_size);
2653 
2654 	memcpy(newcontents, buffer, flash_size);
2655 	combine_image_by_layout(flashctx, newcontents, curcontents);
2656 
2657 	// parse the new fmap and disable soft WP if necessary
2658 	if ((tmp = cros_ec_prepare(flashctx, newcontents, flash_size))) {
2659 		msg_cerr("CROS_EC prepare failed, ret=%d.\n", tmp);
2660 		goto _finalize_ret;
2661 	}
2662 
2663 	bool all_skipped = true;
2664 	if (g_use_upstream_erasewrite_path)
2665 		ret = write_by_layout(flashctx, curcontents, newcontents, &all_skipped);
2666 	else
2667 		ret = erase_and_write_flash(flashctx, curcontents, newcontents, &all_skipped);
2668 	if (ret) {
2669 		msg_cerr("Uh oh. Erase/write failed. ");
2670 		ret = 2;
2671 		if (verify_all) {
2672 			msg_cerr("Checking if anything has changed.\n");
2673 			msg_cinfo("Reading current flash chip contents... ");
2674 			if (!read_flash(flashctx, curcontents, 0, flash_size)) {
2675 				msg_cinfo("done.\n");
2676 				if (!memcmp(oldcontents, curcontents, flash_size)) {
2677 					nonfatal_help_message();
2678 					goto _finalize_ret;
2679 				}
2680 				msg_cerr("Apparently at least some data has changed.\n");
2681 			} else
2682 				msg_cerr("Can't even read anymore!\n");
2683 			emergency_help_message();
2684 			goto _finalize_ret;
2685 		} else {
2686 			msg_cerr("\n");
2687 		}
2688 		emergency_help_message();
2689 		goto _finalize_ret;
2690 	}
2691 
2692 	tmp = cros_ec_need_2nd_pass();
2693 	if (tmp < 0) {
2694 		// Jump failed
2695 		msg_cerr("cros_ec_need_2nd_pass() failed. Stop.\n");
2696 		emergency_help_message();
2697 		goto _finalize_ret;
2698 	} else if (tmp > 0) {
2699 		// Need 2nd pass. Get the just written content.
2700 		msg_pdbg("CROS_EC needs 2nd pass.\n");
2701 		if (setup_curcontents(flashctx, curcontents, NULL)) {
2702 			emergency_help_message();
2703 			goto _finalize_ret;
2704 		}
2705 
2706 		// write 2nd pass
2707 		if (g_use_upstream_erasewrite_path)
2708 			ret = write_by_layout(flashctx, curcontents, newcontents, &all_skipped);
2709 		else
2710 			ret = erase_and_write_flash(flashctx, curcontents, newcontents, &all_skipped);
2711 		if (ret) {
2712 			msg_cerr("Uh oh. CROS_EC 2nd pass failed.\n");
2713 			ret = 2;
2714 			emergency_help_message();
2715 			goto _finalize_ret;
2716 		}
2717 	}
2718 
2719 	/* Verify only if we actually changed something. */
2720 	if (verify && !all_skipped) {
2721 		msg_cinfo("Verifying flash... ");
2722 
2723 		/*
2724 		 * Work around chips which "need some time to calm down."
2725 		 *
2726 		 * Frankly, it's not 100% clear why this delay is here at all,
2727 		 * except for a terse message from 2009 of "a few reports where
2728 		 * verify directly after erase had unpleasant side effects like
2729 		 * corrupting flash or at least getting incorrect verify
2730 		 * results". Ideally, if there were a few known problematic
2731 		 * chips or programmers, we could add quirks flags for those
2732 		 * specific implementations without penalizing all other
2733 		 * flashrom users. But alas, we don't know which systems
2734 		 * experienced those issues.
2735 		 *
2736 		 * Out of an extreme abundance of caution, we retain this
2737 		 * delay, but only for a few non-SPI bus types that were the
2738 		 * likely prevalent targets at the time. This is a complete
2739 		 * guess, which conveniently avoids wasting time on common
2740 		 * BUS_SPI and BUS_PROG systems.
2741 		 *
2742 		 * Background thread:
2743 		 * Subject: RFC: removing 1 second verification delay
2744 		 * https://mail.coreboot.org/hyperkitty/list/[email protected]/thread/SFV3OJBVVMDKRLI3FQA3DDDGEXJ7W4ED/
2745 		 */
2746 		if (flashctx->chip->bustype & (BUS_PARALLEL | BUS_LPC | BUS_FWH))
2747 			programmer_delay(flashctx, 1000*1000);
2748 
2749 		ret = verify_by_layout(flashctx, verify_layout, curcontents, newcontents);
2750 		/* If we tried to write, and verification now fails, we
2751 		   might have an emergency situation. */
2752 		if (ret) {
2753 			emergency_help_message();
2754 			goto _finalize_ret;
2755 		}
2756 		else
2757 			msg_cinfo("VERIFIED.\n");
2758 	} else {
2759 		/* We didn't change anything. */
2760 		ret = 0;
2761 	}
2762 
2763 	if (cros_ec_finish() < 0) {
2764 		msg_cerr("cros_ec_finish() failed. Stop.\n");
2765 		ret = 1;
2766 		emergency_help_message();
2767 	}
2768 
2769 _finalize_ret:
2770 	finalize_flash_access(flashctx);
2771 _free_ret:
2772 	free(oldcontents);
2773 	free(curcontents);
2774 	free(newcontents);
2775 	return ret;
2776 }
2777 
flashrom_image_verify(struct flashctx * const flashctx,const void * const buffer,const size_t buffer_len)2778 int flashrom_image_verify(struct flashctx *const flashctx, const void *const buffer, const size_t buffer_len)
2779 {
2780 	const struct flashrom_layout *const layout = get_layout(flashctx);
2781 	const size_t flash_size = flashctx->chip->total_size * 1024;
2782 
2783 	if (buffer_len != flash_size)
2784 		return 2;
2785 
2786 	const uint8_t *const newcontents = buffer;
2787 	uint8_t *const curcontents = malloc(flash_size);
2788 	if (!curcontents) {
2789 		msg_gerr("Out of memory!\n");
2790 		return 1;
2791 	}
2792 
2793 	int ret = 1;
2794 
2795 	if (prepare_flash_access(flashctx, false, false, false, true))
2796 		goto _free_ret;
2797 
2798 	msg_cinfo("Verifying flash... ");
2799 	ret = verify_by_layout(flashctx, layout, curcontents, newcontents);
2800 	if (!ret)
2801 		msg_cinfo("VERIFIED.\n");
2802 
2803 	finalize_flash_access(flashctx);
2804 _free_ret:
2805 	free(curcontents);
2806 	return ret;
2807 }
2808