flashrom 

flashrom Svn Source Tree

Root/trunk/flashrom.c

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

Archive Download this file

Revision: HEAD