flashrom: Fix bug in r3790
[coreboot.git] / util / flashrom / flashrom.c
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  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21  */
22
23 #include <errno.h>
24 #include <fcntl.h>
25 #include <sys/mman.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <getopt.h>
33 #include <pci/pci.h>
34 /* for iopl */
35 #if defined (__sun) && (defined(__i386) || defined(__amd64))
36 #include <strings.h>
37 #include <sys/sysi86.h>
38 #include <sys/psw.h>
39 #include <asm/sunddi.h>
40 #endif
41 #include "flash.h"
42
43 char *chip_to_probe = NULL;
44 struct pci_access *pacc;        /* For board and chipset_enable */
45 int exclude_start_page, exclude_end_page;
46 int verbose = 0;
47 int fd_mem;
48
49 struct pci_dev *pci_dev_find(uint16_t vendor, uint16_t device)
50 {
51         struct pci_dev *temp;
52         struct pci_filter filter;
53
54         pci_filter_init(NULL, &filter);
55         filter.vendor = vendor;
56         filter.device = device;
57
58         for (temp = pacc->devices; temp; temp = temp->next)
59                 if (pci_filter_match(&filter, temp))
60                         return temp;
61
62         return NULL;
63 }
64
65 struct pci_dev *pci_card_find(uint16_t vendor, uint16_t device,
66                               uint16_t card_vendor, uint16_t card_device)
67 {
68         struct pci_dev *temp;
69         struct pci_filter filter;
70
71         pci_filter_init(NULL, &filter);
72         filter.vendor = vendor;
73         filter.device = device;
74
75         for (temp = pacc->devices; temp; temp = temp->next)
76                 if (pci_filter_match(&filter, temp)) {
77                         if ((card_vendor ==
78                              pci_read_word(temp, PCI_SUBSYSTEM_VENDOR_ID))
79                             && (card_device ==
80                                 pci_read_word(temp, PCI_SUBSYSTEM_ID)))
81                                 return temp;
82                 }
83
84         return NULL;
85 }
86
87 int map_flash_registers(struct flashchip *flash)
88 {
89         volatile uint8_t *registers;
90         size_t size = flash->total_size * 1024;
91
92         registers = mmap(0, size, PROT_WRITE | PROT_READ, MAP_SHARED,
93                          fd_mem, (off_t) (0xFFFFFFFF - 0x400000 - size + 1));
94
95         if (registers == MAP_FAILED) {
96                 perror("Can't mmap registers using " MEM_DEV);
97                 exit(1);
98         }
99         flash->virtual_registers = registers;
100
101         return 0;
102 }
103
104 struct flashchip *probe_flash(struct flashchip *first_flash, int force)
105 {
106         volatile uint8_t *bios;
107         struct flashchip *flash;
108         unsigned long base, size;
109
110         for (flash = first_flash; flash && flash->name; flash++) {
111                 if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0)
112                         continue;
113                 printf_debug("Probing for %s %s, %d KB: ",
114                              flash->vendor, flash->name, flash->total_size);
115                 if (!flash->probe && !force) {
116                         printf_debug("failed! flashrom has no probe function for this flash chip.\n");
117                         continue;
118                 }
119
120                 size = flash->total_size * 1024;
121
122                 /* If getpagesize() > size -> 
123                  * "Can't mmap memory using /dev/mem: Invalid argument"
124                  * This should never happen as we don't support any flash chips
125                  * smaller than 4k or 8k (yet).
126                  */
127
128                 if (getpagesize() > size) {
129                         /*
130                          * if a flash size of 0 is mapped, we map a single page
131                          * so we can probe in that area whether we know the
132                          * vendor at least.
133                          */
134                         size = getpagesize();
135                 }
136
137                 base = flashbase ? flashbase : (0xffffffff - size + 1);
138                 bios = mmap(0, size, PROT_WRITE | PROT_READ, MAP_SHARED,
139                             fd_mem, (off_t) base);
140                 if (bios == MAP_FAILED) {
141                         perror("Can't mmap memory using " MEM_DEV);
142                         exit(1);
143                 }
144                 flash->virtual_memory = bios;
145
146                 if (force)
147                         break;
148
149                 if (flash->probe(flash) != 1)
150                         goto notfound;
151
152                 if (first_flash == flashchips
153                     || flash->model_id != GENERIC_DEVICE_ID)
154                         break;
155
156 notfound:
157                 munmap((void *)bios, size);
158         }
159
160         if (!flash || !flash->name)
161                 return NULL;
162
163         printf("Found chip \"%s %s\" (%d KB) at physical address 0x%lx.\n",
164                flash->vendor, flash->name, flash->total_size, base);
165         flashbase = base;
166         return flash;
167 }
168
169 int verify_flash(struct flashchip *flash, uint8_t *buf)
170 {
171         int idx;
172         int total_size = flash->total_size * 1024;
173         uint8_t *buf2 = (uint8_t *) calloc(total_size, sizeof(char));
174         if (flash->read == NULL)
175                 memcpy(buf2, (const char *)flash->virtual_memory, total_size);
176         else
177                 flash->read(flash, buf2);
178
179         printf("Verifying flash... ");
180
181         if (verbose)
182                 printf("address: 0x00000000\b\b\b\b\b\b\b\b\b\b");
183
184         for (idx = 0; idx < total_size; idx++) {
185                 if (verbose && ((idx & 0xfff) == 0xfff))
186                         printf("0x%08x", idx);
187
188                 if (*(buf2 + idx) != *(buf + idx)) {
189                         if (verbose) {
190                                 printf("0x%08x ", idx);
191                         }
192                         printf("FAILED!  Expected=0x%02x, Read=0x%02x\n",
193                                *(buf + idx), *(buf2 + idx));
194                         return 1;
195                 }
196
197                 if (verbose && ((idx & 0xfff) == 0xfff))
198                         printf("\b\b\b\b\b\b\b\b\b\b");
199         }
200         if (verbose)
201                 printf("\b\b\b\b\b\b\b\b\b\b ");
202
203         printf("VERIFIED.          \n");
204
205         return 0;
206 }
207
208 void print_supported_chips(void)
209 {
210         int i;
211
212         printf("Supported ROM chips:\n\n");
213
214         for (i = 0; flashchips[i].name != NULL; i++)
215                 printf("%s %s\n", flashchips[i].vendor, flashchips[i].name);
216 }
217
218 void usage(const char *name)
219 {
220         printf("usage: %s [-rwvEVfLhR] [-c chipname] [-s exclude_start]\n",
221                name);
222         printf("       [-e exclude_end] [-m [vendor:]part] [-l file.layout] [-i imagename] [file]\n");
223         printf
224             ("   -r | --read:                      read flash and save into file\n"
225              "   -w | --write:                     write file into flash\n"
226              "   -v | --verify:                    verify flash against file\n"
227              "   -E | --erase:                     erase flash device\n"
228              "   -V | --verbose:                   more verbose output\n"
229              "   -c | --chip <chipname>:           probe only for specified flash chip\n"
230              "   -s | --estart <addr>:             exclude start position\n"
231              "   -e | --eend <addr>:               exclude end postion\n"
232              "   -m | --mainboard <[vendor:]part>: override mainboard settings\n"
233              "   -f | --force:                     force write without checking image\n"
234              "   -l | --layout <file.layout>:      read rom layout from file\n"
235              "   -i | --image <name>:              only flash image name from flash layout\n"
236              "   -L | --list-supported:            print supported devices\n"
237              "   -h | --help:                      print this help text\n"
238              "   -R | --version:                   print the version (release)\n"
239              "\n" " If no file is specified, then all that happens"
240              " is that flash info is dumped.\n\n");
241         exit(1);
242 }
243
244 void print_version(void)
245 {
246         printf("flashrom r%s\n", FLASHROM_VERSION);
247 }
248
249 int main(int argc, char *argv[])
250 {
251         uint8_t *buf;
252         unsigned long size;
253         FILE *image;
254         /* Probe for up to three flash chips. */
255         struct flashchip *flash, *flashes[3];
256         int opt;
257         int option_index = 0;
258         int force = 0;
259         int read_it = 0, write_it = 0, erase_it = 0, verify_it = 0;
260         int ret = 0, i;
261 #ifdef __FreeBSD__
262         int io_fd;
263 #endif
264
265         static struct option long_options[] = {
266                 {"read", 0, 0, 'r'},
267                 {"write", 0, 0, 'w'},
268                 {"erase", 0, 0, 'E'},
269                 {"verify", 0, 0, 'v'},
270                 {"chip", 1, 0, 'c'},
271                 {"estart", 1, 0, 's'},
272                 {"eend", 1, 0, 'e'},
273                 {"mainboard", 1, 0, 'm'},
274                 {"verbose", 0, 0, 'V'},
275                 {"force", 0, 0, 'f'},
276                 {"layout", 1, 0, 'l'},
277                 {"image", 1, 0, 'i'},
278                 {"list-supported", 0, 0, 'L'},
279                 {"help", 0, 0, 'h'},
280                 {"version", 0, 0, 'R'},
281                 {0, 0, 0, 0}
282         };
283
284         char *filename = NULL;
285
286         unsigned int exclude_start_position = 0, exclude_end_position = 0;      // [x,y)
287         char *tempstr = NULL, *tempstr2 = NULL;
288
289         if (argc > 1) {
290                 /* Yes, print them. */
291                 int i;
292                 printf_debug("The arguments are:\n");
293                 for (i = 1; i < argc; ++i)
294                         printf_debug("%s\n", argv[i]);
295         }
296
297         setbuf(stdout, NULL);
298         while ((opt = getopt_long(argc, argv, "rRwvVEfc:s:e:m:l:i:Lh",
299                                   long_options, &option_index)) != EOF) {
300                 switch (opt) {
301                 case 'r':
302                         read_it = 1;
303                         break;
304                 case 'w':
305                         write_it = 1;
306                         break;
307                 case 'v':
308                         verify_it = 1;
309                         break;
310                 case 'c':
311                         chip_to_probe = strdup(optarg);
312                         break;
313                 case 'V':
314                         verbose = 1;
315                         break;
316                 case 'E':
317                         erase_it = 1;
318                         break;
319                 case 's':
320                         tempstr = strdup(optarg);
321                         sscanf(tempstr, "%x", &exclude_start_position);
322                         break;
323                 case 'e':
324                         tempstr = strdup(optarg);
325                         sscanf(tempstr, "%x", &exclude_end_position);
326                         break;
327                 case 'm':
328                         tempstr = strdup(optarg);
329                         strtok(tempstr, ":");
330                         tempstr2 = strtok(NULL, ":");
331                         if (tempstr2) {
332                                 lb_vendor = tempstr;
333                                 lb_part = tempstr2;
334                         } else {
335                                 lb_vendor = NULL;
336                                 lb_part = tempstr;
337                         }
338                         break;
339                 case 'f':
340                         force = 1;
341                         break;
342                 case 'l':
343                         tempstr = strdup(optarg);
344                         if (read_romlayout(tempstr))
345                                 exit(1);
346                         break;
347                 case 'i':
348                         tempstr = strdup(optarg);
349                         find_romentry(tempstr);
350                         break;
351                 case 'L':
352                         print_supported_chips();
353                         print_supported_chipsets();
354                         print_supported_boards();
355                         exit(0);
356                         break;
357                 case 'R':
358                         print_version();
359                         exit(0);
360                         break;
361                 case 'h':
362                 default:
363                         usage(argv[0]);
364                         break;
365                 }
366         }
367
368         if (read_it && write_it) {
369                 printf("Error: -r and -w are mutually exclusive.\n");
370                 usage(argv[0]);
371         }
372
373         if (optind < argc)
374                 filename = argv[optind++];
375
376         /* First get full io access */
377 #if defined (__sun) && (defined(__i386) || defined(__amd64))
378         if (sysi86(SI86V86, V86SC_IOPL, PS_IOPL) != 0) {
379 #elif defined(__FreeBSD__)
380         if ((io_fd = open("/dev/io", O_RDWR)) < 0) {
381 #else
382         if (iopl(3) != 0) {
383 #endif
384                 fprintf(stderr, "ERROR: Could not get IO privileges (%s).\nYou need to be root.\n", strerror(errno));
385                 exit(1);
386         }
387
388         /* Initialize PCI access for flash enables */
389         pacc = pci_alloc();     /* Get the pci_access structure */
390         /* Set all options you want -- here we stick with the defaults */
391         pci_init(pacc);         /* Initialize the PCI library */
392         pci_scan_bus(pacc);     /* We want to get the list of devices */
393
394         /* Open the memory device UNCACHED. That's important for MMIO. */
395         if ((fd_mem = open(MEM_DEV, O_RDWR | O_SYNC)) < 0) {
396                 perror("Error: Can not access memory using " MEM_DEV
397                        ". You need to be root.");
398                 exit(1);
399         }
400
401         myusec_calibrate_delay();
402
403         /* We look at the lbtable first to see if we need a
404          * mainboard specific flash enable sequence.
405          */
406         coreboot_init();
407
408         /* try to enable it. Failure IS an option, since not all motherboards
409          * really need this to be done, etc., etc.
410          */
411         ret = chipset_flash_enable();
412         if (ret == -2) {
413                 printf("WARNING: No chipset found. Flash detection "
414                        "will most likely fail.\n");
415         }
416
417         board_flash_enable(lb_vendor, lb_part);
418
419         for (i = 0; i < ARRAY_SIZE(flashes); i++) {
420                 flashes[i] =
421                     probe_flash(i ? flashes[i - 1] + 1 : flashchips, 0);
422                 if (!flashes[i])
423                         for (i++; i < ARRAY_SIZE(flashes); i++)
424                                 flashes[i] = NULL;
425         }
426
427         if (flashes[1]) {
428                 printf("Multiple flash chips were detected:");
429                 for (i = 0; i < ARRAY_SIZE(flashes) && flashes[i]; i++)
430                         printf(" %s", flashes[i]->name);
431                 printf("\nPlease specify which chip to use with the -c <chipname> option.\n");
432                 exit(1);
433         } else if (!flashes[0]) {
434                 printf("No EEPROM/flash device found.\n");
435                 if (!force || !chip_to_probe) {
436                         printf("If you know which flash chip you have, and if this version of flashrom\n");
437                         printf("supports a similar flash chip, you can try to force read your chip. Run:\n");
438                         printf("flashrom -f -r -c similar_supported_flash_chip filename\n");
439                         printf("\n");
440                         printf("Note: flashrom can never write when the flash chip isn't found automatically.\n");
441                 }
442                 if (force && read_it && chip_to_probe) {
443                         printf("Force read (-f -r -c) requested, forcing chip probe success:\n");
444                         flashes[0] = probe_flash(flashchips, 1);
445                         if (!flashes[0]) {
446                                 printf("flashrom does not support a flash chip named '%s'.\n", chip_to_probe);
447                                 printf("Run flashrom -L to view the hardware supported in this flashrom version.\n");
448                                 exit(1);
449                         }
450                         if (!filename) {
451                                 printf("Error: No filename specified.\n");
452                                 exit(1);
453                         }
454                         size = flashes[0]->total_size * 1024;
455                         buf = (uint8_t *) calloc(size, sizeof(char));
456
457                         if ((image = fopen(filename, "w")) == NULL) {
458                                 perror(filename);
459                                 exit(1);
460                         }
461                         printf("Force reading flash... ");
462                         if (!flashes[0]->read)
463                                 memcpy(buf, (const char *)flashes[0]->virtual_memory, size);
464                         else
465                                 flashes[0]->read(flashes[0], buf);
466
467                         if (exclude_end_position - exclude_start_position > 0)
468                                 memset(buf + exclude_start_position, 0,
469                                        exclude_end_position -
470                                        exclude_start_position);
471
472                         fwrite(buf, sizeof(char), size, image);
473                         fclose(image);
474                         printf("done.\n");
475                         free(buf);
476                         exit(0);
477                 }
478                 // FIXME: flash writes stay enabled!
479                 exit(1);
480         }
481
482         flash = flashes[0];
483
484         if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
485                 printf("===\n");
486                 if (flash->tested & TEST_BAD_MASK) {
487                         printf("This flash part has status NOT WORKING for operations:");
488                         if (flash->tested & TEST_BAD_PROBE)
489                                 printf(" PROBE");
490                         if (flash->tested & TEST_BAD_READ)
491                                 printf(" READ");
492                         if (flash->tested & TEST_BAD_ERASE)
493                                 printf(" ERASE");
494                         if (flash->tested & TEST_BAD_WRITE)
495                                 printf(" WRITE");
496                         printf("\n");
497                 }
498                 if ((!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE)) ||
499                     (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ)) ||
500                     (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE)) ||
501                     (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))) {
502                         printf("This flash part has status UNTESTED for operations:");
503                         if (!(flash->tested & TEST_BAD_PROBE) && !(flash->tested & TEST_OK_PROBE))
504                                 printf(" PROBE");
505                         if (!(flash->tested & TEST_BAD_READ) && !(flash->tested & TEST_OK_READ))
506                                 printf(" READ");
507                         if (!(flash->tested & TEST_BAD_ERASE) && !(flash->tested & TEST_OK_ERASE))
508                                 printf(" ERASE");
509                         if (!(flash->tested & TEST_BAD_WRITE) && !(flash->tested & TEST_OK_WRITE))
510                                 printf(" WRITE");
511                         printf("\n");
512                 }
513                 printf("Please email a report to flashrom@coreboot.org if any of the above operations\n");
514                 printf("work correctly for you with this flash part. Please include the full output\n");
515                 printf("from the program, including chipset found. Thank you for your help!\n");
516                 printf("===\n");
517         }
518
519         if (!(read_it | write_it | verify_it | erase_it)) {
520                 printf("No operations were specified.\n");
521                 // FIXME: flash writes stay enabled!
522                 exit(1);
523         }
524
525         if (!filename && !erase_it) {
526                 printf("Error: No filename specified.\n");
527                 // FIXME: flash writes stay enabled!
528                 exit(1);
529         }
530
531         size = flash->total_size * 1024;
532         buf = (uint8_t *) calloc(size, sizeof(char));
533
534         if (erase_it) {
535                 printf("Erasing flash chip... ");
536                 if (!flash->erase) {
537                         fprintf(stderr, "Error: flashrom has no erase function for this flash chip.\n");
538                         return 1;
539                 }
540                 flash->erase(flash);
541                 printf("done.\n");
542                 exit(0);
543         } else if (read_it) {
544                 if ((image = fopen(filename, "w")) == NULL) {
545                         perror(filename);
546                         exit(1);
547                 }
548                 printf("Reading flash... ");
549                 if (flash->read == NULL)
550                         memcpy(buf, (const char *)flash->virtual_memory, size);
551                 else
552                         flash->read(flash, buf);
553
554                 if (exclude_end_position - exclude_start_position > 0)
555                         memset(buf + exclude_start_position, 0,
556                                exclude_end_position - exclude_start_position);
557
558                 fwrite(buf, sizeof(char), size, image);
559                 fclose(image);
560                 printf("done.\n");
561         } else {
562                 struct stat image_stat;
563
564                 if ((image = fopen(filename, "r")) == NULL) {
565                         perror(filename);
566                         exit(1);
567                 }
568                 if (fstat(fileno(image), &image_stat) != 0) {
569                         perror(filename);
570                         exit(1);
571                 }
572                 if (image_stat.st_size != flash->total_size * 1024) {
573                         fprintf(stderr, "Error: Image size doesn't match\n");
574                         exit(1);
575                 }
576
577                 fread(buf, sizeof(char), size, image);
578                 show_id(buf, size, force);
579                 fclose(image);
580         }
581
582         /* exclude range stuff. Nice idea, but at the moment it is only
583          * supported in hardware by the pm49fl004 chips. 
584          * Instead of implementing this for all chips I suggest advancing
585          * it to the rom layout feature below and drop exclude range
586          * completely once all flash chips can do rom layouts. stepan
587          */
588
589         // ////////////////////////////////////////////////////////////
590         if (exclude_end_position - exclude_start_position > 0)
591                 memcpy(buf + exclude_start_position,
592                        (const char *)flash->virtual_memory +
593                        exclude_start_position,
594                        exclude_end_position - exclude_start_position);
595
596         exclude_start_page = exclude_start_position / flash->page_size;
597         if ((exclude_start_position % flash->page_size) != 0) {
598                 exclude_start_page++;
599         }
600         exclude_end_page = exclude_end_position / flash->page_size;
601         // ////////////////////////////////////////////////////////////
602
603         // This should be moved into each flash part's code to do it 
604         // cleanly. This does the job.
605         handle_romentries(buf, (uint8_t *) flash->virtual_memory);
606
607         // ////////////////////////////////////////////////////////////
608
609         if (write_it) {
610                 if (!flash->write) {
611                         fprintf(stderr, "Error: flashrom has no write function for this flash chip.\n");
612                         return 1;
613                 }
614                 ret |= flash->write(flash, buf);
615         }
616
617         if (verify_it)
618                 ret |= verify_flash(flash, buf);
619
620 #ifdef __FreeBSD__
621         close(io_fd);
622 #endif
623         return ret;
624 }