1 /*
2  * Copyright (c) 2013 Broadcom Corporation
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
11  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
13  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include <linux/kernel.h>
18 #include <linux/slab.h>
19 #include <linux/device.h>
20 #include <linux/firmware.h>
21 #include <linux/module.h>
22 #include <linux/bcm47xx_nvram.h>
23 
24 #include "debug.h"
25 #include "firmware.h"
26 #include "core.h"
27 #include "common.h"
28 #include "chip.h"
29 
30 #define BRCMF_FW_MAX_NVRAM_SIZE			64000
31 #define BRCMF_FW_NVRAM_DEVPATH_LEN		19	/* devpath0=pcie/1/4/ */
32 #define BRCMF_FW_NVRAM_PCIEDEV_LEN		10	/* pcie/1/4/ + \0 */
33 #define BRCMF_FW_DEFAULT_BOARDREV		"boardrev=0xff"
34 
35 enum nvram_parser_state {
36 	IDLE,
37 	KEY,
38 	VALUE,
39 	COMMENT,
40 	END
41 };
42 
43 /**
44  * struct nvram_parser - internal info for parser.
45  *
46  * @state: current parser state.
47  * @data: input buffer being parsed.
48  * @nvram: output buffer with parse result.
49  * @nvram_len: lenght of parse result.
50  * @line: current line.
51  * @column: current column in line.
52  * @pos: byte offset in input buffer.
53  * @entry: start position of key,value entry.
54  * @multi_dev_v1: detect pcie multi device v1 (compressed).
55  * @multi_dev_v2: detect pcie multi device v2.
56  * @boardrev_found: nvram contains boardrev information.
57  */
58 struct nvram_parser {
59 	enum nvram_parser_state state;
60 	const u8 *data;
61 	u8 *nvram;
62 	u32 nvram_len;
63 	u32 line;
64 	u32 column;
65 	u32 pos;
66 	u32 entry;
67 	bool multi_dev_v1;
68 	bool multi_dev_v2;
69 	bool boardrev_found;
70 };
71 
72 /**
73  * is_nvram_char() - check if char is a valid one for NVRAM entry
74  *
75  * It accepts all printable ASCII chars except for '#' which opens a comment.
76  * Please note that ' ' (space) while accepted is not a valid key name char.
77  */
78 static bool is_nvram_char(char c)
79 {
80 	/* comment marker excluded */
81 	if (c == '#')
82 		return false;
83 
84 	/* key and value may have any other readable character */
85 	return (c >= 0x20 && c < 0x7f);
86 }
87 
88 static bool is_whitespace(char c)
89 {
90 	return (c == ' ' || c == '\r' || c == '\n' || c == '\t');
91 }
92 
93 static enum nvram_parser_state brcmf_nvram_handle_idle(struct nvram_parser *nvp)
94 {
95 	char c;
96 
97 	c = nvp->data[nvp->pos];
98 	if (c == '\n')
99 		return COMMENT;
100 	if (is_whitespace(c) || c == '\0')
101 		goto proceed;
102 	if (c == '#')
103 		return COMMENT;
104 	if (is_nvram_char(c)) {
105 		nvp->entry = nvp->pos;
106 		return KEY;
107 	}
108 	brcmf_dbg(INFO, "warning: ln=%d:col=%d: ignoring invalid character\n",
109 		  nvp->line, nvp->column);
110 proceed:
111 	nvp->column++;
112 	nvp->pos++;
113 	return IDLE;
114 }
115 
116 static enum nvram_parser_state brcmf_nvram_handle_key(struct nvram_parser *nvp)
117 {
118 	enum nvram_parser_state st = nvp->state;
119 	char c;
120 
121 	c = nvp->data[nvp->pos];
122 	if (c == '=') {
123 		/* ignore RAW1 by treating as comment */
124 		if (strncmp(&nvp->data[nvp->entry], "RAW1", 4) == 0)
125 			st = COMMENT;
126 		else
127 			st = VALUE;
128 		if (strncmp(&nvp->data[nvp->entry], "devpath", 7) == 0)
129 			nvp->multi_dev_v1 = true;
130 		if (strncmp(&nvp->data[nvp->entry], "pcie/", 5) == 0)
131 			nvp->multi_dev_v2 = true;
132 		if (strncmp(&nvp->data[nvp->entry], "boardrev", 8) == 0)
133 			nvp->boardrev_found = true;
134 	} else if (!is_nvram_char(c) || c == ' ') {
135 		brcmf_dbg(INFO, "warning: ln=%d:col=%d: '=' expected, skip invalid key entry\n",
136 			  nvp->line, nvp->column);
137 		return COMMENT;
138 	}
139 
140 	nvp->column++;
141 	nvp->pos++;
142 	return st;
143 }
144 
145 static enum nvram_parser_state
146 brcmf_nvram_handle_value(struct nvram_parser *nvp)
147 {
148 	char c;
149 	char *skv;
150 	char *ekv;
151 	u32 cplen;
152 
153 	c = nvp->data[nvp->pos];
154 	if (!is_nvram_char(c)) {
155 		/* key,value pair complete */
156 		ekv = (u8 *)&nvp->data[nvp->pos];
157 		skv = (u8 *)&nvp->data[nvp->entry];
158 		cplen = ekv - skv;
159 		if (nvp->nvram_len + cplen + 1 >= BRCMF_FW_MAX_NVRAM_SIZE)
160 			return END;
161 		/* copy to output buffer */
162 		memcpy(&nvp->nvram[nvp->nvram_len], skv, cplen);
163 		nvp->nvram_len += cplen;
164 		nvp->nvram[nvp->nvram_len] = '\0';
165 		nvp->nvram_len++;
166 		return IDLE;
167 	}
168 	nvp->pos++;
169 	nvp->column++;
170 	return VALUE;
171 }
172 
173 static enum nvram_parser_state
174 brcmf_nvram_handle_comment(struct nvram_parser *nvp)
175 {
176 	char *eoc, *sol;
177 
178 	sol = (char *)&nvp->data[nvp->pos];
179 	eoc = strchr(sol, '\n');
180 	if (!eoc) {
181 		eoc = strchr(sol, '\0');
182 		if (!eoc)
183 			return END;
184 	}
185 
186 	/* eat all moving to next line */
187 	nvp->line++;
188 	nvp->column = 1;
189 	nvp->pos += (eoc - sol) + 1;
190 	return IDLE;
191 }
192 
193 static enum nvram_parser_state brcmf_nvram_handle_end(struct nvram_parser *nvp)
194 {
195 	/* final state */
196 	return END;
197 }
198 
199 static enum nvram_parser_state
200 (*nv_parser_states[])(struct nvram_parser *nvp) = {
201 	brcmf_nvram_handle_idle,
202 	brcmf_nvram_handle_key,
203 	brcmf_nvram_handle_value,
204 	brcmf_nvram_handle_comment,
205 	brcmf_nvram_handle_end
206 };
207 
208 static int brcmf_init_nvram_parser(struct nvram_parser *nvp,
209 				   const u8 *data, size_t data_len)
210 {
211 	size_t size;
212 
213 	memset(nvp, 0, sizeof(*nvp));
214 	nvp->data = data;
215 	/* Limit size to MAX_NVRAM_SIZE, some files contain lot of comment */
216 	if (data_len > BRCMF_FW_MAX_NVRAM_SIZE)
217 		size = BRCMF_FW_MAX_NVRAM_SIZE;
218 	else
219 		size = data_len;
220 	/* Alloc for extra 0 byte + roundup by 4 + length field */
221 	size += 1 + 3 + sizeof(u32);
222 	nvp->nvram = kzalloc(size, GFP_KERNEL);
223 	if (!nvp->nvram)
224 		return -ENOMEM;
225 
226 	nvp->line = 1;
227 	nvp->column = 1;
228 	return 0;
229 }
230 
231 /* brcmf_fw_strip_multi_v1 :Some nvram files contain settings for multiple
232  * devices. Strip it down for one device, use domain_nr/bus_nr to determine
233  * which data is to be returned. v1 is the version where nvram is stored
234  * compressed and "devpath" maps to index for valid entries.
235  */
236 static void brcmf_fw_strip_multi_v1(struct nvram_parser *nvp, u16 domain_nr,
237 				    u16 bus_nr)
238 {
239 	/* Device path with a leading '=' key-value separator */
240 	char pci_path[] = "=pci/?/?";
241 	size_t pci_len;
242 	char pcie_path[] = "=pcie/?/?";
243 	size_t pcie_len;
244 
245 	u32 i, j;
246 	bool found;
247 	u8 *nvram;
248 	u8 id;
249 
250 	nvram = kzalloc(nvp->nvram_len + 1 + 3 + sizeof(u32), GFP_KERNEL);
251 	if (!nvram)
252 		goto fail;
253 
254 	/* min length: devpath0=pcie/1/4/ + 0:x=y */
255 	if (nvp->nvram_len < BRCMF_FW_NVRAM_DEVPATH_LEN + 6)
256 		goto fail;
257 
258 	/* First search for the devpathX and see if it is the configuration
259 	 * for domain_nr/bus_nr. Search complete nvp
260 	 */
261 	snprintf(pci_path, sizeof(pci_path), "=pci/%d/%d", domain_nr,
262 		 bus_nr);
263 	pci_len = strlen(pci_path);
264 	snprintf(pcie_path, sizeof(pcie_path), "=pcie/%d/%d", domain_nr,
265 		 bus_nr);
266 	pcie_len = strlen(pcie_path);
267 	found = false;
268 	i = 0;
269 	while (i < nvp->nvram_len - BRCMF_FW_NVRAM_DEVPATH_LEN) {
270 		/* Format: devpathX=pcie/Y/Z/
271 		 * Y = domain_nr, Z = bus_nr, X = virtual ID
272 		 */
273 		if (strncmp(&nvp->nvram[i], "devpath", 7) == 0 &&
274 		    (!strncmp(&nvp->nvram[i + 8], pci_path, pci_len) ||
275 		     !strncmp(&nvp->nvram[i + 8], pcie_path, pcie_len))) {
276 			id = nvp->nvram[i + 7] - '0';
277 			found = true;
278 			break;
279 		}
280 		while (nvp->nvram[i] != 0)
281 			i++;
282 		i++;
283 	}
284 	if (!found)
285 		goto fail;
286 
287 	/* Now copy all valid entries, release old nvram and assign new one */
288 	i = 0;
289 	j = 0;
290 	while (i < nvp->nvram_len) {
291 		if ((nvp->nvram[i] - '0' == id) && (nvp->nvram[i + 1] == ':')) {
292 			i += 2;
293 			if (strncmp(&nvp->nvram[i], "boardrev", 8) == 0)
294 				nvp->boardrev_found = true;
295 			while (nvp->nvram[i] != 0) {
296 				nvram[j] = nvp->nvram[i];
297 				i++;
298 				j++;
299 			}
300 			nvram[j] = 0;
301 			j++;
302 		}
303 		while (nvp->nvram[i] != 0)
304 			i++;
305 		i++;
306 	}
307 	kfree(nvp->nvram);
308 	nvp->nvram = nvram;
309 	nvp->nvram_len = j;
310 	return;
311 
312 fail:
313 	kfree(nvram);
314 	nvp->nvram_len = 0;
315 }
316 
317 /* brcmf_fw_strip_multi_v2 :Some nvram files contain settings for multiple
318  * devices. Strip it down for one device, use domain_nr/bus_nr to determine
319  * which data is to be returned. v2 is the version where nvram is stored
320  * uncompressed, all relevant valid entries are identified by
321  * pcie/domain_nr/bus_nr:
322  */
323 static void brcmf_fw_strip_multi_v2(struct nvram_parser *nvp, u16 domain_nr,
324 				    u16 bus_nr)
325 {
326 	char prefix[BRCMF_FW_NVRAM_PCIEDEV_LEN];
327 	size_t len;
328 	u32 i, j;
329 	u8 *nvram;
330 
331 	nvram = kzalloc(nvp->nvram_len + 1 + 3 + sizeof(u32), GFP_KERNEL);
332 	if (!nvram)
333 		goto fail;
334 
335 	/* Copy all valid entries, release old nvram and assign new one.
336 	 * Valid entries are of type pcie/X/Y/ where X = domain_nr and
337 	 * Y = bus_nr.
338 	 */
339 	snprintf(prefix, sizeof(prefix), "pcie/%d/%d/", domain_nr, bus_nr);
340 	len = strlen(prefix);
341 	i = 0;
342 	j = 0;
343 	while (i < nvp->nvram_len - len) {
344 		if (strncmp(&nvp->nvram[i], prefix, len) == 0) {
345 			i += len;
346 			if (strncmp(&nvp->nvram[i], "boardrev", 8) == 0)
347 				nvp->boardrev_found = true;
348 			while (nvp->nvram[i] != 0) {
349 				nvram[j] = nvp->nvram[i];
350 				i++;
351 				j++;
352 			}
353 			nvram[j] = 0;
354 			j++;
355 		}
356 		while (nvp->nvram[i] != 0)
357 			i++;
358 		i++;
359 	}
360 	kfree(nvp->nvram);
361 	nvp->nvram = nvram;
362 	nvp->nvram_len = j;
363 	return;
364 fail:
365 	kfree(nvram);
366 	nvp->nvram_len = 0;
367 }
368 
369 static void brcmf_fw_add_defaults(struct nvram_parser *nvp)
370 {
371 	if (nvp->boardrev_found)
372 		return;
373 
374 	memcpy(&nvp->nvram[nvp->nvram_len], &BRCMF_FW_DEFAULT_BOARDREV,
375 	       strlen(BRCMF_FW_DEFAULT_BOARDREV));
376 	nvp->nvram_len += strlen(BRCMF_FW_DEFAULT_BOARDREV);
377 	nvp->nvram[nvp->nvram_len] = '\0';
378 	nvp->nvram_len++;
379 }
380 
381 /* brcmf_nvram_strip :Takes a buffer of "<var>=<value>\n" lines read from a fil
382  * and ending in a NUL. Removes carriage returns, empty lines, comment lines,
383  * and converts newlines to NULs. Shortens buffer as needed and pads with NULs.
384  * End of buffer is completed with token identifying length of buffer.
385  */
386 static void *brcmf_fw_nvram_strip(const u8 *data, size_t data_len,
387 				  u32 *new_length, u16 domain_nr, u16 bus_nr)
388 {
389 	struct nvram_parser nvp;
390 	u32 pad;
391 	u32 token;
392 	__le32 token_le;
393 
394 	if (brcmf_init_nvram_parser(&nvp, data, data_len) < 0)
395 		return NULL;
396 
397 	while (nvp.pos < data_len) {
398 		nvp.state = nv_parser_states[nvp.state](&nvp);
399 		if (nvp.state == END)
400 			break;
401 	}
402 	if (nvp.multi_dev_v1) {
403 		nvp.boardrev_found = false;
404 		brcmf_fw_strip_multi_v1(&nvp, domain_nr, bus_nr);
405 	} else if (nvp.multi_dev_v2) {
406 		nvp.boardrev_found = false;
407 		brcmf_fw_strip_multi_v2(&nvp, domain_nr, bus_nr);
408 	}
409 
410 	if (nvp.nvram_len == 0) {
411 		kfree(nvp.nvram);
412 		return NULL;
413 	}
414 
415 	brcmf_fw_add_defaults(&nvp);
416 
417 	pad = nvp.nvram_len;
418 	*new_length = roundup(nvp.nvram_len + 1, 4);
419 	while (pad != *new_length) {
420 		nvp.nvram[pad] = 0;
421 		pad++;
422 	}
423 
424 	token = *new_length / 4;
425 	token = (~token << 16) | (token & 0x0000FFFF);
426 	token_le = cpu_to_le32(token);
427 
428 	memcpy(&nvp.nvram[*new_length], &token_le, sizeof(token_le));
429 	*new_length += sizeof(token_le);
430 
431 	return nvp.nvram;
432 }
433 
434 void brcmf_fw_nvram_free(void *nvram)
435 {
436 	kfree(nvram);
437 }
438 
439 struct brcmf_fw {
440 	struct device *dev;
441 	u16 flags;
442 	const struct firmware *code;
443 	const char *nvram_name;
444 	u16 domain_nr;
445 	u16 bus_nr;
446 	void (*done)(struct device *dev, int err, const struct firmware *fw,
447 		     void *nvram_image, u32 nvram_len);
448 };
449 
450 static void brcmf_fw_request_nvram_done(const struct firmware *fw, void *ctx)
451 {
452 	struct brcmf_fw *fwctx = ctx;
453 	u32 nvram_length = 0;
454 	void *nvram = NULL;
455 	u8 *data = NULL;
456 	size_t data_len;
457 	bool raw_nvram;
458 
459 	brcmf_dbg(TRACE, "enter: dev=%s\n", dev_name(fwctx->dev));
460 	if (fw && fw->data) {
461 		data = (u8 *)fw->data;
462 		data_len = fw->size;
463 		raw_nvram = false;
464 	} else {
465 		data = bcm47xx_nvram_get_contents(&data_len);
466 		if (!data && !(fwctx->flags & BRCMF_FW_REQ_NV_OPTIONAL))
467 			goto fail;
468 		raw_nvram = true;
469 	}
470 
471 	if (data)
472 		nvram = brcmf_fw_nvram_strip(data, data_len, &nvram_length,
473 					     fwctx->domain_nr, fwctx->bus_nr);
474 
475 	if (raw_nvram)
476 		bcm47xx_nvram_release_contents(data);
477 	release_firmware(fw);
478 	if (!nvram && !(fwctx->flags & BRCMF_FW_REQ_NV_OPTIONAL))
479 		goto fail;
480 
481 	fwctx->done(fwctx->dev, 0, fwctx->code, nvram, nvram_length);
482 	kfree(fwctx);
483 	return;
484 
485 fail:
486 	brcmf_dbg(TRACE, "failed: dev=%s\n", dev_name(fwctx->dev));
487 	release_firmware(fwctx->code);
488 	fwctx->done(fwctx->dev, -ENOENT, NULL, NULL, 0);
489 	kfree(fwctx);
490 }
491 
492 static void brcmf_fw_request_code_done(const struct firmware *fw, void *ctx)
493 {
494 	struct brcmf_fw *fwctx = ctx;
495 	int ret = 0;
496 
497 	brcmf_dbg(TRACE, "enter: dev=%s\n", dev_name(fwctx->dev));
498 	if (!fw) {
499 		ret = -ENOENT;
500 		goto fail;
501 	}
502 	/* only requested code so done here */
503 	if (!(fwctx->flags & BRCMF_FW_REQUEST_NVRAM))
504 		goto done;
505 
506 	fwctx->code = fw;
507 	ret = request_firmware_nowait(THIS_MODULE, true, fwctx->nvram_name,
508 				      fwctx->dev, GFP_KERNEL, fwctx,
509 				      brcmf_fw_request_nvram_done);
510 
511 	/* pass NULL to nvram callback for bcm47xx fallback */
512 	if (ret)
513 		brcmf_fw_request_nvram_done(NULL, fwctx);
514 	return;
515 
516 fail:
517 	brcmf_dbg(TRACE, "failed: dev=%s\n", dev_name(fwctx->dev));
518 done:
519 	fwctx->done(fwctx->dev, ret, fw, NULL, 0);
520 	kfree(fwctx);
521 }
522 
523 int brcmf_fw_get_firmwares_pcie(struct device *dev, u16 flags,
524 				const char *code, const char *nvram,
525 				void (*fw_cb)(struct device *dev, int err,
526 					      const struct firmware *fw,
527 					      void *nvram_image, u32 nvram_len),
528 				u16 domain_nr, u16 bus_nr)
529 {
530 	struct brcmf_fw *fwctx;
531 
532 	brcmf_dbg(TRACE, "enter: dev=%s\n", dev_name(dev));
533 	if (!fw_cb || !code)
534 		return -EINVAL;
535 
536 	if ((flags & BRCMF_FW_REQUEST_NVRAM) && !nvram)
537 		return -EINVAL;
538 
539 	fwctx = kzalloc(sizeof(*fwctx), GFP_KERNEL);
540 	if (!fwctx)
541 		return -ENOMEM;
542 
543 	fwctx->dev = dev;
544 	fwctx->flags = flags;
545 	fwctx->done = fw_cb;
546 	if (flags & BRCMF_FW_REQUEST_NVRAM)
547 		fwctx->nvram_name = nvram;
548 	fwctx->domain_nr = domain_nr;
549 	fwctx->bus_nr = bus_nr;
550 
551 	return request_firmware_nowait(THIS_MODULE, true, code, dev,
552 				       GFP_KERNEL, fwctx,
553 				       brcmf_fw_request_code_done);
554 }
555 
556 int brcmf_fw_get_firmwares(struct device *dev, u16 flags,
557 			   const char *code, const char *nvram,
558 			   void (*fw_cb)(struct device *dev, int err,
559 					 const struct firmware *fw,
560 					 void *nvram_image, u32 nvram_len))
561 {
562 	return brcmf_fw_get_firmwares_pcie(dev, flags, code, nvram, fw_cb, 0,
563 					   0);
564 }
565 
566 int brcmf_fw_map_chip_to_name(u32 chip, u32 chiprev,
567 			      struct brcmf_firmware_mapping mapping_table[],
568 			      u32 table_size, char fw_name[BRCMF_FW_NAME_LEN],
569 			      char nvram_name[BRCMF_FW_NAME_LEN])
570 {
571 	char chipname[12];
572 	u32 i;
573 	char end;
574 
575 	for (i = 0; i < table_size; i++) {
576 		if (mapping_table[i].chipid == chip &&
577 		    mapping_table[i].revmask & BIT(chiprev))
578 			break;
579 	}
580 
581 	if (i == table_size) {
582 		brcmf_err("Unknown chipid %d [%d]\n", chip, chiprev);
583 		return -ENODEV;
584 	}
585 
586 	brcmf_chip_name(chip, chiprev, chipname, sizeof(chipname));
587 
588 	/* check if firmware path is provided by module parameter */
589 	if (brcmf_mp_global.firmware_path[0] != '\0') {
590 		strlcpy(fw_name, brcmf_mp_global.firmware_path,
591 			BRCMF_FW_NAME_LEN);
592 		if ((nvram_name) && (mapping_table[i].nvram))
593 			strlcpy(nvram_name, brcmf_mp_global.firmware_path,
594 				BRCMF_FW_NAME_LEN);
595 
596 		end = brcmf_mp_global.firmware_path[
597 				strlen(brcmf_mp_global.firmware_path) - 1];
598 		if (end != '/') {
599 			strlcat(fw_name, "/", BRCMF_FW_NAME_LEN);
600 			if ((nvram_name) && (mapping_table[i].nvram))
601 				strlcat(nvram_name, "/", BRCMF_FW_NAME_LEN);
602 		}
603 	}
604 	strlcat(fw_name, mapping_table[i].fw, BRCMF_FW_NAME_LEN);
605 	if ((nvram_name) && (mapping_table[i].nvram))
606 		strlcat(nvram_name, mapping_table[i].nvram, BRCMF_FW_NAME_LEN);
607 
608 	brcmf_info("using %s for chip %s\n", fw_name, chipname);
609 
610 	return 0;
611 }
612 
613