ar71xx: merge mach-files for TP-Link TL-WR802N v1 and v2
[openwrt/openwrt.git] / target / linux / ar71xx / files / arch / mips / ath79 / nvram.c
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
11 #include <linux/kernel.h>
12 #include <linux/vmalloc.h>
13 #include <linux/errno.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/etherdevice.h>
17
18 #include "nvram.h"
19
20 char *ath79_nvram_find_var(const char *name, const char *buf, unsigned buf_len)
21 {
22 unsigned len = strlen(name);
23 char *cur, *last;
24
25 if (buf_len == 0 || len == 0)
26 return NULL;
27
28 if (buf_len < len)
29 return NULL;
30
31 if (len == 1)
32 return memchr(buf, (int) *name, buf_len);
33
34 last = (char *) buf + buf_len - len;
35 for (cur = (char *) buf; cur <= last; cur++)
36 if (cur[0] == name[0] && memcmp(cur, name, len) == 0)
37 return cur + len;
38
39 return NULL;
40 }
41
42 int ath79_nvram_parse_mac_addr(const char *nvram, unsigned nvram_len,
43 const char *name, char *mac)
44 {
45 char *buf;
46 char *mac_str;
47 int ret;
48 int t;
49
50 buf = vmalloc(nvram_len);
51 if (!buf)
52 return -ENOMEM;
53
54 memcpy(buf, nvram, nvram_len);
55 buf[nvram_len - 1] = '\0';
56
57 mac_str = ath79_nvram_find_var(name, buf, nvram_len);
58 if (!mac_str) {
59 ret = -EINVAL;
60 goto free;
61 }
62
63 if (strlen(mac_str) == 19 && mac_str[0] == '"' && mac_str[18] == '"') {
64 mac_str[18] = 0;
65 mac_str++;
66 }
67
68 t = sscanf(mac_str, "%02hhx:%02hhx:%02hhx:%02hhx:%02hhx:%02hhx",
69 &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
70
71 if (t != ETH_ALEN)
72 t = sscanf(mac_str, "%02hhx-%02hhx-%02hhx-%02hhx-%02hhx-%02hhx",
73 &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]);
74
75 if (t != ETH_ALEN) {
76 ret = -EINVAL;
77 goto free;
78 }
79
80 ret = 0;
81
82 free:
83 vfree(buf);
84 return ret;
85 }