source: trunk/flashrom.c

Last change on this file was 1668, checked in by stefanct, 6 weeks ago

Get rid of perror().

It prints to stderr and that's not what we want necesserily;
using msg_*err gives us more control.

Signed-off-by: Stefan Tauner <stefan.tauner@…>
Acked-by: Carl-Daniel Hailfinger <c-d.hailfinger.devel.2006@…>

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