Christian Gmeiner | 415eab0 | 2020-11-03 15:34:51 +0100 | [diff] [blame] | 1 | // SPDX-License-Identifier: GPL-2.0+ |
| 2 | /* |
| 3 | * Copyright (C) 2020, Bachmann electronic GmbH |
| 4 | */ |
| 5 | |
| 6 | #include <common.h> |
| 7 | #include <smbios.h> |
| 8 | |
| 9 | static inline int verify_checksum(const struct smbios_entry *e) |
| 10 | { |
| 11 | /* |
| 12 | * Checksums for SMBIOS tables are calculated to have a value, so that |
| 13 | * the sum over all bytes yields zero (using unsigned 8 bit arithmetic). |
| 14 | */ |
| 15 | u8 *byte = (u8 *)e; |
| 16 | u8 sum = 0; |
| 17 | |
| 18 | for (int i = 0; i < e->length; i++) |
| 19 | sum += byte[i]; |
| 20 | |
| 21 | return sum; |
| 22 | } |
| 23 | |
| 24 | const struct smbios_entry *smbios_entry(u64 address, u32 size) |
| 25 | { |
| 26 | const struct smbios_entry *entry = (struct smbios_entry *)(uintptr_t)address; |
| 27 | |
| 28 | if (!address | !size) |
| 29 | return NULL; |
| 30 | |
| 31 | if (memcmp(entry->anchor, "_SM_", 4)) |
| 32 | return NULL; |
| 33 | |
| 34 | if (verify_checksum(entry)) |
| 35 | return NULL; |
| 36 | |
| 37 | return entry; |
| 38 | } |
| 39 | |
| 40 | static const struct smbios_header *next_header(const struct smbios_header *curr) |
| 41 | { |
| 42 | u8 *pos = ((u8 *)curr) + curr->length; |
| 43 | |
| 44 | /* search for _double_ NULL bytes */ |
| 45 | while (!((*pos == 0) && (*(pos + 1) == 0))) |
| 46 | pos++; |
| 47 | |
| 48 | /* step behind the double NULL bytes */ |
| 49 | pos += 2; |
| 50 | |
| 51 | return (struct smbios_header *)pos; |
| 52 | } |
| 53 | |
| 54 | const struct smbios_header *smbios_header(const struct smbios_entry *entry, int type) |
| 55 | { |
| 56 | const unsigned int num_header = entry->struct_count; |
| 57 | const struct smbios_header *header = (struct smbios_header *)entry->struct_table_address; |
| 58 | |
| 59 | for (unsigned int i = 0; i < num_header; i++) { |
| 60 | if (header->type == type) |
| 61 | return header; |
| 62 | |
| 63 | header = next_header(header); |
| 64 | } |
| 65 | |
| 66 | return NULL; |
| 67 | } |
| 68 | |
| 69 | static const char *string_from_smbios_table(const struct smbios_header *header, |
| 70 | int idx) |
| 71 | { |
| 72 | unsigned int i = 1; |
| 73 | u8 *pos; |
| 74 | |
| 75 | if (!header) |
| 76 | return NULL; |
| 77 | |
| 78 | pos = ((u8 *)header) + header->length; |
| 79 | |
| 80 | while (i < idx) { |
| 81 | if (*pos == 0x0) |
| 82 | i++; |
| 83 | |
| 84 | pos++; |
| 85 | } |
| 86 | |
| 87 | return (const char *)pos; |
| 88 | } |
| 89 | |
| 90 | const char *smbios_string(const struct smbios_header *header, int index) |
| 91 | { |
| 92 | if (!header) |
| 93 | return NULL; |
| 94 | |
| 95 | return string_from_smbios_table(header, index); |
| 96 | } |