1/*
2 * Copyright(c) 2015 - 2019 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/bitfield.h>
49#include <linux/pci.h>
50#include <linux/io.h>
51#include <linux/delay.h>
52#include <linux/vmalloc.h>
53#include <linux/aer.h>
54#include <linux/module.h>
55
56#include "hfi.h"
57#include "chip_registers.h"
58#include "aspm.h"
59
60/*
61 * This file contains PCIe utility routines.
62 */
63
64/*
65 * Do all the common PCIe setup and initialization.
66 */
67int hfi1_pcie_init(struct hfi1_devdata *dd)
68{
69	int ret;
70	struct pci_dev *pdev = dd->pcidev;
71
72	ret = pci_enable_device(pdev);
73	if (ret) {
74		/*
75		 * This can happen (in theory) iff:
76		 * We did a chip reset, and then failed to reprogram the
77		 * BAR, or the chip reset due to an internal error.  We then
78		 * unloaded the driver and reloaded it.
79		 *
80		 * Both reset cases set the BAR back to initial state.  For
81		 * the latter case, the AER sticky error bit at offset 0x718
82		 * should be set, but the Linux kernel doesn't yet know
83		 * about that, it appears.  If the original BAR was retained
84		 * in the kernel data structures, this may be OK.
85		 */
86		dd_dev_err(dd, "pci enable failed: error %d\n", -ret);
87		return ret;
88	}
89
90	ret = pci_request_regions(pdev, DRIVER_NAME);
91	if (ret) {
92		dd_dev_err(dd, "pci_request_regions fails: err %d\n", -ret);
93		goto bail;
94	}
95
96	ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
97	if (ret) {
98		/*
99		 * If the 64 bit setup fails, try 32 bit.  Some systems
100		 * do not setup 64 bit maps on systems with 2GB or less
101		 * memory installed.
102		 */
103		ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
104		if (ret) {
105			dd_dev_err(dd, "Unable to set DMA mask: %d\n", ret);
106			goto bail;
107		}
108		ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
109	} else {
110		ret = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
111	}
112	if (ret) {
113		dd_dev_err(dd, "Unable to set DMA consistent mask: %d\n", ret);
114		goto bail;
115	}
116
117	pci_set_master(pdev);
118	(void)pci_enable_pcie_error_reporting(pdev);
119	return 0;
120
121bail:
122	hfi1_pcie_cleanup(pdev);
123	return ret;
124}
125
126/*
127 * Clean what was done in hfi1_pcie_init()
128 */
129void hfi1_pcie_cleanup(struct pci_dev *pdev)
130{
131	pci_disable_device(pdev);
132	/*
133	 * Release regions should be called after the disable. OK to
134	 * call if request regions has not been called or failed.
135	 */
136	pci_release_regions(pdev);
137}
138
139/*
140 * Do remaining PCIe setup, once dd is allocated, and save away
141 * fields required to re-initialize after a chip reset, or for
142 * various other purposes
143 */
144int hfi1_pcie_ddinit(struct hfi1_devdata *dd, struct pci_dev *pdev)
145{
146	unsigned long len;
147	resource_size_t addr;
148	int ret = 0;
149	u32 rcv_array_count;
150
151	addr = pci_resource_start(pdev, 0);
152	len = pci_resource_len(pdev, 0);
153
154	/*
155	 * The TXE PIO buffers are at the tail end of the chip space.
156	 * Cut them off and map them separately.
157	 */
158
159	/* sanity check vs expectations */
160	if (len != TXE_PIO_SEND + TXE_PIO_SIZE) {
161		dd_dev_err(dd, "chip PIO range does not match\n");
162		return -EINVAL;
163	}
164
165	dd->kregbase1 = ioremap(addr, RCV_ARRAY);
166	if (!dd->kregbase1) {
167		dd_dev_err(dd, "UC mapping of kregbase1 failed\n");
168		return -ENOMEM;
169	}
170	dd_dev_info(dd, "UC base1: %p for %x\n", dd->kregbase1, RCV_ARRAY);
171
172	/* verify that reads actually work, save revision for reset check */
173	dd->revision = readq(dd->kregbase1 + CCE_REVISION);
174	if (dd->revision == ~(u64)0) {
175		dd_dev_err(dd, "Cannot read chip CSRs\n");
176		goto nomem;
177	}
178
179	rcv_array_count = readq(dd->kregbase1 + RCV_ARRAY_CNT);
180	dd_dev_info(dd, "RcvArray count: %u\n", rcv_array_count);
181	dd->base2_start  = RCV_ARRAY + rcv_array_count * 8;
182
183	dd->kregbase2 = ioremap(
184		addr + dd->base2_start,
185		TXE_PIO_SEND - dd->base2_start);
186	if (!dd->kregbase2) {
187		dd_dev_err(dd, "UC mapping of kregbase2 failed\n");
188		goto nomem;
189	}
190	dd_dev_info(dd, "UC base2: %p for %x\n", dd->kregbase2,
191		    TXE_PIO_SEND - dd->base2_start);
192
193	dd->piobase = ioremap_wc(addr + TXE_PIO_SEND, TXE_PIO_SIZE);
194	if (!dd->piobase) {
195		dd_dev_err(dd, "WC mapping of send buffers failed\n");
196		goto nomem;
197	}
198	dd_dev_info(dd, "WC piobase: %p for %x\n", dd->piobase, TXE_PIO_SIZE);
199
200	dd->physaddr = addr;        /* used for io_remap, etc. */
201
202	/*
203	 * Map the chip's RcvArray as write-combining to allow us
204	 * to write an entire cacheline worth of entries in one shot.
205	 */
206	dd->rcvarray_wc = ioremap_wc(addr + RCV_ARRAY,
207				     rcv_array_count * 8);
208	if (!dd->rcvarray_wc) {
209		dd_dev_err(dd, "WC mapping of receive array failed\n");
210		goto nomem;
211	}
212	dd_dev_info(dd, "WC RcvArray: %p for %x\n",
213		    dd->rcvarray_wc, rcv_array_count * 8);
214
215	dd->flags |= HFI1_PRESENT;	/* chip.c CSR routines now work */
216	return 0;
217nomem:
218	ret = -ENOMEM;
219	hfi1_pcie_ddcleanup(dd);
220	return ret;
221}
222
223/*
224 * Do PCIe cleanup related to dd, after chip-specific cleanup, etc.  Just prior
225 * to releasing the dd memory.
226 * Void because all of the core pcie cleanup functions are void.
227 */
228void hfi1_pcie_ddcleanup(struct hfi1_devdata *dd)
229{
230	dd->flags &= ~HFI1_PRESENT;
231	if (dd->kregbase1)
232		iounmap(dd->kregbase1);
233	dd->kregbase1 = NULL;
234	if (dd->kregbase2)
235		iounmap(dd->kregbase2);
236	dd->kregbase2 = NULL;
237	if (dd->rcvarray_wc)
238		iounmap(dd->rcvarray_wc);
239	dd->rcvarray_wc = NULL;
240	if (dd->piobase)
241		iounmap(dd->piobase);
242	dd->piobase = NULL;
243}
244
245/* return the PCIe link speed from the given link status */
246static u32 extract_speed(u16 linkstat)
247{
248	u32 speed;
249
250	switch (linkstat & PCI_EXP_LNKSTA_CLS) {
251	default: /* not defined, assume Gen1 */
252	case PCI_EXP_LNKSTA_CLS_2_5GB:
253		speed = 2500; /* Gen 1, 2.5GHz */
254		break;
255	case PCI_EXP_LNKSTA_CLS_5_0GB:
256		speed = 5000; /* Gen 2, 5GHz */
257		break;
258	case PCI_EXP_LNKSTA_CLS_8_0GB:
259		speed = 8000; /* Gen 3, 8GHz */
260		break;
261	}
262	return speed;
263}
264
265/* read the link status and set dd->{lbus_width,lbus_speed,lbus_info} */
266static void update_lbus_info(struct hfi1_devdata *dd)
267{
268	u16 linkstat;
269	int ret;
270
271	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKSTA, &linkstat);
272	if (ret) {
273		dd_dev_err(dd, "Unable to read from PCI config\n");
274		return;
275	}
276
277	dd->lbus_width = FIELD_GET(PCI_EXP_LNKSTA_NLW, linkstat);
278	dd->lbus_speed = extract_speed(linkstat);
279	snprintf(dd->lbus_info, sizeof(dd->lbus_info),
280		 "PCIe,%uMHz,x%u", dd->lbus_speed, dd->lbus_width);
281}
282
283/*
284 * Read in the current PCIe link width and speed.  Find if the link is
285 * Gen3 capable.
286 */
287int pcie_speeds(struct hfi1_devdata *dd)
288{
289	u32 linkcap;
290	struct pci_dev *parent = dd->pcidev->bus->self;
291	int ret;
292
293	if (!pci_is_pcie(dd->pcidev)) {
294		dd_dev_err(dd, "Can't find PCI Express capability!\n");
295		return -EINVAL;
296	}
297
298	/* find if our max speed is Gen3 and parent supports Gen3 speeds */
299	dd->link_gen3_capable = 1;
300
301	ret = pcie_capability_read_dword(dd->pcidev, PCI_EXP_LNKCAP, &linkcap);
302	if (ret) {
303		dd_dev_err(dd, "Unable to read from PCI config\n");
304		return pcibios_err_to_errno(ret);
305	}
306
307	if ((linkcap & PCI_EXP_LNKCAP_SLS) != PCI_EXP_LNKCAP_SLS_8_0GB) {
308		dd_dev_info(dd,
309			    "This HFI is not Gen3 capable, max speed 0x%x, need 0x3\n",
310			    linkcap & PCI_EXP_LNKCAP_SLS);
311		dd->link_gen3_capable = 0;
312	}
313
314	/*
315	 * bus->max_bus_speed is set from the bridge's linkcap Max Link Speed
316	 */
317	if (parent &&
318	    (dd->pcidev->bus->max_bus_speed == PCIE_SPEED_2_5GT ||
319	     dd->pcidev->bus->max_bus_speed == PCIE_SPEED_5_0GT)) {
320		dd_dev_info(dd, "Parent PCIe bridge does not support Gen3\n");
321		dd->link_gen3_capable = 0;
322	}
323
324	/* obtain the link width and current speed */
325	update_lbus_info(dd);
326
327	dd_dev_info(dd, "%s\n", dd->lbus_info);
328
329	return 0;
330}
331
332/**
333 * Restore command and BARs after a reset has wiped them out
334 *
335 * Returns 0 on success, otherwise a negative error value
336 */
337int restore_pci_variables(struct hfi1_devdata *dd)
338{
339	int ret;
340
341	ret = pci_write_config_word(dd->pcidev, PCI_COMMAND, dd->pci_command);
342	if (ret)
343		goto error;
344
345	ret = pci_write_config_dword(dd->pcidev, PCI_BASE_ADDRESS_0,
346				     dd->pcibar0);
347	if (ret)
348		goto error;
349
350	ret = pci_write_config_dword(dd->pcidev, PCI_BASE_ADDRESS_1,
351				     dd->pcibar1);
352	if (ret)
353		goto error;
354
355	ret = pci_write_config_dword(dd->pcidev, PCI_ROM_ADDRESS, dd->pci_rom);
356	if (ret)
357		goto error;
358
359	ret = pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL,
360					 dd->pcie_devctl);
361	if (ret)
362		goto error;
363
364	ret = pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL,
365					 dd->pcie_lnkctl);
366	if (ret)
367		goto error;
368
369	ret = pcie_capability_write_word(dd->pcidev, PCI_EXP_DEVCTL2,
370					 dd->pcie_devctl2);
371	if (ret)
372		goto error;
373
374	ret = pci_write_config_dword(dd->pcidev, PCI_CFG_MSIX0, dd->pci_msix0);
375	if (ret)
376		goto error;
377
378	if (pci_find_ext_capability(dd->pcidev, PCI_EXT_CAP_ID_TPH)) {
379		ret = pci_write_config_dword(dd->pcidev, PCIE_CFG_TPH2,
380					     dd->pci_tph2);
381		if (ret)
382			goto error;
383	}
384	return 0;
385
386error:
387	dd_dev_err(dd, "Unable to write to PCI config\n");
388	return pcibios_err_to_errno(ret);
389}
390
391/**
392 * Save BARs and command to rewrite after device reset
393 *
394 * Returns 0 on success, otherwise a negative error value
395 */
396int save_pci_variables(struct hfi1_devdata *dd)
397{
398	int ret;
399
400	ret = pci_read_config_dword(dd->pcidev, PCI_BASE_ADDRESS_0,
401				    &dd->pcibar0);
402	if (ret)
403		goto error;
404
405	ret = pci_read_config_dword(dd->pcidev, PCI_BASE_ADDRESS_1,
406				    &dd->pcibar1);
407	if (ret)
408		goto error;
409
410	ret = pci_read_config_dword(dd->pcidev, PCI_ROM_ADDRESS, &dd->pci_rom);
411	if (ret)
412		goto error;
413
414	ret = pci_read_config_word(dd->pcidev, PCI_COMMAND, &dd->pci_command);
415	if (ret)
416		goto error;
417
418	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL,
419					&dd->pcie_devctl);
420	if (ret)
421		goto error;
422
423	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL,
424					&dd->pcie_lnkctl);
425	if (ret)
426		goto error;
427
428	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL2,
429					&dd->pcie_devctl2);
430	if (ret)
431		goto error;
432
433	ret = pci_read_config_dword(dd->pcidev, PCI_CFG_MSIX0, &dd->pci_msix0);
434	if (ret)
435		goto error;
436
437	if (pci_find_ext_capability(dd->pcidev, PCI_EXT_CAP_ID_TPH)) {
438		ret = pci_read_config_dword(dd->pcidev, PCIE_CFG_TPH2,
439					    &dd->pci_tph2);
440		if (ret)
441			goto error;
442	}
443	return 0;
444
445error:
446	dd_dev_err(dd, "Unable to read from PCI config\n");
447	return pcibios_err_to_errno(ret);
448}
449
450/*
451 * BIOS may not set PCIe bus-utilization parameters for best performance.
452 * Check and optionally adjust them to maximize our throughput.
453 */
454static int hfi1_pcie_caps;
455module_param_named(pcie_caps, hfi1_pcie_caps, int, 0444);
456MODULE_PARM_DESC(pcie_caps, "Max PCIe tuning: Payload (0..3), ReadReq (4..7)");
457
458/**
459 * tune_pcie_caps() - Code to adjust PCIe capabilities.
460 * @dd: Valid device data structure
461 *
462 */
463void tune_pcie_caps(struct hfi1_devdata *dd)
464{
465	struct pci_dev *parent;
466	u16 rc_mpss, rc_mps, ep_mpss, ep_mps;
467	u16 rc_mrrs, ep_mrrs, max_mrrs, ectl;
468	int ret;
469
470	/*
471	 * Turn on extended tags in DevCtl in case the BIOS has turned it off
472	 * to improve WFR SDMA bandwidth
473	 */
474	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_DEVCTL, &ectl);
475	if ((!ret) && !(ectl & PCI_EXP_DEVCTL_EXT_TAG)) {
476		dd_dev_info(dd, "Enabling PCIe extended tags\n");
477		ectl |= PCI_EXP_DEVCTL_EXT_TAG;
478		ret = pcie_capability_write_word(dd->pcidev,
479						 PCI_EXP_DEVCTL, ectl);
480		if (ret)
481			dd_dev_info(dd, "Unable to write to PCI config\n");
482	}
483	/* Find out supported and configured values for parent (root) */
484	parent = dd->pcidev->bus->self;
485	/*
486	 * The driver cannot perform the tuning if it does not have
487	 * access to the upstream component.
488	 */
489	if (!parent) {
490		dd_dev_info(dd, "Parent not found\n");
491		return;
492	}
493	if (!pci_is_root_bus(parent->bus)) {
494		dd_dev_info(dd, "Parent not root\n");
495		return;
496	}
497	if (!pci_is_pcie(parent)) {
498		dd_dev_info(dd, "Parent is not PCI Express capable\n");
499		return;
500	}
501	if (!pci_is_pcie(dd->pcidev)) {
502		dd_dev_info(dd, "PCI device is not PCI Express capable\n");
503		return;
504	}
505	rc_mpss = parent->pcie_mpss;
506	rc_mps = ffs(pcie_get_mps(parent)) - 8;
507	/* Find out supported and configured values for endpoint (us) */
508	ep_mpss = dd->pcidev->pcie_mpss;
509	ep_mps = ffs(pcie_get_mps(dd->pcidev)) - 8;
510
511	/* Find max payload supported by root, endpoint */
512	if (rc_mpss > ep_mpss)
513		rc_mpss = ep_mpss;
514
515	/* If Supported greater than limit in module param, limit it */
516	if (rc_mpss > (hfi1_pcie_caps & 7))
517		rc_mpss = hfi1_pcie_caps & 7;
518	/* If less than (allowed, supported), bump root payload */
519	if (rc_mpss > rc_mps) {
520		rc_mps = rc_mpss;
521		pcie_set_mps(parent, 128 << rc_mps);
522	}
523	/* If less than (allowed, supported), bump endpoint payload */
524	if (rc_mpss > ep_mps) {
525		ep_mps = rc_mpss;
526		pcie_set_mps(dd->pcidev, 128 << ep_mps);
527	}
528
529	/*
530	 * Now the Read Request size.
531	 * No field for max supported, but PCIe spec limits it to 4096,
532	 * which is code '5' (log2(4096) - 7)
533	 */
534	max_mrrs = 5;
535	if (max_mrrs > ((hfi1_pcie_caps >> 4) & 7))
536		max_mrrs = (hfi1_pcie_caps >> 4) & 7;
537
538	max_mrrs = 128 << max_mrrs;
539	rc_mrrs = pcie_get_readrq(parent);
540	ep_mrrs = pcie_get_readrq(dd->pcidev);
541
542	if (max_mrrs > rc_mrrs) {
543		rc_mrrs = max_mrrs;
544		pcie_set_readrq(parent, rc_mrrs);
545	}
546	if (max_mrrs > ep_mrrs) {
547		ep_mrrs = max_mrrs;
548		pcie_set_readrq(dd->pcidev, ep_mrrs);
549	}
550}
551
552/* End of PCIe capability tuning */
553
554/*
555 * From here through hfi1_pci_err_handler definition is invoked via
556 * PCI error infrastructure, registered via pci
557 */
558static pci_ers_result_t
559pci_error_detected(struct pci_dev *pdev, pci_channel_state_t state)
560{
561	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
562	pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;
563
564	switch (state) {
565	case pci_channel_io_normal:
566		dd_dev_info(dd, "State Normal, ignoring\n");
567		break;
568
569	case pci_channel_io_frozen:
570		dd_dev_info(dd, "State Frozen, requesting reset\n");
571		pci_disable_device(pdev);
572		ret = PCI_ERS_RESULT_NEED_RESET;
573		break;
574
575	case pci_channel_io_perm_failure:
576		if (dd) {
577			dd_dev_info(dd, "State Permanent Failure, disabling\n");
578			/* no more register accesses! */
579			dd->flags &= ~HFI1_PRESENT;
580			hfi1_disable_after_error(dd);
581		}
582		 /* else early, or other problem */
583		ret =  PCI_ERS_RESULT_DISCONNECT;
584		break;
585
586	default: /* shouldn't happen */
587		dd_dev_info(dd, "HFI1 PCI errors detected (state %d)\n",
588			    state);
589		break;
590	}
591	return ret;
592}
593
594static pci_ers_result_t
595pci_mmio_enabled(struct pci_dev *pdev)
596{
597	u64 words = 0U;
598	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
599	pci_ers_result_t ret = PCI_ERS_RESULT_RECOVERED;
600
601	if (dd && dd->pport) {
602		words = read_port_cntr(dd->pport, C_RX_WORDS, CNTR_INVALID_VL);
603		if (words == ~0ULL)
604			ret = PCI_ERS_RESULT_NEED_RESET;
605		dd_dev_info(dd,
606			    "HFI1 mmio_enabled function called, read wordscntr %llx, returning %d\n",
607			    words, ret);
608	}
609	return  ret;
610}
611
612static pci_ers_result_t
613pci_slot_reset(struct pci_dev *pdev)
614{
615	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
616
617	dd_dev_info(dd, "HFI1 slot_reset function called, ignored\n");
618	return PCI_ERS_RESULT_CAN_RECOVER;
619}
620
621static void
622pci_resume(struct pci_dev *pdev)
623{
624	struct hfi1_devdata *dd = pci_get_drvdata(pdev);
625
626	dd_dev_info(dd, "HFI1 resume function called\n");
627	/*
628	 * Running jobs will fail, since it's asynchronous
629	 * unlike sysfs-requested reset.   Better than
630	 * doing nothing.
631	 */
632	hfi1_init(dd, 1); /* same as re-init after reset */
633}
634
635const struct pci_error_handlers hfi1_pci_err_handler = {
636	.error_detected = pci_error_detected,
637	.mmio_enabled = pci_mmio_enabled,
638	.slot_reset = pci_slot_reset,
639	.resume = pci_resume,
640};
641
642/*============================================================================*/
643/* PCIe Gen3 support */
644
645/*
646 * This code is separated out because it is expected to be removed in the
647 * final shipping product.  If not, then it will be revisited and items
648 * will be moved to more standard locations.
649 */
650
651/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_STS field values */
652#define DL_STATUS_HFI0 0x1	/* hfi0 firmware download complete */
653#define DL_STATUS_HFI1 0x2	/* hfi1 firmware download complete */
654#define DL_STATUS_BOTH 0x3	/* hfi0 and hfi1 firmware download complete */
655
656/* ASIC_PCI_SD_HOST_STATUS.FW_DNLD_ERR field values */
657#define DL_ERR_NONE		0x0	/* no error */
658#define DL_ERR_SWAP_PARITY	0x1	/* parity error in SerDes interrupt */
659					/*   or response data */
660#define DL_ERR_DISABLED	0x2	/* hfi disabled */
661#define DL_ERR_SECURITY	0x3	/* security check failed */
662#define DL_ERR_SBUS		0x4	/* SBus status error */
663#define DL_ERR_XFR_PARITY	0x5	/* parity error during ROM transfer*/
664
665/* gasket block secondary bus reset delay */
666#define SBR_DELAY_US 200000	/* 200ms */
667
668static uint pcie_target = 3;
669module_param(pcie_target, uint, S_IRUGO);
670MODULE_PARM_DESC(pcie_target, "PCIe target speed (0 skip, 1-3 Gen1-3)");
671
672static uint pcie_force;
673module_param(pcie_force, uint, S_IRUGO);
674MODULE_PARM_DESC(pcie_force, "Force driver to do a PCIe firmware download even if already at target speed");
675
676static uint pcie_retry = 5;
677module_param(pcie_retry, uint, S_IRUGO);
678MODULE_PARM_DESC(pcie_retry, "Driver will try this many times to reach requested speed");
679
680#define UNSET_PSET 255
681#define DEFAULT_DISCRETE_PSET 2	/* discrete HFI */
682#define DEFAULT_MCP_PSET 6	/* MCP HFI */
683static uint pcie_pset = UNSET_PSET;
684module_param(pcie_pset, uint, S_IRUGO);
685MODULE_PARM_DESC(pcie_pset, "PCIe Eq Pset value to use, range is 0-10");
686
687static uint pcie_ctle = 3; /* discrete on, integrated on */
688module_param(pcie_ctle, uint, S_IRUGO);
689MODULE_PARM_DESC(pcie_ctle, "PCIe static CTLE mode, bit 0 - discrete on/off, bit 1 - integrated on/off");
690
691/* equalization columns */
692#define PREC 0
693#define ATTN 1
694#define POST 2
695
696/* discrete silicon preliminary equalization values */
697static const u8 discrete_preliminary_eq[11][3] = {
698	/* prec   attn   post */
699	{  0x00,  0x00,  0x12 },	/* p0 */
700	{  0x00,  0x00,  0x0c },	/* p1 */
701	{  0x00,  0x00,  0x0f },	/* p2 */
702	{  0x00,  0x00,  0x09 },	/* p3 */
703	{  0x00,  0x00,  0x00 },	/* p4 */
704	{  0x06,  0x00,  0x00 },	/* p5 */
705	{  0x09,  0x00,  0x00 },	/* p6 */
706	{  0x06,  0x00,  0x0f },	/* p7 */
707	{  0x09,  0x00,  0x09 },	/* p8 */
708	{  0x0c,  0x00,  0x00 },	/* p9 */
709	{  0x00,  0x00,  0x18 },	/* p10 */
710};
711
712/* integrated silicon preliminary equalization values */
713static const u8 integrated_preliminary_eq[11][3] = {
714	/* prec   attn   post */
715	{  0x00,  0x1e,  0x07 },	/* p0 */
716	{  0x00,  0x1e,  0x05 },	/* p1 */
717	{  0x00,  0x1e,  0x06 },	/* p2 */
718	{  0x00,  0x1e,  0x04 },	/* p3 */
719	{  0x00,  0x1e,  0x00 },	/* p4 */
720	{  0x03,  0x1e,  0x00 },	/* p5 */
721	{  0x04,  0x1e,  0x00 },	/* p6 */
722	{  0x03,  0x1e,  0x06 },	/* p7 */
723	{  0x03,  0x1e,  0x04 },	/* p8 */
724	{  0x05,  0x1e,  0x00 },	/* p9 */
725	{  0x00,  0x1e,  0x0a },	/* p10 */
726};
727
728static const u8 discrete_ctle_tunings[11][4] = {
729	/* DC     LF     HF     BW */
730	{  0x48,  0x0b,  0x04,  0x04 },	/* p0 */
731	{  0x60,  0x05,  0x0f,  0x0a },	/* p1 */
732	{  0x50,  0x09,  0x06,  0x06 },	/* p2 */
733	{  0x68,  0x05,  0x0f,  0x0a },	/* p3 */
734	{  0x80,  0x05,  0x0f,  0x0a },	/* p4 */
735	{  0x70,  0x05,  0x0f,  0x0a },	/* p5 */
736	{  0x68,  0x05,  0x0f,  0x0a },	/* p6 */
737	{  0x38,  0x0f,  0x00,  0x00 },	/* p7 */
738	{  0x48,  0x09,  0x06,  0x06 },	/* p8 */
739	{  0x60,  0x05,  0x0f,  0x0a },	/* p9 */
740	{  0x38,  0x0f,  0x00,  0x00 },	/* p10 */
741};
742
743static const u8 integrated_ctle_tunings[11][4] = {
744	/* DC     LF     HF     BW */
745	{  0x38,  0x0f,  0x00,  0x00 },	/* p0 */
746	{  0x38,  0x0f,  0x00,  0x00 },	/* p1 */
747	{  0x38,  0x0f,  0x00,  0x00 },	/* p2 */
748	{  0x38,  0x0f,  0x00,  0x00 },	/* p3 */
749	{  0x58,  0x0a,  0x05,  0x05 },	/* p4 */
750	{  0x48,  0x0a,  0x05,  0x05 },	/* p5 */
751	{  0x40,  0x0a,  0x05,  0x05 },	/* p6 */
752	{  0x38,  0x0f,  0x00,  0x00 },	/* p7 */
753	{  0x38,  0x0f,  0x00,  0x00 },	/* p8 */
754	{  0x38,  0x09,  0x06,  0x06 },	/* p9 */
755	{  0x38,  0x0e,  0x01,  0x01 },	/* p10 */
756};
757
758/* helper to format the value to write to hardware */
759#define eq_value(pre, curr, post) \
760	((((u32)(pre)) << \
761			PCIE_CFG_REG_PL102_GEN3_EQ_PRE_CURSOR_PSET_SHIFT) \
762	| (((u32)(curr)) << PCIE_CFG_REG_PL102_GEN3_EQ_CURSOR_PSET_SHIFT) \
763	| (((u32)(post)) << \
764		PCIE_CFG_REG_PL102_GEN3_EQ_POST_CURSOR_PSET_SHIFT))
765
766/*
767 * Load the given EQ preset table into the PCIe hardware.
768 */
769static int load_eq_table(struct hfi1_devdata *dd, const u8 eq[11][3], u8 fs,
770			 u8 div)
771{
772	struct pci_dev *pdev = dd->pcidev;
773	u32 hit_error = 0;
774	u32 violation;
775	u32 i;
776	u8 c_minus1, c0, c_plus1;
777	int ret;
778
779	for (i = 0; i < 11; i++) {
780		/* set index */
781		pci_write_config_dword(pdev, PCIE_CFG_REG_PL103, i);
782		/* write the value */
783		c_minus1 = eq[i][PREC] / div;
784		c0 = fs - (eq[i][PREC] / div) - (eq[i][POST] / div);
785		c_plus1 = eq[i][POST] / div;
786		pci_write_config_dword(pdev, PCIE_CFG_REG_PL102,
787				       eq_value(c_minus1, c0, c_plus1));
788		/* check if these coefficients violate EQ rules */
789		ret = pci_read_config_dword(dd->pcidev,
790					    PCIE_CFG_REG_PL105, &violation);
791		if (ret) {
792			dd_dev_err(dd, "Unable to read from PCI config\n");
793			hit_error = 1;
794			break;
795		}
796
797		if (violation
798		    & PCIE_CFG_REG_PL105_GEN3_EQ_VIOLATE_COEF_RULES_SMASK){
799			if (hit_error == 0) {
800				dd_dev_err(dd,
801					   "Gen3 EQ Table Coefficient rule violations\n");
802				dd_dev_err(dd, "         prec   attn   post\n");
803			}
804			dd_dev_err(dd, "   p%02d:   %02x     %02x     %02x\n",
805				   i, (u32)eq[i][0], (u32)eq[i][1],
806				   (u32)eq[i][2]);
807			dd_dev_err(dd, "            %02x     %02x     %02x\n",
808				   (u32)c_minus1, (u32)c0, (u32)c_plus1);
809			hit_error = 1;
810		}
811	}
812	if (hit_error)
813		return -EINVAL;
814	return 0;
815}
816
817/*
818 * Steps to be done after the PCIe firmware is downloaded and
819 * before the SBR for the Pcie Gen3.
820 * The SBus resource is already being held.
821 */
822static void pcie_post_steps(struct hfi1_devdata *dd)
823{
824	int i;
825
826	set_sbus_fast_mode(dd);
827	/*
828	 * Write to the PCIe PCSes to set the G3_LOCKED_NEXT bits to 1.
829	 * This avoids a spurious framing error that can otherwise be
830	 * generated by the MAC layer.
831	 *
832	 * Use individual addresses since no broadcast is set up.
833	 */
834	for (i = 0; i < NUM_PCIE_SERDES; i++) {
835		sbus_request(dd, pcie_pcs_addrs[dd->hfi1_id][i],
836			     0x03, WRITE_SBUS_RECEIVER, 0x00022132);
837	}
838
839	clear_sbus_fast_mode(dd);
840}
841
842/*
843 * Trigger a secondary bus reset (SBR) on ourselves using our parent.
844 *
845 * Based on pci_parent_bus_reset() which is not exported by the
846 * kernel core.
847 */
848static int trigger_sbr(struct hfi1_devdata *dd)
849{
850	struct pci_dev *dev = dd->pcidev;
851	struct pci_dev *pdev;
852
853	/* need a parent */
854	if (!dev->bus->self) {
855		dd_dev_err(dd, "%s: no parent device\n", __func__);
856		return -ENOTTY;
857	}
858
859	/* should not be anyone else on the bus */
860	list_for_each_entry(pdev, &dev->bus->devices, bus_list)
861		if (pdev != dev) {
862			dd_dev_err(dd,
863				   "%s: another device is on the same bus\n",
864				   __func__);
865			return -ENOTTY;
866		}
867
868	/*
869	 * This is an end around to do an SBR during probe time. A new API needs
870	 * to be implemented to have cleaner interface but this fixes the
871	 * current brokenness
872	 */
873	return pci_bridge_secondary_bus_reset(dev->bus->self);
874}
875
876/*
877 * Write the given gasket interrupt register.
878 */
879static void write_gasket_interrupt(struct hfi1_devdata *dd, int index,
880				   u16 code, u16 data)
881{
882	write_csr(dd, ASIC_PCIE_SD_INTRPT_LIST + (index * 8),
883		  (((u64)code << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_CODE_SHIFT) |
884		   ((u64)data << ASIC_PCIE_SD_INTRPT_LIST_INTRPT_DATA_SHIFT)));
885}
886
887/*
888 * Tell the gasket logic how to react to the reset.
889 */
890static void arm_gasket_logic(struct hfi1_devdata *dd)
891{
892	u64 reg;
893
894	reg = (((u64)1 << dd->hfi1_id) <<
895	       ASIC_PCIE_SD_HOST_CMD_INTRPT_CMD_SHIFT) |
896	      ((u64)pcie_serdes_broadcast[dd->hfi1_id] <<
897	       ASIC_PCIE_SD_HOST_CMD_SBUS_RCVR_ADDR_SHIFT |
898	       ASIC_PCIE_SD_HOST_CMD_SBR_MODE_SMASK |
899	       ((u64)SBR_DELAY_US & ASIC_PCIE_SD_HOST_CMD_TIMER_MASK) <<
900	       ASIC_PCIE_SD_HOST_CMD_TIMER_SHIFT);
901	write_csr(dd, ASIC_PCIE_SD_HOST_CMD, reg);
902	/* read back to push the write */
903	read_csr(dd, ASIC_PCIE_SD_HOST_CMD);
904}
905
906/*
907 * CCE_PCIE_CTRL long name helpers
908 * We redefine these shorter macros to use in the code while leaving
909 * chip_registers.h to be autogenerated from the hardware spec.
910 */
911#define LANE_BUNDLE_MASK              CCE_PCIE_CTRL_PCIE_LANE_BUNDLE_MASK
912#define LANE_BUNDLE_SHIFT             CCE_PCIE_CTRL_PCIE_LANE_BUNDLE_SHIFT
913#define LANE_DELAY_MASK               CCE_PCIE_CTRL_PCIE_LANE_DELAY_MASK
914#define LANE_DELAY_SHIFT              CCE_PCIE_CTRL_PCIE_LANE_DELAY_SHIFT
915#define MARGIN_OVERWRITE_ENABLE_SHIFT CCE_PCIE_CTRL_XMT_MARGIN_OVERWRITE_ENABLE_SHIFT
916#define MARGIN_SHIFT                  CCE_PCIE_CTRL_XMT_MARGIN_SHIFT
917#define MARGIN_G1_G2_OVERWRITE_MASK   CCE_PCIE_CTRL_XMT_MARGIN_GEN1_GEN2_OVERWRITE_ENABLE_MASK
918#define MARGIN_G1_G2_OVERWRITE_SHIFT  CCE_PCIE_CTRL_XMT_MARGIN_GEN1_GEN2_OVERWRITE_ENABLE_SHIFT
919#define MARGIN_GEN1_GEN2_MASK         CCE_PCIE_CTRL_XMT_MARGIN_GEN1_GEN2_MASK
920#define MARGIN_GEN1_GEN2_SHIFT        CCE_PCIE_CTRL_XMT_MARGIN_GEN1_GEN2_SHIFT
921
922 /*
923  * Write xmt_margin for full-swing (WFR-B) or half-swing (WFR-C).
924  */
925static void write_xmt_margin(struct hfi1_devdata *dd, const char *fname)
926{
927	u64 pcie_ctrl;
928	u64 xmt_margin;
929	u64 xmt_margin_oe;
930	u64 lane_delay;
931	u64 lane_bundle;
932
933	pcie_ctrl = read_csr(dd, CCE_PCIE_CTRL);
934
935	/*
936	 * For Discrete, use full-swing.
937	 *  - PCIe TX defaults to full-swing.
938	 *    Leave this register as default.
939	 * For Integrated, use half-swing
940	 *  - Copy xmt_margin and xmt_margin_oe
941	 *    from Gen1/Gen2 to Gen3.
942	 */
943	if (dd->pcidev->device == PCI_DEVICE_ID_INTEL1) { /* integrated */
944		/* extract initial fields */
945		xmt_margin = (pcie_ctrl >> MARGIN_GEN1_GEN2_SHIFT)
946			      & MARGIN_GEN1_GEN2_MASK;
947		xmt_margin_oe = (pcie_ctrl >> MARGIN_G1_G2_OVERWRITE_SHIFT)
948				 & MARGIN_G1_G2_OVERWRITE_MASK;
949		lane_delay = (pcie_ctrl >> LANE_DELAY_SHIFT) & LANE_DELAY_MASK;
950		lane_bundle = (pcie_ctrl >> LANE_BUNDLE_SHIFT)
951			       & LANE_BUNDLE_MASK;
952
953		/*
954		 * For A0, EFUSE values are not set.  Override with the
955		 * correct values.
956		 */
957		if (is_ax(dd)) {
958			/*
959			 * xmt_margin and OverwiteEnabel should be the
960			 * same for Gen1/Gen2 and Gen3
961			 */
962			xmt_margin = 0x5;
963			xmt_margin_oe = 0x1;
964			lane_delay = 0xF; /* Delay 240ns. */
965			lane_bundle = 0x0; /* Set to 1 lane. */
966		}
967
968		/* overwrite existing values */
969		pcie_ctrl = (xmt_margin << MARGIN_GEN1_GEN2_SHIFT)
970			| (xmt_margin_oe << MARGIN_G1_G2_OVERWRITE_SHIFT)
971			| (xmt_margin << MARGIN_SHIFT)
972			| (xmt_margin_oe << MARGIN_OVERWRITE_ENABLE_SHIFT)
973			| (lane_delay << LANE_DELAY_SHIFT)
974			| (lane_bundle << LANE_BUNDLE_SHIFT);
975
976		write_csr(dd, CCE_PCIE_CTRL, pcie_ctrl);
977	}
978
979	dd_dev_dbg(dd, "%s: program XMT margin, CcePcieCtrl 0x%llx\n",
980		   fname, pcie_ctrl);
981}
982
983/*
984 * Do all the steps needed to transition the PCIe link to Gen3 speed.
985 */
986int do_pcie_gen3_transition(struct hfi1_devdata *dd)
987{
988	struct pci_dev *parent = dd->pcidev->bus->self;
989	u64 fw_ctrl;
990	u64 reg, therm;
991	u32 reg32, fs, lf;
992	u32 status, err;
993	int ret;
994	int do_retry, retry_count = 0;
995	int intnum = 0;
996	uint default_pset;
997	uint pset = pcie_pset;
998	u16 target_vector, target_speed;
999	u16 lnkctl2, vendor;
1000	u8 div;
1001	const u8 (*eq)[3];
1002	const u8 (*ctle_tunings)[4];
1003	uint static_ctle_mode;
1004	int return_error = 0;
1005	u32 target_width;
1006
1007	/* PCIe Gen3 is for the ASIC only */
1008	if (dd->icode != ICODE_RTL_SILICON)
1009		return 0;
1010
1011	if (pcie_target == 1) {			/* target Gen1 */
1012		target_vector = PCI_EXP_LNKCTL2_TLS_2_5GT;
1013		target_speed = 2500;
1014	} else if (pcie_target == 2) {		/* target Gen2 */
1015		target_vector = PCI_EXP_LNKCTL2_TLS_5_0GT;
1016		target_speed = 5000;
1017	} else if (pcie_target == 3) {		/* target Gen3 */
1018		target_vector = PCI_EXP_LNKCTL2_TLS_8_0GT;
1019		target_speed = 8000;
1020	} else {
1021		/* off or invalid target - skip */
1022		dd_dev_info(dd, "%s: Skipping PCIe transition\n", __func__);
1023		return 0;
1024	}
1025
1026	/* if already at target speed, done (unless forced) */
1027	if (dd->lbus_speed == target_speed) {
1028		dd_dev_info(dd, "%s: PCIe already at gen%d, %s\n", __func__,
1029			    pcie_target,
1030			    pcie_force ? "re-doing anyway" : "skipping");
1031		if (!pcie_force)
1032			return 0;
1033	}
1034
1035	/*
1036	 * The driver cannot do the transition if it has no access to the
1037	 * upstream component
1038	 */
1039	if (!parent) {
1040		dd_dev_info(dd, "%s: No upstream, Can't do gen3 transition\n",
1041			    __func__);
1042		return 0;
1043	}
1044
1045	/* Previous Gen1/Gen2 bus width */
1046	target_width = dd->lbus_width;
1047
1048	/*
1049	 * Do the Gen3 transition.  Steps are those of the PCIe Gen3
1050	 * recipe.
1051	 */
1052
1053	/* step 1: pcie link working in gen1/gen2 */
1054
1055	/* step 2: if either side is not capable of Gen3, done */
1056	if (pcie_target == 3 && !dd->link_gen3_capable) {
1057		dd_dev_err(dd, "The PCIe link is not Gen3 capable\n");
1058		ret = -ENOSYS;
1059		goto done_no_mutex;
1060	}
1061
1062	/* hold the SBus resource across the firmware download and SBR */
1063	ret = acquire_chip_resource(dd, CR_SBUS, SBUS_TIMEOUT);
1064	if (ret) {
1065		dd_dev_err(dd, "%s: unable to acquire SBus resource\n",
1066			   __func__);
1067		return ret;
1068	}
1069
1070	/* make sure thermal polling is not causing interrupts */
1071	therm = read_csr(dd, ASIC_CFG_THERM_POLL_EN);
1072	if (therm) {
1073		write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x0);
1074		msleep(100);
1075		dd_dev_info(dd, "%s: Disabled therm polling\n",
1076			    __func__);
1077	}
1078
1079retry:
1080	/* the SBus download will reset the spico for thermal */
1081
1082	/* step 3: download SBus Master firmware */
1083	/* step 4: download PCIe Gen3 SerDes firmware */
1084	dd_dev_info(dd, "%s: downloading firmware\n", __func__);
1085	ret = load_pcie_firmware(dd);
1086	if (ret) {
1087		/* do not proceed if the firmware cannot be downloaded */
1088		return_error = 1;
1089		goto done;
1090	}
1091
1092	/* step 5: set up device parameter settings */
1093	dd_dev_info(dd, "%s: setting PCIe registers\n", __func__);
1094
1095	/*
1096	 * PcieCfgSpcie1 - Link Control 3
1097	 * Leave at reset value.  No need to set PerfEq - link equalization
1098	 * will be performed automatically after the SBR when the target
1099	 * speed is 8GT/s.
1100	 */
1101
1102	/* clear all 16 per-lane error bits (PCIe: Lane Error Status) */
1103	pci_write_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, 0xffff);
1104
1105	/* step 5a: Set Synopsys Port Logic registers */
1106
1107	/*
1108	 * PcieCfgRegPl2 - Port Force Link
1109	 *
1110	 * Set the low power field to 0x10 to avoid unnecessary power
1111	 * management messages.  All other fields are zero.
1112	 */
1113	reg32 = 0x10ul << PCIE_CFG_REG_PL2_LOW_PWR_ENT_CNT_SHIFT;
1114	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL2, reg32);
1115
1116	/*
1117	 * PcieCfgRegPl100 - Gen3 Control
1118	 *
1119	 * turn off PcieCfgRegPl100.Gen3ZRxDcNonCompl
1120	 * turn on PcieCfgRegPl100.EqEieosCnt
1121	 * Everything else zero.
1122	 */
1123	reg32 = PCIE_CFG_REG_PL100_EQ_EIEOS_CNT_SMASK;
1124	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL100, reg32);
1125
1126	/*
1127	 * PcieCfgRegPl101 - Gen3 EQ FS and LF
1128	 * PcieCfgRegPl102 - Gen3 EQ Presets to Coefficients Mapping
1129	 * PcieCfgRegPl103 - Gen3 EQ Preset Index
1130	 * PcieCfgRegPl105 - Gen3 EQ Status
1131	 *
1132	 * Give initial EQ settings.
1133	 */
1134	if (dd->pcidev->device == PCI_DEVICE_ID_INTEL0) { /* discrete */
1135		/* 1000mV, FS=24, LF = 8 */
1136		fs = 24;
1137		lf = 8;
1138		div = 3;
1139		eq = discrete_preliminary_eq;
1140		default_pset = DEFAULT_DISCRETE_PSET;
1141		ctle_tunings = discrete_ctle_tunings;
1142		/* bit 0 - discrete on/off */
1143		static_ctle_mode = pcie_ctle & 0x1;
1144	} else {
1145		/* 400mV, FS=29, LF = 9 */
1146		fs = 29;
1147		lf = 9;
1148		div = 1;
1149		eq = integrated_preliminary_eq;
1150		default_pset = DEFAULT_MCP_PSET;
1151		ctle_tunings = integrated_ctle_tunings;
1152		/* bit 1 - integrated on/off */
1153		static_ctle_mode = (pcie_ctle >> 1) & 0x1;
1154	}
1155	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL101,
1156			       (fs <<
1157				PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_FS_SHIFT) |
1158			       (lf <<
1159				PCIE_CFG_REG_PL101_GEN3_EQ_LOCAL_LF_SHIFT));
1160	ret = load_eq_table(dd, eq, fs, div);
1161	if (ret)
1162		goto done;
1163
1164	/*
1165	 * PcieCfgRegPl106 - Gen3 EQ Control
1166	 *
1167	 * Set Gen3EqPsetReqVec, leave other fields 0.
1168	 */
1169	if (pset == UNSET_PSET)
1170		pset = default_pset;
1171	if (pset > 10) {	/* valid range is 0-10, inclusive */
1172		dd_dev_err(dd, "%s: Invalid Eq Pset %u, setting to %d\n",
1173			   __func__, pset, default_pset);
1174		pset = default_pset;
1175	}
1176	dd_dev_info(dd, "%s: using EQ Pset %u\n", __func__, pset);
1177	pci_write_config_dword(dd->pcidev, PCIE_CFG_REG_PL106,
1178			       ((1 << pset) <<
1179			PCIE_CFG_REG_PL106_GEN3_EQ_PSET_REQ_VEC_SHIFT) |
1180			PCIE_CFG_REG_PL106_GEN3_EQ_EVAL2MS_DISABLE_SMASK |
1181			PCIE_CFG_REG_PL106_GEN3_EQ_PHASE23_EXIT_MODE_SMASK);
1182
1183	/*
1184	 * step 5b: Do post firmware download steps via SBus
1185	 */
1186	dd_dev_info(dd, "%s: doing pcie post steps\n", __func__);
1187	pcie_post_steps(dd);
1188
1189	/*
1190	 * step 5c: Program gasket interrupts
1191	 */
1192	/* set the Rx Bit Rate to REFCLK ratio */
1193	write_gasket_interrupt(dd, intnum++, 0x0006, 0x0050);
1194	/* disable pCal for PCIe Gen3 RX equalization */
1195	/* select adaptive or static CTLE */
1196	write_gasket_interrupt(dd, intnum++, 0x0026,
1197			       0x5b01 | (static_ctle_mode << 3));
1198	/*
1199	 * Enable iCal for PCIe Gen3 RX equalization, and set which
1200	 * evaluation of RX_EQ_EVAL will launch the iCal procedure.
1201	 */
1202	write_gasket_interrupt(dd, intnum++, 0x0026, 0x5202);
1203
1204	if (static_ctle_mode) {
1205		/* apply static CTLE tunings */
1206		u8 pcie_dc, pcie_lf, pcie_hf, pcie_bw;
1207
1208		pcie_dc = ctle_tunings[pset][0];
1209		pcie_lf = ctle_tunings[pset][1];
1210		pcie_hf = ctle_tunings[pset][2];
1211		pcie_bw = ctle_tunings[pset][3];
1212		write_gasket_interrupt(dd, intnum++, 0x0026, 0x0200 | pcie_dc);
1213		write_gasket_interrupt(dd, intnum++, 0x0026, 0x0100 | pcie_lf);
1214		write_gasket_interrupt(dd, intnum++, 0x0026, 0x0000 | pcie_hf);
1215		write_gasket_interrupt(dd, intnum++, 0x0026, 0x5500 | pcie_bw);
1216	}
1217
1218	/* terminate list */
1219	write_gasket_interrupt(dd, intnum++, 0x0000, 0x0000);
1220
1221	/*
1222	 * step 5d: program XMT margin
1223	 */
1224	write_xmt_margin(dd, __func__);
1225
1226	/*
1227	 * step 5e: disable active state power management (ASPM). It
1228	 * will be enabled if required later
1229	 */
1230	dd_dev_info(dd, "%s: clearing ASPM\n", __func__);
1231	aspm_hw_disable_l1(dd);
1232
1233	/*
1234	 * step 5f: clear DirectSpeedChange
1235	 * PcieCfgRegPl67.DirectSpeedChange must be zero to prevent the
1236	 * change in the speed target from starting before we are ready.
1237	 * This field defaults to 0 and we are not changing it, so nothing
1238	 * needs to be done.
1239	 */
1240
1241	/* step 5g: Set target link speed */
1242	/*
1243	 * Set target link speed to be target on both device and parent.
1244	 * On setting the parent: Some system BIOSs "helpfully" set the
1245	 * parent target speed to Gen2 to match the ASIC's initial speed.
1246	 * We can set the target Gen3 because we have already checked
1247	 * that it is Gen3 capable earlier.
1248	 */
1249	dd_dev_info(dd, "%s: setting parent target link speed\n", __func__);
1250	ret = pcie_capability_read_word(parent, PCI_EXP_LNKCTL2, &lnkctl2);
1251	if (ret) {
1252		dd_dev_err(dd, "Unable to read from PCI config\n");
1253		return_error = 1;
1254		goto done;
1255	}
1256
1257	dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
1258		    (u32)lnkctl2);
1259	/* only write to parent if target is not as high as ours */
1260	if ((lnkctl2 & PCI_EXP_LNKCTL2_TLS) < target_vector) {
1261		lnkctl2 &= ~PCI_EXP_LNKCTL2_TLS;
1262		lnkctl2 |= target_vector;
1263		dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
1264			    (u32)lnkctl2);
1265		ret = pcie_capability_write_word(parent,
1266						 PCI_EXP_LNKCTL2, lnkctl2);
1267		if (ret) {
1268			dd_dev_err(dd, "Unable to write to PCI config\n");
1269			return_error = 1;
1270			goto done;
1271		}
1272	} else {
1273		dd_dev_info(dd, "%s: ..target speed is OK\n", __func__);
1274	}
1275
1276	dd_dev_info(dd, "%s: setting target link speed\n", __func__);
1277	ret = pcie_capability_read_word(dd->pcidev, PCI_EXP_LNKCTL2, &lnkctl2);
1278	if (ret) {
1279		dd_dev_err(dd, "Unable to read from PCI config\n");
1280		return_error = 1;
1281		goto done;
1282	}
1283
1284	dd_dev_info(dd, "%s: ..old link control2: 0x%x\n", __func__,
1285		    (u32)lnkctl2);
1286	lnkctl2 &= ~PCI_EXP_LNKCTL2_TLS;
1287	lnkctl2 |= target_vector;
1288	dd_dev_info(dd, "%s: ..new link control2: 0x%x\n", __func__,
1289		    (u32)lnkctl2);
1290	ret = pcie_capability_write_word(dd->pcidev, PCI_EXP_LNKCTL2, lnkctl2);
1291	if (ret) {
1292		dd_dev_err(dd, "Unable to write to PCI config\n");
1293		return_error = 1;
1294		goto done;
1295	}
1296
1297	/* step 5h: arm gasket logic */
1298	/* hold DC in reset across the SBR */
1299	write_csr(dd, CCE_DC_CTRL, CCE_DC_CTRL_DC_RESET_SMASK);
1300	(void)read_csr(dd, CCE_DC_CTRL); /* DC reset hold */
1301	/* save firmware control across the SBR */
1302	fw_ctrl = read_csr(dd, MISC_CFG_FW_CTRL);
1303
1304	dd_dev_info(dd, "%s: arming gasket logic\n", __func__);
1305	arm_gasket_logic(dd);
1306
1307	/*
1308	 * step 6: quiesce PCIe link
1309	 * The chip has already been reset, so there will be no traffic
1310	 * from the chip.  Linux has no easy way to enforce that it will
1311	 * not try to access the device, so we just need to hope it doesn't
1312	 * do it while we are doing the reset.
1313	 */
1314
1315	/*
1316	 * step 7: initiate the secondary bus reset (SBR)
1317	 * step 8: hardware brings the links back up
1318	 * step 9: wait for link speed transition to be complete
1319	 */
1320	dd_dev_info(dd, "%s: calling trigger_sbr\n", __func__);
1321	ret = trigger_sbr(dd);
1322	if (ret)
1323		goto done;
1324
1325	/* step 10: decide what to do next */
1326
1327	/* check if we can read PCI space */
1328	ret = pci_read_config_word(dd->pcidev, PCI_VENDOR_ID, &vendor);
1329	if (ret) {
1330		dd_dev_info(dd,
1331			    "%s: read of VendorID failed after SBR, err %d\n",
1332			    __func__, ret);
1333		return_error = 1;
1334		goto done;
1335	}
1336	if (vendor == 0xffff) {
1337		dd_dev_info(dd, "%s: VendorID is all 1s after SBR\n", __func__);
1338		return_error = 1;
1339		ret = -EIO;
1340		goto done;
1341	}
1342
1343	/* restore PCI space registers we know were reset */
1344	dd_dev_info(dd, "%s: calling restore_pci_variables\n", __func__);
1345	ret = restore_pci_variables(dd);
1346	if (ret) {
1347		dd_dev_err(dd, "%s: Could not restore PCI variables\n",
1348			   __func__);
1349		return_error = 1;
1350		goto done;
1351	}
1352
1353	/* restore firmware control */
1354	write_csr(dd, MISC_CFG_FW_CTRL, fw_ctrl);
1355
1356	/*
1357	 * Check the gasket block status.
1358	 *
1359	 * This is the first CSR read after the SBR.  If the read returns
1360	 * all 1s (fails), the link did not make it back.
1361	 *
1362	 * Once we're sure we can read and write, clear the DC reset after
1363	 * the SBR.  Then check for any per-lane errors. Then look over
1364	 * the status.
1365	 */
1366	reg = read_csr(dd, ASIC_PCIE_SD_HOST_STATUS);
1367	dd_dev_info(dd, "%s: gasket block status: 0x%llx\n", __func__, reg);
1368	if (reg == ~0ull) {	/* PCIe read failed/timeout */
1369		dd_dev_err(dd, "SBR failed - unable to read from device\n");
1370		return_error = 1;
1371		ret = -ENOSYS;
1372		goto done;
1373	}
1374
1375	/* clear the DC reset */
1376	write_csr(dd, CCE_DC_CTRL, 0);
1377
1378	/* Set the LED off */
1379	setextled(dd, 0);
1380
1381	/* check for any per-lane errors */
1382	ret = pci_read_config_dword(dd->pcidev, PCIE_CFG_SPCIE2, &reg32);
1383	if (ret) {
1384		dd_dev_err(dd, "Unable to read from PCI config\n");
1385		return_error = 1;
1386		goto done;
1387	}
1388
1389	dd_dev_info(dd, "%s: per-lane errors: 0x%x\n", __func__, reg32);
1390
1391	/* extract status, look for our HFI */
1392	status = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_SHIFT)
1393			& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_STS_MASK;
1394	if ((status & (1 << dd->hfi1_id)) == 0) {
1395		dd_dev_err(dd,
1396			   "%s: gasket status 0x%x, expecting 0x%x\n",
1397			   __func__, status, 1 << dd->hfi1_id);
1398		ret = -EIO;
1399		goto done;
1400	}
1401
1402	/* extract error */
1403	err = (reg >> ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_SHIFT)
1404		& ASIC_PCIE_SD_HOST_STATUS_FW_DNLD_ERR_MASK;
1405	if (err) {
1406		dd_dev_err(dd, "%s: gasket error %d\n", __func__, err);
1407		ret = -EIO;
1408		goto done;
1409	}
1410
1411	/* update our link information cache */
1412	update_lbus_info(dd);
1413	dd_dev_info(dd, "%s: new speed and width: %s\n", __func__,
1414		    dd->lbus_info);
1415
1416	if (dd->lbus_speed != target_speed ||
1417	    dd->lbus_width < target_width) { /* not target */
1418		/* maybe retry */
1419		do_retry = retry_count < pcie_retry;
1420		dd_dev_err(dd, "PCIe link speed or width did not match target%s\n",
1421			   do_retry ? ", retrying" : "");
1422		retry_count++;
1423		if (do_retry) {
1424			msleep(100); /* allow time to settle */
1425			goto retry;
1426		}
1427		ret = -EIO;
1428	}
1429
1430done:
1431	if (therm) {
1432		write_csr(dd, ASIC_CFG_THERM_POLL_EN, 0x1);
1433		msleep(100);
1434		dd_dev_info(dd, "%s: Re-enable therm polling\n",
1435			    __func__);
1436	}
1437	release_chip_resource(dd, CR_SBUS);
1438done_no_mutex:
1439	/* return no error if it is OK to be at current speed */
1440	if (ret && !return_error) {
1441		dd_dev_err(dd, "Proceeding at current speed PCIe speed\n");
1442		ret = 0;
1443	}
1444
1445	dd_dev_info(dd, "%s: done\n", __func__);
1446	return ret;
1447}
1448