xref: /openbmc/u-boot/tools/ifdtool.c (revision 8f240a3b)
1 /*
2  * ifdtool - Manage Intel Firmware Descriptor information
3  *
4  * Copyright 2014 Google, Inc
5  *
6  * SPDX-License-Identifier:	GPL-2.0
7  *
8  * From Coreboot project, but it got a serious code clean-up
9  * and a few new features
10  */
11 
12 #include <assert.h>
13 #include <fcntl.h>
14 #include <getopt.h>
15 #include <stdbool.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <linux/libfdt.h>
23 #include "ifdtool.h"
24 
25 #undef DEBUG
26 
27 #ifdef DEBUG
28 #define debug(fmt, args...)	printf(fmt, ##args)
29 #else
30 #define debug(fmt, args...)
31 #endif
32 
33 #define FD_SIGNATURE		0x0FF0A55A
34 #define FLREG_BASE(reg)		((reg & 0x00000fff) << 12);
35 #define FLREG_LIMIT(reg)	(((reg & 0x0fff0000) >> 4) | 0xfff);
36 
37 struct input_file {
38 	char *fname;
39 	unsigned int addr;
40 };
41 
42 /**
43  * find_fd() - Find the flash description in the ROM image
44  *
45  * @image:	Pointer to image
46  * @size:	Size of image in bytes
47  * @return pointer to structure, or NULL if not found
48  */
49 static struct fdbar_t *find_fd(char *image, int size)
50 {
51 	uint32_t *ptr, *end;
52 
53 	/* Scan for FD signature */
54 	for (ptr = (uint32_t *)image, end = ptr + size / 4; ptr < end; ptr++) {
55 		if (*ptr == FD_SIGNATURE)
56 			break;
57 	}
58 
59 	if (ptr == end) {
60 		printf("No Flash Descriptor found in this image\n");
61 		return NULL;
62 	}
63 
64 	debug("Found Flash Descriptor signature at 0x%08lx\n",
65 	      (char *)ptr - image);
66 
67 	return (struct fdbar_t *)ptr;
68 }
69 
70 /**
71  * get_region() - Get information about the selected region
72  *
73  * @frba:		Flash region list
74  * @region_type:	Type of region (0..MAX_REGIONS-1)
75  * @region:		Region information is written here
76  * @return 0 if OK, else -ve
77  */
78 static int get_region(struct frba_t *frba, int region_type,
79 		      struct region_t *region)
80 {
81 	if (region_type >= MAX_REGIONS) {
82 		fprintf(stderr, "Invalid region type.\n");
83 		return -1;
84 	}
85 
86 	region->base = FLREG_BASE(frba->flreg[region_type]);
87 	region->limit = FLREG_LIMIT(frba->flreg[region_type]);
88 	region->size = region->limit - region->base + 1;
89 
90 	return 0;
91 }
92 
93 static const char *region_name(int region_type)
94 {
95 	static const char *const regions[] = {
96 		"Flash Descriptor",
97 		"BIOS",
98 		"Intel ME",
99 		"GbE",
100 		"Platform Data"
101 	};
102 
103 	assert(region_type < MAX_REGIONS);
104 
105 	return regions[region_type];
106 }
107 
108 static const char *region_filename(int region_type)
109 {
110 	static const char *const region_filenames[] = {
111 		"flashregion_0_flashdescriptor.bin",
112 		"flashregion_1_bios.bin",
113 		"flashregion_2_intel_me.bin",
114 		"flashregion_3_gbe.bin",
115 		"flashregion_4_platform_data.bin"
116 	};
117 
118 	assert(region_type < MAX_REGIONS);
119 
120 	return region_filenames[region_type];
121 }
122 
123 static int dump_region(int num, struct frba_t *frba)
124 {
125 	struct region_t region;
126 	int ret;
127 
128 	ret = get_region(frba, num, &region);
129 	if (ret)
130 		return ret;
131 
132 	printf("  Flash Region %d (%s): %08x - %08x %s\n",
133 	       num, region_name(num), region.base, region.limit,
134 	       region.size < 1 ? "(unused)" : "");
135 
136 	return ret;
137 }
138 
139 static void dump_frba(struct frba_t *frba)
140 {
141 	int i;
142 
143 	printf("Found Region Section\n");
144 	for (i = 0; i < MAX_REGIONS; i++) {
145 		printf("FLREG%d:    0x%08x\n", i, frba->flreg[i]);
146 		dump_region(i, frba);
147 	}
148 }
149 
150 static void decode_spi_frequency(unsigned int freq)
151 {
152 	switch (freq) {
153 	case SPI_FREQUENCY_20MHZ:
154 		printf("20MHz");
155 		break;
156 	case SPI_FREQUENCY_33MHZ:
157 		printf("33MHz");
158 		break;
159 	case SPI_FREQUENCY_50MHZ:
160 		printf("50MHz");
161 		break;
162 	default:
163 		printf("unknown<%x>MHz", freq);
164 	}
165 }
166 
167 static void decode_component_density(unsigned int density)
168 {
169 	switch (density) {
170 	case COMPONENT_DENSITY_512KB:
171 		printf("512KiB");
172 		break;
173 	case COMPONENT_DENSITY_1MB:
174 		printf("1MiB");
175 		break;
176 	case COMPONENT_DENSITY_2MB:
177 		printf("2MiB");
178 		break;
179 	case COMPONENT_DENSITY_4MB:
180 		printf("4MiB");
181 		break;
182 	case COMPONENT_DENSITY_8MB:
183 		printf("8MiB");
184 		break;
185 	case COMPONENT_DENSITY_16MB:
186 		printf("16MiB");
187 		break;
188 	default:
189 		printf("unknown<%x>MiB", density);
190 	}
191 }
192 
193 static void dump_fcba(struct fcba_t *fcba)
194 {
195 	printf("\nFound Component Section\n");
196 	printf("FLCOMP     0x%08x\n", fcba->flcomp);
197 	printf("  Dual Output Fast Read Support:       %ssupported\n",
198 	       (fcba->flcomp & (1 << 30)) ? "" : "not ");
199 	printf("  Read ID/Read Status Clock Frequency: ");
200 	decode_spi_frequency((fcba->flcomp >> 27) & 7);
201 	printf("\n  Write/Erase Clock Frequency:         ");
202 	decode_spi_frequency((fcba->flcomp >> 24) & 7);
203 	printf("\n  Fast Read Clock Frequency:           ");
204 	decode_spi_frequency((fcba->flcomp >> 21) & 7);
205 	printf("\n  Fast Read Support:                   %ssupported",
206 	       (fcba->flcomp & (1 << 20)) ? "" : "not ");
207 	printf("\n  Read Clock Frequency:                ");
208 	decode_spi_frequency((fcba->flcomp >> 17) & 7);
209 	printf("\n  Component 2 Density:                 ");
210 	decode_component_density((fcba->flcomp >> 3) & 7);
211 	printf("\n  Component 1 Density:                 ");
212 	decode_component_density(fcba->flcomp & 7);
213 	printf("\n");
214 	printf("FLILL      0x%08x\n", fcba->flill);
215 	printf("  Invalid Instruction 3: 0x%02x\n",
216 	       (fcba->flill >> 24) & 0xff);
217 	printf("  Invalid Instruction 2: 0x%02x\n",
218 	       (fcba->flill >> 16) & 0xff);
219 	printf("  Invalid Instruction 1: 0x%02x\n",
220 	       (fcba->flill >> 8) & 0xff);
221 	printf("  Invalid Instruction 0: 0x%02x\n",
222 	       fcba->flill & 0xff);
223 	printf("FLPB       0x%08x\n", fcba->flpb);
224 	printf("  Flash Partition Boundary Address: 0x%06x\n\n",
225 	       (fcba->flpb & 0xfff) << 12);
226 }
227 
228 static void dump_fpsba(struct fpsba_t *fpsba)
229 {
230 	int i;
231 
232 	printf("Found PCH Strap Section\n");
233 	for (i = 0; i < MAX_STRAPS; i++)
234 		printf("PCHSTRP%-2d:  0x%08x\n", i, fpsba->pchstrp[i]);
235 }
236 
237 static const char *get_enabled(int flag)
238 {
239 	return flag ? "enabled" : "disabled";
240 }
241 
242 static void decode_flmstr(uint32_t flmstr)
243 {
244 	printf("  Platform Data Region Write Access: %s\n",
245 	       get_enabled(flmstr & (1 << 28)));
246 	printf("  GbE Region Write Access:           %s\n",
247 	       get_enabled(flmstr & (1 << 27)));
248 	printf("  Intel ME Region Write Access:      %s\n",
249 	       get_enabled(flmstr & (1 << 26)));
250 	printf("  Host CPU/BIOS Region Write Access: %s\n",
251 	       get_enabled(flmstr & (1 << 25)));
252 	printf("  Flash Descriptor Write Access:     %s\n",
253 	       get_enabled(flmstr & (1 << 24)));
254 
255 	printf("  Platform Data Region Read Access:  %s\n",
256 	       get_enabled(flmstr & (1 << 20)));
257 	printf("  GbE Region Read Access:            %s\n",
258 	       get_enabled(flmstr & (1 << 19)));
259 	printf("  Intel ME Region Read Access:       %s\n",
260 	       get_enabled(flmstr & (1 << 18)));
261 	printf("  Host CPU/BIOS Region Read Access:  %s\n",
262 	       get_enabled(flmstr & (1 << 17)));
263 	printf("  Flash Descriptor Read Access:      %s\n",
264 	       get_enabled(flmstr & (1 << 16)));
265 
266 	printf("  Requester ID:                      0x%04x\n\n",
267 	       flmstr & 0xffff);
268 }
269 
270 static void dump_fmba(struct fmba_t *fmba)
271 {
272 	printf("Found Master Section\n");
273 	printf("FLMSTR1:   0x%08x (Host CPU/BIOS)\n", fmba->flmstr1);
274 	decode_flmstr(fmba->flmstr1);
275 	printf("FLMSTR2:   0x%08x (Intel ME)\n", fmba->flmstr2);
276 	decode_flmstr(fmba->flmstr2);
277 	printf("FLMSTR3:   0x%08x (GbE)\n", fmba->flmstr3);
278 	decode_flmstr(fmba->flmstr3);
279 }
280 
281 static void dump_fmsba(struct fmsba_t *fmsba)
282 {
283 	int i;
284 
285 	printf("Found Processor Strap Section\n");
286 	for (i = 0; i < 4; i++)
287 		printf("????:      0x%08x\n", fmsba->data[0]);
288 }
289 
290 static void dump_jid(uint32_t jid)
291 {
292 	printf("    SPI Component Device ID 1:          0x%02x\n",
293 	       (jid >> 16) & 0xff);
294 	printf("    SPI Component Device ID 0:          0x%02x\n",
295 	       (jid >> 8) & 0xff);
296 	printf("    SPI Component Vendor ID:            0x%02x\n",
297 	       jid & 0xff);
298 }
299 
300 static void dump_vscc(uint32_t vscc)
301 {
302 	printf("    Lower Erase Opcode:                 0x%02x\n",
303 	       vscc >> 24);
304 	printf("    Lower Write Enable on Write Status: 0x%02x\n",
305 	       vscc & (1 << 20) ? 0x06 : 0x50);
306 	printf("    Lower Write Status Required:        %s\n",
307 	       vscc & (1 << 19) ? "Yes" : "No");
308 	printf("    Lower Write Granularity:            %d bytes\n",
309 	       vscc & (1 << 18) ? 64 : 1);
310 	printf("    Lower Block / Sector Erase Size:    ");
311 	switch ((vscc >> 16) & 0x3) {
312 	case 0:
313 		printf("256 Byte\n");
314 		break;
315 	case 1:
316 		printf("4KB\n");
317 		break;
318 	case 2:
319 		printf("8KB\n");
320 		break;
321 	case 3:
322 		printf("64KB\n");
323 		break;
324 	}
325 
326 	printf("    Upper Erase Opcode:                 0x%02x\n",
327 	       (vscc >> 8) & 0xff);
328 	printf("    Upper Write Enable on Write Status: 0x%02x\n",
329 	       vscc & (1 << 4) ? 0x06 : 0x50);
330 	printf("    Upper Write Status Required:        %s\n",
331 	       vscc & (1 << 3) ? "Yes" : "No");
332 	printf("    Upper Write Granularity:            %d bytes\n",
333 	       vscc & (1 << 2) ? 64 : 1);
334 	printf("    Upper Block / Sector Erase Size:    ");
335 	switch (vscc & 0x3) {
336 	case 0:
337 		printf("256 Byte\n");
338 		break;
339 	case 1:
340 		printf("4KB\n");
341 		break;
342 	case 2:
343 		printf("8KB\n");
344 		break;
345 	case 3:
346 		printf("64KB\n");
347 		break;
348 	}
349 }
350 
351 static void dump_vtba(struct vtba_t *vtba, int vtl)
352 {
353 	int i;
354 	int num = (vtl >> 1) < 8 ? (vtl >> 1) : 8;
355 
356 	printf("ME VSCC table:\n");
357 	for (i = 0; i < num; i++) {
358 		printf("  JID%d:  0x%08x\n", i, vtba->entry[i].jid);
359 		dump_jid(vtba->entry[i].jid);
360 		printf("  VSCC%d: 0x%08x\n", i, vtba->entry[i].vscc);
361 		dump_vscc(vtba->entry[i].vscc);
362 	}
363 	printf("\n");
364 }
365 
366 static void dump_oem(uint8_t *oem)
367 {
368 	int i, j;
369 	printf("OEM Section:\n");
370 	for (i = 0; i < 4; i++) {
371 		printf("%02x:", i << 4);
372 		for (j = 0; j < 16; j++)
373 			printf(" %02x", oem[(i<<4)+j]);
374 		printf("\n");
375 	}
376 	printf("\n");
377 }
378 
379 /**
380  * dump_fd() - Display a dump of the full flash description
381  *
382  * @image:	Pointer to image
383  * @size:	Size of image in bytes
384  * @return 0 if OK, -1 on error
385  */
386 static int dump_fd(char *image, int size)
387 {
388 	struct fdbar_t *fdb = find_fd(image, size);
389 
390 	if (!fdb)
391 		return -1;
392 
393 	printf("FLMAP0:    0x%08x\n", fdb->flmap0);
394 	printf("  NR:      %d\n", (fdb->flmap0 >> 24) & 7);
395 	printf("  FRBA:    0x%x\n", ((fdb->flmap0 >> 16) & 0xff) << 4);
396 	printf("  NC:      %d\n", ((fdb->flmap0 >> 8) & 3) + 1);
397 	printf("  FCBA:    0x%x\n", ((fdb->flmap0) & 0xff) << 4);
398 
399 	printf("FLMAP1:    0x%08x\n", fdb->flmap1);
400 	printf("  ISL:     0x%02x\n", (fdb->flmap1 >> 24) & 0xff);
401 	printf("  FPSBA:   0x%x\n", ((fdb->flmap1 >> 16) & 0xff) << 4);
402 	printf("  NM:      %d\n", (fdb->flmap1 >> 8) & 3);
403 	printf("  FMBA:    0x%x\n", ((fdb->flmap1) & 0xff) << 4);
404 
405 	printf("FLMAP2:    0x%08x\n", fdb->flmap2);
406 	printf("  PSL:     0x%04x\n", (fdb->flmap2 >> 8) & 0xffff);
407 	printf("  FMSBA:   0x%x\n", ((fdb->flmap2) & 0xff) << 4);
408 
409 	printf("FLUMAP1:   0x%08x\n", fdb->flumap1);
410 	printf("  Intel ME VSCC Table Length (VTL):        %d\n",
411 	       (fdb->flumap1 >> 8) & 0xff);
412 	printf("  Intel ME VSCC Table Base Address (VTBA): 0x%06x\n\n",
413 	       (fdb->flumap1 & 0xff) << 4);
414 	dump_vtba((struct vtba_t *)
415 			(image + ((fdb->flumap1 & 0xff) << 4)),
416 			(fdb->flumap1 >> 8) & 0xff);
417 	dump_oem((uint8_t *)image + 0xf00);
418 	dump_frba((struct frba_t *)(image + (((fdb->flmap0 >> 16) & 0xff)
419 			<< 4)));
420 	dump_fcba((struct fcba_t *)(image + (((fdb->flmap0) & 0xff) << 4)));
421 	dump_fpsba((struct fpsba_t *)
422 			(image + (((fdb->flmap1 >> 16) & 0xff) << 4)));
423 	dump_fmba((struct fmba_t *)(image + (((fdb->flmap1) & 0xff) << 4)));
424 	dump_fmsba((struct fmsba_t *)(image + (((fdb->flmap2) & 0xff) << 4)));
425 
426 	return 0;
427 }
428 
429 /**
430  * write_regions() - Write each region from an image to its own file
431  *
432  * The filename to use in each case is fixed - see region_filename()
433  *
434  * @image:	Pointer to image
435  * @size:	Size of image in bytes
436  * @return 0 if OK, -ve on error
437  */
438 static int write_regions(char *image, int size)
439 {
440 	struct fdbar_t *fdb;
441 	struct frba_t *frba;
442 	int ret = 0;
443 	int i;
444 
445 	fdb =  find_fd(image, size);
446 	if (!fdb)
447 		return -1;
448 
449 	frba = (struct frba_t *)(image + (((fdb->flmap0 >> 16) & 0xff) << 4));
450 
451 	for (i = 0; i < MAX_REGIONS; i++) {
452 		struct region_t region;
453 		int region_fd;
454 
455 		ret = get_region(frba, i, &region);
456 		if (ret)
457 			return ret;
458 		dump_region(i, frba);
459 		if (region.size <= 0)
460 			continue;
461 		region_fd = open(region_filename(i),
462 				 O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR |
463 				 S_IWUSR | S_IRGRP | S_IROTH);
464 		if (write(region_fd, image + region.base, region.size) !=
465 				region.size) {
466 			perror("Error while writing");
467 			ret = -1;
468 		}
469 		close(region_fd);
470 	}
471 
472 	return ret;
473 }
474 
475 static int perror_fname(const char *fmt, const char *fname)
476 {
477 	char msg[strlen(fmt) + strlen(fname) + 1];
478 
479 	sprintf(msg, fmt, fname);
480 	perror(msg);
481 
482 	return -1;
483 }
484 
485 /**
486  * write_image() - Write the image to a file
487  *
488  * @filename:	Filename to use for the image
489  * @image:	Pointer to image
490  * @size:	Size of image in bytes
491  * @return 0 if OK, -ve on error
492  */
493 static int write_image(char *filename, char *image, int size)
494 {
495 	int new_fd;
496 
497 	debug("Writing new image to %s\n", filename);
498 
499 	new_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR |
500 		      S_IWUSR | S_IRGRP | S_IROTH);
501 	if (new_fd < 0)
502 		return perror_fname("Could not open file '%s'", filename);
503 	if (write(new_fd, image, size) != size)
504 		return perror_fname("Could not write file '%s'", filename);
505 	close(new_fd);
506 
507 	return 0;
508 }
509 
510 /**
511  * set_spi_frequency() - Set the SPI frequency to use when booting
512  *
513  * Several frequencies are supported, some of which work with fast devices.
514  * For SPI emulators, the slowest (SPI_FREQUENCY_20MHZ) is often used. The
515  * Intel boot system uses this information somehow on boot.
516  *
517  * The image is updated with the supplied value
518  *
519  * @image:	Pointer to image
520  * @size:	Size of image in bytes
521  * @freq:	SPI frequency to use
522  */
523 static void set_spi_frequency(char *image, int size, enum spi_frequency freq)
524 {
525 	struct fdbar_t *fdb = find_fd(image, size);
526 	struct fcba_t *fcba;
527 
528 	fcba = (struct fcba_t *)(image + (((fdb->flmap0) & 0xff) << 4));
529 
530 	/* clear bits 21-29 */
531 	fcba->flcomp &= ~0x3fe00000;
532 	/* Read ID and Read Status Clock Frequency */
533 	fcba->flcomp |= freq << 27;
534 	/* Write and Erase Clock Frequency */
535 	fcba->flcomp |= freq << 24;
536 	/* Fast Read Clock Frequency */
537 	fcba->flcomp |= freq << 21;
538 }
539 
540 /**
541  * set_em100_mode() - Set a SPI frequency that will work with Dediprog EM100
542  *
543  * @image:	Pointer to image
544  * @size:	Size of image in bytes
545  */
546 static void set_em100_mode(char *image, int size)
547 {
548 	struct fdbar_t *fdb = find_fd(image, size);
549 	struct fcba_t *fcba;
550 
551 	fcba = (struct fcba_t *)(image + (((fdb->flmap0) & 0xff) << 4));
552 	fcba->flcomp &= ~(1 << 30);
553 	set_spi_frequency(image, size, SPI_FREQUENCY_20MHZ);
554 }
555 
556 /**
557  * lock_descriptor() - Lock the NE descriptor so it cannot be updated
558  *
559  * @image:	Pointer to image
560  * @size:	Size of image in bytes
561  */
562 static void lock_descriptor(char *image, int size)
563 {
564 	struct fdbar_t *fdb = find_fd(image, size);
565 	struct fmba_t *fmba;
566 
567 	/*
568 	 * TODO: Dynamically take Platform Data Region and GbE Region into
569 	 * account.
570 	 */
571 	fmba = (struct fmba_t *)(image + (((fdb->flmap1) & 0xff) << 4));
572 	fmba->flmstr1 = 0x0a0b0000;
573 	fmba->flmstr2 = 0x0c0d0000;
574 	fmba->flmstr3 = 0x08080118;
575 }
576 
577 /**
578  * unlock_descriptor() - Lock the NE descriptor so it can be updated
579  *
580  * @image:	Pointer to image
581  * @size:	Size of image in bytes
582  */
583 static void unlock_descriptor(char *image, int size)
584 {
585 	struct fdbar_t *fdb = find_fd(image, size);
586 	struct fmba_t *fmba;
587 
588 	fmba = (struct fmba_t *)(image + (((fdb->flmap1) & 0xff) << 4));
589 	fmba->flmstr1 = 0xffff0000;
590 	fmba->flmstr2 = 0xffff0000;
591 	fmba->flmstr3 = 0x08080118;
592 }
593 
594 /**
595  * open_for_read() - Open a file for reading
596  *
597  * @fname:	Filename to open
598  * @sizep:	Returns file size in bytes
599  * @return 0 if OK, -1 on error
600  */
601 int open_for_read(const char *fname, int *sizep)
602 {
603 	int fd = open(fname, O_RDONLY);
604 	struct stat buf;
605 
606 	if (fd == -1)
607 		return perror_fname("Could not open file '%s'", fname);
608 	if (fstat(fd, &buf) == -1)
609 		return perror_fname("Could not stat file '%s'", fname);
610 	*sizep = buf.st_size;
611 	debug("File %s is %d bytes\n", fname, *sizep);
612 
613 	return fd;
614 }
615 
616 /**
617  * inject_region() - Add a file to an image region
618  *
619  * This puts a file into a particular region of the flash. Several pre-defined
620  * regions are used.
621  *
622  * @image:		Pointer to image
623  * @size:		Size of image in bytes
624  * @region_type:	Region where the file should be added
625  * @region_fname:	Filename to add to the image
626  * @return 0 if OK, -ve on error
627  */
628 int inject_region(char *image, int size, int region_type, char *region_fname)
629 {
630 	struct fdbar_t *fdb = find_fd(image, size);
631 	struct region_t region;
632 	struct frba_t *frba;
633 	int region_size;
634 	int offset = 0;
635 	int region_fd;
636 	int ret;
637 
638 	if (!fdb)
639 		exit(EXIT_FAILURE);
640 	frba = (struct frba_t *)(image + (((fdb->flmap0 >> 16) & 0xff) << 4));
641 
642 	ret = get_region(frba, region_type, &region);
643 	if (ret)
644 		return -1;
645 	if (region.size <= 0xfff) {
646 		fprintf(stderr, "Region %s is disabled in target. Not injecting.\n",
647 			region_name(region_type));
648 		return -1;
649 	}
650 
651 	region_fd = open_for_read(region_fname, &region_size);
652 	if (region_fd < 0)
653 		return region_fd;
654 
655 	if ((region_size > region.size) ||
656 	    ((region_type != 1) && (region_size > region.size))) {
657 		fprintf(stderr, "Region %s is %d(0x%x) bytes. File is %d(0x%x)  bytes. Not injecting.\n",
658 			region_name(region_type), region.size,
659 			region.size, region_size, region_size);
660 		return -1;
661 	}
662 
663 	if ((region_type == 1) && (region_size < region.size)) {
664 		fprintf(stderr, "Region %s is %d(0x%x) bytes. File is %d(0x%x) bytes. Padding before injecting.\n",
665 			region_name(region_type), region.size,
666 			region.size, region_size, region_size);
667 		offset = region.size - region_size;
668 		memset(image + region.base, 0xff, offset);
669 	}
670 
671 	if (size < region.base + offset + region_size) {
672 		fprintf(stderr, "Output file is too small. (%d < %d)\n",
673 			size, region.base + offset + region_size);
674 		return -1;
675 	}
676 
677 	if (read(region_fd, image + region.base + offset, region_size)
678 							!= region_size) {
679 		perror("Could not read file");
680 		return -1;
681 	}
682 
683 	close(region_fd);
684 
685 	debug("Adding %s as the %s section\n", region_fname,
686 	      region_name(region_type));
687 
688 	return 0;
689 }
690 
691 /**
692  * write_data() - Write some raw data into a region
693  *
694  * This puts a file into a particular place in the flash, ignoring the
695  * regions. Be careful not to overwrite something important.
696  *
697  * @image:		Pointer to image
698  * @size:		Size of image in bytes
699  * @addr:		x86 ROM address to put file. The ROM ends at
700  *			0xffffffff so use an address relative to that. For an
701  *			8MB ROM the start address is 0xfff80000.
702  * @write_fname:	Filename to add to the image
703  * @offset_uboot_top:	Offset of the top of U-Boot
704  * @offset_uboot_start:	Offset of the start of U-Boot
705  * @return number of bytes written if OK, -ve on error
706  */
707 static int write_data(char *image, int size, unsigned int addr,
708 		      const char *write_fname, int offset_uboot_top,
709 		      int offset_uboot_start)
710 {
711 	int write_fd, write_size;
712 	int offset;
713 
714 	write_fd = open_for_read(write_fname, &write_size);
715 	if (write_fd < 0)
716 		return write_fd;
717 
718 	offset = (uint32_t)(addr + size);
719 	if (offset_uboot_top) {
720 		if (offset_uboot_start < offset &&
721 		    offset_uboot_top >= offset) {
722 			fprintf(stderr, "U-Boot image overlaps with region '%s'\n",
723 				write_fname);
724 			fprintf(stderr,
725 				"U-Boot finishes at offset %x, file starts at %x\n",
726 				offset_uboot_top, offset);
727 			return -EXDEV;
728 		}
729 		if (offset_uboot_start > offset &&
730 		    offset_uboot_start <= offset + write_size) {
731 			fprintf(stderr, "U-Boot image overlaps with region '%s'\n",
732 				write_fname);
733 			fprintf(stderr,
734 				"U-Boot starts at offset %x, file finishes at %x\n",
735 				offset_uboot_start, offset + write_size);
736 			return -EXDEV;
737 		}
738 	}
739 	debug("Writing %s to offset %#x\n", write_fname, offset);
740 
741 	if (offset < 0 || offset + write_size > size) {
742 		fprintf(stderr, "Output file is too small. (%d < %d)\n",
743 			size, offset + write_size);
744 		return -1;
745 	}
746 
747 	if (read(write_fd, image + offset, write_size) != write_size) {
748 		perror("Could not read file");
749 		return -1;
750 	}
751 
752 	close(write_fd);
753 
754 	return write_size;
755 }
756 
757 static void print_version(void)
758 {
759 	printf("ifdtool v%s -- ", IFDTOOL_VERSION);
760 	printf("Copyright (C) 2014 Google Inc.\n\n");
761 	printf("SPDX-License-Identifier:	GPL-2.0+\n");
762 }
763 
764 static void print_usage(const char *name)
765 {
766 	printf("usage: %s [-vhdix?] <filename> [<outfile>]\n", name);
767 	printf("\n"
768 	       "   -d | --dump:                      dump intel firmware descriptor\n"
769 	       "   -x | --extract:                   extract intel fd modules\n"
770 	       "   -i | --inject <region>:<module>   inject file <module> into region <region>\n"
771 	       "   -w | --write <addr>:<file>        write file to appear at memory address <addr>\n"
772 	       "                                     multiple files can be written simultaneously\n"
773 	       "   -s | --spifreq <20|33|50>         set the SPI frequency\n"
774 	       "   -e | --em100                      set SPI frequency to 20MHz and disable\n"
775 	       "                                     Dual Output Fast Read Support\n"
776 	       "   -l | --lock                       Lock firmware descriptor and ME region\n"
777 	       "   -u | --unlock                     Unlock firmware descriptor and ME region\n"
778 	       "   -r | --romsize                    Specify ROM size\n"
779 	       "   -D | --write-descriptor <file>    Write descriptor at base\n"
780 	       "   -c | --create                     Create a new empty image\n"
781 	       "   -v | --version:                   print the version\n"
782 	       "   -h | --help:                      print this help\n\n"
783 	       "<region> is one of Descriptor, BIOS, ME, GbE, Platform\n"
784 	       "\n");
785 }
786 
787 /**
788  * get_two_words() - Convert a string into two words separated by :
789  *
790  * The supplied string is split at ':', two substrings are allocated and
791  * returned.
792  *
793  * @str:	String to split
794  * @firstp:	Returns first string
795  * @secondp:	Returns second string
796  * @return 0 if OK, -ve if @str does not have a :
797  */
798 static int get_two_words(const char *str, char **firstp, char **secondp)
799 {
800 	const char *p;
801 
802 	p = strchr(str, ':');
803 	if (!p)
804 		return -1;
805 	*firstp = strdup(str);
806 	(*firstp)[p - str] = '\0';
807 	*secondp = strdup(p + 1);
808 
809 	return 0;
810 }
811 
812 int main(int argc, char *argv[])
813 {
814 	int opt, option_index = 0;
815 	int mode_dump = 0, mode_extract = 0, mode_inject = 0;
816 	int mode_spifreq = 0, mode_em100 = 0, mode_locked = 0;
817 	int mode_unlocked = 0, mode_write = 0, mode_write_descriptor = 0;
818 	int create = 0;
819 	char *region_type_string = NULL, *inject_fname = NULL;
820 	char *desc_fname = NULL, *addr_str = NULL;
821 	int region_type = -1, inputfreq = 0;
822 	enum spi_frequency spifreq = SPI_FREQUENCY_20MHZ;
823 	struct input_file input_file[WRITE_MAX], *ifile, *fdt = NULL;
824 	unsigned char wr_idx, wr_num = 0;
825 	int rom_size = -1;
826 	bool write_it;
827 	char *filename;
828 	char *outfile = NULL;
829 	struct stat buf;
830 	int size = 0;
831 	bool have_uboot = false;
832 	int bios_fd;
833 	char *image;
834 	int ret;
835 	static struct option long_options[] = {
836 		{"create", 0, NULL, 'c'},
837 		{"dump", 0, NULL, 'd'},
838 		{"descriptor", 1, NULL, 'D'},
839 		{"em100", 0, NULL, 'e'},
840 		{"extract", 0, NULL, 'x'},
841 		{"fdt", 1, NULL, 'f'},
842 		{"inject", 1, NULL, 'i'},
843 		{"lock", 0, NULL, 'l'},
844 		{"romsize", 1, NULL, 'r'},
845 		{"spifreq", 1, NULL, 's'},
846 		{"unlock", 0, NULL, 'u'},
847 		{"uboot", 1, NULL, 'U'},
848 		{"write", 1, NULL, 'w'},
849 		{"version", 0, NULL, 'v'},
850 		{"help", 0, NULL, 'h'},
851 		{0, 0, 0, 0}
852 	};
853 
854 	while ((opt = getopt_long(argc, argv, "cdD:ef:hi:lr:s:uU:vw:x?",
855 				  long_options, &option_index)) != EOF) {
856 		switch (opt) {
857 		case 'c':
858 			create = 1;
859 			break;
860 		case 'd':
861 			mode_dump = 1;
862 			break;
863 		case 'D':
864 			mode_write_descriptor = 1;
865 			desc_fname = optarg;
866 			break;
867 		case 'e':
868 			mode_em100 = 1;
869 			break;
870 		case 'i':
871 			if (get_two_words(optarg, &region_type_string,
872 					  &inject_fname)) {
873 				print_usage(argv[0]);
874 				exit(EXIT_FAILURE);
875 			}
876 			if (!strcasecmp("Descriptor", region_type_string))
877 				region_type = 0;
878 			else if (!strcasecmp("BIOS", region_type_string))
879 				region_type = 1;
880 			else if (!strcasecmp("ME", region_type_string))
881 				region_type = 2;
882 			else if (!strcasecmp("GbE", region_type_string))
883 				region_type = 3;
884 			else if (!strcasecmp("Platform", region_type_string))
885 				region_type = 4;
886 			if (region_type == -1) {
887 				fprintf(stderr, "No such region type: '%s'\n\n",
888 					region_type_string);
889 				print_usage(argv[0]);
890 				exit(EXIT_FAILURE);
891 			}
892 			mode_inject = 1;
893 			break;
894 		case 'l':
895 			mode_locked = 1;
896 			break;
897 		case 'r':
898 			rom_size = strtol(optarg, NULL, 0);
899 			debug("ROM size %d\n", rom_size);
900 			break;
901 		case 's':
902 			/* Parse the requested SPI frequency */
903 			inputfreq = strtol(optarg, NULL, 0);
904 			switch (inputfreq) {
905 			case 20:
906 				spifreq = SPI_FREQUENCY_20MHZ;
907 				break;
908 			case 33:
909 				spifreq = SPI_FREQUENCY_33MHZ;
910 				break;
911 			case 50:
912 				spifreq = SPI_FREQUENCY_50MHZ;
913 				break;
914 			default:
915 				fprintf(stderr, "Invalid SPI Frequency: %d\n",
916 					inputfreq);
917 				print_usage(argv[0]);
918 				exit(EXIT_FAILURE);
919 			}
920 			mode_spifreq = 1;
921 			break;
922 		case 'u':
923 			mode_unlocked = 1;
924 			break;
925 		case 'v':
926 			print_version();
927 			exit(EXIT_SUCCESS);
928 			break;
929 		case 'w':
930 		case 'U':
931 		case 'f':
932 			ifile = &input_file[wr_num];
933 			mode_write = 1;
934 			if (wr_num < WRITE_MAX) {
935 				if (get_two_words(optarg, &addr_str,
936 						  &ifile->fname)) {
937 					print_usage(argv[0]);
938 					exit(EXIT_FAILURE);
939 				}
940 				ifile->addr = strtoll(optarg, NULL, 0);
941 				wr_num++;
942 			} else {
943 				fprintf(stderr,
944 					"The number of files to write simultaneously exceeds the limitation (%d)\n",
945 					WRITE_MAX);
946 			}
947 			break;
948 		case 'x':
949 			mode_extract = 1;
950 			break;
951 		case 'h':
952 		case '?':
953 		default:
954 			print_usage(argv[0]);
955 			exit(EXIT_SUCCESS);
956 			break;
957 		}
958 	}
959 
960 	if (mode_locked == 1 && mode_unlocked == 1) {
961 		fprintf(stderr, "Locking/Unlocking FD and ME are mutually exclusive\n");
962 		exit(EXIT_FAILURE);
963 	}
964 
965 	if (mode_inject == 1 && mode_write == 1) {
966 		fprintf(stderr, "Inject/Write are mutually exclusive\n");
967 		exit(EXIT_FAILURE);
968 	}
969 
970 	if ((mode_dump + mode_extract + mode_inject +
971 		(mode_spifreq | mode_em100 | mode_unlocked |
972 		 mode_locked)) > 1) {
973 		fprintf(stderr, "You may not specify more than one mode.\n\n");
974 		print_usage(argv[0]);
975 		exit(EXIT_FAILURE);
976 	}
977 
978 	if ((mode_dump + mode_extract + mode_inject + mode_spifreq +
979 	     mode_em100 + mode_locked + mode_unlocked + mode_write +
980 	     mode_write_descriptor) == 0 && !create) {
981 		fprintf(stderr, "You need to specify a mode.\n\n");
982 		print_usage(argv[0]);
983 		exit(EXIT_FAILURE);
984 	}
985 
986 	if (create && rom_size == -1) {
987 		fprintf(stderr, "You need to specify a rom size when creating.\n\n");
988 		exit(EXIT_FAILURE);
989 	}
990 
991 	if (optind + 1 != argc) {
992 		fprintf(stderr, "You need to specify a file.\n\n");
993 		print_usage(argv[0]);
994 		exit(EXIT_FAILURE);
995 	}
996 
997 	if (have_uboot && !fdt) {
998 		fprintf(stderr,
999 			"You must supply a device tree file for U-Boot\n\n");
1000 		print_usage(argv[0]);
1001 		exit(EXIT_FAILURE);
1002 	}
1003 
1004 	filename = argv[optind];
1005 	if (optind + 2 != argc)
1006 		outfile = argv[optind + 1];
1007 
1008 	if (create)
1009 		bios_fd = open(filename, O_WRONLY | O_CREAT, 0666);
1010 	else
1011 		bios_fd = open(filename, outfile ? O_RDONLY : O_RDWR);
1012 
1013 	if (bios_fd == -1) {
1014 		perror("Could not open file");
1015 		exit(EXIT_FAILURE);
1016 	}
1017 
1018 	if (!create) {
1019 		if (fstat(bios_fd, &buf) == -1) {
1020 			perror("Could not stat file");
1021 			exit(EXIT_FAILURE);
1022 		}
1023 		size = buf.st_size;
1024 	}
1025 
1026 	debug("File %s is %d bytes\n", filename, size);
1027 
1028 	if (rom_size == -1)
1029 		rom_size = size;
1030 
1031 	image = malloc(rom_size);
1032 	if (!image) {
1033 		printf("Out of memory.\n");
1034 		exit(EXIT_FAILURE);
1035 	}
1036 
1037 	memset(image, '\xff', rom_size);
1038 	if (!create && read(bios_fd, image, size) != size) {
1039 		perror("Could not read file");
1040 		exit(EXIT_FAILURE);
1041 	}
1042 	if (size != rom_size) {
1043 		debug("ROM size changed to %d bytes\n", rom_size);
1044 		size = rom_size;
1045 	}
1046 
1047 	write_it = true;
1048 	ret = 0;
1049 	if (mode_dump) {
1050 		ret = dump_fd(image, size);
1051 		write_it = false;
1052 	}
1053 
1054 	if (mode_extract) {
1055 		ret = write_regions(image, size);
1056 		write_it = false;
1057 	}
1058 
1059 	if (mode_write_descriptor)
1060 		ret = write_data(image, size, -size, desc_fname, 0, 0);
1061 
1062 	if (mode_inject)
1063 		ret = inject_region(image, size, region_type, inject_fname);
1064 
1065 	if (mode_write) {
1066 		int offset_uboot_top = 0;
1067 		int offset_uboot_start = 0;
1068 
1069 		for (wr_idx = 0; wr_idx < wr_num; wr_idx++) {
1070 			ifile = &input_file[wr_idx];
1071 			ret = write_data(image, size, ifile->addr,
1072 					 ifile->fname, offset_uboot_top,
1073 					 offset_uboot_start);
1074 			if (ret < 0)
1075 				break;
1076 		}
1077 	}
1078 
1079 	if (mode_spifreq)
1080 		set_spi_frequency(image, size, spifreq);
1081 
1082 	if (mode_em100)
1083 		set_em100_mode(image, size);
1084 
1085 	if (mode_locked)
1086 		lock_descriptor(image, size);
1087 
1088 	if (mode_unlocked)
1089 		unlock_descriptor(image, size);
1090 
1091 	if (write_it) {
1092 		if (outfile) {
1093 			ret = write_image(outfile, image, size);
1094 		} else {
1095 			if (lseek(bios_fd, 0, SEEK_SET)) {
1096 				perror("Error while seeking");
1097 				ret = -1;
1098 			}
1099 			if (write(bios_fd, image, size) != size) {
1100 				perror("Error while writing");
1101 				ret = -1;
1102 			}
1103 		}
1104 	}
1105 
1106 	free(image);
1107 	close(bios_fd);
1108 
1109 	return ret < 0 ? 1 : 0;
1110 }
1111