1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (C) 2011 Samsung Electronics
4  */
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <errno.h>
11 #include <string.h>
12 #include <sys/stat.h>
13 
14 #define BUFSIZE			(16*1024)
15 #define IMG_SIZE		(16*1024)
16 #define SPL_HEADER_SIZE		16
17 #define FILE_PERM		(S_IRUSR | S_IWUSR | S_IRGRP \
18 				| S_IWGRP | S_IROTH | S_IWOTH)
19 #define SPL_HEADER		"S5PC210 HEADER  "
20 /*
21 * Requirement:
22 * IROM code reads first 14K bytes from boot device.
23 * It then calculates the checksum of 14K-4 bytes and compare with data at
24 * 14K-4 offset.
25 *
26 * This function takes two filenames:
27 * IN  "u-boot-spl.bin" and
28 * OUT "$(BOARD)-spl.bin as filenames.
29 * It reads the "u-boot-spl.bin" in 16K buffer.
30 * It calculates checksum of 14K-4 Bytes and stores at 14K-4 offset in buffer.
31 * It writes the buffer to "$(BOARD)-spl.bin" file.
32 */
33 
main(int argc,char ** argv)34 int main(int argc, char **argv)
35 {
36 	int i, len;
37 	unsigned char buffer[BUFSIZE] = {0};
38 	int ifd, ofd;
39 	unsigned int checksum = 0, count;
40 
41 	if (argc != 3) {
42 		printf(" %d Wrong number of arguments\n", argc);
43 		exit(EXIT_FAILURE);
44 	}
45 
46 	ifd = open(argv[1], O_RDONLY);
47 	if (ifd < 0) {
48 		fprintf(stderr, "%s: Can't open %s: %s\n",
49 			argv[0], argv[1], strerror(errno));
50 		exit(EXIT_FAILURE);
51 	}
52 
53 	ofd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, FILE_PERM);
54 	if (ofd < 0) {
55 		fprintf(stderr, "%s: Can't open %s: %s\n",
56 			argv[0], argv[2], strerror(errno));
57 		if (ifd)
58 			close(ifd);
59 		exit(EXIT_FAILURE);
60 	}
61 
62 	len = lseek(ifd, 0, SEEK_END);
63 	lseek(ifd, 0, SEEK_SET);
64 
65 	memcpy(&buffer[0], SPL_HEADER, SPL_HEADER_SIZE);
66 
67 	count = (len < (IMG_SIZE - SPL_HEADER_SIZE))
68 		? len : (IMG_SIZE - SPL_HEADER_SIZE);
69 
70 	if (read(ifd, buffer + SPL_HEADER_SIZE, count) != count) {
71 		fprintf(stderr, "%s: Can't read %s: %s\n",
72 			argv[0], argv[1], strerror(errno));
73 
74 		if (ifd)
75 			close(ifd);
76 		if (ofd)
77 			close(ofd);
78 
79 		exit(EXIT_FAILURE);
80 	}
81 
82 	for (i = 0; i < IMG_SIZE - SPL_HEADER_SIZE; i++)
83 		checksum += buffer[i+16];
84 
85 	*(unsigned long *)buffer ^= 0x1f;
86 	*(unsigned long *)(buffer+4) ^= checksum;
87 
88 	for (i = 1; i < SPL_HEADER_SIZE; i++)
89 		buffer[i] ^= buffer[i-1];
90 
91 	if (write(ofd, buffer, BUFSIZE) != BUFSIZE) {
92 		fprintf(stderr, "%s: Can't write %s: %s\n",
93 			argv[0], argv[2], strerror(errno));
94 
95 		if (ifd)
96 			close(ifd);
97 		if (ofd)
98 			close(ofd);
99 
100 		exit(EXIT_FAILURE);
101 	}
102 
103 	if (ifd)
104 		close(ifd);
105 	if (ofd)
106 		close(ofd);
107 
108 	return EXIT_SUCCESS;
109 }
110