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

Archive Download this file

Revision: HEAD