Flashrom

Flashrom Svn Source Tree

Root/trunk/flashrom.c

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

Archive Download this file

Revision: HEAD