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