1# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright (C) 2018 Synopsys, Inc. All rights reserved.
4# Author: Eugeniy Paltsev <Eugeniy.Paltsev@synopsys.com>
5
6import os, getopt, sys, zlib
7from elftools.elf.elffile import ELFFile
8
9
10def usage(exit_code):
11    print("usage:")
12    print(sys.argv[0] + " --arc-id 0x52 --image u-boot.bin --elf u-boot")
13    sys.exit(exit_code)
14
15
16def elf_get_entry(filename):
17    with open(filename, 'rb') as f:
18        elffile = ELFFile(f)
19        return elffile.header['e_entry']
20
21
22def calc_check_sum(filename):
23    # u-boot.head check_sum for preloader - it is sum of all u-boot binary bytes
24    with open(filename, "rb") as file:
25        ba = bytearray(file.read())
26    return sum(ba) & 0xFF
27
28
29def arg_verify(uboot_bin_filename, uboot_elf_filename, arc_id):
30    if arc_id not in [0x52, 0x53, 0x54]:
31        print("unknown ARC ID: " + hex(arc_id))
32        sys.exit(2)
33
34    if not os.path.isfile(uboot_bin_filename):
35        print("uboot bin file not exists: " + uboot_bin_filename)
36        sys.exit(2)
37
38    if not os.path.isfile(uboot_elf_filename):
39        print("uboot elf file not exists: " + uboot_elf_filename)
40        sys.exit(2)
41
42
43def main():
44    try:
45        opts, args = getopt.getopt(sys.argv[1:],
46            "ha:i:l:e:", ["help", "arc-id=", "image=", "elf="])
47    except getopt.GetoptError as err:
48        print(err)
49        usage(2)
50
51    # default filenames
52    uboot_elf_filename  = "u-boot"
53    uboot_bin_filename  = "u-boot.bin"
54    headerised_filename = "u-boot.head"
55    uboot_scrypt_file   = "u-boot-update.txt"
56
57    # initial header values: place where preloader will store u-boot binary,
58    # should be equal to CONFIG_TEXT_BASE
59    image_copy_adr  = 0x81000000
60
61    # initial constant header values, do not change these values
62    arc_id          = 0x52         # 0x52 for 1st HSDK release (hardcoded in RTL)
63    magic1          = 0xdeadbeafaf # big endian byte order
64    flash_address   = 0x0
65    flash_type      = 0x0          # 0 - SPI flash, 1 - NOR flash
66    magic2          = [            # big endian byte order
67    0x20202a2020202020202020202a20202020207c5c2e20202020202e2f7c20202020207c2d,
68    0x2e5c2020202f2e2d7c20202020205c2020602d2d2d6020202f20202020202f205f202020,
69    0x205f20205c20202020207c205f60712070205f207c2020202020272e5f3d2f205c3d5f2e,
70    0x272020202020202020605c202f60202020202020202020202020206f2020202020202020]
71
72    for opt, arg in opts:
73        if opt in ('-h', "--help"):   usage(0)
74        if opt in ('-a', "--arc-id"): arc_id             = int(arg, 16)
75        if opt in ('-i', "--image"):  uboot_bin_filename = arg
76        if opt in ('-e', "--elf"):    uboot_elf_filename = arg
77
78    arg_verify(uboot_bin_filename, uboot_elf_filename, arc_id)
79
80    uboot_img_size = os.path.getsize(uboot_bin_filename)
81    jump_address = elf_get_entry(uboot_elf_filename)
82    check_sum = calc_check_sum(uboot_bin_filename)
83
84    # write header to file
85    with open(headerised_filename, "wb") as file:
86        file.write(arc_id.to_bytes(2, byteorder='little'))
87        file.write(uboot_img_size.to_bytes(4, byteorder='little'))
88        file.write(check_sum.to_bytes(1, byteorder='little'))
89        file.write(image_copy_adr.to_bytes(4, byteorder='little'))
90        file.write(magic1.to_bytes(5, byteorder='big'))
91        file.write(jump_address.to_bytes(4, byteorder='little'))
92        for i in range(12): file.write(0xFF.to_bytes(1, byteorder='little'))
93        for byte in magic2: file.write(byte.to_bytes(36, byteorder='big'))
94        for i in range(208 - len(magic2) * 36):
95            file.write(0xFF.to_bytes(1, byteorder='little'))
96        file.write(flash_address.to_bytes(4, byteorder='little'))
97        for i in range(11): file.write(0xFF.to_bytes(1, byteorder='little'))
98        file.write(flash_type.to_bytes(1, byteorder='little'))
99
100    # append u-boot image to header
101    with open(headerised_filename, "ab") as fo:
102        with open(uboot_bin_filename,'rb') as fi:
103            fo.write(fi.read())
104
105    # calc u-boot headerized image CRC32 (will be used by uboot update
106    # command for check)
107    headerised_image_crc = ""
108    with open(headerised_filename, "rb") as fi:
109        headerised_image_crc = hex(zlib.crc32(fi.read()) & 0xffffffff)
110
111    load_addr = 0x81000000
112    crc_store_adr = load_addr - 0x8
113    crc_calc_adr = crc_store_adr - 0x4
114    load_size = os.path.getsize(headerised_filename)
115    crc_calc_cmd = \
116        "crc32 " + hex(load_addr) + " " + hex(load_size) + " " + hex(crc_calc_adr)
117    crc_check_cmd = \
118        "mw.l " + hex(crc_store_adr) + " " + headerised_image_crc + " && " + \
119        crc_calc_cmd + " && " + \
120        "cmp.l " + hex(crc_store_adr) + " " + hex(crc_calc_adr) + " 1"
121
122    # make errase size to be allighned by 64K
123    if load_size & 0xFFFF == 0:
124        errase_size = load_size
125    else:
126        errase_size = load_size - (load_size & 0xFFFF) + 0x10000
127
128    # u-bood CMD to load u-bood with header to SPI flash
129    sf_load_image_cmd = \
130        "fatload mmc 0:1 " + hex(load_addr) + " " + headerised_filename + " && " + \
131        "sf probe 0:0 && " + \
132        crc_check_cmd + " && " + \
133        "sf protect unlock 0x0 " + hex(errase_size) + " && " + \
134        "sf erase 0x0 " + hex(errase_size) + " && " + \
135        "sf write " + hex(load_addr) + " 0x0 " + hex(load_size) + " && " + \
136        "sf protect lock 0x0 " + hex(errase_size)
137
138    update_uboot_cmd = sf_load_image_cmd + " && echo \"u-boot update: OK\""
139
140    with open(uboot_scrypt_file, "wb") as fo:
141        fo.write(update_uboot_cmd.encode('ascii'))
142
143
144if __name__ == "__main__":
145    try:
146        main()
147    except Exception as err:
148        print(err)
149        sys.exit(2)
150