xref: /freebsd/sys/contrib/dev/iwlwifi/pcie/trans.c (revision d27ba3088424e53eabc0b0186ed122ec43119501)
1 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2 /*
3  * Copyright (C) 2007-2015, 2018-2020 Intel Corporation
4  * Copyright (C) 2013-2015 Intel Mobile Communications GmbH
5  * Copyright (C) 2016-2017 Intel Deutschland GmbH
6  */
7 #include <linux/pci.h>
8 #include <linux/interrupt.h>
9 #include <linux/debugfs.h>
10 #include <linux/sched.h>
11 #include <linux/bitops.h>
12 #include <linux/gfp.h>
13 #include <linux/vmalloc.h>
14 #include <linux/module.h>
15 #include <linux/wait.h>
16 #include <linux/seq_file.h>
17 #if defined(__FreeBSD__)
18 #include <linux/delay.h>
19 #endif
20 
21 #include "iwl-drv.h"
22 #include "iwl-trans.h"
23 #include "iwl-csr.h"
24 #include "iwl-prph.h"
25 #include "iwl-scd.h"
26 #include "iwl-agn-hw.h"
27 #include "fw/error-dump.h"
28 #include "fw/dbg.h"
29 #include "fw/api/tx.h"
30 #include "internal.h"
31 #include "iwl-fh.h"
32 #include "iwl-context-info-gen3.h"
33 
34 /* extended range in FW SRAM */
35 #define IWL_FW_MEM_EXTENDED_START	0x40000
36 #define IWL_FW_MEM_EXTENDED_END		0x57FFF
37 
38 void iwl_trans_pcie_dump_regs(struct iwl_trans *trans)
39 {
40 #define PCI_DUMP_SIZE		352
41 #define PCI_MEM_DUMP_SIZE	64
42 #define PCI_PARENT_DUMP_SIZE	524
43 #define PREFIX_LEN		32
44 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
45 	struct pci_dev *pdev = trans_pcie->pci_dev;
46 	u32 i, pos, alloc_size, *ptr, *buf;
47 	char *prefix;
48 
49 	if (trans_pcie->pcie_dbg_dumped_once)
50 		return;
51 
52 	/* Should be a multiple of 4 */
53 	BUILD_BUG_ON(PCI_DUMP_SIZE > 4096 || PCI_DUMP_SIZE & 0x3);
54 	BUILD_BUG_ON(PCI_MEM_DUMP_SIZE > 4096 || PCI_MEM_DUMP_SIZE & 0x3);
55 	BUILD_BUG_ON(PCI_PARENT_DUMP_SIZE > 4096 || PCI_PARENT_DUMP_SIZE & 0x3);
56 
57 	/* Alloc a max size buffer */
58 	alloc_size = PCI_ERR_ROOT_ERR_SRC +  4 + PREFIX_LEN;
59 	alloc_size = max_t(u32, alloc_size, PCI_DUMP_SIZE + PREFIX_LEN);
60 	alloc_size = max_t(u32, alloc_size, PCI_MEM_DUMP_SIZE + PREFIX_LEN);
61 	alloc_size = max_t(u32, alloc_size, PCI_PARENT_DUMP_SIZE + PREFIX_LEN);
62 
63 	buf = kmalloc(alloc_size, GFP_ATOMIC);
64 	if (!buf)
65 		return;
66 	prefix = (char *)buf + alloc_size - PREFIX_LEN;
67 
68 	IWL_ERR(trans, "iwlwifi transaction failed, dumping registers\n");
69 
70 	/* Print wifi device registers */
71 	sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
72 	IWL_ERR(trans, "iwlwifi device config registers:\n");
73 	for (i = 0, ptr = buf; i < PCI_DUMP_SIZE; i += 4, ptr++)
74 		if (pci_read_config_dword(pdev, i, ptr))
75 			goto err_read;
76 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
77 
78 	IWL_ERR(trans, "iwlwifi device memory mapped registers:\n");
79 	for (i = 0, ptr = buf; i < PCI_MEM_DUMP_SIZE; i += 4, ptr++)
80 		*ptr = iwl_read32(trans, i);
81 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
82 
83 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR);
84 	if (pos) {
85 		IWL_ERR(trans, "iwlwifi device AER capability structure:\n");
86 		for (i = 0, ptr = buf; i < PCI_ERR_ROOT_COMMAND; i += 4, ptr++)
87 			if (pci_read_config_dword(pdev, pos + i, ptr))
88 				goto err_read;
89 		iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
90 	}
91 
92 	/* Print parent device registers next */
93 	if (!pdev->bus->self)
94 		goto out;
95 
96 	pdev = pdev->bus->self;
97 	sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
98 
99 	IWL_ERR(trans, "iwlwifi parent port (%s) config registers:\n",
100 		pci_name(pdev));
101 	for (i = 0, ptr = buf; i < PCI_PARENT_DUMP_SIZE; i += 4, ptr++)
102 		if (pci_read_config_dword(pdev, i, ptr))
103 			goto err_read;
104 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
105 
106 	/* Print root port AER registers */
107 	pos = 0;
108 	pdev = pcie_find_root_port(pdev);
109 	if (pdev)
110 		pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR);
111 	if (pos) {
112 		IWL_ERR(trans, "iwlwifi root port (%s) AER cap structure:\n",
113 			pci_name(pdev));
114 		sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
115 		for (i = 0, ptr = buf; i <= PCI_ERR_ROOT_ERR_SRC; i += 4, ptr++)
116 			if (pci_read_config_dword(pdev, pos + i, ptr))
117 				goto err_read;
118 		iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
119 	}
120 	goto out;
121 
122 err_read:
123 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
124 	IWL_ERR(trans, "Read failed at 0x%X\n", i);
125 out:
126 	trans_pcie->pcie_dbg_dumped_once = 1;
127 	kfree(buf);
128 }
129 
130 static void iwl_trans_pcie_sw_reset(struct iwl_trans *trans)
131 {
132 	/* Reset entire device - do controller reset (results in SHRD_HW_RST) */
133 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
134 		iwl_set_bit(trans, CSR_GP_CNTRL,
135 			    CSR_GP_CNTRL_REG_FLAG_SW_RESET);
136 	else
137 		iwl_set_bit(trans, CSR_RESET,
138 			    CSR_RESET_REG_FLAG_SW_RESET);
139 	usleep_range(5000, 6000);
140 }
141 
142 static void iwl_pcie_free_fw_monitor(struct iwl_trans *trans)
143 {
144 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
145 
146 	if (!fw_mon->size)
147 		return;
148 
149 	dma_free_coherent(trans->dev, fw_mon->size, fw_mon->block,
150 			  fw_mon->physical);
151 
152 	fw_mon->block = NULL;
153 	fw_mon->physical = 0;
154 	fw_mon->size = 0;
155 }
156 
157 static void iwl_pcie_alloc_fw_monitor_block(struct iwl_trans *trans,
158 					    u8 max_power, u8 min_power)
159 {
160 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
161 	void *block = NULL;
162 	dma_addr_t physical = 0;
163 	u32 size = 0;
164 	u8 power;
165 
166 	if (fw_mon->size)
167 		return;
168 
169 	for (power = max_power; power >= min_power; power--) {
170 		size = BIT(power);
171 		block = dma_alloc_coherent(trans->dev, size, &physical,
172 					   GFP_KERNEL | __GFP_NOWARN);
173 		if (!block)
174 			continue;
175 
176 		IWL_INFO(trans,
177 			 "Allocated 0x%08x bytes for firmware monitor.\n",
178 			 size);
179 		break;
180 	}
181 
182 	if (WARN_ON_ONCE(!block))
183 		return;
184 
185 	if (power != max_power)
186 		IWL_ERR(trans,
187 			"Sorry - debug buffer is only %luK while you requested %luK\n",
188 			(unsigned long)BIT(power - 10),
189 			(unsigned long)BIT(max_power - 10));
190 
191 	fw_mon->block = block;
192 	fw_mon->physical = physical;
193 	fw_mon->size = size;
194 }
195 
196 void iwl_pcie_alloc_fw_monitor(struct iwl_trans *trans, u8 max_power)
197 {
198 	if (!max_power) {
199 		/* default max_power is maximum */
200 		max_power = 26;
201 	} else {
202 		max_power += 11;
203 	}
204 
205 	if (WARN(max_power > 26,
206 		 "External buffer size for monitor is too big %d, check the FW TLV\n",
207 		 max_power))
208 		return;
209 
210 	if (trans->dbg.fw_mon.size)
211 		return;
212 
213 	iwl_pcie_alloc_fw_monitor_block(trans, max_power, 11);
214 }
215 
216 static u32 iwl_trans_pcie_read_shr(struct iwl_trans *trans, u32 reg)
217 {
218 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_CTRL_REG,
219 		    ((reg & 0x0000ffff) | (2 << 28)));
220 	return iwl_read32(trans, HEEP_CTRL_WRD_PCIEX_DATA_REG);
221 }
222 
223 static void iwl_trans_pcie_write_shr(struct iwl_trans *trans, u32 reg, u32 val)
224 {
225 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_DATA_REG, val);
226 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_CTRL_REG,
227 		    ((reg & 0x0000ffff) | (3 << 28)));
228 }
229 
230 static void iwl_pcie_set_pwr(struct iwl_trans *trans, bool vaux)
231 {
232 	if (trans->cfg->apmg_not_supported)
233 		return;
234 
235 	if (vaux && pci_pme_capable(to_pci_dev(trans->dev), PCI_D3cold))
236 		iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG,
237 				       APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
238 				       ~APMG_PS_CTRL_MSK_PWR_SRC);
239 	else
240 		iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG,
241 				       APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
242 				       ~APMG_PS_CTRL_MSK_PWR_SRC);
243 }
244 
245 /* PCI registers */
246 #define PCI_CFG_RETRY_TIMEOUT	0x041
247 
248 void iwl_pcie_apm_config(struct iwl_trans *trans)
249 {
250 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
251 	u16 lctl;
252 	u16 cap;
253 
254 	/*
255 	 * L0S states have been found to be unstable with our devices
256 	 * and in newer hardware they are not officially supported at
257 	 * all, so we must always set the L0S_DISABLED bit.
258 	 */
259 	iwl_set_bit(trans, CSR_GIO_REG, CSR_GIO_REG_VAL_L0S_DISABLED);
260 
261 	pcie_capability_read_word(trans_pcie->pci_dev, PCI_EXP_LNKCTL, &lctl);
262 	trans->pm_support = !(lctl & PCI_EXP_LNKCTL_ASPM_L0S);
263 
264 	pcie_capability_read_word(trans_pcie->pci_dev, PCI_EXP_DEVCTL2, &cap);
265 	trans->ltr_enabled = cap & PCI_EXP_DEVCTL2_LTR_EN;
266 	IWL_DEBUG_POWER(trans, "L1 %sabled - LTR %sabled\n",
267 			(lctl & PCI_EXP_LNKCTL_ASPM_L1) ? "En" : "Dis",
268 			trans->ltr_enabled ? "En" : "Dis");
269 }
270 
271 /*
272  * Start up NIC's basic functionality after it has been reset
273  * (e.g. after platform boot, or shutdown via iwl_pcie_apm_stop())
274  * NOTE:  This does not load uCode nor start the embedded processor
275  */
276 static int iwl_pcie_apm_init(struct iwl_trans *trans)
277 {
278 	int ret;
279 
280 	IWL_DEBUG_INFO(trans, "Init card's basic functions\n");
281 
282 	/*
283 	 * Use "set_bit" below rather than "write", to preserve any hardware
284 	 * bits already set by default after reset.
285 	 */
286 
287 	/* Disable L0S exit timer (platform NMI Work/Around) */
288 	if (trans->trans_cfg->device_family < IWL_DEVICE_FAMILY_8000)
289 		iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS,
290 			    CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
291 
292 	/*
293 	 * Disable L0s without affecting L1;
294 	 *  don't wait for ICH L0s (ICH bug W/A)
295 	 */
296 	iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS,
297 		    CSR_GIO_CHICKEN_BITS_REG_BIT_L1A_NO_L0S_RX);
298 
299 	/* Set FH wait threshold to maximum (HW error during stress W/A) */
300 	iwl_set_bit(trans, CSR_DBG_HPET_MEM_REG, CSR_DBG_HPET_MEM_REG_VAL);
301 
302 	/*
303 	 * Enable HAP INTA (interrupt from management bus) to
304 	 * wake device's PCI Express link L1a -> L0s
305 	 */
306 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
307 		    CSR_HW_IF_CONFIG_REG_BIT_HAP_WAKE_L1A);
308 
309 	iwl_pcie_apm_config(trans);
310 
311 	/* Configure analog phase-lock-loop before activating to D0A */
312 	if (trans->trans_cfg->base_params->pll_cfg)
313 		iwl_set_bit(trans, CSR_ANA_PLL_CFG, CSR50_ANA_PLL_CFG_VAL);
314 
315 	ret = iwl_finish_nic_init(trans);
316 	if (ret)
317 		return ret;
318 
319 	if (trans->cfg->host_interrupt_operation_mode) {
320 		/*
321 		 * This is a bit of an abuse - This is needed for 7260 / 3160
322 		 * only check host_interrupt_operation_mode even if this is
323 		 * not related to host_interrupt_operation_mode.
324 		 *
325 		 * Enable the oscillator to count wake up time for L1 exit. This
326 		 * consumes slightly more power (100uA) - but allows to be sure
327 		 * that we wake up from L1 on time.
328 		 *
329 		 * This looks weird: read twice the same register, discard the
330 		 * value, set a bit, and yet again, read that same register
331 		 * just to discard the value. But that's the way the hardware
332 		 * seems to like it.
333 		 */
334 		iwl_read_prph(trans, OSC_CLK);
335 		iwl_read_prph(trans, OSC_CLK);
336 		iwl_set_bits_prph(trans, OSC_CLK, OSC_CLK_FORCE_CONTROL);
337 		iwl_read_prph(trans, OSC_CLK);
338 		iwl_read_prph(trans, OSC_CLK);
339 	}
340 
341 	/*
342 	 * Enable DMA clock and wait for it to stabilize.
343 	 *
344 	 * Write to "CLK_EN_REG"; "1" bits enable clocks, while "0"
345 	 * bits do not disable clocks.  This preserves any hardware
346 	 * bits already set by default in "CLK_CTRL_REG" after reset.
347 	 */
348 	if (!trans->cfg->apmg_not_supported) {
349 		iwl_write_prph(trans, APMG_CLK_EN_REG,
350 			       APMG_CLK_VAL_DMA_CLK_RQT);
351 		udelay(20);
352 
353 		/* Disable L1-Active */
354 		iwl_set_bits_prph(trans, APMG_PCIDEV_STT_REG,
355 				  APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
356 
357 		/* Clear the interrupt in APMG if the NIC is in RFKILL */
358 		iwl_write_prph(trans, APMG_RTC_INT_STT_REG,
359 			       APMG_RTC_INT_STT_RFKILL);
360 	}
361 
362 	set_bit(STATUS_DEVICE_ENABLED, &trans->status);
363 
364 	return 0;
365 }
366 
367 /*
368  * Enable LP XTAL to avoid HW bug where device may consume much power if
369  * FW is not loaded after device reset. LP XTAL is disabled by default
370  * after device HW reset. Do it only if XTAL is fed by internal source.
371  * Configure device's "persistence" mode to avoid resetting XTAL again when
372  * SHRD_HW_RST occurs in S3.
373  */
374 static void iwl_pcie_apm_lp_xtal_enable(struct iwl_trans *trans)
375 {
376 	int ret;
377 	u32 apmg_gp1_reg;
378 	u32 apmg_xtal_cfg_reg;
379 	u32 dl_cfg_reg;
380 
381 	/* Force XTAL ON */
382 	__iwl_trans_pcie_set_bit(trans, CSR_GP_CNTRL,
383 				 CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
384 
385 	iwl_trans_pcie_sw_reset(trans);
386 
387 	ret = iwl_finish_nic_init(trans);
388 	if (WARN_ON(ret)) {
389 		/* Release XTAL ON request */
390 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
391 					   CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
392 		return;
393 	}
394 
395 	/*
396 	 * Clear "disable persistence" to avoid LP XTAL resetting when
397 	 * SHRD_HW_RST is applied in S3.
398 	 */
399 	iwl_clear_bits_prph(trans, APMG_PCIDEV_STT_REG,
400 				    APMG_PCIDEV_STT_VAL_PERSIST_DIS);
401 
402 	/*
403 	 * Force APMG XTAL to be active to prevent its disabling by HW
404 	 * caused by APMG idle state.
405 	 */
406 	apmg_xtal_cfg_reg = iwl_trans_pcie_read_shr(trans,
407 						    SHR_APMG_XTAL_CFG_REG);
408 	iwl_trans_pcie_write_shr(trans, SHR_APMG_XTAL_CFG_REG,
409 				 apmg_xtal_cfg_reg |
410 				 SHR_APMG_XTAL_CFG_XTAL_ON_REQ);
411 
412 	iwl_trans_pcie_sw_reset(trans);
413 
414 	/* Enable LP XTAL by indirect access through CSR */
415 	apmg_gp1_reg = iwl_trans_pcie_read_shr(trans, SHR_APMG_GP1_REG);
416 	iwl_trans_pcie_write_shr(trans, SHR_APMG_GP1_REG, apmg_gp1_reg |
417 				 SHR_APMG_GP1_WF_XTAL_LP_EN |
418 				 SHR_APMG_GP1_CHICKEN_BIT_SELECT);
419 
420 	/* Clear delay line clock power up */
421 	dl_cfg_reg = iwl_trans_pcie_read_shr(trans, SHR_APMG_DL_CFG_REG);
422 	iwl_trans_pcie_write_shr(trans, SHR_APMG_DL_CFG_REG, dl_cfg_reg &
423 				 ~SHR_APMG_DL_CFG_DL_CLOCK_POWER_UP);
424 
425 	/*
426 	 * Enable persistence mode to avoid LP XTAL resetting when
427 	 * SHRD_HW_RST is applied in S3.
428 	 */
429 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
430 		    CSR_HW_IF_CONFIG_REG_PERSIST_MODE);
431 
432 	/*
433 	 * Clear "initialization complete" bit to move adapter from
434 	 * D0A* (powered-up Active) --> D0U* (Uninitialized) state.
435 	 */
436 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
437 
438 	/* Activates XTAL resources monitor */
439 	__iwl_trans_pcie_set_bit(trans, CSR_MONITOR_CFG_REG,
440 				 CSR_MONITOR_XTAL_RESOURCES);
441 
442 	/* Release XTAL ON request */
443 	__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
444 				   CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
445 	udelay(10);
446 
447 	/* Release APMG XTAL */
448 	iwl_trans_pcie_write_shr(trans, SHR_APMG_XTAL_CFG_REG,
449 				 apmg_xtal_cfg_reg &
450 				 ~SHR_APMG_XTAL_CFG_XTAL_ON_REQ);
451 }
452 
453 void iwl_pcie_apm_stop_master(struct iwl_trans *trans)
454 {
455 	int ret;
456 
457 	/* stop device's busmaster DMA activity */
458 
459 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ) {
460 		iwl_set_bit(trans, CSR_GP_CNTRL,
461 			    CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_REQ);
462 
463 		ret = iwl_poll_bit(trans, CSR_GP_CNTRL,
464 				   CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_STATUS,
465 				   CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_STATUS,
466 				   100);
467 		msleep(100);
468 	} else {
469 		iwl_set_bit(trans, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
470 
471 		ret = iwl_poll_bit(trans, CSR_RESET,
472 				   CSR_RESET_REG_FLAG_MASTER_DISABLED,
473 				   CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
474 	}
475 
476 	if (ret < 0)
477 		IWL_WARN(trans, "Master Disable Timed Out, 100 usec\n");
478 
479 	IWL_DEBUG_INFO(trans, "stop master\n");
480 }
481 
482 static void iwl_pcie_apm_stop(struct iwl_trans *trans, bool op_mode_leave)
483 {
484 	IWL_DEBUG_INFO(trans, "Stop card, put in low power state\n");
485 
486 	if (op_mode_leave) {
487 		if (!test_bit(STATUS_DEVICE_ENABLED, &trans->status))
488 			iwl_pcie_apm_init(trans);
489 
490 		/* inform ME that we are leaving */
491 		if (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_7000)
492 			iwl_set_bits_prph(trans, APMG_PCIDEV_STT_REG,
493 					  APMG_PCIDEV_STT_VAL_WAKE_ME);
494 		else if (trans->trans_cfg->device_family >=
495 			 IWL_DEVICE_FAMILY_8000) {
496 			iwl_set_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
497 				    CSR_RESET_LINK_PWR_MGMT_DISABLED);
498 			iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
499 				    CSR_HW_IF_CONFIG_REG_PREPARE |
500 				    CSR_HW_IF_CONFIG_REG_ENABLE_PME);
501 			mdelay(1);
502 			iwl_clear_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
503 				      CSR_RESET_LINK_PWR_MGMT_DISABLED);
504 		}
505 		mdelay(5);
506 	}
507 
508 	clear_bit(STATUS_DEVICE_ENABLED, &trans->status);
509 
510 	/* Stop device's DMA activity */
511 	iwl_pcie_apm_stop_master(trans);
512 
513 	if (trans->cfg->lp_xtal_workaround) {
514 		iwl_pcie_apm_lp_xtal_enable(trans);
515 		return;
516 	}
517 
518 	iwl_trans_pcie_sw_reset(trans);
519 
520 	/*
521 	 * Clear "initialization complete" bit to move adapter from
522 	 * D0A* (powered-up Active) --> D0U* (Uninitialized) state.
523 	 */
524 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
525 }
526 
527 static int iwl_pcie_nic_init(struct iwl_trans *trans)
528 {
529 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
530 	int ret;
531 
532 	/* nic_init */
533 	spin_lock_bh(&trans_pcie->irq_lock);
534 	ret = iwl_pcie_apm_init(trans);
535 	spin_unlock_bh(&trans_pcie->irq_lock);
536 
537 	if (ret)
538 		return ret;
539 
540 	iwl_pcie_set_pwr(trans, false);
541 
542 	iwl_op_mode_nic_config(trans->op_mode);
543 
544 	/* Allocate the RX queue, or reset if it is already allocated */
545 	ret = iwl_pcie_rx_init(trans);
546 	if (ret)
547 		return ret;
548 
549 	/* Allocate or reset and init all Tx and Command queues */
550 	if (iwl_pcie_tx_init(trans)) {
551 		iwl_pcie_rx_free(trans);
552 		return -ENOMEM;
553 	}
554 
555 	if (trans->trans_cfg->base_params->shadow_reg_enable) {
556 		/* enable shadow regs in HW */
557 		iwl_set_bit(trans, CSR_MAC_SHADOW_REG_CTRL, 0x800FFFFF);
558 		IWL_DEBUG_INFO(trans, "Enabling shadow registers in device\n");
559 	}
560 
561 	return 0;
562 }
563 
564 #define HW_READY_TIMEOUT (50)
565 
566 /* Note: returns poll_bit return value, which is >= 0 if success */
567 static int iwl_pcie_set_hw_ready(struct iwl_trans *trans)
568 {
569 	int ret;
570 
571 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
572 		    CSR_HW_IF_CONFIG_REG_BIT_NIC_READY);
573 
574 	/* See if we got it */
575 	ret = iwl_poll_bit(trans, CSR_HW_IF_CONFIG_REG,
576 			   CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
577 			   CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
578 			   HW_READY_TIMEOUT);
579 
580 	if (ret >= 0)
581 		iwl_set_bit(trans, CSR_MBOX_SET_REG, CSR_MBOX_SET_REG_OS_ALIVE);
582 
583 	IWL_DEBUG_INFO(trans, "hardware%s ready\n", ret < 0 ? " not" : "");
584 	return ret;
585 }
586 
587 /* Note: returns standard 0/-ERROR code */
588 int iwl_pcie_prepare_card_hw(struct iwl_trans *trans)
589 {
590 	int ret;
591 	int t = 0;
592 	int iter;
593 
594 	IWL_DEBUG_INFO(trans, "iwl_trans_prepare_card_hw enter\n");
595 
596 	ret = iwl_pcie_set_hw_ready(trans);
597 	/* If the card is ready, exit 0 */
598 	if (ret >= 0)
599 		return 0;
600 
601 	iwl_set_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
602 		    CSR_RESET_LINK_PWR_MGMT_DISABLED);
603 	usleep_range(1000, 2000);
604 
605 	for (iter = 0; iter < 10; iter++) {
606 		/* If HW is not ready, prepare the conditions to check again */
607 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
608 			    CSR_HW_IF_CONFIG_REG_PREPARE);
609 
610 		do {
611 			ret = iwl_pcie_set_hw_ready(trans);
612 			if (ret >= 0)
613 				return 0;
614 
615 			usleep_range(200, 1000);
616 			t += 200;
617 		} while (t < 150000);
618 		msleep(25);
619 	}
620 
621 	IWL_ERR(trans, "Couldn't prepare the card\n");
622 
623 	return ret;
624 }
625 
626 /*
627  * ucode
628  */
629 static void iwl_pcie_load_firmware_chunk_fh(struct iwl_trans *trans,
630 					    u32 dst_addr, dma_addr_t phy_addr,
631 					    u32 byte_cnt)
632 {
633 	iwl_write32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL),
634 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE);
635 
636 	iwl_write32(trans, FH_SRVC_CHNL_SRAM_ADDR_REG(FH_SRVC_CHNL),
637 		    dst_addr);
638 
639 	iwl_write32(trans, FH_TFDIB_CTRL0_REG(FH_SRVC_CHNL),
640 		    phy_addr & FH_MEM_TFDIB_DRAM_ADDR_LSB_MSK);
641 
642 	iwl_write32(trans, FH_TFDIB_CTRL1_REG(FH_SRVC_CHNL),
643 		    (iwl_get_dma_hi_addr(phy_addr)
644 			<< FH_MEM_TFDIB_REG1_ADDR_BITSHIFT) | byte_cnt);
645 
646 	iwl_write32(trans, FH_TCSR_CHNL_TX_BUF_STS_REG(FH_SRVC_CHNL),
647 		    BIT(FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_NUM) |
648 		    BIT(FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_IDX) |
649 		    FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_VALID);
650 
651 	iwl_write32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL),
652 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
653 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_DISABLE |
654 		    FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_ENDTFD);
655 }
656 
657 static int iwl_pcie_load_firmware_chunk(struct iwl_trans *trans,
658 					u32 dst_addr, dma_addr_t phy_addr,
659 					u32 byte_cnt)
660 {
661 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
662 	int ret;
663 
664 	trans_pcie->ucode_write_complete = false;
665 
666 	if (!iwl_trans_grab_nic_access(trans))
667 		return -EIO;
668 
669 	iwl_pcie_load_firmware_chunk_fh(trans, dst_addr, phy_addr,
670 					byte_cnt);
671 	iwl_trans_release_nic_access(trans);
672 
673 	ret = wait_event_timeout(trans_pcie->ucode_write_waitq,
674 				 trans_pcie->ucode_write_complete, 5 * HZ);
675 	if (!ret) {
676 		IWL_ERR(trans, "Failed to load firmware chunk!\n");
677 		iwl_trans_pcie_dump_regs(trans);
678 		return -ETIMEDOUT;
679 	}
680 
681 	return 0;
682 }
683 
684 static int iwl_pcie_load_section(struct iwl_trans *trans, u8 section_num,
685 			    const struct fw_desc *section)
686 {
687 	u8 *v_addr;
688 	dma_addr_t p_addr;
689 	u32 offset, chunk_sz = min_t(u32, FH_MEM_TB_MAX_LENGTH, section->len);
690 	int ret = 0;
691 
692 	IWL_DEBUG_FW(trans, "[%d] uCode section being loaded...\n",
693 		     section_num);
694 
695 	v_addr = dma_alloc_coherent(trans->dev, chunk_sz, &p_addr,
696 				    GFP_KERNEL | __GFP_NOWARN);
697 	if (!v_addr) {
698 		IWL_DEBUG_INFO(trans, "Falling back to small chunks of DMA\n");
699 		chunk_sz = PAGE_SIZE;
700 		v_addr = dma_alloc_coherent(trans->dev, chunk_sz,
701 					    &p_addr, GFP_KERNEL);
702 		if (!v_addr)
703 			return -ENOMEM;
704 	}
705 
706 	for (offset = 0; offset < section->len; offset += chunk_sz) {
707 		u32 copy_size, dst_addr;
708 		bool extended_addr = false;
709 
710 		copy_size = min_t(u32, chunk_sz, section->len - offset);
711 		dst_addr = section->offset + offset;
712 
713 		if (dst_addr >= IWL_FW_MEM_EXTENDED_START &&
714 		    dst_addr <= IWL_FW_MEM_EXTENDED_END)
715 			extended_addr = true;
716 
717 		if (extended_addr)
718 			iwl_set_bits_prph(trans, LMPM_CHICK,
719 					  LMPM_CHICK_EXTENDED_ADDR_SPACE);
720 
721 		memcpy(v_addr, (const u8 *)section->data + offset, copy_size);
722 		ret = iwl_pcie_load_firmware_chunk(trans, dst_addr, p_addr,
723 						   copy_size);
724 
725 		if (extended_addr)
726 			iwl_clear_bits_prph(trans, LMPM_CHICK,
727 					    LMPM_CHICK_EXTENDED_ADDR_SPACE);
728 
729 		if (ret) {
730 			IWL_ERR(trans,
731 				"Could not load the [%d] uCode section\n",
732 				section_num);
733 			break;
734 		}
735 	}
736 
737 	dma_free_coherent(trans->dev, chunk_sz, v_addr, p_addr);
738 	return ret;
739 }
740 
741 static int iwl_pcie_load_cpu_sections_8000(struct iwl_trans *trans,
742 					   const struct fw_img *image,
743 					   int cpu,
744 					   int *first_ucode_section)
745 {
746 	int shift_param;
747 	int i, ret = 0, sec_num = 0x1;
748 	u32 val, last_read_idx = 0;
749 
750 	if (cpu == 1) {
751 		shift_param = 0;
752 		*first_ucode_section = 0;
753 	} else {
754 		shift_param = 16;
755 		(*first_ucode_section)++;
756 	}
757 
758 	for (i = *first_ucode_section; i < image->num_sec; i++) {
759 		last_read_idx = i;
760 
761 		/*
762 		 * CPU1_CPU2_SEPARATOR_SECTION delimiter - separate between
763 		 * CPU1 to CPU2.
764 		 * PAGING_SEPARATOR_SECTION delimiter - separate between
765 		 * CPU2 non paged to CPU2 paging sec.
766 		 */
767 		if (!image->sec[i].data ||
768 		    image->sec[i].offset == CPU1_CPU2_SEPARATOR_SECTION ||
769 		    image->sec[i].offset == PAGING_SEPARATOR_SECTION) {
770 			IWL_DEBUG_FW(trans,
771 				     "Break since Data not valid or Empty section, sec = %d\n",
772 				     i);
773 			break;
774 		}
775 
776 		ret = iwl_pcie_load_section(trans, i, &image->sec[i]);
777 		if (ret)
778 			return ret;
779 
780 		/* Notify ucode of loaded section number and status */
781 		val = iwl_read_direct32(trans, FH_UCODE_LOAD_STATUS);
782 		val = val | (sec_num << shift_param);
783 		iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS, val);
784 
785 		sec_num = (sec_num << 1) | 0x1;
786 	}
787 
788 	*first_ucode_section = last_read_idx;
789 
790 	iwl_enable_interrupts(trans);
791 
792 	if (trans->trans_cfg->use_tfh) {
793 		if (cpu == 1)
794 			iwl_write_prph(trans, UREG_UCODE_LOAD_STATUS,
795 				       0xFFFF);
796 		else
797 			iwl_write_prph(trans, UREG_UCODE_LOAD_STATUS,
798 				       0xFFFFFFFF);
799 	} else {
800 		if (cpu == 1)
801 			iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS,
802 					   0xFFFF);
803 		else
804 			iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS,
805 					   0xFFFFFFFF);
806 	}
807 
808 	return 0;
809 }
810 
811 static int iwl_pcie_load_cpu_sections(struct iwl_trans *trans,
812 				      const struct fw_img *image,
813 				      int cpu,
814 				      int *first_ucode_section)
815 {
816 	int i, ret = 0;
817 	u32 last_read_idx = 0;
818 
819 	if (cpu == 1)
820 		*first_ucode_section = 0;
821 	else
822 		(*first_ucode_section)++;
823 
824 	for (i = *first_ucode_section; i < image->num_sec; i++) {
825 		last_read_idx = i;
826 
827 		/*
828 		 * CPU1_CPU2_SEPARATOR_SECTION delimiter - separate between
829 		 * CPU1 to CPU2.
830 		 * PAGING_SEPARATOR_SECTION delimiter - separate between
831 		 * CPU2 non paged to CPU2 paging sec.
832 		 */
833 		if (!image->sec[i].data ||
834 		    image->sec[i].offset == CPU1_CPU2_SEPARATOR_SECTION ||
835 		    image->sec[i].offset == PAGING_SEPARATOR_SECTION) {
836 			IWL_DEBUG_FW(trans,
837 				     "Break since Data not valid or Empty section, sec = %d\n",
838 				     i);
839 			break;
840 		}
841 
842 		ret = iwl_pcie_load_section(trans, i, &image->sec[i]);
843 		if (ret)
844 			return ret;
845 	}
846 
847 	*first_ucode_section = last_read_idx;
848 
849 	return 0;
850 }
851 
852 static void iwl_pcie_apply_destination_ini(struct iwl_trans *trans)
853 {
854 	enum iwl_fw_ini_allocation_id alloc_id = IWL_FW_INI_ALLOCATION_ID_DBGC1;
855 	struct iwl_fw_ini_allocation_tlv *fw_mon_cfg =
856 		&trans->dbg.fw_mon_cfg[alloc_id];
857 	struct iwl_dram_data *frag;
858 
859 	if (!iwl_trans_dbg_ini_valid(trans))
860 		return;
861 
862 	if (le32_to_cpu(fw_mon_cfg->buf_location) ==
863 	    IWL_FW_INI_LOCATION_SRAM_PATH) {
864 		IWL_DEBUG_FW(trans, "WRT: Applying SMEM buffer destination\n");
865 		/* set sram monitor by enabling bit 7 */
866 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
867 			    CSR_HW_IF_CONFIG_REG_BIT_MONITOR_SRAM);
868 
869 		return;
870 	}
871 
872 	if (le32_to_cpu(fw_mon_cfg->buf_location) !=
873 	    IWL_FW_INI_LOCATION_DRAM_PATH ||
874 	    !trans->dbg.fw_mon_ini[alloc_id].num_frags)
875 		return;
876 
877 	frag = &trans->dbg.fw_mon_ini[alloc_id].frags[0];
878 
879 	IWL_DEBUG_FW(trans, "WRT: Applying DRAM destination (alloc_id=%u)\n",
880 		     alloc_id);
881 
882 	iwl_write_umac_prph(trans, MON_BUFF_BASE_ADDR_VER2,
883 			    frag->physical >> MON_BUFF_SHIFT_VER2);
884 	iwl_write_umac_prph(trans, MON_BUFF_END_ADDR_VER2,
885 			    (frag->physical + frag->size - 256) >>
886 			    MON_BUFF_SHIFT_VER2);
887 }
888 
889 void iwl_pcie_apply_destination(struct iwl_trans *trans)
890 {
891 	const struct iwl_fw_dbg_dest_tlv_v1 *dest = trans->dbg.dest_tlv;
892 	const struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
893 	int i;
894 
895 	if (iwl_trans_dbg_ini_valid(trans)) {
896 		iwl_pcie_apply_destination_ini(trans);
897 		return;
898 	}
899 
900 	IWL_INFO(trans, "Applying debug destination %s\n",
901 		 get_fw_dbg_mode_string(dest->monitor_mode));
902 
903 	if (dest->monitor_mode == EXTERNAL_MODE)
904 		iwl_pcie_alloc_fw_monitor(trans, dest->size_power);
905 	else
906 		IWL_WARN(trans, "PCI should have external buffer debug\n");
907 
908 	for (i = 0; i < trans->dbg.n_dest_reg; i++) {
909 		u32 addr = le32_to_cpu(dest->reg_ops[i].addr);
910 		u32 val = le32_to_cpu(dest->reg_ops[i].val);
911 
912 		switch (dest->reg_ops[i].op) {
913 		case CSR_ASSIGN:
914 			iwl_write32(trans, addr, val);
915 			break;
916 		case CSR_SETBIT:
917 			iwl_set_bit(trans, addr, BIT(val));
918 			break;
919 		case CSR_CLEARBIT:
920 			iwl_clear_bit(trans, addr, BIT(val));
921 			break;
922 		case PRPH_ASSIGN:
923 			iwl_write_prph(trans, addr, val);
924 			break;
925 		case PRPH_SETBIT:
926 			iwl_set_bits_prph(trans, addr, BIT(val));
927 			break;
928 		case PRPH_CLEARBIT:
929 			iwl_clear_bits_prph(trans, addr, BIT(val));
930 			break;
931 		case PRPH_BLOCKBIT:
932 			if (iwl_read_prph(trans, addr) & BIT(val)) {
933 				IWL_ERR(trans,
934 					"BIT(%u) in address 0x%x is 1, stopping FW configuration\n",
935 					val, addr);
936 				goto monitor;
937 			}
938 			break;
939 		default:
940 			IWL_ERR(trans, "FW debug - unknown OP %d\n",
941 				dest->reg_ops[i].op);
942 			break;
943 		}
944 	}
945 
946 monitor:
947 	if (dest->monitor_mode == EXTERNAL_MODE && fw_mon->size) {
948 		iwl_write_prph(trans, le32_to_cpu(dest->base_reg),
949 			       fw_mon->physical >> dest->base_shift);
950 		if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
951 			iwl_write_prph(trans, le32_to_cpu(dest->end_reg),
952 				       (fw_mon->physical + fw_mon->size -
953 					256) >> dest->end_shift);
954 		else
955 			iwl_write_prph(trans, le32_to_cpu(dest->end_reg),
956 				       (fw_mon->physical + fw_mon->size) >>
957 				       dest->end_shift);
958 	}
959 }
960 
961 static int iwl_pcie_load_given_ucode(struct iwl_trans *trans,
962 				const struct fw_img *image)
963 {
964 	int ret = 0;
965 	int first_ucode_section;
966 
967 	IWL_DEBUG_FW(trans, "working with %s CPU\n",
968 		     image->is_dual_cpus ? "Dual" : "Single");
969 
970 	/* load to FW the binary non secured sections of CPU1 */
971 	ret = iwl_pcie_load_cpu_sections(trans, image, 1, &first_ucode_section);
972 	if (ret)
973 		return ret;
974 
975 	if (image->is_dual_cpus) {
976 		/* set CPU2 header address */
977 		iwl_write_prph(trans,
978 			       LMPM_SECURE_UCODE_LOAD_CPU2_HDR_ADDR,
979 			       LMPM_SECURE_CPU2_HDR_MEM_SPACE);
980 
981 		/* load to FW the binary sections of CPU2 */
982 		ret = iwl_pcie_load_cpu_sections(trans, image, 2,
983 						 &first_ucode_section);
984 		if (ret)
985 			return ret;
986 	}
987 
988 	if (iwl_pcie_dbg_on(trans))
989 		iwl_pcie_apply_destination(trans);
990 
991 	iwl_enable_interrupts(trans);
992 
993 	/* release CPU reset */
994 	iwl_write32(trans, CSR_RESET, 0);
995 
996 	return 0;
997 }
998 
999 static int iwl_pcie_load_given_ucode_8000(struct iwl_trans *trans,
1000 					  const struct fw_img *image)
1001 {
1002 	int ret = 0;
1003 	int first_ucode_section;
1004 
1005 	IWL_DEBUG_FW(trans, "working with %s CPU\n",
1006 		     image->is_dual_cpus ? "Dual" : "Single");
1007 
1008 	if (iwl_pcie_dbg_on(trans))
1009 		iwl_pcie_apply_destination(trans);
1010 
1011 	IWL_DEBUG_POWER(trans, "Original WFPM value = 0x%08X\n",
1012 			iwl_read_prph(trans, WFPM_GP2));
1013 
1014 	/*
1015 	 * Set default value. On resume reading the values that were
1016 	 * zeored can provide debug data on the resume flow.
1017 	 * This is for debugging only and has no functional impact.
1018 	 */
1019 	iwl_write_prph(trans, WFPM_GP2, 0x01010101);
1020 
1021 	/* configure the ucode to be ready to get the secured image */
1022 	/* release CPU reset */
1023 	iwl_write_prph(trans, RELEASE_CPU_RESET, RELEASE_CPU_RESET_BIT);
1024 
1025 	/* load to FW the binary Secured sections of CPU1 */
1026 	ret = iwl_pcie_load_cpu_sections_8000(trans, image, 1,
1027 					      &first_ucode_section);
1028 	if (ret)
1029 		return ret;
1030 
1031 	/* load to FW the binary sections of CPU2 */
1032 	return iwl_pcie_load_cpu_sections_8000(trans, image, 2,
1033 					       &first_ucode_section);
1034 }
1035 
1036 bool iwl_pcie_check_hw_rf_kill(struct iwl_trans *trans)
1037 {
1038 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
1039 	bool hw_rfkill = iwl_is_rfkill_set(trans);
1040 	bool prev = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
1041 	bool report;
1042 
1043 	if (hw_rfkill) {
1044 		set_bit(STATUS_RFKILL_HW, &trans->status);
1045 		set_bit(STATUS_RFKILL_OPMODE, &trans->status);
1046 	} else {
1047 		clear_bit(STATUS_RFKILL_HW, &trans->status);
1048 		if (trans_pcie->opmode_down)
1049 			clear_bit(STATUS_RFKILL_OPMODE, &trans->status);
1050 	}
1051 
1052 	report = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
1053 
1054 	if (prev != report)
1055 		iwl_trans_pcie_rf_kill(trans, report);
1056 
1057 	return hw_rfkill;
1058 }
1059 
1060 struct iwl_causes_list {
1061 	u32 cause_num;
1062 	u32 mask_reg;
1063 	u8 addr;
1064 };
1065 
1066 static const struct iwl_causes_list causes_list_common[] = {
1067 	{MSIX_FH_INT_CAUSES_D2S_CH0_NUM,	CSR_MSIX_FH_INT_MASK_AD, 0},
1068 	{MSIX_FH_INT_CAUSES_D2S_CH1_NUM,	CSR_MSIX_FH_INT_MASK_AD, 0x1},
1069 	{MSIX_FH_INT_CAUSES_S2D,		CSR_MSIX_FH_INT_MASK_AD, 0x3},
1070 	{MSIX_FH_INT_CAUSES_FH_ERR,		CSR_MSIX_FH_INT_MASK_AD, 0x5},
1071 	{MSIX_HW_INT_CAUSES_REG_ALIVE,		CSR_MSIX_HW_INT_MASK_AD, 0x10},
1072 	{MSIX_HW_INT_CAUSES_REG_WAKEUP,		CSR_MSIX_HW_INT_MASK_AD, 0x11},
1073 	{MSIX_HW_INT_CAUSES_REG_RESET_DONE,	CSR_MSIX_HW_INT_MASK_AD, 0x12},
1074 	{MSIX_HW_INT_CAUSES_REG_CT_KILL,	CSR_MSIX_HW_INT_MASK_AD, 0x16},
1075 	{MSIX_HW_INT_CAUSES_REG_RF_KILL,	CSR_MSIX_HW_INT_MASK_AD, 0x17},
1076 	{MSIX_HW_INT_CAUSES_REG_PERIODIC,	CSR_MSIX_HW_INT_MASK_AD, 0x18},
1077 	{MSIX_HW_INT_CAUSES_REG_SCD,		CSR_MSIX_HW_INT_MASK_AD, 0x2A},
1078 	{MSIX_HW_INT_CAUSES_REG_FH_TX,		CSR_MSIX_HW_INT_MASK_AD, 0x2B},
1079 	{MSIX_HW_INT_CAUSES_REG_HW_ERR,		CSR_MSIX_HW_INT_MASK_AD, 0x2D},
1080 	{MSIX_HW_INT_CAUSES_REG_HAP,		CSR_MSIX_HW_INT_MASK_AD, 0x2E},
1081 };
1082 
1083 static const struct iwl_causes_list causes_list_pre_bz[] = {
1084 	{MSIX_HW_INT_CAUSES_REG_SW_ERR,		CSR_MSIX_HW_INT_MASK_AD, 0x29},
1085 };
1086 
1087 static const struct iwl_causes_list causes_list_bz[] = {
1088 	{MSIX_HW_INT_CAUSES_REG_SW_ERR_BZ,	CSR_MSIX_HW_INT_MASK_AD, 0x29},
1089 };
1090 
1091 static void iwl_pcie_map_list(struct iwl_trans *trans,
1092 			      const struct iwl_causes_list *causes,
1093 			      int arr_size, int val)
1094 {
1095 	int i;
1096 
1097 	for (i = 0; i < arr_size; i++) {
1098 		iwl_write8(trans, CSR_MSIX_IVAR(causes[i].addr), val);
1099 		iwl_clear_bit(trans, causes[i].mask_reg,
1100 			      causes[i].cause_num);
1101 	}
1102 }
1103 
1104 static void iwl_pcie_map_non_rx_causes(struct iwl_trans *trans)
1105 {
1106 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
1107 	int val = trans_pcie->def_irq | MSIX_NON_AUTO_CLEAR_CAUSE;
1108 	/*
1109 	 * Access all non RX causes and map them to the default irq.
1110 	 * In case we are missing at least one interrupt vector,
1111 	 * the first interrupt vector will serve non-RX and FBQ causes.
1112 	 */
1113 	iwl_pcie_map_list(trans, causes_list_common,
1114 			  ARRAY_SIZE(causes_list_common), val);
1115 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
1116 		iwl_pcie_map_list(trans, causes_list_bz,
1117 				  ARRAY_SIZE(causes_list_bz), val);
1118 	else
1119 		iwl_pcie_map_list(trans, causes_list_pre_bz,
1120 				  ARRAY_SIZE(causes_list_pre_bz), val);
1121 }
1122 
1123 static void iwl_pcie_map_rx_causes(struct iwl_trans *trans)
1124 {
1125 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1126 	u32 offset =
1127 		trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS ? 1 : 0;
1128 	u32 val, idx;
1129 
1130 	/*
1131 	 * The first RX queue - fallback queue, which is designated for
1132 	 * management frame, command responses etc, is always mapped to the
1133 	 * first interrupt vector. The other RX queues are mapped to
1134 	 * the other (N - 2) interrupt vectors.
1135 	 */
1136 	val = BIT(MSIX_FH_INT_CAUSES_Q(0));
1137 	for (idx = 1; idx < trans->num_rx_queues; idx++) {
1138 		iwl_write8(trans, CSR_MSIX_RX_IVAR(idx),
1139 			   MSIX_FH_INT_CAUSES_Q(idx - offset));
1140 		val |= BIT(MSIX_FH_INT_CAUSES_Q(idx));
1141 	}
1142 	iwl_write32(trans, CSR_MSIX_FH_INT_MASK_AD, ~val);
1143 
1144 	val = MSIX_FH_INT_CAUSES_Q(0);
1145 	if (trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_NON_RX)
1146 		val |= MSIX_NON_AUTO_CLEAR_CAUSE;
1147 	iwl_write8(trans, CSR_MSIX_RX_IVAR(0), val);
1148 
1149 	if (trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS)
1150 		iwl_write8(trans, CSR_MSIX_RX_IVAR(1), val);
1151 }
1152 
1153 void iwl_pcie_conf_msix_hw(struct iwl_trans_pcie *trans_pcie)
1154 {
1155 	struct iwl_trans *trans = trans_pcie->trans;
1156 
1157 	if (!trans_pcie->msix_enabled) {
1158 		if (trans->trans_cfg->mq_rx_supported &&
1159 		    test_bit(STATUS_DEVICE_ENABLED, &trans->status))
1160 			iwl_write_umac_prph(trans, UREG_CHICK,
1161 					    UREG_CHICK_MSI_ENABLE);
1162 		return;
1163 	}
1164 	/*
1165 	 * The IVAR table needs to be configured again after reset,
1166 	 * but if the device is disabled, we can't write to
1167 	 * prph.
1168 	 */
1169 	if (test_bit(STATUS_DEVICE_ENABLED, &trans->status))
1170 		iwl_write_umac_prph(trans, UREG_CHICK, UREG_CHICK_MSIX_ENABLE);
1171 
1172 	/*
1173 	 * Each cause from the causes list above and the RX causes is
1174 	 * represented as a byte in the IVAR table. The first nibble
1175 	 * represents the bound interrupt vector of the cause, the second
1176 	 * represents no auto clear for this cause. This will be set if its
1177 	 * interrupt vector is bound to serve other causes.
1178 	 */
1179 	iwl_pcie_map_rx_causes(trans);
1180 
1181 	iwl_pcie_map_non_rx_causes(trans);
1182 }
1183 
1184 static void iwl_pcie_init_msix(struct iwl_trans_pcie *trans_pcie)
1185 {
1186 	struct iwl_trans *trans = trans_pcie->trans;
1187 
1188 	iwl_pcie_conf_msix_hw(trans_pcie);
1189 
1190 	if (!trans_pcie->msix_enabled)
1191 		return;
1192 
1193 	trans_pcie->fh_init_mask = ~iwl_read32(trans, CSR_MSIX_FH_INT_MASK_AD);
1194 	trans_pcie->fh_mask = trans_pcie->fh_init_mask;
1195 	trans_pcie->hw_init_mask = ~iwl_read32(trans, CSR_MSIX_HW_INT_MASK_AD);
1196 	trans_pcie->hw_mask = trans_pcie->hw_init_mask;
1197 }
1198 
1199 static void _iwl_trans_pcie_stop_device(struct iwl_trans *trans)
1200 {
1201 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1202 
1203 	lockdep_assert_held(&trans_pcie->mutex);
1204 
1205 	if (trans_pcie->is_down)
1206 		return;
1207 
1208 	trans_pcie->is_down = true;
1209 
1210 	/* tell the device to stop sending interrupts */
1211 	iwl_disable_interrupts(trans);
1212 
1213 	/* device going down, Stop using ICT table */
1214 	iwl_pcie_disable_ict(trans);
1215 
1216 	/*
1217 	 * If a HW restart happens during firmware loading,
1218 	 * then the firmware loading might call this function
1219 	 * and later it might be called again due to the
1220 	 * restart. So don't process again if the device is
1221 	 * already dead.
1222 	 */
1223 	if (test_and_clear_bit(STATUS_DEVICE_ENABLED, &trans->status)) {
1224 		IWL_DEBUG_INFO(trans,
1225 			       "DEVICE_ENABLED bit was set and is now cleared\n");
1226 		iwl_pcie_tx_stop(trans);
1227 		iwl_pcie_rx_stop(trans);
1228 
1229 		/* Power-down device's busmaster DMA clocks */
1230 		if (!trans->cfg->apmg_not_supported) {
1231 			iwl_write_prph(trans, APMG_CLK_DIS_REG,
1232 				       APMG_CLK_VAL_DMA_CLK_RQT);
1233 			udelay(5);
1234 		}
1235 	}
1236 
1237 	/* Make sure (redundant) we've released our request to stay awake */
1238 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
1239 		iwl_clear_bit(trans, CSR_GP_CNTRL,
1240 			      CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ);
1241 	else
1242 		iwl_clear_bit(trans, CSR_GP_CNTRL,
1243 			      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
1244 
1245 	/* Stop the device, and put it in low power state */
1246 	iwl_pcie_apm_stop(trans, false);
1247 
1248 	iwl_trans_pcie_sw_reset(trans);
1249 
1250 	/*
1251 	 * Upon stop, the IVAR table gets erased, so msi-x won't
1252 	 * work. This causes a bug in RF-KILL flows, since the interrupt
1253 	 * that enables radio won't fire on the correct irq, and the
1254 	 * driver won't be able to handle the interrupt.
1255 	 * Configure the IVAR table again after reset.
1256 	 */
1257 	iwl_pcie_conf_msix_hw(trans_pcie);
1258 
1259 	/*
1260 	 * Upon stop, the APM issues an interrupt if HW RF kill is set.
1261 	 * This is a bug in certain verions of the hardware.
1262 	 * Certain devices also keep sending HW RF kill interrupt all
1263 	 * the time, unless the interrupt is ACKed even if the interrupt
1264 	 * should be masked. Re-ACK all the interrupts here.
1265 	 */
1266 	iwl_disable_interrupts(trans);
1267 
1268 	/* clear all status bits */
1269 	clear_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status);
1270 	clear_bit(STATUS_INT_ENABLED, &trans->status);
1271 	clear_bit(STATUS_TPOWER_PMI, &trans->status);
1272 
1273 	/*
1274 	 * Even if we stop the HW, we still want the RF kill
1275 	 * interrupt
1276 	 */
1277 	iwl_enable_rfkill_int(trans);
1278 
1279 	/* re-take ownership to prevent other users from stealing the device */
1280 	iwl_pcie_prepare_card_hw(trans);
1281 }
1282 
1283 void iwl_pcie_synchronize_irqs(struct iwl_trans *trans)
1284 {
1285 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1286 
1287 	if (trans_pcie->msix_enabled) {
1288 		int i;
1289 
1290 		for (i = 0; i < trans_pcie->alloc_vecs; i++)
1291 			synchronize_irq(trans_pcie->msix_entries[i].vector);
1292 	} else {
1293 		synchronize_irq(trans_pcie->pci_dev->irq);
1294 	}
1295 }
1296 
1297 static int iwl_trans_pcie_start_fw(struct iwl_trans *trans,
1298 				   const struct fw_img *fw, bool run_in_rfkill)
1299 {
1300 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1301 	bool hw_rfkill;
1302 	int ret;
1303 
1304 	/* This may fail if AMT took ownership of the device */
1305 	if (iwl_pcie_prepare_card_hw(trans)) {
1306 		IWL_WARN(trans, "Exit HW not ready\n");
1307 		ret = -EIO;
1308 		goto out;
1309 	}
1310 
1311 	iwl_enable_rfkill_int(trans);
1312 
1313 	iwl_write32(trans, CSR_INT, 0xFFFFFFFF);
1314 
1315 	/*
1316 	 * We enabled the RF-Kill interrupt and the handler may very
1317 	 * well be running. Disable the interrupts to make sure no other
1318 	 * interrupt can be fired.
1319 	 */
1320 	iwl_disable_interrupts(trans);
1321 
1322 	/* Make sure it finished running */
1323 	iwl_pcie_synchronize_irqs(trans);
1324 
1325 	mutex_lock(&trans_pcie->mutex);
1326 
1327 	/* If platform's RF_KILL switch is NOT set to KILL */
1328 	hw_rfkill = iwl_pcie_check_hw_rf_kill(trans);
1329 	if (hw_rfkill && !run_in_rfkill) {
1330 		ret = -ERFKILL;
1331 		goto out;
1332 	}
1333 
1334 	/* Someone called stop_device, don't try to start_fw */
1335 	if (trans_pcie->is_down) {
1336 		IWL_WARN(trans,
1337 			 "Can't start_fw since the HW hasn't been started\n");
1338 		ret = -EIO;
1339 		goto out;
1340 	}
1341 
1342 	/* make sure rfkill handshake bits are cleared */
1343 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
1344 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR,
1345 		    CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
1346 
1347 	/* clear (again), then enable host interrupts */
1348 	iwl_write32(trans, CSR_INT, 0xFFFFFFFF);
1349 
1350 	ret = iwl_pcie_nic_init(trans);
1351 	if (ret) {
1352 		IWL_ERR(trans, "Unable to init nic\n");
1353 		goto out;
1354 	}
1355 
1356 	/*
1357 	 * Now, we load the firmware and don't want to be interrupted, even
1358 	 * by the RF-Kill interrupt (hence mask all the interrupt besides the
1359 	 * FH_TX interrupt which is needed to load the firmware). If the
1360 	 * RF-Kill switch is toggled, we will find out after having loaded
1361 	 * the firmware and return the proper value to the caller.
1362 	 */
1363 	iwl_enable_fw_load_int(trans);
1364 
1365 	/* really make sure rfkill handshake bits are cleared */
1366 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
1367 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
1368 
1369 	/* Load the given image to the HW */
1370 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
1371 		ret = iwl_pcie_load_given_ucode_8000(trans, fw);
1372 	else
1373 		ret = iwl_pcie_load_given_ucode(trans, fw);
1374 
1375 	/* re-check RF-Kill state since we may have missed the interrupt */
1376 	hw_rfkill = iwl_pcie_check_hw_rf_kill(trans);
1377 	if (hw_rfkill && !run_in_rfkill)
1378 		ret = -ERFKILL;
1379 
1380 out:
1381 	mutex_unlock(&trans_pcie->mutex);
1382 	return ret;
1383 }
1384 
1385 static void iwl_trans_pcie_fw_alive(struct iwl_trans *trans, u32 scd_addr)
1386 {
1387 	iwl_pcie_reset_ict(trans);
1388 	iwl_pcie_tx_start(trans, scd_addr);
1389 }
1390 
1391 void iwl_trans_pcie_handle_stop_rfkill(struct iwl_trans *trans,
1392 				       bool was_in_rfkill)
1393 {
1394 	bool hw_rfkill;
1395 
1396 	/*
1397 	 * Check again since the RF kill state may have changed while
1398 	 * all the interrupts were disabled, in this case we couldn't
1399 	 * receive the RF kill interrupt and update the state in the
1400 	 * op_mode.
1401 	 * Don't call the op_mode if the rkfill state hasn't changed.
1402 	 * This allows the op_mode to call stop_device from the rfkill
1403 	 * notification without endless recursion. Under very rare
1404 	 * circumstances, we might have a small recursion if the rfkill
1405 	 * state changed exactly now while we were called from stop_device.
1406 	 * This is very unlikely but can happen and is supported.
1407 	 */
1408 	hw_rfkill = iwl_is_rfkill_set(trans);
1409 	if (hw_rfkill) {
1410 		set_bit(STATUS_RFKILL_HW, &trans->status);
1411 		set_bit(STATUS_RFKILL_OPMODE, &trans->status);
1412 	} else {
1413 		clear_bit(STATUS_RFKILL_HW, &trans->status);
1414 		clear_bit(STATUS_RFKILL_OPMODE, &trans->status);
1415 	}
1416 	if (hw_rfkill != was_in_rfkill)
1417 		iwl_trans_pcie_rf_kill(trans, hw_rfkill);
1418 }
1419 
1420 static void iwl_trans_pcie_stop_device(struct iwl_trans *trans)
1421 {
1422 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1423 	bool was_in_rfkill;
1424 
1425 	iwl_op_mode_time_point(trans->op_mode,
1426 			       IWL_FW_INI_TIME_POINT_HOST_DEVICE_DISABLE,
1427 			       NULL);
1428 
1429 	mutex_lock(&trans_pcie->mutex);
1430 	trans_pcie->opmode_down = true;
1431 	was_in_rfkill = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
1432 	_iwl_trans_pcie_stop_device(trans);
1433 	iwl_trans_pcie_handle_stop_rfkill(trans, was_in_rfkill);
1434 	mutex_unlock(&trans_pcie->mutex);
1435 }
1436 
1437 void iwl_trans_pcie_rf_kill(struct iwl_trans *trans, bool state)
1438 {
1439 	struct iwl_trans_pcie __maybe_unused *trans_pcie =
1440 		IWL_TRANS_GET_PCIE_TRANS(trans);
1441 
1442 	lockdep_assert_held(&trans_pcie->mutex);
1443 
1444 	IWL_WARN(trans, "reporting RF_KILL (radio %s)\n",
1445 		 state ? "disabled" : "enabled");
1446 	if (iwl_op_mode_hw_rf_kill(trans->op_mode, state)) {
1447 		if (trans->trans_cfg->gen2)
1448 			_iwl_trans_pcie_gen2_stop_device(trans);
1449 		else
1450 			_iwl_trans_pcie_stop_device(trans);
1451 	}
1452 }
1453 
1454 void iwl_pcie_d3_complete_suspend(struct iwl_trans *trans,
1455 				  bool test, bool reset)
1456 {
1457 	iwl_disable_interrupts(trans);
1458 
1459 	/*
1460 	 * in testing mode, the host stays awake and the
1461 	 * hardware won't be reset (not even partially)
1462 	 */
1463 	if (test)
1464 		return;
1465 
1466 	iwl_pcie_disable_ict(trans);
1467 
1468 	iwl_pcie_synchronize_irqs(trans);
1469 
1470 	iwl_clear_bit(trans, CSR_GP_CNTRL,
1471 		      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
1472 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
1473 
1474 	if (reset) {
1475 		/*
1476 		 * reset TX queues -- some of their registers reset during S3
1477 		 * so if we don't reset everything here the D3 image would try
1478 		 * to execute some invalid memory upon resume
1479 		 */
1480 		iwl_trans_pcie_tx_reset(trans);
1481 	}
1482 
1483 	iwl_pcie_set_pwr(trans, true);
1484 }
1485 
1486 static int iwl_trans_pcie_d3_suspend(struct iwl_trans *trans, bool test,
1487 				     bool reset)
1488 {
1489 	int ret;
1490 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
1491 
1492 	if (!reset)
1493 		/* Enable persistence mode to avoid reset */
1494 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
1495 			    CSR_HW_IF_CONFIG_REG_PERSIST_MODE);
1496 
1497 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
1498 		iwl_write_umac_prph(trans, UREG_DOORBELL_TO_ISR6,
1499 				    UREG_DOORBELL_TO_ISR6_SUSPEND);
1500 
1501 		ret = wait_event_timeout(trans_pcie->sx_waitq,
1502 					 trans_pcie->sx_complete, 2 * HZ);
1503 		/*
1504 		 * Invalidate it toward resume.
1505 		 */
1506 		trans_pcie->sx_complete = false;
1507 
1508 		if (!ret) {
1509 			IWL_ERR(trans, "Timeout entering D3\n");
1510 			return -ETIMEDOUT;
1511 		}
1512 	}
1513 	iwl_pcie_d3_complete_suspend(trans, test, reset);
1514 
1515 	return 0;
1516 }
1517 
1518 static int iwl_trans_pcie_d3_resume(struct iwl_trans *trans,
1519 				    enum iwl_d3_status *status,
1520 				    bool test,  bool reset)
1521 {
1522 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
1523 	u32 val;
1524 	int ret;
1525 
1526 	if (test) {
1527 		iwl_enable_interrupts(trans);
1528 		*status = IWL_D3_STATUS_ALIVE;
1529 		goto out;
1530 	}
1531 
1532 	iwl_set_bit(trans, CSR_GP_CNTRL,
1533 		    CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
1534 
1535 	ret = iwl_finish_nic_init(trans);
1536 	if (ret)
1537 		return ret;
1538 
1539 	/*
1540 	 * Reconfigure IVAR table in case of MSIX or reset ict table in
1541 	 * MSI mode since HW reset erased it.
1542 	 * Also enables interrupts - none will happen as
1543 	 * the device doesn't know we're waking it up, only when
1544 	 * the opmode actually tells it after this call.
1545 	 */
1546 	iwl_pcie_conf_msix_hw(trans_pcie);
1547 	if (!trans_pcie->msix_enabled)
1548 		iwl_pcie_reset_ict(trans);
1549 	iwl_enable_interrupts(trans);
1550 
1551 	iwl_pcie_set_pwr(trans, false);
1552 
1553 	if (!reset) {
1554 		iwl_clear_bit(trans, CSR_GP_CNTRL,
1555 			      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
1556 	} else {
1557 		iwl_trans_pcie_tx_reset(trans);
1558 
1559 		ret = iwl_pcie_rx_init(trans);
1560 		if (ret) {
1561 			IWL_ERR(trans,
1562 				"Failed to resume the device (RX reset)\n");
1563 			return ret;
1564 		}
1565 	}
1566 
1567 	IWL_DEBUG_POWER(trans, "WFPM value upon resume = 0x%08X\n",
1568 			iwl_read_umac_prph(trans, WFPM_GP2));
1569 
1570 	val = iwl_read32(trans, CSR_RESET);
1571 	if (val & CSR_RESET_REG_FLAG_NEVO_RESET)
1572 		*status = IWL_D3_STATUS_RESET;
1573 	else
1574 		*status = IWL_D3_STATUS_ALIVE;
1575 
1576 out:
1577 	if (*status == IWL_D3_STATUS_ALIVE &&
1578 	    trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
1579 		trans_pcie->sx_complete = false;
1580 		iwl_write_umac_prph(trans, UREG_DOORBELL_TO_ISR6,
1581 				    UREG_DOORBELL_TO_ISR6_RESUME);
1582 
1583 		ret = wait_event_timeout(trans_pcie->sx_waitq,
1584 					 trans_pcie->sx_complete, 2 * HZ);
1585 		/*
1586 		 * Invalidate it toward next suspend.
1587 		 */
1588 		trans_pcie->sx_complete = false;
1589 
1590 		if (!ret) {
1591 			IWL_ERR(trans, "Timeout exiting D3\n");
1592 			return -ETIMEDOUT;
1593 		}
1594 	}
1595 	return 0;
1596 }
1597 
1598 static void
1599 iwl_pcie_set_interrupt_capa(struct pci_dev *pdev,
1600 			    struct iwl_trans *trans,
1601 			    const struct iwl_cfg_trans_params *cfg_trans)
1602 {
1603 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1604 	int max_irqs, num_irqs, i, ret;
1605 	u16 pci_cmd;
1606 	u32 max_rx_queues = IWL_MAX_RX_HW_QUEUES;
1607 
1608 	if (!cfg_trans->mq_rx_supported)
1609 		goto enable_msi;
1610 
1611 	if (cfg_trans->device_family <= IWL_DEVICE_FAMILY_9000)
1612 		max_rx_queues = IWL_9000_MAX_RX_HW_QUEUES;
1613 
1614 	max_irqs = min_t(u32, num_online_cpus() + 2, max_rx_queues);
1615 	for (i = 0; i < max_irqs; i++)
1616 		trans_pcie->msix_entries[i].entry = i;
1617 
1618 	num_irqs = pci_enable_msix_range(pdev, trans_pcie->msix_entries,
1619 					 MSIX_MIN_INTERRUPT_VECTORS,
1620 					 max_irqs);
1621 	if (num_irqs < 0) {
1622 		IWL_DEBUG_INFO(trans,
1623 			       "Failed to enable msi-x mode (ret %d). Moving to msi mode.\n",
1624 			       num_irqs);
1625 		goto enable_msi;
1626 	}
1627 	trans_pcie->def_irq = (num_irqs == max_irqs) ? num_irqs - 1 : 0;
1628 
1629 	IWL_DEBUG_INFO(trans,
1630 		       "MSI-X enabled. %d interrupt vectors were allocated\n",
1631 		       num_irqs);
1632 
1633 	/*
1634 	 * In case the OS provides fewer interrupts than requested, different
1635 	 * causes will share the same interrupt vector as follows:
1636 	 * One interrupt less: non rx causes shared with FBQ.
1637 	 * Two interrupts less: non rx causes shared with FBQ and RSS.
1638 	 * More than two interrupts: we will use fewer RSS queues.
1639 	 */
1640 	if (num_irqs <= max_irqs - 2) {
1641 		trans_pcie->trans->num_rx_queues = num_irqs + 1;
1642 		trans_pcie->shared_vec_mask = IWL_SHARED_IRQ_NON_RX |
1643 			IWL_SHARED_IRQ_FIRST_RSS;
1644 	} else if (num_irqs == max_irqs - 1) {
1645 		trans_pcie->trans->num_rx_queues = num_irqs;
1646 		trans_pcie->shared_vec_mask = IWL_SHARED_IRQ_NON_RX;
1647 	} else {
1648 		trans_pcie->trans->num_rx_queues = num_irqs - 1;
1649 	}
1650 
1651 	IWL_DEBUG_INFO(trans,
1652 		       "MSI-X enabled with rx queues %d, vec mask 0x%x\n",
1653 		       trans_pcie->trans->num_rx_queues, trans_pcie->shared_vec_mask);
1654 
1655 	WARN_ON(trans_pcie->trans->num_rx_queues > IWL_MAX_RX_HW_QUEUES);
1656 
1657 	trans_pcie->alloc_vecs = num_irqs;
1658 	trans_pcie->msix_enabled = true;
1659 	return;
1660 
1661 enable_msi:
1662 	ret = pci_enable_msi(pdev);
1663 	if (ret) {
1664 		dev_err(&pdev->dev, "pci_enable_msi failed - %d\n", ret);
1665 		/* enable rfkill interrupt: hw bug w/a */
1666 		pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd);
1667 		if (pci_cmd & PCI_COMMAND_INTX_DISABLE) {
1668 			pci_cmd &= ~PCI_COMMAND_INTX_DISABLE;
1669 			pci_write_config_word(pdev, PCI_COMMAND, pci_cmd);
1670 		}
1671 	}
1672 }
1673 
1674 static void iwl_pcie_irq_set_affinity(struct iwl_trans *trans)
1675 {
1676 	int iter_rx_q, i, ret, cpu, offset;
1677 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1678 
1679 	i = trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS ? 0 : 1;
1680 	iter_rx_q = trans_pcie->trans->num_rx_queues - 1 + i;
1681 	offset = 1 + i;
1682 	for (; i < iter_rx_q ; i++) {
1683 		/*
1684 		 * Get the cpu prior to the place to search
1685 		 * (i.e. return will be > i - 1).
1686 		 */
1687 		cpu = cpumask_next(i - offset, cpu_online_mask);
1688 		cpumask_set_cpu(cpu, &trans_pcie->affinity_mask[i]);
1689 		ret = irq_set_affinity_hint(trans_pcie->msix_entries[i].vector,
1690 					    &trans_pcie->affinity_mask[i]);
1691 		if (ret)
1692 			IWL_ERR(trans_pcie->trans,
1693 				"Failed to set affinity mask for IRQ %d\n",
1694 				trans_pcie->msix_entries[i].vector);
1695 	}
1696 }
1697 
1698 static int iwl_pcie_init_msix_handler(struct pci_dev *pdev,
1699 				      struct iwl_trans_pcie *trans_pcie)
1700 {
1701 	int i;
1702 
1703 	for (i = 0; i < trans_pcie->alloc_vecs; i++) {
1704 		int ret;
1705 		struct msix_entry *msix_entry;
1706 		const char *qname = queue_name(&pdev->dev, trans_pcie, i);
1707 
1708 		if (!qname)
1709 			return -ENOMEM;
1710 
1711 		msix_entry = &trans_pcie->msix_entries[i];
1712 		ret = devm_request_threaded_irq(&pdev->dev,
1713 						msix_entry->vector,
1714 						iwl_pcie_msix_isr,
1715 						(i == trans_pcie->def_irq) ?
1716 						iwl_pcie_irq_msix_handler :
1717 						iwl_pcie_irq_rx_msix_handler,
1718 						IRQF_SHARED,
1719 						qname,
1720 						msix_entry);
1721 		if (ret) {
1722 			IWL_ERR(trans_pcie->trans,
1723 				"Error allocating IRQ %d\n", i);
1724 
1725 			return ret;
1726 		}
1727 	}
1728 	iwl_pcie_irq_set_affinity(trans_pcie->trans);
1729 
1730 	return 0;
1731 }
1732 
1733 static int iwl_trans_pcie_clear_persistence_bit(struct iwl_trans *trans)
1734 {
1735 	u32 hpm, wprot;
1736 
1737 	switch (trans->trans_cfg->device_family) {
1738 	case IWL_DEVICE_FAMILY_9000:
1739 		wprot = PREG_PRPH_WPROT_9000;
1740 		break;
1741 	case IWL_DEVICE_FAMILY_22000:
1742 		wprot = PREG_PRPH_WPROT_22000;
1743 		break;
1744 	default:
1745 		return 0;
1746 	}
1747 
1748 	hpm = iwl_read_umac_prph_no_grab(trans, HPM_DEBUG);
1749 	if (hpm != 0xa5a5a5a0 && (hpm & PERSISTENCE_BIT)) {
1750 		u32 wprot_val = iwl_read_umac_prph_no_grab(trans, wprot);
1751 
1752 		if (wprot_val & PREG_WFPM_ACCESS) {
1753 			IWL_ERR(trans,
1754 				"Error, can not clear persistence bit\n");
1755 			return -EPERM;
1756 		}
1757 		iwl_write_umac_prph_no_grab(trans, HPM_DEBUG,
1758 					    hpm & ~PERSISTENCE_BIT);
1759 	}
1760 
1761 	return 0;
1762 }
1763 
1764 static int iwl_pcie_gen2_force_power_gating(struct iwl_trans *trans)
1765 {
1766 	int ret;
1767 
1768 	ret = iwl_finish_nic_init(trans);
1769 	if (ret < 0)
1770 		return ret;
1771 
1772 	iwl_set_bits_prph(trans, HPM_HIPM_GEN_CFG,
1773 			  HPM_HIPM_GEN_CFG_CR_FORCE_ACTIVE);
1774 	udelay(20);
1775 	iwl_set_bits_prph(trans, HPM_HIPM_GEN_CFG,
1776 			  HPM_HIPM_GEN_CFG_CR_PG_EN |
1777 			  HPM_HIPM_GEN_CFG_CR_SLP_EN);
1778 	udelay(20);
1779 	iwl_clear_bits_prph(trans, HPM_HIPM_GEN_CFG,
1780 			    HPM_HIPM_GEN_CFG_CR_FORCE_ACTIVE);
1781 
1782 	iwl_trans_pcie_sw_reset(trans);
1783 
1784 	return 0;
1785 }
1786 
1787 static int _iwl_trans_pcie_start_hw(struct iwl_trans *trans)
1788 {
1789 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1790 	int err;
1791 
1792 	lockdep_assert_held(&trans_pcie->mutex);
1793 
1794 	err = iwl_pcie_prepare_card_hw(trans);
1795 	if (err) {
1796 		IWL_ERR(trans, "Error while preparing HW: %d\n", err);
1797 		return err;
1798 	}
1799 
1800 	err = iwl_trans_pcie_clear_persistence_bit(trans);
1801 	if (err)
1802 		return err;
1803 
1804 	iwl_trans_pcie_sw_reset(trans);
1805 
1806 	if (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_22000 &&
1807 	    trans->trans_cfg->integrated) {
1808 		err = iwl_pcie_gen2_force_power_gating(trans);
1809 		if (err)
1810 			return err;
1811 	}
1812 
1813 	err = iwl_pcie_apm_init(trans);
1814 	if (err)
1815 		return err;
1816 
1817 	iwl_pcie_init_msix(trans_pcie);
1818 
1819 	/* From now on, the op_mode will be kept updated about RF kill state */
1820 	iwl_enable_rfkill_int(trans);
1821 
1822 	trans_pcie->opmode_down = false;
1823 
1824 	/* Set is_down to false here so that...*/
1825 	trans_pcie->is_down = false;
1826 
1827 	/* ...rfkill can call stop_device and set it false if needed */
1828 	iwl_pcie_check_hw_rf_kill(trans);
1829 
1830 	return 0;
1831 }
1832 
1833 static int iwl_trans_pcie_start_hw(struct iwl_trans *trans)
1834 {
1835 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1836 	int ret;
1837 
1838 	mutex_lock(&trans_pcie->mutex);
1839 	ret = _iwl_trans_pcie_start_hw(trans);
1840 	mutex_unlock(&trans_pcie->mutex);
1841 
1842 	return ret;
1843 }
1844 
1845 static void iwl_trans_pcie_op_mode_leave(struct iwl_trans *trans)
1846 {
1847 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1848 
1849 	mutex_lock(&trans_pcie->mutex);
1850 
1851 	/* disable interrupts - don't enable HW RF kill interrupt */
1852 	iwl_disable_interrupts(trans);
1853 
1854 	iwl_pcie_apm_stop(trans, true);
1855 
1856 	iwl_disable_interrupts(trans);
1857 
1858 	iwl_pcie_disable_ict(trans);
1859 
1860 	mutex_unlock(&trans_pcie->mutex);
1861 
1862 	iwl_pcie_synchronize_irqs(trans);
1863 }
1864 
1865 #if defined(__linux__)
1866 static void iwl_trans_pcie_write8(struct iwl_trans *trans, u32 ofs, u8 val)
1867 {
1868 	writeb(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
1869 }
1870 
1871 static void iwl_trans_pcie_write32(struct iwl_trans *trans, u32 ofs, u32 val)
1872 {
1873 	writel(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
1874 }
1875 
1876 static u32 iwl_trans_pcie_read32(struct iwl_trans *trans, u32 ofs)
1877 {
1878 	return readl(IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
1879 }
1880 #elif defined(__FreeBSD__)
1881 static void iwl_trans_pcie_write8(struct iwl_trans *trans, u32 ofs, u8 val)
1882 {
1883 
1884 	IWL_DEBUG_PCI_RW(trans, "W1 %#010x %#04x\n", ofs, val);
1885 	bus_write_1((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs, val);
1886 }
1887 
1888 static void iwl_trans_pcie_write32(struct iwl_trans *trans, u32 ofs, u32 val)
1889 {
1890 
1891 	IWL_DEBUG_PCI_RW(trans, "W4 %#010x %#010x\n", ofs, val);
1892 	bus_write_4((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs, val);
1893 }
1894 
1895 static u32 iwl_trans_pcie_read32(struct iwl_trans *trans, u32 ofs)
1896 {
1897 	u32 v;
1898 
1899 	v = bus_read_4((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs);
1900 	IWL_DEBUG_PCI_RW(trans, "R4 %#010x %#010x\n", ofs, v);
1901 	return (v);
1902 }
1903 #endif
1904 
1905 static u32 iwl_trans_pcie_prph_msk(struct iwl_trans *trans)
1906 {
1907 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210)
1908 		return 0x00FFFFFF;
1909 	else
1910 		return 0x000FFFFF;
1911 }
1912 
1913 static u32 iwl_trans_pcie_read_prph(struct iwl_trans *trans, u32 reg)
1914 {
1915 	u32 mask = iwl_trans_pcie_prph_msk(trans);
1916 
1917 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_RADDR,
1918 			       ((reg & mask) | (3 << 24)));
1919 	return iwl_trans_pcie_read32(trans, HBUS_TARG_PRPH_RDAT);
1920 }
1921 
1922 static void iwl_trans_pcie_write_prph(struct iwl_trans *trans, u32 addr,
1923 				      u32 val)
1924 {
1925 	u32 mask = iwl_trans_pcie_prph_msk(trans);
1926 
1927 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_WADDR,
1928 			       ((addr & mask) | (3 << 24)));
1929 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_WDAT, val);
1930 }
1931 
1932 static void iwl_trans_pcie_configure(struct iwl_trans *trans,
1933 				     const struct iwl_trans_config *trans_cfg)
1934 {
1935 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1936 
1937 	/* free all first - we might be reconfigured for a different size */
1938 	iwl_pcie_free_rbs_pool(trans);
1939 
1940 	trans->txqs.cmd.q_id = trans_cfg->cmd_queue;
1941 	trans->txqs.cmd.fifo = trans_cfg->cmd_fifo;
1942 	trans->txqs.cmd.wdg_timeout = trans_cfg->cmd_q_wdg_timeout;
1943 	trans->txqs.page_offs = trans_cfg->cb_data_offs;
1944 	trans->txqs.dev_cmd_offs = trans_cfg->cb_data_offs + sizeof(void *);
1945 
1946 	if (WARN_ON(trans_cfg->n_no_reclaim_cmds > MAX_NO_RECLAIM_CMDS))
1947 		trans_pcie->n_no_reclaim_cmds = 0;
1948 	else
1949 		trans_pcie->n_no_reclaim_cmds = trans_cfg->n_no_reclaim_cmds;
1950 	if (trans_pcie->n_no_reclaim_cmds)
1951 		memcpy(trans_pcie->no_reclaim_cmds, trans_cfg->no_reclaim_cmds,
1952 		       trans_pcie->n_no_reclaim_cmds * sizeof(u8));
1953 
1954 	trans_pcie->rx_buf_size = trans_cfg->rx_buf_size;
1955 	trans_pcie->rx_page_order =
1956 		iwl_trans_get_rb_size_order(trans_pcie->rx_buf_size);
1957 	trans_pcie->rx_buf_bytes =
1958 		iwl_trans_get_rb_size(trans_pcie->rx_buf_size);
1959 	trans_pcie->supported_dma_mask = DMA_BIT_MASK(12);
1960 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210)
1961 		trans_pcie->supported_dma_mask = DMA_BIT_MASK(11);
1962 
1963 	trans->txqs.bc_table_dword = trans_cfg->bc_table_dword;
1964 	trans_pcie->scd_set_active = trans_cfg->scd_set_active;
1965 
1966 	trans->command_groups = trans_cfg->command_groups;
1967 	trans->command_groups_size = trans_cfg->command_groups_size;
1968 
1969 	/* Initialize NAPI here - it should be before registering to mac80211
1970 	 * in the opmode but after the HW struct is allocated.
1971 	 * As this function may be called again in some corner cases don't
1972 	 * do anything if NAPI was already initialized.
1973 	 */
1974 	if (trans_pcie->napi_dev.reg_state != NETREG_DUMMY)
1975 		init_dummy_netdev(&trans_pcie->napi_dev);
1976 
1977 	trans_pcie->fw_reset_handshake = trans_cfg->fw_reset_handshake;
1978 }
1979 
1980 void iwl_trans_pcie_free(struct iwl_trans *trans)
1981 {
1982 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
1983 	int i;
1984 
1985 	iwl_pcie_synchronize_irqs(trans);
1986 
1987 	if (trans->trans_cfg->gen2)
1988 		iwl_txq_gen2_tx_free(trans);
1989 	else
1990 		iwl_pcie_tx_free(trans);
1991 	iwl_pcie_rx_free(trans);
1992 
1993 	if (trans_pcie->rba.alloc_wq) {
1994 		destroy_workqueue(trans_pcie->rba.alloc_wq);
1995 		trans_pcie->rba.alloc_wq = NULL;
1996 	}
1997 
1998 	if (trans_pcie->msix_enabled) {
1999 		for (i = 0; i < trans_pcie->alloc_vecs; i++) {
2000 			irq_set_affinity_hint(
2001 				trans_pcie->msix_entries[i].vector,
2002 				NULL);
2003 		}
2004 
2005 		trans_pcie->msix_enabled = false;
2006 	} else {
2007 		iwl_pcie_free_ict(trans);
2008 	}
2009 
2010 	iwl_pcie_free_fw_monitor(trans);
2011 
2012 	if (trans_pcie->pnvm_dram.size)
2013 		dma_free_coherent(trans->dev, trans_pcie->pnvm_dram.size,
2014 				  trans_pcie->pnvm_dram.block,
2015 				  trans_pcie->pnvm_dram.physical);
2016 
2017 	if (trans_pcie->reduce_power_dram.size)
2018 		dma_free_coherent(trans->dev,
2019 				  trans_pcie->reduce_power_dram.size,
2020 				  trans_pcie->reduce_power_dram.block,
2021 				  trans_pcie->reduce_power_dram.physical);
2022 
2023 	mutex_destroy(&trans_pcie->mutex);
2024 	iwl_trans_free(trans);
2025 }
2026 
2027 static void iwl_trans_pcie_set_pmi(struct iwl_trans *trans, bool state)
2028 {
2029 	if (state)
2030 		set_bit(STATUS_TPOWER_PMI, &trans->status);
2031 	else
2032 		clear_bit(STATUS_TPOWER_PMI, &trans->status);
2033 }
2034 
2035 struct iwl_trans_pcie_removal {
2036 	struct pci_dev *pdev;
2037 	struct work_struct work;
2038 };
2039 
2040 static void iwl_trans_pcie_removal_wk(struct work_struct *wk)
2041 {
2042 	struct iwl_trans_pcie_removal *removal =
2043 		container_of(wk, struct iwl_trans_pcie_removal, work);
2044 	struct pci_dev *pdev = removal->pdev;
2045 	static char *prop[] = {"EVENT=INACCESSIBLE", NULL};
2046 
2047 	dev_err(&pdev->dev, "Device gone - attempting removal\n");
2048 	kobject_uevent_env(&pdev->dev.kobj, KOBJ_CHANGE, prop);
2049 	pci_lock_rescan_remove();
2050 	pci_dev_put(pdev);
2051 	pci_stop_and_remove_bus_device(pdev);
2052 	pci_unlock_rescan_remove();
2053 
2054 	kfree(removal);
2055 	module_put(THIS_MODULE);
2056 }
2057 
2058 /*
2059  * This version doesn't disable BHs but rather assumes they're
2060  * already disabled.
2061  */
2062 bool __iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)
2063 {
2064 	int ret;
2065 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2066 	u32 write = CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ;
2067 	u32 mask = CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY |
2068 		   CSR_GP_CNTRL_REG_FLAG_GOING_TO_SLEEP;
2069 	u32 poll = CSR_GP_CNTRL_REG_VAL_MAC_ACCESS_EN;
2070 
2071 	spin_lock(&trans_pcie->reg_lock);
2072 
2073 	if (trans_pcie->cmd_hold_nic_awake)
2074 		goto out;
2075 
2076 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ) {
2077 		write = CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ;
2078 		mask = CSR_GP_CNTRL_REG_FLAG_MAC_STATUS;
2079 		poll = CSR_GP_CNTRL_REG_FLAG_MAC_STATUS;
2080 	}
2081 
2082 	/* this bit wakes up the NIC */
2083 	__iwl_trans_pcie_set_bit(trans, CSR_GP_CNTRL, write);
2084 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
2085 		udelay(2);
2086 
2087 	/*
2088 	 * These bits say the device is running, and should keep running for
2089 	 * at least a short while (at least as long as MAC_ACCESS_REQ stays 1),
2090 	 * but they do not indicate that embedded SRAM is restored yet;
2091 	 * HW with volatile SRAM must save/restore contents to/from
2092 	 * host DRAM when sleeping/waking for power-saving.
2093 	 * Each direction takes approximately 1/4 millisecond; with this
2094 	 * overhead, it's a good idea to grab and hold MAC_ACCESS_REQUEST if a
2095 	 * series of register accesses are expected (e.g. reading Event Log),
2096 	 * to keep device from sleeping.
2097 	 *
2098 	 * CSR_UCODE_DRV_GP1 register bit MAC_SLEEP == 0 indicates that
2099 	 * SRAM is okay/restored.  We don't check that here because this call
2100 	 * is just for hardware register access; but GP1 MAC_SLEEP
2101 	 * check is a good idea before accessing the SRAM of HW with
2102 	 * volatile SRAM (e.g. reading Event Log).
2103 	 *
2104 	 * 5000 series and later (including 1000 series) have non-volatile SRAM,
2105 	 * and do not save/restore SRAM when power cycling.
2106 	 */
2107 	ret = iwl_poll_bit(trans, CSR_GP_CNTRL, poll, mask, 15000);
2108 	if (unlikely(ret < 0)) {
2109 		u32 cntrl = iwl_read32(trans, CSR_GP_CNTRL);
2110 
2111 		WARN_ONCE(1,
2112 			  "Timeout waiting for hardware access (CSR_GP_CNTRL 0x%08x)\n",
2113 			  cntrl);
2114 
2115 		iwl_trans_pcie_dump_regs(trans);
2116 
2117 		if (iwlwifi_mod_params.remove_when_gone && cntrl == ~0U) {
2118 			struct iwl_trans_pcie_removal *removal;
2119 
2120 			if (test_bit(STATUS_TRANS_DEAD, &trans->status))
2121 				goto err;
2122 
2123 			IWL_ERR(trans, "Device gone - scheduling removal!\n");
2124 
2125 			/*
2126 			 * get a module reference to avoid doing this
2127 			 * while unloading anyway and to avoid
2128 			 * scheduling a work with code that's being
2129 			 * removed.
2130 			 */
2131 			if (!try_module_get(THIS_MODULE)) {
2132 				IWL_ERR(trans,
2133 					"Module is being unloaded - abort\n");
2134 				goto err;
2135 			}
2136 
2137 			removal = kzalloc(sizeof(*removal), GFP_ATOMIC);
2138 			if (!removal) {
2139 				module_put(THIS_MODULE);
2140 				goto err;
2141 			}
2142 			/*
2143 			 * we don't need to clear this flag, because
2144 			 * the trans will be freed and reallocated.
2145 			*/
2146 			set_bit(STATUS_TRANS_DEAD, &trans->status);
2147 
2148 			removal->pdev = to_pci_dev(trans->dev);
2149 			INIT_WORK(&removal->work, iwl_trans_pcie_removal_wk);
2150 			pci_dev_get(removal->pdev);
2151 			schedule_work(&removal->work);
2152 		} else {
2153 			iwl_write32(trans, CSR_RESET,
2154 				    CSR_RESET_REG_FLAG_FORCE_NMI);
2155 		}
2156 
2157 err:
2158 		spin_unlock(&trans_pcie->reg_lock);
2159 		return false;
2160 	}
2161 
2162 out:
2163 	/*
2164 	 * Fool sparse by faking we release the lock - sparse will
2165 	 * track nic_access anyway.
2166 	 */
2167 	__release(&trans_pcie->reg_lock);
2168 	return true;
2169 }
2170 
2171 static bool iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)
2172 {
2173 	bool ret;
2174 
2175 	local_bh_disable();
2176 	ret = __iwl_trans_pcie_grab_nic_access(trans);
2177 	if (ret) {
2178 		/* keep BHs disabled until iwl_trans_pcie_release_nic_access */
2179 		return ret;
2180 	}
2181 	local_bh_enable();
2182 	return false;
2183 }
2184 
2185 static void iwl_trans_pcie_release_nic_access(struct iwl_trans *trans)
2186 {
2187 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2188 
2189 	lockdep_assert_held(&trans_pcie->reg_lock);
2190 
2191 	/*
2192 	 * Fool sparse by faking we acquiring the lock - sparse will
2193 	 * track nic_access anyway.
2194 	 */
2195 	__acquire(&trans_pcie->reg_lock);
2196 
2197 	if (trans_pcie->cmd_hold_nic_awake)
2198 		goto out;
2199 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
2200 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
2201 					   CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ);
2202 	else
2203 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
2204 					   CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
2205 	/*
2206 	 * Above we read the CSR_GP_CNTRL register, which will flush
2207 	 * any previous writes, but we need the write that clears the
2208 	 * MAC_ACCESS_REQ bit to be performed before any other writes
2209 	 * scheduled on different CPUs (after we drop reg_lock).
2210 	 */
2211 out:
2212 	spin_unlock_bh(&trans_pcie->reg_lock);
2213 }
2214 
2215 static int iwl_trans_pcie_read_mem(struct iwl_trans *trans, u32 addr,
2216 				   void *buf, int dwords)
2217 {
2218 	int offs = 0;
2219 	u32 *vals = buf;
2220 
2221 	while (offs < dwords) {
2222 		/* limit the time we spin here under lock to 1/2s */
2223 		unsigned long end = jiffies + HZ / 2;
2224 		bool resched = false;
2225 
2226 		if (iwl_trans_grab_nic_access(trans)) {
2227 			iwl_write32(trans, HBUS_TARG_MEM_RADDR,
2228 				    addr + 4 * offs);
2229 
2230 			while (offs < dwords) {
2231 				vals[offs] = iwl_read32(trans,
2232 							HBUS_TARG_MEM_RDAT);
2233 				offs++;
2234 
2235 				if (time_after(jiffies, end)) {
2236 					resched = true;
2237 					break;
2238 				}
2239 			}
2240 			iwl_trans_release_nic_access(trans);
2241 
2242 			if (resched)
2243 				cond_resched();
2244 		} else {
2245 			return -EBUSY;
2246 		}
2247 	}
2248 
2249 	return 0;
2250 }
2251 
2252 static int iwl_trans_pcie_write_mem(struct iwl_trans *trans, u32 addr,
2253 				    const void *buf, int dwords)
2254 {
2255 	int offs, ret = 0;
2256 	const u32 *vals = buf;
2257 
2258 	if (iwl_trans_grab_nic_access(trans)) {
2259 		iwl_write32(trans, HBUS_TARG_MEM_WADDR, addr);
2260 		for (offs = 0; offs < dwords; offs++)
2261 			iwl_write32(trans, HBUS_TARG_MEM_WDAT,
2262 				    vals ? vals[offs] : 0);
2263 		iwl_trans_release_nic_access(trans);
2264 	} else {
2265 		ret = -EBUSY;
2266 	}
2267 	return ret;
2268 }
2269 
2270 static int iwl_trans_pcie_read_config32(struct iwl_trans *trans, u32 ofs,
2271 					u32 *val)
2272 {
2273 	return pci_read_config_dword(IWL_TRANS_GET_PCIE_TRANS(trans)->pci_dev,
2274 				     ofs, val);
2275 }
2276 
2277 static void iwl_trans_pcie_block_txq_ptrs(struct iwl_trans *trans, bool block)
2278 {
2279 	int i;
2280 
2281 	for (i = 0; i < trans->trans_cfg->base_params->num_of_queues; i++) {
2282 		struct iwl_txq *txq = trans->txqs.txq[i];
2283 
2284 		if (i == trans->txqs.cmd.q_id)
2285 			continue;
2286 
2287 		spin_lock_bh(&txq->lock);
2288 
2289 		if (!block && !(WARN_ON_ONCE(!txq->block))) {
2290 			txq->block--;
2291 			if (!txq->block) {
2292 				iwl_write32(trans, HBUS_TARG_WRPTR,
2293 					    txq->write_ptr | (i << 8));
2294 			}
2295 		} else if (block) {
2296 			txq->block++;
2297 		}
2298 
2299 		spin_unlock_bh(&txq->lock);
2300 	}
2301 }
2302 
2303 #define IWL_FLUSH_WAIT_MS	2000
2304 
2305 static int iwl_trans_pcie_rxq_dma_data(struct iwl_trans *trans, int queue,
2306 				       struct iwl_trans_rxq_dma_data *data)
2307 {
2308 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2309 
2310 	if (queue >= trans->num_rx_queues || !trans_pcie->rxq)
2311 		return -EINVAL;
2312 
2313 	data->fr_bd_cb = trans_pcie->rxq[queue].bd_dma;
2314 	data->urbd_stts_wrptr = trans_pcie->rxq[queue].rb_stts_dma;
2315 	data->ur_bd_cb = trans_pcie->rxq[queue].used_bd_dma;
2316 	data->fr_bd_wid = 0;
2317 
2318 	return 0;
2319 }
2320 
2321 static int iwl_trans_pcie_wait_txq_empty(struct iwl_trans *trans, int txq_idx)
2322 {
2323 	struct iwl_txq *txq;
2324 	unsigned long now = jiffies;
2325 	bool overflow_tx;
2326 	u8 wr_ptr;
2327 
2328 	/* Make sure the NIC is still alive in the bus */
2329 	if (test_bit(STATUS_TRANS_DEAD, &trans->status))
2330 		return -ENODEV;
2331 
2332 	if (!test_bit(txq_idx, trans->txqs.queue_used))
2333 		return -EINVAL;
2334 
2335 	IWL_DEBUG_TX_QUEUES(trans, "Emptying queue %d...\n", txq_idx);
2336 	txq = trans->txqs.txq[txq_idx];
2337 
2338 	spin_lock_bh(&txq->lock);
2339 	overflow_tx = txq->overflow_tx ||
2340 		      !skb_queue_empty(&txq->overflow_q);
2341 	spin_unlock_bh(&txq->lock);
2342 
2343 	wr_ptr = READ_ONCE(txq->write_ptr);
2344 
2345 	while ((txq->read_ptr != READ_ONCE(txq->write_ptr) ||
2346 		overflow_tx) &&
2347 	       !time_after(jiffies,
2348 			   now + msecs_to_jiffies(IWL_FLUSH_WAIT_MS))) {
2349 		u8 write_ptr = READ_ONCE(txq->write_ptr);
2350 
2351 		/*
2352 		 * If write pointer moved during the wait, warn only
2353 		 * if the TX came from op mode. In case TX came from
2354 		 * trans layer (overflow TX) don't warn.
2355 		 */
2356 		if (WARN_ONCE(wr_ptr != write_ptr && !overflow_tx,
2357 			      "WR pointer moved while flushing %d -> %d\n",
2358 			      wr_ptr, write_ptr))
2359 			return -ETIMEDOUT;
2360 		wr_ptr = write_ptr;
2361 
2362 		usleep_range(1000, 2000);
2363 
2364 		spin_lock_bh(&txq->lock);
2365 		overflow_tx = txq->overflow_tx ||
2366 			      !skb_queue_empty(&txq->overflow_q);
2367 		spin_unlock_bh(&txq->lock);
2368 	}
2369 
2370 	if (txq->read_ptr != txq->write_ptr) {
2371 		IWL_ERR(trans,
2372 			"fail to flush all tx fifo queues Q %d\n", txq_idx);
2373 		iwl_txq_log_scd_error(trans, txq);
2374 		return -ETIMEDOUT;
2375 	}
2376 
2377 	IWL_DEBUG_TX_QUEUES(trans, "Queue %d is now empty.\n", txq_idx);
2378 
2379 	return 0;
2380 }
2381 
2382 static int iwl_trans_pcie_wait_txqs_empty(struct iwl_trans *trans, u32 txq_bm)
2383 {
2384 	int cnt;
2385 	int ret = 0;
2386 
2387 	/* waiting for all the tx frames complete might take a while */
2388 	for (cnt = 0;
2389 	     cnt < trans->trans_cfg->base_params->num_of_queues;
2390 	     cnt++) {
2391 
2392 		if (cnt == trans->txqs.cmd.q_id)
2393 			continue;
2394 		if (!test_bit(cnt, trans->txqs.queue_used))
2395 			continue;
2396 		if (!(BIT(cnt) & txq_bm))
2397 			continue;
2398 
2399 		ret = iwl_trans_pcie_wait_txq_empty(trans, cnt);
2400 		if (ret)
2401 			break;
2402 	}
2403 
2404 	return ret;
2405 }
2406 
2407 static void iwl_trans_pcie_set_bits_mask(struct iwl_trans *trans, u32 reg,
2408 					 u32 mask, u32 value)
2409 {
2410 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2411 
2412 	spin_lock_bh(&trans_pcie->reg_lock);
2413 	__iwl_trans_pcie_set_bits_mask(trans, reg, mask, value);
2414 	spin_unlock_bh(&trans_pcie->reg_lock);
2415 }
2416 
2417 static const char *get_csr_string(int cmd)
2418 {
2419 #define IWL_CMD(x) case x: return #x
2420 	switch (cmd) {
2421 	IWL_CMD(CSR_HW_IF_CONFIG_REG);
2422 	IWL_CMD(CSR_INT_COALESCING);
2423 	IWL_CMD(CSR_INT);
2424 	IWL_CMD(CSR_INT_MASK);
2425 	IWL_CMD(CSR_FH_INT_STATUS);
2426 	IWL_CMD(CSR_GPIO_IN);
2427 	IWL_CMD(CSR_RESET);
2428 	IWL_CMD(CSR_GP_CNTRL);
2429 	IWL_CMD(CSR_HW_REV);
2430 	IWL_CMD(CSR_EEPROM_REG);
2431 	IWL_CMD(CSR_EEPROM_GP);
2432 	IWL_CMD(CSR_OTP_GP_REG);
2433 	IWL_CMD(CSR_GIO_REG);
2434 	IWL_CMD(CSR_GP_UCODE_REG);
2435 	IWL_CMD(CSR_GP_DRIVER_REG);
2436 	IWL_CMD(CSR_UCODE_DRV_GP1);
2437 	IWL_CMD(CSR_UCODE_DRV_GP2);
2438 	IWL_CMD(CSR_LED_REG);
2439 	IWL_CMD(CSR_DRAM_INT_TBL_REG);
2440 	IWL_CMD(CSR_GIO_CHICKEN_BITS);
2441 	IWL_CMD(CSR_ANA_PLL_CFG);
2442 	IWL_CMD(CSR_HW_REV_WA_REG);
2443 	IWL_CMD(CSR_MONITOR_STATUS_REG);
2444 	IWL_CMD(CSR_DBG_HPET_MEM_REG);
2445 	default:
2446 		return "UNKNOWN";
2447 	}
2448 #undef IWL_CMD
2449 }
2450 
2451 void iwl_pcie_dump_csr(struct iwl_trans *trans)
2452 {
2453 	int i;
2454 	static const u32 csr_tbl[] = {
2455 		CSR_HW_IF_CONFIG_REG,
2456 		CSR_INT_COALESCING,
2457 		CSR_INT,
2458 		CSR_INT_MASK,
2459 		CSR_FH_INT_STATUS,
2460 		CSR_GPIO_IN,
2461 		CSR_RESET,
2462 		CSR_GP_CNTRL,
2463 		CSR_HW_REV,
2464 		CSR_EEPROM_REG,
2465 		CSR_EEPROM_GP,
2466 		CSR_OTP_GP_REG,
2467 		CSR_GIO_REG,
2468 		CSR_GP_UCODE_REG,
2469 		CSR_GP_DRIVER_REG,
2470 		CSR_UCODE_DRV_GP1,
2471 		CSR_UCODE_DRV_GP2,
2472 		CSR_LED_REG,
2473 		CSR_DRAM_INT_TBL_REG,
2474 		CSR_GIO_CHICKEN_BITS,
2475 		CSR_ANA_PLL_CFG,
2476 		CSR_MONITOR_STATUS_REG,
2477 		CSR_HW_REV_WA_REG,
2478 		CSR_DBG_HPET_MEM_REG
2479 	};
2480 	IWL_ERR(trans, "CSR values:\n");
2481 	IWL_ERR(trans, "(2nd byte of CSR_INT_COALESCING is "
2482 		"CSR_INT_PERIODIC_REG)\n");
2483 	for (i = 0; i <  ARRAY_SIZE(csr_tbl); i++) {
2484 		IWL_ERR(trans, "  %25s: 0X%08x\n",
2485 			get_csr_string(csr_tbl[i]),
2486 			iwl_read32(trans, csr_tbl[i]));
2487 	}
2488 }
2489 
2490 #ifdef CONFIG_IWLWIFI_DEBUGFS
2491 /* create and remove of files */
2492 #define DEBUGFS_ADD_FILE(name, parent, mode) do {			\
2493 	debugfs_create_file(#name, mode, parent, trans,			\
2494 			    &iwl_dbgfs_##name##_ops);			\
2495 } while (0)
2496 
2497 /* file operation */
2498 #define DEBUGFS_READ_FILE_OPS(name)					\
2499 static const struct file_operations iwl_dbgfs_##name##_ops = {		\
2500 	.read = iwl_dbgfs_##name##_read,				\
2501 	.open = simple_open,						\
2502 	.llseek = generic_file_llseek,					\
2503 };
2504 
2505 #define DEBUGFS_WRITE_FILE_OPS(name)                                    \
2506 static const struct file_operations iwl_dbgfs_##name##_ops = {          \
2507 	.write = iwl_dbgfs_##name##_write,                              \
2508 	.open = simple_open,						\
2509 	.llseek = generic_file_llseek,					\
2510 };
2511 
2512 #define DEBUGFS_READ_WRITE_FILE_OPS(name)				\
2513 static const struct file_operations iwl_dbgfs_##name##_ops = {		\
2514 	.write = iwl_dbgfs_##name##_write,				\
2515 	.read = iwl_dbgfs_##name##_read,				\
2516 	.open = simple_open,						\
2517 	.llseek = generic_file_llseek,					\
2518 };
2519 
2520 struct iwl_dbgfs_tx_queue_priv {
2521 	struct iwl_trans *trans;
2522 };
2523 
2524 struct iwl_dbgfs_tx_queue_state {
2525 	loff_t pos;
2526 };
2527 
2528 static void *iwl_dbgfs_tx_queue_seq_start(struct seq_file *seq, loff_t *pos)
2529 {
2530 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
2531 	struct iwl_dbgfs_tx_queue_state *state;
2532 
2533 	if (*pos >= priv->trans->trans_cfg->base_params->num_of_queues)
2534 		return NULL;
2535 
2536 	state = kmalloc(sizeof(*state), GFP_KERNEL);
2537 	if (!state)
2538 		return NULL;
2539 	state->pos = *pos;
2540 	return state;
2541 }
2542 
2543 static void *iwl_dbgfs_tx_queue_seq_next(struct seq_file *seq,
2544 					 void *v, loff_t *pos)
2545 {
2546 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
2547 	struct iwl_dbgfs_tx_queue_state *state = v;
2548 
2549 	*pos = ++state->pos;
2550 
2551 	if (*pos >= priv->trans->trans_cfg->base_params->num_of_queues)
2552 		return NULL;
2553 
2554 	return state;
2555 }
2556 
2557 static void iwl_dbgfs_tx_queue_seq_stop(struct seq_file *seq, void *v)
2558 {
2559 	kfree(v);
2560 }
2561 
2562 static int iwl_dbgfs_tx_queue_seq_show(struct seq_file *seq, void *v)
2563 {
2564 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
2565 	struct iwl_dbgfs_tx_queue_state *state = v;
2566 	struct iwl_trans *trans = priv->trans;
2567 	struct iwl_txq *txq = trans->txqs.txq[state->pos];
2568 
2569 	seq_printf(seq, "hwq %.3u: used=%d stopped=%d ",
2570 		   (unsigned int)state->pos,
2571 		   !!test_bit(state->pos, trans->txqs.queue_used),
2572 		   !!test_bit(state->pos, trans->txqs.queue_stopped));
2573 	if (txq)
2574 		seq_printf(seq,
2575 			   "read=%u write=%u need_update=%d frozen=%d n_window=%d ampdu=%d",
2576 			   txq->read_ptr, txq->write_ptr,
2577 			   txq->need_update, txq->frozen,
2578 			   txq->n_window, txq->ampdu);
2579 	else
2580 		seq_puts(seq, "(unallocated)");
2581 
2582 	if (state->pos == trans->txqs.cmd.q_id)
2583 		seq_puts(seq, " (HCMD)");
2584 	seq_puts(seq, "\n");
2585 
2586 	return 0;
2587 }
2588 
2589 static const struct seq_operations iwl_dbgfs_tx_queue_seq_ops = {
2590 	.start = iwl_dbgfs_tx_queue_seq_start,
2591 	.next = iwl_dbgfs_tx_queue_seq_next,
2592 	.stop = iwl_dbgfs_tx_queue_seq_stop,
2593 	.show = iwl_dbgfs_tx_queue_seq_show,
2594 };
2595 
2596 static int iwl_dbgfs_tx_queue_open(struct inode *inode, struct file *filp)
2597 {
2598 	struct iwl_dbgfs_tx_queue_priv *priv;
2599 
2600 	priv = __seq_open_private(filp, &iwl_dbgfs_tx_queue_seq_ops,
2601 				  sizeof(*priv));
2602 
2603 	if (!priv)
2604 		return -ENOMEM;
2605 
2606 	priv->trans = inode->i_private;
2607 	return 0;
2608 }
2609 
2610 static ssize_t iwl_dbgfs_rx_queue_read(struct file *file,
2611 				       char __user *user_buf,
2612 				       size_t count, loff_t *ppos)
2613 {
2614 	struct iwl_trans *trans = file->private_data;
2615 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2616 	char *buf;
2617 	int pos = 0, i, ret;
2618 	size_t bufsz;
2619 
2620 	bufsz = sizeof(char) * 121 * trans->num_rx_queues;
2621 
2622 	if (!trans_pcie->rxq)
2623 		return -EAGAIN;
2624 
2625 	buf = kzalloc(bufsz, GFP_KERNEL);
2626 	if (!buf)
2627 		return -ENOMEM;
2628 
2629 	for (i = 0; i < trans->num_rx_queues && pos < bufsz; i++) {
2630 		struct iwl_rxq *rxq = &trans_pcie->rxq[i];
2631 
2632 		pos += scnprintf(buf + pos, bufsz - pos, "queue#: %2d\n",
2633 				 i);
2634 		pos += scnprintf(buf + pos, bufsz - pos, "\tread: %u\n",
2635 				 rxq->read);
2636 		pos += scnprintf(buf + pos, bufsz - pos, "\twrite: %u\n",
2637 				 rxq->write);
2638 		pos += scnprintf(buf + pos, bufsz - pos, "\twrite_actual: %u\n",
2639 				 rxq->write_actual);
2640 		pos += scnprintf(buf + pos, bufsz - pos, "\tneed_update: %2d\n",
2641 				 rxq->need_update);
2642 		pos += scnprintf(buf + pos, bufsz - pos, "\tfree_count: %u\n",
2643 				 rxq->free_count);
2644 		if (rxq->rb_stts) {
2645 			u32 r =	__le16_to_cpu(iwl_get_closed_rb_stts(trans,
2646 								     rxq));
2647 			pos += scnprintf(buf + pos, bufsz - pos,
2648 					 "\tclosed_rb_num: %u\n",
2649 					 r & 0x0FFF);
2650 		} else {
2651 			pos += scnprintf(buf + pos, bufsz - pos,
2652 					 "\tclosed_rb_num: Not Allocated\n");
2653 		}
2654 	}
2655 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
2656 	kfree(buf);
2657 
2658 	return ret;
2659 }
2660 
2661 static ssize_t iwl_dbgfs_interrupt_read(struct file *file,
2662 					char __user *user_buf,
2663 					size_t count, loff_t *ppos)
2664 {
2665 	struct iwl_trans *trans = file->private_data;
2666 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2667 	struct isr_statistics *isr_stats = &trans_pcie->isr_stats;
2668 
2669 	int pos = 0;
2670 	char *buf;
2671 	int bufsz = 24 * 64; /* 24 items * 64 char per item */
2672 	ssize_t ret;
2673 
2674 	buf = kzalloc(bufsz, GFP_KERNEL);
2675 	if (!buf)
2676 		return -ENOMEM;
2677 
2678 	pos += scnprintf(buf + pos, bufsz - pos,
2679 			"Interrupt Statistics Report:\n");
2680 
2681 	pos += scnprintf(buf + pos, bufsz - pos, "HW Error:\t\t\t %u\n",
2682 		isr_stats->hw);
2683 	pos += scnprintf(buf + pos, bufsz - pos, "SW Error:\t\t\t %u\n",
2684 		isr_stats->sw);
2685 	if (isr_stats->sw || isr_stats->hw) {
2686 		pos += scnprintf(buf + pos, bufsz - pos,
2687 			"\tLast Restarting Code:  0x%X\n",
2688 			isr_stats->err_code);
2689 	}
2690 #ifdef CONFIG_IWLWIFI_DEBUG
2691 	pos += scnprintf(buf + pos, bufsz - pos, "Frame transmitted:\t\t %u\n",
2692 		isr_stats->sch);
2693 	pos += scnprintf(buf + pos, bufsz - pos, "Alive interrupt:\t\t %u\n",
2694 		isr_stats->alive);
2695 #endif
2696 	pos += scnprintf(buf + pos, bufsz - pos,
2697 		"HW RF KILL switch toggled:\t %u\n", isr_stats->rfkill);
2698 
2699 	pos += scnprintf(buf + pos, bufsz - pos, "CT KILL:\t\t\t %u\n",
2700 		isr_stats->ctkill);
2701 
2702 	pos += scnprintf(buf + pos, bufsz - pos, "Wakeup Interrupt:\t\t %u\n",
2703 		isr_stats->wakeup);
2704 
2705 	pos += scnprintf(buf + pos, bufsz - pos,
2706 		"Rx command responses:\t\t %u\n", isr_stats->rx);
2707 
2708 	pos += scnprintf(buf + pos, bufsz - pos, "Tx/FH interrupt:\t\t %u\n",
2709 		isr_stats->tx);
2710 
2711 	pos += scnprintf(buf + pos, bufsz - pos, "Unexpected INTA:\t\t %u\n",
2712 		isr_stats->unhandled);
2713 
2714 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
2715 	kfree(buf);
2716 	return ret;
2717 }
2718 
2719 static ssize_t iwl_dbgfs_interrupt_write(struct file *file,
2720 					 const char __user *user_buf,
2721 					 size_t count, loff_t *ppos)
2722 {
2723 	struct iwl_trans *trans = file->private_data;
2724 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2725 	struct isr_statistics *isr_stats = &trans_pcie->isr_stats;
2726 	u32 reset_flag;
2727 	int ret;
2728 
2729 	ret = kstrtou32_from_user(user_buf, count, 16, &reset_flag);
2730 	if (ret)
2731 		return ret;
2732 	if (reset_flag == 0)
2733 		memset(isr_stats, 0, sizeof(*isr_stats));
2734 
2735 	return count;
2736 }
2737 
2738 static ssize_t iwl_dbgfs_csr_write(struct file *file,
2739 				   const char __user *user_buf,
2740 				   size_t count, loff_t *ppos)
2741 {
2742 	struct iwl_trans *trans = file->private_data;
2743 
2744 	iwl_pcie_dump_csr(trans);
2745 
2746 	return count;
2747 }
2748 
2749 static ssize_t iwl_dbgfs_fh_reg_read(struct file *file,
2750 				     char __user *user_buf,
2751 				     size_t count, loff_t *ppos)
2752 {
2753 	struct iwl_trans *trans = file->private_data;
2754 	char *buf = NULL;
2755 	ssize_t ret;
2756 
2757 	ret = iwl_dump_fh(trans, &buf);
2758 	if (ret < 0)
2759 		return ret;
2760 	if (!buf)
2761 		return -EINVAL;
2762 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
2763 	kfree(buf);
2764 	return ret;
2765 }
2766 
2767 static ssize_t iwl_dbgfs_rfkill_read(struct file *file,
2768 				     char __user *user_buf,
2769 				     size_t count, loff_t *ppos)
2770 {
2771 	struct iwl_trans *trans = file->private_data;
2772 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2773 	char buf[100];
2774 	int pos;
2775 
2776 	pos = scnprintf(buf, sizeof(buf), "debug: %d\nhw: %d\n",
2777 			trans_pcie->debug_rfkill,
2778 			!(iwl_read32(trans, CSR_GP_CNTRL) &
2779 				CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW));
2780 
2781 	return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
2782 }
2783 
2784 static ssize_t iwl_dbgfs_rfkill_write(struct file *file,
2785 				      const char __user *user_buf,
2786 				      size_t count, loff_t *ppos)
2787 {
2788 	struct iwl_trans *trans = file->private_data;
2789 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2790 	bool new_value;
2791 	int ret;
2792 
2793 	ret = kstrtobool_from_user(user_buf, count, &new_value);
2794 	if (ret)
2795 		return ret;
2796 	if (new_value == trans_pcie->debug_rfkill)
2797 		return count;
2798 	IWL_WARN(trans, "changing debug rfkill %d->%d\n",
2799 		 trans_pcie->debug_rfkill, new_value);
2800 	trans_pcie->debug_rfkill = new_value;
2801 	iwl_pcie_handle_rfkill_irq(trans);
2802 
2803 	return count;
2804 }
2805 
2806 static int iwl_dbgfs_monitor_data_open(struct inode *inode,
2807 				       struct file *file)
2808 {
2809 	struct iwl_trans *trans = inode->i_private;
2810 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2811 
2812 	if (!trans->dbg.dest_tlv ||
2813 	    trans->dbg.dest_tlv->monitor_mode != EXTERNAL_MODE) {
2814 		IWL_ERR(trans, "Debug destination is not set to DRAM\n");
2815 		return -ENOENT;
2816 	}
2817 
2818 	if (trans_pcie->fw_mon_data.state != IWL_FW_MON_DBGFS_STATE_CLOSED)
2819 		return -EBUSY;
2820 
2821 	trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_OPEN;
2822 	return simple_open(inode, file);
2823 }
2824 
2825 static int iwl_dbgfs_monitor_data_release(struct inode *inode,
2826 					  struct file *file)
2827 {
2828 	struct iwl_trans_pcie *trans_pcie =
2829 		IWL_TRANS_GET_PCIE_TRANS(inode->i_private);
2830 
2831 	if (trans_pcie->fw_mon_data.state == IWL_FW_MON_DBGFS_STATE_OPEN)
2832 		trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;
2833 	return 0;
2834 }
2835 
2836 static bool iwl_write_to_user_buf(char __user *user_buf, ssize_t count,
2837 				  void *buf, ssize_t *size,
2838 				  ssize_t *bytes_copied)
2839 {
2840 	int buf_size_left = count - *bytes_copied;
2841 
2842 	buf_size_left = buf_size_left - (buf_size_left % sizeof(u32));
2843 	if (*size > buf_size_left)
2844 		*size = buf_size_left;
2845 
2846 	*size -= copy_to_user(user_buf, buf, *size);
2847 	*bytes_copied += *size;
2848 
2849 	if (buf_size_left == *size)
2850 		return true;
2851 	return false;
2852 }
2853 
2854 static ssize_t iwl_dbgfs_monitor_data_read(struct file *file,
2855 					   char __user *user_buf,
2856 					   size_t count, loff_t *ppos)
2857 {
2858 	struct iwl_trans *trans = file->private_data;
2859 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2860 	void *cpu_addr = (void *)trans->dbg.fw_mon.block, *curr_buf;
2861 	struct cont_rec *data = &trans_pcie->fw_mon_data;
2862 	u32 write_ptr_addr, wrap_cnt_addr, write_ptr, wrap_cnt;
2863 	ssize_t size, bytes_copied = 0;
2864 	bool b_full;
2865 
2866 	if (trans->dbg.dest_tlv) {
2867 		write_ptr_addr =
2868 			le32_to_cpu(trans->dbg.dest_tlv->write_ptr_reg);
2869 		wrap_cnt_addr = le32_to_cpu(trans->dbg.dest_tlv->wrap_count);
2870 	} else {
2871 		write_ptr_addr = MON_BUFF_WRPTR;
2872 		wrap_cnt_addr = MON_BUFF_CYCLE_CNT;
2873 	}
2874 
2875 	if (unlikely(!trans->dbg.rec_on))
2876 		return 0;
2877 
2878 	mutex_lock(&data->mutex);
2879 	if (data->state ==
2880 	    IWL_FW_MON_DBGFS_STATE_DISABLED) {
2881 		mutex_unlock(&data->mutex);
2882 		return 0;
2883 	}
2884 
2885 	/* write_ptr position in bytes rather then DW */
2886 	write_ptr = iwl_read_prph(trans, write_ptr_addr) * sizeof(u32);
2887 	wrap_cnt = iwl_read_prph(trans, wrap_cnt_addr);
2888 
2889 	if (data->prev_wrap_cnt == wrap_cnt) {
2890 		size = write_ptr - data->prev_wr_ptr;
2891 		curr_buf = cpu_addr + data->prev_wr_ptr;
2892 		b_full = iwl_write_to_user_buf(user_buf, count,
2893 					       curr_buf, &size,
2894 					       &bytes_copied);
2895 		data->prev_wr_ptr += size;
2896 
2897 	} else if (data->prev_wrap_cnt == wrap_cnt - 1 &&
2898 		   write_ptr < data->prev_wr_ptr) {
2899 		size = trans->dbg.fw_mon.size - data->prev_wr_ptr;
2900 		curr_buf = cpu_addr + data->prev_wr_ptr;
2901 		b_full = iwl_write_to_user_buf(user_buf, count,
2902 					       curr_buf, &size,
2903 					       &bytes_copied);
2904 		data->prev_wr_ptr += size;
2905 
2906 		if (!b_full) {
2907 			size = write_ptr;
2908 			b_full = iwl_write_to_user_buf(user_buf, count,
2909 						       cpu_addr, &size,
2910 						       &bytes_copied);
2911 			data->prev_wr_ptr = size;
2912 			data->prev_wrap_cnt++;
2913 		}
2914 	} else {
2915 		if (data->prev_wrap_cnt == wrap_cnt - 1 &&
2916 		    write_ptr > data->prev_wr_ptr)
2917 			IWL_WARN(trans,
2918 				 "write pointer passed previous write pointer, start copying from the beginning\n");
2919 		else if (!unlikely(data->prev_wrap_cnt == 0 &&
2920 				   data->prev_wr_ptr == 0))
2921 			IWL_WARN(trans,
2922 				 "monitor data is out of sync, start copying from the beginning\n");
2923 
2924 		size = write_ptr;
2925 		b_full = iwl_write_to_user_buf(user_buf, count,
2926 					       cpu_addr, &size,
2927 					       &bytes_copied);
2928 		data->prev_wr_ptr = size;
2929 		data->prev_wrap_cnt = wrap_cnt;
2930 	}
2931 
2932 	mutex_unlock(&data->mutex);
2933 
2934 	return bytes_copied;
2935 }
2936 
2937 static ssize_t iwl_dbgfs_rf_read(struct file *file,
2938 				 char __user *user_buf,
2939 				 size_t count, loff_t *ppos)
2940 {
2941 	struct iwl_trans *trans = file->private_data;
2942 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2943 
2944 	if (!trans_pcie->rf_name[0])
2945 		return -ENODEV;
2946 
2947 	return simple_read_from_buffer(user_buf, count, ppos,
2948 				       trans_pcie->rf_name,
2949 				       strlen(trans_pcie->rf_name));
2950 }
2951 
2952 DEBUGFS_READ_WRITE_FILE_OPS(interrupt);
2953 DEBUGFS_READ_FILE_OPS(fh_reg);
2954 DEBUGFS_READ_FILE_OPS(rx_queue);
2955 DEBUGFS_WRITE_FILE_OPS(csr);
2956 DEBUGFS_READ_WRITE_FILE_OPS(rfkill);
2957 DEBUGFS_READ_FILE_OPS(rf);
2958 
2959 static const struct file_operations iwl_dbgfs_tx_queue_ops = {
2960 	.owner = THIS_MODULE,
2961 	.open = iwl_dbgfs_tx_queue_open,
2962 	.read = seq_read,
2963 	.llseek = seq_lseek,
2964 	.release = seq_release_private,
2965 };
2966 
2967 static const struct file_operations iwl_dbgfs_monitor_data_ops = {
2968 	.read = iwl_dbgfs_monitor_data_read,
2969 	.open = iwl_dbgfs_monitor_data_open,
2970 	.release = iwl_dbgfs_monitor_data_release,
2971 };
2972 
2973 /* Create the debugfs files and directories */
2974 void iwl_trans_pcie_dbgfs_register(struct iwl_trans *trans)
2975 {
2976 	struct dentry *dir = trans->dbgfs_dir;
2977 
2978 	DEBUGFS_ADD_FILE(rx_queue, dir, 0400);
2979 	DEBUGFS_ADD_FILE(tx_queue, dir, 0400);
2980 	DEBUGFS_ADD_FILE(interrupt, dir, 0600);
2981 	DEBUGFS_ADD_FILE(csr, dir, 0200);
2982 	DEBUGFS_ADD_FILE(fh_reg, dir, 0400);
2983 	DEBUGFS_ADD_FILE(rfkill, dir, 0600);
2984 	DEBUGFS_ADD_FILE(monitor_data, dir, 0400);
2985 	DEBUGFS_ADD_FILE(rf, dir, 0400);
2986 }
2987 
2988 static void iwl_trans_pcie_debugfs_cleanup(struct iwl_trans *trans)
2989 {
2990 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
2991 	struct cont_rec *data = &trans_pcie->fw_mon_data;
2992 
2993 	mutex_lock(&data->mutex);
2994 	data->state = IWL_FW_MON_DBGFS_STATE_DISABLED;
2995 	mutex_unlock(&data->mutex);
2996 }
2997 #endif /*CONFIG_IWLWIFI_DEBUGFS */
2998 
2999 static u32 iwl_trans_pcie_get_cmdlen(struct iwl_trans *trans, void *tfd)
3000 {
3001 	u32 cmdlen = 0;
3002 	int i;
3003 
3004 	for (i = 0; i < trans->txqs.tfd.max_tbs; i++)
3005 		cmdlen += iwl_txq_gen1_tfd_tb_get_len(trans, tfd, i);
3006 
3007 	return cmdlen;
3008 }
3009 
3010 static u32 iwl_trans_pcie_dump_rbs(struct iwl_trans *trans,
3011 				   struct iwl_fw_error_dump_data **data,
3012 				   int allocated_rb_nums)
3013 {
3014 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
3015 	int max_len = trans_pcie->rx_buf_bytes;
3016 	/* Dump RBs is supported only for pre-9000 devices (1 queue) */
3017 	struct iwl_rxq *rxq = &trans_pcie->rxq[0];
3018 	u32 i, r, j, rb_len = 0;
3019 
3020 	spin_lock(&rxq->lock);
3021 
3022 	r = le16_to_cpu(iwl_get_closed_rb_stts(trans, rxq)) & 0x0FFF;
3023 
3024 	for (i = rxq->read, j = 0;
3025 	     i != r && j < allocated_rb_nums;
3026 	     i = (i + 1) & RX_QUEUE_MASK, j++) {
3027 		struct iwl_rx_mem_buffer *rxb = rxq->queue[i];
3028 		struct iwl_fw_error_dump_rb *rb;
3029 
3030 		dma_sync_single_for_cpu(trans->dev, rxb->page_dma,
3031 					max_len, DMA_FROM_DEVICE);
3032 
3033 		rb_len += sizeof(**data) + sizeof(*rb) + max_len;
3034 
3035 		(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_RB);
3036 		(*data)->len = cpu_to_le32(sizeof(*rb) + max_len);
3037 		rb = (void *)(*data)->data;
3038 		rb->index = cpu_to_le32(i);
3039 		memcpy(rb->data, page_address(rxb->page), max_len);
3040 
3041 		*data = iwl_fw_error_next_data(*data);
3042 	}
3043 
3044 	spin_unlock(&rxq->lock);
3045 
3046 	return rb_len;
3047 }
3048 #define IWL_CSR_TO_DUMP (0x250)
3049 
3050 static u32 iwl_trans_pcie_dump_csr(struct iwl_trans *trans,
3051 				   struct iwl_fw_error_dump_data **data)
3052 {
3053 	u32 csr_len = sizeof(**data) + IWL_CSR_TO_DUMP;
3054 	__le32 *val;
3055 	int i;
3056 
3057 	(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_CSR);
3058 	(*data)->len = cpu_to_le32(IWL_CSR_TO_DUMP);
3059 	val = (void *)(*data)->data;
3060 
3061 	for (i = 0; i < IWL_CSR_TO_DUMP; i += 4)
3062 		*val++ = cpu_to_le32(iwl_trans_pcie_read32(trans, i));
3063 
3064 	*data = iwl_fw_error_next_data(*data);
3065 
3066 	return csr_len;
3067 }
3068 
3069 static u32 iwl_trans_pcie_fh_regs_dump(struct iwl_trans *trans,
3070 				       struct iwl_fw_error_dump_data **data)
3071 {
3072 	u32 fh_regs_len = FH_MEM_UPPER_BOUND - FH_MEM_LOWER_BOUND;
3073 	__le32 *val;
3074 	int i;
3075 
3076 	if (!iwl_trans_grab_nic_access(trans))
3077 		return 0;
3078 
3079 	(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_FH_REGS);
3080 	(*data)->len = cpu_to_le32(fh_regs_len);
3081 	val = (void *)(*data)->data;
3082 
3083 	if (!trans->trans_cfg->gen2)
3084 		for (i = FH_MEM_LOWER_BOUND; i < FH_MEM_UPPER_BOUND;
3085 		     i += sizeof(u32))
3086 			*val++ = cpu_to_le32(iwl_trans_pcie_read32(trans, i));
3087 	else
3088 		for (i = iwl_umac_prph(trans, FH_MEM_LOWER_BOUND_GEN2);
3089 		     i < iwl_umac_prph(trans, FH_MEM_UPPER_BOUND_GEN2);
3090 		     i += sizeof(u32))
3091 			*val++ = cpu_to_le32(iwl_trans_pcie_read_prph(trans,
3092 								      i));
3093 
3094 	iwl_trans_release_nic_access(trans);
3095 
3096 	*data = iwl_fw_error_next_data(*data);
3097 
3098 	return sizeof(**data) + fh_regs_len;
3099 }
3100 
3101 static u32
3102 iwl_trans_pci_dump_marbh_monitor(struct iwl_trans *trans,
3103 				 struct iwl_fw_error_dump_fw_mon *fw_mon_data,
3104 				 u32 monitor_len)
3105 {
3106 	u32 buf_size_in_dwords = (monitor_len >> 2);
3107 	u32 *buffer = (u32 *)fw_mon_data->data;
3108 	u32 i;
3109 
3110 	if (!iwl_trans_grab_nic_access(trans))
3111 		return 0;
3112 
3113 	iwl_write_umac_prph_no_grab(trans, MON_DMARB_RD_CTL_ADDR, 0x1);
3114 	for (i = 0; i < buf_size_in_dwords; i++)
3115 		buffer[i] = iwl_read_umac_prph_no_grab(trans,
3116 						       MON_DMARB_RD_DATA_ADDR);
3117 	iwl_write_umac_prph_no_grab(trans, MON_DMARB_RD_CTL_ADDR, 0x0);
3118 
3119 	iwl_trans_release_nic_access(trans);
3120 
3121 	return monitor_len;
3122 }
3123 
3124 static void
3125 iwl_trans_pcie_dump_pointers(struct iwl_trans *trans,
3126 			     struct iwl_fw_error_dump_fw_mon *fw_mon_data)
3127 {
3128 	u32 base, base_high, write_ptr, write_ptr_val, wrap_cnt;
3129 
3130 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
3131 		base = DBGC_CUR_DBGBUF_BASE_ADDR_LSB;
3132 		base_high = DBGC_CUR_DBGBUF_BASE_ADDR_MSB;
3133 		write_ptr = DBGC_CUR_DBGBUF_STATUS;
3134 		wrap_cnt = DBGC_DBGBUF_WRAP_AROUND;
3135 	} else if (trans->dbg.dest_tlv) {
3136 		write_ptr = le32_to_cpu(trans->dbg.dest_tlv->write_ptr_reg);
3137 		wrap_cnt = le32_to_cpu(trans->dbg.dest_tlv->wrap_count);
3138 		base = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
3139 	} else {
3140 		base = MON_BUFF_BASE_ADDR;
3141 		write_ptr = MON_BUFF_WRPTR;
3142 		wrap_cnt = MON_BUFF_CYCLE_CNT;
3143 	}
3144 
3145 	write_ptr_val = iwl_read_prph(trans, write_ptr);
3146 	fw_mon_data->fw_mon_cycle_cnt =
3147 		cpu_to_le32(iwl_read_prph(trans, wrap_cnt));
3148 	fw_mon_data->fw_mon_base_ptr =
3149 		cpu_to_le32(iwl_read_prph(trans, base));
3150 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
3151 		fw_mon_data->fw_mon_base_high_ptr =
3152 			cpu_to_le32(iwl_read_prph(trans, base_high));
3153 		write_ptr_val &= DBGC_CUR_DBGBUF_STATUS_OFFSET_MSK;
3154 		/* convert wrtPtr to DWs, to align with all HWs */
3155 		write_ptr_val >>= 2;
3156 	}
3157 	fw_mon_data->fw_mon_wr_ptr = cpu_to_le32(write_ptr_val);
3158 }
3159 
3160 static u32
3161 iwl_trans_pcie_dump_monitor(struct iwl_trans *trans,
3162 			    struct iwl_fw_error_dump_data **data,
3163 			    u32 monitor_len)
3164 {
3165 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
3166 	u32 len = 0;
3167 
3168 	if (trans->dbg.dest_tlv ||
3169 	    (fw_mon->size &&
3170 	     (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_7000 ||
3171 	      trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210))) {
3172 		struct iwl_fw_error_dump_fw_mon *fw_mon_data;
3173 
3174 		(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_FW_MONITOR);
3175 		fw_mon_data = (void *)(*data)->data;
3176 
3177 		iwl_trans_pcie_dump_pointers(trans, fw_mon_data);
3178 
3179 		len += sizeof(**data) + sizeof(*fw_mon_data);
3180 		if (fw_mon->size) {
3181 			memcpy(fw_mon_data->data, fw_mon->block, fw_mon->size);
3182 			monitor_len = fw_mon->size;
3183 		} else if (trans->dbg.dest_tlv->monitor_mode == SMEM_MODE) {
3184 			u32 base = le32_to_cpu(fw_mon_data->fw_mon_base_ptr);
3185 			/*
3186 			 * Update pointers to reflect actual values after
3187 			 * shifting
3188 			 */
3189 			if (trans->dbg.dest_tlv->version) {
3190 				base = (iwl_read_prph(trans, base) &
3191 					IWL_LDBG_M2S_BUF_BA_MSK) <<
3192 				       trans->dbg.dest_tlv->base_shift;
3193 				base *= IWL_M2S_UNIT_SIZE;
3194 				base += trans->cfg->smem_offset;
3195 			} else {
3196 				base = iwl_read_prph(trans, base) <<
3197 				       trans->dbg.dest_tlv->base_shift;
3198 			}
3199 
3200 			iwl_trans_read_mem(trans, base, fw_mon_data->data,
3201 					   monitor_len / sizeof(u32));
3202 		} else if (trans->dbg.dest_tlv->monitor_mode == MARBH_MODE) {
3203 			monitor_len =
3204 				iwl_trans_pci_dump_marbh_monitor(trans,
3205 								 fw_mon_data,
3206 								 monitor_len);
3207 		} else {
3208 			/* Didn't match anything - output no monitor data */
3209 			monitor_len = 0;
3210 		}
3211 
3212 		len += monitor_len;
3213 		(*data)->len = cpu_to_le32(monitor_len + sizeof(*fw_mon_data));
3214 	}
3215 
3216 	return len;
3217 }
3218 
3219 static int iwl_trans_get_fw_monitor_len(struct iwl_trans *trans, u32 *len)
3220 {
3221 	if (trans->dbg.fw_mon.size) {
3222 		*len += sizeof(struct iwl_fw_error_dump_data) +
3223 			sizeof(struct iwl_fw_error_dump_fw_mon) +
3224 			trans->dbg.fw_mon.size;
3225 		return trans->dbg.fw_mon.size;
3226 	} else if (trans->dbg.dest_tlv) {
3227 		u32 base, end, cfg_reg, monitor_len;
3228 
3229 		if (trans->dbg.dest_tlv->version == 1) {
3230 			cfg_reg = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
3231 			cfg_reg = iwl_read_prph(trans, cfg_reg);
3232 			base = (cfg_reg & IWL_LDBG_M2S_BUF_BA_MSK) <<
3233 				trans->dbg.dest_tlv->base_shift;
3234 			base *= IWL_M2S_UNIT_SIZE;
3235 			base += trans->cfg->smem_offset;
3236 
3237 			monitor_len =
3238 				(cfg_reg & IWL_LDBG_M2S_BUF_SIZE_MSK) >>
3239 				trans->dbg.dest_tlv->end_shift;
3240 			monitor_len *= IWL_M2S_UNIT_SIZE;
3241 		} else {
3242 			base = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
3243 			end = le32_to_cpu(trans->dbg.dest_tlv->end_reg);
3244 
3245 			base = iwl_read_prph(trans, base) <<
3246 			       trans->dbg.dest_tlv->base_shift;
3247 			end = iwl_read_prph(trans, end) <<
3248 			      trans->dbg.dest_tlv->end_shift;
3249 
3250 			/* Make "end" point to the actual end */
3251 			if (trans->trans_cfg->device_family >=
3252 			    IWL_DEVICE_FAMILY_8000 ||
3253 			    trans->dbg.dest_tlv->monitor_mode == MARBH_MODE)
3254 				end += (1 << trans->dbg.dest_tlv->end_shift);
3255 			monitor_len = end - base;
3256 		}
3257 		*len += sizeof(struct iwl_fw_error_dump_data) +
3258 			sizeof(struct iwl_fw_error_dump_fw_mon) +
3259 			monitor_len;
3260 		return monitor_len;
3261 	}
3262 	return 0;
3263 }
3264 
3265 static struct iwl_trans_dump_data *
3266 iwl_trans_pcie_dump_data(struct iwl_trans *trans,
3267 			 u32 dump_mask,
3268 			 const struct iwl_dump_sanitize_ops *sanitize_ops,
3269 			 void *sanitize_ctx)
3270 {
3271 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
3272 	struct iwl_fw_error_dump_data *data;
3273 	struct iwl_txq *cmdq = trans->txqs.txq[trans->txqs.cmd.q_id];
3274 	struct iwl_fw_error_dump_txcmd *txcmd;
3275 	struct iwl_trans_dump_data *dump_data;
3276 	u32 len, num_rbs = 0, monitor_len = 0;
3277 	int i, ptr;
3278 	bool dump_rbs = test_bit(STATUS_FW_ERROR, &trans->status) &&
3279 			!trans->trans_cfg->mq_rx_supported &&
3280 			dump_mask & BIT(IWL_FW_ERROR_DUMP_RB);
3281 
3282 	if (!dump_mask)
3283 		return NULL;
3284 
3285 	/* transport dump header */
3286 	len = sizeof(*dump_data);
3287 
3288 	/* host commands */
3289 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_TXCMD) && cmdq)
3290 		len += sizeof(*data) +
3291 			cmdq->n_window * (sizeof(*txcmd) +
3292 					  TFD_MAX_PAYLOAD_SIZE);
3293 
3294 	/* FW monitor */
3295 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FW_MONITOR))
3296 		monitor_len = iwl_trans_get_fw_monitor_len(trans, &len);
3297 
3298 	/* CSR registers */
3299 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_CSR))
3300 		len += sizeof(*data) + IWL_CSR_TO_DUMP;
3301 
3302 	/* FH registers */
3303 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FH_REGS)) {
3304 		if (trans->trans_cfg->gen2)
3305 			len += sizeof(*data) +
3306 			       (iwl_umac_prph(trans, FH_MEM_UPPER_BOUND_GEN2) -
3307 				iwl_umac_prph(trans, FH_MEM_LOWER_BOUND_GEN2));
3308 		else
3309 			len += sizeof(*data) +
3310 			       (FH_MEM_UPPER_BOUND -
3311 				FH_MEM_LOWER_BOUND);
3312 	}
3313 
3314 	if (dump_rbs) {
3315 		/* Dump RBs is supported only for pre-9000 devices (1 queue) */
3316 		struct iwl_rxq *rxq = &trans_pcie->rxq[0];
3317 		/* RBs */
3318 		num_rbs =
3319 			le16_to_cpu(iwl_get_closed_rb_stts(trans, rxq))
3320 			& 0x0FFF;
3321 		num_rbs = (num_rbs - rxq->read) & RX_QUEUE_MASK;
3322 		len += num_rbs * (sizeof(*data) +
3323 				  sizeof(struct iwl_fw_error_dump_rb) +
3324 				  (PAGE_SIZE << trans_pcie->rx_page_order));
3325 	}
3326 
3327 	/* Paged memory for gen2 HW */
3328 	if (trans->trans_cfg->gen2 && dump_mask & BIT(IWL_FW_ERROR_DUMP_PAGING))
3329 		for (i = 0; i < trans->init_dram.paging_cnt; i++)
3330 			len += sizeof(*data) +
3331 			       sizeof(struct iwl_fw_error_dump_paging) +
3332 			       trans->init_dram.paging[i].size;
3333 
3334 	dump_data = vzalloc(len);
3335 	if (!dump_data)
3336 		return NULL;
3337 
3338 	len = 0;
3339 	data = (void *)dump_data->data;
3340 
3341 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_TXCMD) && cmdq) {
3342 		u16 tfd_size = trans->txqs.tfd.size;
3343 
3344 		data->type = cpu_to_le32(IWL_FW_ERROR_DUMP_TXCMD);
3345 		txcmd = (void *)data->data;
3346 		spin_lock_bh(&cmdq->lock);
3347 		ptr = cmdq->write_ptr;
3348 		for (i = 0; i < cmdq->n_window; i++) {
3349 			u8 idx = iwl_txq_get_cmd_index(cmdq, ptr);
3350 			u8 tfdidx;
3351 			u32 caplen, cmdlen;
3352 
3353 			if (trans->trans_cfg->use_tfh)
3354 				tfdidx = idx;
3355 			else
3356 				tfdidx = ptr;
3357 
3358 			cmdlen = iwl_trans_pcie_get_cmdlen(trans,
3359 							   (u8 *)cmdq->tfds +
3360 							   tfd_size * tfdidx);
3361 			caplen = min_t(u32, TFD_MAX_PAYLOAD_SIZE, cmdlen);
3362 
3363 			if (cmdlen) {
3364 				len += sizeof(*txcmd) + caplen;
3365 				txcmd->cmdlen = cpu_to_le32(cmdlen);
3366 				txcmd->caplen = cpu_to_le32(caplen);
3367 				memcpy(txcmd->data, cmdq->entries[idx].cmd,
3368 				       caplen);
3369 				if (sanitize_ops && sanitize_ops->frob_hcmd)
3370 					sanitize_ops->frob_hcmd(sanitize_ctx,
3371 								txcmd->data,
3372 								caplen);
3373 				txcmd = (void *)((u8 *)txcmd->data + caplen);
3374 			}
3375 
3376 			ptr = iwl_txq_dec_wrap(trans, ptr);
3377 		}
3378 		spin_unlock_bh(&cmdq->lock);
3379 
3380 		data->len = cpu_to_le32(len);
3381 		len += sizeof(*data);
3382 		data = iwl_fw_error_next_data(data);
3383 	}
3384 
3385 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_CSR))
3386 		len += iwl_trans_pcie_dump_csr(trans, &data);
3387 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FH_REGS))
3388 		len += iwl_trans_pcie_fh_regs_dump(trans, &data);
3389 	if (dump_rbs)
3390 		len += iwl_trans_pcie_dump_rbs(trans, &data, num_rbs);
3391 
3392 	/* Paged memory for gen2 HW */
3393 	if (trans->trans_cfg->gen2 &&
3394 	    dump_mask & BIT(IWL_FW_ERROR_DUMP_PAGING)) {
3395 		for (i = 0; i < trans->init_dram.paging_cnt; i++) {
3396 			struct iwl_fw_error_dump_paging *paging;
3397 			u32 page_len = trans->init_dram.paging[i].size;
3398 
3399 			data->type = cpu_to_le32(IWL_FW_ERROR_DUMP_PAGING);
3400 			data->len = cpu_to_le32(sizeof(*paging) + page_len);
3401 			paging = (void *)data->data;
3402 			paging->index = cpu_to_le32(i);
3403 			memcpy(paging->data,
3404 			       trans->init_dram.paging[i].block, page_len);
3405 			data = iwl_fw_error_next_data(data);
3406 
3407 			len += sizeof(*data) + sizeof(*paging) + page_len;
3408 		}
3409 	}
3410 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FW_MONITOR))
3411 		len += iwl_trans_pcie_dump_monitor(trans, &data, monitor_len);
3412 
3413 	dump_data->len = len;
3414 
3415 	return dump_data;
3416 }
3417 
3418 static void iwl_trans_pci_interrupts(struct iwl_trans *trans, bool enable)
3419 {
3420 	if (enable)
3421 		iwl_enable_interrupts(trans);
3422 	else
3423 		iwl_disable_interrupts(trans);
3424 }
3425 
3426 static void iwl_trans_pcie_sync_nmi(struct iwl_trans *trans)
3427 {
3428 	u32 inta_addr, sw_err_bit;
3429 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
3430 
3431 	if (trans_pcie->msix_enabled) {
3432 		inta_addr = CSR_MSIX_HW_INT_CAUSES_AD;
3433 		if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
3434 			sw_err_bit = MSIX_HW_INT_CAUSES_REG_SW_ERR_BZ;
3435 		else
3436 			sw_err_bit = MSIX_HW_INT_CAUSES_REG_SW_ERR;
3437 	} else {
3438 		inta_addr = CSR_INT;
3439 		sw_err_bit = CSR_INT_BIT_SW_ERR;
3440 	}
3441 
3442 	iwl_trans_sync_nmi_with_addr(trans, inta_addr, sw_err_bit);
3443 }
3444 
3445 #define IWL_TRANS_COMMON_OPS						\
3446 	.op_mode_leave = iwl_trans_pcie_op_mode_leave,			\
3447 	.write8 = iwl_trans_pcie_write8,				\
3448 	.write32 = iwl_trans_pcie_write32,				\
3449 	.read32 = iwl_trans_pcie_read32,				\
3450 	.read_prph = iwl_trans_pcie_read_prph,				\
3451 	.write_prph = iwl_trans_pcie_write_prph,			\
3452 	.read_mem = iwl_trans_pcie_read_mem,				\
3453 	.write_mem = iwl_trans_pcie_write_mem,				\
3454 	.read_config32 = iwl_trans_pcie_read_config32,			\
3455 	.configure = iwl_trans_pcie_configure,				\
3456 	.set_pmi = iwl_trans_pcie_set_pmi,				\
3457 	.sw_reset = iwl_trans_pcie_sw_reset,				\
3458 	.grab_nic_access = iwl_trans_pcie_grab_nic_access,		\
3459 	.release_nic_access = iwl_trans_pcie_release_nic_access,	\
3460 	.set_bits_mask = iwl_trans_pcie_set_bits_mask,			\
3461 	.dump_data = iwl_trans_pcie_dump_data,				\
3462 	.d3_suspend = iwl_trans_pcie_d3_suspend,			\
3463 	.d3_resume = iwl_trans_pcie_d3_resume,				\
3464 	.interrupts = iwl_trans_pci_interrupts,				\
3465 	.sync_nmi = iwl_trans_pcie_sync_nmi				\
3466 
3467 static const struct iwl_trans_ops trans_ops_pcie = {
3468 	IWL_TRANS_COMMON_OPS,
3469 	.start_hw = iwl_trans_pcie_start_hw,
3470 	.fw_alive = iwl_trans_pcie_fw_alive,
3471 	.start_fw = iwl_trans_pcie_start_fw,
3472 	.stop_device = iwl_trans_pcie_stop_device,
3473 
3474 	.send_cmd = iwl_pcie_enqueue_hcmd,
3475 
3476 	.tx = iwl_trans_pcie_tx,
3477 	.reclaim = iwl_txq_reclaim,
3478 
3479 	.txq_disable = iwl_trans_pcie_txq_disable,
3480 	.txq_enable = iwl_trans_pcie_txq_enable,
3481 
3482 	.txq_set_shared_mode = iwl_trans_pcie_txq_set_shared_mode,
3483 
3484 	.wait_tx_queues_empty = iwl_trans_pcie_wait_txqs_empty,
3485 
3486 	.freeze_txq_timer = iwl_trans_txq_freeze_timer,
3487 	.block_txq_ptrs = iwl_trans_pcie_block_txq_ptrs,
3488 #ifdef CONFIG_IWLWIFI_DEBUGFS
3489 	.debugfs_cleanup = iwl_trans_pcie_debugfs_cleanup,
3490 #endif
3491 };
3492 
3493 static const struct iwl_trans_ops trans_ops_pcie_gen2 = {
3494 	IWL_TRANS_COMMON_OPS,
3495 	.start_hw = iwl_trans_pcie_start_hw,
3496 	.fw_alive = iwl_trans_pcie_gen2_fw_alive,
3497 	.start_fw = iwl_trans_pcie_gen2_start_fw,
3498 	.stop_device = iwl_trans_pcie_gen2_stop_device,
3499 
3500 	.send_cmd = iwl_pcie_gen2_enqueue_hcmd,
3501 
3502 	.tx = iwl_txq_gen2_tx,
3503 	.reclaim = iwl_txq_reclaim,
3504 
3505 	.set_q_ptrs = iwl_txq_set_q_ptrs,
3506 
3507 	.txq_alloc = iwl_txq_dyn_alloc,
3508 	.txq_free = iwl_txq_dyn_free,
3509 	.wait_txq_empty = iwl_trans_pcie_wait_txq_empty,
3510 	.rxq_dma_data = iwl_trans_pcie_rxq_dma_data,
3511 	.set_pnvm = iwl_trans_pcie_ctx_info_gen3_set_pnvm,
3512 	.set_reduce_power = iwl_trans_pcie_ctx_info_gen3_set_reduce_power,
3513 #ifdef CONFIG_IWLWIFI_DEBUGFS
3514 	.debugfs_cleanup = iwl_trans_pcie_debugfs_cleanup,
3515 #endif
3516 };
3517 
3518 struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev,
3519 			       const struct pci_device_id *ent,
3520 			       const struct iwl_cfg_trans_params *cfg_trans)
3521 {
3522 	struct iwl_trans_pcie *trans_pcie;
3523 	struct iwl_trans *trans;
3524 	int ret, addr_size;
3525 	const struct iwl_trans_ops *ops = &trans_ops_pcie_gen2;
3526 	void __iomem * const *table;
3527 
3528 	if (!cfg_trans->gen2)
3529 		ops = &trans_ops_pcie;
3530 
3531 	ret = pcim_enable_device(pdev);
3532 	if (ret)
3533 		return ERR_PTR(ret);
3534 
3535 	trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, ops,
3536 				cfg_trans);
3537 	if (!trans)
3538 		return ERR_PTR(-ENOMEM);
3539 
3540 	trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
3541 
3542 	trans_pcie->trans = trans;
3543 	trans_pcie->opmode_down = true;
3544 	spin_lock_init(&trans_pcie->irq_lock);
3545 	spin_lock_init(&trans_pcie->reg_lock);
3546 	spin_lock_init(&trans_pcie->alloc_page_lock);
3547 	mutex_init(&trans_pcie->mutex);
3548 	init_waitqueue_head(&trans_pcie->ucode_write_waitq);
3549 	init_waitqueue_head(&trans_pcie->fw_reset_waitq);
3550 
3551 	trans_pcie->rba.alloc_wq = alloc_workqueue("rb_allocator",
3552 						   WQ_HIGHPRI | WQ_UNBOUND, 1);
3553 	if (!trans_pcie->rba.alloc_wq) {
3554 		ret = -ENOMEM;
3555 		goto out_free_trans;
3556 	}
3557 	INIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work);
3558 
3559 	trans_pcie->debug_rfkill = -1;
3560 
3561 	if (!cfg_trans->base_params->pcie_l1_allowed) {
3562 		/*
3563 		 * W/A - seems to solve weird behavior. We need to remove this
3564 		 * if we don't want to stay in L1 all the time. This wastes a
3565 		 * lot of power.
3566 		 */
3567 		pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S |
3568 				       PCIE_LINK_STATE_L1 |
3569 				       PCIE_LINK_STATE_CLKPM);
3570 	}
3571 
3572 	trans_pcie->def_rx_queue = 0;
3573 
3574 	pci_set_master(pdev);
3575 
3576 	addr_size = trans->txqs.tfd.addr_size;
3577 	ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(addr_size));
3578 	if (ret) {
3579 		ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
3580 		/* both attempts failed: */
3581 		if (ret) {
3582 			dev_err(&pdev->dev, "No suitable DMA available\n");
3583 			goto out_no_pci;
3584 		}
3585 	}
3586 
3587 	ret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME);
3588 	if (ret) {
3589 		dev_err(&pdev->dev, "pcim_iomap_regions_request_all failed\n");
3590 		goto out_no_pci;
3591 	}
3592 
3593 #if defined(__FreeBSD__)
3594 	linuxkpi_pcim_want_to_use_bus_functions(pdev);
3595 #endif
3596 	table = pcim_iomap_table(pdev);
3597 	if (!table) {
3598 		dev_err(&pdev->dev, "pcim_iomap_table failed\n");
3599 		ret = -ENOMEM;
3600 		goto out_no_pci;
3601 	}
3602 
3603 	trans_pcie->hw_base = table[0];
3604 	if (!trans_pcie->hw_base) {
3605 		dev_err(&pdev->dev, "couldn't find IO mem in first BAR\n");
3606 		ret = -ENODEV;
3607 		goto out_no_pci;
3608 	}
3609 
3610 	/* We disable the RETRY_TIMEOUT register (0x41) to keep
3611 	 * PCI Tx retries from interfering with C3 CPU state */
3612 	pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);
3613 
3614 	trans_pcie->pci_dev = pdev;
3615 	iwl_disable_interrupts(trans);
3616 
3617 	trans->hw_rev = iwl_read32(trans, CSR_HW_REV);
3618 	if (trans->hw_rev == 0xffffffff) {
3619 		dev_err(&pdev->dev, "HW_REV=0xFFFFFFFF, PCI issues?\n");
3620 		ret = -EIO;
3621 		goto out_no_pci;
3622 	}
3623 
3624 	/*
3625 	 * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have
3626 	 * changed, and now the revision step also includes bit 0-1 (no more
3627 	 * "dash" value). To keep hw_rev backwards compatible - we'll store it
3628 	 * in the old format.
3629 	 */
3630 	if (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000)
3631 		trans->hw_rev = (trans->hw_rev & 0xfff0) |
3632 				(CSR_HW_REV_STEP(trans->hw_rev << 2) << 2);
3633 
3634 	IWL_DEBUG_INFO(trans, "HW REV: 0x%0x\n", trans->hw_rev);
3635 
3636 	iwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans);
3637 	trans->hw_id = (pdev->device << 16) + pdev->subsystem_device;
3638 	snprintf(trans->hw_id_str, sizeof(trans->hw_id_str),
3639 		 "PCI ID: 0x%04X:0x%04X", pdev->device, pdev->subsystem_device);
3640 
3641 	init_waitqueue_head(&trans_pcie->sx_waitq);
3642 
3643 
3644 	if (trans_pcie->msix_enabled) {
3645 		ret = iwl_pcie_init_msix_handler(pdev, trans_pcie);
3646 		if (ret)
3647 			goto out_no_pci;
3648 	 } else {
3649 		ret = iwl_pcie_alloc_ict(trans);
3650 		if (ret)
3651 			goto out_no_pci;
3652 
3653 		ret = devm_request_threaded_irq(&pdev->dev, pdev->irq,
3654 						iwl_pcie_isr,
3655 						iwl_pcie_irq_handler,
3656 						IRQF_SHARED, DRV_NAME, trans);
3657 		if (ret) {
3658 			IWL_ERR(trans, "Error allocating IRQ %d\n", pdev->irq);
3659 			goto out_free_ict;
3660 		}
3661 	 }
3662 
3663 #ifdef CONFIG_IWLWIFI_DEBUGFS
3664 	trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;
3665 	mutex_init(&trans_pcie->fw_mon_data.mutex);
3666 #endif
3667 
3668 	iwl_dbg_tlv_init(trans);
3669 
3670 	return trans;
3671 
3672 out_free_ict:
3673 	iwl_pcie_free_ict(trans);
3674 out_no_pci:
3675 	destroy_workqueue(trans_pcie->rba.alloc_wq);
3676 out_free_trans:
3677 	iwl_trans_free(trans);
3678 	return ERR_PTR(ret);
3679 }
3680