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

Archive Download this file

Revision: HEAD