Flashrom

Flashrom Svn Source Tree

Root/trunk/flashrom.c

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
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 <yhlu@tyan.com>
6 * Copyright (C) 2005-2008 coresystems GmbH
7 * Copyright (C) 2008,2009 Carl-Daniel Hailfinger
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 */
23
24#include <stdio.h>
25#include <sys/types.h>
26#ifndef __LIBPAYLOAD__
27#include <fcntl.h>
28#include <sys/stat.h>
29#endif
30#include <string.h>
31#include <stdlib.h>
32#include <errno.h>
33#include <ctype.h>
34#include <getopt.h>
35#if HAVE_UTSNAME == 1
36#include <sys/utsname.h>
37#endif
38#include "flash.h"
39#include "flashchips.h"
40#include "programmer.h"
41#include "hwaccess.h"
42
43const char flashrom_version[] = FLASHROM_VERSION;
44const char *chip_to_probe = NULL;
45int verbose_screen = MSG_INFO;
46int verbose_logfile = MSG_DEBUG2;
47
48static enum programmer programmer = PROGRAMMER_INVALID;
49
50static const char *programmer_param = NULL;
51
52/*
53 * Programmers supporting multiple buses can have differing size limits on
54 * each bus. Store the limits for each bus in a common struct.
55 */
56struct decode_sizes max_rom_decode;
57
58/* If nonzero, used as the start address of bottom-aligned flash. */
59unsigned long flashbase;
60
61/* Is writing allowed with this programmer? */
62int programmer_may_write;
63
64const struct programmer_entry programmer_table[] = {
65#if CONFIG_INTERNAL == 1
66{
67.name= "internal",
68.type= OTHER,
69.devs.note= NULL,
70.init= internal_init,
71.map_flash_region= physmap,
72.unmap_flash_region= physunmap,
73.delay= internal_delay,
74},
75#endif
76
77#if CONFIG_DUMMY == 1
78{
79.name= "dummy",
80.type= OTHER,
81/* FIXME */
82.devs.note= "Dummy device, does nothing and logs all accesses\n",
83.init= dummy_init,
84.map_flash_region= dummy_map,
85.unmap_flash_region= dummy_unmap,
86.delay= internal_delay,
87},
88#endif
89
90#if CONFIG_NIC3COM == 1
91{
92.name= "nic3com",
93.type= PCI,
94.devs.dev= nics_3com,
95.init= nic3com_init,
96.map_flash_region= fallback_map,
97.unmap_flash_region= fallback_unmap,
98.delay= internal_delay,
99},
100#endif
101
102#if CONFIG_NICREALTEK == 1
103{
104/* This programmer works for Realtek RTL8139 and SMC 1211. */
105.name= "nicrealtek",
106.type= PCI,
107.devs.dev= nics_realtek,
108.init= nicrealtek_init,
109.map_flash_region= fallback_map,
110.unmap_flash_region= fallback_unmap,
111.delay= internal_delay,
112},
113#endif
114
115#if CONFIG_NICNATSEMI == 1
116{
117.name= "nicnatsemi",
118.type= PCI,
119.devs.dev= nics_natsemi,
120.init= nicnatsemi_init,
121.map_flash_region= fallback_map,
122.unmap_flash_region= fallback_unmap,
123.delay= internal_delay,
124},
125#endif
126
127#if CONFIG_GFXNVIDIA == 1
128{
129.name= "gfxnvidia",
130.type= PCI,
131.devs.dev= gfx_nvidia,
132.init= gfxnvidia_init,
133.map_flash_region= fallback_map,
134.unmap_flash_region= fallback_unmap,
135.delay= internal_delay,
136},
137#endif
138
139#if CONFIG_DRKAISER == 1
140{
141.name= "drkaiser",
142.type= PCI,
143.devs.dev= drkaiser_pcidev,
144.init= drkaiser_init,
145.map_flash_region= fallback_map,
146.unmap_flash_region= fallback_unmap,
147.delay= internal_delay,
148},
149#endif
150
151#if CONFIG_SATASII == 1
152{
153.name= "satasii",
154.type= PCI,
155.devs.dev= satas_sii,
156.init= satasii_init,
157.map_flash_region= fallback_map,
158.unmap_flash_region= fallback_unmap,
159.delay= internal_delay,
160},
161#endif
162
163#if CONFIG_ATAHPT == 1
164{
165.name= "atahpt",
166.type= PCI,
167.devs.dev= ata_hpt,
168.init= atahpt_init,
169.map_flash_region= fallback_map,
170.unmap_flash_region= fallback_unmap,
171.delay= internal_delay,
172},
173#endif
174
175#if CONFIG_ATAVIA == 1
176{
177.name= "atavia",
178.type= PCI,
179.devs.dev= ata_via,
180.init= atavia_init,
181.map_flash_region= atavia_map,
182.unmap_flash_region= fallback_unmap,
183.delay= internal_delay,
184},
185#endif
186
187#if CONFIG_IT8212 == 1
188{
189.name= "it8212",
190.type= PCI,
191.devs.dev= devs_it8212,
192.init= it8212_init,
193.map_flash_region= fallback_map,
194.unmap_flash_region= fallback_unmap,
195.delay= internal_delay,
196},
197#endif
198
199#if CONFIG_FT2232_SPI == 1
200{
201.name= "ft2232_spi",
202.type= USB,
203.devs.dev= devs_ft2232spi,
204.init= ft2232_spi_init,
205.map_flash_region= fallback_map,
206.unmap_flash_region= fallback_unmap,
207.delay= internal_delay,
208},
209#endif
210
211#if CONFIG_SERPROG == 1
212{
213.name= "serprog",
214.type= OTHER,
215/* FIXME */
216.devs.note= "All programmer devices speaking the serprog protocol\n",
217.init= serprog_init,
218.map_flash_region= fallback_map,
219.unmap_flash_region= fallback_unmap,
220.delay= serprog_delay,
221},
222#endif
223
224#if CONFIG_BUSPIRATE_SPI == 1
225{
226.name= "buspirate_spi",
227.type= OTHER,
228/* FIXME */
229.devs.note= "Dangerous Prototypes Bus Pirate\n",
230.init= buspirate_spi_init,
231.map_flash_region= fallback_map,
232.unmap_flash_region= fallback_unmap,
233.delay= internal_delay,
234},
235#endif
236
237#if CONFIG_DEDIPROG == 1
238{
239.name= "dediprog",
240.type= OTHER,
241/* FIXME */
242.devs.note= "Dediprog SF100\n",
243.init= dediprog_init,
244.map_flash_region= fallback_map,
245.unmap_flash_region= fallback_unmap,
246.delay= internal_delay,
247},
248#endif
249
250#if CONFIG_RAYER_SPI == 1
251{
252.name= "rayer_spi",
253.type= OTHER,
254/* FIXME */
255.devs.note= "RayeR parallel port programmer\n",
256.init= rayer_spi_init,
257.map_flash_region= fallback_map,
258.unmap_flash_region= fallback_unmap,
259.delay= internal_delay,
260},
261#endif
262
263#if CONFIG_PONY_SPI == 1
264{
265.name= "pony_spi",
266.type= OTHER,
267/* FIXME */
268.devs.note= "Programmers compatible with SI-Prog, serbang or AJAWe\n",
269.init= pony_spi_init,
270.map_flash_region= fallback_map,
271.unmap_flash_region= fallback_unmap,
272.delay= internal_delay,
273},
274#endif
275
276#if CONFIG_NICINTEL == 1
277{
278.name= "nicintel",
279.type= PCI,
280.devs.dev= nics_intel,
281.init= nicintel_init,
282.map_flash_region= fallback_map,
283.unmap_flash_region= fallback_unmap,
284.delay= internal_delay,
285},
286#endif
287
288#if CONFIG_NICINTEL_SPI == 1
289{
290.name= "nicintel_spi",
291.type= PCI,
292.devs.dev= nics_intel_spi,
293.init= nicintel_spi_init,
294.map_flash_region= fallback_map,
295.unmap_flash_region= fallback_unmap,
296.delay= internal_delay,
297},
298#endif
299
300#if CONFIG_NICINTEL_EEPROM == 1
301{
302.name= "nicintel_eeprom",
303.type= PCI,
304.devs.dev= nics_intel_ee,
305.init= nicintel_ee_init,
306.map_flash_region= fallback_map,
307.unmap_flash_region= fallback_unmap,
308.delay= internal_delay,
309},
310#endif
311
312#if CONFIG_OGP_SPI == 1
313{
314.name= "ogp_spi",
315.type= PCI,
316.devs.dev= ogp_spi,
317.init= ogp_spi_init,
318.map_flash_region= fallback_map,
319.unmap_flash_region= fallback_unmap,
320.delay= internal_delay,
321},
322#endif
323
324#if CONFIG_SATAMV == 1
325{
326.name= "satamv",
327.type= PCI,
328.devs.dev= satas_mv,
329.init= satamv_init,
330.map_flash_region= fallback_map,
331.unmap_flash_region= fallback_unmap,
332.delay= internal_delay,
333},
334#endif
335
336#if CONFIG_LINUX_SPI == 1
337{
338.name= "linux_spi",
339.type= OTHER,
340.devs.note= "Device files /dev/spidev*.*\n",
341.init= linux_spi_init,
342.map_flash_region= fallback_map,
343.unmap_flash_region= fallback_unmap,
344.delay= internal_delay,
345},
346#endif
347
348#if CONFIG_USBBLASTER_SPI == 1
349{
350.name= "usbblaster_spi",
351.type= USB,
352.devs.dev= devs_usbblasterspi,
353.init= usbblaster_spi_init,
354.map_flash_region= fallback_map,
355.unmap_flash_region= fallback_unmap,
356.delay= internal_delay,
357},
358#endif
359
360{0}, /* This entry corresponds to PROGRAMMER_INVALID. */
361};
362
363#define SHUTDOWN_MAXFN 32
364static int shutdown_fn_count = 0;
365struct shutdown_func_data {
366int (*func) (void *data);
367void *data;
368} static shutdown_fn[SHUTDOWN_MAXFN];
369/* Initialize to 0 to make sure nobody registers a shutdown function before
370 * programmer init.
371 */
372static int may_register_shutdown = 0;
373
374/* Did we change something or was every erase/write skipped (if any)? */
375static bool all_skipped = true;
376
377static int check_block_eraser(const struct flashctx *flash, int k, int log);
378
379/* Register a function to be executed on programmer shutdown.
380 * The advantage over atexit() is that you can supply a void pointer which will
381 * be used as parameter to the registered function upon programmer shutdown.
382 * This pointer can point to arbitrary data used by said function, e.g. undo
383 * information for GPIO settings etc. If unneeded, set data=NULL.
384 * Please note that the first (void *data) belongs to the function signature of
385 * the function passed as first parameter.
386 */
387int register_shutdown(int (*function) (void *data), void *data)
388{
389if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
390msg_perr("Tried to register more than %i shutdown functions.\n",
391 SHUTDOWN_MAXFN);
392return 1;
393}
394if (!may_register_shutdown) {
395msg_perr("Tried to register a shutdown function before "
396 "programmer init.\n");
397return 1;
398}
399shutdown_fn[shutdown_fn_count].func = function;
400shutdown_fn[shutdown_fn_count].data = data;
401shutdown_fn_count++;
402
403return 0;
404}
405
406int programmer_init(enum programmer prog, const char *param)
407{
408int ret;
409
410if (prog >= PROGRAMMER_INVALID) {
411msg_perr("Invalid programmer specified!\n");
412return -1;
413}
414programmer = prog;
415/* Initialize all programmer specific data. */
416/* Default to unlimited decode sizes. */
417max_rom_decode = (const struct decode_sizes) {
418.parallel= 0xffffffff,
419.lpc= 0xffffffff,
420.fwh= 0xffffffff,
421.spi= 0xffffffff,
422};
423/* Default to top aligned flash at 4 GB. */
424flashbase = 0;
425/* Registering shutdown functions is now allowed. */
426may_register_shutdown = 1;
427/* Default to allowing writes. Broken programmers set this to 0. */
428programmer_may_write = 1;
429
430programmer_param = param;
431msg_pdbg("Initializing %s programmer\n", programmer_table[programmer].name);
432ret = programmer_table[programmer].init();
433if (programmer_param && strlen(programmer_param)) {
434if (ret != 0) {
435/* It is quite possible that any unhandled programmer parameter would have been valid,
436 * but an error in actual programmer init happened before the parameter was evaluated.
437 */
438msg_pwarn("Unhandled programmer parameters (possibly due to another failure): %s\n",
439 programmer_param);
440} else {
441/* Actual programmer init was successful, but the user specified an invalid or unusable
442 * (for the current programmer configuration) parameter.
443 */
444msg_perr("Unhandled programmer parameters: %s\n", programmer_param);
445msg_perr("Aborting.\n");
446ret = ERROR_FATAL;
447}
448}
449return ret;
450}
451
452/** Calls registered shutdown functions and resets internal programmer-related variables.
453 * Calling it is safe even without previous initialization, but further interactions with programmer support
454 * require a call to programmer_init() (afterwards).
455 *
456 * @return The OR-ed result values of all shutdown functions (i.e. 0 on success). */
457int programmer_shutdown(void)
458{
459int ret = 0;
460
461/* Registering shutdown functions is no longer allowed. */
462may_register_shutdown = 0;
463while (shutdown_fn_count > 0) {
464int i = --shutdown_fn_count;
465ret |= shutdown_fn[i].func(shutdown_fn[i].data);
466}
467
468programmer_param = NULL;
469registered_master_count = 0;
470
471return ret;
472}
473
474void *programmer_map_flash_region(const char *descr, uintptr_t phys_addr, size_t len)
475{
476void *ret = programmer_table[programmer].map_flash_region(descr, phys_addr, len);
477msg_gspew("%s: mapping %s from 0x%0*" PRIxPTR " to 0x%0*" PRIxPTR "\n",
478 __func__, descr, PRIxPTR_WIDTH, phys_addr, PRIxPTR_WIDTH, (uintptr_t) ret);
479return ret;
480}
481
482void programmer_unmap_flash_region(void *virt_addr, size_t len)
483{
484programmer_table[programmer].unmap_flash_region(virt_addr, len);
485}
486
487void chip_writeb(const struct flashctx *flash, uint8_t val, chipaddr addr)
488{
489flash->mst->par.chip_writeb(flash, val, addr);
490}
491
492void chip_writew(const struct flashctx *flash, uint16_t val, chipaddr addr)
493{
494flash->mst->par.chip_writew(flash, val, addr);
495}
496
497void chip_writel(const struct flashctx *flash, uint32_t val, chipaddr addr)
498{
499flash->mst->par.chip_writel(flash, val, addr);
500}
501
502void chip_writen(const struct flashctx *flash, const uint8_t *buf, chipaddr addr, size_t len)
503{
504flash->mst->par.chip_writen(flash, buf, addr, len);
505}
506
507uint8_t chip_readb(const struct flashctx *flash, const chipaddr addr)
508{
509return flash->mst->par.chip_readb(flash, addr);
510}
511
512uint16_t chip_readw(const struct flashctx *flash, const chipaddr addr)
513{
514return flash->mst->par.chip_readw(flash, addr);
515}
516
517uint32_t chip_readl(const struct flashctx *flash, const chipaddr addr)
518{
519return flash->mst->par.chip_readl(flash, addr);
520}
521
522void chip_readn(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
523size_t len)
524{
525flash->mst->par.chip_readn(flash, buf, addr, len);
526}
527
528void programmer_delay(unsigned int usecs)
529{
530if (usecs > 0)
531programmer_table[programmer].delay(usecs);
532}
533
534void map_flash_registers(struct flashctx *flash)
535{
536size_t size = flash->chip->total_size * 1024;
537/* Flash registers live 4 MByte below the flash. */
538/* FIXME: This is incorrect for nonstandard flashbase. */
539flash->virtual_registers = (chipaddr)programmer_map_flash_region("flash chip registers", (0xFFFFFFFF - 0x400000 - size + 1), size);
540}
541
542int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start,
543 int unsigned len)
544{
545chip_readn(flash, buf, flash->virtual_memory + start, len);
546
547return 0;
548}
549
550/* This is a somewhat hacked function similar in some ways to strtok().
551 * It will look for needle with a subsequent '=' in haystack, return a copy of
552 * needle and remove everything from the first occurrence of needle to the next
553 * delimiter from haystack.
554 */
555char *extract_param(const char *const *haystack, const char *needle, const char *delim)
556{
557char *param_pos, *opt_pos, *rest;
558char *opt = NULL;
559int optlen;
560int needlelen;
561
562needlelen = strlen(needle);
563if (!needlelen) {
564msg_gerr("%s: empty needle! Please report a bug at "
565 "flashrom@flashrom.org\n", __func__);
566return NULL;
567}
568/* No programmer parameters given. */
569if (*haystack == NULL)
570return NULL;
571param_pos = strstr(*haystack, needle);
572do {
573if (!param_pos)
574return NULL;
575/* Needle followed by '='? */
576if (param_pos[needlelen] == '=') {
577
578/* Beginning of the string? */
579if (param_pos == *haystack)
580break;
581/* After a delimiter? */
582if (strchr(delim, *(param_pos - 1)))
583break;
584}
585/* Continue searching. */
586param_pos++;
587param_pos = strstr(param_pos, needle);
588} while (1);
589
590if (param_pos) {
591/* Get the string after needle and '='. */
592opt_pos = param_pos + needlelen + 1;
593optlen = strcspn(opt_pos, delim);
594/* Return an empty string if the parameter was empty. */
595opt = malloc(optlen + 1);
596if (!opt) {
597msg_gerr("Out of memory!\n");
598exit(1);
599}
600strncpy(opt, opt_pos, optlen);
601opt[optlen] = '\0';
602rest = opt_pos + optlen;
603/* Skip all delimiters after the current parameter. */
604rest += strspn(rest, delim);
605memmove(param_pos, rest, strlen(rest) + 1);
606/* We could shrink haystack, but the effort is not worth it. */
607}
608
609return opt;
610}
611
612char *extract_programmer_param(const char *param_name)
613{
614return extract_param(&programmer_param, param_name, ",");
615}
616
617/* Returns the number of well-defined erasers for a chip. */
618static unsigned int count_usable_erasers(const struct flashctx *flash)
619{
620unsigned int usable_erasefunctions = 0;
621int k;
622for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
623if (!check_block_eraser(flash, k, 0))
624usable_erasefunctions++;
625}
626return usable_erasefunctions;
627}
628
629static int compare_range(const uint8_t *wantbuf, const uint8_t *havebuf, unsigned int start, unsigned int len)
630{
631int ret = 0, failcount = 0;
632unsigned int i;
633for (i = 0; i < len; i++) {
634if (wantbuf[i] != havebuf[i]) {
635/* Only print the first failure. */
636if (!failcount++)
637msg_cerr("FAILED at 0x%08x! Expected=0x%02x, Found=0x%02x,",
638 start + i, wantbuf[i], havebuf[i]);
639}
640}
641if (failcount) {
642msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
643 start, start + len - 1, failcount);
644ret = -1;
645}
646return ret;
647}
648
649/* start is an offset to the base address of the flash chip */
650int check_erased_range(struct flashctx *flash, unsigned int start,
651 unsigned int len)
652{
653int ret;
654uint8_t *cmpbuf = malloc(len);
655
656if (!cmpbuf) {
657msg_gerr("Could not allocate memory!\n");
658exit(1);
659}
660memset(cmpbuf, 0xff, len);
661ret = verify_range(flash, cmpbuf, start, len);
662free(cmpbuf);
663return ret;
664}
665
666/*
667 * @cmpbufbuffer to compare against, cmpbuf[0] is expected to match the
668 *flash content at location start
669 * @startoffset to the base address of the flash chip
670 * @lenlength of the verified area
671 * @return0 for success, -1 for failure
672 */
673int verify_range(struct flashctx *flash, const uint8_t *cmpbuf, unsigned int start, unsigned int len)
674{
675if (!len)
676return -1;
677
678if (!flash->chip->read) {
679msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
680return -1;
681}
682
683uint8_t *readbuf = malloc(len);
684if (!readbuf) {
685msg_gerr("Could not allocate memory!\n");
686return -1;
687}
688int ret = 0;
689
690if (start + len > flash->chip->total_size * 1024) {
691msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
692" total_size 0x%x\n", __func__, start, len,
693flash->chip->total_size * 1024);
694ret = -1;
695goto out_free;
696}
697
698ret = flash->chip->read(flash, readbuf, start, len);
699if (ret) {
700msg_gerr("Verification impossible because read failed "
701 "at 0x%x (len 0x%x)\n", start, len);
702ret = -1;
703goto out_free;
704}
705
706ret = compare_range(cmpbuf, readbuf, start, len);
707out_free:
708free(readbuf);
709return ret;
710}
711
712/* Helper function for need_erase() that focuses on granularities of gran bytes. */
713static int need_erase_gran_bytes(const uint8_t *have, const uint8_t *want, unsigned int len, unsigned int gran)
714{
715unsigned int i, j, limit;
716for (j = 0; j < len / gran; j++) {
717limit = min (gran, len - j * gran);
718/* Are 'have' and 'want' identical? */
719if (!memcmp(have + j * gran, want + j * gran, limit))
720continue;
721/* have needs to be in erased state. */
722for (i = 0; i < limit; i++)
723if (have[j * gran + i] != 0xff)
724return 1;
725}
726return 0;
727}
728
729/*
730 * Check if the buffer @have can be programmed to the content of @want without
731 * erasing. This is only possible if all chunks of size @gran are either kept
732 * as-is or changed from an all-ones state to any other state.
733 *
734 * Warning: This function assumes that @have and @want point to naturally
735 * aligned regions.
736 *
737 * @have buffer with current content
738 * @want buffer with desired content
739 * @lenlength of the checked area
740 * @granwrite granularity (enum, not count)
741 * @return 0 if no erase is needed, 1 otherwise
742 */
743int need_erase(const uint8_t *have, const uint8_t *want, unsigned int len, enum write_granularity gran)
744{
745int result = 0;
746unsigned int i;
747
748switch (gran) {
749case write_gran_1bit:
750for (i = 0; i < len; i++)
751if ((have[i] & want[i]) != want[i]) {
752result = 1;
753break;
754}
755break;
756case write_gran_1byte:
757for (i = 0; i < len; i++)
758if ((have[i] != want[i]) && (have[i] != 0xff)) {
759result = 1;
760break;
761}
762break;
763case write_gran_256bytes:
764result = need_erase_gran_bytes(have, want, len, 256);
765break;
766case write_gran_264bytes:
767result = need_erase_gran_bytes(have, want, len, 264);
768break;
769case write_gran_512bytes:
770result = need_erase_gran_bytes(have, want, len, 512);
771break;
772case write_gran_528bytes:
773result = need_erase_gran_bytes(have, want, len, 528);
774break;
775case write_gran_1024bytes:
776result = need_erase_gran_bytes(have, want, len, 1024);
777break;
778case write_gran_1056bytes:
779result = need_erase_gran_bytes(have, want, len, 1056);
780break;
781case write_gran_1byte_implicit_erase:
782/* Do not erase, handle content changes from anything->0xff by writing 0xff. */
783result = 0;
784break;
785default:
786msg_cerr("%s: Unsupported granularity! Please report a bug at "
787 "flashrom@flashrom.org\n", __func__);
788}
789return result;
790}
791
792/**
793 * Check if the buffer @have needs to be programmed to get the content of @want.
794 * If yes, return 1 and fill in first_start with the start address of the
795 * write operation and first_len with the length of the first to-be-written
796 * chunk. If not, return 0 and leave first_start and first_len undefined.
797 *
798 * Warning: This function assumes that @have and @want point to naturally
799 * aligned regions.
800 *
801 * @havebuffer with current content
802 * @wantbuffer with desired content
803 * @lenlength of the checked area
804 * @granwrite granularity (enum, not count)
805 * @first_startoffset of the first byte which needs to be written (passed in
806 *value is increased by the offset of the first needed write
807 *relative to have/want or unchanged if no write is needed)
808 * @returnlength of the first contiguous area which needs to be written
809 *0 if no write is needed
810 *
811 * FIXME: This function needs a parameter which tells it about coalescing
812 * in relation to the max write length of the programmer and the max write
813 * length of the chip.
814 */
815static unsigned int get_next_write(const uint8_t *have, const uint8_t *want, unsigned int len,
816 unsigned int *first_start,
817 enum write_granularity gran)
818{
819int need_write = 0;
820unsigned int rel_start = 0, first_len = 0;
821unsigned int i, limit, stride;
822
823switch (gran) {
824case write_gran_1bit:
825case write_gran_1byte:
826case write_gran_1byte_implicit_erase:
827stride = 1;
828break;
829case write_gran_256bytes:
830stride = 256;
831break;
832case write_gran_264bytes:
833stride = 264;
834break;
835case write_gran_512bytes:
836stride = 512;
837break;
838case write_gran_528bytes:
839stride = 528;
840break;
841case write_gran_1024bytes:
842stride = 1024;
843break;
844case write_gran_1056bytes:
845stride = 1056;
846break;
847default:
848msg_cerr("%s: Unsupported granularity! Please report a bug at "
849 "flashrom@flashrom.org\n", __func__);
850/* Claim that no write was needed. A write with unknown
851 * granularity is too dangerous to try.
852 */
853return 0;
854}
855for (i = 0; i < len / stride; i++) {
856limit = min(stride, len - i * stride);
857/* Are 'have' and 'want' identical? */
858if (memcmp(have + i * stride, want + i * stride, limit)) {
859if (!need_write) {
860/* First location where have and want differ. */
861need_write = 1;
862rel_start = i * stride;
863}
864} else {
865if (need_write) {
866/* First location where have and want
867 * do not differ anymore.
868 */
869break;
870}
871}
872}
873if (need_write)
874first_len = min(i * stride - rel_start, len);
875*first_start += rel_start;
876return first_len;
877}
878
879/* This function generates various test patterns useful for testing controller
880 * and chip communication as well as chip behaviour.
881 *
882 * If a byte can be written multiple times, each time keeping 0-bits at 0
883 * and changing 1-bits to 0 if the new value for that bit is 0, the effect
884 * is essentially an AND operation. That's also the reason why this function
885 * provides the result of AND between various patterns.
886 *
887 * Below is a list of patterns (and their block length).
888 * Pattern 0 is 05 15 25 35 45 55 65 75 85 95 a5 b5 c5 d5 e5 f5 (16 Bytes)
889 * Pattern 1 is 0a 1a 2a 3a 4a 5a 6a 7a 8a 9a aa ba ca da ea fa (16 Bytes)
890 * Pattern 2 is 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f (16 Bytes)
891 * Pattern 3 is a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af (16 Bytes)
892 * Pattern 4 is 00 10 20 30 40 50 60 70 80 90 a0 b0 c0 d0 e0 f0 (16 Bytes)
893 * Pattern 5 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f (16 Bytes)
894 * Pattern 6 is 00 (1 Byte)
895 * Pattern 7 is ff (1 Byte)
896 * Patterns 0-7 have a big-endian block number in the last 2 bytes of each 256
897 * byte block.
898 *
899 * Pattern 8 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11... (256 B)
900 * Pattern 9 is ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 ef ee... (256 B)
901 * Pattern 10 is 00 00 00 01 00 02 00 03 00 04... (128 kB big-endian counter)
902 * Pattern 11 is ff ff ff fe ff fd ff fc ff fb... (128 kB big-endian downwards)
903 * Pattern 12 is 00 (1 Byte)
904 * Pattern 13 is ff (1 Byte)
905 * Patterns 8-13 have no block number.
906 *
907 * Patterns 0-3 are created to detect and efficiently diagnose communication
908 * slips like missed bits or bytes and their repetitive nature gives good visual
909 * cues to the person inspecting the results. In addition, the following holds:
910 * AND Pattern 0/1 == Pattern 4
911 * AND Pattern 2/3 == Pattern 5
912 * AND Pattern 0/1/2/3 == AND Pattern 4/5 == Pattern 6
913 * A weakness of pattern 0-5 is the inability to detect swaps/copies between
914 * any two 16-byte blocks except for the last 16-byte block in a 256-byte bloc.
915 * They work perfectly for detecting any swaps/aliasing of blocks >= 256 bytes.
916 * 0x5 and 0xa were picked because they are 0101 and 1010 binary.
917 * Patterns 8-9 are best for detecting swaps/aliasing of blocks < 256 bytes.
918 * Besides that, they provide for bit testing of the last two bytes of every
919 * 256 byte block which contains the block number for patterns 0-6.
920 * Patterns 10-11 are special purpose for detecting subblock aliasing with
921 * block sizes >256 bytes (some Dataflash chips etc.)
922 * AND Pattern 8/9 == Pattern 12
923 * AND Pattern 10/11 == Pattern 12
924 * Pattern 13 is the completely erased state.
925 * None of the patterns can detect aliasing at boundaries which are a multiple
926 * of 16 MBytes (but such chips do not exist anyway for Parallel/LPC/FWH/SPI).
927 */
928int generate_testpattern(uint8_t *buf, uint32_t size, int variant)
929{
930int i;
931
932if (!buf) {
933msg_gerr("Invalid buffer!\n");
934return 1;
935}
936
937switch (variant) {
938case 0:
939for (i = 0; i < size; i++)
940buf[i] = (i & 0xf) << 4 | 0x5;
941break;
942case 1:
943for (i = 0; i < size; i++)
944buf[i] = (i & 0xf) << 4 | 0xa;
945break;
946case 2:
947for (i = 0; i < size; i++)
948buf[i] = 0x50 | (i & 0xf);
949break;
950case 3:
951for (i = 0; i < size; i++)
952buf[i] = 0xa0 | (i & 0xf);
953break;
954case 4:
955for (i = 0; i < size; i++)
956buf[i] = (i & 0xf) << 4;
957break;
958case 5:
959for (i = 0; i < size; i++)
960buf[i] = i & 0xf;
961break;
962case 6:
963memset(buf, 0x00, size);
964break;
965case 7:
966memset(buf, 0xff, size);
967break;
968case 8:
969for (i = 0; i < size; i++)
970buf[i] = i & 0xff;
971break;
972case 9:
973for (i = 0; i < size; i++)
974buf[i] = ~(i & 0xff);
975break;
976case 10:
977for (i = 0; i < size % 2; i++) {
978buf[i * 2] = (i >> 8) & 0xff;
979buf[i * 2 + 1] = i & 0xff;
980}
981if (size & 0x1)
982buf[i * 2] = (i >> 8) & 0xff;
983break;
984case 11:
985for (i = 0; i < size % 2; i++) {
986buf[i * 2] = ~((i >> 8) & 0xff);
987buf[i * 2 + 1] = ~(i & 0xff);
988}
989if (size & 0x1)
990buf[i * 2] = ~((i >> 8) & 0xff);
991break;
992case 12:
993memset(buf, 0x00, size);
994break;
995case 13:
996memset(buf, 0xff, size);
997break;
998}
999
1000if ((variant >= 0) && (variant <= 7)) {
1001/* Write block number in the last two bytes of each 256-byte
1002 * block, big endian for easier reading of the hexdump.
1003 * Note that this wraps around for chips larger than 2^24 bytes
1004 * (16 MB).
1005 */
1006for (i = 0; i < size / 256; i++) {
1007buf[i * 256 + 254] = (i >> 8) & 0xff;
1008buf[i * 256 + 255] = i & 0xff;
1009}
1010}
1011
1012return 0;
1013}
1014
1015int check_max_decode(enum chipbustype buses, uint32_t size)
1016{
1017int limitexceeded = 0;
1018
1019if ((buses & BUS_PARALLEL) && (max_rom_decode.parallel < size)) {
1020limitexceeded++;
1021msg_pdbg("Chip size %u kB is bigger than supported "
1022 "size %u kB of chipset/board/programmer "
1023 "for %s interface, "
1024 "probe/read/erase/write may fail. ", size / 1024,
1025 max_rom_decode.parallel / 1024, "Parallel");
1026}
1027if ((buses & BUS_LPC) && (max_rom_decode.lpc < size)) {
1028limitexceeded++;
1029msg_pdbg("Chip size %u kB is bigger than supported "
1030 "size %u kB of chipset/board/programmer "
1031 "for %s interface, "
1032 "probe/read/erase/write may fail. ", size / 1024,
1033 max_rom_decode.lpc / 1024, "LPC");
1034}
1035if ((buses & BUS_FWH) && (max_rom_decode.fwh < size)) {
1036limitexceeded++;
1037msg_pdbg("Chip size %u kB is bigger than supported "
1038 "size %u kB of chipset/board/programmer "
1039 "for %s interface, "
1040 "probe/read/erase/write may fail. ", size / 1024,
1041 max_rom_decode.fwh / 1024, "FWH");
1042}
1043if ((buses & BUS_SPI) && (max_rom_decode.spi < size)) {
1044limitexceeded++;
1045msg_pdbg("Chip size %u kB is bigger than supported "
1046 "size %u kB of chipset/board/programmer "
1047 "for %s interface, "
1048 "probe/read/erase/write may fail. ", size / 1024,
1049 max_rom_decode.spi / 1024, "SPI");
1050}
1051if (!limitexceeded)
1052return 0;
1053/* Sometimes chip and programmer have more than one bus in common,
1054 * and the limit is not exceeded on all buses. Tell the user.
1055 */
1056if (bitcount(buses) > limitexceeded)
1057/* FIXME: This message is designed towards CLI users. */
1058msg_pdbg("There is at least one common chip/programmer "
1059 "interface which can support a chip of this size. "
1060 "You can try --force at your own risk.\n");
1061return 1;
1062}
1063
1064int probe_flash(struct registered_master *mst, int startchip, struct flashctx *flash, int force)
1065{
1066const struct flashchip *chip;
1067unsigned long base = 0;
1068char location[64];
1069uint32_t size;
1070enum chipbustype buses_common;
1071char *tmp;
1072
1073for (chip = flashchips + startchip; chip && chip->name; chip++) {
1074if (chip_to_probe && strcmp(chip->name, chip_to_probe) != 0)
1075continue;
1076buses_common = mst->buses_supported & chip->bustype;
1077if (!buses_common)
1078continue;
1079msg_gdbg("Probing for %s %s, %d kB: ", chip->vendor, chip->name, chip->total_size);
1080if (!chip->probe && !force) {
1081msg_gdbg("failed! flashrom has no probe function for this flash chip.\n");
1082continue;
1083}
1084
1085size = chip->total_size * 1024;
1086check_max_decode(buses_common, size);
1087
1088/* Start filling in the dynamic data. */
1089flash->chip = calloc(1, sizeof(struct flashchip));
1090if (!flash->chip) {
1091msg_gerr("Out of memory!\n");
1092exit(1);
1093}
1094memcpy(flash->chip, chip, sizeof(struct flashchip));
1095flash->mst = mst;
1096
1097base = flashbase ? flashbase : (0xffffffff - size + 1);
1098flash->virtual_memory = (chipaddr)programmer_map_flash_region("flash chip", base, size);
1099
1100/* We handle a forced match like a real match, we just avoid probing. Note that probe_flash()
1101 * is only called with force=1 after normal probing failed.
1102 */
1103if (force)
1104break;
1105
1106if (flash->chip->probe(flash) != 1)
1107goto notfound;
1108
1109/* If this is the first chip found, accept it.
1110 * If this is not the first chip found, accept it only if it is
1111 * a non-generic match. SFDP and CFI are generic matches.
1112 * startchip==0 means this call to probe_flash() is the first
1113 * one for this programmer interface (master) and thus no other chip has
1114 * been found on this interface.
1115 */
1116if (startchip == 0 && flash->chip->model_id == SFDP_DEVICE_ID) {
1117msg_cinfo("===\n"
1118 "SFDP has autodetected a flash chip which is "
1119 "not natively supported by flashrom yet.\n");
1120if (count_usable_erasers(flash) == 0)
1121msg_cinfo("The standard operations read and "
1122 "verify should work, but to support "
1123 "erase, write and all other "
1124 "possible features");
1125else
1126msg_cinfo("All standard operations (read, "
1127 "verify, erase and write) should "
1128 "work, but to support all possible "
1129 "features");
1130
1131msg_cinfo(" we need to add them manually.\n"
1132 "You can help us by mailing us the output of the following command to "
1133 "flashrom@flashrom.org:\n"
1134 "'flashrom -VV [plus the -p/--programmer parameter]'\n"
1135 "Thanks for your help!\n"
1136 "===\n");
1137}
1138
1139/* First flash chip detected on this bus. */
1140if (startchip == 0)
1141break;
1142/* Not the first flash chip detected on this bus, but not a generic match either. */
1143if ((flash->chip->model_id != GENERIC_DEVICE_ID) && (flash->chip->model_id != SFDP_DEVICE_ID))
1144break;
1145/* Not the first flash chip detected on this bus, and it's just a generic match. Ignore it. */
1146notfound:
1147programmer_unmap_flash_region((void *)flash->virtual_memory, size);
1148flash->virtual_memory = (chipaddr)NULL;
1149free(flash->chip);
1150flash->chip = NULL;
1151}
1152
1153if (!flash->chip)
1154return -1;
1155
1156#if CONFIG_INTERNAL == 1
1157if (programmer_table[programmer].map_flash_region == physmap)
1158snprintf(location, sizeof(location), "at physical address 0x%lx", base);
1159else
1160#endif
1161snprintf(location, sizeof(location), "on %s", programmer_table[programmer].name);
1162
1163tmp = flashbuses_to_text(flash->chip->bustype);
1164msg_cinfo("%s %s flash chip \"%s\" (%d kB, %s) %s.\n", force ? "Assuming" : "Found",
1165 flash->chip->vendor, flash->chip->name, flash->chip->total_size, tmp, location);
1166free(tmp);
1167
1168/* Flash registers will not be mapped if the chip was forced. Lock info
1169 * may be stored in registers, so avoid lock info printing.
1170 */
1171if (!force)
1172if (flash->chip->printlock)
1173flash->chip->printlock(flash);
1174
1175/* Return position of matching chip. */
1176return chip - flashchips;
1177}
1178
1179int read_buf_from_file(unsigned char *buf, unsigned long size,
1180 const char *filename)
1181{
1182#ifdef __LIBPAYLOAD__
1183msg_gerr("Error: No file I/O support in libpayload\n");
1184return 1;
1185#else
1186unsigned long numbytes;
1187FILE *image;
1188struct stat image_stat;
1189
1190if ((image = fopen(filename, "rb")) == NULL) {
1191msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
1192return 1;
1193}
1194if (fstat(fileno(image), &image_stat) != 0) {
1195msg_gerr("Error: getting metadata of file \"%s\" failed: %s\n", filename, strerror(errno));
1196fclose(image);
1197return 1;
1198}
1199if (image_stat.st_size != size) {
1200msg_gerr("Error: Image size (%jd B) doesn't match the flash chip's size (%lu B)!\n",
1201 (intmax_t)image_stat.st_size, size);
1202fclose(image);
1203return 1;
1204}
1205numbytes = fread(buf, 1, size, image);
1206if (fclose(image)) {
1207msg_gerr("Error: closing file \"%s\" failed: %s\n", filename, strerror(errno));
1208return 1;
1209}
1210if (numbytes != size) {
1211msg_gerr("Error: Failed to read complete file. Got %ld bytes, "
1212 "wanted %ld!\n", numbytes, size);
1213return 1;
1214}
1215return 0;
1216#endif
1217}
1218
1219int write_buf_to_file(const unsigned char *buf, unsigned long size, const char *filename)
1220{
1221#ifdef __LIBPAYLOAD__
1222msg_gerr("Error: No file I/O support in libpayload\n");
1223return 1;
1224#else
1225unsigned long numbytes;
1226FILE *image;
1227
1228if (!filename) {
1229msg_gerr("No filename specified.\n");
1230return 1;
1231}
1232if ((image = fopen(filename, "wb")) == NULL) {
1233msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
1234return 1;
1235}
1236
1237numbytes = fwrite(buf, 1, size, image);
1238fclose(image);
1239if (numbytes != size) {
1240msg_gerr("File %s could not be written completely.\n",
1241 filename);
1242return 1;
1243}
1244return 0;
1245#endif
1246}
1247
1248int read_flash_to_file(struct flashctx *flash, const char *filename)
1249{
1250unsigned long size = flash->chip->total_size * 1024;
1251unsigned char *buf = calloc(size, sizeof(char));
1252int ret = 0;
1253
1254msg_cinfo("Reading flash... ");
1255if (!buf) {
1256msg_gerr("Memory allocation failed!\n");
1257msg_cinfo("FAILED.\n");
1258return 1;
1259}
1260if (!flash->chip->read) {
1261msg_cerr("No read function available for this flash chip.\n");
1262ret = 1;
1263goto out_free;
1264}
1265if (flash->chip->read(flash, buf, 0, size)) {
1266msg_cerr("Read operation failed!\n");
1267ret = 1;
1268goto out_free;
1269}
1270
1271ret = write_buf_to_file(buf, size, filename);
1272out_free:
1273free(buf);
1274msg_cinfo("%s.\n", ret ? "FAILED" : "done");
1275return ret;
1276}
1277
1278/* Even if an error is found, the function will keep going and check the rest. */
1279static int selfcheck_eraseblocks(const struct flashchip *chip)
1280{
1281int i, j, k;
1282int ret = 0;
1283
1284for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1285unsigned int done = 0;
1286struct block_eraser eraser = chip->block_erasers[k];
1287
1288for (i = 0; i < NUM_ERASEREGIONS; i++) {
1289/* Blocks with zero size are bugs in flashchips.c. */
1290if (eraser.eraseblocks[i].count &&
1291 !eraser.eraseblocks[i].size) {
1292msg_gerr("ERROR: Flash chip %s erase function "
1293"%i region %i has size 0. Please report"
1294" a bug at flashrom@flashrom.org\n",
1295chip->name, k, i);
1296ret = 1;
1297}
1298/* Blocks with zero count are bugs in flashchips.c. */
1299if (!eraser.eraseblocks[i].count &&
1300 eraser.eraseblocks[i].size) {
1301msg_gerr("ERROR: Flash chip %s erase function "
1302"%i region %i has count 0. Please report"
1303" a bug at flashrom@flashrom.org\n",
1304chip->name, k, i);
1305ret = 1;
1306}
1307done += eraser.eraseblocks[i].count *
1308eraser.eraseblocks[i].size;
1309}
1310/* Empty eraseblock definition with erase function. */
1311if (!done && eraser.block_erase)
1312msg_gspew("Strange: Empty eraseblock definition with "
1313 "non-empty erase function. Not an error.\n");
1314if (!done)
1315continue;
1316if (done != chip->total_size * 1024) {
1317msg_gerr("ERROR: Flash chip %s erase function %i "
1318"region walking resulted in 0x%06x bytes total,"
1319" expected 0x%06x bytes. Please report a bug at"
1320" flashrom@flashrom.org\n", chip->name, k,
1321done, chip->total_size * 1024);
1322ret = 1;
1323}
1324if (!eraser.block_erase)
1325continue;
1326/* Check if there are identical erase functions for different
1327 * layouts. That would imply "magic" erase functions. The
1328 * easiest way to check this is with function pointers.
1329 */
1330for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
1331if (eraser.block_erase ==
1332 chip->block_erasers[j].block_erase) {
1333msg_gerr("ERROR: Flash chip %s erase function "
1334"%i and %i are identical. Please report"
1335" a bug at flashrom@flashrom.org\n",
1336chip->name, k, j);
1337ret = 1;
1338}
1339}
1340}
1341return ret;
1342}
1343
1344static int erase_and_write_block_helper(struct flashctx *flash,
1345unsigned int start, unsigned int len,
1346uint8_t *curcontents,
1347uint8_t *newcontents,
1348int (*erasefn) (struct flashctx *flash,
1349unsigned int addr,
1350unsigned int len))
1351{
1352unsigned int starthere = 0, lenhere = 0;
1353int ret = 0, skip = 1, writecount = 0;
1354enum write_granularity gran = flash->chip->gran;
1355
1356/* curcontents and newcontents are opaque to walk_eraseregions, and
1357 * need to be adjusted here to keep the impression of proper abstraction
1358 */
1359curcontents += start;
1360newcontents += start;
1361msg_cdbg(":");
1362if (need_erase(curcontents, newcontents, len, gran)) {
1363msg_cdbg("E");
1364ret = erasefn(flash, start, len);
1365if (ret)
1366return ret;
1367if (check_erased_range(flash, start, len)) {
1368msg_cerr("ERASE FAILED!\n");
1369return -1;
1370}
1371/* Erase was successful. Adjust curcontents. */
1372memset(curcontents, 0xff, len);
1373skip = 0;
1374}
1375/* get_next_write() sets starthere to a new value after the call. */
1376while ((lenhere = get_next_write(curcontents + starthere,
1377 newcontents + starthere,
1378 len - starthere, &starthere, gran))) {
1379if (!writecount++)
1380msg_cdbg("W");
1381/* Needs the partial write function signature. */
1382ret = flash->chip->write(flash, newcontents + starthere,
1383 start + starthere, lenhere);
1384if (ret)
1385return ret;
1386starthere += lenhere;
1387skip = 0;
1388}
1389if (skip)
1390msg_cdbg("S");
1391else
1392all_skipped = false;
1393return ret;
1394}
1395
1396static int walk_eraseregions(struct flashctx *flash, int erasefunction,
1397 int (*do_something) (struct flashctx *flash,
1398 unsigned int addr,
1399 unsigned int len,
1400 uint8_t *param1,
1401 uint8_t *param2,
1402 int (*erasefn) (
1403struct flashctx *flash,
1404unsigned int addr,
1405unsigned int len)),
1406 void *param1, void *param2)
1407{
1408int i, j;
1409unsigned int start = 0;
1410unsigned int len;
1411struct block_eraser eraser = flash->chip->block_erasers[erasefunction];
1412
1413for (i = 0; i < NUM_ERASEREGIONS; i++) {
1414/* count==0 for all automatically initialized array
1415 * members so the loop below won't be executed for them.
1416 */
1417len = eraser.eraseblocks[i].size;
1418for (j = 0; j < eraser.eraseblocks[i].count; j++) {
1419/* Print this for every block except the first one. */
1420if (i || j)
1421msg_cdbg(", ");
1422msg_cdbg("0x%06x-0x%06x", start,
1423 start + len - 1);
1424if (do_something(flash, start, len, param1, param2,
1425 eraser.block_erase)) {
1426return 1;
1427}
1428start += len;
1429}
1430}
1431msg_cdbg("\n");
1432return 0;
1433}
1434
1435static int check_block_eraser(const struct flashctx *flash, int k, int log)
1436{
1437struct block_eraser eraser = flash->chip->block_erasers[k];
1438
1439if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
1440if (log)
1441msg_cdbg("not defined. ");
1442return 1;
1443}
1444if (!eraser.block_erase && eraser.eraseblocks[0].count) {
1445if (log)
1446msg_cdbg("eraseblock layout is known, but matching "
1447 "block erase function is not implemented. ");
1448return 1;
1449}
1450if (eraser.block_erase && !eraser.eraseblocks[0].count) {
1451if (log)
1452msg_cdbg("block erase function found, but "
1453 "eraseblock layout is not defined. ");
1454return 1;
1455}
1456// TODO: Once erase functions are annotated with allowed buses, check that as well.
1457return 0;
1458}
1459
1460int erase_and_write_flash(struct flashctx *flash, uint8_t *oldcontents, uint8_t *newcontents)
1461{
1462int k, ret = 1;
1463uint8_t *curcontents;
1464unsigned long size = flash->chip->total_size * 1024;
1465unsigned int usable_erasefunctions = count_usable_erasers(flash);
1466
1467msg_cinfo("Erasing and writing flash chip... ");
1468curcontents = malloc(size);
1469if (!curcontents) {
1470msg_gerr("Out of memory!\n");
1471exit(1);
1472}
1473/* Copy oldcontents to curcontents to avoid clobbering oldcontents. */
1474memcpy(curcontents, oldcontents, size);
1475
1476for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
1477if (k != 0)
1478msg_cinfo("Looking for another erase function.\n");
1479if (!usable_erasefunctions) {
1480msg_cinfo("No usable erase functions left.\n");
1481break;
1482}
1483msg_cdbg("Trying erase function %i... ", k);
1484if (check_block_eraser(flash, k, 1))
1485continue;
1486usable_erasefunctions--;
1487ret = walk_eraseregions(flash, k, &erase_and_write_block_helper,
1488curcontents, newcontents);
1489/* If everything is OK, don't try another erase function. */
1490if (!ret)
1491break;
1492/* Write/erase failed, so try to find out what the current chip
1493 * contents are. If no usable erase functions remain, we can
1494 * skip this: the next iteration will break immediately anyway.
1495 */
1496if (!usable_erasefunctions)
1497continue;
1498/* Reading the whole chip may take a while, inform the user even
1499 * in non-verbose mode.
1500 */
1501msg_cinfo("Reading current flash chip contents... ");
1502if (flash->chip->read(flash, curcontents, 0, size)) {
1503/* Now we are truly screwed. Read failed as well. */
1504msg_cerr("Can't read anymore! Aborting.\n");
1505/* We have no idea about the flash chip contents, so
1506 * retrying with another erase function is pointless.
1507 */
1508break;
1509}
1510msg_cinfo("done. ");
1511}
1512/* Free the scratchpad. */
1513free(curcontents);
1514
1515if (ret) {
1516msg_cerr("FAILED!\n");
1517} else {
1518if (all_skipped)
1519msg_cinfo("\nWarning: Chip content is identical to the requested image.\n");
1520msg_cinfo("Erase/write done.\n");
1521}
1522return ret;
1523}
1524
1525static void nonfatal_help_message(void)
1526{
1527msg_gerr("Good, writing to the flash chip apparently didn't do anything.\n");
1528#if CONFIG_INTERNAL == 1
1529if (programmer == PROGRAMMER_INTERNAL)
1530msg_gerr("This means we have to add special support for your board, programmer or flash\n"
1531 "chip. Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
1532 "mail flashrom@flashrom.org, thanks!\n"
1533 "-------------------------------------------------------------------------------\n"
1534 "You may now reboot or simply leave the machine running.\n");
1535else
1536#endif
1537msg_gerr("Please check the connections (especially those to write protection pins) between\n"
1538 "the programmer and the flash chip. If you think the error is caused by flashrom\n"
1539 "please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
1540 "mail flashrom@flashrom.org, thanks!\n");
1541}
1542
1543static void emergency_help_message(void)
1544{
1545msg_gerr("Your flash chip is in an unknown state.\n");
1546#if CONFIG_INTERNAL == 1
1547if (programmer == PROGRAMMER_INTERNAL)
1548msg_gerr("Get help on IRC at chat.freenode.net (channel #flashrom) or\n"
1549"mail flashrom@flashrom.org with the subject \"FAILED: <your board name>\"!\n"
1550"-------------------------------------------------------------------------------\n"
1551"DO NOT REBOOT OR POWEROFF!\n");
1552else
1553#endif
1554msg_gerr("Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
1555 "mail flashrom@flashrom.org, thanks!\n");
1556}
1557
1558/* The way to go if you want a delimited list of programmers */
1559void list_programmers(const char *delim)
1560{
1561enum programmer p;
1562for (p = 0; p < PROGRAMMER_INVALID; p++) {
1563msg_ginfo("%s", programmer_table[p].name);
1564if (p < PROGRAMMER_INVALID - 1)
1565msg_ginfo("%s", delim);
1566}
1567msg_ginfo("\n");
1568}
1569
1570void list_programmers_linebreak(int startcol, int cols, int paren)
1571{
1572const char *pname;
1573int pnamelen;
1574int remaining = 0, firstline = 1;
1575enum programmer p;
1576int i;
1577
1578for (p = 0; p < PROGRAMMER_INVALID; p++) {
1579pname = programmer_table[p].name;
1580pnamelen = strlen(pname);
1581if (remaining - pnamelen - 2 < 0) {
1582if (firstline)
1583firstline = 0;
1584else
1585msg_ginfo("\n");
1586for (i = 0; i < startcol; i++)
1587msg_ginfo(" ");
1588remaining = cols - startcol;
1589} else {
1590msg_ginfo(" ");
1591remaining--;
1592}
1593if (paren && (p == 0)) {
1594msg_ginfo("(");
1595remaining--;
1596}
1597msg_ginfo("%s", pname);
1598remaining -= pnamelen;
1599if (p < PROGRAMMER_INVALID - 1) {
1600msg_ginfo(",");
1601remaining--;
1602} else {
1603if (paren)
1604msg_ginfo(")");
1605}
1606}
1607}
1608
1609void print_sysinfo(void)
1610{
1611#ifdef _WIN32
1612SYSTEM_INFO si;
1613OSVERSIONINFOEX osvi;
1614
1615memset(&si, 0, sizeof(SYSTEM_INFO));
1616memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
1617msg_ginfo(" on Windows");
1618/* Tell Windows which version of the structure we want. */
1619osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1620if (GetVersionEx((OSVERSIONINFO*) &osvi))
1621msg_ginfo(" %lu.%lu", osvi.dwMajorVersion, osvi.dwMinorVersion);
1622else
1623msg_ginfo(" unknown version");
1624GetSystemInfo(&si);
1625switch (si.wProcessorArchitecture) {
1626case PROCESSOR_ARCHITECTURE_AMD64:
1627msg_ginfo(" (x86_64)");
1628break;
1629case PROCESSOR_ARCHITECTURE_INTEL:
1630msg_ginfo(" (x86)");
1631break;
1632default:
1633msg_ginfo(" (unknown arch)");
1634break;
1635}
1636#elif HAVE_UTSNAME == 1
1637struct utsname osinfo;
1638
1639uname(&osinfo);
1640msg_ginfo(" on %s %s (%s)", osinfo.sysname, osinfo.release,
1641 osinfo.machine);
1642#else
1643msg_ginfo(" on unknown machine");
1644#endif
1645}
1646
1647void print_buildinfo(void)
1648{
1649msg_gdbg("flashrom was built with");
1650#if NEED_PCI == 1
1651#ifdef PCILIB_VERSION
1652msg_gdbg(" libpci %s,", PCILIB_VERSION);
1653#else
1654msg_gdbg(" unknown PCI library,");
1655#endif
1656#endif
1657#ifdef __clang__
1658msg_gdbg(" LLVM Clang");
1659#ifdef __clang_version__
1660msg_gdbg(" %s,", __clang_version__);
1661#else
1662msg_gdbg(" unknown version (before r102686),");
1663#endif
1664#elif defined(__GNUC__)
1665msg_gdbg(" GCC");
1666#ifdef __VERSION__
1667msg_gdbg(" %s,", __VERSION__);
1668#else
1669msg_gdbg(" unknown version,");
1670#endif
1671#else
1672msg_gdbg(" unknown compiler,");
1673#endif
1674#if defined (__FLASHROM_LITTLE_ENDIAN__)
1675msg_gdbg(" little endian");
1676#elif defined (__FLASHROM_BIG_ENDIAN__)
1677msg_gdbg(" big endian");
1678#else
1679#error Endianness could not be determined
1680#endif
1681msg_gdbg("\n");
1682}
1683
1684void print_version(void)
1685{
1686msg_ginfo("flashrom v%s", flashrom_version);
1687print_sysinfo();
1688msg_ginfo("\n");
1689}
1690
1691void print_banner(void)
1692{
1693msg_ginfo("flashrom is free software, get the source code at "
1694 "http://www.flashrom.org\n");
1695msg_ginfo("\n");
1696}
1697
1698int selfcheck(void)
1699{
1700unsigned int i;
1701int ret = 0;
1702
1703/* Safety check. Instead of aborting after the first error, check
1704 * if more errors exist.
1705 */
1706if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
1707msg_gerr("Programmer table miscompilation!\n");
1708ret = 1;
1709}
1710for (i = 0; i < PROGRAMMER_INVALID; i++) {
1711const struct programmer_entry p = programmer_table[i];
1712if (p.name == NULL) {
1713msg_gerr("All programmers need a valid name, but the one with index %d does not!\n", i);
1714ret = 1;
1715/* This might hide other problems with this programmer, but allows for better error
1716 * messages below without jumping through hoops. */
1717continue;
1718}
1719switch (p.type) {
1720case USB:
1721case PCI:
1722case OTHER:
1723if (p.devs.note == NULL) {
1724if (strcmp("internal", p.name) == 0)
1725break; /* This one has its device list stored separately. */
1726msg_gerr("Programmer %s has neither a device list nor a textual description!\n",
1727 p.name);
1728ret = 1;
1729}
1730break;
1731default:
1732msg_gerr("Programmer %s does not have a valid type set!\n", p.name);
1733ret = 1;
1734break;
1735}
1736if (p.init == NULL) {
1737msg_gerr("Programmer %s does not have a valid init function!\n", p.name);
1738ret = 1;
1739}
1740if (p.delay == NULL) {
1741msg_gerr("Programmer %s does not have a valid delay function!\n", p.name);
1742ret = 1;
1743}
1744if (p.map_flash_region == NULL) {
1745msg_gerr("Programmer %s does not have a valid map_flash_region function!\n", p.name);
1746ret = 1;
1747}
1748if (p.unmap_flash_region == NULL) {
1749msg_gerr("Programmer %s does not have a valid unmap_flash_region function!\n", p.name);
1750ret = 1;
1751}
1752}
1753
1754/* It would be favorable if we could check for the correct layout (especially termination) of various
1755 * constant arrays: flashchips, chipset_enables, board_matches, boards_known, laptops_known.
1756 * They are all defined as externs in this compilation unit so we don't know their sizes which vary
1757 * depending on compiler flags, e.g. the target architecture, and can sometimes be 0.
1758 * For 'flashchips' we export the size explicitly to work around this and to be able to implement the
1759 * checks below. */
1760if (flashchips_size <= 1 || flashchips[flashchips_size-1].name != NULL) {
1761msg_gerr("Flashchips table miscompilation!\n");
1762ret = 1;
1763} else {
1764for (i = 0; i < flashchips_size - 1; i++) {
1765const struct flashchip *chip = &flashchips[i];
1766if (chip->vendor == NULL || chip->name == NULL || chip->bustype == BUS_NONE) {
1767ret = 1;
1768msg_gerr("ERROR: Some field of flash chip #%d (%s) is misconfigured.\n"
1769 "Please report a bug at flashrom@flashrom.org\n", i,
1770 chip->name == NULL ? "unnamed" : chip->name);
1771}
1772if (selfcheck_eraseblocks(chip)) {
1773ret = 1;
1774}
1775}
1776}
1777
1778#if CONFIG_INTERNAL == 1
1779ret |= selfcheck_board_enables();
1780#endif
1781
1782/* TODO: implement similar sanity checks for other arrays where deemed necessary. */
1783return ret;
1784}
1785
1786void check_chip_supported(const struct flashchip *chip)
1787{
1788if (chip->feature_bits & FEATURE_OTP) {
1789msg_cdbg("This chip may contain one-time programmable memory. "
1790 "flashrom cannot read\nand may never be able to write "
1791 "it, hence it may not be able to completely\n"
1792 "clone the contents of this chip (see man page for "
1793 "details).\n");
1794}
1795
1796if ((chip->tested.erase == NA) && (chip->tested.write == NA)) {
1797msg_cdbg("This chip's main memory can not be erased/written by design.\n");
1798}
1799
1800if ((chip->tested.probe == BAD) || (chip->tested.probe == NT) ||
1801 (chip->tested.read == BAD) || (chip->tested.read == NT) ||
1802 (chip->tested.erase == BAD) || (chip->tested.erase == NT) ||
1803 (chip->tested.write == BAD) || (chip->tested.write == NT)){
1804msg_cinfo("===\n");
1805if ((chip->tested.probe == BAD) ||
1806 (chip->tested.read == BAD) ||
1807 (chip->tested.erase == BAD) ||
1808 (chip->tested.write == BAD)) {
1809msg_cinfo("This flash part has status NOT WORKING for operations:");
1810if (chip->tested.probe == BAD)
1811msg_cinfo(" PROBE");
1812if (chip->tested.read == BAD)
1813msg_cinfo(" READ");
1814if (chip->tested.erase == BAD)
1815msg_cinfo(" ERASE");
1816if (chip->tested.write == BAD)
1817msg_cinfo(" WRITE");
1818msg_cinfo("\n");
1819}
1820if ((chip->tested.probe == NT) ||
1821 (chip->tested.read == NT) ||
1822 (chip->tested.erase == NT) ||
1823 (chip->tested.write == NT)) {
1824msg_cinfo("This flash part has status UNTESTED for operations:");
1825if (chip->tested.probe == NT)
1826msg_cinfo(" PROBE");
1827if (chip->tested.read == NT)
1828msg_cinfo(" READ");
1829if (chip->tested.erase == NT)
1830msg_cinfo(" ERASE");
1831if (chip->tested.write == NT)
1832msg_cinfo(" WRITE");
1833msg_cinfo("\n");
1834}
1835/* FIXME: This message is designed towards CLI users. */
1836msg_cinfo("The test status of this chip may have been updated "
1837 "in the latest development\n"
1838 "version of flashrom. If you are running the latest "
1839 "development version,\n"
1840 "please email a report to flashrom@flashrom.org if "
1841 "any of the above operations\n"
1842 "work correctly for you with this flash part. Please "
1843 "include the flashrom\n"
1844 "output with the additional -V option for all "
1845 "operations you tested (-V, -Vr,\n"
1846 "-VE, -Vw), and mention which mainboard or "
1847 "programmer you tested.\n"
1848 "Please mention your board in the subject line. "
1849 "Thanks for your help!\n");
1850}
1851}
1852
1853/* FIXME: This function signature needs to be improved once doit() has a better
1854 * function signature.
1855 */
1856int chip_safety_check(const struct flashctx *flash, int force, int read_it, int write_it, int erase_it,
1857 int verify_it)
1858{
1859const struct flashchip *chip = flash->chip;
1860
1861if (!programmer_may_write && (write_it || erase_it)) {
1862msg_perr("Write/erase is not working yet on your programmer in "
1863 "its current configuration.\n");
1864/* --force is the wrong approach, but it's the best we can do
1865 * until the generic programmer parameter parser is merged.
1866 */
1867if (!force)
1868return 1;
1869msg_cerr("Continuing anyway.\n");
1870}
1871
1872if (read_it || erase_it || write_it || verify_it) {
1873/* Everything needs read. */
1874if (chip->tested.read == BAD) {
1875msg_cerr("Read is not working on this chip. ");
1876if (!force)
1877return 1;
1878msg_cerr("Continuing anyway.\n");
1879}
1880if (!chip->read) {
1881msg_cerr("flashrom has no read function for this "
1882 "flash chip.\n");
1883return 1;
1884}
1885}
1886if (erase_it || write_it) {
1887/* Write needs erase. */
1888if (chip->tested.erase == NA) {
1889msg_cerr("Erase is not possible on this chip.\n");
1890return 1;
1891}
1892if (chip->tested.erase == BAD) {
1893msg_cerr("Erase is not working on this chip. ");
1894if (!force)
1895return 1;
1896msg_cerr("Continuing anyway.\n");
1897}
1898if(count_usable_erasers(flash) == 0) {
1899msg_cerr("flashrom has no erase function for this "
1900 "flash chip.\n");
1901return 1;
1902}
1903}
1904if (write_it) {
1905if (chip->tested.write == NA) {
1906msg_cerr("Write is not possible on this chip.\n");
1907return 1;
1908}
1909if (chip->tested.write == BAD) {
1910msg_cerr("Write is not working on this chip. ");
1911if (!force)
1912return 1;
1913msg_cerr("Continuing anyway.\n");
1914}
1915if (!chip->write) {
1916msg_cerr("flashrom has no write function for this "
1917 "flash chip.\n");
1918return 1;
1919}
1920}
1921return 0;
1922}
1923
1924/* This function signature is horrible. We need to design a better interface,
1925 * but right now it allows us to split off the CLI code.
1926 * Besides that, the function itself is a textbook example of abysmal code flow.
1927 */
1928int doit(struct flashctx *flash, int force, const char *filename, int read_it,
1929 int write_it, int erase_it, int verify_it)
1930{
1931uint8_t *oldcontents;
1932uint8_t *newcontents;
1933int ret = 0;
1934unsigned long size = flash->chip->total_size * 1024;
1935
1936if (chip_safety_check(flash, force, read_it, write_it, erase_it, verify_it)) {
1937msg_cerr("Aborting.\n");
1938return 1;
1939}
1940
1941if (normalize_romentries(flash)) {
1942msg_cerr("Requested regions can not be handled. Aborting.\n");
1943return 1;
1944}
1945
1946/* Given the existence of read locks, we want to unlock for read,
1947 * erase and write.
1948 */
1949if (flash->chip->unlock)
1950flash->chip->unlock(flash);
1951
1952if (read_it) {
1953return read_flash_to_file(flash, filename);
1954}
1955
1956oldcontents = malloc(size);
1957if (!oldcontents) {
1958msg_gerr("Out of memory!\n");
1959exit(1);
1960}
1961/* Assume worst case: All bits are 0. */
1962memset(oldcontents, 0x00, size);
1963newcontents = malloc(size);
1964if (!newcontents) {
1965msg_gerr("Out of memory!\n");
1966exit(1);
1967}
1968/* Assume best case: All bits should be 1. */
1969memset(newcontents, 0xff, size);
1970/* Side effect of the assumptions above: Default write action is erase
1971 * because newcontents looks like a completely erased chip, and
1972 * oldcontents being completely 0x00 means we have to erase everything
1973 * before we can write.
1974 */
1975
1976if (erase_it) {
1977/* FIXME: Do we really want the scary warning if erase failed?
1978 * After all, after erase the chip is either blank or partially
1979 * blank or it has the old contents. A blank chip won't boot,
1980 * so if the user wanted erase and reboots afterwards, the user
1981 * knows very well that booting won't work.
1982 */
1983if (erase_and_write_flash(flash, oldcontents, newcontents)) {
1984emergency_help_message();
1985ret = 1;
1986}
1987goto out;
1988}
1989
1990if (write_it || verify_it) {
1991if (read_buf_from_file(newcontents, size, filename)) {
1992ret = 1;
1993goto out;
1994}
1995
1996#if CONFIG_INTERNAL == 1
1997if (programmer == PROGRAMMER_INTERNAL && cb_check_image(newcontents, size) < 0) {
1998if (force_boardmismatch) {
1999msg_pinfo("Proceeding anyway because user forced us to.\n");
2000} else {
2001msg_perr("Aborting. You can override this with "
2002 "-p internal:boardmismatch=force.\n");
2003ret = 1;
2004goto out;
2005}
2006}
2007#endif
2008}
2009
2010/* Read the whole chip to be able to check whether regions need to be
2011 * erased and to give better diagnostics in case write fails.
2012 * The alternative would be to read only the regions which are to be
2013 * preserved, but in that case we might perform unneeded erase which
2014 * takes time as well.
2015 */
2016msg_cinfo("Reading old flash chip contents... ");
2017if (flash->chip->read(flash, oldcontents, 0, size)) {
2018ret = 1;
2019msg_cinfo("FAILED.\n");
2020goto out;
2021}
2022msg_cinfo("done.\n");
2023
2024/* Build a new image taking the given layout into account. */
2025build_new_image(flash, oldcontents, newcontents);
2026
2027// ////////////////////////////////////////////////////////////
2028
2029if (write_it) {
2030if (erase_and_write_flash(flash, oldcontents, newcontents)) {
2031msg_cerr("Uh oh. Erase/write failed. Checking if anything has changed.\n");
2032msg_cinfo("Reading current flash chip contents... ");
2033if (!flash->chip->read(flash, newcontents, 0, size)) {
2034msg_cinfo("done.\n");
2035if (!memcmp(oldcontents, newcontents, size)) {
2036nonfatal_help_message();
2037ret = 1;
2038goto out;
2039}
2040msg_cerr("Apparently at least some data has changed.\n");
2041} else
2042msg_cerr("Can't even read anymore!\n");
2043emergency_help_message();
2044ret = 1;
2045goto out;
2046}
2047}
2048
2049/* Verify only if we either did not try to write (verify operation) or actually changed something. */
2050if (verify_it && (!write_it || !all_skipped)) {
2051msg_cinfo("Verifying flash... ");
2052
2053if (write_it) {
2054/* Work around chips which need some time to calm down. */
2055programmer_delay(1000*1000);
2056ret = verify_range(flash, newcontents, 0, size);
2057/* If we tried to write, and verification now fails, we
2058 * might have an emergency situation.
2059 */
2060if (ret)
2061emergency_help_message();
2062} else {
2063ret = compare_range(newcontents, oldcontents, 0, size);
2064}
2065if (!ret)
2066msg_cinfo("VERIFIED.\n");
2067}
2068
2069out:
2070free(oldcontents);
2071free(newcontents);
2072return ret;
2073}

Archive Download this file

Revision: HEAD