Flashrom

Flashrom Svn Source Tree

Root/trunk/flashrom.c

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

Archive Download this file

Revision: HEAD