1 // SPDX-License-Identifier: (GPL-2.0 OR MPL-1.1)
2 /* from src/prism2/download/prism2dl.c
3  *
4  * utility for downloading prism2 images moved into kernelspace
5  *
6  * Copyright (C) 1999 AbsoluteValue Systems, Inc.  All Rights Reserved.
7  * --------------------------------------------------------------------
8  *
9  * linux-wlan
10  *
11  *   The contents of this file are subject to the Mozilla Public
12  *   License Version 1.1 (the "License"); you may not use this file
13  *   except in compliance with the License. You may obtain a copy of
14  *   the License at http://www.mozilla.org/MPL/
15  *
16  *   Software distributed under the License is distributed on an "AS
17  *   IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
18  *   implied. See the License for the specific language governing
19  *   rights and limitations under the License.
20  *
21  *   Alternatively, the contents of this file may be used under the
22  *   terms of the GNU Public License version 2 (the "GPL"), in which
23  *   case the provisions of the GPL are applicable instead of the
24  *   above.  If you wish to allow the use of your version of this file
25  *   only under the terms of the GPL and not to allow others to use
26  *   your version of this file under the MPL, indicate your decision
27  *   by deleting the provisions above and replace them with the notice
28  *   and other provisions required by the GPL.  If you do not delete
29  *   the provisions above, a recipient may use your version of this
30  *   file under either the MPL or the GPL.
31  *
32  * --------------------------------------------------------------------
33  *
34  * Inquiries regarding the linux-wlan Open Source project can be
35  * made directly to:
36  *
37  * AbsoluteValue Systems Inc.
38  * info@linux-wlan.com
39  * http://www.linux-wlan.com
40  *
41  * --------------------------------------------------------------------
42  *
43  * Portions of the development of this software were funded by
44  * Intersil Corporation as part of PRISM(R) chipset product development.
45  *
46  * --------------------------------------------------------------------
47  */
48 
49 /*================================================================*/
50 /* System Includes */
51 #include <linux/ihex.h>
52 #include <linux/slab.h>
53 
54 /*================================================================*/
55 /* Local Constants */
56 
57 #define PRISM2_USB_FWFILE	"prism2_ru.fw"
58 MODULE_FIRMWARE(PRISM2_USB_FWFILE);
59 
60 #define S3DATA_MAX		5000
61 #define S3PLUG_MAX		200
62 #define S3CRC_MAX		200
63 #define S3INFO_MAX		50
64 
65 #define S3ADDR_PLUG		(0xff000000UL)
66 #define S3ADDR_CRC		(0xff100000UL)
67 #define S3ADDR_INFO		(0xff200000UL)
68 #define S3ADDR_START		(0xff400000UL)
69 
70 #define CHUNKS_MAX		100
71 
72 #define WRITESIZE_MAX		4096
73 
74 /*================================================================*/
75 /* Local Types */
76 
77 struct s3datarec {
78 	u32 len;
79 	u32 addr;
80 	u8 checksum;
81 	u8 *data;
82 };
83 
84 struct s3plugrec {
85 	u32 itemcode;
86 	u32 addr;
87 	u32 len;
88 };
89 
90 struct s3crcrec {
91 	u32 addr;
92 	u32 len;
93 	unsigned int dowrite;
94 };
95 
96 struct s3inforec {
97 	u16 len;
98 	u16 type;
99 	union {
100 		struct hfa384x_compident version;
101 		struct hfa384x_caplevel compat;
102 		u16 buildseq;
103 		struct hfa384x_compident platform;
104 	} info;
105 };
106 
107 struct pda {
108 	u8 buf[HFA384x_PDA_LEN_MAX];
109 	struct hfa384x_pdrec *rec[HFA384x_PDA_RECS_MAX];
110 	unsigned int nrec;
111 };
112 
113 struct imgchunk {
114 	u32 addr;	/* start address */
115 	u32 len;	/* in bytes */
116 	u16 crc;	/* CRC value (if it falls at a chunk boundary) */
117 	u8 *data;
118 };
119 
120 /*================================================================*/
121 /* Local Static Definitions */
122 
123 /*----------------------------------------------------------------*/
124 /* s-record image processing */
125 
126 /* Data records */
127 static unsigned int ns3data;
128 static struct s3datarec *s3data;
129 
130 /* Plug records */
131 static unsigned int ns3plug;
132 static struct s3plugrec s3plug[S3PLUG_MAX];
133 
134 /* CRC records */
135 static unsigned int ns3crc;
136 static struct s3crcrec s3crc[S3CRC_MAX];
137 
138 /* Info records */
139 static unsigned int ns3info;
140 static struct s3inforec s3info[S3INFO_MAX];
141 
142 /* S7 record (there _better_ be only one) */
143 static u32 startaddr;
144 
145 /* Load image chunks */
146 static unsigned int nfchunks;
147 static struct imgchunk fchunk[CHUNKS_MAX];
148 
149 /* Note that for the following pdrec_t arrays, the len and code */
150 /*   fields are stored in HOST byte order. The mkpdrlist() function */
151 /*   does the conversion.  */
152 /*----------------------------------------------------------------*/
153 /* PDA, built from [card|newfile]+[addfile1+addfile2...] */
154 
155 static struct pda pda;
156 static struct hfa384x_compident nicid;
157 static struct hfa384x_caplevel rfid;
158 static struct hfa384x_caplevel macid;
159 static struct hfa384x_caplevel priid;
160 
161 /*================================================================*/
162 /* Local Function Declarations */
163 
164 static int prism2_fwapply(const struct ihex_binrec *rfptr,
165 			  struct wlandevice *wlandev);
166 
167 static int read_fwfile(const struct ihex_binrec *rfptr);
168 
169 static int mkimage(struct imgchunk *clist, unsigned int *ccnt);
170 
171 static int read_cardpda(struct pda *pda, struct wlandevice *wlandev);
172 
173 static int mkpdrlist(struct pda *pda);
174 
175 static int plugimage(struct imgchunk *fchunk, unsigned int nfchunks,
176 		     struct s3plugrec *s3plug, unsigned int ns3plug,
177 		     struct pda *pda);
178 
179 static int crcimage(struct imgchunk *fchunk, unsigned int nfchunks,
180 		    struct s3crcrec *s3crc, unsigned int ns3crc);
181 
182 static int writeimage(struct wlandevice *wlandev, struct imgchunk *fchunk,
183 		      unsigned int nfchunks);
184 
185 static void free_chunks(struct imgchunk *fchunk, unsigned int *nfchunks);
186 
187 static void free_srecs(void);
188 
189 static int validate_identity(void);
190 
191 /*================================================================*/
192 /* Function Definitions */
193 
194 /*----------------------------------------------------------------
195  * prism2_fwtry
196  *
197  * Try and get firmware into memory
198  *
199  * Arguments:
200  *	udev	usb device structure
201  *	wlandev wlan device structure
202  *
203  * Returns:
204  *	0	- success
205  *	~0	- failure
206  *----------------------------------------------------------------
207  */
208 static int prism2_fwtry(struct usb_device *udev, struct wlandevice *wlandev)
209 {
210 	const struct firmware *fw_entry = NULL;
211 
212 	netdev_info(wlandev->netdev, "prism2_usb: Checking for firmware %s\n",
213 		    PRISM2_USB_FWFILE);
214 	if (request_ihex_firmware(&fw_entry,
215 				  PRISM2_USB_FWFILE, &udev->dev) != 0) {
216 		netdev_info(wlandev->netdev,
217 			    "prism2_usb: Firmware not available, but not essential\n");
218 		netdev_info(wlandev->netdev,
219 			    "prism2_usb: can continue to use card anyway.\n");
220 		return 1;
221 	}
222 
223 	netdev_info(wlandev->netdev,
224 		    "prism2_usb: %s will be processed, size %zu\n",
225 		    PRISM2_USB_FWFILE, fw_entry->size);
226 	prism2_fwapply((const struct ihex_binrec *)fw_entry->data, wlandev);
227 
228 	release_firmware(fw_entry);
229 	return 0;
230 }
231 
232 /*----------------------------------------------------------------
233  * prism2_fwapply
234  *
235  * Apply the firmware loaded into memory
236  *
237  * Arguments:
238  *	rfptr	firmware image in kernel memory
239  *	wlandev device
240  *
241  * Returns:
242  *	0	- success
243  *	~0	- failure
244  *----------------------------------------------------------------
245  */
246 static int prism2_fwapply(const struct ihex_binrec *rfptr,
247 			  struct wlandevice *wlandev)
248 {
249 	signed int result = 0;
250 	struct p80211msg_dot11req_mibget getmsg;
251 	struct p80211itemd *item;
252 	u32 *data;
253 
254 	/* Initialize the data structures */
255 	ns3data = 0;
256 	s3data = kcalloc(S3DATA_MAX, sizeof(*s3data), GFP_KERNEL);
257 	if (!s3data) {
258 		result = -ENOMEM;
259 		goto out;
260 	}
261 
262 	ns3plug = 0;
263 	memset(s3plug, 0, sizeof(s3plug));
264 	ns3crc = 0;
265 	memset(s3crc, 0, sizeof(s3crc));
266 	ns3info = 0;
267 	memset(s3info, 0, sizeof(s3info));
268 	startaddr = 0;
269 
270 	nfchunks = 0;
271 	memset(fchunk, 0, sizeof(fchunk));
272 	memset(&nicid, 0, sizeof(nicid));
273 	memset(&rfid, 0, sizeof(rfid));
274 	memset(&macid, 0, sizeof(macid));
275 	memset(&priid, 0, sizeof(priid));
276 
277 	/* clear the pda and add an initial END record */
278 	memset(&pda, 0, sizeof(pda));
279 	pda.rec[0] = (struct hfa384x_pdrec *)pda.buf;
280 	pda.rec[0]->len = cpu_to_le16(2);	/* len in words */
281 	pda.rec[0]->code = cpu_to_le16(HFA384x_PDR_END_OF_PDA);
282 	pda.nrec = 1;
283 
284 	/*-----------------------------------------------------*/
285 	/* Put card into fwload state */
286 	prism2sta_ifstate(wlandev, P80211ENUM_ifstate_fwload);
287 
288 	/* Build the PDA we're going to use. */
289 	if (read_cardpda(&pda, wlandev)) {
290 		netdev_err(wlandev->netdev, "load_cardpda failed, exiting.\n");
291 		result = 1;
292 		goto out;
293 	}
294 
295 	/* read the card's PRI-SUP */
296 	memset(&getmsg, 0, sizeof(getmsg));
297 	getmsg.msgcode = DIDMSG_DOT11REQ_MIBGET;
298 	getmsg.msglen = sizeof(getmsg);
299 	strscpy(getmsg.devname, wlandev->name, sizeof(getmsg.devname));
300 
301 	getmsg.mibattribute.did = DIDMSG_DOT11REQ_MIBGET_MIBATTRIBUTE;
302 	getmsg.mibattribute.status = P80211ENUM_msgitem_status_data_ok;
303 	getmsg.resultcode.did = DIDMSG_DOT11REQ_MIBGET_RESULTCODE;
304 	getmsg.resultcode.status = P80211ENUM_msgitem_status_no_value;
305 
306 	item = (struct p80211itemd *)getmsg.mibattribute.data;
307 	item->did = DIDMIB_P2_NIC_PRISUPRANGE;
308 	item->status = P80211ENUM_msgitem_status_no_value;
309 
310 	data = (u32 *)item->data;
311 
312 	/* DIDmsg_dot11req_mibget */
313 	prism2mgmt_mibset_mibget(wlandev, &getmsg);
314 	if (getmsg.resultcode.data != P80211ENUM_resultcode_success)
315 		netdev_err(wlandev->netdev, "Couldn't fetch PRI-SUP info\n");
316 
317 	/* Already in host order */
318 	priid.role = *data++;
319 	priid.id = *data++;
320 	priid.variant = *data++;
321 	priid.bottom = *data++;
322 	priid.top = *data++;
323 
324 	/* Read the S3 file */
325 	result = read_fwfile(rfptr);
326 	if (result) {
327 		netdev_err(wlandev->netdev,
328 			   "Failed to read the data exiting.\n");
329 		goto out;
330 	}
331 
332 	result = validate_identity();
333 	if (result) {
334 		netdev_err(wlandev->netdev, "Incompatible firmware image.\n");
335 		goto out;
336 	}
337 
338 	if (startaddr == 0x00000000) {
339 		netdev_err(wlandev->netdev,
340 			   "Can't RAM download a Flash image!\n");
341 		result = 1;
342 		goto out;
343 	}
344 
345 	/* Make the image chunks */
346 	result = mkimage(fchunk, &nfchunks);
347 	if (result) {
348 		netdev_err(wlandev->netdev, "Failed to make image chunk.\n");
349 		goto free_chunks;
350 	}
351 
352 	/* Do any plugging */
353 	result = plugimage(fchunk, nfchunks, s3plug, ns3plug, &pda);
354 	if (result) {
355 		netdev_err(wlandev->netdev, "Failed to plug data.\n");
356 		goto free_chunks;
357 	}
358 
359 	/* Insert any CRCs */
360 	result = crcimage(fchunk, nfchunks, s3crc, ns3crc);
361 	if (result) {
362 		netdev_err(wlandev->netdev, "Failed to insert all CRCs\n");
363 		goto free_chunks;
364 	}
365 
366 	/* Write the image */
367 	result = writeimage(wlandev, fchunk, nfchunks);
368 	if (result) {
369 		netdev_err(wlandev->netdev, "Failed to ramwrite image data.\n");
370 		goto free_chunks;
371 	}
372 
373 	netdev_info(wlandev->netdev, "prism2_usb: firmware loading finished.\n");
374 
375 free_chunks:
376 	/* clear any allocated memory */
377 	free_chunks(fchunk, &nfchunks);
378 	free_srecs();
379 
380 out:
381 	return result;
382 }
383 
384 /*----------------------------------------------------------------
385  * crcimage
386  *
387  * Adds a CRC16 in the two bytes prior to each block identified by
388  * an S3 CRC record.  Currently, we don't actually do a CRC we just
389  * insert the value 0xC0DE in hfa384x order.
390  *
391  * Arguments:
392  *	fchunk		Array of image chunks
393  *	nfchunks	Number of image chunks
394  *	s3crc		Array of crc records
395  *	ns3crc		Number of crc records
396  *
397  * Returns:
398  *	0	success
399  *	~0	failure
400  *----------------------------------------------------------------
401  */
402 static int crcimage(struct imgchunk *fchunk, unsigned int nfchunks,
403 		    struct s3crcrec *s3crc, unsigned int ns3crc)
404 {
405 	int result = 0;
406 	int i;
407 	int c;
408 	u32 crcstart;
409 	u32 cstart = 0;
410 	u32 cend;
411 	u8 *dest;
412 	u32 chunkoff;
413 
414 	for (i = 0; i < ns3crc; i++) {
415 		if (!s3crc[i].dowrite)
416 			continue;
417 		crcstart = s3crc[i].addr;
418 		/* Find chunk */
419 		for (c = 0; c < nfchunks; c++) {
420 			cstart = fchunk[c].addr;
421 			cend = fchunk[c].addr + fchunk[c].len;
422 			/* the line below does an address & len match search */
423 			/* unfortunately, I've found that the len fields of */
424 			/* some crc records don't match with the length of */
425 			/* the actual data, so we're not checking right now */
426 			/* if (crcstart-2 >= cstart && crcend <= cend) break; */
427 
428 			/* note the -2 below, it's to make sure the chunk has */
429 			/* space for the CRC value */
430 			if (crcstart - 2 >= cstart && crcstart < cend)
431 				break;
432 		}
433 		if (c >= nfchunks) {
434 			pr_err("Failed to find chunk for crcrec[%d], addr=0x%06x len=%d , aborting crc.\n",
435 			       i, s3crc[i].addr, s3crc[i].len);
436 			return 1;
437 		}
438 
439 		/* Insert crc */
440 		pr_debug("Adding crc @ 0x%06x\n", s3crc[i].addr - 2);
441 		chunkoff = crcstart - cstart - 2;
442 		dest = fchunk[c].data + chunkoff;
443 		*dest = 0xde;
444 		*(dest + 1) = 0xc0;
445 	}
446 	return result;
447 }
448 
449 /*----------------------------------------------------------------
450  * free_chunks
451  *
452  * Clears the chunklist data structures in preparation for a new file.
453  *
454  * Arguments:
455  *	none
456  *
457  * Returns:
458  *	nothing
459  *----------------------------------------------------------------
460  */
461 static void free_chunks(struct imgchunk *fchunk, unsigned int *nfchunks)
462 {
463 	int i;
464 
465 	for (i = 0; i < *nfchunks; i++)
466 		kfree(fchunk[i].data);
467 
468 	*nfchunks = 0;
469 	memset(fchunk, 0, sizeof(*fchunk));
470 }
471 
472 /*----------------------------------------------------------------
473  * free_srecs
474  *
475  * Clears the srec data structures in preparation for a new file.
476  *
477  * Arguments:
478  *	none
479  *
480  * Returns:
481  *	nothing
482  *----------------------------------------------------------------
483  */
484 static void free_srecs(void)
485 {
486 	ns3data = 0;
487 	kfree(s3data);
488 	ns3plug = 0;
489 	memset(s3plug, 0, sizeof(s3plug));
490 	ns3crc = 0;
491 	memset(s3crc, 0, sizeof(s3crc));
492 	ns3info = 0;
493 	memset(s3info, 0, sizeof(s3info));
494 	startaddr = 0;
495 }
496 
497 /*----------------------------------------------------------------
498  * mkimage
499  *
500  * Scans the currently loaded set of S records for data residing
501  * in contiguous memory regions.  Each contiguous region is then
502  * made into a 'chunk'.  This function assumes that we're building
503  * a new chunk list.  Assumes the s3data items are in sorted order.
504  *
505  * Arguments:	none
506  *
507  * Returns:
508  *	0	- success
509  *	~0	- failure (probably an errno)
510  *----------------------------------------------------------------
511  */
512 static int mkimage(struct imgchunk *clist, unsigned int *ccnt)
513 {
514 	int result = 0;
515 	int i;
516 	int j;
517 	int currchunk = 0;
518 	u32 nextaddr = 0;
519 	u32 s3start;
520 	u32 s3end;
521 	u32 cstart = 0;
522 	u32 cend;
523 	u32 coffset;
524 
525 	/* There may already be data in the chunklist */
526 	*ccnt = 0;
527 
528 	/* Establish the location and size of each chunk */
529 	for (i = 0; i < ns3data; i++) {
530 		if (s3data[i].addr == nextaddr) {
531 			/* existing chunk, grow it */
532 			clist[currchunk].len += s3data[i].len;
533 			nextaddr += s3data[i].len;
534 		} else {
535 			/* New chunk */
536 			(*ccnt)++;
537 			currchunk = *ccnt - 1;
538 			clist[currchunk].addr = s3data[i].addr;
539 			clist[currchunk].len = s3data[i].len;
540 			nextaddr = s3data[i].addr + s3data[i].len;
541 			/* Expand the chunk if there is a CRC record at */
542 			/* their beginning bound */
543 			for (j = 0; j < ns3crc; j++) {
544 				if (s3crc[j].dowrite &&
545 				    s3crc[j].addr == clist[currchunk].addr) {
546 					clist[currchunk].addr -= 2;
547 					clist[currchunk].len += 2;
548 				}
549 			}
550 		}
551 	}
552 
553 	/* We're currently assuming there aren't any overlapping chunks */
554 	/*  if this proves false, we'll need to add code to coalesce. */
555 
556 	/* Allocate buffer space for chunks */
557 	for (i = 0; i < *ccnt; i++) {
558 		clist[i].data = kzalloc(clist[i].len, GFP_KERNEL);
559 		if (!clist[i].data)
560 			return 1;
561 
562 		pr_debug("chunk[%d]: addr=0x%06x len=%d\n",
563 			 i, clist[i].addr, clist[i].len);
564 	}
565 
566 	/* Copy srec data to chunks */
567 	for (i = 0; i < ns3data; i++) {
568 		s3start = s3data[i].addr;
569 		s3end = s3start + s3data[i].len - 1;
570 		for (j = 0; j < *ccnt; j++) {
571 			cstart = clist[j].addr;
572 			cend = cstart + clist[j].len - 1;
573 			if (s3start >= cstart && s3end <= cend)
574 				break;
575 		}
576 		if (((unsigned int)j) >= (*ccnt)) {
577 			pr_err("s3rec(a=0x%06x,l=%d), no chunk match, exiting.\n",
578 			       s3start, s3data[i].len);
579 			return 1;
580 		}
581 		coffset = s3start - cstart;
582 		memcpy(clist[j].data + coffset, s3data[i].data, s3data[i].len);
583 	}
584 
585 	return result;
586 }
587 
588 /*----------------------------------------------------------------
589  * mkpdrlist
590  *
591  * Reads a raw PDA and builds an array of pdrec_t structures.
592  *
593  * Arguments:
594  *	pda	buffer containing raw PDA bytes
595  *	pdrec	ptr to an array of pdrec_t's.  Will be filled on exit.
596  *	nrec	ptr to a variable that will contain the count of PDRs
597  *
598  * Returns:
599  *	0	- success
600  *	~0	- failure (probably an errno)
601  *----------------------------------------------------------------
602  */
603 static int mkpdrlist(struct pda *pda)
604 {
605 	__le16 *pda16 = (__le16 *)pda->buf;
606 	int curroff;		/* in 'words' */
607 
608 	pda->nrec = 0;
609 	curroff = 0;
610 	while (curroff < (HFA384x_PDA_LEN_MAX / 2 - 1) &&
611 	       le16_to_cpu(pda16[curroff + 1]) != HFA384x_PDR_END_OF_PDA) {
612 		pda->rec[pda->nrec] = (struct hfa384x_pdrec *)&pda16[curroff];
613 
614 		if (le16_to_cpu(pda->rec[pda->nrec]->code) ==
615 		    HFA384x_PDR_NICID) {
616 			memcpy(&nicid, &pda->rec[pda->nrec]->data.nicid,
617 			       sizeof(nicid));
618 			le16_to_cpus(&nicid.id);
619 			le16_to_cpus(&nicid.variant);
620 			le16_to_cpus(&nicid.major);
621 			le16_to_cpus(&nicid.minor);
622 		}
623 		if (le16_to_cpu(pda->rec[pda->nrec]->code) ==
624 		    HFA384x_PDR_MFISUPRANGE) {
625 			memcpy(&rfid, &pda->rec[pda->nrec]->data.mfisuprange,
626 			       sizeof(rfid));
627 			le16_to_cpus(&rfid.id);
628 			le16_to_cpus(&rfid.variant);
629 			le16_to_cpus(&rfid.bottom);
630 			le16_to_cpus(&rfid.top);
631 		}
632 		if (le16_to_cpu(pda->rec[pda->nrec]->code) ==
633 		    HFA384x_PDR_CFISUPRANGE) {
634 			memcpy(&macid, &pda->rec[pda->nrec]->data.cfisuprange,
635 			       sizeof(macid));
636 			le16_to_cpus(&macid.id);
637 			le16_to_cpus(&macid.variant);
638 			le16_to_cpus(&macid.bottom);
639 			le16_to_cpus(&macid.top);
640 		}
641 
642 		(pda->nrec)++;
643 		curroff += le16_to_cpu(pda16[curroff]) + 1;
644 	}
645 	if (curroff >= (HFA384x_PDA_LEN_MAX / 2 - 1)) {
646 		pr_err("no end record found or invalid lengths in PDR data, exiting. %x %d\n",
647 		       curroff, pda->nrec);
648 		return 1;
649 	}
650 	pda->rec[pda->nrec] = (struct hfa384x_pdrec *)&pda16[curroff];
651 	(pda->nrec)++;
652 	return 0;
653 }
654 
655 /*----------------------------------------------------------------
656  * plugimage
657  *
658  * Plugs the given image using the given plug records from the given
659  * PDA and filename.
660  *
661  * Arguments:
662  *	fchunk		Array of image chunks
663  *	nfchunks	Number of image chunks
664  *	s3plug		Array of plug records
665  *	ns3plug		Number of plug records
666  *	pda		Current pda data
667  *
668  * Returns:
669  *	0	success
670  *	~0	failure
671  *----------------------------------------------------------------
672  */
673 static int plugimage(struct imgchunk *fchunk, unsigned int nfchunks,
674 		     struct s3plugrec *s3plug, unsigned int ns3plug,
675 		     struct pda *pda)
676 {
677 	int result = 0;
678 	int i;			/* plug index */
679 	int j;			/* index of PDR or -1 if fname plug */
680 	int c;			/* chunk index */
681 	u32 pstart;
682 	u32 pend;
683 	u32 cstart = 0;
684 	u32 cend;
685 	u32 chunkoff;
686 	u8 *dest;
687 
688 	/* for each plug record */
689 	for (i = 0; i < ns3plug; i++) {
690 		pstart = s3plug[i].addr;
691 		pend = s3plug[i].addr + s3plug[i].len;
692 		j = -1;
693 		/* find the matching PDR (or filename) */
694 		if (s3plug[i].itemcode != 0xffffffffUL) { /* not filename */
695 			for (j = 0; j < pda->nrec; j++) {
696 				if (s3plug[i].itemcode ==
697 				    le16_to_cpu(pda->rec[j]->code))
698 					break;
699 			}
700 		}
701 		if (j >= pda->nrec && j != -1) { /*  if no matching PDR, fail */
702 			pr_warn("warning: Failed to find PDR for plugrec 0x%04x.\n",
703 				s3plug[i].itemcode);
704 			continue;	/* and move on to the next PDR */
705 
706 			/* MSM: They swear that unless it's the MAC address,
707 			 * the serial number, or the TX calibration records,
708 			 * then there's reasonable defaults in the f/w
709 			 * image.  Therefore, missing PDRs in the card
710 			 * should only be a warning, not fatal.
711 			 * TODO: add fatals for the PDRs mentioned above.
712 			 */
713 		}
714 
715 		/* Validate plug len against PDR len */
716 		if (j != -1 && s3plug[i].len < le16_to_cpu(pda->rec[j]->len)) {
717 			pr_err("error: Plug vs. PDR len mismatch for plugrec 0x%04x, abort plugging.\n",
718 			       s3plug[i].itemcode);
719 			result = 1;
720 			continue;
721 		}
722 
723 		/*
724 		 * Validate plug address against
725 		 * chunk data and identify chunk
726 		 */
727 		for (c = 0; c < nfchunks; c++) {
728 			cstart = fchunk[c].addr;
729 			cend = fchunk[c].addr + fchunk[c].len;
730 			if (pstart >= cstart && pend <= cend)
731 				break;
732 		}
733 		if (c >= nfchunks) {
734 			pr_err("error: Failed to find image chunk for plugrec 0x%04x.\n",
735 			       s3plug[i].itemcode);
736 			result = 1;
737 			continue;
738 		}
739 
740 		/* Plug data */
741 		chunkoff = pstart - cstart;
742 		dest = fchunk[c].data + chunkoff;
743 		pr_debug("Plugging item 0x%04x @ 0x%06x, len=%d, cnum=%d coff=0x%06x\n",
744 			 s3plug[i].itemcode, pstart, s3plug[i].len,
745 			 c, chunkoff);
746 
747 		if (j == -1) {	/* plug the filename */
748 			memset(dest, 0, s3plug[i].len);
749 			strncpy(dest, PRISM2_USB_FWFILE, s3plug[i].len - 1);
750 		} else {	/* plug a PDR */
751 			memcpy(dest, &pda->rec[j]->data, s3plug[i].len);
752 		}
753 	}
754 	return result;
755 }
756 
757 /*----------------------------------------------------------------
758  * read_cardpda
759  *
760  * Sends the command for the driver to read the pda from the card
761  * named in the device variable.  Upon success, the card pda is
762  * stored in the "cardpda" variables.  Note that the pda structure
763  * is considered 'well formed' after this function.  That means
764  * that the nrecs is valid, the rec array has been set up, and there's
765  * a valid PDAEND record in the raw PDA data.
766  *
767  * Arguments:
768  *	pda		pda structure
769  *	wlandev		device
770  *
771  * Returns:
772  *	0	- success
773  *	~0	- failure (probably an errno)
774  *----------------------------------------------------------------
775  */
776 static int read_cardpda(struct pda *pda, struct wlandevice *wlandev)
777 {
778 	int result = 0;
779 	struct p80211msg_p2req_readpda *msg;
780 
781 	msg = kzalloc(sizeof(*msg), GFP_KERNEL);
782 	if (!msg)
783 		return -ENOMEM;
784 
785 	/* set up the msg */
786 	msg->msgcode = DIDMSG_P2REQ_READPDA;
787 	msg->msglen = sizeof(msg);
788 	strscpy(msg->devname, wlandev->name, sizeof(msg->devname));
789 	msg->pda.did = DIDMSG_P2REQ_READPDA_PDA;
790 	msg->pda.len = HFA384x_PDA_LEN_MAX;
791 	msg->pda.status = P80211ENUM_msgitem_status_no_value;
792 	msg->resultcode.did = DIDMSG_P2REQ_READPDA_RESULTCODE;
793 	msg->resultcode.len = sizeof(u32);
794 	msg->resultcode.status = P80211ENUM_msgitem_status_no_value;
795 
796 	if (prism2mgmt_readpda(wlandev, msg) != 0) {
797 		/* prism2mgmt_readpda prints an errno if appropriate */
798 		result = -1;
799 	} else if (msg->resultcode.data == P80211ENUM_resultcode_success) {
800 		memcpy(pda->buf, msg->pda.data, HFA384x_PDA_LEN_MAX);
801 		result = mkpdrlist(pda);
802 	} else {
803 		/* resultcode must've been something other than success */
804 		result = -1;
805 	}
806 
807 	kfree(msg);
808 	return result;
809 }
810 
811 /*----------------------------------------------------------------
812  * read_fwfile
813  *
814  * Reads the given fw file which should have been compiled from an srec
815  * file. Each record in the fw file will either be a plain data record,
816  * a start address record, or other records used for plugging.
817  *
818  * Note that data records are expected to be sorted into
819  * ascending address order in the fw file.
820  *
821  * Note also that the start address record, originally an S7 record in
822  * the srec file, is expected in the fw file to be like a data record but
823  * with a certain address to make it identifiable.
824  *
825  * Here's the SREC format that the fw should have come from:
826  * S[37]nnaaaaaaaaddd...dddcc
827  *
828  *       nn - number of bytes starting with the address field
829  * aaaaaaaa - address in readable (or big endian) format
830  * dd....dd - 0-245 data bytes (two chars per byte)
831  *       cc - checksum
832  *
833  * The S7 record's (there should be only one) address value gets
834  * converted to an S3 record with address of 0xff400000, with the
835  * start address being stored as a 4 byte data word. That address is
836  * the start execution address used for RAM downloads.
837  *
838  * The S3 records have a collection of subformats indicated by the
839  * value of aaaaaaaa:
840  *   0xff000000 - Plug record, data field format:
841  *                xxxxxxxxaaaaaaaassssssss
842  *                x - PDR code number (little endian)
843  *                a - Address in load image to plug (little endian)
844  *                s - Length of plug data area (little endian)
845  *
846  *   0xff100000 - CRC16 generation record, data field format:
847  *                aaaaaaaassssssssbbbbbbbb
848  *                a - Start address for CRC calculation (little endian)
849  *                s - Length of data to  calculate over (little endian)
850  *                b - Boolean, true=write crc, false=don't write
851  *
852  *   0xff200000 - Info record, data field format:
853  *                ssssttttdd..dd
854  *                s - Size in words (little endian)
855  *                t - Info type (little endian), see #defines and
856  *                    struct s3inforec for details about types.
857  *                d - (s - 1) little endian words giving the contents of
858  *                    the given info type.
859  *
860  *   0xff400000 - Start address record, data field format:
861  *                aaaaaaaa
862  *                a - Address in load image to plug (little endian)
863  *
864  * Arguments:
865  *	record	firmware image (ihex record structure) in kernel memory
866  *
867  * Returns:
868  *	0	- success
869  *	~0	- failure (probably an errno)
870  *----------------------------------------------------------------
871  */
872 static int read_fwfile(const struct ihex_binrec *record)
873 {
874 	int		i;
875 	int		rcnt = 0;
876 	u16		*tmpinfo;
877 	u16		*ptr16;
878 	u32		*ptr32, len, addr;
879 
880 	pr_debug("Reading fw file ...\n");
881 
882 	while (record) {
883 		rcnt++;
884 
885 		len = be16_to_cpu(record->len);
886 		addr = be32_to_cpu(record->addr);
887 
888 		/* Point into data for different word lengths */
889 		ptr32 = (u32 *)record->data;
890 		ptr16 = (u16 *)record->data;
891 
892 		/* parse what was an S3 srec and put it in the right array */
893 		switch (addr) {
894 		case S3ADDR_START:
895 			startaddr = *ptr32;
896 			pr_debug("  S7 start addr, record=%d addr=0x%08x\n",
897 				 rcnt,
898 				 startaddr);
899 			break;
900 		case S3ADDR_PLUG:
901 			s3plug[ns3plug].itemcode = *ptr32;
902 			s3plug[ns3plug].addr = *(ptr32 + 1);
903 			s3plug[ns3plug].len = *(ptr32 + 2);
904 
905 			pr_debug("  S3 plugrec, record=%d itemcode=0x%08x addr=0x%08x len=%d\n",
906 				 rcnt,
907 				 s3plug[ns3plug].itemcode,
908 				 s3plug[ns3plug].addr,
909 				 s3plug[ns3plug].len);
910 
911 			ns3plug++;
912 			if (ns3plug == S3PLUG_MAX) {
913 				pr_err("S3 plugrec limit reached - aborting\n");
914 				return 1;
915 			}
916 			break;
917 		case S3ADDR_CRC:
918 			s3crc[ns3crc].addr = *ptr32;
919 			s3crc[ns3crc].len = *(ptr32 + 1);
920 			s3crc[ns3crc].dowrite = *(ptr32 + 2);
921 
922 			pr_debug("  S3 crcrec, record=%d addr=0x%08x len=%d write=0x%08x\n",
923 				 rcnt,
924 				 s3crc[ns3crc].addr,
925 				 s3crc[ns3crc].len,
926 				 s3crc[ns3crc].dowrite);
927 			ns3crc++;
928 			if (ns3crc == S3CRC_MAX) {
929 				pr_err("S3 crcrec limit reached - aborting\n");
930 				return 1;
931 			}
932 			break;
933 		case S3ADDR_INFO:
934 			s3info[ns3info].len = *ptr16;
935 			s3info[ns3info].type = *(ptr16 + 1);
936 
937 			pr_debug("  S3 inforec, record=%d len=0x%04x type=0x%04x\n",
938 				 rcnt,
939 				 s3info[ns3info].len,
940 				 s3info[ns3info].type);
941 			if (((s3info[ns3info].len - 1) * sizeof(u16)) >
942 			   sizeof(s3info[ns3info].info)) {
943 				pr_err("S3 inforec length too long - aborting\n");
944 				return 1;
945 			}
946 
947 			tmpinfo = (u16 *)&s3info[ns3info].info.version;
948 			pr_debug("            info=");
949 			for (i = 0; i < s3info[ns3info].len - 1; i++) {
950 				tmpinfo[i] = *(ptr16 + 2 + i);
951 				pr_debug("%04x ", tmpinfo[i]);
952 			}
953 			pr_debug("\n");
954 
955 			ns3info++;
956 			if (ns3info == S3INFO_MAX) {
957 				pr_err("S3 inforec limit reached - aborting\n");
958 				return 1;
959 			}
960 			break;
961 		default:	/* Data record */
962 			s3data[ns3data].addr = addr;
963 			s3data[ns3data].len = len;
964 			s3data[ns3data].data = (uint8_t *)record->data;
965 			ns3data++;
966 			if (ns3data == S3DATA_MAX) {
967 				pr_err("S3 datarec limit reached - aborting\n");
968 				return 1;
969 			}
970 			break;
971 		}
972 		record = ihex_next_binrec(record);
973 	}
974 	return 0;
975 }
976 
977 /*----------------------------------------------------------------
978  * writeimage
979  *
980  * Takes the chunks, builds p80211 messages and sends them down
981  * to the driver for writing to the card.
982  *
983  * Arguments:
984  *	wlandev		device
985  *	fchunk		Array of image chunks
986  *	nfchunks	Number of image chunks
987  *
988  * Returns:
989  *	0	success
990  *	~0	failure
991  *----------------------------------------------------------------
992  */
993 static int writeimage(struct wlandevice *wlandev, struct imgchunk *fchunk,
994 		      unsigned int nfchunks)
995 {
996 	int result = 0;
997 	struct p80211msg_p2req_ramdl_state *rstmsg;
998 	struct p80211msg_p2req_ramdl_write *rwrmsg;
999 	u32 resultcode;
1000 	int i;
1001 	int j;
1002 	unsigned int nwrites;
1003 	u32 curroff;
1004 	u32 currlen;
1005 	u32 currdaddr;
1006 
1007 	rstmsg = kzalloc(sizeof(*rstmsg), GFP_KERNEL);
1008 	rwrmsg = kzalloc(sizeof(*rwrmsg), GFP_KERNEL);
1009 	if (!rstmsg || !rwrmsg) {
1010 		netdev_err(wlandev->netdev,
1011 			   "%s: no memory for firmware download, aborting download\n",
1012 			   __func__);
1013 		result = -ENOMEM;
1014 		goto free_result;
1015 	}
1016 
1017 	/* Initialize the messages */
1018 	strscpy(rstmsg->devname, wlandev->name, sizeof(rstmsg->devname));
1019 	rstmsg->msgcode = DIDMSG_P2REQ_RAMDL_STATE;
1020 	rstmsg->msglen = sizeof(*rstmsg);
1021 	rstmsg->enable.did = DIDMSG_P2REQ_RAMDL_STATE_ENABLE;
1022 	rstmsg->exeaddr.did = DIDMSG_P2REQ_RAMDL_STATE_EXEADDR;
1023 	rstmsg->resultcode.did = DIDMSG_P2REQ_RAMDL_STATE_RESULTCODE;
1024 	rstmsg->enable.status = P80211ENUM_msgitem_status_data_ok;
1025 	rstmsg->exeaddr.status = P80211ENUM_msgitem_status_data_ok;
1026 	rstmsg->resultcode.status = P80211ENUM_msgitem_status_no_value;
1027 	rstmsg->enable.len = sizeof(u32);
1028 	rstmsg->exeaddr.len = sizeof(u32);
1029 	rstmsg->resultcode.len = sizeof(u32);
1030 
1031 	strscpy(rwrmsg->devname, wlandev->name, sizeof(rwrmsg->devname));
1032 	rwrmsg->msgcode = DIDMSG_P2REQ_RAMDL_WRITE;
1033 	rwrmsg->msglen = sizeof(*rwrmsg);
1034 	rwrmsg->addr.did = DIDMSG_P2REQ_RAMDL_WRITE_ADDR;
1035 	rwrmsg->len.did = DIDMSG_P2REQ_RAMDL_WRITE_LEN;
1036 	rwrmsg->data.did = DIDMSG_P2REQ_RAMDL_WRITE_DATA;
1037 	rwrmsg->resultcode.did = DIDMSG_P2REQ_RAMDL_WRITE_RESULTCODE;
1038 	rwrmsg->addr.status = P80211ENUM_msgitem_status_data_ok;
1039 	rwrmsg->len.status = P80211ENUM_msgitem_status_data_ok;
1040 	rwrmsg->data.status = P80211ENUM_msgitem_status_data_ok;
1041 	rwrmsg->resultcode.status = P80211ENUM_msgitem_status_no_value;
1042 	rwrmsg->addr.len = sizeof(u32);
1043 	rwrmsg->len.len = sizeof(u32);
1044 	rwrmsg->data.len = WRITESIZE_MAX;
1045 	rwrmsg->resultcode.len = sizeof(u32);
1046 
1047 	/* Send xxx_state(enable) */
1048 	pr_debug("Sending dl_state(enable) message.\n");
1049 	rstmsg->enable.data = P80211ENUM_truth_true;
1050 	rstmsg->exeaddr.data = startaddr;
1051 
1052 	result = prism2mgmt_ramdl_state(wlandev, rstmsg);
1053 	if (result) {
1054 		netdev_err(wlandev->netdev,
1055 			   "%s state enable failed w/ result=%d, aborting download\n",
1056 			   __func__, result);
1057 		goto free_result;
1058 	}
1059 	resultcode = rstmsg->resultcode.data;
1060 	if (resultcode != P80211ENUM_resultcode_success) {
1061 		netdev_err(wlandev->netdev,
1062 			   "%s()->xxxdl_state msg indicates failure, w/ resultcode=%d, aborting download.\n",
1063 			   __func__, resultcode);
1064 		result = 1;
1065 		goto free_result;
1066 	}
1067 
1068 	/* Now, loop through the data chunks and send WRITESIZE_MAX data */
1069 	for (i = 0; i < nfchunks; i++) {
1070 		nwrites = fchunk[i].len / WRITESIZE_MAX;
1071 		nwrites += (fchunk[i].len % WRITESIZE_MAX) ? 1 : 0;
1072 		curroff = 0;
1073 		for (j = 0; j < nwrites; j++) {
1074 			/* TODO Move this to a separate function */
1075 			int lenleft = fchunk[i].len - (WRITESIZE_MAX * j);
1076 
1077 			if (fchunk[i].len > WRITESIZE_MAX)
1078 				currlen = WRITESIZE_MAX;
1079 			else
1080 				currlen = lenleft;
1081 			curroff = j * WRITESIZE_MAX;
1082 			currdaddr = fchunk[i].addr + curroff;
1083 			/* Setup the message */
1084 			rwrmsg->addr.data = currdaddr;
1085 			rwrmsg->len.data = currlen;
1086 			memcpy(rwrmsg->data.data,
1087 			       fchunk[i].data + curroff, currlen);
1088 
1089 			/* Send flashdl_write(pda) */
1090 			pr_debug
1091 			    ("Sending xxxdl_write message addr=%06x len=%d.\n",
1092 			     currdaddr, currlen);
1093 
1094 			result = prism2mgmt_ramdl_write(wlandev, rwrmsg);
1095 
1096 			/* Check the results */
1097 			if (result) {
1098 				netdev_err(wlandev->netdev,
1099 					   "%s chunk write failed w/ result=%d, aborting download\n",
1100 					   __func__, result);
1101 				goto free_result;
1102 			}
1103 			resultcode = rstmsg->resultcode.data;
1104 			if (resultcode != P80211ENUM_resultcode_success) {
1105 				pr_err("%s()->xxxdl_write msg indicates failure, w/ resultcode=%d, aborting download.\n",
1106 				       __func__, resultcode);
1107 				result = 1;
1108 				goto free_result;
1109 			}
1110 		}
1111 	}
1112 
1113 	/* Send xxx_state(disable) */
1114 	pr_debug("Sending dl_state(disable) message.\n");
1115 	rstmsg->enable.data = P80211ENUM_truth_false;
1116 	rstmsg->exeaddr.data = 0;
1117 
1118 	result = prism2mgmt_ramdl_state(wlandev, rstmsg);
1119 	if (result) {
1120 		netdev_err(wlandev->netdev,
1121 			   "%s state disable failed w/ result=%d, aborting download\n",
1122 			   __func__, result);
1123 		goto free_result;
1124 	}
1125 	resultcode = rstmsg->resultcode.data;
1126 	if (resultcode != P80211ENUM_resultcode_success) {
1127 		netdev_err(wlandev->netdev,
1128 			   "%s()->xxxdl_state msg indicates failure, w/ resultcode=%d, aborting download.\n",
1129 			   __func__, resultcode);
1130 		result = 1;
1131 		goto free_result;
1132 	}
1133 
1134 free_result:
1135 	kfree(rstmsg);
1136 	kfree(rwrmsg);
1137 	return result;
1138 }
1139 
1140 static int validate_identity(void)
1141 {
1142 	int i;
1143 	int result = 1;
1144 	int trump = 0;
1145 
1146 	pr_debug("NIC ID: %#x v%d.%d.%d\n",
1147 		 nicid.id, nicid.major, nicid.minor, nicid.variant);
1148 	pr_debug("MFI ID: %#x v%d %d->%d\n",
1149 		 rfid.id, rfid.variant, rfid.bottom, rfid.top);
1150 	pr_debug("CFI ID: %#x v%d %d->%d\n",
1151 		 macid.id, macid.variant, macid.bottom, macid.top);
1152 	pr_debug("PRI ID: %#x v%d %d->%d\n",
1153 		 priid.id, priid.variant, priid.bottom, priid.top);
1154 
1155 	for (i = 0; i < ns3info; i++) {
1156 		switch (s3info[i].type) {
1157 		case 1:
1158 			pr_debug("Version:  ID %#x %d.%d.%d\n",
1159 				 s3info[i].info.version.id,
1160 				 s3info[i].info.version.major,
1161 				 s3info[i].info.version.minor,
1162 				 s3info[i].info.version.variant);
1163 			break;
1164 		case 2:
1165 			pr_debug("Compat: Role %#x Id %#x v%d %d->%d\n",
1166 				 s3info[i].info.compat.role,
1167 				 s3info[i].info.compat.id,
1168 				 s3info[i].info.compat.variant,
1169 				 s3info[i].info.compat.bottom,
1170 				 s3info[i].info.compat.top);
1171 
1172 			/* MAC compat range */
1173 			if ((s3info[i].info.compat.role == 1) &&
1174 			    (s3info[i].info.compat.id == 2)) {
1175 				if (s3info[i].info.compat.variant !=
1176 				    macid.variant) {
1177 					result = 2;
1178 				}
1179 			}
1180 
1181 			/* PRI compat range */
1182 			if ((s3info[i].info.compat.role == 1) &&
1183 			    (s3info[i].info.compat.id == 3)) {
1184 				if ((s3info[i].info.compat.bottom >
1185 				     priid.top) ||
1186 				    (s3info[i].info.compat.top <
1187 				     priid.bottom)) {
1188 					result = 3;
1189 				}
1190 			}
1191 			/* SEC compat range */
1192 			if ((s3info[i].info.compat.role == 1) &&
1193 			    (s3info[i].info.compat.id == 4)) {
1194 				/* FIXME: isn't something missing here? */
1195 			}
1196 
1197 			break;
1198 		case 3:
1199 			pr_debug("Seq: %#x\n", s3info[i].info.buildseq);
1200 
1201 			break;
1202 		case 4:
1203 			pr_debug("Platform:  ID %#x %d.%d.%d\n",
1204 				 s3info[i].info.version.id,
1205 				 s3info[i].info.version.major,
1206 				 s3info[i].info.version.minor,
1207 				 s3info[i].info.version.variant);
1208 
1209 			if (nicid.id != s3info[i].info.version.id)
1210 				continue;
1211 			if (nicid.major != s3info[i].info.version.major)
1212 				continue;
1213 			if (nicid.minor != s3info[i].info.version.minor)
1214 				continue;
1215 			if ((nicid.variant != s3info[i].info.version.variant) &&
1216 			    (nicid.id != 0x8008))
1217 				continue;
1218 
1219 			trump = 1;
1220 			break;
1221 		case 0x8001:
1222 			pr_debug("name inforec len %d\n", s3info[i].len);
1223 
1224 			break;
1225 		default:
1226 			pr_debug("Unknown inforec type %d\n", s3info[i].type);
1227 		}
1228 	}
1229 	/* walk through */
1230 
1231 	if (trump && (result != 2))
1232 		result = 0;
1233 	return result;
1234 }
1235