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

Archive Download this file

Revision: HEAD