Add more infrastructure for flashrom ICH9 support.
[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         /* Probe for up to three flash chips. */
250         struct flashchip *flash, *flashes[3];
251         int opt;
252         int option_index = 0;
253         int read_it = 0, write_it = 0, erase_it = 0, verify_it = 0;
254         int ret = 0, i;
255
256         static struct option long_options[] = {
257                 {"read", 0, 0, 'r'},
258                 {"write", 0, 0, 'w'},
259                 {"erase", 0, 0, 'E'},
260                 {"verify", 0, 0, 'v'},
261                 {"chip", 1, 0, 'c'},
262                 {"estart", 1, 0, 's'},
263                 {"eend", 1, 0, 'e'},
264                 {"mainboard", 1, 0, 'm'},
265                 {"verbose", 0, 0, 'V'},
266                 {"force", 0, 0, 'f'},
267                 {"layout", 1, 0, 'l'},
268                 {"image", 1, 0, 'i'},
269                 {"list-supported", 0, 0, 'L'},
270                 {"help", 0, 0, 'h'},
271                 {"version", 0, 0, 'R'},
272                 {0, 0, 0, 0}
273         };
274
275         char *filename = NULL;
276
277         unsigned int exclude_start_position = 0, exclude_end_position = 0;      // [x,y)
278         char *tempstr = NULL, *tempstr2 = NULL;
279
280         if (argc > 1) {
281                 /* Yes, print them. */
282                 int i;
283                 printf_debug("The arguments are:\n");
284                 for (i = 1; i < argc; ++i)
285                         printf_debug("%s\n", argv[i]);
286         }
287
288         setbuf(stdout, NULL);
289         while ((opt = getopt_long(argc, argv, "rRwvVEfc:s:e:m:l:i:Lh",
290                                   long_options, &option_index)) != EOF) {
291                 switch (opt) {
292                 case 'r':
293                         read_it = 1;
294                         break;
295                 case 'w':
296                         write_it = 1;
297                         break;
298                 case 'v':
299                         verify_it = 1;
300                         break;
301                 case 'c':
302                         chip_to_probe = strdup(optarg);
303                         break;
304                 case 'V':
305                         verbose = 1;
306                         break;
307                 case 'E':
308                         erase_it = 1;
309                         break;
310                 case 's':
311                         tempstr = strdup(optarg);
312                         sscanf(tempstr, "%x", &exclude_start_position);
313                         break;
314                 case 'e':
315                         tempstr = strdup(optarg);
316                         sscanf(tempstr, "%x", &exclude_end_position);
317                         break;
318                 case 'm':
319                         tempstr = strdup(optarg);
320                         strtok(tempstr, ":");
321                         tempstr2 = strtok(NULL, ":");
322                         if (tempstr2) {
323                                 lb_vendor = tempstr;
324                                 lb_part = tempstr2;
325                         } else {
326                                 lb_vendor = NULL;
327                                 lb_part = tempstr;
328                         }
329                         break;
330                 case 'f':
331                         force = 1;
332                         break;
333                 case 'l':
334                         tempstr = strdup(optarg);
335                         if (read_romlayout(tempstr))
336                                 exit(1);
337                         break;
338                 case 'i':
339                         tempstr = strdup(optarg);
340                         find_romentry(tempstr);
341                         break;
342                 case 'L':
343                         print_supported_chips();
344                         print_supported_chipsets();
345                         print_supported_boards();
346                         exit(0);
347                         break;
348                 case 'R':
349                         print_version();
350                         exit(0);
351                         break;
352                 case 'h':
353                 default:
354                         usage(argv[0]);
355                         break;
356                 }
357         }
358
359         if (read_it && write_it) {
360                 printf("-r and -w are mutually exclusive\n");
361                 usage(argv[0]);
362         }
363
364         if (optind < argc)
365                 filename = argv[optind++];
366
367         /* First get full io access */
368 #if defined (__sun) && (defined(__i386) || defined(__amd64))
369         if (sysi86(SI86V86, V86SC_IOPL, PS_IOPL) != 0) {
370 #else
371         if (iopl(3) != 0) {
372 #endif
373                 fprintf(stderr, "ERROR: iopl failed: \"%s\"\n",
374                         strerror(errno));
375                 exit(1);
376         }
377
378         /* Initialize PCI access for flash enables */
379         pacc = pci_alloc();     /* Get the pci_access structure */
380         /* Set all options you want -- here we stick with the defaults */
381         pci_init(pacc);         /* Initialize the PCI library */
382         pci_scan_bus(pacc);     /* We want to get the list of devices */
383
384         /* Open the memory device UNCACHED. That's important for MMIO. */
385         if ((fd_mem = open(MEM_DEV, O_RDWR|O_SYNC)) < 0) {
386                 perror("Error: Can not access memory using " MEM_DEV
387                        ". You need to be root.");
388                 exit(1);
389         }
390
391         myusec_calibrate_delay();
392
393         /* We look at the lbtable first to see if we need a
394          * mainboard specific flash enable sequence.
395          */
396         coreboot_init();
397
398         /* try to enable it. Failure IS an option, since not all motherboards
399          * really need this to be done, etc., etc.
400          */
401         ret = chipset_flash_enable();
402         if (ret == -2) {
403                 printf("WARNING: No chipset found. Flash detection "
404                        "will most likely fail.\n");
405         }
406
407         board_flash_enable(lb_vendor, lb_part);
408
409         for (i = 0; i < ARRAY_SIZE(flashes); i++) {
410                 flashes[i] = probe_flash(i ? flashes[i - 1] + 1 : flashchips);
411                 if (!flashes[i])
412                         for (i++; i < ARRAY_SIZE(flashes); i++)
413                                 flashes[i] = NULL;
414         }
415
416         if (flashes[1]) {
417                 printf("Multiple flash chips were detected:");
418                 for (i = 0; i < ARRAY_SIZE(flashes) && flashes[i]; i++)
419                         printf(" %s", flashes[i]->name);
420                 printf("\nPlease specify which chip to use with the -c <chipname> option.\n");
421                 exit(1);
422         } else if (!flashes[0]) {
423                 printf("No EEPROM/flash device found.\n");
424                 // FIXME: flash writes stay enabled!
425                 exit(1);
426         }
427
428         flash = flashes[0];
429
430         printf("Flash part is %s (%d KB).\n", flash->name, flash->total_size);
431         if (TEST_OK_MASK != (flash->tested & TEST_OK_MASK)) {
432                 printf("===\n");
433                 if (flash->tested & TEST_BAD_MASK) {
434                         printf("This flash part has status NOT WORKING for operations:");
435                         if (flash->tested & TEST_BAD_PROBE)
436                                 printf(" PROBE");
437                         if (flash->tested & TEST_BAD_READ)
438                                 printf(" READ");
439                         if (flash->tested & TEST_BAD_ERASE)
440                                 printf(" ERASE");
441                         if (flash->tested & TEST_BAD_WRITE)
442                                 printf(" WRITE");
443                         printf("\n");
444                 } else {
445                         printf("This flash part has status UNTESTED for operations:");
446                         if (!(flash->tested & TEST_OK_PROBE))
447                                 printf(" PROBE");
448                         if (!(flash->tested & TEST_OK_READ))
449                                 printf(" READ");
450                         if (!(flash->tested & TEST_OK_ERASE))
451                                 printf(" ERASE");
452                         if (!(flash->tested & TEST_OK_WRITE))
453                                 printf(" WRITE");
454                         printf("\n");
455                 }
456                 printf("Please email a report to flashrom@coreboot.org if any of the above operations\n");
457                 printf("work correctly for you with this flash part. Please include the full output\n");
458                 printf("from the program, including chipset found. Thank you for your help!\n");
459                 printf("===\n");
460         }
461
462         if (!(read_it | write_it | verify_it | erase_it)) {
463                 printf("No operations were specified.\n");
464                 // FIXME: flash writes stay enabled!
465                 exit(1);
466         }
467
468         if (!filename && !erase_it) {
469                 printf("Error: No filename specified.\n");
470                 // FIXME: flash writes stay enabled!
471                 exit(1);
472         }
473
474         size = flash->total_size * 1024;
475         buf = (uint8_t *) calloc(size, sizeof(char));
476
477         if (erase_it) {
478                 printf("Erasing flash chip\n");
479                 if (!flash->erase) {
480                         fprintf(stderr, "Error: flashrom has no erase function for this flash chip.\n");
481                         return 1;
482                 }
483                 flash->erase(flash);
484                 exit(0);
485         } else if (read_it) {
486                 if ((image = fopen(filename, "w")) == NULL) {
487                         perror(filename);
488                         exit(1);
489                 }
490                 printf("Reading Flash...");
491                 if (flash->read == NULL)
492                         memcpy(buf, (const char *)flash->virtual_memory, size);
493                 else
494                         flash->read(flash, buf);
495
496                 if (exclude_end_position - exclude_start_position > 0)
497                         memset(buf + exclude_start_position, 0,
498                                exclude_end_position - exclude_start_position);
499
500                 fwrite(buf, sizeof(char), size, image);
501                 fclose(image);
502                 printf("done\n");
503         } else {
504                 struct stat image_stat;
505
506                 if ((image = fopen(filename, "r")) == NULL) {
507                         perror(filename);
508                         exit(1);
509                 }
510                 if (fstat(fileno(image), &image_stat) != 0) {
511                         perror(filename);
512                         exit(1);
513                 }
514                 if (image_stat.st_size != flash->total_size * 1024) {
515                         fprintf(stderr, "Error: Image size doesnt match\n");
516                         exit(1);
517                 }
518
519                 fread(buf, sizeof(char), size, image);
520                 show_id(buf, size);
521                 fclose(image);
522         }
523
524         /* exclude range stuff. Nice idea, but at the moment it is only
525          * supported in hardware by the pm49fl004 chips. 
526          * Instead of implementing this for all chips I suggest advancing
527          * it to the rom layout feature below and drop exclude range
528          * completely once all flash chips can do rom layouts. stepan
529          */
530
531         // ////////////////////////////////////////////////////////////
532         if (exclude_end_position - exclude_start_position > 0)
533                 memcpy(buf + exclude_start_position,
534                        (const char *)flash->virtual_memory +
535                        exclude_start_position,
536                        exclude_end_position - exclude_start_position);
537
538         exclude_start_page = exclude_start_position / flash->page_size;
539         if ((exclude_start_position % flash->page_size) != 0) {
540                 exclude_start_page++;
541         }
542         exclude_end_page = exclude_end_position / flash->page_size;
543         // ////////////////////////////////////////////////////////////
544
545         // This should be moved into each flash part's code to do it 
546         // cleanly. This does the job.
547         handle_romentries(buf, (uint8_t *) flash->virtual_memory);
548
549         // ////////////////////////////////////////////////////////////
550
551         if (write_it) {
552                 if (!flash->write) {
553                         fprintf(stderr, "Error: flashrom has no write function for this flash chip.\n");
554                         return 1;
555                 }
556                 ret |= flash->write(flash, buf);
557         }
558
559         if (verify_it)
560                 ret |= verify_flash(flash, buf);
561
562         return ret;
563 }