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

Archive Download this file

Revision: HEAD