source: trunk/flashrom.c @ 1536

Revision 1536, 49.7 KB checked in by hailfinger, 6 days ago (diff)

Convert printf to msg_* where appropriate.
Clean up cli_output.c to be more readable.
Use enum instead of #define for message levels.
Kill a few exit(0) calls.
Print the command line arguments in verbose mode.
Move actions (--list-supported etc.) after argument sanity checks.
Reduce the number of code paths which have their own
programmer_shutdown().

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

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