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

Archive Download this file

Revision: HEAD