blob: f647f7504475977b8086bbb4bae379f127e841ad [file] [log] [blame]
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +00001/*
Uwe Hermannd1107642007-08-29 17:52:32 +00002 * This file is part of the flashrom project.
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +00003 *
Uwe Hermannd22a1d42007-09-09 20:21:05 +00004 * Copyright (C) 2000 Silicon Integrated System Corporation
5 * Copyright (C) 2004 Tyan Corp <yhlu@tyan.com>
Uwe Hermannc7e8a0c2009-05-19 14:14:21 +00006 * Copyright (C) 2005-2008 coresystems GmbH
Carl-Daniel Hailfinger03b4e712009-05-08 12:49:03 +00007 * Copyright (C) 2008,2009 Carl-Daniel Hailfinger
Nico Huber7af0e792016-04-29 16:40:15 +02008 * Copyright (C) 2016 secunet Security Networks AG
9 * (Written by Nico Huber <nico.huber@secunet.com> for secunet)
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +000010 *
Uwe Hermannd1107642007-08-29 17:52:32 +000011 * 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.
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +000015 *
Uwe Hermannd1107642007-08-29 17:52:32 +000016 * 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.
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +000020 */
21
Felix Singerf25447e2022-08-19 02:44:28 +020022#include <stdbool.h>
Carl-Daniel Hailfinger831e8f42010-05-30 22:24:40 +000023#include <stdio.h>
Stefan Reinauer018aca82006-11-21 23:48:51 +000024#include <sys/types.h>
Ronald G. Minnichceec4202003-07-25 04:37:41 +000025#include <string.h>
Stefan Tauner16687702015-12-25 21:59:45 +000026#include <unistd.h>
Ronald G. Minnicheaab50b2003-09-12 22:41:53 +000027#include <stdlib.h>
Stefan Tauner363fd7e2013-04-07 13:08:30 +000028#include <errno.h>
Carl-Daniel Hailfingerc2441382010-11-09 22:00:31 +000029#include <ctype.h>
Edward O'Callaghan3b64d812022-08-12 13:07:51 +100030
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +000031#include "flash.h"
Carl-Daniel Hailfinger08454642009-06-15 14:14:48 +000032#include "flashchips.h"
Carl-Daniel Hailfinger5b997c32010-07-27 22:41:39 +000033#include "programmer.h"
Thomas Heijligen74b4aa02021-12-14 17:52:30 +010034#include "hwaccess_physmap.h"
Nico Huberfbc41d22026-02-22 23:04:01 +010035#include "chipdrivers/spi.h"
Nico Huber9d09e0f2025-03-02 22:55:10 +010036#include "version.h"
Ronald G. Minnichf4cf2ba2002-01-29 18:26:26 +000037
Nico Huberc3b02dc2023-08-12 01:13:45 +020038const char flashprog_version[] = FLASHPROG_VERSION;
Carl-Daniel Hailfinger66ef4e52009-12-13 22:28:00 +000039
Thomas Heijligenc7e5b8b2021-06-01 14:21:41 +020040static const struct programmer_entry *programmer = NULL;
Nico Huber6a2ebeb2022-08-26 11:36:48 +020041static char *programmer_param = NULL;
Stefan Reinauer70385642007-04-06 11:58:03 +000042
Carl-Daniel Hailfingerd1be52d2010-07-03 12:14:25 +000043/* Is writing allowed with this programmer? */
Felix Singer980d6b82022-08-19 02:48:15 +020044bool programmer_may_write;
Carl-Daniel Hailfingerd1be52d2010-07-03 12:14:25 +000045
Carl-Daniel Hailfinger2bee8cf2010-11-10 15:25:18 +000046#define SHUTDOWN_MAXFN 32
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000047static int shutdown_fn_count = 0;
Nico Huber454f6132012-12-10 13:34:10 +000048/** @private */
Richard Hughes93e16252018-12-19 11:54:47 +000049static struct shutdown_func_data {
David Hendricks8bb20212011-06-14 01:35:36 +000050 int (*func) (void *data);
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000051 void *data;
Richard Hughes93e16252018-12-19 11:54:47 +000052} shutdown_fn[SHUTDOWN_MAXFN];
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +000053/* Initialize to 0 to make sure nobody registers a shutdown function before
54 * programmer init.
55 */
Felix Singerf25447e2022-08-19 02:44:28 +020056static bool may_register_shutdown = false;
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000057
Stefan Taunerc4f44df2013-08-12 22:58:43 +000058/* Did we change something or was every erase/write skipped (if any)? */
59static bool all_skipped = true;
60
Carl-Daniel Hailfinger63fd9022011-12-14 22:25:15 +000061static int check_block_eraser(const struct flashctx *flash, int k, int log);
Stefan Tauner5368dca2011-07-01 00:19:12 +000062
Stefan Tauner2a1ed772014-08-31 00:09:21 +000063int shutdown_free(void *data)
64{
65 free(data);
66 return 0;
67}
68
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000069/* Register a function to be executed on programmer shutdown.
70 * The advantage over atexit() is that you can supply a void pointer which will
71 * be used as parameter to the registered function upon programmer shutdown.
72 * This pointer can point to arbitrary data used by said function, e.g. undo
73 * information for GPIO settings etc. If unneeded, set data=NULL.
74 * Please note that the first (void *data) belongs to the function signature of
75 * the function passed as first parameter.
76 */
David Hendricks8bb20212011-06-14 01:35:36 +000077int register_shutdown(int (*function) (void *data), void *data)
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000078{
79 if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
Carl-Daniel Hailfinger9f5f2152010-06-04 23:20:21 +000080 msg_perr("Tried to register more than %i shutdown functions.\n",
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000081 SHUTDOWN_MAXFN);
82 return 1;
83 }
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +000084 if (!may_register_shutdown) {
85 msg_perr("Tried to register a shutdown function before "
86 "programmer init.\n");
87 return 1;
88 }
Carl-Daniel Hailfingercc389fc2010-02-14 01:20:28 +000089 shutdown_fn[shutdown_fn_count].func = function;
90 shutdown_fn[shutdown_fn_count].data = data;
91 shutdown_fn_count++;
92
93 return 0;
94}
95
Nikolai Artemiev4ad48642020-11-05 13:54:27 +110096int register_chip_restore(chip_restore_fn_cb_t func,
97 struct flashctx *flash, uint8_t status)
98{
99 if (flash->chip_restore_fn_count >= MAX_CHIP_RESTORE_FUNCTIONS) {
100 msg_perr("Tried to register more than %i chip restore"
101 " functions.\n", MAX_CHIP_RESTORE_FUNCTIONS);
102 return 1;
103 }
104 flash->chip_restore_fn[flash->chip_restore_fn_count].func = func;
105 flash->chip_restore_fn[flash->chip_restore_fn_count].status = status;
106 flash->chip_restore_fn_count++;
107
108 return 0;
109}
110
111static int deregister_chip_restore(struct flashctx *flash)
112{
113 int rc = 0;
114
115 while (flash->chip_restore_fn_count > 0) {
116 int i = --flash->chip_restore_fn_count;
117 rc |= flash->chip_restore_fn[i].func(
118 flash, flash->chip_restore_fn[i].status);
119 }
120
121 return rc;
122}
123
Nico Huber2b66ad92023-01-11 20:15:15 +0100124int programmer_init(struct flashprog_programmer *const prog)
Uwe Hermann09e04f72009-05-16 22:36:00 +0000125{
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000126 int ret;
Carl-Daniel Hailfinger2e681602011-09-08 00:00:29 +0000127
Nico Huber2b66ad92023-01-11 20:15:15 +0100128 if (prog == NULL || prog->driver == NULL) {
Carl-Daniel Hailfinger2e681602011-09-08 00:00:29 +0000129 msg_perr("Invalid programmer specified!\n");
130 return -1;
131 }
Nico Huber2b66ad92023-01-11 20:15:15 +0100132 programmer = prog->driver;
133 programmer_param = prog->param;
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +0000134 /* Registering shutdown functions is now allowed. */
Felix Singerf25447e2022-08-19 02:44:28 +0200135 may_register_shutdown = true;
Carl-Daniel Hailfingerd1be52d2010-07-03 12:14:25 +0000136 /* Default to allowing writes. Broken programmers set this to 0. */
Felix Singer980d6b82022-08-19 02:48:15 +0200137 programmer_may_write = true;
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +0000138
Thomas Heijligenc7e5b8b2021-06-01 14:21:41 +0200139 msg_pdbg("Initializing %s programmer\n", programmer->name);
Nico Hubere3a26882023-01-11 21:45:51 +0100140 ret = programmer->init(prog);
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000141 if (programmer_param && strlen(programmer_param)) {
Carl-Daniel Hailfinger20a36ba2013-08-13 07:09:57 +0000142 if (ret != 0) {
143 /* It is quite possible that any unhandled programmer parameter would have been valid,
144 * but an error in actual programmer init happened before the parameter was evaluated.
145 */
146 msg_pwarn("Unhandled programmer parameters (possibly due to another failure): %s\n",
147 programmer_param);
148 } else {
149 /* Actual programmer init was successful, but the user specified an invalid or unusable
150 * (for the current programmer configuration) parameter.
151 */
152 msg_perr("Unhandled programmer parameters: %s\n", programmer_param);
153 msg_perr("Aborting.\n");
154 ret = ERROR_FATAL;
155 }
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000156 }
Nico Huber6a2ebeb2022-08-26 11:36:48 +0200157 programmer_param = NULL;
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000158 return ret;
Uwe Hermann09e04f72009-05-16 22:36:00 +0000159}
160
Stefan Tauner20da4aa2014-05-07 22:07:23 +0000161/** Calls registered shutdown functions and resets internal programmer-related variables.
162 * Calling it is safe even without previous initialization, but further interactions with programmer support
163 * require a call to programmer_init() (afterwards).
164 *
165 * @return The OR-ed result values of all shutdown functions (i.e. 0 on success). */
Nico Huber2b66ad92023-01-11 20:15:15 +0100166int programmer_shutdown(struct flashprog_programmer *const prog)
Uwe Hermann09e04f72009-05-16 22:36:00 +0000167{
David Hendricks8bb20212011-06-14 01:35:36 +0000168 int ret = 0;
169
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +0000170 /* Registering shutdown functions is no longer allowed. */
Felix Singerf25447e2022-08-19 02:44:28 +0200171 may_register_shutdown = false;
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +0000172 while (shutdown_fn_count > 0) {
173 int i = --shutdown_fn_count;
David Hendricks8bb20212011-06-14 01:35:36 +0000174 ret |= shutdown_fn[i].func(shutdown_fn[i].data);
Carl-Daniel Hailfingerad3cc552010-07-03 11:02:10 +0000175 }
Carl-Daniel Hailfingera5bcbce2014-07-19 22:03:29 +0000176 registered_master_count = 0;
Stefan Taunere34e3e82013-01-01 00:06:51 +0000177
David Hendricks8bb20212011-06-14 01:35:36 +0000178 return ret;
Uwe Hermann09e04f72009-05-16 22:36:00 +0000179}
180
Stefan Taunerf80419c2014-05-02 15:41:42 +0000181void programmer_delay(unsigned int usecs)
Carl-Daniel Hailfingerca8bfc62009-06-05 17:48:08 +0000182{
Edward O'Callaghan56684d92022-09-07 10:47:45 +1000183 if (usecs > 0) {
184 if (programmer->delay)
185 programmer->delay(usecs);
186 else
187 internal_delay(usecs);
188 }
Carl-Daniel Hailfingerca8bfc62009-06-05 17:48:08 +0000189}
190
Nico Hubercdcfda22023-04-29 13:29:33 +0200191static int read_memmapped_chunk(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
Carl-Daniel Hailfinger03b4e712009-05-08 12:49:03 +0000192{
Carl-Daniel Hailfinger8a3c60c2011-12-18 15:01:24 +0000193 chip_readn(flash, buf, flash->virtual_memory + start, len);
Carl-Daniel Hailfinger03b4e712009-05-08 12:49:03 +0000194 return 0;
195}
Nico Hubercdcfda22023-04-29 13:29:33 +0200196int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start, int unsigned len)
197{
198 return flashprog_read_chunked(flash, buf, start, len, MAX_DATA_READ_UNLIMITED, read_memmapped_chunk);
199}
Carl-Daniel Hailfinger03b4e712009-05-08 12:49:03 +0000200
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000201/* This is a somewhat hacked function similar in some ways to strtok().
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000202 * It will look for needle with a subsequent '=' in haystack, return a copy of
203 * needle and remove everything from the first occurrence of needle to the next
204 * delimiter from haystack.
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000205 */
Nico Huber6a2ebeb2022-08-26 11:36:48 +0200206static char *extract_param(char *const *haystack, const char *needle, const char *delim)
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000207{
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000208 char *param_pos, *opt_pos, *rest;
209 char *opt = NULL;
210 int optlen;
Carl-Daniel Hailfinger27023762010-04-28 15:22:14 +0000211 int needlelen;
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000212
Carl-Daniel Hailfinger27023762010-04-28 15:22:14 +0000213 needlelen = strlen(needle);
214 if (!needlelen) {
215 msg_gerr("%s: empty needle! Please report a bug at "
Nico Huberc3b02dc2023-08-12 01:13:45 +0200216 "flashprog@flashprog.org\n", __func__);
Carl-Daniel Hailfinger27023762010-04-28 15:22:14 +0000217 return NULL;
218 }
219 /* No programmer parameters given. */
220 if (*haystack == NULL)
221 return NULL;
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000222 param_pos = strstr(*haystack, needle);
223 do {
224 if (!param_pos)
225 return NULL;
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000226 /* Needle followed by '='? */
227 if (param_pos[needlelen] == '=') {
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000228 /* Beginning of the string? */
229 if (param_pos == *haystack)
230 break;
231 /* After a delimiter? */
232 if (strchr(delim, *(param_pos - 1)))
233 break;
234 }
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000235 /* Continue searching. */
236 param_pos++;
237 param_pos = strstr(param_pos, needle);
238 } while (1);
Uwe Hermann91f4afa2011-07-28 08:13:25 +0000239
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000240 if (param_pos) {
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000241 /* Get the string after needle and '='. */
242 opt_pos = param_pos + needlelen + 1;
243 optlen = strcspn(opt_pos, delim);
244 /* Return an empty string if the parameter was empty. */
245 opt = malloc(optlen + 1);
246 if (!opt) {
Sean Nelson316a29f2010-05-07 20:09:04 +0000247 msg_gerr("Out of memory!\n");
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000248 exit(1);
249 }
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000250 strncpy(opt, opt_pos, optlen);
251 opt[optlen] = '\0';
252 rest = opt_pos + optlen;
253 /* Skip all delimiters after the current parameter. */
254 rest += strspn(rest, delim);
255 memmove(param_pos, rest, strlen(rest) + 1);
256 /* We could shrink haystack, but the effort is not worth it. */
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000257 }
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000258
Carl-Daniel Hailfinger744132a2010-07-06 09:55:48 +0000259 return opt;
Carl-Daniel Hailfingerd5b28fa2009-11-24 18:27:10 +0000260}
261
Stefan Tauner66652442011-06-26 17:38:17 +0000262char *extract_programmer_param(const char *param_name)
Carl-Daniel Hailfinger2b6dcb32010-07-08 10:13:37 +0000263{
264 return extract_param(&programmer_param, param_name, ",");
265}
266
Richard Hughes842d6782021-01-15 09:48:12 +0000267static void flashprog_progress_report(struct flashprog_progress *const p)
268{
269 if (p->current > p->total) {
270 msg_gdbg2("Sanitizing progress report: %zu bytes off.", p->current - p->total);
271 p->current = p->total;
272 }
273
274 if (!p->callback)
275 return;
276
277 p->callback(p->stage, p->current, p->total, p->user_data);
278}
279
280static void flashprog_progress_start(struct flashprog_flashctx *const flashctx,
281 const enum flashprog_progress_stage stage, const size_t total)
282{
283 flashctx->progress.stage = stage;
284 flashctx->progress.current = 0;
285 flashctx->progress.total = total;
286 flashprog_progress_report(&flashctx->progress);
287}
288
289static void flashprog_progress_start_by_layout(struct flashprog_flashctx *const flashctx,
290 const enum flashprog_progress_stage stage,
291 const struct flashprog_layout *const layout)
292{
293 const struct romentry *entry = NULL;
294 size_t total = 0;
295
296 while ((entry = layout_next_included(layout, entry)))
297 total += entry->end - entry->start + 1;
298
299 flashprog_progress_start(flashctx, stage, total);
300}
301
302static void flashprog_progress_set(struct flashprog_flashctx *const flashctx, const size_t current)
303{
304 flashctx->progress.current = current;
305 flashprog_progress_report(&flashctx->progress);
306}
307
308/** @private */
309void flashprog_progress_add(struct flashprog_flashctx *const flashctx, const size_t progress)
310{
311 flashctx->progress.current += progress;
312 flashprog_progress_report(&flashctx->progress);
313}
314
315static void flashprog_progress_finish(struct flashprog_flashctx *const flashctx)
316{
317 if (flashctx->progress.current == flashctx->progress.total)
318 return;
319
320 flashctx->progress.current = flashctx->progress.total;
321 flashprog_progress_report(&flashctx->progress);
322}
323
Sylvain "ythier" Hitier9db45512011-07-04 07:27:17 +0000324/* Returns the number of well-defined erasers for a chip. */
Nico Huberbb8ab372026-03-14 11:46:02 +0100325unsigned int flashprog_count_usable_erasers(const struct flashctx *flash)
Stefan Tauner5368dca2011-07-01 00:19:12 +0000326{
327 unsigned int usable_erasefunctions = 0;
328 int k;
329 for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
330 if (!check_block_eraser(flash, k, 0))
331 usable_erasefunctions++;
332 }
333 return usable_erasefunctions;
334}
335
Mark Marshallf20b7be2014-05-09 21:16:21 +0000336static int compare_range(const uint8_t *wantbuf, const uint8_t *havebuf, unsigned int start, unsigned int len)
Stefan Tauner78ffbea2012-10-27 15:36:56 +0000337{
338 int ret = 0, failcount = 0;
339 unsigned int i;
340 for (i = 0; i < len; i++) {
341 if (wantbuf[i] != havebuf[i]) {
342 /* Only print the first failure. */
343 if (!failcount++)
344 msg_cerr("FAILED at 0x%08x! Expected=0x%02x, Found=0x%02x,",
345 start + i, wantbuf[i], havebuf[i]);
346 }
347 }
348 if (failcount) {
349 msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
350 start, start + len - 1, failcount);
351 ret = -1;
352 }
353 return ret;
354}
355
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000356/* start is an offset to the base address of the flash chip */
Jacob Garberbeeb8bc2019-06-21 15:24:17 -0600357static int check_erased_range(struct flashctx *flash, unsigned int start, unsigned int len)
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000358{
359 int ret;
Paul Kocialkowski995f7552018-01-15 01:06:09 +0300360 const uint8_t erased_value = ERASED_VALUE(flash);
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000361
Edward O'Callaghanf60f64f2022-11-12 12:08:01 +1100362 uint8_t *cmpbuf = malloc(len);
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000363 if (!cmpbuf) {
Edward O'Callaghana31a5722022-11-12 12:05:36 +1100364 msg_gerr("Out of memory!\n");
Edward O'Callaghan6edf9f82022-11-12 12:08:46 +1100365 return -1;
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000366 }
Paul Kocialkowski995f7552018-01-15 01:06:09 +0300367 memset(cmpbuf, erased_value, len);
Stefan Tauner78ffbea2012-10-27 15:36:56 +0000368 ret = verify_range(flash, cmpbuf, start, len);
Edward O'Callaghanf60f64f2022-11-12 12:08:01 +1100369
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000370 free(cmpbuf);
371 return ret;
372}
373
Richard Hughes842d6782021-01-15 09:48:12 +0000374int flashprog_read_range(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
375{
376 flashprog_progress_start(flash, FLASHPROG_PROGRESS_READ, len);
377 const int ret = flash->chip->read(flash, buf, start, len);
378 flashprog_progress_finish(flash);
379 return ret;
380}
381
Uwe Hermann48ec1b12010-08-08 17:01:18 +0000382/*
Carl-Daniel Hailfingerd0250a32009-11-25 17:05:52 +0000383 * @cmpbuf buffer to compare against, cmpbuf[0] is expected to match the
Uwe Hermann91f4afa2011-07-28 08:13:25 +0000384 * flash content at location start
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000385 * @start offset to the base address of the flash chip
386 * @len length of the verified area
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000387 * @return 0 for success, -1 for failure
388 */
Mark Marshallf20b7be2014-05-09 21:16:21 +0000389int verify_range(struct flashctx *flash, const uint8_t *cmpbuf, unsigned int start, unsigned int len)
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000390{
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000391 if (!len)
Stefan Taunerdf64a422014-05-27 00:06:14 +0000392 return -1;
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000393
Edward O'Callaghan6ae640b2021-11-17 14:24:04 +1100394 if (start + len > flash->chip->total_size * 1024) {
395 msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
396 " total_size 0x%x\n", __func__, start, len,
397 flash->chip->total_size * 1024);
398 return -1;
399 }
400
Stefan Taunerdf64a422014-05-27 00:06:14 +0000401 uint8_t *readbuf = malloc(len);
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000402 if (!readbuf) {
Edward O'Callaghana31a5722022-11-12 12:05:36 +1100403 msg_gerr("Out of memory!\n");
Stefan Taunerdf64a422014-05-27 00:06:14 +0000404 return -1;
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000405 }
406
Edward O'Callaghan6ae640b2021-11-17 14:24:04 +1100407 int ret = flash->chip->read(flash, readbuf, start, len);
Carl-Daniel Hailfingerd8369412010-11-16 17:21:58 +0000408 if (ret) {
409 msg_gerr("Verification impossible because read failed "
410 "at 0x%x (len 0x%x)\n", start, len);
Stefan Taunerdf64a422014-05-27 00:06:14 +0000411 ret = -1;
412 goto out_free;
Carl-Daniel Hailfingerd8369412010-11-16 17:21:58 +0000413 }
414
Stefan Tauner78ffbea2012-10-27 15:36:56 +0000415 ret = compare_range(cmpbuf, readbuf, start, len);
Carl-Daniel Hailfinger30f7cb22009-06-15 17:23:36 +0000416out_free:
417 free(readbuf);
418 return ret;
419}
420
Nico Huber3ac761c2023-01-16 02:43:17 +0100421size_t gran_to_bytes(const enum write_granularity gran)
Nico Huberb77607f2023-01-16 02:25:45 +0100422{
423 switch (gran) {
424 case write_gran_1bit: return 1;
425 case write_gran_1byte: return 1;
426 case write_gran_1byte_implicit_erase: return 1;
427 case write_gran_128bytes: return 128;
428 case write_gran_256bytes: return 256;
429 case write_gran_264bytes: return 264;
430 case write_gran_512bytes: return 512;
431 case write_gran_528bytes: return 528;
432 case write_gran_1024bytes: return 1024;
433 case write_gran_1056bytes: return 1056;
434 default: return 0;
435 }
436}
437
Stefan Tauner02437452013-04-01 19:34:53 +0000438/* Helper function for need_erase() that focuses on granularities of gran bytes. */
Paul Kocialkowski995f7552018-01-15 01:06:09 +0300439static int need_erase_gran_bytes(const uint8_t *have, const uint8_t *want, unsigned int len,
440 unsigned int gran, const uint8_t erased_value)
Stefan Tauner02437452013-04-01 19:34:53 +0000441{
442 unsigned int i, j, limit;
443 for (j = 0; j < len / gran; j++) {
444 limit = min (gran, len - j * gran);
445 /* Are 'have' and 'want' identical? */
446 if (!memcmp(have + j * gran, want + j * gran, limit))
447 continue;
448 /* have needs to be in erased state. */
449 for (i = 0; i < limit; i++)
Paul Kocialkowski995f7552018-01-15 01:06:09 +0300450 if (have[j * gran + i] != erased_value)
Stefan Tauner02437452013-04-01 19:34:53 +0000451 return 1;
452 }
453 return 0;
454}
455
Uwe Hermann48ec1b12010-08-08 17:01:18 +0000456/*
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000457 * Check if the buffer @have can be programmed to the content of @want without
458 * erasing. This is only possible if all chunks of size @gran are either kept
459 * as-is or changed from an all-ones state to any other state.
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000460 *
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000461 * Warning: This function assumes that @have and @want point to naturally
462 * aligned regions.
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000463 *
464 * @have buffer with current content
465 * @want buffer with desired content
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000466 * @len length of the checked area
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000467 * @gran write granularity (enum, not count)
468 * @return 0 if no erase is needed, 1 otherwise
469 */
Edward O'Callaghana1805092022-05-16 11:10:36 +1000470static int need_erase(const uint8_t *have, const uint8_t *want, unsigned int len,
471 enum write_granularity gran, const uint8_t erased_value)
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000472{
Stefan Tauner02437452013-04-01 19:34:53 +0000473 unsigned int i;
Nico Huberb77607f2023-01-16 02:25:45 +0100474 size_t stride;
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000475
476 switch (gran) {
477 case write_gran_1bit:
Nico Huberb77607f2023-01-16 02:25:45 +0100478 for (i = 0; i < len; i++) {
479 if ((have[i] & want[i]) != want[i])
480 return 1;
481 }
482 return 0;
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000483 case write_gran_1byte:
Nico Huberb77607f2023-01-16 02:25:45 +0100484 for (i = 0; i < len; i++) {
485 if ((have[i] != want[i]) && (have[i] != erased_value))
486 return 1;
487 }
488 return 0;
Carl-Daniel Hailfinger1b0e9fc2014-06-16 22:36:17 +0000489 case write_gran_1byte_implicit_erase:
490 /* Do not erase, handle content changes from anything->0xff by writing 0xff. */
Nico Huberb77607f2023-01-16 02:25:45 +0100491 return 0;
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000492 default:
Nico Huberb77607f2023-01-16 02:25:45 +0100493 stride = gran_to_bytes(gran);
494 if (stride) {
495 return need_erase_gran_bytes(have, want, len, stride, erased_value);
496 }
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000497 msg_cerr("%s: Unsupported granularity! Please report a bug at "
Nico Huberc3b02dc2023-08-12 01:13:45 +0200498 "flashprog@flashprog.org\n", __func__);
Nico Huberb77607f2023-01-16 02:25:45 +0100499 return 0;
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000500 }
Carl-Daniel Hailfingere8e369f2010-03-08 00:42:32 +0000501}
502
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000503/**
504 * Check if the buffer @have needs to be programmed to get the content of @want.
505 * If yes, return 1 and fill in first_start with the start address of the
506 * write operation and first_len with the length of the first to-be-written
507 * chunk. If not, return 0 and leave first_start and first_len undefined.
508 *
509 * Warning: This function assumes that @have and @want point to naturally
510 * aligned regions.
511 *
512 * @have buffer with current content
513 * @want buffer with desired content
514 * @len length of the checked area
515 * @gran write granularity (enum, not count)
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000516 * @first_start offset of the first byte which needs to be written (passed in
517 * value is increased by the offset of the first needed write
518 * relative to have/want or unchanged if no write is needed)
519 * @return length of the first contiguous area which needs to be written
520 * 0 if no write is needed
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000521 *
522 * FIXME: This function needs a parameter which tells it about coalescing
523 * in relation to the max write length of the programmer and the max write
524 * length of the chip.
525 */
Nico Huber3b9c86d2023-01-15 22:58:06 +0100526static unsigned int get_next_write(const uint8_t *have, const uint8_t *want, chipsize_t len,
527 chipoff_t *first_start, enum write_granularity gran)
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000528{
Felix Singerf25447e2022-08-19 02:44:28 +0200529 bool need_write = false;
Stefan Taunerc69c9c82011-11-23 09:13:48 +0000530 unsigned int rel_start = 0, first_len = 0;
Nico Huberb77607f2023-01-16 02:25:45 +0100531 unsigned int i, limit;
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000532
Nico Huberb77607f2023-01-16 02:25:45 +0100533 const size_t stride = gran_to_bytes(gran);
534 if (!stride) {
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000535 msg_cerr("%s: Unsupported granularity! Please report a bug at "
Nico Huberc3b02dc2023-08-12 01:13:45 +0200536 "flashprog@flashprog.org\n", __func__);
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000537 /* Claim that no write was needed. A write with unknown
538 * granularity is too dangerous to try.
539 */
540 return 0;
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000541 }
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000542 for (i = 0; i < len / stride; i++) {
543 limit = min(stride, len - i * stride);
544 /* Are 'have' and 'want' identical? */
545 if (memcmp(have + i * stride, want + i * stride, limit)) {
546 if (!need_write) {
547 /* First location where have and want differ. */
Felix Singerf25447e2022-08-19 02:44:28 +0200548 need_write = true;
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000549 rel_start = i * stride;
550 }
551 } else {
552 if (need_write) {
553 /* First location where have and want
554 * do not differ anymore.
555 */
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000556 break;
557 }
558 }
559 }
Carl-Daniel Hailfinger202bf532010-12-06 13:05:44 +0000560 if (need_write)
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000561 first_len = min(i * stride - rel_start, len);
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000562 *first_start += rel_start;
Carl-Daniel Hailfinger12d6d822010-11-05 14:51:59 +0000563 return first_len;
Carl-Daniel Hailfinger6e2ea322010-11-04 01:04:27 +0000564}
565
Nico Huber2d625722016-05-03 10:48:02 +0200566/*
567 * Return a string corresponding to the bustype parameter.
568 * Memory is obtained with malloc() and must be freed with free() by the caller.
569 */
570char *flashbuses_to_text(enum chipbustype bustype)
571{
572 char *ret = calloc(1, 1);
573 /*
574 * FIXME: Once all chipsets and flash chips have been updated, NONSPI
575 * will cease to exist and should be eliminated here as well.
576 */
Nico Huber0d2b45e2026-03-23 22:42:46 +0100577 if (bustype == BUS_PRESPI) {
Nico Huber2d625722016-05-03 10:48:02 +0200578 ret = strcat_realloc(ret, "Non-SPI, ");
579 } else {
580 if (bustype & BUS_PARALLEL)
581 ret = strcat_realloc(ret, "Parallel, ");
582 if (bustype & BUS_LPC)
583 ret = strcat_realloc(ret, "LPC, ");
584 if (bustype & BUS_FWH)
585 ret = strcat_realloc(ret, "FWH, ");
586 if (bustype & BUS_SPI)
587 ret = strcat_realloc(ret, "SPI, ");
Nico Huber0d2b45e2026-03-23 22:42:46 +0100588 if (bustype & BUS_OPAQUE)
Nico Huber2d625722016-05-03 10:48:02 +0200589 ret = strcat_realloc(ret, "Programmer-specific, ");
590 if (bustype == BUS_NONE)
591 ret = strcat_realloc(ret, "None, ");
592 }
593 /* Kill last comma. */
594 ret[strlen(ret) - 2] = '\0';
595 ret = realloc(ret, strlen(ret) + 1);
596 return ret;
597}
598
Stefan Tauner96658be2014-05-26 22:05:31 +0000599/* Even if an error is found, the function will keep going and check the rest. */
Nico Huber72d0ada2026-01-26 18:28:20 +0100600static int selfcheck_eraseblocks(const struct flashchip *chip, const char *label)
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000601{
Carl-Daniel Hailfinger082c8b52011-08-15 19:54:20 +0000602 int i, j, k;
603 int ret = 0;
Aarya Chaumal478e1792022-06-04 01:34:44 +0530604 unsigned int prev_eraseblock_count = chip->total_size * 1024;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000605
606 for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
607 unsigned int done = 0;
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +0000608 struct block_eraser eraser = chip->block_erasers[k];
Aarya Chaumal478e1792022-06-04 01:34:44 +0530609 unsigned int curr_eraseblock_count = 0;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000610
611 for (i = 0; i < NUM_ERASEREGIONS; i++) {
612 /* Blocks with zero size are bugs in flashchips.c. */
613 if (eraser.eraseblocks[i].count &&
614 !eraser.eraseblocks[i].size) {
Nico Huberac90af62022-12-18 00:22:47 +0000615 msg_gerr("ERROR: Flash chip %s erase function %i region %i has size 0.\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +0200616 "Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +0100617 label, k, i);
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000618 ret = 1;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000619 }
620 /* Blocks with zero count are bugs in flashchips.c. */
621 if (!eraser.eraseblocks[i].count &&
622 eraser.eraseblocks[i].size) {
Nico Huberac90af62022-12-18 00:22:47 +0000623 msg_gerr("ERROR: Flash chip %s erase function %i region %i has count 0.\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +0200624 "Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +0100625 label, k, i);
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000626 ret = 1;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000627 }
628 done += eraser.eraseblocks[i].count *
629 eraser.eraseblocks[i].size;
Aarya Chaumal478e1792022-06-04 01:34:44 +0530630 curr_eraseblock_count += eraser.eraseblocks[i].count;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000631 }
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000632 /* Empty eraseblock definition with erase function. */
633 if (!done && eraser.block_erase)
Sean Nelson316a29f2010-05-07 20:09:04 +0000634 msg_gspew("Strange: Empty eraseblock definition with "
Uwe Hermann91f4afa2011-07-28 08:13:25 +0000635 "non-empty erase function. Not an error.\n");
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000636 if (!done)
637 continue;
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +0000638 if (done != chip->total_size * 1024) {
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000639 msg_gerr("ERROR: Flash chip %s erase function %i "
640 "region walking resulted in 0x%06x bytes total,"
Nico Huberac90af62022-12-18 00:22:47 +0000641 " expected 0x%06x bytes.\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +0200642 "Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +0100643 label, k, done, chip->total_size * 1024);
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000644 ret = 1;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000645 }
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000646 if (!eraser.block_erase)
647 continue;
648 /* Check if there are identical erase functions for different
649 * layouts. That would imply "magic" erase functions. The
650 * easiest way to check this is with function pointers.
651 */
Uwe Hermann43959702010-03-13 17:28:29 +0000652 for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000653 if (eraser.block_erase ==
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +0000654 chip->block_erasers[j].block_erase) {
Nico Huberac90af62022-12-18 00:22:47 +0000655 msg_gerr("ERROR: Flash chip %s erase function %i and %i are identical.\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +0200656 "Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +0100657 label, k, j);
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000658 ret = 1;
659 }
Uwe Hermann43959702010-03-13 17:28:29 +0000660 }
Aarya Chaumal478e1792022-06-04 01:34:44 +0530661 if(curr_eraseblock_count > prev_eraseblock_count)
662 {
Nico Huberac90af62022-12-18 00:22:47 +0000663 msg_gerr("ERROR: Flash chip %s erase function %i is not in order.\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +0200664 "Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +0100665 label, k);
Aarya Chaumal478e1792022-06-04 01:34:44 +0530666 ret = 1;
667 }
668 prev_eraseblock_count = curr_eraseblock_count;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000669 }
Carl-Daniel Hailfinger415afcf2010-01-19 06:42:46 +0000670 return ret;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +0000671}
672
Carl-Daniel Hailfinger63fd9022011-12-14 22:25:15 +0000673static int check_block_eraser(const struct flashctx *flash, int k, int log)
Carl-Daniel Hailfingerdce73ae2010-12-05 15:14:44 +0000674{
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +0000675 struct block_eraser eraser = flash->chip->block_erasers[k];
Carl-Daniel Hailfingerdce73ae2010-12-05 15:14:44 +0000676
677 if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
678 if (log)
679 msg_cdbg("not defined. ");
680 return 1;
681 }
682 if (!eraser.block_erase && eraser.eraseblocks[0].count) {
683 if (log)
684 msg_cdbg("eraseblock layout is known, but matching "
Stefan Tauner355cbfd2011-05-28 02:37:14 +0000685 "block erase function is not implemented. ");
Carl-Daniel Hailfingerdce73ae2010-12-05 15:14:44 +0000686 return 1;
687 }
688 if (eraser.block_erase && !eraser.eraseblocks[0].count) {
689 if (log)
690 msg_cdbg("block erase function found, but "
Stefan Tauner355cbfd2011-05-28 02:37:14 +0000691 "eraseblock layout is not defined. ");
Carl-Daniel Hailfingerdce73ae2010-12-05 15:14:44 +0000692 return 1;
693 }
Aarya Chaumal6d98aec2022-08-14 23:16:44 +0530694
Nico Hubere149fbe2024-08-21 10:23:53 +0200695 if (flash->chip->bustype == BUS_SPI && flash->chip->spi_cmd_set == SPI25) {
Nico Huber13389362024-03-05 18:35:30 +0100696 bool native_4ba;
Nico Huber13f97a52023-01-14 23:55:06 +0100697 int i;
Nico Huber13389362024-03-05 18:35:30 +0100698
699 const uint8_t *opcode = spi_get_opcode_from_erasefn(eraser.block_erase, &native_4ba);
Nico Huber07ebc682024-08-21 10:18:27 +0200700 if (!opcode)
701 return 1;
702
Nico Huber13f97a52023-01-14 23:55:06 +0100703 for (i = 0; opcode[i]; i++) {
Nico Huber13389362024-03-05 18:35:30 +0100704 if ((native_4ba && !spi_master_4ba(flash)) ||
Nico Huber9a11cbf2023-01-13 01:19:07 +0100705 !flash->mst.spi->probe_opcode(flash, opcode[i])) {
Aarya Chaumal6d98aec2022-08-14 23:16:44 +0530706 if (log)
707 msg_cdbg("block erase function and layout found "
708 "but SPI master doesn't support the function. ");
709 return 1;
710 }
711 }
712 }
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +0000713 // TODO: Once erase functions are annotated with allowed buses, check that as well.
Carl-Daniel Hailfingerdce73ae2010-12-05 15:14:44 +0000714 return 0;
715}
716
Nico Huber7af0e792016-04-29 16:40:15 +0200717/**
718 * @brief Reads the included layout regions into a buffer.
719 *
720 * If there is no layout set in the given flash context, the whole chip will
721 * be read.
722 *
723 * @param flashctx Flash context to be used.
724 * @param buffer Buffer of full chip size to read into.
725 * @return 0 on success,
726 * 1 if any read fails.
727 */
728static int read_by_layout(struct flashctx *const flashctx, uint8_t *const buffer)
729{
Nico Huberc3b02dc2023-08-12 01:13:45 +0200730 const struct flashprog_layout *const layout = get_layout(flashctx);
Nico Huber5ca55232019-06-15 22:29:08 +0200731 const struct romentry *entry = NULL;
Nico Huber7af0e792016-04-29 16:40:15 +0200732
Richard Hughes842d6782021-01-15 09:48:12 +0000733 flashprog_progress_start_by_layout(flashctx, FLASHPROG_PROGRESS_READ, layout);
734
Nico Huber5ca55232019-06-15 22:29:08 +0200735 while ((entry = layout_next_included(layout, entry))) {
736 const chipoff_t region_start = entry->start;
737 const chipsize_t region_len = entry->end - entry->start + 1;
Nico Huber7af0e792016-04-29 16:40:15 +0200738
739 if (flashctx->chip->read(flashctx, buffer + region_start, region_start, region_len))
740 return 1;
741 }
Richard Hughes842d6782021-01-15 09:48:12 +0000742
743 flashprog_progress_finish(flashctx);
744
Nico Huber7af0e792016-04-29 16:40:15 +0200745 return 0;
746}
747
Nico Huber7af0e792016-04-29 16:40:15 +0200748/**
749 * @private
750 *
751 * For read-erase-write, `curcontents` and `newcontents` shall point
752 * to buffers of the chip's size. Both are supposed to be prefilled
753 * with at least the included layout regions of the current flash
754 * contents (`curcontents`) and the data to be written to the flash
755 * (`newcontents`).
756 *
757 * For erase, `curcontents` and `newcontents` shall be NULL-pointers.
758 *
759 * The `chipoff_t` values are used internally by `walk_by_layout()`.
760 */
761struct walk_info {
762 uint8_t *curcontents;
763 const uint8_t *newcontents;
764 chipoff_t region_start;
765 chipoff_t region_end;
766 chipoff_t erase_start;
767 chipoff_t erase_end;
768};
Nico Huber3b9c86d2023-01-15 22:58:06 +0100769
Nico Huberf9666632026-06-16 12:53:27 +0200770/** @private */
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530771struct eraseblock_data {
772 chipoff_t start_addr;
773 chipoff_t end_addr;
774 bool selected;
775 size_t block_num;
776 size_t first_sub_block_index;
777 size_t last_sub_block_index;
778};
779
Nico Huberf9666632026-06-16 12:53:27 +0200780/** @private */
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530781struct erase_layout {
782 struct eraseblock_data* layout_list;
783 size_t block_count;
784 const struct block_eraser *eraser;
785};
786
Nico Huber5ff6fdc2023-01-15 23:43:12 +0100787static bool explicit_erase(const struct walk_info *const info)
788{
789 /* For explicit erase, we are called without new contents. */
790 return !info->newcontents;
791}
792
Nico Huberd96e7032023-01-14 22:31:48 +0100793static size_t calculate_block_count(const struct block_eraser *const eraser)
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530794{
Nico Huberd96e7032023-01-14 22:31:48 +0100795 size_t block_count = 0, i;
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530796
Nico Huberd96e7032023-01-14 22:31:48 +0100797 for (i = 0; i < ARRAY_SIZE(eraser->eraseblocks); ++i)
798 block_count += eraser->eraseblocks[i].count;
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530799
800 return block_count;
801}
802
803static void init_eraseblock(struct erase_layout *layout, size_t idx, size_t block_num,
804 chipoff_t start_addr, chipoff_t end_addr, size_t *sub_block_index)
805{
806 struct eraseblock_data *edata = &layout[idx].layout_list[block_num];
807 edata->start_addr = start_addr;
808 edata->end_addr = end_addr;
809 edata->selected = false;
810 edata->block_num = block_num;
811
812 if (!idx)
813 return;
Nico Hubera02df332023-01-14 23:06:27 +0100814 const struct erase_layout *const sub_layout = &layout[idx - 1];
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530815
816 edata->first_sub_block_index = *sub_block_index;
Nico Hubera02df332023-01-14 23:06:27 +0100817 for (; *sub_block_index < sub_layout->block_count; ++*sub_block_index) {
818 if (sub_layout->layout_list[*sub_block_index].end_addr > end_addr)
819 break;
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530820 }
821 edata->last_sub_block_index = *sub_block_index - 1;
822}
823
824/*
825 * @brief Function to free the created erase_layout
826 *
827 * @param layout pointer to allocated layout
828 * @param erasefn_count number of erase functions for which the layout was created
829 *
830 */
831static void free_erase_layout(struct erase_layout *layout, unsigned int erasefn_count)
832{
Nico Huber13f97a52023-01-14 23:55:06 +0100833 size_t i;
834
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530835 if (!layout)
836 return;
Nico Huber13f97a52023-01-14 23:55:06 +0100837 for (i = 0; i < erasefn_count; i++) {
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530838 free(layout[i].layout_list);
839 }
840 free(layout);
841}
842
843/*
844 * @brief Function to create an erase layout
845 *
846 * @param flashctx flash context
847 * @param e_layout address to the pointer to store the layout
848 * @return 0 on success,
849 * -1 if layout creation fails
850 *
851 * This function creates a layout of which erase functions erase which regions
852 * of the flash chip. This helps to optimally select the erase functions for
853 * erase/write operations.
854 */
Nico Huberc09fca42023-01-29 15:58:09 +0100855static int create_erase_layout(struct flashctx *const flashctx, struct erase_layout **e_layout)
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530856{
857 const struct flashchip *chip = flashctx->chip;
Nico Huberbb8ab372026-03-14 11:46:02 +0100858 const size_t erasefn_count = flashprog_count_usable_erasers(flashctx);
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530859
860 if (!erasefn_count) {
861 msg_gerr("No erase functions supported\n");
862 return 0;
863 }
864
Nico Huberd34864b2023-01-14 23:47:19 +0100865 struct erase_layout *layout = calloc(erasefn_count, sizeof(struct erase_layout));
866 if (!layout) {
867 msg_gerr("Out of memory!\n");
868 return -1;
869 }
870
Nico Huber13f97a52023-01-14 23:55:06 +0100871 size_t layout_idx = 0, eraser_idx;
872 for (eraser_idx = 0; eraser_idx < NUM_ERASEFUNCTIONS; eraser_idx++) {
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530873 if (check_block_eraser(flashctx, eraser_idx, 0))
874 continue;
875
876 layout[layout_idx].eraser = &chip->block_erasers[eraser_idx];
Nico Huberd96e7032023-01-14 22:31:48 +0100877 const size_t block_count = calculate_block_count(&chip->block_erasers[eraser_idx]);
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530878 size_t sub_block_index = 0;
879
880 layout[layout_idx].block_count = block_count;
881 layout[layout_idx].layout_list = (struct eraseblock_data *)calloc(block_count,
882 sizeof(struct eraseblock_data));
883
884 if (!layout[layout_idx].layout_list) {
885 free_erase_layout(layout, layout_idx);
886 return -1;
887 }
888
889 size_t block_num = 0;
890 chipoff_t start_addr = 0;
891
Nico Huber13f97a52023-01-14 23:55:06 +0100892 int i;
893 for (i = 0; block_num < block_count; i++) {
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530894 const struct eraseblock *block = &chip->block_erasers[eraser_idx].eraseblocks[i];
895
Nico Huber13f97a52023-01-14 23:55:06 +0100896 size_t num;
897 for (num = 0; num < block->count; num++) {
Aarya Chaumal18cc8d32022-07-15 16:51:27 +0530898 chipoff_t end_addr = start_addr + block->size - 1;
899 init_eraseblock(layout, layout_idx, block_num,
900 start_addr, end_addr, &sub_block_index);
901 block_num += 1;
902 start_addr = end_addr + 1;
903 }
904 }
905 layout_idx++;
906 }
907
908 *e_layout = layout;
909 return layout_idx;
910}
911
Nico Huber20073e72024-05-10 01:31:40 +0200912static void deselect_erase_block_rec(const struct erase_layout *layout, size_t findex, size_t block_num)
913{
914 struct eraseblock_data *const ed = &layout[findex].layout_list[block_num];
915 size_t i;
916
917 if (ed->selected) {
918 ed->selected = false;
919 } else if (findex > 0) {
920 for (i = ed->first_sub_block_index; i <= ed->last_sub_block_index; ++i)
921 deselect_erase_block_rec(layout, findex - 1, i);
922 }
923}
924
Aarya Chaumald33bea42022-07-14 12:51:14 +0530925/*
926 * @brief Function to select the list of sectors that need erasing
927 *
928 * @param flashctx flash context
929 * @param layout erase layout
930 * @param findex index of the erase function
931 * @param block_num index of the block to erase according to the erase function index
Nico Huber00d1b9f2023-01-29 15:07:33 +0100932 * @param info current info from walking the regions
Nico Huberaa714dd2023-04-22 14:59:33 +0200933 * @return number of bytes selected for erase
Aarya Chaumald33bea42022-07-14 12:51:14 +0530934 */
Nico Huberaa714dd2023-04-22 14:59:33 +0200935static size_t select_erase_functions_rec(const struct flashctx *flashctx, const struct erase_layout *layout,
936 size_t findex, size_t block_num, const struct walk_info *info)
Aarya Chaumald33bea42022-07-14 12:51:14 +0530937{
938 struct eraseblock_data *ll = &layout[findex].layout_list[block_num];
Nico Huberaa714dd2023-04-22 14:59:33 +0200939 const size_t eraseblock_size = ll->end_addr - ll->start_addr + 1;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530940 if (!findex) {
Nico Hubercf6ff0a2023-01-29 15:45:06 +0100941 if (ll->start_addr <= info->region_end && ll->end_addr >= info->region_start) {
Nico Huber1494f8e2023-01-29 15:48:00 +0100942 if (explicit_erase(info)) {
943 ll->selected = true;
Nico Huberaa714dd2023-04-22 14:59:33 +0200944 return eraseblock_size;
Nico Huber1494f8e2023-01-29 15:48:00 +0100945 }
Nico Hubera6212482023-01-29 15:39:26 +0100946 const chipoff_t write_start = MAX(info->region_start, ll->start_addr);
947 const chipoff_t write_end = MIN(info->region_end, ll->end_addr);
948 const chipsize_t write_len = write_end - write_start + 1;
949 const uint8_t erased_value = ERASED_VALUE(flashctx);
Nico Huber00d1b9f2023-01-29 15:07:33 +0100950 ll->selected = need_erase(
Nico Hubera6212482023-01-29 15:39:26 +0100951 info->curcontents + write_start, info->newcontents + write_start,
952 write_len, flashctx->chip->gran, erased_value);
Nico Huberaa714dd2023-04-22 14:59:33 +0200953 if (ll->selected)
954 return eraseblock_size;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530955 }
Nico Huberaa714dd2023-04-22 14:59:33 +0200956 return 0;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530957 } else {
Aarya Chaumald33bea42022-07-14 12:51:14 +0530958 const int sub_block_start = ll->first_sub_block_index;
959 const int sub_block_end = ll->last_sub_block_index;
Nico Huberaa714dd2023-04-22 14:59:33 +0200960 size_t bytes = 0;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530961
Nico Huber13f97a52023-01-14 23:55:06 +0100962 int j;
Nico Huberaa714dd2023-04-22 14:59:33 +0200963 for (j = sub_block_start; j <= sub_block_end; j++)
964 bytes += select_erase_functions_rec(flashctx, layout, findex - 1, j, info);
Aarya Chaumald33bea42022-07-14 12:51:14 +0530965
Nico Huberaa714dd2023-04-22 14:59:33 +0200966 if (bytes > eraseblock_size / 2) {
Nico Huber00d1b9f2023-01-29 15:07:33 +0100967 if (ll->start_addr >= info->region_start && ll->end_addr <= info->region_end) {
Nico Huber20073e72024-05-10 01:31:40 +0200968 deselect_erase_block_rec(layout, findex, block_num);
Aarya Chaumald33bea42022-07-14 12:51:14 +0530969 ll->selected = true;
Nico Huberaa714dd2023-04-22 14:59:33 +0200970 bytes = eraseblock_size;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530971 }
972 }
Nico Huberaa714dd2023-04-22 14:59:33 +0200973 return bytes;
Aarya Chaumald33bea42022-07-14 12:51:14 +0530974 }
975}
976
Nico Huberaa714dd2023-04-22 14:59:33 +0200977static size_t select_erase_functions(const struct flashctx *flashctx, const struct erase_layout *layout,
978 size_t erasefn_count, const struct walk_info *info)
Nico Huberb11b72c2023-01-29 15:33:11 +0100979{
Nico Huberaa714dd2023-04-22 14:59:33 +0200980 size_t bytes = 0;
Nico Huberb11b72c2023-01-29 15:33:11 +0100981 size_t block_num;
982 for (block_num = 0; block_num < layout[erasefn_count - 1].block_count; ++block_num)
Nico Huberaa714dd2023-04-22 14:59:33 +0200983 bytes += select_erase_functions_rec(flashctx, layout, erasefn_count - 1, block_num, info);
984 return bytes;
Nico Huberb11b72c2023-01-29 15:33:11 +0100985}
986
Nico Huber3b9c86d2023-01-15 22:58:06 +0100987static int write_range(struct flashctx *const flashctx, const chipoff_t flash_offset,
988 const uint8_t *const curcontents, const uint8_t *const newcontents,
989 const chipsize_t len, bool *const skipped)
990{
991 unsigned int writecount = 0;
992 chipoff_t starthere = 0;
993 chipsize_t lenhere = 0;
994
995 while ((lenhere = get_next_write(curcontents + starthere, newcontents + starthere,
996 len - starthere, &starthere, flashctx->chip->gran))) {
997 if (!writecount++)
998 msg_cdbg("W");
999 if (flashctx->chip->write(flashctx, newcontents + starthere,
1000 flash_offset + starthere, lenhere))
1001 return 1;
1002 starthere += lenhere;
Richard Hughes842d6782021-01-15 09:48:12 +00001003 if (skipped) {
1004 flashprog_progress_set(flashctx, starthere);
Nico Huber3b9c86d2023-01-15 22:58:06 +01001005 *skipped = false;
Richard Hughes842d6782021-01-15 09:48:12 +00001006 }
Nico Huber3b9c86d2023-01-15 22:58:06 +01001007 }
1008 return 0;
1009}
1010
1011typedef int (*erasefn_t)(struct flashctx *, unsigned int addr, unsigned int len);
Nico Huber7af0e792016-04-29 16:40:15 +02001012/* returns 0 on success, 1 to retry with another erase function, 2 for immediate abort */
1013typedef int (*per_blockfn_t)(struct flashctx *, const struct walk_info *, erasefn_t);
1014
1015static int walk_eraseblocks(struct flashctx *const flashctx,
Nico Huberc09fca42023-01-29 15:58:09 +01001016 struct erase_layout *const layouts,
1017 const size_t layout_count,
Nico Huber7af0e792016-04-29 16:40:15 +02001018 struct walk_info *const info,
Nico Huberc09fca42023-01-29 15:58:09 +01001019 const per_blockfn_t per_blockfn)
Nico Huber7af0e792016-04-29 16:40:15 +02001020{
1021 int ret;
1022 size_t i, j;
1023 bool first = true;
Nico Huber7af0e792016-04-29 16:40:15 +02001024
Nico Huberc09fca42023-01-29 15:58:09 +01001025 for (i = 0; i < layout_count; ++i) {
1026 const struct erase_layout *const layout = &layouts[i];
Nico Huber7af0e792016-04-29 16:40:15 +02001027
Nico Huberc09fca42023-01-29 15:58:09 +01001028 for (j = 0; j < layout->block_count; ++j) {
1029 struct eraseblock_data *const eb = &layout->layout_list[j];
1030
1031 if (eb->start_addr > info->region_end)
Nico Huber7af0e792016-04-29 16:40:15 +02001032 break;
Nico Huberc09fca42023-01-29 15:58:09 +01001033 if (eb->end_addr < info->region_start)
1034 continue;
1035 if (!eb->selected)
1036 continue;
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001037
Nico Huber7af0e792016-04-29 16:40:15 +02001038 /* Print this for every block except the first one. */
1039 if (first)
1040 first = false;
1041 else
1042 msg_cdbg(", ");
Nico Huberc09fca42023-01-29 15:58:09 +01001043 msg_cdbg("0x%06x-0x%06x:", eb->start_addr, eb->end_addr);
Nico Huber7af0e792016-04-29 16:40:15 +02001044
Nico Huberc09fca42023-01-29 15:58:09 +01001045 info->erase_start = eb->start_addr;
1046 info->erase_end = eb->end_addr;
1047 ret = per_blockfn(flashctx, info, layout->eraser->block_erase);
Nico Huber7af0e792016-04-29 16:40:15 +02001048 if (ret)
1049 return ret;
Nico Huberc09fca42023-01-29 15:58:09 +01001050
1051 /* Clean the erase layout up for future use on other
1052 regions. `.selected` is the only field we alter. */
1053 eb->selected = false;
Nico Huber7af0e792016-04-29 16:40:15 +02001054 }
Nico Huber7af0e792016-04-29 16:40:15 +02001055 }
1056 msg_cdbg("\n");
1057 return 0;
1058}
1059
1060static int walk_by_layout(struct flashctx *const flashctx, struct walk_info *const info,
1061 const per_blockfn_t per_blockfn)
1062{
Nico Huberc09fca42023-01-29 15:58:09 +01001063 const bool do_erase = explicit_erase(info) || !(flashctx->chip->feature_bits & FEATURE_NO_ERASE);
Nico Huberc3b02dc2023-08-12 01:13:45 +02001064 const struct flashprog_layout *const layout = get_layout(flashctx);
Nico Huberc09fca42023-01-29 15:58:09 +01001065 struct erase_layout *erase_layouts = NULL;
Nico Huber5ca55232019-06-15 22:29:08 +02001066 const struct romentry *entry = NULL;
Nico Huberc09fca42023-01-29 15:58:09 +01001067 int ret = 0, layout_count = 0;
Nico Huber7af0e792016-04-29 16:40:15 +02001068
1069 all_skipped = true;
Nico Huberc6a924a2024-09-04 15:09:52 +02001070 msg_cinfo("Erasing %sflash chip... ", info->newcontents ? "and writing " : "");
Nico Huber7af0e792016-04-29 16:40:15 +02001071
Nico Huberc09fca42023-01-29 15:58:09 +01001072 if (do_erase) {
1073 layout_count = create_erase_layout(flashctx, &erase_layouts);
1074 if (layout_count <= 0)
1075 return 1;
1076 }
1077
Nico Huber5ca55232019-06-15 22:29:08 +02001078 while ((entry = layout_next_included(layout, entry))) {
1079 info->region_start = entry->start;
1080 info->region_end = entry->end;
Nico Huber7af0e792016-04-29 16:40:15 +02001081
Nico Huberc09fca42023-01-29 15:58:09 +01001082 if (do_erase) {
Richard Hughes842d6782021-01-15 09:48:12 +00001083 const size_t total = select_erase_functions(flashctx, erase_layouts, layout_count, info);
1084
1085 /* We verify every erased block manually. Technically that's
1086 reading, but accounting for it as part of the erase helps
1087 to provide a smooth, overall progress. Hence `total * 2`. */
1088 flashprog_progress_start(flashctx, FLASHPROG_PROGRESS_ERASE, total * 2);
1089
Nico Huberc09fca42023-01-29 15:58:09 +01001090 ret = walk_eraseblocks(flashctx, erase_layouts, layout_count, info, per_blockfn);
1091 if (ret) {
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001092 msg_cerr("FAILED!\n");
Nico Huberc09fca42023-01-29 15:58:09 +01001093 goto free_ret;
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001094 }
Richard Hughes842d6782021-01-15 09:48:12 +00001095
1096 flashprog_progress_finish(flashctx);
Nico Huber7af0e792016-04-29 16:40:15 +02001097 }
Nico Huberd34af7a2023-01-15 23:58:18 +01001098
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001099 if (info->newcontents) {
1100 bool skipped = true;
1101 msg_cdbg("0x%06x-0x%06x:", info->region_start, info->region_end);
Richard Hughes842d6782021-01-15 09:48:12 +00001102 flashprog_progress_start(flashctx, FLASHPROG_PROGRESS_WRITE,
1103 info->region_end - info->region_start + 1);
Nico Huberc09fca42023-01-29 15:58:09 +01001104 ret = write_range(flashctx, info->region_start,
1105 info->curcontents + info->region_start,
1106 info->newcontents + info->region_start,
1107 info->region_end + 1 - info->region_start, &skipped);
1108 if (ret) {
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001109 msg_cerr("FAILED!\n");
Nico Huberc09fca42023-01-29 15:58:09 +01001110 goto free_ret;
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001111 }
Richard Hughes842d6782021-01-15 09:48:12 +00001112 flashprog_progress_finish(flashctx);
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001113 if (skipped) {
1114 msg_cdbg("S\n");
1115 } else {
1116 msg_cdbg("\n");
1117 all_skipped = false;
1118 }
Nico Huberd34af7a2023-01-15 23:58:18 +01001119 }
Nico Huber7af0e792016-04-29 16:40:15 +02001120 }
1121 if (all_skipped)
1122 msg_cinfo("\nWarning: Chip content is identical to the requested image.\n");
Nico Huberc6a924a2024-09-04 15:09:52 +02001123 msg_cinfo("Erase%s done.\n", info->newcontents ? "/write" : "");
Nico Huberc09fca42023-01-29 15:58:09 +01001124
1125free_ret:
1126 free_erase_layout(erase_layouts, layout_count);
1127 return ret;
Nico Huber7af0e792016-04-29 16:40:15 +02001128}
1129
1130static int erase_block(struct flashctx *const flashctx,
1131 const struct walk_info *const info, const erasefn_t erasefn)
1132{
1133 const unsigned int erase_len = info->erase_end + 1 - info->erase_start;
Nico Huber6e61e0c2019-01-23 17:07:49 +01001134 const bool region_unaligned = info->region_start > info->erase_start ||
1135 info->erase_end > info->region_end;
1136 uint8_t *backup_contents = NULL, *erased_contents = NULL;
Nico Huberd34af7a2023-01-15 23:58:18 +01001137 int ret = 1;
Nico Huber7af0e792016-04-29 16:40:15 +02001138
Nico Huber6e61e0c2019-01-23 17:07:49 +01001139 /*
1140 * If the region is not erase-block aligned, merge current flash con-
1141 * tents into a new buffer `backup_contents`.
1142 */
1143 if (region_unaligned) {
1144 backup_contents = malloc(erase_len);
1145 erased_contents = malloc(erase_len);
1146 if (!backup_contents || !erased_contents) {
1147 msg_cerr("Out of memory!\n");
Nico Huber6e61e0c2019-01-23 17:07:49 +01001148 goto _free_ret;
1149 }
1150 memset(backup_contents, ERASED_VALUE(flashctx), erase_len);
1151 memset(erased_contents, ERASED_VALUE(flashctx), erase_len);
1152
1153 msg_cdbg("R");
1154 /* Merge data preceding the current region. */
1155 if (info->region_start > info->erase_start) {
1156 const chipoff_t start = info->erase_start;
1157 const chipsize_t len = info->region_start - info->erase_start;
1158 if (flashctx->chip->read(flashctx, backup_contents, start, len)) {
1159 msg_cerr("Can't read! Aborting.\n");
1160 goto _free_ret;
1161 }
1162 }
1163 /* Merge data following the current region. */
1164 if (info->erase_end > info->region_end) {
1165 const chipoff_t start = info->region_end + 1;
1166 const chipoff_t rel_start = start - info->erase_start; /* within this erase block */
1167 const chipsize_t len = info->erase_end - info->region_end;
1168 if (flashctx->chip->read(flashctx, backup_contents + rel_start, start, len)) {
1169 msg_cerr("Can't read! Aborting.\n");
1170 goto _free_ret;
1171 }
1172 }
1173 }
1174
Nico Huber7af0e792016-04-29 16:40:15 +02001175 all_skipped = false;
1176
1177 msg_cdbg("E");
1178 if (erasefn(flashctx, info->erase_start, erase_len))
Nico Huber6e61e0c2019-01-23 17:07:49 +01001179 goto _free_ret;
Richard Hughes842d6782021-01-15 09:48:12 +00001180 flashprog_progress_add(flashctx, erase_len);
Nico Huber7af0e792016-04-29 16:40:15 +02001181 if (check_erased_range(flashctx, info->erase_start, erase_len)) {
1182 msg_cerr("ERASE FAILED!\n");
Nico Huber6e61e0c2019-01-23 17:07:49 +01001183 goto _free_ret;
Nico Huber7af0e792016-04-29 16:40:15 +02001184 }
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001185 if (info->curcontents)
1186 memset(info->curcontents + info->erase_start, ERASED_VALUE(flashctx), erase_len);
Nico Huber6e61e0c2019-01-23 17:07:49 +01001187
1188 if (region_unaligned) {
Nico Huber3b9c86d2023-01-15 22:58:06 +01001189 if (write_range(flashctx, info->erase_start, erased_contents, backup_contents, erase_len, NULL))
1190 goto _free_ret;
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001191 if (info->curcontents)
1192 memcpy(info->curcontents + info->erase_start, backup_contents, erase_len);
Nico Huber6e61e0c2019-01-23 17:07:49 +01001193 }
1194
1195 ret = 0;
1196
1197_free_ret:
1198 free(erased_contents);
1199 free(backup_contents);
1200 return ret;
Nico Huber7af0e792016-04-29 16:40:15 +02001201}
1202
1203/**
1204 * @brief Erases the included layout regions.
1205 *
1206 * If there is no layout set in the given flash context, the whole chip will
1207 * be erased.
1208 *
1209 * @param flashctx Flash context to be used.
Nico Huber7af0e792016-04-29 16:40:15 +02001210 * @return 0 on success,
1211 * 1 if all available erase functions failed.
1212 */
Nico Huber454f6132012-12-10 13:34:10 +00001213static int erase_by_layout(struct flashctx *const flashctx)
Nico Huber7af0e792016-04-29 16:40:15 +02001214{
1215 struct walk_info info = { 0 };
1216 return walk_by_layout(flashctx, &info, &erase_block);
1217}
1218
Nico Huber7af0e792016-04-29 16:40:15 +02001219/**
1220 * @brief Writes the included layout regions from a given image.
1221 *
1222 * If there is no layout set in the given flash context, the whole image
1223 * will be written.
1224 *
1225 * @param flashctx Flash context to be used.
1226 * @param curcontents A buffer of full chip size with current chip contents of included regions.
1227 * @param newcontents The new image to be written.
1228 * @return 0 on success,
1229 * 1 if anything has gone wrong.
1230 */
Nico Huber454f6132012-12-10 13:34:10 +00001231static int write_by_layout(struct flashctx *const flashctx,
1232 void *const curcontents, const void *const newcontents)
Nico Huber7af0e792016-04-29 16:40:15 +02001233{
1234 struct walk_info info;
1235 info.curcontents = curcontents;
1236 info.newcontents = newcontents;
Nico Huber5ff6fdc2023-01-15 23:43:12 +01001237 return walk_by_layout(flashctx, &info, erase_block);
Nico Huber7af0e792016-04-29 16:40:15 +02001238}
1239
1240/**
1241 * @brief Compares the included layout regions with content from a buffer.
1242 *
1243 * If there is no layout set in the given flash context, the whole chip's
1244 * contents will be compared.
1245 *
1246 * @param flashctx Flash context to be used.
Nico Huber74d09d42019-06-16 03:27:26 +02001247 * @param layout Flash layout information.
Nico Huber7af0e792016-04-29 16:40:15 +02001248 * @param curcontents A buffer of full chip size to read current chip contents into.
1249 * @param newcontents The new image to compare to.
1250 * @return 0 on success,
1251 * 1 if reading failed,
1252 * 3 if the contents don't match.
1253 */
Nico Huber74d09d42019-06-16 03:27:26 +02001254static int verify_by_layout(
1255 struct flashctx *const flashctx,
Nico Huberc3b02dc2023-08-12 01:13:45 +02001256 const struct flashprog_layout *const layout,
Nico Huber74d09d42019-06-16 03:27:26 +02001257 void *const curcontents, const uint8_t *const newcontents)
Nico Huber7af0e792016-04-29 16:40:15 +02001258{
Nico Huber5ca55232019-06-15 22:29:08 +02001259 const struct romentry *entry = NULL;
Nico Huber7af0e792016-04-29 16:40:15 +02001260
Richard Hughes842d6782021-01-15 09:48:12 +00001261 flashprog_progress_start_by_layout(flashctx, FLASHPROG_PROGRESS_READ, layout);
1262
Nico Huber5ca55232019-06-15 22:29:08 +02001263 while ((entry = layout_next_included(layout, entry))) {
1264 const chipoff_t region_start = entry->start;
1265 const chipsize_t region_len = entry->end - entry->start + 1;
Nico Huber7af0e792016-04-29 16:40:15 +02001266
1267 if (flashctx->chip->read(flashctx, curcontents + region_start, region_start, region_len))
1268 return 1;
1269 if (compare_range(newcontents + region_start, curcontents + region_start,
1270 region_start, region_len))
1271 return 3;
1272 }
Richard Hughes842d6782021-01-15 09:48:12 +00001273
1274 flashprog_progress_finish(flashctx);
1275
Nico Huber7af0e792016-04-29 16:40:15 +02001276 return 0;
1277}
1278
Stefan Tauner136388f2013-07-15 10:47:53 +00001279static void nonfatal_help_message(void)
Carl-Daniel Hailfinger42d38a92010-10-19 22:06:20 +00001280{
Stefan Taunera58f6e92014-05-10 09:25:44 +00001281 msg_gerr("Good, writing to the flash chip apparently didn't do anything.\n");
Stefan Tauner136388f2013-07-15 10:47:53 +00001282#if CONFIG_INTERNAL == 1
Thomas Heijligenc7e5b8b2021-06-01 14:21:41 +02001283 if (programmer == &programmer_internal)
Stefan Tauner136388f2013-07-15 10:47:53 +00001284 msg_gerr("This means we have to add special support for your board, programmer or flash\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +02001285 "chip. Please report this to the mailing list at flashprog@flashprog.org or\n"
1286 "on IRC (see https://www.flashprog.org/Contact for details), thanks!\n"
Stefan Tauner136388f2013-07-15 10:47:53 +00001287 "-------------------------------------------------------------------------------\n"
1288 "You may now reboot or simply leave the machine running.\n");
1289 else
1290#endif
1291 msg_gerr("Please check the connections (especially those to write protection pins) between\n"
Nico Huberc3b02dc2023-08-12 01:13:45 +02001292 "the programmer and the flash chip. If you think the error is caused by flashprog\n"
1293 "please report this to the mailing list at flashprog@flashprog.org or on IRC\n"
1294 "(see https://www.flashprog.org/Contact for details), thanks!\n");
Carl-Daniel Hailfinger42d38a92010-10-19 22:06:20 +00001295}
1296
Edward O'Callaghanc72d20a2021-12-13 12:30:03 +11001297void emergency_help_message(void)
Carl-Daniel Hailfinger8ab49e72009-08-19 13:55:34 +00001298{
Stefan Tauner136388f2013-07-15 10:47:53 +00001299 msg_gerr("Your flash chip is in an unknown state.\n");
1300#if CONFIG_INTERNAL == 1
Thomas Heijligenc7e5b8b2021-06-01 14:21:41 +02001301 if (programmer == &programmer_internal)
Nico Huberc3b02dc2023-08-12 01:13:45 +02001302 msg_gerr("Get help on IRC (see https://www.flashprog.org/Contact) or mail\n"
1303 "flashprog@flashprog.org with the subject \"FAILED: <your board name>\"!\n"
Stefan Tauner136388f2013-07-15 10:47:53 +00001304 "-------------------------------------------------------------------------------\n"
1305 "DO NOT REBOOT OR POWEROFF!\n");
1306 else
1307#endif
Nico Huberc3b02dc2023-08-12 01:13:45 +02001308 msg_gerr("Please report this to the mailing list at flashprog@flashprog.org\n"
1309 "or on IRC (see https://www.flashprog.org/Contact for details), thanks!\n");
Carl-Daniel Hailfinger8ab49e72009-08-19 13:55:34 +00001310}
1311
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001312void list_programmers_linebreak(int startcol, int cols, int paren)
1313{
1314 const char *pname;
Carl-Daniel Hailfinger082c8b52011-08-15 19:54:20 +00001315 int pnamelen;
1316 int remaining = 0, firstline = 1;
Thomas Heijligen9163b812021-06-01 14:25:01 +02001317 size_t p;
Carl-Daniel Hailfinger082c8b52011-08-15 19:54:20 +00001318 int i;
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001319
Thomas Heijligend45cb592021-05-19 14:12:18 +02001320 for (p = 0; p < programmer_table_size; p++) {
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001321 pname = programmer_table[p]->name;
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001322 pnamelen = strlen(pname);
1323 if (remaining - pnamelen - 2 < 0) {
1324 if (firstline)
1325 firstline = 0;
1326 else
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001327 msg_ginfo("\n");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001328 for (i = 0; i < startcol; i++)
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001329 msg_ginfo(" ");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001330 remaining = cols - startcol;
1331 } else {
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001332 msg_ginfo(" ");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001333 remaining--;
1334 }
1335 if (paren && (p == 0)) {
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001336 msg_ginfo("(");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001337 remaining--;
1338 }
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001339 msg_ginfo("%s", pname);
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001340 remaining -= pnamelen;
Thomas Heijligend45cb592021-05-19 14:12:18 +02001341 if (p < programmer_table_size - 1) {
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001342 msg_ginfo(",");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001343 remaining--;
1344 } else {
1345 if (paren)
Carl-Daniel Hailfinger901a3ba2012-05-14 22:54:58 +00001346 msg_ginfo(")");
Carl-Daniel Hailfingera73fb492010-10-06 23:48:34 +00001347 }
1348 }
1349}
1350
Nico Huber32fa5082026-01-26 18:26:49 +01001351int selfcheck_chip(const struct flashchip *const chip, const int idx)
1352{
1353 int ret = 0;
Nico Huber72d0ada2026-01-26 18:28:20 +01001354 char label[80];
Nico Huber32fa5082026-01-26 18:26:49 +01001355 const char *const name = chip->name != NULL ? chip->name : "unnamed";
1356
Nico Huber72d0ada2026-01-26 18:28:20 +01001357 if (idx >= 0)
1358 snprintf(label, sizeof(label), "#%d (%s)", idx, name);
1359 else
1360 snprintf(label, sizeof(label), "%s", name);
1361
Nico Huber11136c22023-05-01 12:00:09 +02001362 if (chip->vendor == NULL || chip->name == NULL || chip->bustype == BUS_NONE ||
1363 chip->id.type == ID_FIXME) {
Nico Huber32fa5082026-01-26 18:26:49 +01001364 ret = 1;
Nico Huber72d0ada2026-01-26 18:28:20 +01001365 msg_gerr("ERROR: Some field of flash chip %s is misconfigured.\n"
1366 "Please report a bug at flashprog@flashprog.org\n", label);
Nico Huber32fa5082026-01-26 18:26:49 +01001367 }
1368 if (chip->feature_bits &
1369 (FEATURE_4BA_ENTER | FEATURE_4BA_ENTER_WREN | FEATURE_4BA_ENTER_EAR7 |
1370 FEATURE_ANY_DUAL | FEATURE_ANY_QUAD)
1371 && !chip->prepare_access) {
Nico Huber72d0ada2026-01-26 18:28:20 +01001372 msg_gerr("ERROR: Flash chip %s misses chip\n"
Nico Huber32fa5082026-01-26 18:26:49 +01001373 "preparation function for 4BA and multi-i/o modes.\n"
Nico Huber72d0ada2026-01-26 18:28:20 +01001374 "Please report a bug at flashprog@flashprog.org\n", label);
Nico Huber32fa5082026-01-26 18:26:49 +01001375 ret = 1;
1376 }
1377 uint8_t zero_cycles[sizeof(chip->dummy_cycles)] = { 0 };
1378 if ((chip->feature_bits & (FEATURE_QPI_35_F5 | FEATURE_QPI_38_FF)) &&
1379 !memcmp(&chip->dummy_cycles, zero_cycles, sizeof(zero_cycles))) {
Nico Huber72d0ada2026-01-26 18:28:20 +01001380 msg_gerr("ERROR: Flash chip %s misses QPI dummy-cycle\n"
Nico Huber32fa5082026-01-26 18:26:49 +01001381 "settings. Please report a bug at flashprog@flashprog.org\n",
Nico Huber72d0ada2026-01-26 18:28:20 +01001382 label);
Nico Huber32fa5082026-01-26 18:26:49 +01001383 ret = 1;
1384 }
1385 if (chip->reg_bits.bp[0].reg != INVALID_REG &&
1386 (!chip->wp_write_cfg || !chip->wp_read_cfg ||
1387 !chip->wp_get_ranges || !chip->decode_range)) {
Nico Huber72d0ada2026-01-26 18:28:20 +01001388 msg_gerr("ERROR: Flash chip %s advertises block-protection\n"
Nico Huber32fa5082026-01-26 18:26:49 +01001389 "bits, but misses one or more write-protection functions.\n"
Nico Huber72d0ada2026-01-26 18:28:20 +01001390 "Please report a bug at flashprog@flashprog.org\n", label);
Nico Huber32fa5082026-01-26 18:26:49 +01001391 ret = 1;
1392 }
Nico Huber72d0ada2026-01-26 18:28:20 +01001393 if (selfcheck_eraseblocks(chip, label)) {
Nico Huber32fa5082026-01-26 18:26:49 +01001394 ret = 1;
1395 }
1396
1397 return ret;
1398}
1399
Carl-Daniel Hailfinger552420b2009-12-24 02:15:55 +00001400int selfcheck(void)
1401{
Stefan Tauner96658be2014-05-26 22:05:31 +00001402 unsigned int i;
Stefan Taunera6d96482012-12-26 19:51:23 +00001403 int ret = 0;
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +00001404
Thomas Heijligend45cb592021-05-19 14:12:18 +02001405 for (i = 0; i < programmer_table_size; i++) {
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001406 const struct programmer_entry *const p = programmer_table[i];
1407 if (p == NULL) {
1408 msg_gerr("Programmer with index %d is NULL instead of a valid pointer!\n", i);
1409 ret = 1;
1410 continue;
1411 }
1412 if (p->name == NULL) {
Stefan Taunera6d96482012-12-26 19:51:23 +00001413 msg_gerr("All programmers need a valid name, but the one with index %d does not!\n", i);
1414 ret = 1;
1415 /* This might hide other problems with this programmer, but allows for better error
1416 * messages below without jumping through hoops. */
1417 continue;
1418 }
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001419 switch (p->type) {
Stefan Tauneraf358d62012-12-27 18:40:26 +00001420 case USB:
1421 case PCI:
1422 case OTHER:
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001423 if (p->devs.note == NULL) {
1424 if (strcmp("internal", p->name) == 0)
Stefan Tauneraf358d62012-12-27 18:40:26 +00001425 break; /* This one has its device list stored separately. */
1426 msg_gerr("Programmer %s has neither a device list nor a textual description!\n",
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001427 p->name);
Stefan Tauneraf358d62012-12-27 18:40:26 +00001428 ret = 1;
1429 }
1430 break;
1431 default:
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001432 msg_gerr("Programmer %s does not have a valid type set!\n", p->name);
Stefan Tauneraf358d62012-12-27 18:40:26 +00001433 ret = 1;
1434 break;
1435 }
Thomas Heijligen633d6db2021-03-31 19:09:44 +02001436 if (p->init == NULL) {
1437 msg_gerr("Programmer %s does not have a valid init function!\n", p->name);
Stefan Taunera6d96482012-12-26 19:51:23 +00001438 ret = 1;
1439 }
Stefan Taunera6d96482012-12-26 19:51:23 +00001440 }
Stefan Tauner96658be2014-05-26 22:05:31 +00001441
1442 /* It would be favorable if we could check for the correct layout (especially termination) of various
1443 * constant arrays: flashchips, chipset_enables, board_matches, boards_known, laptops_known.
1444 * They are all defined as externs in this compilation unit so we don't know their sizes which vary
1445 * depending on compiler flags, e.g. the target architecture, and can sometimes be 0.
1446 * For 'flashchips' we export the size explicitly to work around this and to be able to implement the
1447 * checks below. */
Stefan Tauner6697f712014-08-06 15:09:15 +00001448 if (flashchips_size <= 1 || flashchips[flashchips_size - 1].name != NULL) {
Stefan Tauner7bcacb12011-05-26 01:35:19 +00001449 msg_gerr("Flashchips table miscompilation!\n");
1450 ret = 1;
Stefan Tauner96658be2014-05-26 22:05:31 +00001451 } else {
1452 for (i = 0; i < flashchips_size - 1; i++) {
Nico Huber32fa5082026-01-26 18:26:49 +01001453 if (selfcheck_chip(&flashchips[i], i))
Stefan Tauner96658be2014-05-26 22:05:31 +00001454 ret = 1;
Stefan Tauner96658be2014-05-26 22:05:31 +00001455 }
Stefan Tauner7bcacb12011-05-26 01:35:19 +00001456 }
Stefan Tauner7bcacb12011-05-26 01:35:19 +00001457
Stefan Tauner600576b2014-06-12 22:57:36 +00001458#if CONFIG_INTERNAL == 1
1459 ret |= selfcheck_board_enables();
1460#endif
1461
Stefan Tauner96658be2014-05-26 22:05:31 +00001462 /* TODO: implement similar sanity checks for other arrays where deemed necessary. */
Carl-Daniel Hailfinger293adf02010-01-18 08:14:43 +00001463 return ret;
Carl-Daniel Hailfinger552420b2009-12-24 02:15:55 +00001464}
1465
Edward O'Callaghanacb24d42021-04-15 13:44:39 +10001466/* FIXME: This function signature needs to be improved once prepare_flash_access()
1467 * has a better function signature.
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001468 */
Jacob Garberbeeb8bc2019-06-21 15:24:17 -06001469static int chip_safety_check(const struct flashctx *flash, int force,
1470 int read_it, int write_it, int erase_it, int verify_it)
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001471{
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +00001472 const struct flashchip *chip = flash->chip;
1473
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001474 if (!programmer_may_write && (write_it || erase_it)) {
1475 msg_perr("Write/erase is not working yet on your programmer in "
1476 "its current configuration.\n");
1477 /* --force is the wrong approach, but it's the best we can do
1478 * until the generic programmer parameter parser is merged.
1479 */
1480 if (!force)
1481 return 1;
1482 msg_cerr("Continuing anyway.\n");
1483 }
1484
1485 if (read_it || erase_it || write_it || verify_it) {
1486 /* Everything needs read. */
Stefan Tauner6455dff2014-05-26 00:36:24 +00001487 if (chip->tested.read == BAD) {
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001488 msg_cerr("Read is not working on this chip. ");
1489 if (!force)
1490 return 1;
1491 msg_cerr("Continuing anyway.\n");
1492 }
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +00001493 if (!chip->read) {
Nico Huberc3b02dc2023-08-12 01:13:45 +02001494 msg_cerr("flashprog has no read function for this "
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001495 "flash chip.\n");
1496 return 1;
1497 }
1498 }
1499 if (erase_it || write_it) {
1500 /* Write needs erase. */
Stefan Tauner6455dff2014-05-26 00:36:24 +00001501 if (chip->tested.erase == NA) {
1502 msg_cerr("Erase is not possible on this chip.\n");
1503 return 1;
1504 }
1505 if (chip->tested.erase == BAD) {
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001506 msg_cerr("Erase is not working on this chip. ");
1507 if (!force)
1508 return 1;
1509 msg_cerr("Continuing anyway.\n");
1510 }
Nico Huberbb8ab372026-03-14 11:46:02 +01001511 if(flashprog_count_usable_erasers(flash) == 0) {
Nico Huberc3b02dc2023-08-12 01:13:45 +02001512 msg_cerr("flashprog has no erase function for this "
Stefan Tauner5368dca2011-07-01 00:19:12 +00001513 "flash chip.\n");
1514 return 1;
1515 }
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001516 }
1517 if (write_it) {
Stefan Tauner6455dff2014-05-26 00:36:24 +00001518 if (chip->tested.write == NA) {
1519 msg_cerr("Write is not possible on this chip.\n");
1520 return 1;
1521 }
1522 if (chip->tested.write == BAD) {
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001523 msg_cerr("Write is not working on this chip. ");
1524 if (!force)
1525 return 1;
1526 msg_cerr("Continuing anyway.\n");
1527 }
Carl-Daniel Hailfinger5a7cb842012-08-25 01:17:58 +00001528 if (!chip->write) {
Nico Huberc3b02dc2023-08-12 01:13:45 +02001529 msg_cerr("flashprog has no write function for this "
Carl-Daniel Hailfinger43069442010-10-15 00:01:14 +00001530 "flash chip.\n");
1531 return 1;
1532 }
1533 }
1534 return 0;
1535}
1536
Nico Huber305f4172013-06-14 11:55:26 +02001537int prepare_flash_access(struct flashctx *const flash,
1538 const bool read_it, const bool write_it,
1539 const bool erase_it, const bool verify_it)
Nico Huber454f6132012-12-10 13:34:10 +00001540{
1541 if (chip_safety_check(flash, flash->flags.force, read_it, write_it, erase_it, verify_it)) {
1542 msg_cerr("Aborting.\n");
1543 return 1;
1544 }
1545
Nico Huber3ac761c2023-01-16 02:43:17 +01001546 if (layout_sanity_checks(flash, write_it)) {
Nico Huber454f6132012-12-10 13:34:10 +00001547 msg_cerr("Requested regions can not be handled. Aborting.\n");
1548 return 1;
1549 }
1550
Nikolai Artemiev4ad48642020-11-05 13:54:27 +11001551 /* Initialize chip_restore_fn_count before chip unlock calls. */
1552 flash->chip_restore_fn_count = 0;
1553
Nico Huber454f6132012-12-10 13:34:10 +00001554 /* Given the existence of read locks, we want to unlock for read,
1555 erase and write. */
1556 if (flash->chip->unlock)
1557 flash->chip->unlock(flash);
1558
1559 return 0;
1560}
1561
Nico Huber305f4172013-06-14 11:55:26 +02001562void finalize_flash_access(struct flashctx *const flash)
Nico Huber454f6132012-12-10 13:34:10 +00001563{
Nikolai Artemiev4ad48642020-11-05 13:54:27 +11001564 deregister_chip_restore(flash);
Nico Huber454f6132012-12-10 13:34:10 +00001565}
1566
1567/**
Nico Huberc3b02dc2023-08-12 01:13:45 +02001568 * @addtogroup flashprog-flash
Nico Huber454f6132012-12-10 13:34:10 +00001569 * @{
1570 */
1571
1572/**
1573 * @brief Erase the specified ROM chip.
1574 *
1575 * If a layout is set in the given flash context, only included regions
1576 * will be erased.
1577 *
1578 * @param flashctx The context of the flash chip to erase.
1579 * @return 0 on success.
1580 */
Nico Huberc3b02dc2023-08-12 01:13:45 +02001581int flashprog_flash_erase(struct flashctx *const flashctx)
Nico Huber454f6132012-12-10 13:34:10 +00001582{
1583 if (prepare_flash_access(flashctx, false, false, true, false))
1584 return 1;
1585
1586 const int ret = erase_by_layout(flashctx);
1587
1588 finalize_flash_access(flashctx);
1589
1590 return ret;
1591}
1592
Nico Huberc3b02dc2023-08-12 01:13:45 +02001593/** @} */ /* end flashprog-flash */
Nico Huber454f6132012-12-10 13:34:10 +00001594
1595/**
Nico Huberc3b02dc2023-08-12 01:13:45 +02001596 * @defgroup flashprog-ops Operations
Nico Huber454f6132012-12-10 13:34:10 +00001597 * @{
1598 */
1599
1600/**
1601 * @brief Read the current image from the specified ROM chip.
1602 *
1603 * If a layout is set in the specified flash context, only included regions
1604 * will be read.
1605 *
1606 * @param flashctx The context of the flash chip.
1607 * @param buffer Target buffer to write image to.
1608 * @param buffer_len Size of target buffer in bytes.
1609 * @return 0 on success,
1610 * 2 if buffer_len is too short for the flash chip's contents,
1611 * or 1 on any other failure.
1612 */
Nico Huberc3b02dc2023-08-12 01:13:45 +02001613int flashprog_image_read(struct flashctx *const flashctx, void *const buffer, const size_t buffer_len)
Nico Huber454f6132012-12-10 13:34:10 +00001614{
1615 const size_t flash_size = flashctx->chip->total_size * 1024;
1616
1617 if (flash_size > buffer_len)
1618 return 2;
1619
1620 if (prepare_flash_access(flashctx, true, false, false, false))
1621 return 1;
1622
1623 msg_cinfo("Reading flash... ");
1624
1625 int ret = 1;
1626 if (read_by_layout(flashctx, buffer)) {
1627 msg_cerr("Read operation failed!\n");
1628 msg_cinfo("FAILED.\n");
1629 goto _finalize_ret;
1630 }
1631 msg_cinfo("done.\n");
1632 ret = 0;
1633
1634_finalize_ret:
1635 finalize_flash_access(flashctx);
1636 return ret;
1637}
1638
1639static void combine_image_by_layout(const struct flashctx *const flashctx,
1640 uint8_t *const newcontents, const uint8_t *const oldcontents)
1641{
Nico Huberc3b02dc2023-08-12 01:13:45 +02001642 const struct flashprog_layout *const layout = get_layout(flashctx);
Nico Huber3d7b1e32018-12-22 00:53:14 +01001643 const struct romentry *included;
1644 chipoff_t start = 0;
Nico Huber454f6132012-12-10 13:34:10 +00001645
Nico Huber3d7b1e32018-12-22 00:53:14 +01001646 while ((included = layout_next_included_region(layout, start))) {
1647 if (included->start > start) {
1648 /* copy everything up to the start of this included region */
1649 memcpy(newcontents + start, oldcontents + start, included->start - start);
1650 }
1651 /* skip this included region */
1652 start = included->end + 1;
1653 if (start == 0)
1654 return;
Nico Huber454f6132012-12-10 13:34:10 +00001655 }
Nico Huber3d7b1e32018-12-22 00:53:14 +01001656
1657 /* copy the rest of the chip */
1658 const chipsize_t copy_len = flashctx->chip->total_size * 1024 - start;
1659 memcpy(newcontents + start, oldcontents + start, copy_len);
Nico Huber454f6132012-12-10 13:34:10 +00001660}
1661
1662/**
1663 * @brief Write the specified image to the ROM chip.
1664 *
1665 * If a layout is set in the specified flash context, only erase blocks
1666 * containing included regions will be touched.
1667 *
1668 * @param flashctx The context of the flash chip.
Nico Huber1b172f22017-06-19 12:35:24 +02001669 * @param buffer Source buffer to read image from (may be altered for full verification).
Nico Huber454f6132012-12-10 13:34:10 +00001670 * @param buffer_len Size of source buffer in bytes.
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001671 * @param refbuffer If given, assume flash chip contains same data as `refbuffer`.
Nico Huber454f6132012-12-10 13:34:10 +00001672 * @return 0 on success,
1673 * 4 if buffer_len doesn't match the size of the flash chip,
1674 * 3 if write was tried but nothing has changed,
1675 * 2 if write failed and flash contents changed,
1676 * or 1 on any other failure.
1677 */
Nico Huberc3b02dc2023-08-12 01:13:45 +02001678int flashprog_image_write(struct flashctx *const flashctx, void *const buffer, const size_t buffer_len,
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001679 const void *const refbuffer)
Nico Huber454f6132012-12-10 13:34:10 +00001680{
1681 const size_t flash_size = flashctx->chip->total_size * 1024;
1682 const bool verify_all = flashctx->flags.verify_whole_chip;
1683 const bool verify = flashctx->flags.verify_after_write;
Nico Huberc3b02dc2023-08-12 01:13:45 +02001684 const struct flashprog_layout *const verify_layout =
Nico Huber74d09d42019-06-16 03:27:26 +02001685 verify_all ? get_default_layout(flashctx) : get_layout(flashctx);
Nico Huber454f6132012-12-10 13:34:10 +00001686
1687 if (buffer_len != flash_size)
1688 return 4;
1689
1690 int ret = 1;
1691
1692 uint8_t *const newcontents = buffer;
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001693 const uint8_t *const refcontents = refbuffer;
Nico Huber454f6132012-12-10 13:34:10 +00001694 uint8_t *const curcontents = malloc(flash_size);
1695 uint8_t *oldcontents = NULL;
1696 if (verify_all)
1697 oldcontents = malloc(flash_size);
1698 if (!curcontents || (verify_all && !oldcontents)) {
1699 msg_gerr("Out of memory!\n");
1700 goto _free_ret;
1701 }
1702
1703#if CONFIG_INTERNAL == 1
Thomas Heijligenc7e5b8b2021-06-01 14:21:41 +02001704 if (programmer == &programmer_internal && cb_check_image(newcontents, flash_size) < 0) {
Nico Huber454f6132012-12-10 13:34:10 +00001705 if (flashctx->flags.force_boardmismatch) {
1706 msg_pinfo("Proceeding anyway because user forced us to.\n");
1707 } else {
1708 msg_perr("Aborting. You can override this with "
1709 "-p internal:boardmismatch=force.\n");
1710 goto _free_ret;
1711 }
1712 }
1713#endif
1714
1715 if (prepare_flash_access(flashctx, false, true, false, verify))
1716 goto _free_ret;
1717
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001718 /* If given, assume flash chip contains same data as `refcontents`. */
1719 if (refcontents) {
1720 msg_cinfo("Assuming old flash chip contents as ref-file...\n");
1721 memcpy(curcontents, refcontents, flash_size);
1722 if (oldcontents)
1723 memcpy(oldcontents, refcontents, flash_size);
Nico Huber454f6132012-12-10 13:34:10 +00001724 } else {
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001725 /*
1726 * Read the whole chip to be able to check whether regions need to be
1727 * erased and to give better diagnostics in case write fails.
1728 * The alternative is to read only the regions which are to be
1729 * preserved, but in that case we might perform unneeded erase which
1730 * takes time as well.
1731 */
1732 msg_cinfo("Reading old flash chip contents... ");
1733 if (verify_all) {
Richard Hughes842d6782021-01-15 09:48:12 +00001734 if (flashprog_read_range(flashctx, oldcontents, 0, flash_size)) {
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001735 msg_cinfo("FAILED.\n");
1736 goto _finalize_ret;
1737 }
1738 memcpy(curcontents, oldcontents, flash_size);
1739 } else {
1740 if (read_by_layout(flashctx, curcontents)) {
1741 msg_cinfo("FAILED.\n");
1742 goto _finalize_ret;
1743 }
Nico Huber454f6132012-12-10 13:34:10 +00001744 }
Paul Kocialkowskif701f342018-01-15 01:10:36 +03001745 msg_cinfo("done.\n");
Nico Huber454f6132012-12-10 13:34:10 +00001746 }
Nico Huber454f6132012-12-10 13:34:10 +00001747
1748 if (write_by_layout(flashctx, curcontents, newcontents)) {
1749 msg_cerr("Uh oh. Erase/write failed. ");
1750 ret = 2;
1751 if (verify_all) {
1752 msg_cerr("Checking if anything has changed.\n");
1753 msg_cinfo("Reading current flash chip contents... ");
Richard Hughes842d6782021-01-15 09:48:12 +00001754 if (!flashprog_read_range(flashctx, curcontents, 0, flash_size)) {
Nico Huber454f6132012-12-10 13:34:10 +00001755 msg_cinfo("done.\n");
1756 if (!memcmp(oldcontents, curcontents, flash_size)) {
1757 nonfatal_help_message();
1758 goto _finalize_ret;
1759 }
1760 msg_cerr("Apparently at least some data has changed.\n");
1761 } else
1762 msg_cerr("Can't even read anymore!\n");
1763 emergency_help_message();
1764 goto _finalize_ret;
1765 } else {
1766 msg_cerr("\n");
1767 }
1768 emergency_help_message();
1769 goto _finalize_ret;
1770 }
1771
1772 /* Verify only if we actually changed something. */
1773 if (verify && !all_skipped) {
Nico Huber454f6132012-12-10 13:34:10 +00001774 msg_cinfo("Verifying flash... ");
1775
Nico Huber74d09d42019-06-16 03:27:26 +02001776 if (verify_all)
Nico Huber454f6132012-12-10 13:34:10 +00001777 combine_image_by_layout(flashctx, newcontents, oldcontents);
Nico Huber74d09d42019-06-16 03:27:26 +02001778 ret = verify_by_layout(flashctx, verify_layout, curcontents, newcontents);
Nico Huber454f6132012-12-10 13:34:10 +00001779 /* If we tried to write, and verification now fails, we
1780 might have an emergency situation. */
1781 if (ret)
1782 emergency_help_message();
1783 else
1784 msg_cinfo("VERIFIED.\n");
1785 } else {
1786 /* We didn't change anything. */
1787 ret = 0;
1788 }
1789
1790_finalize_ret:
1791 finalize_flash_access(flashctx);
1792_free_ret:
1793 free(oldcontents);
1794 free(curcontents);
1795 return ret;
1796}
1797
1798/**
1799 * @brief Verify the ROM chip's contents with the specified image.
1800 *
1801 * If a layout is set in the specified flash context, only included regions
1802 * will be verified.
1803 *
1804 * @param flashctx The context of the flash chip.
1805 * @param buffer Source buffer to verify with.
1806 * @param buffer_len Size of source buffer in bytes.
1807 * @return 0 on success,
1808 * 3 if the chip's contents don't match,
1809 * 2 if buffer_len doesn't match the size of the flash chip,
1810 * or 1 on any other failure.
1811 */
Nico Huberc3b02dc2023-08-12 01:13:45 +02001812int flashprog_image_verify(struct flashctx *const flashctx, const void *const buffer, const size_t buffer_len)
Nico Huber454f6132012-12-10 13:34:10 +00001813{
Nico Huberc3b02dc2023-08-12 01:13:45 +02001814 const struct flashprog_layout *const layout = get_layout(flashctx);
Nico Huber454f6132012-12-10 13:34:10 +00001815 const size_t flash_size = flashctx->chip->total_size * 1024;
1816
1817 if (buffer_len != flash_size)
1818 return 2;
1819
1820 const uint8_t *const newcontents = buffer;
1821 uint8_t *const curcontents = malloc(flash_size);
1822 if (!curcontents) {
1823 msg_gerr("Out of memory!\n");
1824 return 1;
1825 }
1826
1827 int ret = 1;
1828
1829 if (prepare_flash_access(flashctx, false, false, false, true))
1830 goto _free_ret;
1831
1832 msg_cinfo("Verifying flash... ");
Nico Huber74d09d42019-06-16 03:27:26 +02001833 ret = verify_by_layout(flashctx, layout, curcontents, newcontents);
Nico Huber454f6132012-12-10 13:34:10 +00001834 if (!ret)
1835 msg_cinfo("VERIFIED.\n");
1836
1837 finalize_flash_access(flashctx);
1838_free_ret:
1839 free(curcontents);
1840 return ret;
1841}
1842
Nico Huberc3b02dc2023-08-12 01:13:45 +02001843/** @} */ /* end flashprog-ops */