nvram.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Atheros AR71xx minimal nvram support
  3. *
  4. * Copyright (C) 2009 Gabor Juhos <juhosg@openwrt.org>
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License version 2 as published
  8. * by the Free Software Foundation.
  9. */
  10. #include <linux/kernel.h>
  11. #include <linux/vmalloc.h>
  12. #include <linux/errno.h>
  13. #include <linux/init.h>
  14. #include <linux/string.h>
  15. #include <linux/etherdevice.h>
  16. #include "nvram.h"
  17. char *ath79_nvram_find_var(const char *name, const char *buf, unsigned buf_len)
  18. {
  19. unsigned len = strlen(name);
  20. char *cur, *last;
  21. if (buf_len == 0 || len == 0)
  22. return NULL;
  23. if (buf_len < len)
  24. return NULL;
  25. if (len == 1)
  26. return memchr(buf, (int) *name, buf_len);
  27. last = (char *) buf + buf_len - len;
  28. for (cur = (char *) buf; cur <= last; cur++)
  29. if (cur[0] == name[0] && memcmp(cur, name, len) == 0)
  30. return cur + len;
  31. return NULL;
  32. }
  33. int ath79_nvram_parse_mac_addr(const char *nvram, unsigned nvram_len,
  34. const char *name, char *mac)
  35. {
  36. char *buf;
  37. char *mac_str;
  38. int ret;
  39. int t;
  40. buf = vmalloc(nvram_len);
  41. if (!buf)
  42. return -ENOMEM;
  43. memcpy(buf, nvram, nvram_len);
  44. buf[nvram_len - 1] = '\0';
  45. mac_str = ath79_nvram_find_var(name, buf, nvram_len);
  46. if (!mac_str) {
  47. ret = -EINVAL;
  48. goto free;
  49. }
  50. if (strlen(mac_str) == 19 && mac_str[0] == '"' && mac_str[18] == '"') {
  51. mac_str[18] = 0;
  52. mac_str++;
  53. }
  54. t = sscanf(mac_str, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
  55. &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
  56. if (t != ETH_ALEN)
  57. t = sscanf(mac_str, "%02hhx-%02hhx-%02hhx-%02hhx-%02hhx-%02hhx",
  58. &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
  59. if (t != ETH_ALEN) {
  60. ret = -EINVAL;
  61. goto free;
  62. }
  63. ret = 0;
  64. free:
  65. vfree(buf);
  66. return ret;
  67. }