xref: /linux/drivers/infiniband/hw/hfi1/firmware.c (revision e2be04c7f9958dde770eeb8b30e829ca969b37bb)
1 /*
2  * Copyright(c) 2015 - 2017 Intel Corporation.
3  *
4  * This file is provided under a dual BSD/GPLv2 license.  When using or
5  * redistributing this file, you may do so under either license.
6  *
7  * GPL LICENSE SUMMARY
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of version 2 of the GNU General Public License as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * BSD LICENSE
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  *  - Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  *  - Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in
28  *    the documentation and/or other materials provided with the
29  *    distribution.
30  *  - Neither the name of Intel Corporation nor the names of its
31  *    contributors may be used to endorse or promote products derived
32  *    from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
35  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
36  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
37  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
38  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
39  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
40  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
41  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
42  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
43  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
44  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45  *
46  */
47 
48 #include <linux/firmware.h>
49 #include <linux/mutex.h>
50 #include <linux/module.h>
51 #include <linux/delay.h>
52 #include <linux/crc32.h>
53 
54 #include "hfi.h"
55 #include "trace.h"
56 
57 /*
58  * Make it easy to toggle firmware file name and if it gets loaded by
59  * editing the following. This may be something we do while in development
60  * but not necessarily something a user would ever need to use.
61  */
62 #define DEFAULT_FW_8051_NAME_FPGA "hfi_dc8051.bin"
63 #define DEFAULT_FW_8051_NAME_ASIC "hfi1_dc8051.fw"
64 #define DEFAULT_FW_FABRIC_NAME "hfi1_fabric.fw"
65 #define DEFAULT_FW_SBUS_NAME "hfi1_sbus.fw"
66 #define DEFAULT_FW_PCIE_NAME "hfi1_pcie.fw"
67 #define ALT_FW_8051_NAME_ASIC "hfi1_dc8051_d.fw"
68 #define ALT_FW_FABRIC_NAME "hfi1_fabric_d.fw"
69 #define ALT_FW_SBUS_NAME "hfi1_sbus_d.fw"
70 #define ALT_FW_PCIE_NAME "hfi1_pcie_d.fw"
71 #define HOST_INTERFACE_VERSION 1
72 
73 static uint fw_8051_load = 1;
74 static uint fw_fabric_serdes_load = 1;
75 static uint fw_pcie_serdes_load = 1;
76 static uint fw_sbus_load = 1;
77 
78 /* Firmware file names get set in hfi1_firmware_init() based on the above */
79 static char *fw_8051_name;
80 static char *fw_fabric_serdes_name;
81 static char *fw_sbus_name;
82 static char *fw_pcie_serdes_name;
83 
84 #define SBUS_MAX_POLL_COUNT 100
85 #define SBUS_COUNTER(reg, name) \
86 	(((reg) >> ASIC_STS_SBUS_COUNTERS_##name##_CNT_SHIFT) & \
87 	 ASIC_STS_SBUS_COUNTERS_##name##_CNT_MASK)
88 
89 /*
90  * Firmware security header.
91  */
92 struct css_header {
93 	u32 module_type;
94 	u32 header_len;
95 	u32 header_version;
96 	u32 module_id;
97 	u32 module_vendor;
98 	u32 date;		/* BCD yyyymmdd */
99 	u32 size;		/* in DWORDs */
100 	u32 key_size;		/* in DWORDs */
101 	u32 modulus_size;	/* in DWORDs */
102 	u32 exponent_size;	/* in DWORDs */
103 	u32 reserved[22];
104 };
105 
106 /* expected field values */
107 #define CSS_MODULE_TYPE	   0x00000006
108 #define CSS_HEADER_LEN	   0x000000a1
109 #define CSS_HEADER_VERSION 0x00010000
110 #define CSS_MODULE_VENDOR  0x00008086
111 
112 #define KEY_SIZE      256
113 #define MU_SIZE		8
114 #define EXPONENT_SIZE	4
115 
116 /* the file itself */
117 struct firmware_file {
118 	struct css_header css_header;
119 	u8 modulus[KEY_SIZE];
120 	u8 exponent[EXPONENT_SIZE];
121 	u8 signature[KEY_SIZE];
122 	u8 firmware[];
123 };
124 
125 struct augmented_firmware_file {
126 	struct css_header css_header;
127 	u8 modulus[KEY_SIZE];
128 	u8 exponent[EXPONENT_SIZE];
129 	u8 signature[KEY_SIZE];
130 	u8 r2[KEY_SIZE];
131 	u8 mu[MU_SIZE];
132 	u8 firmware[];
133 };
134 
135 /* augmented file size difference */
136 #define AUGMENT_SIZE (sizeof(struct augmented_firmware_file) - \
137 						sizeof(struct firmware_file))
138 
139 struct firmware_details {
140 	/* Linux core piece */
141 	const struct firmware *fw;
142 
143 	struct css_header *css_header;
144 	u8 *firmware_ptr;		/* pointer to binary data */
145 	u32 firmware_len;		/* length in bytes */
146 	u8 *modulus;			/* pointer to the modulus */
147 	u8 *exponent;			/* pointer to the exponent */
148 	u8 *signature;			/* pointer to the signature */
149 	u8 *r2;				/* pointer to r2 */
150 	u8 *mu;				/* pointer to mu */
151 	struct augmented_firmware_file dummy_header;
152 };
153 
154 /*
155  * The mutex protects fw_state, fw_err, and all of the firmware_details
156  * variables.
157  */
158 static DEFINE_MUTEX(fw_mutex);
159 enum fw_state {
160 	FW_EMPTY,
161 	FW_TRY,
162 	FW_FINAL,
163 	FW_ERR
164 };
165 
166 static enum fw_state fw_state = FW_EMPTY;
167 static int fw_err;
168 static struct firmware_details fw_8051;
169 static struct firmware_details fw_fabric;
170 static struct firmware_details fw_pcie;
171 static struct firmware_details fw_sbus;
172 
173 /* flags for turn_off_spicos() */
174 #define SPICO_SBUS   0x1
175 #define SPICO_FABRIC 0x2
176 #define ENABLE_SPICO_SMASK 0x1
177 
178 /* security block commands */
179 #define RSA_CMD_INIT  0x1
180 #define RSA_CMD_START 0x2
181 
182 /* security block status */
183 #define RSA_STATUS_IDLE   0x0
184 #define RSA_STATUS_ACTIVE 0x1
185 #define RSA_STATUS_DONE   0x2
186 #define RSA_STATUS_FAILED 0x3
187 
188 /* RSA engine timeout, in ms */
189 #define RSA_ENGINE_TIMEOUT 100 /* ms */
190 
191 /* hardware mutex timeout, in ms */
192 #define HM_TIMEOUT 10 /* ms */
193 
194 /* 8051 memory access timeout, in us */
195 #define DC8051_ACCESS_TIMEOUT 100 /* us */
196 
197 /* the number of fabric SerDes on the SBus */
198 #define NUM_FABRIC_SERDES 4
199 
200 /* ASIC_STS_SBUS_RESULT.RESULT_CODE value */
201 #define SBUS_READ_COMPLETE 0x4
202 
203 /* SBus fabric SerDes addresses, one set per HFI */
204 static const u8 fabric_serdes_addrs[2][NUM_FABRIC_SERDES] = {
205 	{ 0x01, 0x02, 0x03, 0x04 },
206 	{ 0x28, 0x29, 0x2a, 0x2b }
207 };
208 
209 /* SBus PCIe SerDes addresses, one set per HFI */
210 static const u8 pcie_serdes_addrs[2][NUM_PCIE_SERDES] = {
211 	{ 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
212 	  0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26 },
213 	{ 0x2f, 0x31, 0x33, 0x35, 0x37, 0x39, 0x3b, 0x3d,
214 	  0x3f, 0x41, 0x43, 0x45, 0x47, 0x49, 0x4b, 0x4d }
215 };
216 
217 /* SBus PCIe PCS addresses, one set per HFI */
218 const u8 pcie_pcs_addrs[2][NUM_PCIE_SERDES] = {
219 	{ 0x09, 0x0b, 0x0d, 0x0f, 0x11, 0x13, 0x15, 0x17,
220 	  0x19, 0x1b, 0x1d, 0x1f, 0x21, 0x23, 0x25, 0x27 },
221 	{ 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e,
222 	  0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e }
223 };
224 
225 /* SBus fabric SerDes broadcast addresses, one per HFI */
226 static const u8 fabric_serdes_broadcast[2] = { 0xe4, 0xe5 };
227 static const u8 all_fabric_serdes_broadcast = 0xe1;
228 
229 /* SBus PCIe SerDes broadcast addresses, one per HFI */
230 const u8 pcie_serdes_broadcast[2] = { 0xe2, 0xe3 };
231 static const u8 all_pcie_serdes_broadcast = 0xe0;
232 
233 static const u32 platform_config_table_limits[PLATFORM_CONFIG_TABLE_MAX] = {
234 	0,
235 	SYSTEM_TABLE_MAX,
236 	PORT_TABLE_MAX,
237 	RX_PRESET_TABLE_MAX,
238 	TX_PRESET_TABLE_MAX,
239 	QSFP_ATTEN_TABLE_MAX,
240 	VARIABLE_SETTINGS_TABLE_MAX
241 };
242 
243 /* forwards */
244 static void dispose_one_firmware(struct firmware_details *fdet);
245 static int load_fabric_serdes_firmware(struct hfi1_devdata *dd,
246 				       struct firmware_details *fdet);
247 static void dump_fw_version(struct hfi1_devdata *dd);
248 
249 /*
250  * Read a single 64-bit value from 8051 data memory.
251  *
252  * Expects:
253  * o caller to have already set up data read, no auto increment
254  * o caller to turn off read enable when finished
255  *
256  * The address argument is a byte offset.  Bits 0:2 in the address are
257  * ignored - i.e. the hardware will always do aligned 8-byte reads as if
258  * the lower bits are zero.
259  *
260  * Return 0 on success, -ENXIO on a read error (timeout).
261  */
262 static int __read_8051_data(struct hfi1_devdata *dd, u32 addr, u64 *result)
263 {
264 	u64 reg;
265 	int count;
266 
267 	/* step 1: set the address, clear enable */
268 	reg = (addr & DC_DC8051_CFG_RAM_ACCESS_CTRL_ADDRESS_MASK)
269 			<< DC_DC8051_CFG_RAM_ACCESS_CTRL_ADDRESS_SHIFT;
270 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_CTRL, reg);
271 	/* step 2: enable */
272 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_CTRL,
273 		  reg | DC_DC8051_CFG_RAM_ACCESS_CTRL_READ_ENA_SMASK);
274 
275 	/* wait until ACCESS_COMPLETED is set */
276 	count = 0;
277 	while ((read_csr(dd, DC_DC8051_CFG_RAM_ACCESS_STATUS)
278 		    & DC_DC8051_CFG_RAM_ACCESS_STATUS_ACCESS_COMPLETED_SMASK)
279 		    == 0) {
280 		count++;
281 		if (count > DC8051_ACCESS_TIMEOUT) {
282 			dd_dev_err(dd, "timeout reading 8051 data\n");
283 			return -ENXIO;
284 		}
285 		ndelay(10);
286 	}
287 
288 	/* gather the data */
289 	*result = read_csr(dd, DC_DC8051_CFG_RAM_ACCESS_RD_DATA);
290 
291 	return 0;
292 }
293 
294 /*
295  * Read 8051 data starting at addr, for len bytes.  Will read in 8-byte chunks.
296  * Return 0 on success, -errno on error.
297  */
298 int read_8051_data(struct hfi1_devdata *dd, u32 addr, u32 len, u64 *result)
299 {
300 	unsigned long flags;
301 	u32 done;
302 	int ret = 0;
303 
304 	spin_lock_irqsave(&dd->dc8051_memlock, flags);
305 
306 	/* data read set-up, no auto-increment */
307 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_SETUP, 0);
308 
309 	for (done = 0; done < len; addr += 8, done += 8, result++) {
310 		ret = __read_8051_data(dd, addr, result);
311 		if (ret)
312 			break;
313 	}
314 
315 	/* turn off read enable */
316 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_CTRL, 0);
317 
318 	spin_unlock_irqrestore(&dd->dc8051_memlock, flags);
319 
320 	return ret;
321 }
322 
323 /*
324  * Write data or code to the 8051 code or data RAM.
325  */
326 static int write_8051(struct hfi1_devdata *dd, int code, u32 start,
327 		      const u8 *data, u32 len)
328 {
329 	u64 reg;
330 	u32 offset;
331 	int aligned, count;
332 
333 	/* check alignment */
334 	aligned = ((unsigned long)data & 0x7) == 0;
335 
336 	/* write set-up */
337 	reg = (code ? DC_DC8051_CFG_RAM_ACCESS_SETUP_RAM_SEL_SMASK : 0ull)
338 		| DC_DC8051_CFG_RAM_ACCESS_SETUP_AUTO_INCR_ADDR_SMASK;
339 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_SETUP, reg);
340 
341 	reg = ((start & DC_DC8051_CFG_RAM_ACCESS_CTRL_ADDRESS_MASK)
342 			<< DC_DC8051_CFG_RAM_ACCESS_CTRL_ADDRESS_SHIFT)
343 		| DC_DC8051_CFG_RAM_ACCESS_CTRL_WRITE_ENA_SMASK;
344 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_CTRL, reg);
345 
346 	/* write */
347 	for (offset = 0; offset < len; offset += 8) {
348 		int bytes = len - offset;
349 
350 		if (bytes < 8) {
351 			reg = 0;
352 			memcpy(&reg, &data[offset], bytes);
353 		} else if (aligned) {
354 			reg = *(u64 *)&data[offset];
355 		} else {
356 			memcpy(&reg, &data[offset], 8);
357 		}
358 		write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_WR_DATA, reg);
359 
360 		/* wait until ACCESS_COMPLETED is set */
361 		count = 0;
362 		while ((read_csr(dd, DC_DC8051_CFG_RAM_ACCESS_STATUS)
363 		    & DC_DC8051_CFG_RAM_ACCESS_STATUS_ACCESS_COMPLETED_SMASK)
364 		    == 0) {
365 			count++;
366 			if (count > DC8051_ACCESS_TIMEOUT) {
367 				dd_dev_err(dd, "timeout writing 8051 data\n");
368 				return -ENXIO;
369 			}
370 			udelay(1);
371 		}
372 	}
373 
374 	/* turn off write access, auto increment (also sets to data access) */
375 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_CTRL, 0);
376 	write_csr(dd, DC_DC8051_CFG_RAM_ACCESS_SETUP, 0);
377 
378 	return 0;
379 }
380 
381 /* return 0 if values match, non-zero and complain otherwise */
382 static int invalid_header(struct hfi1_devdata *dd, const char *what,
383 			  u32 actual, u32 expected)
384 {
385 	if (actual == expected)
386 		return 0;
387 
388 	dd_dev_err(dd,
389 		   "invalid firmware header field %s: expected 0x%x, actual 0x%x\n",
390 		   what, expected, actual);
391 	return 1;
392 }
393 
394 /*
395  * Verify that the static fields in the CSS header match.
396  */
397 static int verify_css_header(struct hfi1_devdata *dd, struct css_header *css)
398 {
399 	/* verify CSS header fields (most sizes are in DW, so add /4) */
400 	if (invalid_header(dd, "module_type", css->module_type,
401 			   CSS_MODULE_TYPE) ||
402 	    invalid_header(dd, "header_len", css->header_len,
403 			   (sizeof(struct firmware_file) / 4)) ||
404 	    invalid_header(dd, "header_version", css->header_version,
405 			   CSS_HEADER_VERSION) ||
406 	    invalid_header(dd, "module_vendor", css->module_vendor,
407 			   CSS_MODULE_VENDOR) ||
408 	    invalid_header(dd, "key_size", css->key_size, KEY_SIZE / 4) ||
409 	    invalid_header(dd, "modulus_size", css->modulus_size,
410 			   KEY_SIZE / 4) ||
411 	    invalid_header(dd, "exponent_size", css->exponent_size,
412 			   EXPONENT_SIZE / 4)) {
413 		return -EINVAL;
414 	}
415 	return 0;
416 }
417 
418 /*
419  * Make sure there are at least some bytes after the prefix.
420  */
421 static int payload_check(struct hfi1_devdata *dd, const char *name,
422 			 long file_size, long prefix_size)
423 {
424 	/* make sure we have some payload */
425 	if (prefix_size >= file_size) {
426 		dd_dev_err(dd,
427 			   "firmware \"%s\", size %ld, must be larger than %ld bytes\n",
428 			   name, file_size, prefix_size);
429 		return -EINVAL;
430 	}
431 
432 	return 0;
433 }
434 
435 /*
436  * Request the firmware from the system.  Extract the pieces and fill in
437  * fdet.  If successful, the caller will need to call dispose_one_firmware().
438  * Returns 0 on success, -ERRNO on error.
439  */
440 static int obtain_one_firmware(struct hfi1_devdata *dd, const char *name,
441 			       struct firmware_details *fdet)
442 {
443 	struct css_header *css;
444 	int ret;
445 
446 	memset(fdet, 0, sizeof(*fdet));
447 
448 	ret = request_firmware(&fdet->fw, name, &dd->pcidev->dev);
449 	if (ret) {
450 		dd_dev_warn(dd, "cannot find firmware \"%s\", err %d\n",
451 			    name, ret);
452 		return ret;
453 	}
454 
455 	/* verify the firmware */
456 	if (fdet->fw->size < sizeof(struct css_header)) {
457 		dd_dev_err(dd, "firmware \"%s\" is too small\n", name);
458 		ret = -EINVAL;
459 		goto done;
460 	}
461 	css = (struct css_header *)fdet->fw->data;
462 
463 	hfi1_cdbg(FIRMWARE, "Firmware %s details:", name);
464 	hfi1_cdbg(FIRMWARE, "file size: 0x%lx bytes", fdet->fw->size);
465 	hfi1_cdbg(FIRMWARE, "CSS structure:");
466 	hfi1_cdbg(FIRMWARE, "  module_type    0x%x", css->module_type);
467 	hfi1_cdbg(FIRMWARE, "  header_len     0x%03x (0x%03x bytes)",
468 		  css->header_len, 4 * css->header_len);
469 	hfi1_cdbg(FIRMWARE, "  header_version 0x%x", css->header_version);
470 	hfi1_cdbg(FIRMWARE, "  module_id      0x%x", css->module_id);
471 	hfi1_cdbg(FIRMWARE, "  module_vendor  0x%x", css->module_vendor);
472 	hfi1_cdbg(FIRMWARE, "  date           0x%x", css->date);
473 	hfi1_cdbg(FIRMWARE, "  size           0x%03x (0x%03x bytes)",
474 		  css->size, 4 * css->size);
475 	hfi1_cdbg(FIRMWARE, "  key_size       0x%03x (0x%03x bytes)",
476 		  css->key_size, 4 * css->key_size);
477 	hfi1_cdbg(FIRMWARE, "  modulus_size   0x%03x (0x%03x bytes)",
478 		  css->modulus_size, 4 * css->modulus_size);
479 	hfi1_cdbg(FIRMWARE, "  exponent_size  0x%03x (0x%03x bytes)",
480 		  css->exponent_size, 4 * css->exponent_size);
481 	hfi1_cdbg(FIRMWARE, "firmware size: 0x%lx bytes",
482 		  fdet->fw->size - sizeof(struct firmware_file));
483 
484 	/*
485 	 * If the file does not have a valid CSS header, fail.
486 	 * Otherwise, check the CSS size field for an expected size.
487 	 * The augmented file has r2 and mu inserted after the header
488 	 * was generated, so there will be a known difference between
489 	 * the CSS header size and the actual file size.  Use this
490 	 * difference to identify an augmented file.
491 	 *
492 	 * Note: css->size is in DWORDs, multiply by 4 to get bytes.
493 	 */
494 	ret = verify_css_header(dd, css);
495 	if (ret) {
496 		dd_dev_info(dd, "Invalid CSS header for \"%s\"\n", name);
497 	} else if ((css->size * 4) == fdet->fw->size) {
498 		/* non-augmented firmware file */
499 		struct firmware_file *ff = (struct firmware_file *)
500 							fdet->fw->data;
501 
502 		/* make sure there are bytes in the payload */
503 		ret = payload_check(dd, name, fdet->fw->size,
504 				    sizeof(struct firmware_file));
505 		if (ret == 0) {
506 			fdet->css_header = css;
507 			fdet->modulus = ff->modulus;
508 			fdet->exponent = ff->exponent;
509 			fdet->signature = ff->signature;
510 			fdet->r2 = fdet->dummy_header.r2; /* use dummy space */
511 			fdet->mu = fdet->dummy_header.mu; /* use dummy space */
512 			fdet->firmware_ptr = ff->firmware;
513 			fdet->firmware_len = fdet->fw->size -
514 						sizeof(struct firmware_file);
515 			/*
516 			 * Header does not include r2 and mu - generate here.
517 			 * For now, fail.
518 			 */
519 			dd_dev_err(dd, "driver is unable to validate firmware without r2 and mu (not in firmware file)\n");
520 			ret = -EINVAL;
521 		}
522 	} else if ((css->size * 4) + AUGMENT_SIZE == fdet->fw->size) {
523 		/* augmented firmware file */
524 		struct augmented_firmware_file *aff =
525 			(struct augmented_firmware_file *)fdet->fw->data;
526 
527 		/* make sure there are bytes in the payload */
528 		ret = payload_check(dd, name, fdet->fw->size,
529 				    sizeof(struct augmented_firmware_file));
530 		if (ret == 0) {
531 			fdet->css_header = css;
532 			fdet->modulus = aff->modulus;
533 			fdet->exponent = aff->exponent;
534 			fdet->signature = aff->signature;
535 			fdet->r2 = aff->r2;
536 			fdet->mu = aff->mu;
537 			fdet->firmware_ptr = aff->firmware;
538 			fdet->firmware_len = fdet->fw->size -
539 					sizeof(struct augmented_firmware_file);
540 		}
541 	} else {
542 		/* css->size check failed */
543 		dd_dev_err(dd,
544 			   "invalid firmware header field size: expected 0x%lx or 0x%lx, actual 0x%x\n",
545 			   fdet->fw->size / 4,
546 			   (fdet->fw->size - AUGMENT_SIZE) / 4,
547 			   css->size);
548 
549 		ret = -EINVAL;
550 	}
551 
552 done:
553 	/* if returning an error, clean up after ourselves */
554 	if (ret)
555 		dispose_one_firmware(fdet);
556 	return ret;
557 }
558 
559 static void dispose_one_firmware(struct firmware_details *fdet)
560 {
561 	release_firmware(fdet->fw);
562 	/* erase all previous information */
563 	memset(fdet, 0, sizeof(*fdet));
564 }
565 
566 /*
567  * Obtain the 4 firmwares from the OS.  All must be obtained at once or not
568  * at all.  If called with the firmware state in FW_TRY, use alternate names.
569  * On exit, this routine will have set the firmware state to one of FW_TRY,
570  * FW_FINAL, or FW_ERR.
571  *
572  * Must be holding fw_mutex.
573  */
574 static void __obtain_firmware(struct hfi1_devdata *dd)
575 {
576 	int err = 0;
577 
578 	if (fw_state == FW_FINAL)	/* nothing more to obtain */
579 		return;
580 	if (fw_state == FW_ERR)		/* already in error */
581 		return;
582 
583 	/* fw_state is FW_EMPTY or FW_TRY */
584 retry:
585 	if (fw_state == FW_TRY) {
586 		/*
587 		 * We tried the original and it failed.  Move to the
588 		 * alternate.
589 		 */
590 		dd_dev_warn(dd, "using alternate firmware names\n");
591 		/*
592 		 * Let others run.  Some systems, when missing firmware, does
593 		 * something that holds for 30 seconds.  If we do that twice
594 		 * in a row it triggers task blocked warning.
595 		 */
596 		cond_resched();
597 		if (fw_8051_load)
598 			dispose_one_firmware(&fw_8051);
599 		if (fw_fabric_serdes_load)
600 			dispose_one_firmware(&fw_fabric);
601 		if (fw_sbus_load)
602 			dispose_one_firmware(&fw_sbus);
603 		if (fw_pcie_serdes_load)
604 			dispose_one_firmware(&fw_pcie);
605 		fw_8051_name = ALT_FW_8051_NAME_ASIC;
606 		fw_fabric_serdes_name = ALT_FW_FABRIC_NAME;
607 		fw_sbus_name = ALT_FW_SBUS_NAME;
608 		fw_pcie_serdes_name = ALT_FW_PCIE_NAME;
609 
610 		/*
611 		 * Add a delay before obtaining and loading debug firmware.
612 		 * Authorization will fail if the delay between firmware
613 		 * authorization events is shorter than 50us. Add 100us to
614 		 * make a delay time safe.
615 		 */
616 		usleep_range(100, 120);
617 	}
618 
619 	if (fw_sbus_load) {
620 		err = obtain_one_firmware(dd, fw_sbus_name, &fw_sbus);
621 		if (err)
622 			goto done;
623 	}
624 
625 	if (fw_pcie_serdes_load) {
626 		err = obtain_one_firmware(dd, fw_pcie_serdes_name, &fw_pcie);
627 		if (err)
628 			goto done;
629 	}
630 
631 	if (fw_fabric_serdes_load) {
632 		err = obtain_one_firmware(dd, fw_fabric_serdes_name,
633 					  &fw_fabric);
634 		if (err)
635 			goto done;
636 	}
637 
638 	if (fw_8051_load) {
639 		err = obtain_one_firmware(dd, fw_8051_name, &fw_8051);
640 		if (err)
641 			goto done;
642 	}
643 
644 done:
645 	if (err) {
646 		/* oops, had problems obtaining a firmware */
647 		if (fw_state == FW_EMPTY && dd->icode == ICODE_RTL_SILICON) {
648 			/* retry with alternate (RTL only) */
649 			fw_state = FW_TRY;
650 			goto retry;
651 		}
652 		dd_dev_err(dd, "unable to obtain working firmware\n");
653 		fw_state = FW_ERR;
654 		fw_err = -ENOENT;
655 	} else {
656 		/* success */
657 		if (fw_state == FW_EMPTY &&
658 		    dd->icode != ICODE_FUNCTIONAL_SIMULATOR)
659 			fw_state = FW_TRY;	/* may retry later */
660 		else
661 			fw_state = FW_FINAL;	/* cannot try again */
662 	}
663 }
664 
665 /*
666  * Called by all HFIs when loading their firmware - i.e. device probe time.
667  * The first one will do the actual firmware load.  Use a mutex to resolve
668  * any possible race condition.
669  *
670  * The call to this routine cannot be moved to driver load because the kernel
671  * call request_firmware() requires a device which is only available after
672  * the first device probe.
673  */
674 static int obtain_firmware(struct hfi1_devdata *dd)
675 {
676 	unsigned long timeout;
677 
678 	mutex_lock(&fw_mutex);
679 
680 	/* 40s delay due to long delay on missing firmware on some systems */
681 	timeout = jiffies + msecs_to_jiffies(40000);
682 	while (fw_state == FW_TRY) {
683 		/*
684 		 * Another device is trying the firmware.  Wait until it
685 		 * decides what works (or not).
686 		 */
687 		if (time_after(jiffies, timeout)) {
688 			/* waited too long */
689 			dd_dev_err(dd, "Timeout waiting for firmware try");
690 			fw_state = FW_ERR;
691 			fw_err = -ETIMEDOUT;
692 			break;
693 		}
694 		mutex_unlock(&fw_mutex);
695 		msleep(20);	/* arbitrary delay */
696 		mutex_lock(&fw_mutex);
697 	}
698 	/* not in FW_TRY state */
699 
700 	/* set fw_state to FW_TRY, FW_FINAL, or FW_ERR, and fw_err */
701 	if (fw_state == FW_EMPTY)
702 		__obtain_firmware(dd);
703 
704 	mutex_unlock(&fw_mutex);
705 	return fw_err;
706 }
707 
708 /*
709  * Called when the driver unloads.  The timing is asymmetric with its
710  * counterpart, obtain_firmware().  If called at device remove time,
711  * then it is conceivable that another device could probe while the
712  * firmware is being disposed.  The mutexes can be moved to do that
713  * safely, but then the firmware would be requested from the OS multiple
714  * times.
715  *
716  * No mutex is needed as the driver is unloading and there cannot be any
717  * other callers.
718  */
719 void dispose_firmware(void)
720 {
721 	dispose_one_firmware(&fw_8051);
722 	dispose_one_firmware(&fw_fabric);
723 	dispose_one_firmware(&fw_pcie);
724 	dispose_one_firmware(&fw_sbus);
725 
726 	/* retain the error state, otherwise revert to empty */
727 	if (fw_state != FW_ERR)
728 		fw_state = FW_EMPTY;
729 }
730 
731 /*
732  * Called with the result of a firmware download.
733  *
734  * Return 1 to retry loading the firmware, 0 to stop.
735  */
736 static int retry_firmware(struct hfi1_devdata *dd, int load_result)
737 {
738 	int retry;
739 
740 	mutex_lock(&fw_mutex);
741 
742 	if (load_result == 0) {
743 		/*
744 		 * The load succeeded, so expect all others to do the same.
745 		 * Do not retry again.
746 		 */
747 		if (fw_state == FW_TRY)
748 			fw_state = FW_FINAL;
749 		retry = 0;	/* do NOT retry */
750 	} else if (fw_state == FW_TRY) {
751 		/* load failed, obtain alternate firmware */
752 		__obtain_firmware(dd);
753 		retry = (fw_state == FW_FINAL);
754 	} else {
755 		/* else in FW_FINAL or FW_ERR, no retry in either case */
756 		retry = 0;
757 	}
758 
759 	mutex_unlock(&fw_mutex);
760 	return retry;
761 }
762 
763 /*
764  * Write a block of data to a given array CSR.  All calls will be in
765  * multiples of 8 bytes.
766  */
767 static void write_rsa_data(struct hfi1_devdata *dd, int what,
768 			   const u8 *data, int nbytes)
769 {
770 	int qw_size = nbytes / 8;
771 	int i;
772 
773 	if (((unsigned long)data & 0x7) == 0) {
774 		/* aligned */
775 		u64 *ptr = (u64 *)data;
776 
777 		for (i = 0; i < qw_size; i++, ptr++)
778 			write_csr(dd, what + (8 * i), *ptr);
779 	} else {
780 		/* not aligned */
781 		for (i = 0; i < qw_size; i++, data += 8) {
782 			u64 value;
783 
784 			memcpy(&value, data, 8);
785 			write_csr(dd, what + (8 * i), value);
786 		}
787 	}
788 }
789 
790 /*
791  * Write a block of data to a given CSR as a stream of writes.  All calls will
792  * be in multiples of 8 bytes.
793  */
794 static void write_streamed_rsa_data(struct hfi1_devdata *dd, int what,
795 				    const u8 *data, int nbytes)
796 {
797 	u64 *ptr = (u64 *)data;
798 	int qw_size = nbytes / 8;
799 
800 	for (; qw_size > 0; qw_size--, ptr++)
801 		write_csr(dd, what, *ptr);
802 }
803 
804 /*
805  * Download the signature and start the RSA mechanism.  Wait for
806  * RSA_ENGINE_TIMEOUT before giving up.
807  */
808 static int run_rsa(struct hfi1_devdata *dd, const char *who,
809 		   const u8 *signature)
810 {
811 	unsigned long timeout;
812 	u64 reg;
813 	u32 status;
814 	int ret = 0;
815 
816 	/* write the signature */
817 	write_rsa_data(dd, MISC_CFG_RSA_SIGNATURE, signature, KEY_SIZE);
818 
819 	/* initialize RSA */
820 	write_csr(dd, MISC_CFG_RSA_CMD, RSA_CMD_INIT);
821 
822 	/*
823 	 * Make sure the engine is idle and insert a delay between the two
824 	 * writes to MISC_CFG_RSA_CMD.
825 	 */
826 	status = (read_csr(dd, MISC_CFG_FW_CTRL)
827 			   & MISC_CFG_FW_CTRL_RSA_STATUS_SMASK)
828 			     >> MISC_CFG_FW_CTRL_RSA_STATUS_SHIFT;
829 	if (status != RSA_STATUS_IDLE) {
830 		dd_dev_err(dd, "%s security engine not idle - giving up\n",
831 			   who);
832 		return -EBUSY;
833 	}
834 
835 	/* start RSA */
836 	write_csr(dd, MISC_CFG_RSA_CMD, RSA_CMD_START);
837 
838 	/*
839 	 * Look for the result.
840 	 *
841 	 * The RSA engine is hooked up to two MISC errors.  The driver
842 	 * masks these errors as they do not respond to the standard
843 	 * error "clear down" mechanism.  Look for these errors here and
844 	 * clear them when possible.  This routine will exit with the
845 	 * errors of the current run still set.
846 	 *
847 	 * MISC_FW_AUTH_FAILED_ERR
848 	 *	Firmware authorization failed.  This can be cleared by
849 	 *	re-initializing the RSA engine, then clearing the status bit.
850 	 *	Do not re-init the RSA angine immediately after a successful
851 	 *	run - this will reset the current authorization.
852 	 *
853 	 * MISC_KEY_MISMATCH_ERR
854 	 *	Key does not match.  The only way to clear this is to load
855 	 *	a matching key then clear the status bit.  If this error
856 	 *	is raised, it will persist outside of this routine until a
857 	 *	matching key is loaded.
858 	 */
859 	timeout = msecs_to_jiffies(RSA_ENGINE_TIMEOUT) + jiffies;
860 	while (1) {
861 		status = (read_csr(dd, MISC_CFG_FW_CTRL)
862 			   & MISC_CFG_FW_CTRL_RSA_STATUS_SMASK)
863 			     >> MISC_CFG_FW_CTRL_RSA_STATUS_SHIFT;
864 
865 		if (status == RSA_STATUS_IDLE) {
866 			/* should not happen */
867 			dd_dev_err(dd, "%s firmware security bad idle state\n",
868 				   who);
869 			ret = -EINVAL;
870 			break;
871 		} else if (status == RSA_STATUS_DONE) {
872 			/* finished successfully */
873 			break;
874 		} else if (status == RSA_STATUS_FAILED) {
875 			/* finished unsuccessfully */
876 			ret = -EINVAL;
877 			break;
878 		}
879 		/* else still active */
880 
881 		if (time_after(jiffies, timeout)) {
882 			/*
883 			 * Timed out while active.  We can't reset the engine
884 			 * if it is stuck active, but run through the
885 			 * error code to see what error bits are set.
886 			 */
887 			dd_dev_err(dd, "%s firmware security time out\n", who);
888 			ret = -ETIMEDOUT;
889 			break;
890 		}
891 
892 		msleep(20);
893 	}
894 
895 	/*
896 	 * Arrive here on success or failure.  Clear all RSA engine
897 	 * errors.  All current errors will stick - the RSA logic is keeping
898 	 * error high.  All previous errors will clear - the RSA logic
899 	 * is not keeping the error high.
900 	 */
901 	write_csr(dd, MISC_ERR_CLEAR,
902 		  MISC_ERR_STATUS_MISC_FW_AUTH_FAILED_ERR_SMASK |
903 		  MISC_ERR_STATUS_MISC_KEY_MISMATCH_ERR_SMASK);
904 	/*
905 	 * All that is left are the current errors.  Print warnings on
906 	 * authorization failure details, if any.  Firmware authorization
907 	 * can be retried, so these are only warnings.
908 	 */
909 	reg = read_csr(dd, MISC_ERR_STATUS);
910 	if (ret) {
911 		if (reg & MISC_ERR_STATUS_MISC_FW_AUTH_FAILED_ERR_SMASK)
912 			dd_dev_warn(dd, "%s firmware authorization failed\n",
913 				    who);
914 		if (reg & MISC_ERR_STATUS_MISC_KEY_MISMATCH_ERR_SMASK)
915 			dd_dev_warn(dd, "%s firmware key mismatch\n", who);
916 	}
917 
918 	return ret;
919 }
920 
921 static void load_security_variables(struct hfi1_devdata *dd,
922 				    struct firmware_details *fdet)
923 {
924 	/* Security variables a.  Write the modulus */
925 	write_rsa_data(dd, MISC_CFG_RSA_MODULUS, fdet->modulus, KEY_SIZE);
926 	/* Security variables b.  Write the r2 */
927 	write_rsa_data(dd, MISC_CFG_RSA_R2, fdet->r2, KEY_SIZE);
928 	/* Security variables c.  Write the mu */
929 	write_rsa_data(dd, MISC_CFG_RSA_MU, fdet->mu, MU_SIZE);
930 	/* Security variables d.  Write the header */
931 	write_streamed_rsa_data(dd, MISC_CFG_SHA_PRELOAD,
932 				(u8 *)fdet->css_header,
933 				sizeof(struct css_header));
934 }
935 
936 /* return the 8051 firmware state */
937 static inline u32 get_firmware_state(struct hfi1_devdata *dd)
938 {
939 	u64 reg = read_csr(dd, DC_DC8051_STS_CUR_STATE);
940 
941 	return (reg >> DC_DC8051_STS_CUR_STATE_FIRMWARE_SHIFT)
942 				& DC_DC8051_STS_CUR_STATE_FIRMWARE_MASK;
943 }
944 
945 /*
946  * Wait until the firmware is up and ready to take host requests.
947  * Return 0 on success, -ETIMEDOUT on timeout.
948  */
949 int wait_fm_ready(struct hfi1_devdata *dd, u32 mstimeout)
950 {
951 	unsigned long timeout;
952 
953 	/* in the simulator, the fake 8051 is always ready */
954 	if (dd->icode == ICODE_FUNCTIONAL_SIMULATOR)
955 		return 0;
956 
957 	timeout = msecs_to_jiffies(mstimeout) + jiffies;
958 	while (1) {
959 		if (get_firmware_state(dd) == 0xa0)	/* ready */
960 			return 0;
961 		if (time_after(jiffies, timeout))	/* timed out */
962 			return -ETIMEDOUT;
963 		usleep_range(1950, 2050); /* sleep 2ms-ish */
964 	}
965 }
966 
967 /*
968  * Load the 8051 firmware.
969  */
970 static int load_8051_firmware(struct hfi1_devdata *dd,
971 			      struct firmware_details *fdet)
972 {
973 	u64 reg;
974 	int ret;
975 	u8 ver_major;
976 	u8 ver_minor;
977 	u8 ver_patch;
978 
979 	/*
980 	 * DC Reset sequence
981 	 * Load DC 8051 firmware
982 	 */
983 	/*
984 	 * DC reset step 1: Reset DC8051
985 	 */
986 	reg = DC_DC8051_CFG_RST_M8051W_SMASK
987 		| DC_DC8051_CFG_RST_CRAM_SMASK
988 		| DC_DC8051_CFG_RST_DRAM_SMASK
989 		| DC_DC8051_CFG_RST_IRAM_SMASK
990 		| DC_DC8051_CFG_RST_SFR_SMASK;
991 	write_csr(dd, DC_DC8051_CFG_RST, reg);
992 
993 	/*
994 	 * DC reset step 2 (optional): Load 8051 data memory with link
995 	 * configuration
996 	 */
997 
998 	/*
999 	 * DC reset step 3: Load DC8051 firmware
1000 	 */
1001 	/* release all but the core reset */
1002 	reg = DC_DC8051_CFG_RST_M8051W_SMASK;
1003 	write_csr(dd, DC_DC8051_CFG_RST, reg);
1004 
1005 	/* Firmware load step 1 */
1006 	load_security_variables(dd, fdet);
1007 
1008 	/*
1009 	 * Firmware load step 2.  Clear MISC_CFG_FW_CTRL.FW_8051_LOADED
1010 	 */
1011 	write_csr(dd, MISC_CFG_FW_CTRL, 0);
1012 
1013 	/* Firmware load steps 3-5 */
1014 	ret = write_8051(dd, 1/*code*/, 0, fdet->firmware_ptr,
1015 			 fdet->firmware_len);
1016 	if (ret)
1017 		return ret;
1018 
1019 	/*
1020 	 * DC reset step 4. Host starts the DC8051 firmware
1021 	 */
1022 	/*
1023 	 * Firmware load step 6.  Set MISC_CFG_FW_CTRL.FW_8051_LOADED
1024 	 */
1025 	write_csr(dd, MISC_CFG_FW_CTRL, MISC_CFG_FW_CTRL_FW_8051_LOADED_SMASK);
1026 
1027 	/* Firmware load steps 7-10 */
1028 	ret = run_rsa(dd, "8051", fdet->signature);
1029 	if (ret)
1030 		return ret;
1031 
1032 	/* clear all reset bits, releasing the 8051 */
1033 	write_csr(dd, DC_DC8051_CFG_RST, 0ull);
1034 
1035 	/*
1036 	 * DC reset step 5. Wait for firmware to be ready to accept host
1037 	 * requests.
1038 	 */
1039 	ret = wait_fm_ready(dd, TIMEOUT_8051_START);
1040 	if (ret) { /* timed out */
1041 		dd_dev_err(dd, "8051 start timeout, current state 0x%x\n",
1042 			   get_firmware_state(dd));
1043 		return -ETIMEDOUT;
1044 	}
1045 
1046 	read_misc_status(dd, &ver_major, &ver_minor, &ver_patch);
1047 	dd_dev_info(dd, "8051 firmware version %d.%d.%d\n",
1048 		    (int)ver_major, (int)ver_minor, (int)ver_patch);
1049 	dd->dc8051_ver = dc8051_ver(ver_major, ver_minor, ver_patch);
1050 	ret = write_host_interface_version(dd, HOST_INTERFACE_VERSION);
1051 	if (ret != HCMD_SUCCESS) {
1052 		dd_dev_err(dd,
1053 			   "Failed to set host interface version, return 0x%x\n",
1054 			   ret);
1055 		return -EIO;
1056 	}
1057 
1058 	return 0;
1059 }
1060 
1061 /*
1062  * Write the SBus request register
1063  *
1064  * No need for masking - the arguments are sized exactly.
1065  */
1066 void sbus_request(struct hfi1_devdata *dd,
1067 		  u8 receiver_addr, u8 data_addr, u8 command, u32 data_in)
1068 {
1069 	write_csr(dd, ASIC_CFG_SBUS_REQUEST,
1070 		  ((u64)data_in << ASIC_CFG_SBUS_REQUEST_DATA_IN_SHIFT) |
1071 		  ((u64)command << ASIC_CFG_SBUS_REQUEST_COMMAND_SHIFT) |
1072 		  ((u64)data_addr << ASIC_CFG_SBUS_REQUEST_DATA_ADDR_SHIFT) |
1073 		  ((u64)receiver_addr <<
1074 		   ASIC_CFG_SBUS_REQUEST_RECEIVER_ADDR_SHIFT));
1075 }
1076 
1077 /*
1078  * Read a value from the SBus.
1079  *
1080  * Requires the caller to be in fast mode
1081  */
1082 static u32 sbus_read(struct hfi1_devdata *dd, u8 receiver_addr, u8 data_addr,
1083 		     u32 data_in)
1084 {
1085 	u64 reg;
1086 	int retries;
1087 	int success = 0;
1088 	u32 result = 0;
1089 	u32 result_code = 0;
1090 
1091 	sbus_request(dd, receiver_addr, data_addr, READ_SBUS_RECEIVER, data_in);
1092 
1093 	for (retries = 0; retries < 100; retries++) {
1094 		usleep_range(1000, 1200); /* arbitrary */
1095 		reg = read_csr(dd, ASIC_STS_SBUS_RESULT);
1096 		result_code = (reg >> ASIC_STS_SBUS_RESULT_RESULT_CODE_SHIFT)
1097 				& ASIC_STS_SBUS_RESULT_RESULT_CODE_MASK;
1098 		if (result_code != SBUS_READ_COMPLETE)
1099 			continue;
1100 
1101 		success = 1;
1102 		result = (reg >> ASIC_STS_SBUS_RESULT_DATA_OUT_SHIFT)
1103 			   & ASIC_STS_SBUS_RESULT_DATA_OUT_MASK;
1104 		break;
1105 	}
1106 
1107 	if (!success) {
1108 		dd_dev_err(dd, "%s: read failed, result code 0x%x\n", __func__,
1109 			   result_code);
1110 	}
1111 
1112 	return result;
1113 }
1114 
1115 /*
1116  * Turn off the SBus and fabric serdes spicos.
1117  *
1118  * + Must be called with Sbus fast mode turned on.
1119  * + Must be called after fabric serdes broadcast is set up.
1120  * + Must be called before the 8051 is loaded - assumes 8051 is not loaded
1121  *   when using MISC_CFG_FW_CTRL.
1122  */
1123 static void turn_off_spicos(struct hfi1_devdata *dd, int flags)
1124 {
1125 	/* only needed on A0 */
1126 	if (!is_ax(dd))
1127 		return;
1128 
1129 	dd_dev_info(dd, "Turning off spicos:%s%s\n",
1130 		    flags & SPICO_SBUS ? " SBus" : "",
1131 		    flags & SPICO_FABRIC ? " fabric" : "");
1132 
1133 	write_csr(dd, MISC_CFG_FW_CTRL, ENABLE_SPICO_SMASK);
1134 	/* disable SBus spico */
1135 	if (flags & SPICO_SBUS)
1136 		sbus_request(dd, SBUS_MASTER_BROADCAST, 0x01,
1137 			     WRITE_SBUS_RECEIVER, 0x00000040);
1138 
1139 	/* disable the fabric serdes spicos */
1140 	if (flags & SPICO_FABRIC)
1141 		sbus_request(dd, fabric_serdes_broadcast[dd->hfi1_id],
1142 			     0x07, WRITE_SBUS_RECEIVER, 0x00000000);
1143 	write_csr(dd, MISC_CFG_FW_CTRL, 0);
1144 }
1145 
1146 /*
1147  * Reset all of the fabric serdes for this HFI in preparation to take the
1148  * link to Polling.
1149  *
1150  * To do a reset, we need to write to to the serdes registers.  Unfortunately,
1151  * the fabric serdes download to the other HFI on the ASIC will have turned
1152  * off the firmware validation on this HFI.  This means we can't write to the
1153  * registers to reset the serdes.  Work around this by performing a complete
1154  * re-download and validation of the fabric serdes firmware.  This, as a
1155  * by-product, will reset the serdes.  NOTE: the re-download requires that
1156  * the 8051 be in the Offline state.  I.e. not actively trying to use the
1157  * serdes.  This routine is called at the point where the link is Offline and
1158  * is getting ready to go to Polling.
1159  */
1160 void fabric_serdes_reset(struct hfi1_devdata *dd)
1161 {
1162 	int ret;
1163 
1164 	if (!fw_fabric_serdes_load)
1165 		return;
1166 
1167 	ret = acquire_chip_resource(dd, CR_SBUS, SBUS_TIMEOUT);
1168 	if (ret) {
1169 		dd_dev_err(dd,
1170 			   "Cannot acquire SBus resource to reset fabric SerDes - perhaps you should reboot\n");
1171 		return;
1172 	}
1173 	set_sbus_fast_mode(dd);
1174 
1175 	if (is_ax(dd)) {
1176 		/* A0 serdes do not work with a re-download */
1177 		u8 ra = fabric_serdes_broadcast[dd->hfi1_id];
1178 
1179 		/* place SerDes in reset and disable SPICO */
1180 		sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000011);
1181 		/* wait 100 refclk cycles @ 156.25MHz => 640ns */
1182 		udelay(1);
1183 		/* remove SerDes reset */
1184 		sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000010);
1185 		/* turn SPICO enable on */
1186 		sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000002);
1187 	} else {
1188 		turn_off_spicos(dd, SPICO_FABRIC);
1189 		/*
1190 		 * No need for firmware retry - what to download has already
1191 		 * been decided.
1192 		 * No need to pay attention to the load return - the only
1193 		 * failure is a validation failure, which has already been
1194 		 * checked by the initial download.
1195 		 */
1196 		(void)load_fabric_serdes_firmware(dd, &fw_fabric);
1197 	}
1198 
1199 	clear_sbus_fast_mode(dd);
1200 	release_chip_resource(dd, CR_SBUS);
1201 }
1202 
1203 /* Access to the SBus in this routine should probably be serialized */
1204 int sbus_request_slow(struct hfi1_devdata *dd,
1205 		      u8 receiver_addr, u8 data_addr, u8 command, u32 data_in)
1206 {
1207 	u64 reg, count = 0;
1208 
1209 	/* make sure fast mode is clear */
1210 	clear_sbus_fast_mode(dd);
1211 
1212 	sbus_request(dd, receiver_addr, data_addr, command, data_in);
1213 	write_csr(dd, ASIC_CFG_SBUS_EXECUTE,
1214 		  ASIC_CFG_SBUS_EXECUTE_EXECUTE_SMASK);
1215 	/* Wait for both DONE and RCV_DATA_VALID to go high */
1216 	reg = read_csr(dd, ASIC_STS_SBUS_RESULT);
1217 	while (!((reg & ASIC_STS_SBUS_RESULT_DONE_SMASK) &&
1218 		 (reg & ASIC_STS_SBUS_RESULT_RCV_DATA_VALID_SMASK))) {
1219 		if (count++ >= SBUS_MAX_POLL_COUNT) {
1220 			u64 counts = read_csr(dd, ASIC_STS_SBUS_COUNTERS);
1221 			/*
1222 			 * If the loop has timed out, we are OK if DONE bit
1223 			 * is set and RCV_DATA_VALID and EXECUTE counters
1224 			 * are the same. If not, we cannot proceed.
1225 			 */
1226 			if ((reg & ASIC_STS_SBUS_RESULT_DONE_SMASK) &&
1227 			    (SBUS_COUNTER(counts, RCV_DATA_VALID) ==
1228 			     SBUS_COUNTER(counts, EXECUTE)))
1229 				break;
1230 			return -ETIMEDOUT;
1231 		}
1232 		udelay(1);
1233 		reg = read_csr(dd, ASIC_STS_SBUS_RESULT);
1234 	}
1235 	count = 0;
1236 	write_csr(dd, ASIC_CFG_SBUS_EXECUTE, 0);
1237 	/* Wait for DONE to clear after EXECUTE is cleared */
1238 	reg = read_csr(dd, ASIC_STS_SBUS_RESULT);
1239 	while (reg & ASIC_STS_SBUS_RESULT_DONE_SMASK) {
1240 		if (count++ >= SBUS_MAX_POLL_COUNT)
1241 			return -ETIME;
1242 		udelay(1);
1243 		reg = read_csr(dd, ASIC_STS_SBUS_RESULT);
1244 	}
1245 	return 0;
1246 }
1247 
1248 static int load_fabric_serdes_firmware(struct hfi1_devdata *dd,
1249 				       struct firmware_details *fdet)
1250 {
1251 	int i, err;
1252 	const u8 ra = fabric_serdes_broadcast[dd->hfi1_id]; /* receiver addr */
1253 
1254 	dd_dev_info(dd, "Downloading fabric firmware\n");
1255 
1256 	/* step 1: load security variables */
1257 	load_security_variables(dd, fdet);
1258 	/* step 2: place SerDes in reset and disable SPICO */
1259 	sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000011);
1260 	/* wait 100 refclk cycles @ 156.25MHz => 640ns */
1261 	udelay(1);
1262 	/* step 3:  remove SerDes reset */
1263 	sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000010);
1264 	/* step 4: assert IMEM override */
1265 	sbus_request(dd, ra, 0x00, WRITE_SBUS_RECEIVER, 0x40000000);
1266 	/* step 5: download SerDes machine code */
1267 	for (i = 0; i < fdet->firmware_len; i += 4) {
1268 		sbus_request(dd, ra, 0x0a, WRITE_SBUS_RECEIVER,
1269 			     *(u32 *)&fdet->firmware_ptr[i]);
1270 	}
1271 	/* step 6: IMEM override off */
1272 	sbus_request(dd, ra, 0x00, WRITE_SBUS_RECEIVER, 0x00000000);
1273 	/* step 7: turn ECC on */
1274 	sbus_request(dd, ra, 0x0b, WRITE_SBUS_RECEIVER, 0x000c0000);
1275 
1276 	/* steps 8-11: run the RSA engine */
1277 	err = run_rsa(dd, "fabric serdes", fdet->signature);
1278 	if (err)
1279 		return err;
1280 
1281 	/* step 12: turn SPICO enable on */
1282 	sbus_request(dd, ra, 0x07, WRITE_SBUS_RECEIVER, 0x00000002);
1283 	/* step 13: enable core hardware interrupts */
1284 	sbus_request(dd, ra, 0x08, WRITE_SBUS_RECEIVER, 0x00000000);
1285 
1286 	return 0;
1287 }
1288 
1289 static int load_sbus_firmware(struct hfi1_devdata *dd,
1290 			      struct firmware_details *fdet)
1291 {
1292 	int i, err;
1293 	const u8 ra = SBUS_MASTER_BROADCAST; /* receiver address */
1294 
1295 	dd_dev_info(dd, "Downloading SBus firmware\n");
1296 
1297 	/* step 1: load security variables */
1298 	load_security_variables(dd, fdet);
1299 	/* step 2: place SPICO into reset and enable off */
1300 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x000000c0);
1301 	/* step 3: remove reset, enable off, IMEM_CNTRL_EN on */
1302 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x00000240);
1303 	/* step 4: set starting IMEM address for burst download */
1304 	sbus_request(dd, ra, 0x03, WRITE_SBUS_RECEIVER, 0x80000000);
1305 	/* step 5: download the SBus Master machine code */
1306 	for (i = 0; i < fdet->firmware_len; i += 4) {
1307 		sbus_request(dd, ra, 0x14, WRITE_SBUS_RECEIVER,
1308 			     *(u32 *)&fdet->firmware_ptr[i]);
1309 	}
1310 	/* step 6: set IMEM_CNTL_EN off */
1311 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x00000040);
1312 	/* step 7: turn ECC on */
1313 	sbus_request(dd, ra, 0x16, WRITE_SBUS_RECEIVER, 0x000c0000);
1314 
1315 	/* steps 8-11: run the RSA engine */
1316 	err = run_rsa(dd, "SBus", fdet->signature);
1317 	if (err)
1318 		return err;
1319 
1320 	/* step 12: set SPICO_ENABLE on */
1321 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x00000140);
1322 
1323 	return 0;
1324 }
1325 
1326 static int load_pcie_serdes_firmware(struct hfi1_devdata *dd,
1327 				     struct firmware_details *fdet)
1328 {
1329 	int i;
1330 	const u8 ra = SBUS_MASTER_BROADCAST; /* receiver address */
1331 
1332 	dd_dev_info(dd, "Downloading PCIe firmware\n");
1333 
1334 	/* step 1: load security variables */
1335 	load_security_variables(dd, fdet);
1336 	/* step 2: assert single step (halts the SBus Master spico) */
1337 	sbus_request(dd, ra, 0x05, WRITE_SBUS_RECEIVER, 0x00000001);
1338 	/* step 3: enable XDMEM access */
1339 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x00000d40);
1340 	/* step 4: load firmware into SBus Master XDMEM */
1341 	/*
1342 	 * NOTE: the dmem address, write_en, and wdata are all pre-packed,
1343 	 * we only need to pick up the bytes and write them
1344 	 */
1345 	for (i = 0; i < fdet->firmware_len; i += 4) {
1346 		sbus_request(dd, ra, 0x04, WRITE_SBUS_RECEIVER,
1347 			     *(u32 *)&fdet->firmware_ptr[i]);
1348 	}
1349 	/* step 5: disable XDMEM access */
1350 	sbus_request(dd, ra, 0x01, WRITE_SBUS_RECEIVER, 0x00000140);
1351 	/* step 6: allow SBus Spico to run */
1352 	sbus_request(dd, ra, 0x05, WRITE_SBUS_RECEIVER, 0x00000000);
1353 
1354 	/*
1355 	 * steps 7-11: run RSA, if it succeeds, firmware is available to
1356 	 * be swapped
1357 	 */
1358 	return run_rsa(dd, "PCIe serdes", fdet->signature);
1359 }
1360 
1361 /*
1362  * Set the given broadcast values on the given list of devices.
1363  */
1364 static void set_serdes_broadcast(struct hfi1_devdata *dd, u8 bg1, u8 bg2,
1365 				 const u8 *addrs, int count)
1366 {
1367 	while (--count >= 0) {
1368 		/*
1369 		 * Set BROADCAST_GROUP_1 and BROADCAST_GROUP_2, leave
1370 		 * defaults for everything else.  Do not read-modify-write,
1371 		 * per instruction from the manufacturer.
1372 		 *
1373 		 * Register 0xfd:
1374 		 *	bits    what
1375 		 *	-----	---------------------------------
1376 		 *	  0	IGNORE_BROADCAST  (default 0)
1377 		 *	11:4	BROADCAST_GROUP_1 (default 0xff)
1378 		 *	23:16	BROADCAST_GROUP_2 (default 0xff)
1379 		 */
1380 		sbus_request(dd, addrs[count], 0xfd, WRITE_SBUS_RECEIVER,
1381 			     (u32)bg1 << 4 | (u32)bg2 << 16);
1382 	}
1383 }
1384 
1385 int acquire_hw_mutex(struct hfi1_devdata *dd)
1386 {
1387 	unsigned long timeout;
1388 	int try = 0;
1389 	u8 mask = 1 << dd->hfi1_id;
1390 	u8 user;
1391 
1392 retry:
1393 	timeout = msecs_to_jiffies(HM_TIMEOUT) + jiffies;
1394 	while (1) {
1395 		write_csr(dd, ASIC_CFG_MUTEX, mask);
1396 		user = (u8)read_csr(dd, ASIC_CFG_MUTEX);
1397 		if (user == mask)
1398 			return 0; /* success */
1399 		if (time_after(jiffies, timeout))
1400 			break; /* timed out */
1401 		msleep(20);
1402 	}
1403 
1404 	/* timed out */
1405 	dd_dev_err(dd,
1406 		   "Unable to acquire hardware mutex, mutex mask %u, my mask %u (%s)\n",
1407 		   (u32)user, (u32)mask, (try == 0) ? "retrying" : "giving up");
1408 
1409 	if (try == 0) {
1410 		/* break mutex and retry */
1411 		write_csr(dd, ASIC_CFG_MUTEX, 0);
1412 		try++;
1413 		goto retry;
1414 	}
1415 
1416 	return -EBUSY;
1417 }
1418 
1419 void release_hw_mutex(struct hfi1_devdata *dd)
1420 {
1421 	write_csr(dd, ASIC_CFG_MUTEX, 0);
1422 }
1423 
1424 /* return the given resource bit(s) as a mask for the given HFI */
1425 static inline u64 resource_mask(u32 hfi1_id, u32 resource)
1426 {
1427 	return ((u64)resource) << (hfi1_id ? CR_DYN_SHIFT : 0);
1428 }
1429 
1430 static void fail_mutex_acquire_message(struct hfi1_devdata *dd,
1431 				       const char *func)
1432 {
1433 	dd_dev_err(dd,
1434 		   "%s: hardware mutex stuck - suggest rebooting the machine\n",
1435 		   func);
1436 }
1437 
1438 /*
1439  * Acquire access to a chip resource.
1440  *
1441  * Return 0 on success, -EBUSY if resource busy, -EIO if mutex acquire failed.
1442  */
1443 static int __acquire_chip_resource(struct hfi1_devdata *dd, u32 resource)
1444 {
1445 	u64 scratch0, all_bits, my_bit;
1446 	int ret;
1447 
1448 	if (resource & CR_DYN_MASK) {
1449 		/* a dynamic resource is in use if either HFI has set the bit */
1450 		if (dd->pcidev->device == PCI_DEVICE_ID_INTEL0 &&
1451 		    (resource & (CR_I2C1 | CR_I2C2))) {
1452 			/* discrete devices must serialize across both chains */
1453 			all_bits = resource_mask(0, CR_I2C1 | CR_I2C2) |
1454 					resource_mask(1, CR_I2C1 | CR_I2C2);
1455 		} else {
1456 			all_bits = resource_mask(0, resource) |
1457 						resource_mask(1, resource);
1458 		}
1459 		my_bit = resource_mask(dd->hfi1_id, resource);
1460 	} else {
1461 		/* non-dynamic resources are not split between HFIs */
1462 		all_bits = resource;
1463 		my_bit = resource;
1464 	}
1465 
1466 	/* lock against other callers within the driver wanting a resource */
1467 	mutex_lock(&dd->asic_data->asic_resource_mutex);
1468 
1469 	ret = acquire_hw_mutex(dd);
1470 	if (ret) {
1471 		fail_mutex_acquire_message(dd, __func__);
1472 		ret = -EIO;
1473 		goto done;
1474 	}
1475 
1476 	scratch0 = read_csr(dd, ASIC_CFG_SCRATCH);
1477 	if (scratch0 & all_bits) {
1478 		ret = -EBUSY;
1479 	} else {
1480 		write_csr(dd, ASIC_CFG_SCRATCH, scratch0 | my_bit);
1481 		/* force write to be visible to other HFI on another OS */
1482 		(void)read_csr(dd, ASIC_CFG_SCRATCH);
1483 	}
1484 
1485 	release_hw_mutex(dd);
1486 
1487 done:
1488 	mutex_unlock(&dd->asic_data->asic_resource_mutex);
1489 	return ret;
1490 }
1491 
1492 /*
1493  * Acquire access to a chip resource, wait up to mswait milliseconds for
1494  * the resource to become available.
1495  *
1496  * Return 0 on success, -EBUSY if busy (even after wait), -EIO if mutex
1497  * acquire failed.
1498  */
1499 int acquire_chip_resource(struct hfi1_devdata *dd, u32 resource, u32 mswait)
1500 {
1501 	unsigned long timeout;
1502 	int ret;
1503 
1504 	timeout = jiffies + msecs_to_jiffies(mswait);
1505 	while (1) {
1506 		ret = __acquire_chip_resource(dd, resource);
1507 		if (ret != -EBUSY)
1508 			return ret;
1509 		/* resource is busy, check our timeout */
1510 		if (time_after_eq(jiffies, timeout))
1511 			return -EBUSY;
1512 		usleep_range(80, 120);	/* arbitrary delay */
1513 	}
1514 }
1515 
1516 /*
1517  * Release access to a chip resource
1518  */
1519 void release_chip_resource(struct hfi1_devdata *dd, u32 resource)
1520 {
1521 	u64 scratch0, bit;
1522 
1523 	/* only dynamic resources should ever be cleared */
1524 	if (!(resource & CR_DYN_MASK)) {
1525 		dd_dev_err(dd, "%s: invalid resource 0x%x\n", __func__,
1526 			   resource);
1527 		return;
1528 	}
1529 	bit = resource_mask(dd->hfi1_id, resource);
1530 
1531 	/* lock against other callers within the driver wanting a resource */
1532 	mutex_lock(&dd->asic_data->asic_resource_mutex);
1533 
1534 	if (acquire_hw_mutex(dd)) {
1535 		fail_mutex_acquire_message(dd, __func__);
1536 		goto done;
1537 	}
1538 
1539 	scratch0 = read_csr(dd, ASIC_CFG_SCRATCH);
1540 	if ((scratch0 & bit) != 0) {
1541 		scratch0 &= ~bit;
1542 		write_csr(dd, ASIC_CFG_SCRATCH, scratch0);
1543 		/* force write to be visible to other HFI on another OS */
1544 		(void)read_csr(dd, ASIC_CFG_SCRATCH);
1545 	} else {
1546 		dd_dev_warn(dd, "%s: id %d, resource 0x%x: bit not set\n",
1547 			    __func__, dd->hfi1_id, resource);
1548 	}
1549 
1550 	release_hw_mutex(dd);
1551 
1552 done:
1553 	mutex_unlock(&dd->asic_data->asic_resource_mutex);
1554 }
1555 
1556 /*
1557  * Return true if resource is set, false otherwise.  Print a warning
1558  * if not set and a function is supplied.
1559  */
1560 bool check_chip_resource(struct hfi1_devdata *dd, u32 resource,
1561 			 const char *func)
1562 {
1563 	u64 scratch0, bit;
1564 
1565 	if (resource & CR_DYN_MASK)
1566 		bit = resource_mask(dd->hfi1_id, resource);
1567 	else
1568 		bit = resource;
1569 
1570 	scratch0 = read_csr(dd, ASIC_CFG_SCRATCH);
1571 	if ((scratch0 & bit) == 0) {
1572 		if (func)
1573 			dd_dev_warn(dd,
1574 				    "%s: id %d, resource 0x%x, not acquired!\n",
1575 				    func, dd->hfi1_id, resource);
1576 		return false;
1577 	}
1578 	return true;
1579 }
1580 
1581 static void clear_chip_resources(struct hfi1_devdata *dd, const char *func)
1582 {
1583 	u64 scratch0;
1584 
1585 	/* lock against other callers within the driver wanting a resource */
1586 	mutex_lock(&dd->asic_data->asic_resource_mutex);
1587 
1588 	if (acquire_hw_mutex(dd)) {
1589 		fail_mutex_acquire_message(dd, func);
1590 		goto done;
1591 	}
1592 
1593 	/* clear all dynamic access bits for this HFI */
1594 	scratch0 = read_csr(dd, ASIC_CFG_SCRATCH);
1595 	scratch0 &= ~resource_mask(dd->hfi1_id, CR_DYN_MASK);
1596 	write_csr(dd, ASIC_CFG_SCRATCH, scratch0);
1597 	/* force write to be visible to other HFI on another OS */
1598 	(void)read_csr(dd, ASIC_CFG_SCRATCH);
1599 
1600 	release_hw_mutex(dd);
1601 
1602 done:
1603 	mutex_unlock(&dd->asic_data->asic_resource_mutex);
1604 }
1605 
1606 void init_chip_resources(struct hfi1_devdata *dd)
1607 {
1608 	/* clear any holds left by us */
1609 	clear_chip_resources(dd, __func__);
1610 }
1611 
1612 void finish_chip_resources(struct hfi1_devdata *dd)
1613 {
1614 	/* clear any holds left by us */
1615 	clear_chip_resources(dd, __func__);
1616 }
1617 
1618 void set_sbus_fast_mode(struct hfi1_devdata *dd)
1619 {
1620 	write_csr(dd, ASIC_CFG_SBUS_EXECUTE,
1621 		  ASIC_CFG_SBUS_EXECUTE_FAST_MODE_SMASK);
1622 }
1623 
1624 void clear_sbus_fast_mode(struct hfi1_devdata *dd)
1625 {
1626 	u64 reg, count = 0;
1627 
1628 	reg = read_csr(dd, ASIC_STS_SBUS_COUNTERS);
1629 	while (SBUS_COUNTER(reg, EXECUTE) !=
1630 	       SBUS_COUNTER(reg, RCV_DATA_VALID)) {
1631 		if (count++ >= SBUS_MAX_POLL_COUNT)
1632 			break;
1633 		udelay(1);
1634 		reg = read_csr(dd, ASIC_STS_SBUS_COUNTERS);
1635 	}
1636 	write_csr(dd, ASIC_CFG_SBUS_EXECUTE, 0);
1637 }
1638 
1639 int load_firmware(struct hfi1_devdata *dd)
1640 {
1641 	int ret;
1642 
1643 	if (fw_fabric_serdes_load) {
1644 		ret = acquire_chip_resource(dd, CR_SBUS, SBUS_TIMEOUT);
1645 		if (ret)
1646 			return ret;
1647 
1648 		set_sbus_fast_mode(dd);
1649 
1650 		set_serdes_broadcast(dd, all_fabric_serdes_broadcast,
1651 				     fabric_serdes_broadcast[dd->hfi1_id],
1652 				     fabric_serdes_addrs[dd->hfi1_id],
1653 				     NUM_FABRIC_SERDES);
1654 		turn_off_spicos(dd, SPICO_FABRIC);
1655 		do {
1656 			ret = load_fabric_serdes_firmware(dd, &fw_fabric);
1657 		} while (retry_firmware(dd, ret));
1658 
1659 		clear_sbus_fast_mode(dd);
1660 		release_chip_resource(dd, CR_SBUS);
1661 		if (ret)
1662 			return ret;
1663 	}
1664 
1665 	if (fw_8051_load) {
1666 		do {
1667 			ret = load_8051_firmware(dd, &fw_8051);
1668 		} while (retry_firmware(dd, ret));
1669 		if (ret)
1670 			return ret;
1671 	}
1672 
1673 	dump_fw_version(dd);
1674 	return 0;
1675 }
1676 
1677 int hfi1_firmware_init(struct hfi1_devdata *dd)
1678 {
1679 	/* only RTL can use these */
1680 	if (dd->icode != ICODE_RTL_SILICON) {
1681 		fw_fabric_serdes_load = 0;
1682 		fw_pcie_serdes_load = 0;
1683 		fw_sbus_load = 0;
1684 	}
1685 
1686 	/* no 8051 or QSFP on simulator */
1687 	if (dd->icode == ICODE_FUNCTIONAL_SIMULATOR)
1688 		fw_8051_load = 0;
1689 
1690 	if (!fw_8051_name) {
1691 		if (dd->icode == ICODE_RTL_SILICON)
1692 			fw_8051_name = DEFAULT_FW_8051_NAME_ASIC;
1693 		else
1694 			fw_8051_name = DEFAULT_FW_8051_NAME_FPGA;
1695 	}
1696 	if (!fw_fabric_serdes_name)
1697 		fw_fabric_serdes_name = DEFAULT_FW_FABRIC_NAME;
1698 	if (!fw_sbus_name)
1699 		fw_sbus_name = DEFAULT_FW_SBUS_NAME;
1700 	if (!fw_pcie_serdes_name)
1701 		fw_pcie_serdes_name = DEFAULT_FW_PCIE_NAME;
1702 
1703 	return obtain_firmware(dd);
1704 }
1705 
1706 /*
1707  * This function is a helper function for parse_platform_config(...) and
1708  * does not check for validity of the platform configuration cache
1709  * (because we know it is invalid as we are building up the cache).
1710  * As such, this should not be called from anywhere other than
1711  * parse_platform_config
1712  */
1713 static int check_meta_version(struct hfi1_devdata *dd, u32 *system_table)
1714 {
1715 	u32 meta_ver, meta_ver_meta, ver_start, ver_len, mask;
1716 	struct platform_config_cache *pcfgcache = &dd->pcfg_cache;
1717 
1718 	if (!system_table)
1719 		return -EINVAL;
1720 
1721 	meta_ver_meta =
1722 	*(pcfgcache->config_tables[PLATFORM_CONFIG_SYSTEM_TABLE].table_metadata
1723 	+ SYSTEM_TABLE_META_VERSION);
1724 
1725 	mask = ((1 << METADATA_TABLE_FIELD_START_LEN_BITS) - 1);
1726 	ver_start = meta_ver_meta & mask;
1727 
1728 	meta_ver_meta >>= METADATA_TABLE_FIELD_LEN_SHIFT;
1729 
1730 	mask = ((1 << METADATA_TABLE_FIELD_LEN_LEN_BITS) - 1);
1731 	ver_len = meta_ver_meta & mask;
1732 
1733 	ver_start /= 8;
1734 	meta_ver = *((u8 *)system_table + ver_start) & ((1 << ver_len) - 1);
1735 
1736 	if (meta_ver < 5) {
1737 		dd_dev_info(
1738 			dd, "%s:Please update platform config\n", __func__);
1739 		return -EINVAL;
1740 	}
1741 	return 0;
1742 }
1743 
1744 int parse_platform_config(struct hfi1_devdata *dd)
1745 {
1746 	struct platform_config_cache *pcfgcache = &dd->pcfg_cache;
1747 	struct hfi1_pportdata *ppd = dd->pport;
1748 	u32 *ptr = NULL;
1749 	u32 header1 = 0, header2 = 0, magic_num = 0, crc = 0, file_length = 0;
1750 	u32 record_idx = 0, table_type = 0, table_length_dwords = 0;
1751 	int ret = -EINVAL; /* assume failure */
1752 
1753 	/*
1754 	 * For integrated devices that did not fall back to the default file,
1755 	 * the SI tuning information for active channels is acquired from the
1756 	 * scratch register bitmap, thus there is no platform config to parse.
1757 	 * Skip parsing in these situations.
1758 	 */
1759 	if (ppd->config_from_scratch)
1760 		return 0;
1761 
1762 	if (!dd->platform_config.data) {
1763 		dd_dev_err(dd, "%s: Missing config file\n", __func__);
1764 		goto bail;
1765 	}
1766 	ptr = (u32 *)dd->platform_config.data;
1767 
1768 	magic_num = *ptr;
1769 	ptr++;
1770 	if (magic_num != PLATFORM_CONFIG_MAGIC_NUM) {
1771 		dd_dev_err(dd, "%s: Bad config file\n", __func__);
1772 		goto bail;
1773 	}
1774 
1775 	/* Field is file size in DWORDs */
1776 	file_length = (*ptr) * 4;
1777 	ptr++;
1778 
1779 	if (file_length > dd->platform_config.size) {
1780 		dd_dev_info(dd, "%s:File claims to be larger than read size\n",
1781 			    __func__);
1782 		goto bail;
1783 	} else if (file_length < dd->platform_config.size) {
1784 		dd_dev_info(dd,
1785 			    "%s:File claims to be smaller than read size, continuing\n",
1786 			    __func__);
1787 	}
1788 	/* exactly equal, perfection */
1789 
1790 	/*
1791 	 * In both cases where we proceed, using the self-reported file length
1792 	 * is the safer option
1793 	 */
1794 	while (ptr < (u32 *)(dd->platform_config.data + file_length)) {
1795 		header1 = *ptr;
1796 		header2 = *(ptr + 1);
1797 		if (header1 != ~header2) {
1798 			dd_dev_err(dd, "%s: Failed validation at offset %ld\n",
1799 				   __func__, (ptr - (u32 *)
1800 					      dd->platform_config.data));
1801 			goto bail;
1802 		}
1803 
1804 		record_idx = *ptr &
1805 			((1 << PLATFORM_CONFIG_HEADER_RECORD_IDX_LEN_BITS) - 1);
1806 
1807 		table_length_dwords = (*ptr >>
1808 				PLATFORM_CONFIG_HEADER_TABLE_LENGTH_SHIFT) &
1809 		      ((1 << PLATFORM_CONFIG_HEADER_TABLE_LENGTH_LEN_BITS) - 1);
1810 
1811 		table_type = (*ptr >> PLATFORM_CONFIG_HEADER_TABLE_TYPE_SHIFT) &
1812 			((1 << PLATFORM_CONFIG_HEADER_TABLE_TYPE_LEN_BITS) - 1);
1813 
1814 		/* Done with this set of headers */
1815 		ptr += 2;
1816 
1817 		if (record_idx) {
1818 			/* data table */
1819 			switch (table_type) {
1820 			case PLATFORM_CONFIG_SYSTEM_TABLE:
1821 				pcfgcache->config_tables[table_type].num_table =
1822 									1;
1823 				ret = check_meta_version(dd, ptr);
1824 				if (ret)
1825 					goto bail;
1826 				break;
1827 			case PLATFORM_CONFIG_PORT_TABLE:
1828 				pcfgcache->config_tables[table_type].num_table =
1829 									2;
1830 				break;
1831 			case PLATFORM_CONFIG_RX_PRESET_TABLE:
1832 				/* fall through */
1833 			case PLATFORM_CONFIG_TX_PRESET_TABLE:
1834 				/* fall through */
1835 			case PLATFORM_CONFIG_QSFP_ATTEN_TABLE:
1836 				/* fall through */
1837 			case PLATFORM_CONFIG_VARIABLE_SETTINGS_TABLE:
1838 				pcfgcache->config_tables[table_type].num_table =
1839 							table_length_dwords;
1840 				break;
1841 			default:
1842 				dd_dev_err(dd,
1843 					   "%s: Unknown data table %d, offset %ld\n",
1844 					   __func__, table_type,
1845 					   (ptr - (u32 *)
1846 					    dd->platform_config.data));
1847 				goto bail; /* We don't trust this file now */
1848 			}
1849 			pcfgcache->config_tables[table_type].table = ptr;
1850 		} else {
1851 			/* metadata table */
1852 			switch (table_type) {
1853 			case PLATFORM_CONFIG_SYSTEM_TABLE:
1854 				/* fall through */
1855 			case PLATFORM_CONFIG_PORT_TABLE:
1856 				/* fall through */
1857 			case PLATFORM_CONFIG_RX_PRESET_TABLE:
1858 				/* fall through */
1859 			case PLATFORM_CONFIG_TX_PRESET_TABLE:
1860 				/* fall through */
1861 			case PLATFORM_CONFIG_QSFP_ATTEN_TABLE:
1862 				/* fall through */
1863 			case PLATFORM_CONFIG_VARIABLE_SETTINGS_TABLE:
1864 				break;
1865 			default:
1866 				dd_dev_err(dd,
1867 					   "%s: Unknown meta table %d, offset %ld\n",
1868 					   __func__, table_type,
1869 					   (ptr -
1870 					    (u32 *)dd->platform_config.data));
1871 				goto bail; /* We don't trust this file now */
1872 			}
1873 			pcfgcache->config_tables[table_type].table_metadata =
1874 									ptr;
1875 		}
1876 
1877 		/* Calculate and check table crc */
1878 		crc = crc32_le(~(u32)0, (unsigned char const *)ptr,
1879 			       (table_length_dwords * 4));
1880 		crc ^= ~(u32)0;
1881 
1882 		/* Jump the table */
1883 		ptr += table_length_dwords;
1884 		if (crc != *ptr) {
1885 			dd_dev_err(dd, "%s: Failed CRC check at offset %ld\n",
1886 				   __func__, (ptr -
1887 				   (u32 *)dd->platform_config.data));
1888 			goto bail;
1889 		}
1890 		/* Jump the CRC DWORD */
1891 		ptr++;
1892 	}
1893 
1894 	pcfgcache->cache_valid = 1;
1895 	return 0;
1896 bail:
1897 	memset(pcfgcache, 0, sizeof(struct platform_config_cache));
1898 	return ret;
1899 }
1900 
1901 static void get_integrated_platform_config_field(
1902 		struct hfi1_devdata *dd,
1903 		enum platform_config_table_type_encoding table_type,
1904 		int field_index, u32 *data)
1905 {
1906 	struct hfi1_pportdata *ppd = dd->pport;
1907 	u8 *cache = ppd->qsfp_info.cache;
1908 	u32 tx_preset = 0;
1909 
1910 	switch (table_type) {
1911 	case PLATFORM_CONFIG_SYSTEM_TABLE:
1912 		if (field_index == SYSTEM_TABLE_QSFP_POWER_CLASS_MAX)
1913 			*data = ppd->max_power_class;
1914 		else if (field_index == SYSTEM_TABLE_QSFP_ATTENUATION_DEFAULT_25G)
1915 			*data = ppd->default_atten;
1916 		break;
1917 	case PLATFORM_CONFIG_PORT_TABLE:
1918 		if (field_index == PORT_TABLE_PORT_TYPE)
1919 			*data = ppd->port_type;
1920 		else if (field_index == PORT_TABLE_LOCAL_ATTEN_25G)
1921 			*data = ppd->local_atten;
1922 		else if (field_index == PORT_TABLE_REMOTE_ATTEN_25G)
1923 			*data = ppd->remote_atten;
1924 		break;
1925 	case PLATFORM_CONFIG_RX_PRESET_TABLE:
1926 		if (field_index == RX_PRESET_TABLE_QSFP_RX_CDR_APPLY)
1927 			*data = (ppd->rx_preset & QSFP_RX_CDR_APPLY_SMASK) >>
1928 				QSFP_RX_CDR_APPLY_SHIFT;
1929 		else if (field_index == RX_PRESET_TABLE_QSFP_RX_EMP_APPLY)
1930 			*data = (ppd->rx_preset & QSFP_RX_EMP_APPLY_SMASK) >>
1931 				QSFP_RX_EMP_APPLY_SHIFT;
1932 		else if (field_index == RX_PRESET_TABLE_QSFP_RX_AMP_APPLY)
1933 			*data = (ppd->rx_preset & QSFP_RX_AMP_APPLY_SMASK) >>
1934 				QSFP_RX_AMP_APPLY_SHIFT;
1935 		else if (field_index == RX_PRESET_TABLE_QSFP_RX_CDR)
1936 			*data = (ppd->rx_preset & QSFP_RX_CDR_SMASK) >>
1937 				QSFP_RX_CDR_SHIFT;
1938 		else if (field_index == RX_PRESET_TABLE_QSFP_RX_EMP)
1939 			*data = (ppd->rx_preset & QSFP_RX_EMP_SMASK) >>
1940 				QSFP_RX_EMP_SHIFT;
1941 		else if (field_index == RX_PRESET_TABLE_QSFP_RX_AMP)
1942 			*data = (ppd->rx_preset & QSFP_RX_AMP_SMASK) >>
1943 				QSFP_RX_AMP_SHIFT;
1944 		break;
1945 	case PLATFORM_CONFIG_TX_PRESET_TABLE:
1946 		if (cache[QSFP_EQ_INFO_OFFS] & 0x4)
1947 			tx_preset = ppd->tx_preset_eq;
1948 		else
1949 			tx_preset = ppd->tx_preset_noeq;
1950 		if (field_index == TX_PRESET_TABLE_PRECUR)
1951 			*data = (tx_preset & TX_PRECUR_SMASK) >>
1952 				TX_PRECUR_SHIFT;
1953 		else if (field_index == TX_PRESET_TABLE_ATTN)
1954 			*data = (tx_preset & TX_ATTN_SMASK) >>
1955 				TX_ATTN_SHIFT;
1956 		else if (field_index == TX_PRESET_TABLE_POSTCUR)
1957 			*data = (tx_preset & TX_POSTCUR_SMASK) >>
1958 				TX_POSTCUR_SHIFT;
1959 		else if (field_index == TX_PRESET_TABLE_QSFP_TX_CDR_APPLY)
1960 			*data = (tx_preset & QSFP_TX_CDR_APPLY_SMASK) >>
1961 				QSFP_TX_CDR_APPLY_SHIFT;
1962 		else if (field_index == TX_PRESET_TABLE_QSFP_TX_EQ_APPLY)
1963 			*data = (tx_preset & QSFP_TX_EQ_APPLY_SMASK) >>
1964 				QSFP_TX_EQ_APPLY_SHIFT;
1965 		else if (field_index == TX_PRESET_TABLE_QSFP_TX_CDR)
1966 			*data = (tx_preset & QSFP_TX_CDR_SMASK) >>
1967 				QSFP_TX_CDR_SHIFT;
1968 		else if (field_index == TX_PRESET_TABLE_QSFP_TX_EQ)
1969 			*data = (tx_preset & QSFP_TX_EQ_SMASK) >>
1970 				QSFP_TX_EQ_SHIFT;
1971 		break;
1972 	case PLATFORM_CONFIG_QSFP_ATTEN_TABLE:
1973 	case PLATFORM_CONFIG_VARIABLE_SETTINGS_TABLE:
1974 	default:
1975 		break;
1976 	}
1977 }
1978 
1979 static int get_platform_fw_field_metadata(struct hfi1_devdata *dd, int table,
1980 					  int field, u32 *field_len_bits,
1981 					  u32 *field_start_bits)
1982 {
1983 	struct platform_config_cache *pcfgcache = &dd->pcfg_cache;
1984 	u32 *src_ptr = NULL;
1985 
1986 	if (!pcfgcache->cache_valid)
1987 		return -EINVAL;
1988 
1989 	switch (table) {
1990 	case PLATFORM_CONFIG_SYSTEM_TABLE:
1991 		/* fall through */
1992 	case PLATFORM_CONFIG_PORT_TABLE:
1993 		/* fall through */
1994 	case PLATFORM_CONFIG_RX_PRESET_TABLE:
1995 		/* fall through */
1996 	case PLATFORM_CONFIG_TX_PRESET_TABLE:
1997 		/* fall through */
1998 	case PLATFORM_CONFIG_QSFP_ATTEN_TABLE:
1999 		/* fall through */
2000 	case PLATFORM_CONFIG_VARIABLE_SETTINGS_TABLE:
2001 		if (field && field < platform_config_table_limits[table])
2002 			src_ptr =
2003 			pcfgcache->config_tables[table].table_metadata + field;
2004 		break;
2005 	default:
2006 		dd_dev_info(dd, "%s: Unknown table\n", __func__);
2007 		break;
2008 	}
2009 
2010 	if (!src_ptr)
2011 		return -EINVAL;
2012 
2013 	if (field_start_bits)
2014 		*field_start_bits = *src_ptr &
2015 		      ((1 << METADATA_TABLE_FIELD_START_LEN_BITS) - 1);
2016 
2017 	if (field_len_bits)
2018 		*field_len_bits = (*src_ptr >> METADATA_TABLE_FIELD_LEN_SHIFT)
2019 		       & ((1 << METADATA_TABLE_FIELD_LEN_LEN_BITS) - 1);
2020 
2021 	return 0;
2022 }
2023 
2024 /* This is the central interface to getting data out of the platform config
2025  * file. It depends on parse_platform_config() having populated the
2026  * platform_config_cache in hfi1_devdata, and checks the cache_valid member to
2027  * validate the sanity of the cache.
2028  *
2029  * The non-obvious parameters:
2030  * @table_index: Acts as a look up key into which instance of the tables the
2031  * relevant field is fetched from.
2032  *
2033  * This applies to the data tables that have multiple instances. The port table
2034  * is an exception to this rule as each HFI only has one port and thus the
2035  * relevant table can be distinguished by hfi_id.
2036  *
2037  * @data: pointer to memory that will be populated with the field requested.
2038  * @len: length of memory pointed by @data in bytes.
2039  */
2040 int get_platform_config_field(struct hfi1_devdata *dd,
2041 			      enum platform_config_table_type_encoding
2042 			      table_type, int table_index, int field_index,
2043 			      u32 *data, u32 len)
2044 {
2045 	int ret = 0, wlen = 0, seek = 0;
2046 	u32 field_len_bits = 0, field_start_bits = 0, *src_ptr = NULL;
2047 	struct platform_config_cache *pcfgcache = &dd->pcfg_cache;
2048 	struct hfi1_pportdata *ppd = dd->pport;
2049 
2050 	if (data)
2051 		memset(data, 0, len);
2052 	else
2053 		return -EINVAL;
2054 
2055 	if (ppd->config_from_scratch) {
2056 		/*
2057 		 * Use saved configuration from ppd for integrated platforms
2058 		 */
2059 		get_integrated_platform_config_field(dd, table_type,
2060 						     field_index, data);
2061 		return 0;
2062 	}
2063 
2064 	ret = get_platform_fw_field_metadata(dd, table_type, field_index,
2065 					     &field_len_bits,
2066 					     &field_start_bits);
2067 	if (ret)
2068 		return -EINVAL;
2069 
2070 	/* Convert length to bits */
2071 	len *= 8;
2072 
2073 	/* Our metadata function checked cache_valid and field_index for us */
2074 	switch (table_type) {
2075 	case PLATFORM_CONFIG_SYSTEM_TABLE:
2076 		src_ptr = pcfgcache->config_tables[table_type].table;
2077 
2078 		if (field_index != SYSTEM_TABLE_QSFP_POWER_CLASS_MAX) {
2079 			if (len < field_len_bits)
2080 				return -EINVAL;
2081 
2082 			seek = field_start_bits / 8;
2083 			wlen = field_len_bits / 8;
2084 
2085 			src_ptr = (u32 *)((u8 *)src_ptr + seek);
2086 
2087 			/*
2088 			 * We expect the field to be byte aligned and whole byte
2089 			 * lengths if we are here
2090 			 */
2091 			memcpy(data, src_ptr, wlen);
2092 			return 0;
2093 		}
2094 		break;
2095 	case PLATFORM_CONFIG_PORT_TABLE:
2096 		/* Port table is 4 DWORDS */
2097 		src_ptr = dd->hfi1_id ?
2098 			pcfgcache->config_tables[table_type].table + 4 :
2099 			pcfgcache->config_tables[table_type].table;
2100 		break;
2101 	case PLATFORM_CONFIG_RX_PRESET_TABLE:
2102 		/* fall through */
2103 	case PLATFORM_CONFIG_TX_PRESET_TABLE:
2104 		/* fall through */
2105 	case PLATFORM_CONFIG_QSFP_ATTEN_TABLE:
2106 		/* fall through */
2107 	case PLATFORM_CONFIG_VARIABLE_SETTINGS_TABLE:
2108 		src_ptr = pcfgcache->config_tables[table_type].table;
2109 
2110 		if (table_index <
2111 			pcfgcache->config_tables[table_type].num_table)
2112 			src_ptr += table_index;
2113 		else
2114 			src_ptr = NULL;
2115 		break;
2116 	default:
2117 		dd_dev_info(dd, "%s: Unknown table\n", __func__);
2118 		break;
2119 	}
2120 
2121 	if (!src_ptr || len < field_len_bits)
2122 		return -EINVAL;
2123 
2124 	src_ptr += (field_start_bits / 32);
2125 	*data = (*src_ptr >> (field_start_bits % 32)) &
2126 			((1 << field_len_bits) - 1);
2127 
2128 	return 0;
2129 }
2130 
2131 /*
2132  * Download the firmware needed for the Gen3 PCIe SerDes.  An update
2133  * to the SBus firmware is needed before updating the PCIe firmware.
2134  *
2135  * Note: caller must be holding the SBus resource.
2136  */
2137 int load_pcie_firmware(struct hfi1_devdata *dd)
2138 {
2139 	int ret = 0;
2140 
2141 	/* both firmware loads below use the SBus */
2142 	set_sbus_fast_mode(dd);
2143 
2144 	if (fw_sbus_load) {
2145 		turn_off_spicos(dd, SPICO_SBUS);
2146 		do {
2147 			ret = load_sbus_firmware(dd, &fw_sbus);
2148 		} while (retry_firmware(dd, ret));
2149 		if (ret)
2150 			goto done;
2151 	}
2152 
2153 	if (fw_pcie_serdes_load) {
2154 		dd_dev_info(dd, "Setting PCIe SerDes broadcast\n");
2155 		set_serdes_broadcast(dd, all_pcie_serdes_broadcast,
2156 				     pcie_serdes_broadcast[dd->hfi1_id],
2157 				     pcie_serdes_addrs[dd->hfi1_id],
2158 				     NUM_PCIE_SERDES);
2159 		do {
2160 			ret = load_pcie_serdes_firmware(dd, &fw_pcie);
2161 		} while (retry_firmware(dd, ret));
2162 		if (ret)
2163 			goto done;
2164 	}
2165 
2166 done:
2167 	clear_sbus_fast_mode(dd);
2168 
2169 	return ret;
2170 }
2171 
2172 /*
2173  * Read the GUID from the hardware, store it in dd.
2174  */
2175 void read_guid(struct hfi1_devdata *dd)
2176 {
2177 	/* Take the DC out of reset to get a valid GUID value */
2178 	write_csr(dd, CCE_DC_CTRL, 0);
2179 	(void)read_csr(dd, CCE_DC_CTRL);
2180 
2181 	dd->base_guid = read_csr(dd, DC_DC8051_CFG_LOCAL_GUID);
2182 	dd_dev_info(dd, "GUID %llx",
2183 		    (unsigned long long)dd->base_guid);
2184 }
2185 
2186 /* read and display firmware version info */
2187 static void dump_fw_version(struct hfi1_devdata *dd)
2188 {
2189 	u32 pcie_vers[NUM_PCIE_SERDES];
2190 	u32 fabric_vers[NUM_FABRIC_SERDES];
2191 	u32 sbus_vers;
2192 	int i;
2193 	int all_same;
2194 	int ret;
2195 	u8 rcv_addr;
2196 
2197 	ret = acquire_chip_resource(dd, CR_SBUS, SBUS_TIMEOUT);
2198 	if (ret) {
2199 		dd_dev_err(dd, "Unable to acquire SBus to read firmware versions\n");
2200 		return;
2201 	}
2202 
2203 	/* set fast mode */
2204 	set_sbus_fast_mode(dd);
2205 
2206 	/* read version for SBus Master */
2207 	sbus_request(dd, SBUS_MASTER_BROADCAST, 0x02, WRITE_SBUS_RECEIVER, 0);
2208 	sbus_request(dd, SBUS_MASTER_BROADCAST, 0x07, WRITE_SBUS_RECEIVER, 0x1);
2209 	/* wait for interrupt to be processed */
2210 	usleep_range(10000, 11000);
2211 	sbus_vers = sbus_read(dd, SBUS_MASTER_BROADCAST, 0x08, 0x1);
2212 	dd_dev_info(dd, "SBus Master firmware version 0x%08x\n", sbus_vers);
2213 
2214 	/* read version for PCIe SerDes */
2215 	all_same = 1;
2216 	pcie_vers[0] = 0;
2217 	for (i = 0; i < NUM_PCIE_SERDES; i++) {
2218 		rcv_addr = pcie_serdes_addrs[dd->hfi1_id][i];
2219 		sbus_request(dd, rcv_addr, 0x03, WRITE_SBUS_RECEIVER, 0);
2220 		/* wait for interrupt to be processed */
2221 		usleep_range(10000, 11000);
2222 		pcie_vers[i] = sbus_read(dd, rcv_addr, 0x04, 0x0);
2223 		if (i > 0 && pcie_vers[0] != pcie_vers[i])
2224 			all_same = 0;
2225 	}
2226 
2227 	if (all_same) {
2228 		dd_dev_info(dd, "PCIe SerDes firmware version 0x%x\n",
2229 			    pcie_vers[0]);
2230 	} else {
2231 		dd_dev_warn(dd, "PCIe SerDes do not have the same firmware version\n");
2232 		for (i = 0; i < NUM_PCIE_SERDES; i++) {
2233 			dd_dev_info(dd,
2234 				    "PCIe SerDes lane %d firmware version 0x%x\n",
2235 				    i, pcie_vers[i]);
2236 		}
2237 	}
2238 
2239 	/* read version for fabric SerDes */
2240 	all_same = 1;
2241 	fabric_vers[0] = 0;
2242 	for (i = 0; i < NUM_FABRIC_SERDES; i++) {
2243 		rcv_addr = fabric_serdes_addrs[dd->hfi1_id][i];
2244 		sbus_request(dd, rcv_addr, 0x03, WRITE_SBUS_RECEIVER, 0);
2245 		/* wait for interrupt to be processed */
2246 		usleep_range(10000, 11000);
2247 		fabric_vers[i] = sbus_read(dd, rcv_addr, 0x04, 0x0);
2248 		if (i > 0 && fabric_vers[0] != fabric_vers[i])
2249 			all_same = 0;
2250 	}
2251 
2252 	if (all_same) {
2253 		dd_dev_info(dd, "Fabric SerDes firmware version 0x%x\n",
2254 			    fabric_vers[0]);
2255 	} else {
2256 		dd_dev_warn(dd, "Fabric SerDes do not have the same firmware version\n");
2257 		for (i = 0; i < NUM_FABRIC_SERDES; i++) {
2258 			dd_dev_info(dd,
2259 				    "Fabric SerDes lane %d firmware version 0x%x\n",
2260 				    i, fabric_vers[i]);
2261 		}
2262 	}
2263 
2264 	clear_sbus_fast_mode(dd);
2265 	release_chip_resource(dd, CR_SBUS);
2266 }
2267