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