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

Archive Download this file

Revision: HEAD