Commit | Line | Data |
---|---|---|
b2441318 | 1 | /* SPDX-License-Identifier: GPL-2.0 */ |
bacfe09d DW |
2 | /* |
3 | * Compact binary representation of ihex records. Some devices need their | |
4 | * firmware loaded in strange orders rather than a single big blob, but | |
5 | * actually parsing ihex-as-text within the kernel seems silly. Thus,... | |
6 | */ | |
7 | ||
8 | #ifndef __LINUX_IHEX_H__ | |
9 | #define __LINUX_IHEX_H__ | |
10 | ||
11 | #include <linux/types.h> | |
12 | #include <linux/firmware.h> | |
f1485f3d | 13 | #include <linux/device.h> |
bacfe09d DW |
14 | |
15 | /* Intel HEX files actually limit the length to 256 bytes, but we have | |
16 | drivers which would benefit from using separate records which are | |
17 | longer than that, so we extend to 16 bits of length */ | |
18 | struct ihex_binrec { | |
19 | __be32 addr; | |
20 | __be16 len; | |
21 | uint8_t data[0]; | |
85ebd003 | 22 | } __attribute__((packed)); |
bacfe09d DW |
23 | |
24 | /* Find the next record, taking into account the 4-byte alignment */ | |
25 | static inline const struct ihex_binrec * | |
26 | ihex_next_binrec(const struct ihex_binrec *rec) | |
27 | { | |
28 | int next = ((be16_to_cpu(rec->len) + 5) & ~3) - 2; | |
29 | rec = (void *)&rec->data[next]; | |
30 | ||
31 | return be16_to_cpu(rec->len) ? rec : NULL; | |
32 | } | |
33 | ||
34 | /* Check that ihex_next_binrec() won't take us off the end of the image... */ | |
35 | static inline int ihex_validate_fw(const struct firmware *fw) | |
36 | { | |
37 | const struct ihex_binrec *rec; | |
38 | size_t ofs = 0; | |
39 | ||
40 | while (ofs <= fw->size - sizeof(*rec)) { | |
41 | rec = (void *)&fw->data[ofs]; | |
42 | ||
43 | /* Zero length marks end of records */ | |
44 | if (!be16_to_cpu(rec->len)) | |
45 | return 0; | |
46 | ||
47 | /* Point to next record... */ | |
48 | ofs += (sizeof(*rec) + be16_to_cpu(rec->len) + 3) & ~3; | |
49 | } | |
50 | return -EINVAL; | |
51 | } | |
f1485f3d DW |
52 | |
53 | /* Request firmware and validate it so that we can trust we won't | |
54 | * run off the end while reading records... */ | |
55 | static inline int request_ihex_firmware(const struct firmware **fw, | |
56 | const char *fw_name, | |
57 | struct device *dev) | |
58 | { | |
59 | const struct firmware *lfw; | |
60 | int ret; | |
61 | ||
62 | ret = request_firmware(&lfw, fw_name, dev); | |
63 | if (ret) | |
64 | return ret; | |
65 | ret = ihex_validate_fw(lfw); | |
66 | if (ret) { | |
67 | dev_err(dev, "Firmware \"%s\" not valid IHEX records\n", | |
68 | fw_name); | |
69 | release_firmware(lfw); | |
70 | return ret; | |
71 | } | |
72 | *fw = lfw; | |
73 | return 0; | |
74 | } | |
bacfe09d | 75 | #endif /* __LINUX_IHEX_H__ */ |