2f3d7c9083c3d725f7fdce89e176b6d7dd7dd931
[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-2007 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 force = 0, 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 == pci_read_word(temp, 0x2C)) &&
78                             (card_device == pci_read_word(temp, 0x2E)))
79                                 return temp;
80                 }
81
82         return NULL;
83 }
84
85 int map_flash_registers(struct flashchip *flash)
86 {
87         volatile uint8_t *registers;
88         size_t size = flash->total_size * 1024;
89
90         registers = mmap(0, size, PROT_WRITE | PROT_READ, MAP_SHARED,
91                          fd_mem, (off_t) (0xFFFFFFFF - 0x400000 - size + 1));
92
93         if (registers == MAP_FAILED) {
94                 perror("Can't mmap registers using " MEM_DEV);
95                 exit(1);
96         }
97         flash->virtual_registers = registers;
98
99         return 0;
100 }
101
102 struct flashchip *probe_flash(struct flashchip *flash)
103 {
104         volatile uint8_t *bios;
105         unsigned long flash_baseaddr, size;
106
107         while (flash->name != NULL) {
108                 if (chip_to_probe && strcmp(flash->name, chip_to_probe) != 0) {
109                         flash++;
110                         continue;
111                 }
112                 printf_debug("Probing for %s %s, %d KB: ",
113                              flash->vendor, flash->name, flash->total_size);
114                 if (!flash->probe) {
115                         printf_debug("failed! flashrom has no probe function for this flash chip.\n");
116                         flash++;
117                         continue;
118                 }
119
120                 size = flash->total_size * 1024;
121
122 #ifdef TS5300
123                 // FIXME: Wrong place for this decision
124                 // FIXME: This should be autodetected. It is trivial.
125                 flash_baseaddr = 0x9400000;
126 #else
127                 flash_baseaddr = (0xffffffff - size + 1);
128 #endif
129
130                 /* If getpagesize() > size -> 
131                  * "Can't mmap memory using /dev/mem: Invalid argument"
132                  * This should never happen as we don't support any flash chips
133                  * smaller than 4k or 8k (yet).
134                  */
135
136                 if (getpagesize() > size) {
137                         /*
138                          * if a flash size of 0 is mapped, we map a single page
139                          * so we can probe in that area whether we know the
140                          * vendor at least.
141                          */
142                         size = getpagesize();
143                 }
144
145                 bios = mmap(0, size, PROT_WRITE | PROT_READ, MAP_SHARED,
146                             fd_mem, (off_t) flash_baseaddr);
147                 if (bios == MAP_FAILED) {
148                         perror("Can't mmap memory using " MEM_DEV);
149                         exit(1);
150                 }
151                 flash->virtual_memory = bios;
152
153                 if (flash->probe(flash) == 1) {
154                         printf("%s found at physical address 0x%lx.\n",
155                                flash->name, flash_baseaddr);
156                         return flash;
157                 }
158                 munmap((void *)bios, size);
159
160                 flash++;
161         }
162
163         return NULL;
164 }
165
166 int verify_flash(struct flashchip *flash, uint8_t *buf)
167 {
168         int idx;
169         int total_size = flash->total_size * 1024;
170         uint8_t *buf2 = (uint8_t *) calloc(total_size, sizeof(char));
171         if (flash->read == NULL)
172                 memcpy(buf2, (const char *)flash->virtual_memory, total_size);
173         else
174                 flash->read(flash, buf2);
175
176         printf("Verifying flash... ");
177
178         if (verbose)
179                 printf("address: 0x00000000\b\b\b\b\b\b\b\b\b\b");
180
181         for (idx = 0; idx < total_size; idx++) {
182                 if (verbose && ((idx & 0xfff) == 0xfff))
183                         printf("0x%08x", idx);
184
185                 if (*(buf2 + idx) != *(buf + idx)) {
186                         if (verbose) {
187                                 printf("0x%08x ", idx);
188                         }
189                         printf("FAILED!\n");
190                         return 1;
191                 }
192
193                 if (verbose && ((idx & 0xfff) == 0xfff))
194                         printf("\b\b\b\b\b\b\b\b\b\b");
195         }
196         if (verbose)
197                 printf("\b\b\b\b\b\b\b\b\b\b ");
198
199         printf("VERIFIED.          \n");
200
201         return 0;
202 }
203
204 void print_supported_chips(void)
205 {
206         int i;
207
208         printf("Supported ROM chips:\n\n");
209
210         for (i = 0; flashchips[i].name != NULL; i++)
211                 printf("%s %s\n", flashchips[i].vendor, flashchips[i].name);
212 }
213
214 void usage(const char *name)
215 {
216         printf("usage: %s [-rwvEVfLhR] [-c chipname] [-s exclude_start]\n", name);
217         printf("       [-e exclude_end] [-m [vendor:]part] [-l file.layout] [-i imagename] [file]\n");
218         printf
219             ("   -r | --read:                      read flash and save into file\n"
220              "   -w | --write:                     write file into flash\n"
221              "   -v | --verify:                    verify flash against file\n"
222              "   -E | --erase:                     erase flash device\n"
223              "   -V | --verbose:                   more verbose output\n"
224              "   -c | --chip <chipname>:           probe only for specified flash chip\n"
225              "   -s | --estart <addr>:             exclude start position\n"
226              "   -e | --eend <addr>:               exclude end postion\n"
227              "   -m | --mainboard <[vendor:]part>: override mainboard settings\n"
228              "   -f | --force:                     force write without checking image\n"
229              "   -l | --layout <file.layout>:      read rom layout from file\n"
230              "   -i | --image <name>:              only flash image name from flash layout\n"
231              "   -L | --list-supported:            print supported devices\n"
232              "   -h | --help:                      print this help text\n"
233              "   -R | --version:                   print the version (release)\n"
234              "\n" " If no file is specified, then all that happens"
235              " is that flash info is dumped.\n\n");
236         exit(1);
237 }
238
239 void print_version(void)
240 {
241         printf("flashrom r%s\n", FLASHROM_VERSION);
242 }
243
244 int main(int argc, char *argv[])
245 {
246         uint8_t *buf;
247         unsigned long size;
248         FILE *image;
249         struct flashchip *flash;
250         int opt;
251         int option_index = 0;
252         int read_it = 0, write_it = 0, erase_it = 0, verify_it = 0;
253         int ret = 0;
254
255         static struct option long_options[] = {
256                 {"read", 0, 0, 'r'},
257                 {"write", 0, 0, 'w'},
258                 {"erase", 0, 0, 'E'},
259                 {"verify", 0, 0, 'v'},
260                 {"chip", 1, 0, 'c'},
261                 {"estart", 1, 0, 's'},
262                 {"eend", 1, 0, 'e'},
263                 {"mainboard", 1, 0, 'm'},
264                 {"verbose", 0, 0, 'V'},
265                 {"force", 0, 0, 'f'},
266                 {"layout", 1, 0, 'l'},
267                 {"image", 1, 0, 'i'},
268                 {"list-supported", 0, 0, 'L'},
269                 {"help", 0, 0, 'h'},
270                 {"version", 0, 0, 'R'},
271                 {0, 0, 0, 0}
272         };
273
274         char *filename = NULL;
275
276         unsigned int exclude_start_position = 0, exclude_end_position = 0;      // [x,y)
277         char *tempstr = NULL, *tempstr2 = NULL;
278
279         if (argc > 1) {
280                 /* Yes, print them. */
281                 int i;
282                 printf_debug("The arguments are:\n");
283                 for (i = 1; i < argc; ++i)
284                         printf_debug("%s\n", argv[i]);
285         }
286
287         setbuf(stdout, NULL);
288         while ((opt = getopt_long(argc, argv, "rRwvVEfc:s:e:m:l:i:Lh",
289                                   long_options, &option_index)) != EOF) {
290                 switch (opt) {
291                 case 'r':
292                         read_it = 1;
293                         break;
294                 case 'w':
295                         write_it = 1;
296                         break;
297                 case 'v':
298                         verify_it = 1;
299                         break;
300                 case 'c':
301                         chip_to_probe = strdup(optarg);
302                         break;
303                 case 'V':
304                         verbose = 1;
305                         break;
306                 case 'E':
307                         erase_it = 1;
308                         break;
309                 case 's':
310                         tempstr = strdup(optarg);
311                         sscanf(tempstr, "%x", &exclude_start_position);
312                         break;
313                 case 'e':
314                         tempstr = strdup(optarg);
315                         sscanf(tempstr, "%x", &exclude_end_position);
316                         break;
317                 case 'm':
318                         tempstr = strdup(optarg);
319                         strtok(tempstr, ":");
320                         tempstr2 = strtok(NULL, ":");
321                         if (tempstr2) {
322                                 lb_vendor = tempstr;
323                                 lb_part = tempstr2;
324                         } else {
325                                 lb_vendor = NULL;
326                                 lb_part = tempstr;
327                         }
328                         break;
329                 case 'f':
330                         force = 1;
331                         break;
332                 case 'l':
333                         tempstr = strdup(optarg);
334                         if (read_romlayout(tempstr))
335                                 exit(1);
336                         break;
337                 case 'i':
338                         tempstr = strdup(optarg);
339                         find_romentry(tempstr);
340                         break;
341                 case 'L':
342                         print_supported_chips();
343                         print_supported_chipsets();
344                         print_supported_boards();
345                         exit(0);
346                         break;
347                 case 'R':
348                         print_version();
349                         exit(0);
350                         break;
351                 case 'h':
352                 default:
353                         usage(argv[0]);
354                         break;
355                 }
356         }
357
358         if (read_it && write_it) {
359                 printf("-r and -w are mutually exclusive\n");
360                 usage(argv[0]);
361         }
362
363         if (optind < argc)
364                 filename = argv[optind++];
365
366         /* First get full io access */
367 #if defined (__sun) && (defined(__i386) || defined(__amd64))
368         if (sysi86(SI86V86, V86SC_IOPL, PS_IOPL) != 0) {
369 #else
370         if (iopl(3) != 0) {
371 #endif
372                 fprintf(stderr, "ERROR: iopl failed: \"%s\"\n",
373                         strerror(errno));
374                 exit(1);
375         }
376
377         /* Initialize PCI access for flash enables */
378         pacc = pci_alloc();     /* Get the pci_access structure */
379         /* Set all options you want -- here we stick with the defaults */
380         pci_init(pacc);         /* Initialize the PCI library */
381         pci_scan_bus(pacc);     /* We want to get the list of devices */
382
383         /* Open the memory device. A lot of functions need it */
384         if ((fd_mem = open(MEM_DEV, O_RDWR)) < 0) {
385                 perror("Error: Can not access memory using " MEM_DEV
386                        ". You need to be root.");
387                 exit(1);
388         }
389
390         myusec_calibrate_delay();
391
392         /* We look at the lbtable first to see if we need a
393          * mainboard specific flash enable sequence.
394          */
395         coreboot_init();
396
397         /* try to enable it. Failure IS an option, since not all motherboards
398          * really need this to be done, etc., etc.
399          */
400         ret = chipset_flash_enable();
401         if (ret == -2) {
402                 printf("WARNING: No chipset found. Flash detection "
403                        "will most likely fail.\n");
404         }
405
406         board_flash_enable(lb_vendor, lb_part);
407
408         if ((flash = probe_flash(flashchips)) == NULL) {
409                 printf("No EEPROM/flash device found.\n");
410                 // FIXME: flash writes stay enabled!
411                 exit(1);
412         }
413
414         printf("Flash part is %s (%d KB).\n", flash->name, flash->total_size);
415         if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
416                 printf("===\n");
417                 if (flash->tested & TEST_BAD_MASK) {
418                         printf("This flash part has status NOT WORKING for operations:");
419                         if (flash->tested & TEST_BAD_PROBE)
420                                 printf(" PROBE");
421                         if (flash->tested & TEST_BAD_READ)
422                                 printf(" READ");
423                         if (flash->tested & TEST_BAD_ERASE)
424                                 printf(" ERASE");
425                         if (flash->tested & TEST_BAD_WRITE)
426                                 printf(" WRITE");
427                         printf("\n");
428                 } else {
429                         printf("This flash part has status UNTESTED for operations:");
430                         if (!(flash->tested & TEST_OK_PROBE))
431                                 printf(" PROBE");
432                         if (!(flash->tested & TEST_OK_READ))
433                                 printf(" READ");
434                         if (!(flash->tested & TEST_OK_ERASE))
435                                 printf(" ERASE");
436                         if (!(flash->tested & TEST_OK_WRITE))
437                                 printf(" WRITE");
438                         printf("\n");
439                 }
440                 printf("Please email a report to flashrom@coreboot.org if any of the above operations\n");
441                 printf("work correctly for you with this flash part. Please include the full output\n");
442                 printf("from the program, including chipset found. Thank you for your help!\n");
443                 printf("===\n");
444         }
445
446         if (!(read_it | write_it | verify_it | erase_it)) {
447                 printf("No operations were specified.\n");
448                 // FIXME: flash writes stay enabled!
449                 exit(1);
450         }
451
452         if (!filename && !erase_it) {
453                 printf("Error: No filename specified.\n");
454                 // FIXME: flash writes stay enabled!
455                 exit(1);
456         }
457
458         size = flash->total_size * 1024;
459         buf = (uint8_t *) calloc(size, sizeof(char));
460
461         if (erase_it) {
462                 printf("Erasing flash chip\n");
463                 if (!flash->erase) {
464                         fprintf(stderr, "Error: flashrom has no erase function for this flash chip.\n");
465                         return 1;
466                 }
467                 flash->erase(flash);
468                 exit(0);
469         } else if (read_it) {
470                 if ((image = fopen(filename, "w")) == NULL) {
471                         perror(filename);
472                         exit(1);
473                 }
474                 printf("Reading Flash...");
475                 if (flash->read == NULL)
476                         memcpy(buf, (const char *)flash->virtual_memory, size);
477                 else
478                         flash->read(flash, buf);
479
480                 if (exclude_end_position - exclude_start_position > 0)
481                         memset(buf + exclude_start_position, 0,
482                                exclude_end_position - exclude_start_position);
483
484                 fwrite(buf, sizeof(char), size, image);
485                 fclose(image);
486                 printf("done\n");
487         } else {
488                 struct stat image_stat;
489
490                 if ((image = fopen(filename, "r")) == NULL) {
491                         perror(filename);
492                         exit(1);
493                 }
494                 if (fstat(fileno(image), &image_stat) != 0) {
495                         perror(filename);
496                         exit(1);
497                 }
498                 if (image_stat.st_size != flash->total_size * 1024) {
499                         fprintf(stderr, "Error: Image size doesnt match\n");
500                         exit(1);
501                 }
502
503                 fread(buf, sizeof(char), size, image);
504                 show_id(buf, size);
505                 fclose(image);
506         }
507
508         /* exclude range stuff. Nice idea, but at the moment it is only
509          * supported in hardware by the pm49fl004 chips. 
510          * Instead of implementing this for all chips I suggest advancing
511          * it to the rom layout feature below and drop exclude range
512          * completely once all flash chips can do rom layouts. stepan
513          */
514
515         // ////////////////////////////////////////////////////////////
516         if (exclude_end_position - exclude_start_position > 0)
517                 memcpy(buf + exclude_start_position,
518                        (const char *)flash->virtual_memory +
519                        exclude_start_position,
520                        exclude_end_position - exclude_start_position);
521
522         exclude_start_page = exclude_start_position / flash->page_size;
523         if ((exclude_start_position % flash->page_size) != 0) {
524                 exclude_start_page++;
525         }
526         exclude_end_page = exclude_end_position / flash->page_size;
527         // ////////////////////////////////////////////////////////////
528
529         // This should be moved into each flash part's code to do it 
530         // cleanly. This does the job.
531         handle_romentries(buf, (uint8_t *) flash->virtual_memory);
532
533         // ////////////////////////////////////////////////////////////
534
535         if (write_it) {
536                 if (!flash->write) {
537                         fprintf(stderr, "Error: flashrom has no write function for this flash chip.\n");
538                         return 1;
539                 }
540                 ret |= flash->write(flash, buf);
541         }
542
543         if (verify_it)
544                 ret |= verify_flash(flash, buf);
545
546         return ret;
547 }