smbios-parser.c 1.9 KB

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