diff --git a/sys/compat/linuxkpi/common/include/linux/interrupt.h b/sys/compat/linuxkpi/common/include/linux/interrupt.h
index 1ae9f48c7ddd..d5f9a0ae7a47 100644
--- a/sys/compat/linuxkpi/common/include/linux/interrupt.h
+++ b/sys/compat/linuxkpi/common/include/linux/interrupt.h
@@ -1,195 +1,195 @@
 /*-
  * Copyright (c) 2010 Isilon Systems, Inc.
  * Copyright (c) 2010 iX Systems, Inc.
  * Copyright (c) 2010 Panasas, Inc.
  * Copyright (c) 2013-2015 Mellanox Technologies, Ltd.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice unmodified, this list of conditions, and the following
  *    disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #ifndef	_LINUXKPI_LINUX_INTERRUPT_H_
 #define	_LINUXKPI_LINUX_INTERRUPT_H_
 
 #include <linux/cpu.h>
 #include <linux/device.h>
 #include <linux/pci.h>
 #include <linux/irqreturn.h>
 #include <linux/hardirq.h>
 
 #include <sys/param.h>
 #include <sys/interrupt.h>
 
 typedef	irqreturn_t	(*irq_handler_t)(int, void *);
 
-#define	IRQF_SHARED	RF_SHAREABLE
+#define	IRQF_SHARED		0x0004	/* Historically */
 #define	IRQF_NOBALANCING	0
 
 #define	IRQ_DISABLE_UNLAZY	0
 
 #define	IRQ_NOTCONNECTED	(1U << 31)
 
 int  lkpi_request_irq(struct device *, unsigned int, irq_handler_t,
 	irq_handler_t, unsigned long, const char *, void *);
 int  lkpi_enable_irq(unsigned int);
 void lkpi_disable_irq(unsigned int);
 int  lkpi_bind_irq_to_cpu(unsigned int, int);
 void lkpi_free_irq(unsigned int, void *);
 void lkpi_devm_free_irq(struct device *, unsigned int, void *);
 
 static inline int
 request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags,
     const char *name, void *arg)
 {
 
 	return (lkpi_request_irq(NULL, irq, handler, NULL, flags, name, arg));
 }
 
 static inline int
 request_threaded_irq(int irq, irq_handler_t handler,
     irq_handler_t thread_handler, unsigned long flags,
     const char *name, void *arg)
 {
 
 	return (lkpi_request_irq(NULL, irq, handler, thread_handler,
 	    flags, name, arg));
 }
 
 static inline int
 devm_request_irq(struct device *dev, int irq,
     irq_handler_t handler, unsigned long flags, const char *name, void *arg)
 {
 
 	return (lkpi_request_irq(dev, irq, handler, NULL, flags, name, arg));
 }
 
 static inline int
 devm_request_threaded_irq(struct device *dev, int irq,
     irq_handler_t handler, irq_handler_t thread_handler,
     unsigned long flags, const char *name, void *arg)
 {
 
 	return (lkpi_request_irq(dev, irq, handler, thread_handler,
 	    flags, name, arg));
 }
 
 static inline int
 enable_irq(unsigned int irq)
 {
 	return (lkpi_enable_irq(irq));
 }
 
 static inline void
 disable_irq(unsigned int irq)
 {
 	lkpi_disable_irq(irq);
 }
 
 static inline void
 disable_irq_nosync(unsigned int irq)
 {
 	lkpi_disable_irq(irq);
 }
 
 static inline int
 bind_irq_to_cpu(unsigned int irq, int cpu_id)
 {
 	return (lkpi_bind_irq_to_cpu(irq, cpu_id));
 }
 
 static inline void
 free_irq(unsigned int irq, void *device)
 {
 	lkpi_free_irq(irq, device);
 }
 
 static inline void
 devm_free_irq(struct device *xdev, unsigned int irq, void *p)
 {
 	lkpi_devm_free_irq(xdev, irq, p);
 }
 
 static inline int
 irq_set_affinity_hint(int vector, const cpumask_t *mask)
 {
 	int error;
 
 	if (mask != NULL)
 		error = intr_setaffinity(vector, CPU_WHICH_IRQ, __DECONST(cpumask_t *, mask));
 	else
 		error = intr_setaffinity(vector, CPU_WHICH_IRQ, cpuset_root);
 
 	return (-error);
 }
 
 static inline struct msi_desc *
 irq_get_msi_desc(unsigned int irq)
 {
 
 	return (lkpi_pci_msi_desc_alloc(irq));
 }
 
 static inline void
 irq_set_status_flags(unsigned int irq __unused, unsigned long flags __unused)
 {
 }
 
 /*
  * LinuxKPI tasklet support
  */
 struct tasklet_struct;
 typedef void tasklet_func_t(unsigned long);
 typedef void tasklet_callback_t(struct tasklet_struct *);
 
 struct tasklet_struct {
 	TAILQ_ENTRY(tasklet_struct) entry;
 	tasklet_func_t *func;
 	/* Our "state" implementation is different. Avoid same name as Linux. */
 	volatile u_int tasklet_state;
 	atomic_t count;
 	unsigned long data;
 	tasklet_callback_t *callback;
 	bool use_callback;
 };
 
 #define	DECLARE_TASKLET(_name, _func, _data)	\
 struct tasklet_struct _name = { .func = (_func), .data = (_data) }
 
 #define	tasklet_hi_schedule(t)	tasklet_schedule(t)
 
 /* Some other compat code in the tree has this defined as well. */
 #define	from_tasklet(_dev, _t, _field)		\
     container_of(_t, typeof(*(_dev)), _field)
 
 void tasklet_setup(struct tasklet_struct *, tasklet_callback_t *);
 extern void tasklet_schedule(struct tasklet_struct *);
 extern void tasklet_kill(struct tasklet_struct *);
 extern void tasklet_init(struct tasklet_struct *, tasklet_func_t *,
     unsigned long data);
 extern void tasklet_enable(struct tasklet_struct *);
 extern void tasklet_disable(struct tasklet_struct *);
 extern void tasklet_disable_nosync(struct tasklet_struct *);
 extern int tasklet_trylock(struct tasklet_struct *);
 extern void tasklet_unlock(struct tasklet_struct *);
 extern void tasklet_unlock_wait(struct tasklet_struct *ts);
 #define	tasklet_unlock_spin_wait(ts)	tasklet_unlock_wait(ts)
 
 #endif	/* _LINUXKPI_LINUX_INTERRUPT_H_ */
diff --git a/sys/compat/linuxkpi/common/include/linux/pci.h b/sys/compat/linuxkpi/common/include/linux/pci.h
index 4406e47d3d63..aa99b050ffd9 100644
--- a/sys/compat/linuxkpi/common/include/linux/pci.h
+++ b/sys/compat/linuxkpi/common/include/linux/pci.h
@@ -1,1763 +1,1468 @@
 /*-
  * Copyright (c) 2010 Isilon Systems, Inc.
  * Copyright (c) 2010 iX Systems, Inc.
  * Copyright (c) 2010 Panasas, Inc.
  * Copyright (c) 2013-2016 Mellanox Technologies, Ltd.
  * All rights reserved.
  * Copyright (c) 2020-2022 The FreeBSD Foundation
  *
  * Portions of this software were developed by Björn Zeeb
  * under sponsorship from the FreeBSD Foundation.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice unmodified, this list of conditions, and the following
  *    disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 #ifndef	_LINUXKPI_LINUX_PCI_H_
 #define	_LINUXKPI_LINUX_PCI_H_
 
 #define	CONFIG_PCI_MSI
 
 #include <linux/types.h>
 
 #include <sys/param.h>
 #include <sys/bus.h>
 #include <sys/module.h>
 #include <sys/nv.h>
 #include <sys/pciio.h>
-#include <sys/rman.h>
 #include <dev/pci/pcivar.h>
 #include <dev/pci/pcireg.h>
 #include <dev/pci/pci_private.h>
 
 #include <machine/resource.h>
 
 #include <linux/list.h>
 #include <linux/dmapool.h>
 #include <linux/dma-mapping.h>
 #include <linux/compiler.h>
 #include <linux/errno.h>
 #include <asm/atomic.h>
 #include <asm/memtype.h>
 #include <linux/device.h>
 #include <linux/pci_ids.h>
 #include <linux/pm.h>
 
 struct pci_device_id {
 	uint32_t	vendor;
 	uint32_t	device;
 	uint32_t	subvendor;
 	uint32_t	subdevice;
 	uint32_t	class;
 	uint32_t	class_mask;
 	uintptr_t	driver_data;
 };
 
 /* Linux has an empty element at the end of the ID table -> nitems() - 1. */
 #define	MODULE_DEVICE_TABLE(_bus, _table)				\
 									\
 static device_method_t _ ## _bus ## _ ## _table ## _methods[] = {	\
 	DEVMETHOD_END							\
 };									\
 									\
 static driver_t _ ## _bus ## _ ## _table ## _driver = {			\
 	"lkpi_" #_bus #_table,						\
 	_ ## _bus ## _ ## _table ## _methods,				\
 	0								\
 };									\
 									\
 DRIVER_MODULE(lkpi_ ## _table, pci, _ ## _bus ## _ ## _table ## _driver,\
 	0, 0);								\
 									\
 MODULE_PNP_INFO("U32:vendor;U32:device;V32:subvendor;V32:subdevice",	\
     _bus, lkpi_ ## _table, _table, nitems(_table) - 1)
 
 #define	PCI_ANY_ID			-1U
 
 #define PCI_DEVFN(slot, func)   ((((slot) & 0x1f) << 3) | ((func) & 0x07))
 #define PCI_SLOT(devfn)		(((devfn) >> 3) & 0x1f)
 #define PCI_FUNC(devfn)		((devfn) & 0x07)
 #define	PCI_BUS_NUM(devfn)	(((devfn) >> 8) & 0xff)
 
 #define PCI_VDEVICE(_vendor, _device)					\
 	    .vendor = PCI_VENDOR_ID_##_vendor, .device = (_device),	\
 	    .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID
 #define	PCI_DEVICE(_vendor, _device)					\
 	    .vendor = (_vendor), .device = (_device),			\
 	    .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID
 
 #define	to_pci_dev(n)	container_of(n, struct pci_dev, dev)
 
 #define	PCI_STD_NUM_BARS	6
 #define	PCI_VENDOR_ID		PCIR_VENDOR
 #define	PCI_DEVICE_ID		PCIR_DEVICE
 #define	PCI_COMMAND		PCIR_COMMAND
 #define	PCI_COMMAND_INTX_DISABLE	PCIM_CMD_INTxDIS
 #define	PCI_COMMAND_MEMORY	PCIM_CMD_MEMEN
 #define	PCI_EXP_DEVCTL		PCIER_DEVICE_CTL		/* Device Control */
 #define	PCI_EXP_LNKCTL		PCIER_LINK_CTL			/* Link Control */
 #define	PCI_EXP_LNKCTL_ASPM_L0S	PCIEM_LINK_CTL_ASPMC_L0S
 #define	PCI_EXP_LNKCTL_ASPM_L1	PCIEM_LINK_CTL_ASPMC_L1
 #define PCI_EXP_LNKCTL_ASPMC	PCIEM_LINK_CTL_ASPMC
 #define	PCI_EXP_LNKCTL_CLKREQ_EN PCIEM_LINK_CTL_ECPM		/* Enable clock PM */
 #define PCI_EXP_LNKCTL_HAWD	PCIEM_LINK_CTL_HAWD
 #define	PCI_EXP_FLAGS_TYPE	PCIEM_FLAGS_TYPE		/* Device/Port type */
 #define	PCI_EXP_DEVCAP		PCIER_DEVICE_CAP		/* Device capabilities */
 #define	PCI_EXP_DEVSTA		PCIER_DEVICE_STA		/* Device Status */
 #define	PCI_EXP_LNKCAP		PCIER_LINK_CAP			/* Link Capabilities */
 #define	PCI_EXP_LNKSTA		PCIER_LINK_STA			/* Link Status */
 #define	PCI_EXP_SLTCAP		PCIER_SLOT_CAP			/* Slot Capabilities */
 #define	PCI_EXP_SLTCTL		PCIER_SLOT_CTL			/* Slot Control */
 #define	PCI_EXP_SLTSTA		PCIER_SLOT_STA			/* Slot Status */
 #define	PCI_EXP_RTCTL		PCIER_ROOT_CTL			/* Root Control */
 #define	PCI_EXP_RTCAP		PCIER_ROOT_CAP			/* Root Capabilities */
 #define	PCI_EXP_RTSTA		PCIER_ROOT_STA			/* Root Status */
 #define	PCI_EXP_DEVCAP2		PCIER_DEVICE_CAP2		/* Device Capabilities 2 */
 #define	PCI_EXP_DEVCTL2		PCIER_DEVICE_CTL2		/* Device Control 2 */
 #define	PCI_EXP_DEVCTL2_LTR_EN	PCIEM_CTL2_LTR_ENABLE
 #define	PCI_EXP_DEVCTL2_COMP_TMOUT_DIS	PCIEM_CTL2_COMP_TIMO_DISABLE
 #define	PCI_EXP_LNKCAP2		PCIER_LINK_CAP2			/* Link Capabilities 2 */
 #define	PCI_EXP_LNKCTL2		PCIER_LINK_CTL2			/* Link Control 2 */
 #define	PCI_EXP_LNKSTA2		PCIER_LINK_STA2			/* Link Status 2 */
 #define	PCI_EXP_FLAGS		PCIER_FLAGS			/* Capabilities register */
 #define	PCI_EXP_FLAGS_VERS	PCIEM_FLAGS_VERSION		/* Capability version */
 #define	PCI_EXP_TYPE_ROOT_PORT	PCIEM_TYPE_ROOT_PORT		/* Root Port */
 #define	PCI_EXP_TYPE_ENDPOINT	PCIEM_TYPE_ENDPOINT		/* Express Endpoint */
 #define	PCI_EXP_TYPE_LEG_END	PCIEM_TYPE_LEGACY_ENDPOINT	/* Legacy Endpoint */
 #define	PCI_EXP_TYPE_DOWNSTREAM PCIEM_TYPE_DOWNSTREAM_PORT	/* Downstream Port */
 #define	PCI_EXP_FLAGS_SLOT	PCIEM_FLAGS_SLOT		/* Slot implemented */
 #define	PCI_EXP_TYPE_RC_EC	PCIEM_TYPE_ROOT_EC		/* Root Complex Event Collector */
 #define	PCI_EXP_LNKSTA_CLS	PCIEM_LINK_STA_SPEED
 #define	PCI_EXP_LNKSTA_CLS_8_0GB	0x0003	/* Current Link Speed 8.0GT/s */
 #define	PCI_EXP_LNKCAP_SLS_2_5GB 0x01	/* Supported Link Speed 2.5GT/s */
 #define	PCI_EXP_LNKCAP_SLS_5_0GB 0x02	/* Supported Link Speed 5.0GT/s */
 #define	PCI_EXP_LNKCAP_SLS_8_0GB 0x03	/* Supported Link Speed 8.0GT/s */
 #define	PCI_EXP_LNKCAP_SLS_16_0GB 0x04	/* Supported Link Speed 16.0GT/s */
 #define	PCI_EXP_LNKCAP_SLS_32_0GB 0x05	/* Supported Link Speed 32.0GT/s */
 #define	PCI_EXP_LNKCAP_SLS_64_0GB 0x06	/* Supported Link Speed 64.0GT/s */
 #define	PCI_EXP_LNKCAP_MLW	0x03f0	/* Maximum Link Width */
 #define	PCI_EXP_LNKCAP2_SLS_2_5GB 0x02	/* Supported Link Speed 2.5GT/s */
 #define	PCI_EXP_LNKCAP2_SLS_5_0GB 0x04	/* Supported Link Speed 5.0GT/s */
 #define	PCI_EXP_LNKCAP2_SLS_8_0GB 0x08	/* Supported Link Speed 8.0GT/s */
 #define	PCI_EXP_LNKCAP2_SLS_16_0GB 0x10	/* Supported Link Speed 16.0GT/s */
 #define	PCI_EXP_LNKCAP2_SLS_32_0GB 0x20	/* Supported Link Speed 32.0GT/s */
 #define	PCI_EXP_LNKCAP2_SLS_64_0GB 0x40	/* Supported Link Speed 64.0GT/s */
 #define	PCI_EXP_LNKCTL2_TLS		0x000f
 #define	PCI_EXP_LNKCTL2_TLS_2_5GT	0x0001	/* Supported Speed 2.5GT/s */
 #define	PCI_EXP_LNKCTL2_TLS_5_0GT	0x0002	/* Supported Speed 5GT/s */
 #define	PCI_EXP_LNKCTL2_TLS_8_0GT	0x0003	/* Supported Speed 8GT/s */
 #define	PCI_EXP_LNKCTL2_TLS_16_0GT	0x0004	/* Supported Speed 16GT/s */
 #define	PCI_EXP_LNKCTL2_TLS_32_0GT	0x0005	/* Supported Speed 32GT/s */
 #define	PCI_EXP_LNKCTL2_TLS_64_0GT	0x0006	/* Supported Speed 64GT/s */
 #define	PCI_EXP_LNKCTL2_ENTER_COMP	0x0010	/* Enter Compliance */
 #define	PCI_EXP_LNKCTL2_TX_MARGIN	0x0380	/* Transmit Margin */
 
 #define	PCI_MSI_ADDRESS_LO	PCIR_MSI_ADDR
 #define	PCI_MSI_ADDRESS_HI	PCIR_MSI_ADDR_HIGH
 #define	PCI_MSI_FLAGS		PCIR_MSI_CTRL
 #define	PCI_MSI_FLAGS_ENABLE	PCIM_MSICTRL_MSI_ENABLE
 #define	PCI_MSIX_FLAGS		PCIR_MSIX_CTRL
 #define	PCI_MSIX_FLAGS_ENABLE	PCIM_MSIXCTRL_MSIX_ENABLE
 
 #define PCI_EXP_LNKCAP_CLKPM	0x00040000
 #define PCI_EXP_DEVSTA_TRPND	0x0020
 
 #define	IORESOURCE_MEM	(1 << SYS_RES_MEMORY)
 #define	IORESOURCE_IO	(1 << SYS_RES_IOPORT)
 #define	IORESOURCE_IRQ	(1 << SYS_RES_IRQ)
 
 enum pci_bus_speed {
 	PCI_SPEED_UNKNOWN = -1,
 	PCIE_SPEED_2_5GT,
 	PCIE_SPEED_5_0GT,
 	PCIE_SPEED_8_0GT,
 	PCIE_SPEED_16_0GT,
 	PCIE_SPEED_32_0GT,
 	PCIE_SPEED_64_0GT,
 };
 
 enum pcie_link_width {
 	PCIE_LNK_WIDTH_RESRV	= 0x00,
 	PCIE_LNK_X1		= 0x01,
 	PCIE_LNK_X2		= 0x02,
 	PCIE_LNK_X4		= 0x04,
 	PCIE_LNK_X8		= 0x08,
 	PCIE_LNK_X12		= 0x0c,
 	PCIE_LNK_X16		= 0x10,
 	PCIE_LNK_X32		= 0x20,
 	PCIE_LNK_WIDTH_UNKNOWN	= 0xff,
 };
 
 #define	PCIE_LINK_STATE_L0S		0x00000001
 #define	PCIE_LINK_STATE_L1		0x00000002
 #define	PCIE_LINK_STATE_CLKPM		0x00000004
 
 typedef int pci_power_t;
 
 #define PCI_D0	PCI_POWERSTATE_D0
 #define PCI_D1	PCI_POWERSTATE_D1
 #define PCI_D2	PCI_POWERSTATE_D2
 #define PCI_D3hot	PCI_POWERSTATE_D3
 #define PCI_D3cold	4
 
 #define PCI_POWER_ERROR	PCI_POWERSTATE_UNKNOWN
 
 extern const char *pci_power_names[6];
 
 #define	PCI_ERR_ROOT_COMMAND		PCIR_AER_ROOTERR_CMD
 #define	PCI_ERR_ROOT_ERR_SRC		PCIR_AER_COR_SOURCE_ID
 
 #define	PCI_EXT_CAP_ID_ERR		PCIZ_AER
 #define	PCI_EXT_CAP_ID_L1SS		PCIZ_L1PM
 
 #define	PCI_L1SS_CTL1			0x8
 #define	PCI_L1SS_CTL1_L1SS_MASK		0xf
 
 #define	PCI_IRQ_LEGACY			0x01
 #define	PCI_IRQ_MSI			0x02
 #define	PCI_IRQ_MSIX			0x04
 #define	PCI_IRQ_ALL_TYPES		(PCI_IRQ_MSIX|PCI_IRQ_MSI|PCI_IRQ_LEGACY)
 
 struct pci_dev;
 
 struct pci_driver {
 	struct list_head		node;
 	char				*name;
 	const struct pci_device_id		*id_table;
 	int  (*probe)(struct pci_dev *dev, const struct pci_device_id *id);
 	void (*remove)(struct pci_dev *dev);
 	int  (*suspend) (struct pci_dev *dev, pm_message_t state);	/* Device suspended */
 	int  (*resume) (struct pci_dev *dev);		/* Device woken up */
 	void (*shutdown) (struct pci_dev *dev);		/* Device shutdown */
 	driver_t			bsddriver;
 	devclass_t			bsdclass;
 	struct device_driver		driver;
 	const struct pci_error_handlers       *err_handler;
 	bool				isdrm;
 	int				bsd_probe_return;
 	int  (*bsd_iov_init)(device_t dev, uint16_t num_vfs,
 	    const nvlist_t *pf_config);
 	void  (*bsd_iov_uninit)(device_t dev);
 	int  (*bsd_iov_add_vf)(device_t dev, uint16_t vfnum,
 	    const nvlist_t *vf_config);
 };
 
 struct pci_bus {
 	struct pci_dev	*self;
 	/* struct pci_bus	*parent */
 	int		domain;
 	int		number;
 };
 
 extern struct list_head pci_drivers;
 extern struct list_head pci_devices;
 extern spinlock_t pci_lock;
 
 #define	__devexit_p(x)	x
 
 #define module_pci_driver(_driver)					\
 									\
 static inline int							\
 _pci_init(void)								\
 {									\
 									\
 	return (linux_pci_register_driver(&_driver));			\
 }									\
 									\
 static inline void							\
 _pci_exit(void)								\
 {									\
 									\
 	linux_pci_unregister_driver(&_driver);				\
 }									\
 									\
 module_init(_pci_init);							\
 module_exit(_pci_exit)
 
 struct msi_msg {
 	uint32_t			data;
 };
 
 struct pci_msi_desc {
 	struct {
 		bool			is_64;
 	} msi_attrib;
 };
 
 struct msi_desc {
 	struct msi_msg			msg;
 	struct pci_msi_desc		pci;
 };
 
+struct msix_entry {
+	int entry;
+	int vector;
+};
+
 /*
  * If we find drivers accessing this from multiple KPIs we may have to
  * refcount objects of this structure.
  */
+struct resource;
 struct pci_mmio_region {
 	TAILQ_ENTRY(pci_mmio_region)	next;
 	struct resource			*res;
 	int				rid;
 	int				type;
 };
 
 struct pci_dev {
 	struct device		dev;
 	struct list_head	links;
 	struct pci_driver	*pdrv;
 	struct pci_bus		*bus;
 	struct pci_dev		*root;
 	pci_power_t		current_state;
 	uint16_t		device;
 	uint16_t		vendor;
 	uint16_t		subsystem_vendor;
 	uint16_t		subsystem_device;
 	unsigned int		irq;
 	unsigned int		devfn;
 	uint32_t		class;
 	uint8_t			revision;
 	uint8_t			msi_cap;
 	uint8_t			msix_cap;
 	bool			managed;	/* devres "pcim_*(). */
 	bool			want_iomap_res;
 	bool			msi_enabled;
 	bool			msix_enabled;
 	phys_addr_t		rom;
 	size_t			romlen;
 	struct msi_desc		**msi_desc;
 	char			*path_name;
 
 	TAILQ_HEAD(, pci_mmio_region)	mmio;
 };
 
-/* We need some meta-struct to keep track of these for devres. */
-struct pci_devres {
-	bool		enable_io;
-	/* PCIR_MAX_BAR_0 + 1 = 6 => BIT(0..5). */
-	uint8_t		region_mask;
-	struct resource	*region_table[PCIR_MAX_BAR_0 + 1]; /* Not needed. */
-};
-struct pcim_iomap_devres {
-	void		*mmio_table[PCIR_MAX_BAR_0 + 1];
-	struct resource	*res_table[PCIR_MAX_BAR_0 + 1];
-};
-
 int pci_request_region(struct pci_dev *pdev, int bar, const char *res_name);
 int pci_alloc_irq_vectors(struct pci_dev *pdev, int minv, int maxv,
     unsigned int flags);
 bool pci_device_is_present(struct pci_dev *pdev);
 
+int linuxkpi_pcim_enable_device(struct pci_dev *pdev);
+void __iomem **linuxkpi_pcim_iomap_table(struct pci_dev *pdev);
+void *linuxkpi_pci_iomap(struct pci_dev *pdev, int mmio_bar, int mmio_size);
+void linuxkpi_pci_iounmap(struct pci_dev *pdev, void *res);
+int linuxkpi_pcim_iomap_regions(struct pci_dev *pdev, uint32_t mask,
+    const char *name);
+int linuxkpi_pci_request_regions(struct pci_dev *pdev, const char *res_name);
+void linuxkpi_pci_release_region(struct pci_dev *pdev, int bar);
+void linuxkpi_pci_release_regions(struct pci_dev *pdev);
+int linuxkpi_pci_enable_msix(struct pci_dev *pdev, struct msix_entry *entries,
+    int nreq);
+
 /* Internal helper function(s). */
 struct pci_dev *lkpinew_pci_dev(device_t);
-struct pci_devres *lkpi_pci_devres_get_alloc(struct pci_dev *pdev);
 void lkpi_pci_devres_release(struct device *, void *);
-struct resource *_lkpi_pci_iomap(struct pci_dev *pdev, int bar, int mmio_size);
-struct pcim_iomap_devres *lkpi_pcim_iomap_devres_find(struct pci_dev *pdev);
-void lkpi_pcim_iomap_table_release(struct device *, void *);
 struct pci_dev *lkpi_pci_get_device(uint16_t, uint16_t, struct pci_dev *);
 struct msi_desc *lkpi_pci_msi_desc_alloc(int);
+struct device *lkpi_pci_find_irq_dev(unsigned int irq);
+int _lkpi_pci_enable_msi_range(struct pci_dev *pdev, int minvec, int maxvec);
 
 static inline bool
 dev_is_pci(struct device *dev)
 {
 
 	return (device_get_devclass(dev->bsddev) == devclass_find("pci"));
 }
 
 static inline int
 pci_resource_type(struct pci_dev *pdev, int bar)
 {
 	struct pci_map *pm;
 
 	pm = pci_find_bar(pdev->dev.bsddev, PCIR_BAR(bar));
 	if (!pm)
 		return (-1);
 
 	if (PCI_BAR_IO(pm->pm_value))
 		return (SYS_RES_IOPORT);
 	else
 		return (SYS_RES_MEMORY);
 }
 
-struct resource_list_entry *linux_pci_reserve_bar(struct pci_dev *pdev,
-		    struct resource_list *rl, int type, int rid);
-
-static inline struct resource_list_entry *
-linux_pci_get_rle(struct pci_dev *pdev, int type, int rid, bool reserve_bar)
-{
-	struct pci_devinfo *dinfo;
-	struct resource_list *rl;
-	struct resource_list_entry *rle;
-
-	dinfo = device_get_ivars(pdev->dev.bsddev);
-	rl = &dinfo->resources;
-	rle = resource_list_find(rl, type, rid);
-	/* Reserve resources for this BAR if needed. */
-	if (rle == NULL && reserve_bar)
-		rle = linux_pci_reserve_bar(pdev, rl, type, rid);
-	return (rle);
-}
-
-static inline struct resource_list_entry *
-linux_pci_get_bar(struct pci_dev *pdev, int bar, bool reserve)
-{
-	int type;
-
-	type = pci_resource_type(pdev, bar);
-	if (type < 0)
-		return (NULL);
-	bar = PCIR_BAR(bar);
-	return (linux_pci_get_rle(pdev, type, bar, reserve));
-}
-
-static inline struct device *
-linux_pci_find_irq_dev(unsigned int irq)
-{
-	struct pci_dev *pdev;
-	struct device *found;
-
-	found = NULL;
-	spin_lock(&pci_lock);
-	list_for_each_entry(pdev, &pci_devices, links) {
-		if (irq == pdev->dev.irq ||
-		    (irq >= pdev->dev.irq_start && irq < pdev->dev.irq_end)) {
-			found = &pdev->dev;
-			break;
-		}
-	}
-	spin_unlock(&pci_lock);
-	return (found);
-}
-
 /*
  * All drivers just seem to want to inspect the type not flags.
  */
 static inline int
 pci_resource_flags(struct pci_dev *pdev, int bar)
 {
 	int type;
 
 	type = pci_resource_type(pdev, bar);
 	if (type < 0)
 		return (0);
 	return (1 << type);
 }
 
 static inline const char *
 pci_name(struct pci_dev *d)
 {
 	return d->path_name;
 }
 
 static inline void *
 pci_get_drvdata(struct pci_dev *pdev)
 {
 
 	return dev_get_drvdata(&pdev->dev);
 }
 
 static inline void
 pci_set_drvdata(struct pci_dev *pdev, void *data)
 {
 
 	dev_set_drvdata(&pdev->dev, data);
 }
 
 static inline struct pci_dev *
 pci_dev_get(struct pci_dev *pdev)
 {
 
 	if (pdev != NULL)
 		get_device(&pdev->dev);
 	return (pdev);
 }
 
 static __inline void
 pci_dev_put(struct pci_dev *pdev)
 {
 
 	if (pdev != NULL)
 		put_device(&pdev->dev);
 }
 
 static inline int
 pci_enable_device(struct pci_dev *pdev)
 {
 
 	pci_enable_io(pdev->dev.bsddev, SYS_RES_IOPORT);
 	pci_enable_io(pdev->dev.bsddev, SYS_RES_MEMORY);
 	return (0);
 }
 
 static inline void
 pci_disable_device(struct pci_dev *pdev)
 {
 
 	pci_disable_busmaster(pdev->dev.bsddev);
 }
 
 static inline int
 pci_set_master(struct pci_dev *pdev)
 {
 
 	pci_enable_busmaster(pdev->dev.bsddev);
 	return (0);
 }
 
 static inline int
 pci_set_power_state(struct pci_dev *pdev, int state)
 {
 
 	pci_set_powerstate(pdev->dev.bsddev, state);
 	return (0);
 }
 
 static inline int
 pci_clear_master(struct pci_dev *pdev)
 {
 
 	pci_disable_busmaster(pdev->dev.bsddev);
 	return (0);
 }
 
 static inline bool
 pci_is_root_bus(struct pci_bus *pbus)
 {
 
 	return (pbus->self == NULL);
 }
 
 static inline struct pci_dev *
 pci_upstream_bridge(struct pci_dev *pdev)
 {
 
 	if (pci_is_root_bus(pdev->bus))
 		return (NULL);
 
 	/*
 	 * If we do not have a (proper) "upstream bridge" set, e.g., we point
 	 * to ourselves, try to handle this case on the fly like we do
 	 * for pcie_find_root_port().
 	 */
 	if (pdev == pdev->bus->self) {
 		device_t bridge;
 
 		bridge = device_get_parent(pdev->dev.bsddev);
 		if (bridge == NULL)
 			goto done;
 		bridge = device_get_parent(bridge);
 		if (bridge == NULL)
 			goto done;
 		if (device_get_devclass(device_get_parent(bridge)) !=
 		    devclass_find("pci"))
 			goto done;
 
 		/*
 		 * "bridge" is a PCI-to-PCI bridge.  Create a Linux pci_dev
 		 * for it so it can be returned.
 		 */
 		pdev->bus->self = lkpinew_pci_dev(bridge);
 	}
 done:
 	return (pdev->bus->self);
 }
 
-static inline struct pci_devres *
-lkpi_pci_devres_find(struct pci_dev *pdev)
-{
-
-	if (!pdev->managed)
-		return (NULL);
-
-	return (lkpi_pci_devres_get_alloc(pdev));
-}
-
-static inline void
-pci_release_region(struct pci_dev *pdev, int bar)
-{
-	struct resource_list_entry *rle;
-	struct pci_devres *dr;
-	struct pci_mmio_region *mmio, *p;
-
-	if ((rle = linux_pci_get_bar(pdev, bar, false)) == NULL)
-		return;
-
-	/*
-	 * As we implicitly track the requests we also need to clear them on
-	 * release.  Do clear before resource release.
-	 */
-	dr = lkpi_pci_devres_find(pdev);
-	if (dr != NULL) {
-		KASSERT(dr->region_table[bar] == rle->res, ("%s: pdev %p bar %d"
-		    " region_table res %p != rel->res %p\n", __func__, pdev,
-		    bar, dr->region_table[bar], rle->res));
-		dr->region_table[bar] = NULL;
-		dr->region_mask &= ~(1 << bar);
-	}
-
-	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
-		if (rle->res != (void *)rman_get_bushandle(mmio->res))
-			continue;
-		TAILQ_REMOVE(&pdev->mmio, mmio, next);
-		free(mmio, M_DEVBUF);
-	}
-
-	bus_release_resource(pdev->dev.bsddev, rle->type, rle->rid, rle->res);
-}
-
-static inline void
-pci_release_regions(struct pci_dev *pdev)
-{
-	int i;
-
-	for (i = 0; i <= PCIR_MAX_BAR_0; i++)
-		pci_release_region(pdev, i);
-}
-
-static inline int
-pci_request_regions(struct pci_dev *pdev, const char *res_name)
-{
-	int error;
-	int i;
-
-	for (i = 0; i <= PCIR_MAX_BAR_0; i++) {
-		error = pci_request_region(pdev, i, res_name);
-		if (error && error != -ENODEV) {
-			pci_release_regions(pdev);
-			return (error);
-		}
-	}
-	return (0);
-}
+#define	pci_release_region(pdev, bar)	linuxkpi_pci_release_region(pdev, bar)
+#define	pci_release_regions(pdev)	linuxkpi_pci_release_regions(pdev)
+#define	pci_request_regions(pdev, res_name) \
+	linuxkpi_pci_request_regions(pdev, res_name)
 
 static inline void
 lkpi_pci_disable_msix(struct pci_dev *pdev)
 {
 
 	pci_release_msi(pdev->dev.bsddev);
 
 	/*
 	 * The MSIX IRQ numbers associated with this PCI device are no
 	 * longer valid and might be re-assigned. Make sure
-	 * linux_pci_find_irq_dev() does no longer see them by
+	 * lkpi_pci_find_irq_dev() does no longer see them by
 	 * resetting their references to zero:
 	 */
 	pdev->dev.irq_start = 0;
 	pdev->dev.irq_end = 0;
 	pdev->msix_enabled = false;
 }
 /* Only for consistency. No conflict on that one. */
 #define	pci_disable_msix(pdev)		lkpi_pci_disable_msix(pdev)
 
 static inline void
 lkpi_pci_disable_msi(struct pci_dev *pdev)
 {
 
 	pci_release_msi(pdev->dev.bsddev);
 
 	pdev->dev.irq_start = 0;
 	pdev->dev.irq_end = 0;
 	pdev->irq = pdev->dev.irq;
 	pdev->msi_enabled = false;
 }
 #define	pci_disable_msi(pdev)		lkpi_pci_disable_msi(pdev)
 #define	pci_free_irq_vectors(pdev)	lkpi_pci_disable_msi(pdev)
 
 unsigned long	pci_resource_start(struct pci_dev *pdev, int bar);
 unsigned long	pci_resource_len(struct pci_dev *pdev, int bar);
 
 static inline bus_addr_t
 pci_bus_address(struct pci_dev *pdev, int bar)
 {
 
 	return (pci_resource_start(pdev, bar));
 }
 
 #define	PCI_CAP_ID_EXP	PCIY_EXPRESS
 #define	PCI_CAP_ID_PCIX	PCIY_PCIX
 #define PCI_CAP_ID_AGP  PCIY_AGP
 #define PCI_CAP_ID_PM   PCIY_PMG
 
 #define PCI_EXP_DEVCTL		PCIER_DEVICE_CTL
 #define PCI_EXP_DEVCTL_PAYLOAD	PCIEM_CTL_MAX_PAYLOAD
 #define PCI_EXP_DEVCTL_READRQ	PCIEM_CTL_MAX_READ_REQUEST
 #define PCI_EXP_LNKCTL		PCIER_LINK_CTL
 #define PCI_EXP_LNKSTA		PCIER_LINK_STA
 
 static inline int
 pci_find_capability(struct pci_dev *pdev, int capid)
 {
 	int reg;
 
 	if (pci_find_cap(pdev->dev.bsddev, capid, &reg))
 		return (0);
 	return (reg);
 }
 
 static inline int pci_pcie_cap(struct pci_dev *dev)
 {
 	return pci_find_capability(dev, PCI_CAP_ID_EXP);
 }
 
 static inline int
 pci_find_ext_capability(struct pci_dev *pdev, int capid)
 {
 	int reg;
 
 	if (pci_find_extcap(pdev->dev.bsddev, capid, &reg))
 		return (0);
 	return (reg);
 }
 
 #define	PCIM_PCAP_PME_SHIFT	11
 static __inline bool
 pci_pme_capable(struct pci_dev *pdev, uint32_t flag)
 {
 	struct pci_devinfo *dinfo;
 	pcicfgregs *cfg;
 
 	if (flag > (PCIM_PCAP_D3PME_COLD >> PCIM_PCAP_PME_SHIFT))
 		return (false);
 
 	dinfo = device_get_ivars(pdev->dev.bsddev);
 	cfg = &dinfo->cfg;
 
 	if (cfg->pp.pp_cap == 0)
 		return (false);
 
 	if ((cfg->pp.pp_cap & (1 << (PCIM_PCAP_PME_SHIFT + flag))) != 0)
 		return (true);
 
 	return (false);
 }
 
 static inline int
 pci_disable_link_state(struct pci_dev *pdev, uint32_t flags)
 {
 
 	if (!pci_enable_aspm)
 		return (-EPERM);
 
 	return (-ENXIO);
 }
 
 static inline int
 pci_read_config_byte(const struct pci_dev *pdev, int where, u8 *val)
 {
 
 	*val = (u8)pci_read_config(pdev->dev.bsddev, where, 1);
 	return (0);
 }
 
 static inline int
 pci_read_config_word(const struct pci_dev *pdev, int where, u16 *val)
 {
 
 	*val = (u16)pci_read_config(pdev->dev.bsddev, where, 2);
 	return (0);
 }
 
 static inline int
 pci_read_config_dword(const struct pci_dev *pdev, int where, u32 *val)
 {
 
 	*val = (u32)pci_read_config(pdev->dev.bsddev, where, 4);
 	return (0);
 }
 
 static inline int
 pci_write_config_byte(const struct pci_dev *pdev, int where, u8 val)
 {
 
 	pci_write_config(pdev->dev.bsddev, where, val, 1);
 	return (0);
 }
 
 static inline int
 pci_write_config_word(const struct pci_dev *pdev, int where, u16 val)
 {
 
 	pci_write_config(pdev->dev.bsddev, where, val, 2);
 	return (0);
 }
 
 static inline int
 pci_write_config_dword(const struct pci_dev *pdev, int where, u32 val)
 {
 
 	pci_write_config(pdev->dev.bsddev, where, val, 4);
 	return (0);
 }
 
 int	linux_pci_register_driver(struct pci_driver *pdrv);
 int	linux_pci_register_drm_driver(struct pci_driver *pdrv);
 void	linux_pci_unregister_driver(struct pci_driver *pdrv);
 void	linux_pci_unregister_drm_driver(struct pci_driver *pdrv);
 
 #define	pci_register_driver(pdrv)	linux_pci_register_driver(pdrv)
 #define	pci_unregister_driver(pdrv)	linux_pci_unregister_driver(pdrv)
 
-struct msix_entry {
-	int entry;
-	int vector;
-};
-
 /*
  * Enable msix, positive errors indicate actual number of available
  * vectors.  Negative errors are failures.
  *
  * NB: define added to prevent this definition of pci_enable_msix from
  * clashing with the native FreeBSD version.
  */
-#define	pci_enable_msix(...) \
-  linux_pci_enable_msix(__VA_ARGS__)
-
-static inline int
-pci_enable_msix(struct pci_dev *pdev, struct msix_entry *entries, int nreq)
-{
-	struct resource_list_entry *rle;
-	int error;
-	int avail;
-	int i;
-
-	avail = pci_msix_count(pdev->dev.bsddev);
-	if (avail < nreq) {
-		if (avail == 0)
-			return -EINVAL;
-		return avail;
-	}
-	avail = nreq;
-	if ((error = -pci_alloc_msix(pdev->dev.bsddev, &avail)) != 0)
-		return error;
-	/*
-	 * Handle case where "pci_alloc_msix()" may allocate less
-	 * interrupts than available and return with no error:
-	 */
-	if (avail < nreq) {
-		pci_release_msi(pdev->dev.bsddev);
-		return avail;
-	}
-	rle = linux_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
-	pdev->dev.irq_start = rle->start;
-	pdev->dev.irq_end = rle->start + avail;
-	for (i = 0; i < nreq; i++)
-		entries[i].vector = pdev->dev.irq_start + i;
-	pdev->msix_enabled = true;
-	return (0);
-}
+#define	pci_enable_msix(...)	linuxkpi_pci_enable_msix(__VA_ARGS__)
 
 #define	pci_enable_msix_range(...) \
   linux_pci_enable_msix_range(__VA_ARGS__)
 
 static inline int
 pci_enable_msix_range(struct pci_dev *dev, struct msix_entry *entries,
     int minvec, int maxvec)
 {
 	int nvec = maxvec;
 	int rc;
 
 	if (maxvec < minvec)
 		return (-ERANGE);
 
 	do {
 		rc = pci_enable_msix(dev, entries, nvec);
 		if (rc < 0) {
 			return (rc);
 		} else if (rc > 0) {
 			if (rc < minvec)
 				return (-ENOSPC);
 			nvec = rc;
 		}
 	} while (rc);
 	return (nvec);
 }
 
 #define	pci_enable_msi(pdev) \
   linux_pci_enable_msi(pdev)
 
-static inline int
-_lkpi_pci_enable_msi_range(struct pci_dev *pdev, int minvec, int maxvec)
-{
-	struct resource_list_entry *rle;
-	int error;
-	int nvec;
-
-	if (maxvec < minvec)
-		return (-EINVAL);
-
-	nvec = pci_msi_count(pdev->dev.bsddev);
-	if (nvec < 1 || nvec < minvec)
-		return (-ENOSPC);
-
-	nvec = min(nvec, maxvec);
-	if ((error = -pci_alloc_msi(pdev->dev.bsddev, &nvec)) != 0)
-		return error;
-
-	/* Native PCI might only ever ask for 32 vectors. */
-	if (nvec < minvec) {
-		pci_release_msi(pdev->dev.bsddev);
-		return (-ENOSPC);
-	}
-
-	rle = linux_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
-	pdev->dev.irq_start = rle->start;
-	pdev->dev.irq_end = rle->start + nvec;
-	pdev->irq = rle->start;
-	pdev->msi_enabled = true;
-	return (0);
-}
-
 static inline int
 pci_enable_msi(struct pci_dev *pdev)
 {
 
 	return (_lkpi_pci_enable_msi_range(pdev, 1, 1));
 }
 
 static inline int
 pci_channel_offline(struct pci_dev *pdev)
 {
 
 	return (pci_read_config(pdev->dev.bsddev, PCIR_VENDOR, 2) == PCIV_INVALID);
 }
 
 static inline int pci_enable_sriov(struct pci_dev *dev, int nr_virtfn)
 {
 	return -ENODEV;
 }
 
 static inline void pci_disable_sriov(struct pci_dev *dev)
 {
 }
 
-static inline void *
-pci_iomap(struct pci_dev *pdev, int mmio_bar, int mmio_size)
-{
-	struct resource *res;
-
-	res = _lkpi_pci_iomap(pdev, mmio_bar, mmio_size);
-	if (res == NULL)
-		return (NULL);
-	/* This is a FreeBSD extension so we can use bus_*(). */
-	if (pdev->want_iomap_res)
-		return (res);
-	return ((void *)rman_get_bushandle(res));
-}
-
-static inline void
-pci_iounmap(struct pci_dev *pdev, void *res)
-{
-	struct pci_mmio_region *mmio, *p;
-
-	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
-		if (res != (void *)rman_get_bushandle(mmio->res))
-			continue;
-		bus_release_resource(pdev->dev.bsddev,
-		    mmio->type, mmio->rid, mmio->res);
-		TAILQ_REMOVE(&pdev->mmio, mmio, next);
-		free(mmio, M_DEVBUF);
-		return;
-	}
-}
+#define	pci_iomap(pdev, mmio_bar, mmio_size) \
+	linuxkpi_pci_iomap(pdev, mmio_bar, mmio_size)
+#define	pci_iounmap(pdev, res)	linuxkpi_pci_iounmap(pdev, res)
 
 static inline void
 lkpi_pci_save_state(struct pci_dev *pdev)
 {
 
 	pci_save_state(pdev->dev.bsddev);
 }
 
 static inline void
 lkpi_pci_restore_state(struct pci_dev *pdev)
 {
 
 	pci_restore_state(pdev->dev.bsddev);
 }
 
 #define pci_save_state(dev)	lkpi_pci_save_state(dev)
 #define pci_restore_state(dev)	lkpi_pci_restore_state(dev)
 
 static inline int
 pci_reset_function(struct pci_dev *pdev)
 {
 
 	return (-ENOSYS);
 }
 
 #define DEFINE_PCI_DEVICE_TABLE(_table) \
 	const struct pci_device_id _table[] __devinitdata
 
 /* XXX This should not be necessary. */
 #define	pcix_set_mmrbc(d, v)	0
 #define	pcix_get_max_mmrbc(d)	0
 #define	pcie_set_readrq(d, v)	pci_set_max_read_req((d)->dev.bsddev, (v))
 
 #define	PCI_DMA_BIDIRECTIONAL	0
 #define	PCI_DMA_TODEVICE	1
 #define	PCI_DMA_FROMDEVICE	2
 #define	PCI_DMA_NONE		3
 
 #define	pci_pool		dma_pool
 #define	pci_pool_destroy(...)	dma_pool_destroy(__VA_ARGS__)
 #define	pci_pool_alloc(...)	dma_pool_alloc(__VA_ARGS__)
 #define	pci_pool_free(...)	dma_pool_free(__VA_ARGS__)
 #define	pci_pool_create(_name, _pdev, _size, _align, _alloc)		\
 	    dma_pool_create(_name, &(_pdev)->dev, _size, _align, _alloc)
 #define	pci_free_consistent(_hwdev, _size, _vaddr, _dma_handle)		\
 	    dma_free_coherent((_hwdev) == NULL ? NULL : &(_hwdev)->dev,	\
 		_size, _vaddr, _dma_handle)
 #define	pci_map_sg(_hwdev, _sg, _nents, _dir)				\
 	    dma_map_sg((_hwdev) == NULL ? NULL : &(_hwdev->dev),	\
 		_sg, _nents, (enum dma_data_direction)_dir)
 #define	pci_map_single(_hwdev, _ptr, _size, _dir)			\
 	    dma_map_single((_hwdev) == NULL ? NULL : &(_hwdev->dev),	\
 		(_ptr), (_size), (enum dma_data_direction)_dir)
 #define	pci_unmap_single(_hwdev, _addr, _size, _dir)			\
 	    dma_unmap_single((_hwdev) == NULL ? NULL : &(_hwdev)->dev,	\
 		_addr, _size, (enum dma_data_direction)_dir)
 #define	pci_unmap_sg(_hwdev, _sg, _nents, _dir)				\
 	    dma_unmap_sg((_hwdev) == NULL ? NULL : &(_hwdev)->dev,	\
 		_sg, _nents, (enum dma_data_direction)_dir)
 #define	pci_map_page(_hwdev, _page, _offset, _size, _dir)		\
 	    dma_map_page((_hwdev) == NULL ? NULL : &(_hwdev)->dev, _page,\
 		_offset, _size, (enum dma_data_direction)_dir)
 #define	pci_unmap_page(_hwdev, _dma_address, _size, _dir)		\
 	    dma_unmap_page((_hwdev) == NULL ? NULL : &(_hwdev)->dev,	\
 		_dma_address, _size, (enum dma_data_direction)_dir)
 #define	pci_set_dma_mask(_pdev, mask)	dma_set_mask(&(_pdev)->dev, (mask))
 #define	pci_dma_mapping_error(_pdev, _dma_addr)				\
 	    dma_mapping_error(&(_pdev)->dev, _dma_addr)
 #define	pci_set_consistent_dma_mask(_pdev, _mask)			\
 	    dma_set_coherent_mask(&(_pdev)->dev, (_mask))
 #define	DECLARE_PCI_UNMAP_ADDR(x)	DEFINE_DMA_UNMAP_ADDR(x);
 #define	DECLARE_PCI_UNMAP_LEN(x)	DEFINE_DMA_UNMAP_LEN(x);
 #define	pci_unmap_addr		dma_unmap_addr
 #define	pci_unmap_addr_set	dma_unmap_addr_set
 #define	pci_unmap_len		dma_unmap_len
 #define	pci_unmap_len_set	dma_unmap_len_set
 
 typedef unsigned int __bitwise pci_channel_state_t;
 typedef unsigned int __bitwise pci_ers_result_t;
 
 enum pci_channel_state {
 	pci_channel_io_normal = 1,
 	pci_channel_io_frozen = 2,
 	pci_channel_io_perm_failure = 3,
 };
 
 enum pci_ers_result {
 	PCI_ERS_RESULT_NONE = 1,
 	PCI_ERS_RESULT_CAN_RECOVER = 2,
 	PCI_ERS_RESULT_NEED_RESET = 3,
 	PCI_ERS_RESULT_DISCONNECT = 4,
 	PCI_ERS_RESULT_RECOVERED = 5,
 };
 
 /* PCI bus error event callbacks */
 struct pci_error_handlers {
 	pci_ers_result_t (*error_detected)(struct pci_dev *dev,
 	    enum pci_channel_state error);
 	pci_ers_result_t (*mmio_enabled)(struct pci_dev *dev);
 	pci_ers_result_t (*link_reset)(struct pci_dev *dev);
 	pci_ers_result_t (*slot_reset)(struct pci_dev *dev);
 	void (*resume)(struct pci_dev *dev);
 };
 
 /* FreeBSD does not support SRIOV - yet */
 static inline struct pci_dev *pci_physfn(struct pci_dev *dev)
 {
 	return dev;
 }
 
 static inline bool pci_is_pcie(struct pci_dev *dev)
 {
 	return !!pci_pcie_cap(dev);
 }
 
 static inline u16 pcie_flags_reg(struct pci_dev *dev)
 {
 	int pos;
 	u16 reg16;
 
 	pos = pci_find_capability(dev, PCI_CAP_ID_EXP);
 	if (!pos)
 		return 0;
 
 	pci_read_config_word(dev, pos + PCI_EXP_FLAGS, &reg16);
 
 	return reg16;
 }
 
 static inline int pci_pcie_type(struct pci_dev *dev)
 {
 	return (pcie_flags_reg(dev) & PCI_EXP_FLAGS_TYPE) >> 4;
 }
 
 static inline int pcie_cap_version(struct pci_dev *dev)
 {
 	return pcie_flags_reg(dev) & PCI_EXP_FLAGS_VERS;
 }
 
 static inline bool pcie_cap_has_lnkctl(struct pci_dev *dev)
 {
 	int type = pci_pcie_type(dev);
 
 	return pcie_cap_version(dev) > 1 ||
 	       type == PCI_EXP_TYPE_ROOT_PORT ||
 	       type == PCI_EXP_TYPE_ENDPOINT ||
 	       type == PCI_EXP_TYPE_LEG_END;
 }
 
 static inline bool pcie_cap_has_devctl(const struct pci_dev *dev)
 {
 		return true;
 }
 
 static inline bool pcie_cap_has_sltctl(struct pci_dev *dev)
 {
 	int type = pci_pcie_type(dev);
 
 	return pcie_cap_version(dev) > 1 || type == PCI_EXP_TYPE_ROOT_PORT ||
 	    (type == PCI_EXP_TYPE_DOWNSTREAM &&
 	    pcie_flags_reg(dev) & PCI_EXP_FLAGS_SLOT);
 }
 
 static inline bool pcie_cap_has_rtctl(struct pci_dev *dev)
 {
 	int type = pci_pcie_type(dev);
 
 	return pcie_cap_version(dev) > 1 || type == PCI_EXP_TYPE_ROOT_PORT ||
 	    type == PCI_EXP_TYPE_RC_EC;
 }
 
 static bool pcie_capability_reg_implemented(struct pci_dev *dev, int pos)
 {
 	if (!pci_is_pcie(dev))
 		return false;
 
 	switch (pos) {
 	case PCI_EXP_FLAGS_TYPE:
 		return true;
 	case PCI_EXP_DEVCAP:
 	case PCI_EXP_DEVCTL:
 	case PCI_EXP_DEVSTA:
 		return pcie_cap_has_devctl(dev);
 	case PCI_EXP_LNKCAP:
 	case PCI_EXP_LNKCTL:
 	case PCI_EXP_LNKSTA:
 		return pcie_cap_has_lnkctl(dev);
 	case PCI_EXP_SLTCAP:
 	case PCI_EXP_SLTCTL:
 	case PCI_EXP_SLTSTA:
 		return pcie_cap_has_sltctl(dev);
 	case PCI_EXP_RTCTL:
 	case PCI_EXP_RTCAP:
 	case PCI_EXP_RTSTA:
 		return pcie_cap_has_rtctl(dev);
 	case PCI_EXP_DEVCAP2:
 	case PCI_EXP_DEVCTL2:
 	case PCI_EXP_LNKCAP2:
 	case PCI_EXP_LNKCTL2:
 	case PCI_EXP_LNKSTA2:
 		return pcie_cap_version(dev) > 1;
 	default:
 		return false;
 	}
 }
 
 static inline int
 pcie_capability_read_dword(struct pci_dev *dev, int pos, u32 *dst)
 {
 	*dst = 0;
 	if (pos & 3)
 		return -EINVAL;
 
 	if (!pcie_capability_reg_implemented(dev, pos))
 		return -EINVAL;
 
 	return pci_read_config_dword(dev, pci_pcie_cap(dev) + pos, dst);
 }
 
 static inline int
 pcie_capability_read_word(struct pci_dev *dev, int pos, u16 *dst)
 {
 	*dst = 0;
 	if (pos & 3)
 		return -EINVAL;
 
 	if (!pcie_capability_reg_implemented(dev, pos))
 		return -EINVAL;
 
 	return pci_read_config_word(dev, pci_pcie_cap(dev) + pos, dst);
 }
 
 static inline int
 pcie_capability_write_word(struct pci_dev *dev, int pos, u16 val)
 {
 	if (pos & 1)
 		return -EINVAL;
 
 	if (!pcie_capability_reg_implemented(dev, pos))
 		return 0;
 
 	return pci_write_config_word(dev, pci_pcie_cap(dev) + pos, val);
 }
 
 static inline int
 pcie_capability_set_word(struct pci_dev *dev, int pos, uint16_t val)
 {
 	int error;
 	uint16_t v;
 
 	error = pcie_capability_read_word(dev, pos, &v);
 	if (error != 0)
 		return (error);
 
 	v |= val;
 
 	error = pcie_capability_write_word(dev, pos, v);
 	return (error);
 }
 
 static inline int
 pcie_capability_clear_word(struct pci_dev *dev, int pos, uint16_t val)
 {
 	int error;
 	uint16_t v;
 
 	error = pcie_capability_read_word(dev, pos, &v);
 	if (error != 0)
 		return (error);
 
 	v &= ~val;
 
 	error = pcie_capability_write_word(dev, pos, v);
 	return (error);
 }
 
 static inline int pcie_get_minimum_link(struct pci_dev *dev,
     enum pci_bus_speed *speed, enum pcie_link_width *width)
 {
 	*speed = PCI_SPEED_UNKNOWN;
 	*width = PCIE_LNK_WIDTH_UNKNOWN;
 	return (0);
 }
 
 static inline int
 pci_num_vf(struct pci_dev *dev)
 {
 	return (0);
 }
 
 static inline enum pci_bus_speed
 pcie_get_speed_cap(struct pci_dev *dev)
 {
 	device_t root;
 	uint32_t lnkcap, lnkcap2;
 	int error, pos;
 
 	root = device_get_parent(dev->dev.bsddev);
 	if (root == NULL)
 		return (PCI_SPEED_UNKNOWN);
 	root = device_get_parent(root);
 	if (root == NULL)
 		return (PCI_SPEED_UNKNOWN);
 	root = device_get_parent(root);
 	if (root == NULL)
 		return (PCI_SPEED_UNKNOWN);
 
 	if (pci_get_vendor(root) == PCI_VENDOR_ID_VIA ||
 	    pci_get_vendor(root) == PCI_VENDOR_ID_SERVERWORKS)
 		return (PCI_SPEED_UNKNOWN);
 
 	if ((error = pci_find_cap(root, PCIY_EXPRESS, &pos)) != 0)
 		return (PCI_SPEED_UNKNOWN);
 
 	lnkcap2 = pci_read_config(root, pos + PCIER_LINK_CAP2, 4);
 
 	if (lnkcap2) {	/* PCIe r3.0-compliant */
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_2_5GB)
 			return (PCIE_SPEED_2_5GT);
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_5_0GB)
 			return (PCIE_SPEED_5_0GT);
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_8_0GB)
 			return (PCIE_SPEED_8_0GT);
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_16_0GB)
 			return (PCIE_SPEED_16_0GT);
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_32_0GB)
 			return (PCIE_SPEED_32_0GT);
 		if (lnkcap2 & PCI_EXP_LNKCAP2_SLS_64_0GB)
 			return (PCIE_SPEED_64_0GT);
 	} else {	/* pre-r3.0 */
 		lnkcap = pci_read_config(root, pos + PCIER_LINK_CAP, 4);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_2_5GB)
 			return (PCIE_SPEED_2_5GT);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_5_0GB)
 			return (PCIE_SPEED_5_0GT);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_8_0GB)
 			return (PCIE_SPEED_8_0GT);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_16_0GB)
 			return (PCIE_SPEED_16_0GT);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_32_0GB)
 			return (PCIE_SPEED_32_0GT);
 		if (lnkcap & PCI_EXP_LNKCAP_SLS_64_0GB)
 			return (PCIE_SPEED_64_0GT);
 	}
 	return (PCI_SPEED_UNKNOWN);
 }
 
 static inline enum pcie_link_width
 pcie_get_width_cap(struct pci_dev *dev)
 {
 	uint32_t lnkcap;
 
 	pcie_capability_read_dword(dev, PCI_EXP_LNKCAP, &lnkcap);
 	if (lnkcap)
 		return ((lnkcap & PCI_EXP_LNKCAP_MLW) >> 4);
 
 	return (PCIE_LNK_WIDTH_UNKNOWN);
 }
 
 static inline int
 pcie_get_mps(struct pci_dev *dev)
 {
 	return (pci_get_max_payload(dev->dev.bsddev));
 }
 
 static inline uint32_t
 PCIE_SPEED2MBS_ENC(enum pci_bus_speed spd)
 {
 
 	switch(spd) {
 	case PCIE_SPEED_64_0GT:
 		return (64000 * 128 / 130);
 	case PCIE_SPEED_32_0GT:
 		return (32000 * 128 / 130);
 	case PCIE_SPEED_16_0GT:
 		return (16000 * 128 / 130);
 	case PCIE_SPEED_8_0GT:
 		return (8000 * 128 / 130);
 	case PCIE_SPEED_5_0GT:
 		return (5000 * 8 / 10);
 	case PCIE_SPEED_2_5GT:
 		return (2500 * 8 / 10);
 	default:
 		return (0);
 	}
 }
 
 static inline uint32_t
 pcie_bandwidth_available(struct pci_dev *pdev,
     struct pci_dev **limiting,
     enum pci_bus_speed *speed,
     enum pcie_link_width *width)
 {
 	enum pci_bus_speed nspeed = pcie_get_speed_cap(pdev);
 	enum pcie_link_width nwidth = pcie_get_width_cap(pdev);
 
 	if (speed)
 		*speed = nspeed;
 	if (width)
 		*width = nwidth;
 
 	return (nwidth * PCIE_SPEED2MBS_ENC(nspeed));
 }
 
 static inline bool
 pcie_aspm_enabled(struct pci_dev *pdev)
 {
 	return (false);
 }
 
 static inline struct pci_dev *
 pcie_find_root_port(struct pci_dev *pdev)
 {
 	device_t root;
 
 	if (pdev->root != NULL)
 		return (pdev->root);
 
 	root = pci_find_pcie_root_port(pdev->dev.bsddev);
 	if (root == NULL)
 		return (NULL);
 
 	pdev->root = lkpinew_pci_dev(root);
 	return (pdev->root);
 }
 
 /* This is needed when people rip out the device "HotPlug". */
 static inline void
 pci_lock_rescan_remove(void)
 {
 }
 
 static inline void
 pci_unlock_rescan_remove(void)
 {
 }
 
 static __inline void
 pci_stop_and_remove_bus_device(struct pci_dev *pdev)
 {
 }
 
 static inline int
 pci_rescan_bus(struct pci_bus *pbus)
 {
 	device_t *devlist, parent;
 	int devcount, error;
 
 	if (!device_is_attached(pbus->self->dev.bsddev))
 		return (0);
 	/* pci_rescan_method() will work on the pcib (parent). */
 	error = BUS_RESCAN(pbus->self->dev.bsddev);
 	if (error != 0)
 		return (0);
 
 	parent = device_get_parent(pbus->self->dev.bsddev);
 	error = device_get_children(parent, &devlist, &devcount);
 	if (error != 0)
 		return (0);
 	if (devcount != 0)
 		free(devlist, M_TEMP);
 
 	return (devcount);
 }
 
 /*
  * The following functions can be used to attach/detach the LinuxKPI's
  * PCI device runtime. The pci_driver and pci_device_id pointer is
  * allowed to be NULL. Other pointers must be all valid.
  * The pci_dev structure should be zero-initialized before passed
  * to the linux_pci_attach_device function.
  */
 extern int linux_pci_attach_device(device_t, struct pci_driver *,
     const struct pci_device_id *, struct pci_dev *);
 extern int linux_pci_detach_device(struct pci_dev *);
 
 static inline int
 pci_dev_present(const struct pci_device_id *cur)
 {
 	while (cur != NULL && (cur->vendor || cur->device)) {
 		if (pci_find_device(cur->vendor, cur->device) != NULL) {
 			return (1);
 		}
 		cur++;
 	}
 	return (0);
 }
 
 struct pci_dev *lkpi_pci_get_domain_bus_and_slot(int domain,
     unsigned int bus, unsigned int devfn);
 #define	pci_get_domain_bus_and_slot(domain, bus, devfn)	\
 	lkpi_pci_get_domain_bus_and_slot(domain, bus, devfn)
 
 static inline int
 pci_domain_nr(struct pci_bus *pbus)
 {
 
 	return (pbus->domain);
 }
 
 static inline int
 pci_bus_read_config(struct pci_bus *bus, unsigned int devfn,
                     int pos, uint32_t *val, int len)
 {
 
 	*val = pci_read_config(bus->self->dev.bsddev, pos, len);
 	return (0);
 }
 
 static inline int
 pci_bus_read_config_word(struct pci_bus *bus, unsigned int devfn, int pos, u16 *val)
 {
 	uint32_t tmp;
 	int ret;
 
 	ret = pci_bus_read_config(bus, devfn, pos, &tmp, 2);
 	*val = (u16)tmp;
 	return (ret);
 }
 
 static inline int
 pci_bus_read_config_byte(struct pci_bus *bus, unsigned int devfn, int pos, u8 *val)
 {
 	uint32_t tmp;
 	int ret;
 
 	ret = pci_bus_read_config(bus, devfn, pos, &tmp, 1);
 	*val = (u8)tmp;
 	return (ret);
 }
 
 static inline int
 pci_bus_write_config(struct pci_bus *bus, unsigned int devfn, int pos,
     uint32_t val, int size)
 {
 
 	pci_write_config(bus->self->dev.bsddev, pos, val, size);
 	return (0);
 }
 
 static inline int
 pci_bus_write_config_byte(struct pci_bus *bus, unsigned int devfn, int pos,
     uint8_t val)
 {
 	return (pci_bus_write_config(bus, devfn, pos, val, 1));
 }
 
 static inline int
 pci_bus_write_config_word(struct pci_bus *bus, unsigned int devfn, int pos,
     uint16_t val)
 {
 	return (pci_bus_write_config(bus, devfn, pos, val, 2));
 }
 
 struct pci_dev *lkpi_pci_get_class(unsigned int class, struct pci_dev *from);
 #define	pci_get_class(class, from)	lkpi_pci_get_class(class, from)
 
 /* -------------------------------------------------------------------------- */
 
-static inline int
-pcim_enable_device(struct pci_dev *pdev)
-{
-	struct pci_devres *dr;
-	int error;
-
-	/* Here we cannot run through the pdev->managed check. */
-	dr = lkpi_pci_devres_get_alloc(pdev);
-	if (dr == NULL)
-		return (-ENOMEM);
-
-	/* If resources were enabled before do not do it again. */
-	if (dr->enable_io)
-		return (0);
-
-	error = pci_enable_device(pdev);
-	if (error == 0)
-		dr->enable_io = true;
-
-	/* This device is not managed. */
-	pdev->managed = true;
-
-	return (error);
-}
-
-static inline void __iomem **
-pcim_iomap_table(struct pci_dev *pdev)
-{
-	struct pcim_iomap_devres *dr;
-
-	dr = lkpi_pcim_iomap_devres_find(pdev);
-	if (dr == NULL)
-		return (NULL);
-
-	/*
-	 * If the driver has manually set a flag to be able to request the
-	 * resource to use bus_read/write_<n>, return the shadow table.
-	 */
-	if (pdev->want_iomap_res)
-		return ((void **)dr->res_table);
-
-	/* This is the Linux default. */
-	return (dr->mmio_table);
-}
-
-static inline int
-pcim_iomap_regions(struct pci_dev *pdev, uint32_t mask, const char *name)
-{
-	struct pcim_iomap_devres *dr;
-	void *res;
-	uint32_t mappings;
-	int bar;
-
-	dr = lkpi_pcim_iomap_devres_find(pdev);
-	if (dr == NULL)
-		return (-ENOMEM);
-
-	/* Now iomap all the requested (by "mask") ones. */
-	for (bar = mappings = 0; mappings != mask; bar++) {
-		if ((mask & (1 << bar)) == 0)
-			continue;
-
-		/* Request double is not allowed. */
-		if (dr->mmio_table[bar] != NULL) {
-			device_printf(pdev->dev.bsddev, "%s: bar %d %p\n",
-			     __func__, bar, dr->mmio_table[bar]);
-			goto err;
-		}
-
-		res = _lkpi_pci_iomap(pdev, bar, 0);
-		if (res == NULL)
-			goto err;
-		dr->mmio_table[bar] = (void *)rman_get_bushandle(res);
-		dr->res_table[bar] = res;
-
-		mappings |= (1 << bar);
-	}
-
-	return (0);
-err:
-	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
-		if ((mappings & (1 << bar)) != 0) {
-			res = dr->mmio_table[bar];
-			if (res == NULL)
-				continue;
-			pci_iounmap(pdev, res);
-		}
-	}
-
-	return (-EINVAL);
-}
+#define	pcim_enable_device(pdev)	linuxkpi_pcim_enable_device(pdev)
+#define	pcim_iomap_table(pdev)	 linuxkpi_pcim_iomap_table(pdev)
+#define	pcim_iomap_regions(pdev, mask, name) \
+	linuxkpi_pcim_iomap_regions(pdev,  mask, name)
 
 static inline int
 pcim_iomap_regions_request_all(struct pci_dev *pdev, uint32_t mask, char *name)
 {
 	uint32_t requests, req_mask;
 	int bar, error;
 
 	/* Request all the BARs ("regions") we do not iomap. */
 	req_mask = ((1 << (PCIR_MAX_BAR_0 + 1)) - 1) & ~mask;
 	for (bar = requests = 0; requests != req_mask; bar++) {
 		if ((req_mask & (1 << bar)) == 0)
 			continue;
 		error = pci_request_region(pdev, bar, name);
 		if (error != 0 && error != -ENODEV)
 			goto err;
 		requests |= (1 << bar);
 	}
 
 	error = pcim_iomap_regions(pdev, mask, name);
 	if (error != 0)
 		goto err;
 
 	return (0);
 
 err:
 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
 		if ((requests & (1 << bar)) != 0)
 			pci_release_region(pdev, bar);
 	}
 
 	return (-EINVAL);
 }
 
 /*
  * We cannot simply re-define pci_get_device() as we would normally do
  * and then hide it in linux_pci.c as too many semi-native drivers still
  * include linux/pci.h and run into the conflict with native PCI. Linux drivers
  * using pci_get_device() need to be changed to call linuxkpi_pci_get_device().
  */
 static inline struct pci_dev *
 linuxkpi_pci_get_device(uint16_t vendor, uint16_t device, struct pci_dev *odev)
 {
 
 	return (lkpi_pci_get_device(vendor, device, odev));
 }
 
 /* This is a FreeBSD extension so we can use bus_*(). */
 static inline void
 linuxkpi_pcim_want_to_use_bus_functions(struct pci_dev *pdev)
 {
 	pdev->want_iomap_res = true;
 }
 
 static inline bool
 pci_is_thunderbolt_attached(struct pci_dev *pdev)
 {
 
 	return (false);
 }
 
 static inline void *
 pci_platform_rom(struct pci_dev *pdev, size_t *size)
 {
 
 	return (NULL);
 }
 
 static inline void
 pci_ignore_hotplug(struct pci_dev *pdev)
 {
 }
 
 static inline const char *
 pci_power_name(pci_power_t state)
 {
 	int pstate = state + 1;
 
 	if (pstate >= 0 && pstate < nitems(pci_power_names))
 		return (pci_power_names[pstate]);
 	else
 		return (pci_power_names[0]);
 }
 
 static inline int
 pcie_get_readrq(struct pci_dev *dev)
 {
 	u16 ctl;
 
 	if (pcie_capability_read_word(dev, PCI_EXP_DEVCTL, &ctl))
 		return (-EINVAL);
 
 	return (128 << ((ctl & PCI_EXP_DEVCTL_READRQ) >> 12));
 }
 
 static inline bool
 pci_is_enabled(struct pci_dev *pdev)
 {
 
 	return ((pci_read_config(pdev->dev.bsddev, PCIR_COMMAND, 2) &
 	    PCIM_CMD_BUSMASTEREN) != 0);
 }
 
 static inline int
 pci_wait_for_pending_transaction(struct pci_dev *pdev)
 {
 
 	return (0);
 }
 
 static inline int
 pci_assign_resource(struct pci_dev *pdev, int bar)
 {
 
 	return (0);
 }
 
 static inline int
 pci_irq_vector(struct pci_dev *pdev, unsigned int vector)
 {
 
 	if (!pdev->msix_enabled && !pdev->msi_enabled) {
 		if (vector != 0)
 			return (-EINVAL);
 		return (pdev->irq);
 	}
 
 	if (pdev->msix_enabled || pdev->msi_enabled) {
 		if ((pdev->dev.irq_start + vector) >= pdev->dev.irq_end)
 			return (-EINVAL);
 		return (pdev->dev.irq_start + vector);
 	}
 
         return (-ENXIO);
 }
 
 #endif	/* _LINUXKPI_LINUX_PCI_H_ */
diff --git a/sys/compat/linuxkpi/common/src/linux_interrupt.c b/sys/compat/linuxkpi/common/src/linux_interrupt.c
index 5602b09c8fb8..378088246f21 100644
--- a/sys/compat/linuxkpi/common/src/linux_interrupt.c
+++ b/sys/compat/linuxkpi/common/src/linux_interrupt.c
@@ -1,248 +1,251 @@
 /*-
  * Copyright (c) 2010 Isilon Systems, Inc.
  * Copyright (c) 2010 iX Systems, Inc.
  * Copyright (c) 2010 Panasas, Inc.
  * Copyright (c) 2013-2015 Mellanox Technologies, Ltd.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice unmodified, this list of conditions, and the following
  *    disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include <linux/device.h>
 #include <linux/interrupt.h>
 #include <linux/pci.h>
 
 #include <sys/param.h>
 #include <sys/bus.h>
 #include <sys/rman.h>
 #include <sys/interrupt.h>
 
 struct irq_ent {
 	struct list_head	links;
 	struct device	*dev;
 	struct resource	*res;
 	void		*arg;
 	irqreturn_t	(*handler)(int, void *);
 	irqreturn_t	(*thread_handler)(int, void *);
 	void		*tag;
 	unsigned int	irq;
 };
 
 static inline int
 lkpi_irq_rid(struct device *dev, unsigned int irq)
 {
 	/* check for MSI- or MSIX- interrupt */
 	if (irq >= dev->irq_start && irq < dev->irq_end)
 		return (irq - dev->irq_start + 1);
 	else
 		return (0);
 }
 
 static inline struct irq_ent *
 lkpi_irq_ent(struct device *dev, unsigned int irq)
 {
 	struct irq_ent *irqe;
 
 	list_for_each_entry(irqe, &dev->irqents, links)
 		if (irqe->irq == irq)
 			return (irqe);
 
 	return (NULL);
 }
 
 static void
 lkpi_irq_handler(void *ent)
 {
 	struct irq_ent *irqe;
 
 	if (linux_set_current_flags(curthread, M_NOWAIT))
 		return;
 
 	irqe = ent;
 	if (irqe->handler(irqe->irq, irqe->arg) == IRQ_WAKE_THREAD &&
 	    irqe->thread_handler != NULL) {
 		THREAD_SLEEPING_OK();
 		irqe->thread_handler(irqe->irq, irqe->arg);
 		THREAD_NO_SLEEPING();
 	}
 }
 
 static inline void
 lkpi_irq_release(struct device *dev, struct irq_ent *irqe)
 {
 	if (irqe->tag != NULL)
 		bus_teardown_intr(dev->bsddev, irqe->res, irqe->tag);
 	if (irqe->res != NULL)
 		bus_release_resource(dev->bsddev, SYS_RES_IRQ,
 		    rman_get_rid(irqe->res), irqe->res);
 	list_del(&irqe->links);
 }
 
 static void
 lkpi_devm_irq_release(struct device *dev, void *p)
 {
 	struct irq_ent *irqe;
 
 	if (dev == NULL || p == NULL)
 		return;
 
 	irqe = p;
 	lkpi_irq_release(dev, irqe);
 }
 
 int
 lkpi_request_irq(struct device *xdev, unsigned int irq,
     irq_handler_t handler, irq_handler_t thread_handler,
     unsigned long flags, const char *name, void *arg)
 {
 	struct resource *res;
 	struct irq_ent *irqe;
 	struct device *dev;
+	unsigned resflags;
 	int error;
 	int rid;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return -ENXIO;
 	if (xdev != NULL && xdev != dev)
 		return -ENXIO;
 	rid = lkpi_irq_rid(dev, irq);
-	res = bus_alloc_resource_any(dev->bsddev, SYS_RES_IRQ, &rid,
-	    flags | RF_ACTIVE);
+	resflags = RF_ACTIVE;
+	if ((flags & IRQF_SHARED) != 0)
+		resflags |= RF_SHAREABLE;
+	res = bus_alloc_resource_any(dev->bsddev, SYS_RES_IRQ, &rid, resflags);
 	if (res == NULL)
 		return (-ENXIO);
 	if (xdev != NULL)
 		irqe = lkpi_devres_alloc(lkpi_devm_irq_release, sizeof(*irqe),
 		    GFP_KERNEL | __GFP_ZERO);
 	else
 		irqe = kzalloc(sizeof(*irqe), GFP_KERNEL);
 	irqe->dev = dev;
 	irqe->res = res;
 	irqe->arg = arg;
 	irqe->handler = handler;
 	irqe->thread_handler = thread_handler;
 	irqe->irq = irq;
 
 	error = bus_setup_intr(dev->bsddev, res, INTR_TYPE_NET | INTR_MPSAFE,
 	    NULL, lkpi_irq_handler, irqe, &irqe->tag);
 	if (error)
 		goto errout;
 	list_add(&irqe->links, &dev->irqents);
 	if (xdev != NULL)
 		devres_add(xdev, irqe);
 
 	return 0;
 
 errout:
 	bus_release_resource(dev->bsddev, SYS_RES_IRQ, rid, irqe->res);
 	if (xdev != NULL)
 		devres_free(irqe);
 	else
 		kfree(irqe);
 	return (-error);
 }
 
 int
 lkpi_enable_irq(unsigned int irq)
 {
 	struct irq_ent *irqe;
 	struct device *dev;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return -EINVAL;
 	irqe = lkpi_irq_ent(dev, irq);
 	if (irqe == NULL || irqe->tag != NULL)
 		return -EINVAL;
 	return -bus_setup_intr(dev->bsddev, irqe->res, INTR_TYPE_NET | INTR_MPSAFE,
 	    NULL, lkpi_irq_handler, irqe, &irqe->tag);
 }
 
 void
 lkpi_disable_irq(unsigned int irq)
 {
 	struct irq_ent *irqe;
 	struct device *dev;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return;
 	irqe = lkpi_irq_ent(dev, irq);
 	if (irqe == NULL)
 		return;
 	if (irqe->tag != NULL)
 		bus_teardown_intr(dev->bsddev, irqe->res, irqe->tag);
 	irqe->tag = NULL;
 }
 
 int
 lkpi_bind_irq_to_cpu(unsigned int irq, int cpu_id)
 {
 	struct irq_ent *irqe;
 	struct device *dev;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return (-ENOENT);
 
 	irqe = lkpi_irq_ent(dev, irq);
 	if (irqe == NULL)
 		return (-ENOENT);
 
 	return (-bus_bind_intr(dev->bsddev, irqe->res, cpu_id));
 }
 
 void
 lkpi_free_irq(unsigned int irq, void *device __unused)
 {
 	struct irq_ent *irqe;
 	struct device *dev;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return;
 	irqe = lkpi_irq_ent(dev, irq);
 	if (irqe == NULL)
 		return;
 	lkpi_irq_release(dev, irqe);
 	kfree(irqe);
 }
 
 void
 lkpi_devm_free_irq(struct device *xdev, unsigned int irq, void *p __unused)
 {
 	struct device *dev;
 	struct irq_ent *irqe;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return;
 	if (xdev != dev)
 		return;
 	irqe = lkpi_irq_ent(dev, irq);
 	if (irqe == NULL)
 		return;
 	lkpi_irq_release(dev, irqe);
 	lkpi_devres_unlink(dev, irqe);
 	lkpi_devres_free(irqe);
 	return;
 }
diff --git a/sys/compat/linuxkpi/common/src/linux_pci.c b/sys/compat/linuxkpi/common/src/linux_pci.c
index 8386552dcd51..4e6cc92f3615 100644
--- a/sys/compat/linuxkpi/common/src/linux_pci.c
+++ b/sys/compat/linuxkpi/common/src/linux_pci.c
@@ -1,1630 +1,1949 @@
 /*-
  * Copyright (c) 2015-2016 Mellanox Technologies, Ltd.
  * All rights reserved.
  * Copyright (c) 2020-2022 The FreeBSD Foundation
  *
  * Portions of this software were developed by Björn Zeeb
  * under sponsorship from the FreeBSD Foundation.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
  * are met:
  * 1. Redistributions of source code must retain the above copyright
  *    notice unmodified, this list of conditions, and the following
  *    disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include <sys/cdefs.h>
 #include <sys/param.h>
 #include <sys/systm.h>
 #include <sys/bus.h>
 #include <sys/malloc.h>
 #include <sys/kernel.h>
 #include <sys/sysctl.h>
 #include <sys/lock.h>
 #include <sys/mutex.h>
 #include <sys/fcntl.h>
 #include <sys/file.h>
 #include <sys/filio.h>
 #include <sys/pciio.h>
 #include <sys/pctrie.h>
+#include <sys/rman.h>
 #include <sys/rwlock.h>
 
 #include <vm/vm.h>
 #include <vm/pmap.h>
 
+#include <machine/bus.h>
+#include <machine/resource.h>
 #include <machine/stdarg.h>
 
 #include <dev/pci/pcivar.h>
 #include <dev/pci/pci_private.h>
 #include <dev/pci/pci_iov.h>
 #include <dev/backlight/backlight.h>
 
 #include <linux/kernel.h>
 #include <linux/kobject.h>
 #include <linux/device.h>
 #include <linux/slab.h>
 #include <linux/module.h>
 #include <linux/cdev.h>
 #include <linux/file.h>
 #include <linux/sysfs.h>
 #include <linux/mm.h>
 #include <linux/io.h>
 #include <linux/vmalloc.h>
 #include <linux/pci.h>
 #include <linux/compat.h>
 
 #include <linux/backlight.h>
 
 #include "backlight_if.h"
 #include "pcib_if.h"
 
 /* Undef the linux function macro defined in linux/pci.h */
 #undef pci_get_class
 
 extern int linuxkpi_debug;
 
 SYSCTL_DECL(_compat_linuxkpi);
 
 static counter_u64_t lkpi_pci_nseg1_fail;
 SYSCTL_COUNTER_U64(_compat_linuxkpi, OID_AUTO, lkpi_pci_nseg1_fail, CTLFLAG_RD,
     &lkpi_pci_nseg1_fail, "Count of busdma mapping failures of single-segment");
 
 static device_probe_t linux_pci_probe;
 static device_attach_t linux_pci_attach;
 static device_detach_t linux_pci_detach;
 static device_suspend_t linux_pci_suspend;
 static device_resume_t linux_pci_resume;
 static device_shutdown_t linux_pci_shutdown;
 static pci_iov_init_t linux_pci_iov_init;
 static pci_iov_uninit_t linux_pci_iov_uninit;
 static pci_iov_add_vf_t linux_pci_iov_add_vf;
 static int linux_backlight_get_status(device_t dev, struct backlight_props *props);
 static int linux_backlight_update_status(device_t dev, struct backlight_props *props);
 static int linux_backlight_get_info(device_t dev, struct backlight_info *info);
+static void lkpi_pcim_iomap_table_release(struct device *, void *);
 
 static device_method_t pci_methods[] = {
 	DEVMETHOD(device_probe, linux_pci_probe),
 	DEVMETHOD(device_attach, linux_pci_attach),
 	DEVMETHOD(device_detach, linux_pci_detach),
 	DEVMETHOD(device_suspend, linux_pci_suspend),
 	DEVMETHOD(device_resume, linux_pci_resume),
 	DEVMETHOD(device_shutdown, linux_pci_shutdown),
 	DEVMETHOD(pci_iov_init, linux_pci_iov_init),
 	DEVMETHOD(pci_iov_uninit, linux_pci_iov_uninit),
 	DEVMETHOD(pci_iov_add_vf, linux_pci_iov_add_vf),
 
 	/* backlight interface */
 	DEVMETHOD(backlight_update_status, linux_backlight_update_status),
 	DEVMETHOD(backlight_get_status, linux_backlight_get_status),
 	DEVMETHOD(backlight_get_info, linux_backlight_get_info),
 	DEVMETHOD_END
 };
 
 const char *pci_power_names[] = {
 	"UNKNOWN", "D0", "D1", "D2", "D3hot", "D3cold"
 };
 
+/* We need some meta-struct to keep track of these for devres. */
+struct pci_devres {
+	bool		enable_io;
+	/* PCIR_MAX_BAR_0 + 1 = 6 => BIT(0..5). */
+	uint8_t		region_mask;
+	struct resource	*region_table[PCIR_MAX_BAR_0 + 1]; /* Not needed. */
+};
+struct pcim_iomap_devres {
+	void		*mmio_table[PCIR_MAX_BAR_0 + 1];
+	struct resource	*res_table[PCIR_MAX_BAR_0 + 1];
+};
+
 struct linux_dma_priv {
 	uint64_t	dma_mask;
 	bus_dma_tag_t	dmat;
 	uint64_t	dma_coherent_mask;
 	bus_dma_tag_t	dmat_coherent;
 	struct mtx	lock;
 	struct pctrie	ptree;
 };
 #define	DMA_PRIV_LOCK(priv) mtx_lock(&(priv)->lock)
 #define	DMA_PRIV_UNLOCK(priv) mtx_unlock(&(priv)->lock)
 
 static int
 linux_pdev_dma_uninit(struct pci_dev *pdev)
 {
 	struct linux_dma_priv *priv;
 
 	priv = pdev->dev.dma_priv;
 	if (priv->dmat)
 		bus_dma_tag_destroy(priv->dmat);
 	if (priv->dmat_coherent)
 		bus_dma_tag_destroy(priv->dmat_coherent);
 	mtx_destroy(&priv->lock);
 	pdev->dev.dma_priv = NULL;
 	free(priv, M_DEVBUF);
 	return (0);
 }
 
 static int
 linux_pdev_dma_init(struct pci_dev *pdev)
 {
 	struct linux_dma_priv *priv;
 	int error;
 
 	priv = malloc(sizeof(*priv), M_DEVBUF, M_WAITOK | M_ZERO);
 
 	mtx_init(&priv->lock, "lkpi-priv-dma", NULL, MTX_DEF);
 	pctrie_init(&priv->ptree);
 
 	pdev->dev.dma_priv = priv;
 
 	/* Create a default DMA tags. */
 	error = linux_dma_tag_init(&pdev->dev, DMA_BIT_MASK(64));
 	if (error != 0)
 		goto err;
 	/* Coherent is lower 32bit only by default in Linux. */
 	error = linux_dma_tag_init_coherent(&pdev->dev, DMA_BIT_MASK(32));
 	if (error != 0)
 		goto err;
 
 	return (error);
 
 err:
 	linux_pdev_dma_uninit(pdev);
 	return (error);
 }
 
 int
 linux_dma_tag_init(struct device *dev, u64 dma_mask)
 {
 	struct linux_dma_priv *priv;
 	int error;
 
 	priv = dev->dma_priv;
 
 	if (priv->dmat) {
 		if (priv->dma_mask == dma_mask)
 			return (0);
 
 		bus_dma_tag_destroy(priv->dmat);
 	}
 
 	priv->dma_mask = dma_mask;
 
 	error = bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
 	    1, 0,			/* alignment, boundary */
 	    dma_mask,			/* lowaddr */
 	    BUS_SPACE_MAXADDR,		/* highaddr */
 	    NULL, NULL,			/* filtfunc, filtfuncarg */
 	    BUS_SPACE_MAXSIZE,		/* maxsize */
 	    1,				/* nsegments */
 	    BUS_SPACE_MAXSIZE,		/* maxsegsz */
 	    0,				/* flags */
 	    NULL, NULL,			/* lockfunc, lockfuncarg */
 	    &priv->dmat);
 	return (-error);
 }
 
 int
 linux_dma_tag_init_coherent(struct device *dev, u64 dma_mask)
 {
 	struct linux_dma_priv *priv;
 	int error;
 
 	priv = dev->dma_priv;
 
 	if (priv->dmat_coherent) {
 		if (priv->dma_coherent_mask == dma_mask)
 			return (0);
 
 		bus_dma_tag_destroy(priv->dmat_coherent);
 	}
 
 	priv->dma_coherent_mask = dma_mask;
 
 	error = bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
 	    1, 0,			/* alignment, boundary */
 	    dma_mask,			/* lowaddr */
 	    BUS_SPACE_MAXADDR,		/* highaddr */
 	    NULL, NULL,			/* filtfunc, filtfuncarg */
 	    BUS_SPACE_MAXSIZE,		/* maxsize */
 	    1,				/* nsegments */
 	    BUS_SPACE_MAXSIZE,		/* maxsegsz */
 	    0,				/* flags */
 	    NULL, NULL,			/* lockfunc, lockfuncarg */
 	    &priv->dmat_coherent);
 	return (-error);
 }
 
 static struct pci_driver *
 linux_pci_find(device_t dev, const struct pci_device_id **idp)
 {
 	const struct pci_device_id *id;
 	struct pci_driver *pdrv;
 	uint16_t vendor;
 	uint16_t device;
 	uint16_t subvendor;
 	uint16_t subdevice;
 
 	vendor = pci_get_vendor(dev);
 	device = pci_get_device(dev);
 	subvendor = pci_get_subvendor(dev);
 	subdevice = pci_get_subdevice(dev);
 
 	spin_lock(&pci_lock);
 	list_for_each_entry(pdrv, &pci_drivers, node) {
 		for (id = pdrv->id_table; id->vendor != 0; id++) {
 			if (vendor == id->vendor &&
 			    (PCI_ANY_ID == id->device || device == id->device) &&
 			    (PCI_ANY_ID == id->subvendor || subvendor == id->subvendor) &&
 			    (PCI_ANY_ID == id->subdevice || subdevice == id->subdevice)) {
 				*idp = id;
 				spin_unlock(&pci_lock);
 				return (pdrv);
 			}
 		}
 	}
 	spin_unlock(&pci_lock);
 	return (NULL);
 }
 
 struct pci_dev *
 lkpi_pci_get_device(uint16_t vendor, uint16_t device, struct pci_dev *odev)
 {
 	struct pci_dev *pdev;
 
 	KASSERT(odev == NULL, ("%s: odev argument not yet supported\n", __func__));
 
 	spin_lock(&pci_lock);
 	list_for_each_entry(pdev, &pci_devices, links) {
 		if (pdev->vendor == vendor && pdev->device == device)
 			break;
 	}
 	spin_unlock(&pci_lock);
 
 	return (pdev);
 }
 
 static void
 lkpi_pci_dev_release(struct device *dev)
 {
 
 	lkpi_devres_release_free_list(dev);
 	spin_lock_destroy(&dev->devres_lock);
 }
 
 static void
 lkpifill_pci_dev(device_t dev, struct pci_dev *pdev)
 {
 
 	pdev->devfn = PCI_DEVFN(pci_get_slot(dev), pci_get_function(dev));
 	pdev->vendor = pci_get_vendor(dev);
 	pdev->device = pci_get_device(dev);
 	pdev->subsystem_vendor = pci_get_subvendor(dev);
 	pdev->subsystem_device = pci_get_subdevice(dev);
 	pdev->class = pci_get_class(dev);
 	pdev->revision = pci_get_revid(dev);
 	pdev->path_name = kasprintf(GFP_KERNEL, "%04d:%02d:%02d.%d",
 	    pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
 	    pci_get_function(dev));
 	pdev->bus = malloc(sizeof(*pdev->bus), M_DEVBUF, M_WAITOK | M_ZERO);
 	/*
 	 * This should be the upstream bridge; pci_upstream_bridge()
 	 * handles that case on demand as otherwise we'll shadow the
 	 * entire PCI hierarchy.
 	 */
 	pdev->bus->self = pdev;
 	pdev->bus->number = pci_get_bus(dev);
 	pdev->bus->domain = pci_get_domain(dev);
 	pdev->dev.bsddev = dev;
 	pdev->dev.parent = &linux_root_device;
 	pdev->dev.release = lkpi_pci_dev_release;
 	INIT_LIST_HEAD(&pdev->dev.irqents);
 
 	if (pci_msi_count(dev) > 0)
 		pdev->msi_desc = malloc(pci_msi_count(dev) *
 		    sizeof(*pdev->msi_desc), M_DEVBUF, M_WAITOK | M_ZERO);
 
 	kobject_init(&pdev->dev.kobj, &linux_dev_ktype);
 	kobject_set_name(&pdev->dev.kobj, device_get_nameunit(dev));
 	kobject_add(&pdev->dev.kobj, &linux_root_device.kobj,
 	    kobject_name(&pdev->dev.kobj));
 	spin_lock_init(&pdev->dev.devres_lock);
 	INIT_LIST_HEAD(&pdev->dev.devres_head);
 }
 
 static void
 lkpinew_pci_dev_release(struct device *dev)
 {
 	struct pci_dev *pdev;
 	int i;
 
 	pdev = to_pci_dev(dev);
 	if (pdev->root != NULL)
 		pci_dev_put(pdev->root);
 	if (pdev->bus->self != pdev)
 		pci_dev_put(pdev->bus->self);
 	free(pdev->bus, M_DEVBUF);
 	if (pdev->msi_desc != NULL) {
 		for (i = pci_msi_count(pdev->dev.bsddev) - 1; i >= 0; i--)
 			free(pdev->msi_desc[i], M_DEVBUF);
 		free(pdev->msi_desc, M_DEVBUF);
 	}
 	kfree(pdev->path_name);
 	free(pdev, M_DEVBUF);
 }
 
 struct pci_dev *
 lkpinew_pci_dev(device_t dev)
 {
 	struct pci_dev *pdev;
 
 	pdev = malloc(sizeof(*pdev), M_DEVBUF, M_WAITOK|M_ZERO);
 	lkpifill_pci_dev(dev, pdev);
 	pdev->dev.release = lkpinew_pci_dev_release;
 
 	return (pdev);
 }
 
 struct pci_dev *
 lkpi_pci_get_class(unsigned int class, struct pci_dev *from)
 {
 	device_t dev;
 	device_t devfrom = NULL;
 	struct pci_dev *pdev;
 
 	if (from != NULL)
 		devfrom = from->dev.bsddev;
 
 	dev = pci_find_class_from(class >> 16, (class >> 8) & 0xFF, devfrom);
 	if (dev == NULL)
 		return (NULL);
 
 	pdev = lkpinew_pci_dev(dev);
 	return (pdev);
 }
 
 struct pci_dev *
 lkpi_pci_get_domain_bus_and_slot(int domain, unsigned int bus,
     unsigned int devfn)
 {
 	device_t dev;
 	struct pci_dev *pdev;
 
 	dev = pci_find_dbsf(domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
 	if (dev == NULL)
 		return (NULL);
 
 	pdev = lkpinew_pci_dev(dev);
 	return (pdev);
 }
 
 static int
 linux_pci_probe(device_t dev)
 {
 	const struct pci_device_id *id;
 	struct pci_driver *pdrv;
 
 	if ((pdrv = linux_pci_find(dev, &id)) == NULL)
 		return (ENXIO);
 	if (device_get_driver(dev) != &pdrv->bsddriver)
 		return (ENXIO);
 	device_set_desc(dev, pdrv->name);
 
 	/* Assume BSS initialized (should never return BUS_PROBE_SPECIFIC). */
 	if (pdrv->bsd_probe_return == 0)
 		return (BUS_PROBE_DEFAULT);
 	else
 		return (pdrv->bsd_probe_return);
 }
 
 static int
 linux_pci_attach(device_t dev)
 {
 	const struct pci_device_id *id;
 	struct pci_driver *pdrv;
 	struct pci_dev *pdev;
 
 	pdrv = linux_pci_find(dev, &id);
 	pdev = device_get_softc(dev);
 
 	MPASS(pdrv != NULL);
 	MPASS(pdev != NULL);
 
 	return (linux_pci_attach_device(dev, pdrv, id, pdev));
 }
 
+static struct resource_list_entry *
+linux_pci_reserve_bar(struct pci_dev *pdev, struct resource_list *rl,
+    int type, int rid)
+{
+	device_t dev;
+	struct resource *res;
+
+	KASSERT(type == SYS_RES_IOPORT || type == SYS_RES_MEMORY,
+	    ("trying to reserve non-BAR type %d", type));
+
+	dev = pdev->pdrv != NULL && pdev->pdrv->isdrm ?
+	    device_get_parent(pdev->dev.bsddev) : pdev->dev.bsddev;
+	res = pci_reserve_map(device_get_parent(dev), dev, type, &rid, 0, ~0,
+	    1, 1, 0);
+	if (res == NULL)
+		return (NULL);
+	return (resource_list_find(rl, type, rid));
+}
+
+static struct resource_list_entry *
+linux_pci_get_rle(struct pci_dev *pdev, int type, int rid, bool reserve_bar)
+{
+	struct pci_devinfo *dinfo;
+	struct resource_list *rl;
+	struct resource_list_entry *rle;
+
+	dinfo = device_get_ivars(pdev->dev.bsddev);
+	rl = &dinfo->resources;
+	rle = resource_list_find(rl, type, rid);
+	/* Reserve resources for this BAR if needed. */
+	if (rle == NULL && reserve_bar)
+		rle = linux_pci_reserve_bar(pdev, rl, type, rid);
+	return (rle);
+}
+
 int
 linux_pci_attach_device(device_t dev, struct pci_driver *pdrv,
     const struct pci_device_id *id, struct pci_dev *pdev)
 {
 	struct resource_list_entry *rle;
 	device_t parent;
 	uintptr_t rid;
 	int error;
 	bool isdrm;
 
 	linux_set_current(curthread);
 
 	parent = device_get_parent(dev);
 	isdrm = pdrv != NULL && pdrv->isdrm;
 
 	if (isdrm) {
 		struct pci_devinfo *dinfo;
 
 		dinfo = device_get_ivars(parent);
 		device_set_ivars(dev, dinfo);
 	}
 
 	lkpifill_pci_dev(dev, pdev);
 	if (isdrm)
 		PCI_GET_ID(device_get_parent(parent), parent, PCI_ID_RID, &rid);
 	else
 		PCI_GET_ID(parent, dev, PCI_ID_RID, &rid);
 	pdev->devfn = rid;
 	pdev->pdrv = pdrv;
 	rle = linux_pci_get_rle(pdev, SYS_RES_IRQ, 0, false);
 	if (rle != NULL)
 		pdev->dev.irq = rle->start;
 	else
 		pdev->dev.irq = LINUX_IRQ_INVALID;
 	pdev->irq = pdev->dev.irq;
 	error = linux_pdev_dma_init(pdev);
 	if (error)
 		goto out_dma_init;
 
 	TAILQ_INIT(&pdev->mmio);
 
 	spin_lock(&pci_lock);
 	list_add(&pdev->links, &pci_devices);
 	spin_unlock(&pci_lock);
 
 	if (pdrv != NULL) {
 		error = pdrv->probe(pdev, id);
 		if (error)
 			goto out_probe;
 	}
 	return (0);
 
 out_probe:
 	free(pdev->bus, M_DEVBUF);
 	linux_pdev_dma_uninit(pdev);
 out_dma_init:
 	spin_lock(&pci_lock);
 	list_del(&pdev->links);
 	spin_unlock(&pci_lock);
 	put_device(&pdev->dev);
 	return (-error);
 }
 
 static int
 linux_pci_detach(device_t dev)
 {
 	struct pci_dev *pdev;
 
 	pdev = device_get_softc(dev);
 
 	MPASS(pdev != NULL);
 
 	device_set_desc(dev, NULL);
 
 	return (linux_pci_detach_device(pdev));
 }
 
 int
 linux_pci_detach_device(struct pci_dev *pdev)
 {
 
 	linux_set_current(curthread);
 
 	if (pdev->pdrv != NULL)
 		pdev->pdrv->remove(pdev);
 
 	if (pdev->root != NULL)
 		pci_dev_put(pdev->root);
 	free(pdev->bus, M_DEVBUF);
 	linux_pdev_dma_uninit(pdev);
 
 	spin_lock(&pci_lock);
 	list_del(&pdev->links);
 	spin_unlock(&pci_lock);
 	put_device(&pdev->dev);
 
 	return (0);
 }
 
 static int
 lkpi_pci_disable_dev(struct device *dev)
 {
 
 	(void) pci_disable_io(dev->bsddev, SYS_RES_MEMORY);
 	(void) pci_disable_io(dev->bsddev, SYS_RES_IOPORT);
 	return (0);
 }
 
-struct pci_devres *
+static struct pci_devres *
 lkpi_pci_devres_get_alloc(struct pci_dev *pdev)
 {
 	struct pci_devres *dr;
 
 	dr = lkpi_devres_find(&pdev->dev, lkpi_pci_devres_release, NULL, NULL);
 	if (dr == NULL) {
 		dr = lkpi_devres_alloc(lkpi_pci_devres_release, sizeof(*dr),
 		    GFP_KERNEL | __GFP_ZERO);
 		if (dr != NULL)
 			lkpi_devres_add(&pdev->dev, dr);
 	}
 
 	return (dr);
 }
 
+static struct pci_devres *
+lkpi_pci_devres_find(struct pci_dev *pdev)
+{
+	if (!pdev->managed)
+		return (NULL);
+
+	return (lkpi_pci_devres_get_alloc(pdev));
+}
+
 void
 lkpi_pci_devres_release(struct device *dev, void *p)
 {
 	struct pci_devres *dr;
 	struct pci_dev *pdev;
 	int bar;
 
 	pdev = to_pci_dev(dev);
 	dr = p;
 
 	if (pdev->msix_enabled)
 		lkpi_pci_disable_msix(pdev);
         if (pdev->msi_enabled)
 		lkpi_pci_disable_msi(pdev);
 
 	if (dr->enable_io && lkpi_pci_disable_dev(dev) == 0)
 		dr->enable_io = false;
 
 	if (dr->region_mask == 0)
 		return;
 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
 
 		if ((dr->region_mask & (1 << bar)) == 0)
 			continue;
 		pci_release_region(pdev, bar);
 	}
 }
 
-struct pcim_iomap_devres *
+int
+linuxkpi_pcim_enable_device(struct pci_dev *pdev)
+{
+	struct pci_devres *dr;
+	int error;
+
+	/* Here we cannot run through the pdev->managed check. */
+	dr = lkpi_pci_devres_get_alloc(pdev);
+	if (dr == NULL)
+		return (-ENOMEM);
+
+	/* If resources were enabled before do not do it again. */
+	if (dr->enable_io)
+		return (0);
+
+	error = pci_enable_device(pdev);
+	if (error == 0)
+		dr->enable_io = true;
+
+	/* This device is not managed. */
+	pdev->managed = true;
+
+	return (error);
+}
+
+static struct pcim_iomap_devres *
 lkpi_pcim_iomap_devres_find(struct pci_dev *pdev)
 {
 	struct pcim_iomap_devres *dr;
 
 	dr = lkpi_devres_find(&pdev->dev, lkpi_pcim_iomap_table_release,
 	    NULL, NULL);
 	if (dr == NULL) {
 		dr = lkpi_devres_alloc(lkpi_pcim_iomap_table_release,
 		    sizeof(*dr), GFP_KERNEL | __GFP_ZERO);
 		if (dr != NULL)
 			lkpi_devres_add(&pdev->dev, dr);
 	}
 
 	if (dr == NULL)
 		device_printf(pdev->dev.bsddev, "%s: NULL\n", __func__);
 
 	return (dr);
 }
 
+void __iomem **
+linuxkpi_pcim_iomap_table(struct pci_dev *pdev)
+{
+	struct pcim_iomap_devres *dr;
+
+	dr = lkpi_pcim_iomap_devres_find(pdev);
+	if (dr == NULL)
+		return (NULL);
+
+	/*
+	 * If the driver has manually set a flag to be able to request the
+	 * resource to use bus_read/write_<n>, return the shadow table.
+	 */
+	if (pdev->want_iomap_res)
+		return ((void **)dr->res_table);
+
+	/* This is the Linux default. */
+	return (dr->mmio_table);
+}
+
+static struct resource *
+_lkpi_pci_iomap(struct pci_dev *pdev, int bar, int mmio_size __unused)
+{
+	struct pci_mmio_region *mmio, *p;
+	int type;
+
+	type = pci_resource_type(pdev, bar);
+	if (type < 0) {
+		device_printf(pdev->dev.bsddev, "%s: bar %d type %d\n",
+		     __func__, bar, type);
+		return (NULL);
+	}
+
+	/*
+	 * Check for duplicate mappings.
+	 * This can happen if a driver calls pci_request_region() first.
+	 */
+	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
+		if (mmio->type == type && mmio->rid == PCIR_BAR(bar)) {
+			return (mmio->res);
+		}
+	}
+
+	mmio = malloc(sizeof(*mmio), M_DEVBUF, M_WAITOK | M_ZERO);
+	mmio->rid = PCIR_BAR(bar);
+	mmio->type = type;
+	mmio->res = bus_alloc_resource_any(pdev->dev.bsddev, mmio->type,
+	    &mmio->rid, RF_ACTIVE|RF_SHAREABLE);
+	if (mmio->res == NULL) {
+		device_printf(pdev->dev.bsddev, "%s: failed to alloc "
+		    "bar %d type %d rid %d\n",
+		    __func__, bar, type, PCIR_BAR(bar));
+		free(mmio, M_DEVBUF);
+		return (NULL);
+	}
+	TAILQ_INSERT_TAIL(&pdev->mmio, mmio, next);
+
+	return (mmio->res);
+}
+
+void *
+linuxkpi_pci_iomap(struct pci_dev *pdev, int mmio_bar, int mmio_size)
+{
+	struct resource *res;
+
+	res = _lkpi_pci_iomap(pdev, mmio_bar, mmio_size);
+	if (res == NULL)
+		return (NULL);
+	/* This is a FreeBSD extension so we can use bus_*(). */
+	if (pdev->want_iomap_res)
+		return (res);
+	return ((void *)rman_get_bushandle(res));
+}
+
 void
+linuxkpi_pci_iounmap(struct pci_dev *pdev, void *res)
+{
+	struct pci_mmio_region *mmio, *p;
+
+	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
+		if (res != (void *)rman_get_bushandle(mmio->res))
+			continue;
+		bus_release_resource(pdev->dev.bsddev,
+		    mmio->type, mmio->rid, mmio->res);
+		TAILQ_REMOVE(&pdev->mmio, mmio, next);
+		free(mmio, M_DEVBUF);
+		return;
+	}
+}
+
+int
+linuxkpi_pcim_iomap_regions(struct pci_dev *pdev, uint32_t mask, const char *name)
+{
+	struct pcim_iomap_devres *dr;
+	void *res;
+	uint32_t mappings;
+	int bar;
+
+	dr = lkpi_pcim_iomap_devres_find(pdev);
+	if (dr == NULL)
+		return (-ENOMEM);
+
+	/* Now iomap all the requested (by "mask") ones. */
+	for (bar = mappings = 0; mappings != mask; bar++) {
+		if ((mask & (1 << bar)) == 0)
+			continue;
+
+		/* Request double is not allowed. */
+		if (dr->mmio_table[bar] != NULL) {
+			device_printf(pdev->dev.bsddev, "%s: bar %d %p\n",
+			    __func__, bar, dr->mmio_table[bar]);
+			goto err;
+		}
+
+		res = _lkpi_pci_iomap(pdev, bar, 0);
+		if (res == NULL)
+			goto err;
+		dr->mmio_table[bar] = (void *)rman_get_bushandle(res);
+		dr->res_table[bar] = res;
+
+		mappings |= (1 << bar);
+	}
+
+	return (0);
+err:
+	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
+		if ((mappings & (1 << bar)) != 0) {
+			res = dr->mmio_table[bar];
+			if (res == NULL)
+				continue;
+			pci_iounmap(pdev, res);
+		}
+	}
+
+	return (-EINVAL);
+}
+
+static void
 lkpi_pcim_iomap_table_release(struct device *dev, void *p)
 {
 	struct pcim_iomap_devres *dr;
 	struct pci_dev *pdev;
 	int bar;
 
 	dr = p;
 	pdev = to_pci_dev(dev);
 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
 
 		if (dr->mmio_table[bar] == NULL)
 			continue;
 
 		pci_iounmap(pdev, dr->mmio_table[bar]);
 	}
 }
 
 static int
 linux_pci_suspend(device_t dev)
 {
 	const struct dev_pm_ops *pmops;
 	struct pm_message pm = { };
 	struct pci_dev *pdev;
 	int error;
 
 	error = 0;
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	pmops = pdev->pdrv->driver.pm;
 
 	if (pdev->pdrv->suspend != NULL)
 		error = -pdev->pdrv->suspend(pdev, pm);
 	else if (pmops != NULL && pmops->suspend != NULL) {
 		error = -pmops->suspend(&pdev->dev);
 		if (error == 0 && pmops->suspend_late != NULL)
 			error = -pmops->suspend_late(&pdev->dev);
 	}
 	return (error);
 }
 
 static int
 linux_pci_resume(device_t dev)
 {
 	const struct dev_pm_ops *pmops;
 	struct pci_dev *pdev;
 	int error;
 
 	error = 0;
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	pmops = pdev->pdrv->driver.pm;
 
 	if (pdev->pdrv->resume != NULL)
 		error = -pdev->pdrv->resume(pdev);
 	else if (pmops != NULL && pmops->resume != NULL) {
 		if (pmops->resume_early != NULL)
 			error = -pmops->resume_early(&pdev->dev);
 		if (error == 0 && pmops->resume != NULL)
 			error = -pmops->resume(&pdev->dev);
 	}
 	return (error);
 }
 
 static int
 linux_pci_shutdown(device_t dev)
 {
 	struct pci_dev *pdev;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	if (pdev->pdrv->shutdown != NULL)
 		pdev->pdrv->shutdown(pdev);
 	return (0);
 }
 
 static int
 linux_pci_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *pf_config)
 {
 	struct pci_dev *pdev;
 	int error;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	if (pdev->pdrv->bsd_iov_init != NULL)
 		error = pdev->pdrv->bsd_iov_init(dev, num_vfs, pf_config);
 	else
 		error = EINVAL;
 	return (error);
 }
 
 static void
 linux_pci_iov_uninit(device_t dev)
 {
 	struct pci_dev *pdev;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	if (pdev->pdrv->bsd_iov_uninit != NULL)
 		pdev->pdrv->bsd_iov_uninit(dev);
 }
 
 static int
 linux_pci_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *vf_config)
 {
 	struct pci_dev *pdev;
 	int error;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 	if (pdev->pdrv->bsd_iov_add_vf != NULL)
 		error = pdev->pdrv->bsd_iov_add_vf(dev, vfnum, vf_config);
 	else
 		error = EINVAL;
 	return (error);
 }
 
 static int
 _linux_pci_register_driver(struct pci_driver *pdrv, devclass_t dc)
 {
 	int error;
 
 	linux_set_current(curthread);
 	spin_lock(&pci_lock);
 	list_add(&pdrv->node, &pci_drivers);
 	spin_unlock(&pci_lock);
 	if (pdrv->bsddriver.name == NULL)
 		pdrv->bsddriver.name = pdrv->name;
 	pdrv->bsddriver.methods = pci_methods;
 	pdrv->bsddriver.size = sizeof(struct pci_dev);
 
 	bus_topo_lock();
 	error = devclass_add_driver(dc, &pdrv->bsddriver,
 	    BUS_PASS_DEFAULT, &pdrv->bsdclass);
 	bus_topo_unlock();
 	return (-error);
 }
 
 int
 linux_pci_register_driver(struct pci_driver *pdrv)
 {
 	devclass_t dc;
 
 	dc = devclass_find("pci");
 	if (dc == NULL)
 		return (-ENXIO);
 	pdrv->isdrm = false;
 	return (_linux_pci_register_driver(pdrv, dc));
 }
 
-struct resource_list_entry *
-linux_pci_reserve_bar(struct pci_dev *pdev, struct resource_list *rl,
-    int type, int rid)
+static struct resource_list_entry *
+lkpi_pci_get_bar(struct pci_dev *pdev, int bar, bool reserve)
 {
-	device_t dev;
-	struct resource *res;
-
-	KASSERT(type == SYS_RES_IOPORT || type == SYS_RES_MEMORY,
-	    ("trying to reserve non-BAR type %d", type));
+	int type;
 
-	dev = pdev->pdrv != NULL && pdev->pdrv->isdrm ?
-	    device_get_parent(pdev->dev.bsddev) : pdev->dev.bsddev;
-	res = pci_reserve_map(device_get_parent(dev), dev, type, &rid, 0, ~0,
-	    1, 1, 0);
-	if (res == NULL)
+	type = pci_resource_type(pdev, bar);
+	if (type < 0)
 		return (NULL);
-	return (resource_list_find(rl, type, rid));
+	bar = PCIR_BAR(bar);
+	return (linux_pci_get_rle(pdev, type, bar, reserve));
+}
+
+struct device *
+lkpi_pci_find_irq_dev(unsigned int irq)
+{
+	struct pci_dev *pdev;
+	struct device *found;
+
+	found = NULL;
+	spin_lock(&pci_lock);
+	list_for_each_entry(pdev, &pci_devices, links) {
+		if (irq == pdev->dev.irq ||
+		    (irq >= pdev->dev.irq_start && irq < pdev->dev.irq_end)) {
+			found = &pdev->dev;
+			break;
+		}
+	}
+	spin_unlock(&pci_lock);
+	return (found);
 }
 
 unsigned long
 pci_resource_start(struct pci_dev *pdev, int bar)
 {
 	struct resource_list_entry *rle;
 	rman_res_t newstart;
 	device_t dev;
 	int error;
 
-	if ((rle = linux_pci_get_bar(pdev, bar, true)) == NULL)
+	if ((rle = lkpi_pci_get_bar(pdev, bar, true)) == NULL)
 		return (0);
 	dev = pdev->pdrv != NULL && pdev->pdrv->isdrm ?
 	    device_get_parent(pdev->dev.bsddev) : pdev->dev.bsddev;
 	error = bus_translate_resource(dev, rle->type, rle->start, &newstart);
 	if (error != 0) {
 		device_printf(pdev->dev.bsddev,
 		    "translate of %#jx failed: %d\n",
 		    (uintmax_t)rle->start, error);
 		return (0);
 	}
 	return (newstart);
 }
 
 unsigned long
 pci_resource_len(struct pci_dev *pdev, int bar)
 {
 	struct resource_list_entry *rle;
 
-	if ((rle = linux_pci_get_bar(pdev, bar, true)) == NULL)
+	if ((rle = lkpi_pci_get_bar(pdev, bar, true)) == NULL)
 		return (0);
 	return (rle->count);
 }
 
 int
 pci_request_region(struct pci_dev *pdev, int bar, const char *res_name)
 {
 	struct resource *res;
 	struct pci_devres *dr;
 	struct pci_mmio_region *mmio;
 	int rid;
 	int type;
 
 	type = pci_resource_type(pdev, bar);
 	if (type < 0)
 		return (-ENODEV);
 	rid = PCIR_BAR(bar);
 	res = bus_alloc_resource_any(pdev->dev.bsddev, type, &rid,
 	    RF_ACTIVE|RF_SHAREABLE);
 	if (res == NULL) {
 		device_printf(pdev->dev.bsddev, "%s: failed to alloc "
 		    "bar %d type %d rid %d\n",
 		    __func__, bar, type, PCIR_BAR(bar));
 		return (-ENODEV);
 	}
 
 	/*
 	 * It seems there is an implicit devres tracking on these if the device
 	 * is managed; otherwise the resources are not automatiaclly freed on
 	 * FreeBSD/LinuxKPI tough they should be/are expected to be by Linux
 	 * drivers.
 	 */
 	dr = lkpi_pci_devres_find(pdev);
 	if (dr != NULL) {
 		dr->region_mask |= (1 << bar);
 		dr->region_table[bar] = res;
 	}
 
 	/* Even if the device is not managed we need to track it for iomap. */
 	mmio = malloc(sizeof(*mmio), M_DEVBUF, M_WAITOK | M_ZERO);
 	mmio->rid = PCIR_BAR(bar);
 	mmio->type = type;
 	mmio->res = res;
 	TAILQ_INSERT_TAIL(&pdev->mmio, mmio, next);
 
 	return (0);
 }
 
-struct resource *
-_lkpi_pci_iomap(struct pci_dev *pdev, int bar, int mmio_size __unused)
+int
+linuxkpi_pci_request_regions(struct pci_dev *pdev, const char *res_name)
 {
-	struct pci_mmio_region *mmio, *p;
-	int type;
+	int error;
+	int i;
 
-	type = pci_resource_type(pdev, bar);
-	if (type < 0) {
-		device_printf(pdev->dev.bsddev, "%s: bar %d type %d\n",
-		     __func__, bar, type);
-		return (NULL);
+	for (i = 0; i <= PCIR_MAX_BAR_0; i++) {
+		error = pci_request_region(pdev, i, res_name);
+		if (error && error != -ENODEV) {
+			pci_release_regions(pdev);
+			return (error);
+		}
 	}
+	return (0);
+}
+
+void
+linuxkpi_pci_release_region(struct pci_dev *pdev, int bar)
+{
+	struct resource_list_entry *rle;
+	struct pci_devres *dr;
+	struct pci_mmio_region *mmio, *p;
+
+	if ((rle = lkpi_pci_get_bar(pdev, bar, false)) == NULL)
+		return;
 
 	/*
-	 * Check for duplicate mappings.
-	 * This can happen if a driver calls pci_request_region() first.
+	 * As we implicitly track the requests we also need to clear them on
+	 * release.  Do clear before resource release.
 	 */
-	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
-		if (mmio->type == type && mmio->rid == PCIR_BAR(bar)) {
-			return (mmio->res);
-		}
+	dr = lkpi_pci_devres_find(pdev);
+	if (dr != NULL) {
+		KASSERT(dr->region_table[bar] == rle->res, ("%s: pdev %p bar %d"
+		    " region_table res %p != rel->res %p\n", __func__, pdev,
+		    bar, dr->region_table[bar], rle->res));
+		dr->region_table[bar] = NULL;
+		dr->region_mask &= ~(1 << bar);
 	}
 
-	mmio = malloc(sizeof(*mmio), M_DEVBUF, M_WAITOK | M_ZERO);
-	mmio->rid = PCIR_BAR(bar);
-	mmio->type = type;
-	mmio->res = bus_alloc_resource_any(pdev->dev.bsddev, mmio->type,
-	    &mmio->rid, RF_ACTIVE|RF_SHAREABLE);
-	if (mmio->res == NULL) {
-		device_printf(pdev->dev.bsddev, "%s: failed to alloc "
-		    "bar %d type %d rid %d\n",
-		    __func__, bar, type, PCIR_BAR(bar));
+	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
+		if (rle->res != (void *)rman_get_bushandle(mmio->res))
+			continue;
+		TAILQ_REMOVE(&pdev->mmio, mmio, next);
 		free(mmio, M_DEVBUF);
-		return (NULL);
 	}
-	TAILQ_INSERT_TAIL(&pdev->mmio, mmio, next);
 
-	return (mmio->res);
+	bus_release_resource(pdev->dev.bsddev, rle->type, rle->rid, rle->res);
+}
+
+void
+linuxkpi_pci_release_regions(struct pci_dev *pdev)
+{
+	int i;
+
+	for (i = 0; i <= PCIR_MAX_BAR_0; i++)
+		pci_release_region(pdev, i);
 }
 
 int
 linux_pci_register_drm_driver(struct pci_driver *pdrv)
 {
 	devclass_t dc;
 
 	dc = devclass_create("vgapci");
 	if (dc == NULL)
 		return (-ENXIO);
 	pdrv->isdrm = true;
 	pdrv->name = "drmn";
 	return (_linux_pci_register_driver(pdrv, dc));
 }
 
 void
 linux_pci_unregister_driver(struct pci_driver *pdrv)
 {
 	devclass_t bus;
 
 	bus = devclass_find("pci");
 
 	spin_lock(&pci_lock);
 	list_del(&pdrv->node);
 	spin_unlock(&pci_lock);
 	bus_topo_lock();
 	if (bus != NULL)
 		devclass_delete_driver(bus, &pdrv->bsddriver);
 	bus_topo_unlock();
 }
 
 void
 linux_pci_unregister_drm_driver(struct pci_driver *pdrv)
 {
 	devclass_t bus;
 
 	bus = devclass_find("vgapci");
 
 	spin_lock(&pci_lock);
 	list_del(&pdrv->node);
 	spin_unlock(&pci_lock);
 	bus_topo_lock();
 	if (bus != NULL)
 		devclass_delete_driver(bus, &pdrv->bsddriver);
 	bus_topo_unlock();
 }
 
+int
+linuxkpi_pci_enable_msix(struct pci_dev *pdev, struct msix_entry *entries,
+    int nreq)
+{
+	struct resource_list_entry *rle;
+	int error;
+	int avail;
+	int i;
+
+	avail = pci_msix_count(pdev->dev.bsddev);
+	if (avail < nreq) {
+		if (avail == 0)
+			return -EINVAL;
+		return avail;
+	}
+	avail = nreq;
+	if ((error = -pci_alloc_msix(pdev->dev.bsddev, &avail)) != 0)
+		return error;
+	/*
+	* Handle case where "pci_alloc_msix()" may allocate less
+	* interrupts than available and return with no error:
+	*/
+	if (avail < nreq) {
+		pci_release_msi(pdev->dev.bsddev);
+		return avail;
+	}
+	rle = linux_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
+	pdev->dev.irq_start = rle->start;
+	pdev->dev.irq_end = rle->start + avail;
+	for (i = 0; i < nreq; i++)
+		entries[i].vector = pdev->dev.irq_start + i;
+	pdev->msix_enabled = true;
+	return (0);
+}
+
+int
+_lkpi_pci_enable_msi_range(struct pci_dev *pdev, int minvec, int maxvec)
+{
+	struct resource_list_entry *rle;
+	int error;
+	int nvec;
+
+	if (maxvec < minvec)
+		return (-EINVAL);
+
+	nvec = pci_msi_count(pdev->dev.bsddev);
+	if (nvec < 1 || nvec < minvec)
+		return (-ENOSPC);
+
+	nvec = min(nvec, maxvec);
+	if ((error = -pci_alloc_msi(pdev->dev.bsddev, &nvec)) != 0)
+		return error;
+
+	/* Native PCI might only ever ask for 32 vectors. */
+	if (nvec < minvec) {
+		pci_release_msi(pdev->dev.bsddev);
+		return (-ENOSPC);
+	}
+
+	rle = linux_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
+	pdev->dev.irq_start = rle->start;
+	pdev->dev.irq_end = rle->start + nvec;
+	pdev->irq = rle->start;
+	pdev->msi_enabled = true;
+	return (0);
+}
+
 int
 pci_alloc_irq_vectors(struct pci_dev *pdev, int minv, int maxv,
     unsigned int flags)
 {
 	int error;
 
 	if (flags & PCI_IRQ_MSIX) {
 		struct msix_entry *entries;
 		int i;
 
 		entries = kcalloc(maxv, sizeof(*entries), GFP_KERNEL);
 		if (entries == NULL) {
 			error = -ENOMEM;
 			goto out;
 		}
 		for (i = 0; i < maxv; ++i)
 			entries[i].entry = i;
 		error = pci_enable_msix(pdev, entries, maxv);
 out:
 		kfree(entries);
 		if (error == 0 && pdev->msix_enabled)
 			return (pdev->dev.irq_end - pdev->dev.irq_start);
 	}
 	if (flags & PCI_IRQ_MSI) {
 		if (pci_msi_count(pdev->dev.bsddev) < minv)
 			return (-ENOSPC);
 		error = _lkpi_pci_enable_msi_range(pdev, minv, maxv);
 		if (error == 0 && pdev->msi_enabled)
 			return (pdev->dev.irq_end - pdev->dev.irq_start);
 	}
 	if (flags & PCI_IRQ_LEGACY) {
 		if (pdev->irq)
 			return (1);
 	}
 
 	return (-EINVAL);
 }
 
 struct msi_desc *
 lkpi_pci_msi_desc_alloc(int irq)
 {
 	struct device *dev;
 	struct pci_dev *pdev;
 	struct msi_desc *desc;
 	struct pci_devinfo *dinfo;
 	struct pcicfg_msi *msi;
 	int vec;
 
-	dev = linux_pci_find_irq_dev(irq);
+	dev = lkpi_pci_find_irq_dev(irq);
 	if (dev == NULL)
 		return (NULL);
 
 	pdev = to_pci_dev(dev);
 
 	if (pdev->msi_desc == NULL)
 		return (NULL);
 
 	if (irq < pdev->dev.irq_start || irq >= pdev->dev.irq_end)
 		return (NULL);
 
 	vec = pdev->dev.irq_start - irq;
 
 	if (pdev->msi_desc[vec] != NULL)
 		return (pdev->msi_desc[vec]);
 
 	dinfo = device_get_ivars(dev->bsddev);
 	msi = &dinfo->cfg.msi;
 
 	desc = malloc(sizeof(*desc), M_DEVBUF, M_WAITOK | M_ZERO);
 
 	desc->pci.msi_attrib.is_64 =
 	   (msi->msi_ctrl & PCIM_MSICTRL_64BIT) ? true : false;
 	desc->msg.data = msi->msi_data;
 
 	pdev->msi_desc[vec] = desc;
 
 	return (desc);
 }
 
 bool
 pci_device_is_present(struct pci_dev *pdev)
 {
 	device_t dev;
 
 	dev = pdev->dev.bsddev;
 
 	return (bus_child_present(dev));
 }
 
 CTASSERT(sizeof(dma_addr_t) <= sizeof(uint64_t));
 
 struct linux_dma_obj {
 	void		*vaddr;
 	uint64_t	dma_addr;
 	bus_dmamap_t	dmamap;
 	bus_dma_tag_t	dmat;
 };
 
 static uma_zone_t linux_dma_trie_zone;
 static uma_zone_t linux_dma_obj_zone;
 
 static void
 linux_dma_init(void *arg)
 {
 
 	linux_dma_trie_zone = uma_zcreate("linux_dma_pctrie",
 	    pctrie_node_size(), NULL, NULL, pctrie_zone_init, NULL,
 	    UMA_ALIGN_PTR, 0);
 	linux_dma_obj_zone = uma_zcreate("linux_dma_object",
 	    sizeof(struct linux_dma_obj), NULL, NULL, NULL, NULL,
 	    UMA_ALIGN_PTR, 0);
 	lkpi_pci_nseg1_fail = counter_u64_alloc(M_WAITOK);
 }
 SYSINIT(linux_dma, SI_SUB_DRIVERS, SI_ORDER_THIRD, linux_dma_init, NULL);
 
 static void
 linux_dma_uninit(void *arg)
 {
 
 	counter_u64_free(lkpi_pci_nseg1_fail);
 	uma_zdestroy(linux_dma_obj_zone);
 	uma_zdestroy(linux_dma_trie_zone);
 }
 SYSUNINIT(linux_dma, SI_SUB_DRIVERS, SI_ORDER_THIRD, linux_dma_uninit, NULL);
 
 static void *
 linux_dma_trie_alloc(struct pctrie *ptree)
 {
 
 	return (uma_zalloc(linux_dma_trie_zone, M_NOWAIT));
 }
 
 static void
 linux_dma_trie_free(struct pctrie *ptree, void *node)
 {
 
 	uma_zfree(linux_dma_trie_zone, node);
 }
 
 PCTRIE_DEFINE(LINUX_DMA, linux_dma_obj, dma_addr, linux_dma_trie_alloc,
     linux_dma_trie_free);
 
 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
 static dma_addr_t
 linux_dma_map_phys_common(struct device *dev, vm_paddr_t phys, size_t len,
     bus_dma_tag_t dmat)
 {
 	struct linux_dma_priv *priv;
 	struct linux_dma_obj *obj;
 	int error, nseg;
 	bus_dma_segment_t seg;
 
 	priv = dev->dma_priv;
 
 	/*
 	 * If the resultant mapping will be entirely 1:1 with the
 	 * physical address, short-circuit the remainder of the
 	 * bus_dma API.  This avoids tracking collisions in the pctrie
 	 * with the additional benefit of reducing overhead.
 	 */
 	if (bus_dma_id_mapped(dmat, phys, len))
 		return (phys);
 
 	obj = uma_zalloc(linux_dma_obj_zone, M_NOWAIT);
 	if (obj == NULL) {
 		return (0);
 	}
 	obj->dmat = dmat;
 
 	DMA_PRIV_LOCK(priv);
 	if (bus_dmamap_create(obj->dmat, 0, &obj->dmamap) != 0) {
 		DMA_PRIV_UNLOCK(priv);
 		uma_zfree(linux_dma_obj_zone, obj);
 		return (0);
 	}
 
 	nseg = -1;
 	if (_bus_dmamap_load_phys(obj->dmat, obj->dmamap, phys, len,
 	    BUS_DMA_NOWAIT, &seg, &nseg) != 0) {
 		bus_dmamap_destroy(obj->dmat, obj->dmamap);
 		DMA_PRIV_UNLOCK(priv);
 		uma_zfree(linux_dma_obj_zone, obj);
 		counter_u64_add(lkpi_pci_nseg1_fail, 1);
 		if (linuxkpi_debug)
 			dump_stack();
 		return (0);
 	}
 
 	KASSERT(++nseg == 1, ("More than one segment (nseg=%d)", nseg));
 	obj->dma_addr = seg.ds_addr;
 
 	error = LINUX_DMA_PCTRIE_INSERT(&priv->ptree, obj);
 	if (error != 0) {
 		bus_dmamap_unload(obj->dmat, obj->dmamap);
 		bus_dmamap_destroy(obj->dmat, obj->dmamap);
 		DMA_PRIV_UNLOCK(priv);
 		uma_zfree(linux_dma_obj_zone, obj);
 		return (0);
 	}
 	DMA_PRIV_UNLOCK(priv);
 	return (obj->dma_addr);
 }
 #else
 static dma_addr_t
 linux_dma_map_phys_common(struct device *dev __unused, vm_paddr_t phys,
     size_t len __unused, bus_dma_tag_t dmat __unused)
 {
 	return (phys);
 }
 #endif
 
 dma_addr_t
 linux_dma_map_phys(struct device *dev, vm_paddr_t phys, size_t len)
 {
 	struct linux_dma_priv *priv;
 
 	priv = dev->dma_priv;
 	return (linux_dma_map_phys_common(dev, phys, len, priv->dmat));
 }
 
 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
 void
 linux_dma_unmap(struct device *dev, dma_addr_t dma_addr, size_t len)
 {
 	struct linux_dma_priv *priv;
 	struct linux_dma_obj *obj;
 
 	priv = dev->dma_priv;
 
 	if (pctrie_is_empty(&priv->ptree))
 		return;
 
 	DMA_PRIV_LOCK(priv);
 	obj = LINUX_DMA_PCTRIE_LOOKUP(&priv->ptree, dma_addr);
 	if (obj == NULL) {
 		DMA_PRIV_UNLOCK(priv);
 		return;
 	}
 	LINUX_DMA_PCTRIE_REMOVE(&priv->ptree, dma_addr);
 	bus_dmamap_unload(obj->dmat, obj->dmamap);
 	bus_dmamap_destroy(obj->dmat, obj->dmamap);
 	DMA_PRIV_UNLOCK(priv);
 
 	uma_zfree(linux_dma_obj_zone, obj);
 }
 #else
 void
 linux_dma_unmap(struct device *dev, dma_addr_t dma_addr, size_t len)
 {
 }
 #endif
 
 void *
 linux_dma_alloc_coherent(struct device *dev, size_t size,
     dma_addr_t *dma_handle, gfp_t flag)
 {
 	struct linux_dma_priv *priv;
 	vm_paddr_t high;
 	size_t align;
 	void *mem;
 
 	if (dev == NULL || dev->dma_priv == NULL) {
 		*dma_handle = 0;
 		return (NULL);
 	}
 	priv = dev->dma_priv;
 	if (priv->dma_coherent_mask)
 		high = priv->dma_coherent_mask;
 	else
 		/* Coherent is lower 32bit only by default in Linux. */
 		high = BUS_SPACE_MAXADDR_32BIT;
 	align = PAGE_SIZE << get_order(size);
 	/* Always zero the allocation. */
 	flag |= M_ZERO;
 	mem = kmem_alloc_contig(size, flag & GFP_NATIVE_MASK, 0, high,
 	    align, 0, VM_MEMATTR_DEFAULT);
 	if (mem != NULL) {
 		*dma_handle = linux_dma_map_phys_common(dev, vtophys(mem), size,
 		    priv->dmat_coherent);
 		if (*dma_handle == 0) {
 			kmem_free(mem, size);
 			mem = NULL;
 		}
 	} else {
 		*dma_handle = 0;
 	}
 	return (mem);
 }
 
 struct lkpi_devres_dmam_coherent {
 	size_t size;
 	dma_addr_t *handle;
 	void *mem;
 };
 
 static void
 lkpi_dmam_free_coherent(struct device *dev, void *p)
 {
 	struct lkpi_devres_dmam_coherent *dr;
 
 	dr = p;
 	dma_free_coherent(dev, dr->size, dr->mem, *dr->handle);
 }
 
 void *
 linuxkpi_dmam_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle,
     gfp_t flag)
 {
 	struct lkpi_devres_dmam_coherent *dr;
 
 	dr = lkpi_devres_alloc(lkpi_dmam_free_coherent,
 	    sizeof(*dr), GFP_KERNEL | __GFP_ZERO);
 
 	if (dr == NULL)
 		return (NULL);
 
 	dr->size = size;
 	dr->mem = linux_dma_alloc_coherent(dev, size, dma_handle, flag);
 	dr->handle = dma_handle;
 	if (dr->mem == NULL) {
 		lkpi_devres_free(dr);
 		return (NULL);
 	}
 
 	lkpi_devres_add(dev, dr);
 	return (dr->mem);
 }
 
 void
 linuxkpi_dma_sync(struct device *dev, dma_addr_t dma_addr, size_t size,
     bus_dmasync_op_t op)
 {
 	struct linux_dma_priv *priv;
 	struct linux_dma_obj *obj;
 
 	priv = dev->dma_priv;
 
 	if (pctrie_is_empty(&priv->ptree))
 		return;
 
 	DMA_PRIV_LOCK(priv);
 	obj = LINUX_DMA_PCTRIE_LOOKUP(&priv->ptree, dma_addr);
 	if (obj == NULL) {
 		DMA_PRIV_UNLOCK(priv);
 		return;
 	}
 
 	bus_dmamap_sync(obj->dmat, obj->dmamap, op);
 	DMA_PRIV_UNLOCK(priv);
 }
 
 int
 linux_dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl, int nents,
     enum dma_data_direction direction, unsigned long attrs __unused)
 {
 	struct linux_dma_priv *priv;
 	struct scatterlist *sg;
 	int i, nseg;
 	bus_dma_segment_t seg;
 
 	priv = dev->dma_priv;
 
 	DMA_PRIV_LOCK(priv);
 
 	/* create common DMA map in the first S/G entry */
 	if (bus_dmamap_create(priv->dmat, 0, &sgl->dma_map) != 0) {
 		DMA_PRIV_UNLOCK(priv);
 		return (0);
 	}
 
 	/* load all S/G list entries */
 	for_each_sg(sgl, sg, nents, i) {
 		nseg = -1;
 		if (_bus_dmamap_load_phys(priv->dmat, sgl->dma_map,
 		    sg_phys(sg), sg->length, BUS_DMA_NOWAIT,
 		    &seg, &nseg) != 0) {
 			bus_dmamap_unload(priv->dmat, sgl->dma_map);
 			bus_dmamap_destroy(priv->dmat, sgl->dma_map);
 			DMA_PRIV_UNLOCK(priv);
 			return (0);
 		}
 		KASSERT(nseg == 0,
 		    ("More than one segment (nseg=%d)", nseg + 1));
 
 		sg_dma_address(sg) = seg.ds_addr;
 	}
 
 	switch (direction) {
 	case DMA_BIDIRECTIONAL:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREWRITE);
 		break;
 	case DMA_TO_DEVICE:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREREAD);
 		break;
 	case DMA_FROM_DEVICE:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREWRITE);
 		break;
 	default:
 		break;
 	}
 
 	DMA_PRIV_UNLOCK(priv);
 
 	return (nents);
 }
 
 void
 linux_dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
     int nents __unused, enum dma_data_direction direction,
     unsigned long attrs __unused)
 {
 	struct linux_dma_priv *priv;
 
 	priv = dev->dma_priv;
 
 	DMA_PRIV_LOCK(priv);
 
 	switch (direction) {
 	case DMA_BIDIRECTIONAL:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_POSTREAD);
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREREAD);
 		break;
 	case DMA_TO_DEVICE:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_POSTWRITE);
 		break;
 	case DMA_FROM_DEVICE:
 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_POSTREAD);
 		break;
 	default:
 		break;
 	}
 
 	bus_dmamap_unload(priv->dmat, sgl->dma_map);
 	bus_dmamap_destroy(priv->dmat, sgl->dma_map);
 	DMA_PRIV_UNLOCK(priv);
 }
 
 struct dma_pool {
 	struct device  *pool_device;
 	uma_zone_t	pool_zone;
 	struct mtx	pool_lock;
 	bus_dma_tag_t	pool_dmat;
 	size_t		pool_entry_size;
 	struct pctrie	pool_ptree;
 };
 
 #define	DMA_POOL_LOCK(pool) mtx_lock(&(pool)->pool_lock)
 #define	DMA_POOL_UNLOCK(pool) mtx_unlock(&(pool)->pool_lock)
 
 static inline int
 dma_pool_obj_ctor(void *mem, int size, void *arg, int flags)
 {
 	struct linux_dma_obj *obj = mem;
 	struct dma_pool *pool = arg;
 	int error, nseg;
 	bus_dma_segment_t seg;
 
 	nseg = -1;
 	DMA_POOL_LOCK(pool);
 	error = _bus_dmamap_load_phys(pool->pool_dmat, obj->dmamap,
 	    vtophys(obj->vaddr), pool->pool_entry_size, BUS_DMA_NOWAIT,
 	    &seg, &nseg);
 	DMA_POOL_UNLOCK(pool);
 	if (error != 0) {
 		return (error);
 	}
 	KASSERT(++nseg == 1, ("More than one segment (nseg=%d)", nseg));
 	obj->dma_addr = seg.ds_addr;
 
 	return (0);
 }
 
 static void
 dma_pool_obj_dtor(void *mem, int size, void *arg)
 {
 	struct linux_dma_obj *obj = mem;
 	struct dma_pool *pool = arg;
 
 	DMA_POOL_LOCK(pool);
 	bus_dmamap_unload(pool->pool_dmat, obj->dmamap);
 	DMA_POOL_UNLOCK(pool);
 }
 
 static int
 dma_pool_obj_import(void *arg, void **store, int count, int domain __unused,
     int flags)
 {
 	struct dma_pool *pool = arg;
 	struct linux_dma_obj *obj;
 	int error, i;
 
 	for (i = 0; i < count; i++) {
 		obj = uma_zalloc(linux_dma_obj_zone, flags);
 		if (obj == NULL)
 			break;
 
 		error = bus_dmamem_alloc(pool->pool_dmat, &obj->vaddr,
 		    BUS_DMA_NOWAIT, &obj->dmamap);
 		if (error!= 0) {
 			uma_zfree(linux_dma_obj_zone, obj);
 			break;
 		}
 
 		store[i] = obj;
 	}
 
 	return (i);
 }
 
 static void
 dma_pool_obj_release(void *arg, void **store, int count)
 {
 	struct dma_pool *pool = arg;
 	struct linux_dma_obj *obj;
 	int i;
 
 	for (i = 0; i < count; i++) {
 		obj = store[i];
 		bus_dmamem_free(pool->pool_dmat, obj->vaddr, obj->dmamap);
 		uma_zfree(linux_dma_obj_zone, obj);
 	}
 }
 
 struct dma_pool *
 linux_dma_pool_create(char *name, struct device *dev, size_t size,
     size_t align, size_t boundary)
 {
 	struct linux_dma_priv *priv;
 	struct dma_pool *pool;
 
 	priv = dev->dma_priv;
 
 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
 	pool->pool_device = dev;
 	pool->pool_entry_size = size;
 
 	if (bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
 	    align, boundary,		/* alignment, boundary */
 	    priv->dma_mask,		/* lowaddr */
 	    BUS_SPACE_MAXADDR,		/* highaddr */
 	    NULL, NULL,			/* filtfunc, filtfuncarg */
 	    size,			/* maxsize */
 	    1,				/* nsegments */
 	    size,			/* maxsegsz */
 	    0,				/* flags */
 	    NULL, NULL,			/* lockfunc, lockfuncarg */
 	    &pool->pool_dmat)) {
 		kfree(pool);
 		return (NULL);
 	}
 
 	pool->pool_zone = uma_zcache_create(name, -1, dma_pool_obj_ctor,
 	    dma_pool_obj_dtor, NULL, NULL, dma_pool_obj_import,
 	    dma_pool_obj_release, pool, 0);
 
 	mtx_init(&pool->pool_lock, "lkpi-dma-pool", NULL, MTX_DEF);
 	pctrie_init(&pool->pool_ptree);
 
 	return (pool);
 }
 
 void
 linux_dma_pool_destroy(struct dma_pool *pool)
 {
 
 	uma_zdestroy(pool->pool_zone);
 	bus_dma_tag_destroy(pool->pool_dmat);
 	mtx_destroy(&pool->pool_lock);
 	kfree(pool);
 }
 
 void
 lkpi_dmam_pool_destroy(struct device *dev, void *p)
 {
 	struct dma_pool *pool;
 
 	pool = *(struct dma_pool **)p;
 	LINUX_DMA_PCTRIE_RECLAIM(&pool->pool_ptree);
 	linux_dma_pool_destroy(pool);
 }
 
 void *
 linux_dma_pool_alloc(struct dma_pool *pool, gfp_t mem_flags,
     dma_addr_t *handle)
 {
 	struct linux_dma_obj *obj;
 
 	obj = uma_zalloc_arg(pool->pool_zone, pool, mem_flags & GFP_NATIVE_MASK);
 	if (obj == NULL)
 		return (NULL);
 
 	DMA_POOL_LOCK(pool);
 	if (LINUX_DMA_PCTRIE_INSERT(&pool->pool_ptree, obj) != 0) {
 		DMA_POOL_UNLOCK(pool);
 		uma_zfree_arg(pool->pool_zone, obj, pool);
 		return (NULL);
 	}
 	DMA_POOL_UNLOCK(pool);
 
 	*handle = obj->dma_addr;
 	return (obj->vaddr);
 }
 
 void
 linux_dma_pool_free(struct dma_pool *pool, void *vaddr, dma_addr_t dma_addr)
 {
 	struct linux_dma_obj *obj;
 
 	DMA_POOL_LOCK(pool);
 	obj = LINUX_DMA_PCTRIE_LOOKUP(&pool->pool_ptree, dma_addr);
 	if (obj == NULL) {
 		DMA_POOL_UNLOCK(pool);
 		return;
 	}
 	LINUX_DMA_PCTRIE_REMOVE(&pool->pool_ptree, dma_addr);
 	DMA_POOL_UNLOCK(pool);
 
 	uma_zfree_arg(pool->pool_zone, obj, pool);
 }
 
 static int
 linux_backlight_get_status(device_t dev, struct backlight_props *props)
 {
 	struct pci_dev *pdev;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 
 	props->brightness = pdev->dev.bd->props.brightness;
 	props->brightness = props->brightness * 100 / pdev->dev.bd->props.max_brightness;
 	props->nlevels = 0;
 
 	return (0);
 }
 
 static int
 linux_backlight_get_info(device_t dev, struct backlight_info *info)
 {
 	struct pci_dev *pdev;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 
 	info->type = BACKLIGHT_TYPE_PANEL;
 	strlcpy(info->name, pdev->dev.bd->name, BACKLIGHTMAXNAMELENGTH);
 	return (0);
 }
 
 static int
 linux_backlight_update_status(device_t dev, struct backlight_props *props)
 {
 	struct pci_dev *pdev;
 
 	linux_set_current(curthread);
 	pdev = device_get_softc(dev);
 
 	pdev->dev.bd->props.brightness = pdev->dev.bd->props.max_brightness *
 		props->brightness / 100;
 	pdev->dev.bd->props.power = props->brightness == 0 ?
 		4/* FB_BLANK_POWERDOWN */ : 0/* FB_BLANK_UNBLANK */;
 	return (pdev->dev.bd->ops->update_status(pdev->dev.bd));
 }
 
 struct backlight_device *
 linux_backlight_device_register(const char *name, struct device *dev,
     void *data, const struct backlight_ops *ops, struct backlight_properties *props)
 {
 
 	dev->bd = malloc(sizeof(*dev->bd), M_DEVBUF, M_WAITOK | M_ZERO);
 	dev->bd->ops = ops;
 	dev->bd->props.type = props->type;
 	dev->bd->props.max_brightness = props->max_brightness;
 	dev->bd->props.brightness = props->brightness;
 	dev->bd->props.power = props->power;
 	dev->bd->data = data;
 	dev->bd->dev = dev;
 	dev->bd->name = strdup(name, M_DEVBUF);
 
 	dev->backlight_dev = backlight_register(name, dev->bsddev);
 
 	return (dev->bd);
 }
 
 void
 linux_backlight_device_unregister(struct backlight_device *bd)
 {
 
 	backlight_destroy(bd->dev->backlight_dev);
 	free(bd->name, M_DEVBUF);
 	free(bd, M_DEVBUF);
 }
diff --git a/sys/contrib/dev/iwlwifi/pcie/trans.c b/sys/contrib/dev/iwlwifi/pcie/trans.c
index 15d7c37c0482..fe7ee266110a 100644
--- a/sys/contrib/dev/iwlwifi/pcie/trans.c
+++ b/sys/contrib/dev/iwlwifi/pcie/trans.c
@@ -1,3822 +1,3823 @@
 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
 /*
  * Copyright (C) 2007-2015, 2018-2023 Intel Corporation
  * Copyright (C) 2013-2015 Intel Mobile Communications GmbH
  * Copyright (C) 2016-2017 Intel Deutschland GmbH
  */
 #include <linux/pci.h>
 #include <linux/interrupt.h>
 #include <linux/debugfs.h>
 #include <linux/sched.h>
 #include <linux/bitops.h>
 #include <linux/gfp.h>
 #include <linux/vmalloc.h>
 #include <linux/module.h>
 #include <linux/wait.h>
 #include <linux/seq_file.h>
 #if defined(__FreeBSD__)
+#include <sys/rman.h>
 #include <linux/delay.h>
 #endif
 
 #include "iwl-drv.h"
 #include "iwl-trans.h"
 #include "iwl-csr.h"
 #include "iwl-prph.h"
 #include "iwl-scd.h"
 #include "iwl-agn-hw.h"
 #include "fw/error-dump.h"
 #include "fw/dbg.h"
 #include "fw/api/tx.h"
 #include "mei/iwl-mei.h"
 #include "internal.h"
 #include "iwl-fh.h"
 #include "iwl-context-info-gen3.h"
 
 /* extended range in FW SRAM */
 #define IWL_FW_MEM_EXTENDED_START	0x40000
 #define IWL_FW_MEM_EXTENDED_END		0x57FFF
 
 void iwl_trans_pcie_dump_regs(struct iwl_trans *trans)
 {
 #define PCI_DUMP_SIZE		352
 #define PCI_MEM_DUMP_SIZE	64
 #define PCI_PARENT_DUMP_SIZE	524
 #define PREFIX_LEN		32
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	struct pci_dev *pdev = trans_pcie->pci_dev;
 	u32 i, pos, alloc_size, *ptr, *buf;
 	char *prefix;
 
 	if (trans_pcie->pcie_dbg_dumped_once)
 		return;
 
 	/* Should be a multiple of 4 */
 	BUILD_BUG_ON(PCI_DUMP_SIZE > 4096 || PCI_DUMP_SIZE & 0x3);
 	BUILD_BUG_ON(PCI_MEM_DUMP_SIZE > 4096 || PCI_MEM_DUMP_SIZE & 0x3);
 	BUILD_BUG_ON(PCI_PARENT_DUMP_SIZE > 4096 || PCI_PARENT_DUMP_SIZE & 0x3);
 
 	/* Alloc a max size buffer */
 	alloc_size = PCI_ERR_ROOT_ERR_SRC +  4 + PREFIX_LEN;
 	alloc_size = max_t(u32, alloc_size, PCI_DUMP_SIZE + PREFIX_LEN);
 	alloc_size = max_t(u32, alloc_size, PCI_MEM_DUMP_SIZE + PREFIX_LEN);
 	alloc_size = max_t(u32, alloc_size, PCI_PARENT_DUMP_SIZE + PREFIX_LEN);
 
 	buf = kmalloc(alloc_size, GFP_ATOMIC);
 	if (!buf)
 		return;
 	prefix = (char *)buf + alloc_size - PREFIX_LEN;
 
 	IWL_ERR(trans, "iwlwifi transaction failed, dumping registers\n");
 
 	/* Print wifi device registers */
 	sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
 	IWL_ERR(trans, "iwlwifi device config registers:\n");
 	for (i = 0, ptr = buf; i < PCI_DUMP_SIZE; i += 4, ptr++)
 		if (pci_read_config_dword(pdev, i, ptr))
 			goto err_read;
 #if defined(__linux__)
 	print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET, 32, 4, buf, i, 0);
 #elif defined(__FreeBSD__)
 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 
 	IWL_ERR(trans, "iwlwifi device memory mapped registers:\n");
 	for (i = 0, ptr = buf; i < PCI_MEM_DUMP_SIZE; i += 4, ptr++)
 		*ptr = iwl_read32(trans, i);
 #if defined(__linux__)
 	print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET, 32, 4, buf, i, 0);
 #elif defined(__FreeBSD__)
 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 
 	pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR);
 	if (pos) {
 		IWL_ERR(trans, "iwlwifi device AER capability structure:\n");
 		for (i = 0, ptr = buf; i < PCI_ERR_ROOT_COMMAND; i += 4, ptr++)
 			if (pci_read_config_dword(pdev, pos + i, ptr))
 				goto err_read;
 #if defined(__linux__)
 		print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET,
 			       32, 4, buf, i, 0);
 #elif defined(__FreeBSD__)
 		iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 	}
 
 	/* Print parent device registers next */
 	if (!pdev->bus->self)
 		goto out;
 
 	pdev = pdev->bus->self;
 	sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
 
 	IWL_ERR(trans, "iwlwifi parent port (%s) config registers:\n",
 		pci_name(pdev));
 	for (i = 0, ptr = buf; i < PCI_PARENT_DUMP_SIZE; i += 4, ptr++)
 		if (pci_read_config_dword(pdev, i, ptr))
 			goto err_read;
 #if defined(__linux__)
 	print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET, 32, 4, buf, i, 0);
 #elif defined(__FreeBSD__)
 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 
 	/* Print root port AER registers */
 	pos = 0;
 	pdev = pcie_find_root_port(pdev);
 	if (pdev)
 		pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_ERR);
 	if (pos) {
 		IWL_ERR(trans, "iwlwifi root port (%s) AER cap structure:\n",
 			pci_name(pdev));
 		sprintf(prefix, "iwlwifi %s: ", pci_name(pdev));
 		for (i = 0, ptr = buf; i <= PCI_ERR_ROOT_ERR_SRC; i += 4, ptr++)
 			if (pci_read_config_dword(pdev, pos + i, ptr))
 				goto err_read;
 #if defined(__linux__)
 		print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET, 32,
 			       4, buf, i, 0);
 #elif defined(__FreeBSD__)
 		iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 	}
 	goto out;
 
 err_read:
 #if defined(__linux__)
 	print_hex_dump(KERN_ERR, prefix, DUMP_PREFIX_OFFSET, 32, 4, buf, i, 0);
 #elif defined(__FreeBSD__)
 	iwl_print_hex_dump(NULL, IWL_DL_ANY, prefix, (u8 *)buf, i);
 #endif
 	IWL_ERR(trans, "Read failed at 0x%X\n", i);
 out:
 	trans_pcie->pcie_dbg_dumped_once = 1;
 	kfree(buf);
 }
 
 static int iwl_trans_pcie_sw_reset(struct iwl_trans *trans,
 				   bool retake_ownership)
 {
 	/* Reset entire device - do controller reset (results in SHRD_HW_RST) */
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ) {
 		iwl_set_bit(trans, CSR_GP_CNTRL,
 			    CSR_GP_CNTRL_REG_FLAG_SW_RESET);
 		usleep_range(10000, 20000);
 	} else {
 		iwl_set_bit(trans, CSR_RESET,
 			    CSR_RESET_REG_FLAG_SW_RESET);
 		usleep_range(5000, 6000);
 	}
 
 	if (retake_ownership)
 		return iwl_pcie_prepare_card_hw(trans);
 
 	return 0;
 }
 
 static void iwl_pcie_free_fw_monitor(struct iwl_trans *trans)
 {
 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
 
 	if (!fw_mon->size)
 		return;
 
 	dma_free_coherent(trans->dev, fw_mon->size, fw_mon->block,
 			  fw_mon->physical);
 
 	fw_mon->block = NULL;
 	fw_mon->physical = 0;
 	fw_mon->size = 0;
 }
 
 static void iwl_pcie_alloc_fw_monitor_block(struct iwl_trans *trans,
 					    u8 max_power)
 {
 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
 	void *block = NULL;
 	dma_addr_t physical = 0;
 	u32 size = 0;
 	u8 power;
 
 	if (fw_mon->size) {
 		memset(fw_mon->block, 0, fw_mon->size);
 		return;
 	}
 
 	/* need at least 2 KiB, so stop at 11 */
 	for (power = max_power; power >= 11; power--) {
 		size = BIT(power);
 		block = dma_alloc_coherent(trans->dev, size, &physical,
 					   GFP_KERNEL | __GFP_NOWARN);
 		if (!block)
 			continue;
 
 		IWL_INFO(trans,
 			 "Allocated 0x%08x bytes for firmware monitor.\n",
 			 size);
 		break;
 	}
 
 	if (WARN_ON_ONCE(!block))
 		return;
 
 	if (power != max_power)
 		IWL_ERR(trans,
 			"Sorry - debug buffer is only %luK while you requested %luK\n",
 			(unsigned long)BIT(power - 10),
 			(unsigned long)BIT(max_power - 10));
 
 	fw_mon->block = block;
 	fw_mon->physical = physical;
 	fw_mon->size = size;
 }
 
 void iwl_pcie_alloc_fw_monitor(struct iwl_trans *trans, u8 max_power)
 {
 	if (!max_power) {
 		/* default max_power is maximum */
 		max_power = 26;
 	} else {
 		max_power += 11;
 	}
 
 	if (WARN(max_power > 26,
 		 "External buffer size for monitor is too big %d, check the FW TLV\n",
 		 max_power))
 		return;
 
 	iwl_pcie_alloc_fw_monitor_block(trans, max_power);
 }
 
 static u32 iwl_trans_pcie_read_shr(struct iwl_trans *trans, u32 reg)
 {
 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_CTRL_REG,
 		    ((reg & 0x0000ffff) | (2 << 28)));
 	return iwl_read32(trans, HEEP_CTRL_WRD_PCIEX_DATA_REG);
 }
 
 static void iwl_trans_pcie_write_shr(struct iwl_trans *trans, u32 reg, u32 val)
 {
 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_DATA_REG, val);
 	iwl_write32(trans, HEEP_CTRL_WRD_PCIEX_CTRL_REG,
 		    ((reg & 0x0000ffff) | (3 << 28)));
 }
 
 static void iwl_pcie_set_pwr(struct iwl_trans *trans, bool vaux)
 {
 	if (trans->cfg->apmg_not_supported)
 		return;
 
 	if (vaux && pci_pme_capable(to_pci_dev(trans->dev), PCI_D3cold))
 		iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG,
 				       APMG_PS_CTRL_VAL_PWR_SRC_VAUX,
 				       ~APMG_PS_CTRL_MSK_PWR_SRC);
 	else
 		iwl_set_bits_mask_prph(trans, APMG_PS_CTRL_REG,
 				       APMG_PS_CTRL_VAL_PWR_SRC_VMAIN,
 				       ~APMG_PS_CTRL_MSK_PWR_SRC);
 }
 
 /* PCI registers */
 #define PCI_CFG_RETRY_TIMEOUT	0x041
 
 void iwl_pcie_apm_config(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	u16 lctl;
 	u16 cap;
 
 	/*
 	 * L0S states have been found to be unstable with our devices
 	 * and in newer hardware they are not officially supported at
 	 * all, so we must always set the L0S_DISABLED bit.
 	 */
 	iwl_set_bit(trans, CSR_GIO_REG, CSR_GIO_REG_VAL_L0S_DISABLED);
 
 	pcie_capability_read_word(trans_pcie->pci_dev, PCI_EXP_LNKCTL, &lctl);
 	trans->pm_support = !(lctl & PCI_EXP_LNKCTL_ASPM_L0S);
 
 	pcie_capability_read_word(trans_pcie->pci_dev, PCI_EXP_DEVCTL2, &cap);
 	trans->ltr_enabled = cap & PCI_EXP_DEVCTL2_LTR_EN;
 	IWL_DEBUG_POWER(trans, "L1 %sabled - LTR %sabled\n",
 			(lctl & PCI_EXP_LNKCTL_ASPM_L1) ? "En" : "Dis",
 			trans->ltr_enabled ? "En" : "Dis");
 }
 
 /*
  * Start up NIC's basic functionality after it has been reset
  * (e.g. after platform boot, or shutdown via iwl_pcie_apm_stop())
  * NOTE:  This does not load uCode nor start the embedded processor
  */
 static int iwl_pcie_apm_init(struct iwl_trans *trans)
 {
 	int ret;
 
 	IWL_DEBUG_INFO(trans, "Init card's basic functions\n");
 
 	/*
 	 * Use "set_bit" below rather than "write", to preserve any hardware
 	 * bits already set by default after reset.
 	 */
 
 	/* Disable L0S exit timer (platform NMI Work/Around) */
 	if (trans->trans_cfg->device_family < IWL_DEVICE_FAMILY_8000)
 		iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS,
 			    CSR_GIO_CHICKEN_BITS_REG_BIT_DIS_L0S_EXIT_TIMER);
 
 	/*
 	 * Disable L0s without affecting L1;
 	 *  don't wait for ICH L0s (ICH bug W/A)
 	 */
 	iwl_set_bit(trans, CSR_GIO_CHICKEN_BITS,
 		    CSR_GIO_CHICKEN_BITS_REG_BIT_L1A_NO_L0S_RX);
 
 	/* Set FH wait threshold to maximum (HW error during stress W/A) */
 	iwl_set_bit(trans, CSR_DBG_HPET_MEM_REG, CSR_DBG_HPET_MEM_REG_VAL);
 
 	/*
 	 * Enable HAP INTA (interrupt from management bus) to
 	 * wake device's PCI Express link L1a -> L0s
 	 */
 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 		    CSR_HW_IF_CONFIG_REG_BIT_HAP_WAKE_L1A);
 
 	iwl_pcie_apm_config(trans);
 
 	/* Configure analog phase-lock-loop before activating to D0A */
 	if (trans->trans_cfg->base_params->pll_cfg)
 		iwl_set_bit(trans, CSR_ANA_PLL_CFG, CSR50_ANA_PLL_CFG_VAL);
 
 	ret = iwl_finish_nic_init(trans);
 	if (ret)
 		return ret;
 
 	if (trans->cfg->host_interrupt_operation_mode) {
 		/*
 		 * This is a bit of an abuse - This is needed for 7260 / 3160
 		 * only check host_interrupt_operation_mode even if this is
 		 * not related to host_interrupt_operation_mode.
 		 *
 		 * Enable the oscillator to count wake up time for L1 exit. This
 		 * consumes slightly more power (100uA) - but allows to be sure
 		 * that we wake up from L1 on time.
 		 *
 		 * This looks weird: read twice the same register, discard the
 		 * value, set a bit, and yet again, read that same register
 		 * just to discard the value. But that's the way the hardware
 		 * seems to like it.
 		 */
 		iwl_read_prph(trans, OSC_CLK);
 		iwl_read_prph(trans, OSC_CLK);
 		iwl_set_bits_prph(trans, OSC_CLK, OSC_CLK_FORCE_CONTROL);
 		iwl_read_prph(trans, OSC_CLK);
 		iwl_read_prph(trans, OSC_CLK);
 	}
 
 	/*
 	 * Enable DMA clock and wait for it to stabilize.
 	 *
 	 * Write to "CLK_EN_REG"; "1" bits enable clocks, while "0"
 	 * bits do not disable clocks.  This preserves any hardware
 	 * bits already set by default in "CLK_CTRL_REG" after reset.
 	 */
 	if (!trans->cfg->apmg_not_supported) {
 		iwl_write_prph(trans, APMG_CLK_EN_REG,
 			       APMG_CLK_VAL_DMA_CLK_RQT);
 		udelay(20);
 
 		/* Disable L1-Active */
 		iwl_set_bits_prph(trans, APMG_PCIDEV_STT_REG,
 				  APMG_PCIDEV_STT_VAL_L1_ACT_DIS);
 
 		/* Clear the interrupt in APMG if the NIC is in RFKILL */
 		iwl_write_prph(trans, APMG_RTC_INT_STT_REG,
 			       APMG_RTC_INT_STT_RFKILL);
 	}
 
 	set_bit(STATUS_DEVICE_ENABLED, &trans->status);
 
 	return 0;
 }
 
 /*
  * Enable LP XTAL to avoid HW bug where device may consume much power if
  * FW is not loaded after device reset. LP XTAL is disabled by default
  * after device HW reset. Do it only if XTAL is fed by internal source.
  * Configure device's "persistence" mode to avoid resetting XTAL again when
  * SHRD_HW_RST occurs in S3.
  */
 static void iwl_pcie_apm_lp_xtal_enable(struct iwl_trans *trans)
 {
 	int ret;
 	u32 apmg_gp1_reg;
 	u32 apmg_xtal_cfg_reg;
 	u32 dl_cfg_reg;
 
 	/* Force XTAL ON */
 	__iwl_trans_pcie_set_bit(trans, CSR_GP_CNTRL,
 				 CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
 
 	ret = iwl_trans_pcie_sw_reset(trans, true);
 
 	if (!ret)
 		ret = iwl_finish_nic_init(trans);
 
 	if (WARN_ON(ret)) {
 		/* Release XTAL ON request */
 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
 					   CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
 		return;
 	}
 
 	/*
 	 * Clear "disable persistence" to avoid LP XTAL resetting when
 	 * SHRD_HW_RST is applied in S3.
 	 */
 	iwl_clear_bits_prph(trans, APMG_PCIDEV_STT_REG,
 				    APMG_PCIDEV_STT_VAL_PERSIST_DIS);
 
 	/*
 	 * Force APMG XTAL to be active to prevent its disabling by HW
 	 * caused by APMG idle state.
 	 */
 	apmg_xtal_cfg_reg = iwl_trans_pcie_read_shr(trans,
 						    SHR_APMG_XTAL_CFG_REG);
 	iwl_trans_pcie_write_shr(trans, SHR_APMG_XTAL_CFG_REG,
 				 apmg_xtal_cfg_reg |
 				 SHR_APMG_XTAL_CFG_XTAL_ON_REQ);
 
 	ret = iwl_trans_pcie_sw_reset(trans, true);
 	if (ret)
 		IWL_ERR(trans,
 			"iwl_pcie_apm_lp_xtal_enable: failed to retake NIC ownership\n");
 
 	/* Enable LP XTAL by indirect access through CSR */
 	apmg_gp1_reg = iwl_trans_pcie_read_shr(trans, SHR_APMG_GP1_REG);
 	iwl_trans_pcie_write_shr(trans, SHR_APMG_GP1_REG, apmg_gp1_reg |
 				 SHR_APMG_GP1_WF_XTAL_LP_EN |
 				 SHR_APMG_GP1_CHICKEN_BIT_SELECT);
 
 	/* Clear delay line clock power up */
 	dl_cfg_reg = iwl_trans_pcie_read_shr(trans, SHR_APMG_DL_CFG_REG);
 	iwl_trans_pcie_write_shr(trans, SHR_APMG_DL_CFG_REG, dl_cfg_reg &
 				 ~SHR_APMG_DL_CFG_DL_CLOCK_POWER_UP);
 
 	/*
 	 * Enable persistence mode to avoid LP XTAL resetting when
 	 * SHRD_HW_RST is applied in S3.
 	 */
 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 		    CSR_HW_IF_CONFIG_REG_PERSIST_MODE);
 
 	/*
 	 * Clear "initialization complete" bit to move adapter from
 	 * D0A* (powered-up Active) --> D0U* (Uninitialized) state.
 	 */
 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
 
 	/* Activates XTAL resources monitor */
 	__iwl_trans_pcie_set_bit(trans, CSR_MONITOR_CFG_REG,
 				 CSR_MONITOR_XTAL_RESOURCES);
 
 	/* Release XTAL ON request */
 	__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
 				   CSR_GP_CNTRL_REG_FLAG_XTAL_ON);
 	udelay(10);
 
 	/* Release APMG XTAL */
 	iwl_trans_pcie_write_shr(trans, SHR_APMG_XTAL_CFG_REG,
 				 apmg_xtal_cfg_reg &
 				 ~SHR_APMG_XTAL_CFG_XTAL_ON_REQ);
 }
 
 void iwl_pcie_apm_stop_master(struct iwl_trans *trans)
 {
 	int ret;
 
 	/* stop device's busmaster DMA activity */
 
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ) {
 		iwl_set_bit(trans, CSR_GP_CNTRL,
 			    CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_REQ);
 
 		ret = iwl_poll_bit(trans, CSR_GP_CNTRL,
 				   CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_STATUS,
 				   CSR_GP_CNTRL_REG_FLAG_BUS_MASTER_DISABLE_STATUS,
 				   100);
 		usleep_range(10000, 20000);
 	} else {
 		iwl_set_bit(trans, CSR_RESET, CSR_RESET_REG_FLAG_STOP_MASTER);
 
 		ret = iwl_poll_bit(trans, CSR_RESET,
 				   CSR_RESET_REG_FLAG_MASTER_DISABLED,
 				   CSR_RESET_REG_FLAG_MASTER_DISABLED, 100);
 	}
 
 	if (ret < 0)
 		IWL_WARN(trans, "Master Disable Timed Out, 100 usec\n");
 
 	IWL_DEBUG_INFO(trans, "stop master\n");
 }
 
 static void iwl_pcie_apm_stop(struct iwl_trans *trans, bool op_mode_leave)
 {
 	IWL_DEBUG_INFO(trans, "Stop card, put in low power state\n");
 
 	if (op_mode_leave) {
 		if (!test_bit(STATUS_DEVICE_ENABLED, &trans->status))
 			iwl_pcie_apm_init(trans);
 
 		/* inform ME that we are leaving */
 		if (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_7000)
 			iwl_set_bits_prph(trans, APMG_PCIDEV_STT_REG,
 					  APMG_PCIDEV_STT_VAL_WAKE_ME);
 		else if (trans->trans_cfg->device_family >=
 			 IWL_DEVICE_FAMILY_8000) {
 			iwl_set_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
 				    CSR_RESET_LINK_PWR_MGMT_DISABLED);
 			iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 				    CSR_HW_IF_CONFIG_REG_PREPARE |
 				    CSR_HW_IF_CONFIG_REG_ENABLE_PME);
 			mdelay(1);
 			iwl_clear_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
 				      CSR_RESET_LINK_PWR_MGMT_DISABLED);
 		}
 		mdelay(5);
 	}
 
 	clear_bit(STATUS_DEVICE_ENABLED, &trans->status);
 
 	/* Stop device's DMA activity */
 	iwl_pcie_apm_stop_master(trans);
 
 	if (trans->cfg->lp_xtal_workaround) {
 		iwl_pcie_apm_lp_xtal_enable(trans);
 		return;
 	}
 
 	iwl_trans_pcie_sw_reset(trans, false);
 
 	/*
 	 * Clear "initialization complete" bit to move adapter from
 	 * D0A* (powered-up Active) --> D0U* (Uninitialized) state.
 	 */
 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
 }
 
 static int iwl_pcie_nic_init(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int ret;
 
 	/* nic_init */
 	spin_lock_bh(&trans_pcie->irq_lock);
 	ret = iwl_pcie_apm_init(trans);
 	spin_unlock_bh(&trans_pcie->irq_lock);
 
 	if (ret)
 		return ret;
 
 	iwl_pcie_set_pwr(trans, false);
 
 	iwl_op_mode_nic_config(trans->op_mode);
 
 	/* Allocate the RX queue, or reset if it is already allocated */
 	ret = iwl_pcie_rx_init(trans);
 	if (ret)
 		return ret;
 
 	/* Allocate or reset and init all Tx and Command queues */
 	if (iwl_pcie_tx_init(trans)) {
 		iwl_pcie_rx_free(trans);
 		return -ENOMEM;
 	}
 
 	if (trans->trans_cfg->base_params->shadow_reg_enable) {
 		/* enable shadow regs in HW */
 		iwl_set_bit(trans, CSR_MAC_SHADOW_REG_CTRL, 0x800FFFFF);
 		IWL_DEBUG_INFO(trans, "Enabling shadow registers in device\n");
 	}
 
 	return 0;
 }
 
 #define HW_READY_TIMEOUT (50)
 
 /* Note: returns poll_bit return value, which is >= 0 if success */
 static int iwl_pcie_set_hw_ready(struct iwl_trans *trans)
 {
 	int ret;
 
 	iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 		    CSR_HW_IF_CONFIG_REG_BIT_NIC_READY);
 
 	/* See if we got it */
 	ret = iwl_poll_bit(trans, CSR_HW_IF_CONFIG_REG,
 			   CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
 			   CSR_HW_IF_CONFIG_REG_BIT_NIC_READY,
 			   HW_READY_TIMEOUT);
 
 	if (ret >= 0)
 		iwl_set_bit(trans, CSR_MBOX_SET_REG, CSR_MBOX_SET_REG_OS_ALIVE);
 
 	IWL_DEBUG_INFO(trans, "hardware%s ready\n", ret < 0 ? " not" : "");
 	return ret;
 }
 
 /* Note: returns standard 0/-ERROR code */
 int iwl_pcie_prepare_card_hw(struct iwl_trans *trans)
 {
 	int ret;
 	int iter;
 
 	IWL_DEBUG_INFO(trans, "iwl_trans_prepare_card_hw enter\n");
 
 	ret = iwl_pcie_set_hw_ready(trans);
 	/* If the card is ready, exit 0 */
 	if (ret >= 0) {
 		trans->csme_own = false;
 		return 0;
 	}
 
 	iwl_set_bit(trans, CSR_DBG_LINK_PWR_MGMT_REG,
 		    CSR_RESET_LINK_PWR_MGMT_DISABLED);
 	usleep_range(1000, 2000);
 
 	for (iter = 0; iter < 10; iter++) {
 		int t = 0;
 
 		/* If HW is not ready, prepare the conditions to check again */
 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 			    CSR_HW_IF_CONFIG_REG_PREPARE);
 
 		do {
 			ret = iwl_pcie_set_hw_ready(trans);
 			if (ret >= 0) {
 				trans->csme_own = false;
 				return 0;
 			}
 
 			if (iwl_mei_is_connected()) {
 				IWL_DEBUG_INFO(trans,
 					       "Couldn't prepare the card but SAP is connected\n");
 				trans->csme_own = true;
 				if (trans->trans_cfg->device_family !=
 				    IWL_DEVICE_FAMILY_9000)
 					IWL_ERR(trans,
 						"SAP not supported for this NIC family\n");
 
 				return -EBUSY;
 			}
 
 			usleep_range(200, 1000);
 			t += 200;
 		} while (t < 150000);
 		msleep(25);
 	}
 
 	IWL_ERR(trans, "Couldn't prepare the card\n");
 
 	return ret;
 }
 
 /*
  * ucode
  */
 static void iwl_pcie_load_firmware_chunk_fh(struct iwl_trans *trans,
 					    u32 dst_addr, dma_addr_t phy_addr,
 					    u32 byte_cnt)
 {
 	iwl_write32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL),
 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE);
 
 	iwl_write32(trans, FH_SRVC_CHNL_SRAM_ADDR_REG(FH_SRVC_CHNL),
 		    dst_addr);
 
 	iwl_write32(trans, FH_TFDIB_CTRL0_REG(FH_SRVC_CHNL),
 		    phy_addr & FH_MEM_TFDIB_DRAM_ADDR_LSB_MSK);
 
 	iwl_write32(trans, FH_TFDIB_CTRL1_REG(FH_SRVC_CHNL),
 		    (iwl_get_dma_hi_addr(phy_addr)
 			<< FH_MEM_TFDIB_REG1_ADDR_BITSHIFT) | byte_cnt);
 
 	iwl_write32(trans, FH_TCSR_CHNL_TX_BUF_STS_REG(FH_SRVC_CHNL),
 		    BIT(FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_NUM) |
 		    BIT(FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_IDX) |
 		    FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_VALID);
 
 	iwl_write32(trans, FH_TCSR_CHNL_TX_CONFIG_REG(FH_SRVC_CHNL),
 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE |
 		    FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_DISABLE |
 		    FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_ENDTFD);
 }
 
 static int iwl_pcie_load_firmware_chunk(struct iwl_trans *trans,
 					u32 dst_addr, dma_addr_t phy_addr,
 					u32 byte_cnt)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int ret;
 
 	trans_pcie->ucode_write_complete = false;
 
 	if (!iwl_trans_grab_nic_access(trans))
 		return -EIO;
 
 	iwl_pcie_load_firmware_chunk_fh(trans, dst_addr, phy_addr,
 					byte_cnt);
 	iwl_trans_release_nic_access(trans);
 
 	ret = wait_event_timeout(trans_pcie->ucode_write_waitq,
 				 trans_pcie->ucode_write_complete, 5 * HZ);
 	if (!ret) {
 		IWL_ERR(trans, "Failed to load firmware chunk!\n");
 		iwl_trans_pcie_dump_regs(trans);
 		return -ETIMEDOUT;
 	}
 
 	return 0;
 }
 
 static int iwl_pcie_load_section(struct iwl_trans *trans, u8 section_num,
 			    const struct fw_desc *section)
 {
 	u8 *v_addr;
 	dma_addr_t p_addr;
 	u32 offset, chunk_sz = min_t(u32, FH_MEM_TB_MAX_LENGTH, section->len);
 	int ret = 0;
 
 	IWL_DEBUG_FW(trans, "[%d] uCode section being loaded...\n",
 		     section_num);
 
 	v_addr = dma_alloc_coherent(trans->dev, chunk_sz, &p_addr,
 				    GFP_KERNEL | __GFP_NOWARN);
 	if (!v_addr) {
 		IWL_DEBUG_INFO(trans, "Falling back to small chunks of DMA\n");
 		chunk_sz = PAGE_SIZE;
 		v_addr = dma_alloc_coherent(trans->dev, chunk_sz,
 					    &p_addr, GFP_KERNEL);
 		if (!v_addr)
 			return -ENOMEM;
 	}
 
 	for (offset = 0; offset < section->len; offset += chunk_sz) {
 		u32 copy_size, dst_addr;
 		bool extended_addr = false;
 
 		copy_size = min_t(u32, chunk_sz, section->len - offset);
 		dst_addr = section->offset + offset;
 
 		if (dst_addr >= IWL_FW_MEM_EXTENDED_START &&
 		    dst_addr <= IWL_FW_MEM_EXTENDED_END)
 			extended_addr = true;
 
 		if (extended_addr)
 			iwl_set_bits_prph(trans, LMPM_CHICK,
 					  LMPM_CHICK_EXTENDED_ADDR_SPACE);
 
 		memcpy(v_addr, (const u8 *)section->data + offset, copy_size);
 		ret = iwl_pcie_load_firmware_chunk(trans, dst_addr, p_addr,
 						   copy_size);
 
 		if (extended_addr)
 			iwl_clear_bits_prph(trans, LMPM_CHICK,
 					    LMPM_CHICK_EXTENDED_ADDR_SPACE);
 
 		if (ret) {
 			IWL_ERR(trans,
 				"Could not load the [%d] uCode section\n",
 				section_num);
 			break;
 		}
 	}
 
 	dma_free_coherent(trans->dev, chunk_sz, v_addr, p_addr);
 	return ret;
 }
 
 static int iwl_pcie_load_cpu_sections_8000(struct iwl_trans *trans,
 					   const struct fw_img *image,
 					   int cpu,
 					   int *first_ucode_section)
 {
 	int shift_param;
 	int i, ret = 0, sec_num = 0x1;
 	u32 val, last_read_idx = 0;
 
 	if (cpu == 1) {
 		shift_param = 0;
 		*first_ucode_section = 0;
 	} else {
 		shift_param = 16;
 		(*first_ucode_section)++;
 	}
 
 	for (i = *first_ucode_section; i < image->num_sec; i++) {
 		last_read_idx = i;
 
 		/*
 		 * CPU1_CPU2_SEPARATOR_SECTION delimiter - separate between
 		 * CPU1 to CPU2.
 		 * PAGING_SEPARATOR_SECTION delimiter - separate between
 		 * CPU2 non paged to CPU2 paging sec.
 		 */
 		if (!image->sec[i].data ||
 		    image->sec[i].offset == CPU1_CPU2_SEPARATOR_SECTION ||
 		    image->sec[i].offset == PAGING_SEPARATOR_SECTION) {
 			IWL_DEBUG_FW(trans,
 				     "Break since Data not valid or Empty section, sec = %d\n",
 				     i);
 			break;
 		}
 
 		ret = iwl_pcie_load_section(trans, i, &image->sec[i]);
 		if (ret)
 			return ret;
 
 		/* Notify ucode of loaded section number and status */
 		val = iwl_read_direct32(trans, FH_UCODE_LOAD_STATUS);
 		val = val | (sec_num << shift_param);
 		iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS, val);
 
 		sec_num = (sec_num << 1) | 0x1;
 	}
 
 	*first_ucode_section = last_read_idx;
 
 	iwl_enable_interrupts(trans);
 
 	if (trans->trans_cfg->gen2) {
 		if (cpu == 1)
 			iwl_write_prph(trans, UREG_UCODE_LOAD_STATUS,
 				       0xFFFF);
 		else
 			iwl_write_prph(trans, UREG_UCODE_LOAD_STATUS,
 				       0xFFFFFFFF);
 	} else {
 		if (cpu == 1)
 			iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS,
 					   0xFFFF);
 		else
 			iwl_write_direct32(trans, FH_UCODE_LOAD_STATUS,
 					   0xFFFFFFFF);
 	}
 
 	return 0;
 }
 
 static int iwl_pcie_load_cpu_sections(struct iwl_trans *trans,
 				      const struct fw_img *image,
 				      int cpu,
 				      int *first_ucode_section)
 {
 	int i, ret = 0;
 	u32 last_read_idx = 0;
 
 	if (cpu == 1)
 		*first_ucode_section = 0;
 	else
 		(*first_ucode_section)++;
 
 	for (i = *first_ucode_section; i < image->num_sec; i++) {
 		last_read_idx = i;
 
 		/*
 		 * CPU1_CPU2_SEPARATOR_SECTION delimiter - separate between
 		 * CPU1 to CPU2.
 		 * PAGING_SEPARATOR_SECTION delimiter - separate between
 		 * CPU2 non paged to CPU2 paging sec.
 		 */
 		if (!image->sec[i].data ||
 		    image->sec[i].offset == CPU1_CPU2_SEPARATOR_SECTION ||
 		    image->sec[i].offset == PAGING_SEPARATOR_SECTION) {
 			IWL_DEBUG_FW(trans,
 				     "Break since Data not valid or Empty section, sec = %d\n",
 				     i);
 			break;
 		}
 
 		ret = iwl_pcie_load_section(trans, i, &image->sec[i]);
 		if (ret)
 			return ret;
 	}
 
 	*first_ucode_section = last_read_idx;
 
 	return 0;
 }
 
 static void iwl_pcie_apply_destination_ini(struct iwl_trans *trans)
 {
 	enum iwl_fw_ini_allocation_id alloc_id = IWL_FW_INI_ALLOCATION_ID_DBGC1;
 	struct iwl_fw_ini_allocation_tlv *fw_mon_cfg =
 		&trans->dbg.fw_mon_cfg[alloc_id];
 	struct iwl_dram_data *frag;
 
 	if (!iwl_trans_dbg_ini_valid(trans))
 		return;
 
 	if (le32_to_cpu(fw_mon_cfg->buf_location) ==
 	    IWL_FW_INI_LOCATION_SRAM_PATH) {
 		IWL_DEBUG_FW(trans, "WRT: Applying SMEM buffer destination\n");
 		/* set sram monitor by enabling bit 7 */
 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 			    CSR_HW_IF_CONFIG_REG_BIT_MONITOR_SRAM);
 
 		return;
 	}
 
 	if (le32_to_cpu(fw_mon_cfg->buf_location) !=
 	    IWL_FW_INI_LOCATION_DRAM_PATH ||
 	    !trans->dbg.fw_mon_ini[alloc_id].num_frags)
 		return;
 
 	frag = &trans->dbg.fw_mon_ini[alloc_id].frags[0];
 
 	IWL_DEBUG_FW(trans, "WRT: Applying DRAM destination (alloc_id=%u)\n",
 		     alloc_id);
 
 	iwl_write_umac_prph(trans, MON_BUFF_BASE_ADDR_VER2,
 			    frag->physical >> MON_BUFF_SHIFT_VER2);
 	iwl_write_umac_prph(trans, MON_BUFF_END_ADDR_VER2,
 			    (frag->physical + frag->size - 256) >>
 			    MON_BUFF_SHIFT_VER2);
 }
 
 void iwl_pcie_apply_destination(struct iwl_trans *trans)
 {
 	const struct iwl_fw_dbg_dest_tlv_v1 *dest = trans->dbg.dest_tlv;
 	const struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
 	int i;
 
 	if (iwl_trans_dbg_ini_valid(trans)) {
 		iwl_pcie_apply_destination_ini(trans);
 		return;
 	}
 
 	IWL_INFO(trans, "Applying debug destination %s\n",
 		 get_fw_dbg_mode_string(dest->monitor_mode));
 
 	if (dest->monitor_mode == EXTERNAL_MODE)
 		iwl_pcie_alloc_fw_monitor(trans, dest->size_power);
 	else
 		IWL_WARN(trans, "PCI should have external buffer debug\n");
 
 	for (i = 0; i < trans->dbg.n_dest_reg; i++) {
 		u32 addr = le32_to_cpu(dest->reg_ops[i].addr);
 		u32 val = le32_to_cpu(dest->reg_ops[i].val);
 
 		switch (dest->reg_ops[i].op) {
 		case CSR_ASSIGN:
 			iwl_write32(trans, addr, val);
 			break;
 		case CSR_SETBIT:
 			iwl_set_bit(trans, addr, BIT(val));
 			break;
 		case CSR_CLEARBIT:
 			iwl_clear_bit(trans, addr, BIT(val));
 			break;
 		case PRPH_ASSIGN:
 			iwl_write_prph(trans, addr, val);
 			break;
 		case PRPH_SETBIT:
 			iwl_set_bits_prph(trans, addr, BIT(val));
 			break;
 		case PRPH_CLEARBIT:
 			iwl_clear_bits_prph(trans, addr, BIT(val));
 			break;
 		case PRPH_BLOCKBIT:
 			if (iwl_read_prph(trans, addr) & BIT(val)) {
 				IWL_ERR(trans,
 					"BIT(%u) in address 0x%x is 1, stopping FW configuration\n",
 					val, addr);
 				goto monitor;
 			}
 			break;
 		default:
 			IWL_ERR(trans, "FW debug - unknown OP %d\n",
 				dest->reg_ops[i].op);
 			break;
 		}
 	}
 
 monitor:
 	if (dest->monitor_mode == EXTERNAL_MODE && fw_mon->size) {
 		iwl_write_prph(trans, le32_to_cpu(dest->base_reg),
 			       fw_mon->physical >> dest->base_shift);
 		if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
 			iwl_write_prph(trans, le32_to_cpu(dest->end_reg),
 				       (fw_mon->physical + fw_mon->size -
 					256) >> dest->end_shift);
 		else
 			iwl_write_prph(trans, le32_to_cpu(dest->end_reg),
 				       (fw_mon->physical + fw_mon->size) >>
 				       dest->end_shift);
 	}
 }
 
 static int iwl_pcie_load_given_ucode(struct iwl_trans *trans,
 				const struct fw_img *image)
 {
 	int ret = 0;
 	int first_ucode_section;
 
 	IWL_DEBUG_FW(trans, "working with %s CPU\n",
 		     image->is_dual_cpus ? "Dual" : "Single");
 
 	/* load to FW the binary non secured sections of CPU1 */
 	ret = iwl_pcie_load_cpu_sections(trans, image, 1, &first_ucode_section);
 	if (ret)
 		return ret;
 
 	if (image->is_dual_cpus) {
 		/* set CPU2 header address */
 		iwl_write_prph(trans,
 			       LMPM_SECURE_UCODE_LOAD_CPU2_HDR_ADDR,
 			       LMPM_SECURE_CPU2_HDR_MEM_SPACE);
 
 		/* load to FW the binary sections of CPU2 */
 		ret = iwl_pcie_load_cpu_sections(trans, image, 2,
 						 &first_ucode_section);
 		if (ret)
 			return ret;
 	}
 
 	if (iwl_pcie_dbg_on(trans))
 		iwl_pcie_apply_destination(trans);
 
 	iwl_enable_interrupts(trans);
 
 	/* release CPU reset */
 	iwl_write32(trans, CSR_RESET, 0);
 
 	return 0;
 }
 
 static int iwl_pcie_load_given_ucode_8000(struct iwl_trans *trans,
 					  const struct fw_img *image)
 {
 	int ret = 0;
 	int first_ucode_section;
 
 	IWL_DEBUG_FW(trans, "working with %s CPU\n",
 		     image->is_dual_cpus ? "Dual" : "Single");
 
 	if (iwl_pcie_dbg_on(trans))
 		iwl_pcie_apply_destination(trans);
 
 	IWL_DEBUG_POWER(trans, "Original WFPM value = 0x%08X\n",
 			iwl_read_prph(trans, WFPM_GP2));
 
 	/*
 	 * Set default value. On resume reading the values that were
 	 * zeored can provide debug data on the resume flow.
 	 * This is for debugging only and has no functional impact.
 	 */
 	iwl_write_prph(trans, WFPM_GP2, 0x01010101);
 
 	/* configure the ucode to be ready to get the secured image */
 	/* release CPU reset */
 	iwl_write_prph(trans, RELEASE_CPU_RESET, RELEASE_CPU_RESET_BIT);
 
 	/* load to FW the binary Secured sections of CPU1 */
 	ret = iwl_pcie_load_cpu_sections_8000(trans, image, 1,
 					      &first_ucode_section);
 	if (ret)
 		return ret;
 
 	/* load to FW the binary sections of CPU2 */
 	return iwl_pcie_load_cpu_sections_8000(trans, image, 2,
 					       &first_ucode_section);
 }
 
 bool iwl_pcie_check_hw_rf_kill(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
 	bool hw_rfkill = iwl_is_rfkill_set(trans);
 	bool prev = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	bool report;
 
 	if (hw_rfkill) {
 		set_bit(STATUS_RFKILL_HW, &trans->status);
 		set_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	} else {
 		clear_bit(STATUS_RFKILL_HW, &trans->status);
 		if (trans_pcie->opmode_down)
 			clear_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	}
 
 	report = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
 
 	if (prev != report)
 		iwl_trans_pcie_rf_kill(trans, report);
 
 	return hw_rfkill;
 }
 
 struct iwl_causes_list {
 	u16 mask_reg;
 	u8 bit;
 	u8 addr;
 };
 
 #define IWL_CAUSE(reg, mask)						\
 	{								\
 		.mask_reg = reg,					\
 		.bit = ilog2(mask),					\
 		.addr = ilog2(mask) +					\
 			((reg) == CSR_MSIX_FH_INT_MASK_AD ? -16 :	\
 			 (reg) == CSR_MSIX_HW_INT_MASK_AD ? 16 :	\
 			 0xffff),	/* causes overflow warning */	\
 	}
 
 static const struct iwl_causes_list causes_list_common[] = {
 	IWL_CAUSE(CSR_MSIX_FH_INT_MASK_AD, MSIX_FH_INT_CAUSES_D2S_CH0_NUM),
 	IWL_CAUSE(CSR_MSIX_FH_INT_MASK_AD, MSIX_FH_INT_CAUSES_D2S_CH1_NUM),
 	IWL_CAUSE(CSR_MSIX_FH_INT_MASK_AD, MSIX_FH_INT_CAUSES_S2D),
 	IWL_CAUSE(CSR_MSIX_FH_INT_MASK_AD, MSIX_FH_INT_CAUSES_FH_ERR),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_ALIVE),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_WAKEUP),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_RESET_DONE),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_CT_KILL),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_RF_KILL),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_PERIODIC),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_SCD),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_FH_TX),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_HW_ERR),
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_HAP),
 };
 
 static const struct iwl_causes_list causes_list_pre_bz[] = {
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_SW_ERR),
 };
 
 static const struct iwl_causes_list causes_list_bz[] = {
 	IWL_CAUSE(CSR_MSIX_HW_INT_MASK_AD, MSIX_HW_INT_CAUSES_REG_SW_ERR_BZ),
 };
 
 static void iwl_pcie_map_list(struct iwl_trans *trans,
 			      const struct iwl_causes_list *causes,
 			      int arr_size, int val)
 {
 	int i;
 
 	for (i = 0; i < arr_size; i++) {
 		iwl_write8(trans, CSR_MSIX_IVAR(causes[i].addr), val);
 		iwl_clear_bit(trans, causes[i].mask_reg,
 			      BIT(causes[i].bit));
 	}
 }
 
 static void iwl_pcie_map_non_rx_causes(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
 	int val = trans_pcie->def_irq | MSIX_NON_AUTO_CLEAR_CAUSE;
 	/*
 	 * Access all non RX causes and map them to the default irq.
 	 * In case we are missing at least one interrupt vector,
 	 * the first interrupt vector will serve non-RX and FBQ causes.
 	 */
 	iwl_pcie_map_list(trans, causes_list_common,
 			  ARRAY_SIZE(causes_list_common), val);
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
 		iwl_pcie_map_list(trans, causes_list_bz,
 				  ARRAY_SIZE(causes_list_bz), val);
 	else
 		iwl_pcie_map_list(trans, causes_list_pre_bz,
 				  ARRAY_SIZE(causes_list_pre_bz), val);
 }
 
 static void iwl_pcie_map_rx_causes(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	u32 offset =
 		trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS ? 1 : 0;
 	u32 val, idx;
 
 	/*
 	 * The first RX queue - fallback queue, which is designated for
 	 * management frame, command responses etc, is always mapped to the
 	 * first interrupt vector. The other RX queues are mapped to
 	 * the other (N - 2) interrupt vectors.
 	 */
 	val = BIT(MSIX_FH_INT_CAUSES_Q(0));
 	for (idx = 1; idx < trans->num_rx_queues; idx++) {
 		iwl_write8(trans, CSR_MSIX_RX_IVAR(idx),
 			   MSIX_FH_INT_CAUSES_Q(idx - offset));
 		val |= BIT(MSIX_FH_INT_CAUSES_Q(idx));
 	}
 	iwl_write32(trans, CSR_MSIX_FH_INT_MASK_AD, ~val);
 
 	val = MSIX_FH_INT_CAUSES_Q(0);
 	if (trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_NON_RX)
 		val |= MSIX_NON_AUTO_CLEAR_CAUSE;
 	iwl_write8(trans, CSR_MSIX_RX_IVAR(0), val);
 
 	if (trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS)
 		iwl_write8(trans, CSR_MSIX_RX_IVAR(1), val);
 }
 
 void iwl_pcie_conf_msix_hw(struct iwl_trans_pcie *trans_pcie)
 {
 	struct iwl_trans *trans = trans_pcie->trans;
 
 	if (!trans_pcie->msix_enabled) {
 		if (trans->trans_cfg->mq_rx_supported &&
 		    test_bit(STATUS_DEVICE_ENABLED, &trans->status))
 			iwl_write_umac_prph(trans, UREG_CHICK,
 					    UREG_CHICK_MSI_ENABLE);
 		return;
 	}
 	/*
 	 * The IVAR table needs to be configured again after reset,
 	 * but if the device is disabled, we can't write to
 	 * prph.
 	 */
 	if (test_bit(STATUS_DEVICE_ENABLED, &trans->status))
 		iwl_write_umac_prph(trans, UREG_CHICK, UREG_CHICK_MSIX_ENABLE);
 
 	/*
 	 * Each cause from the causes list above and the RX causes is
 	 * represented as a byte in the IVAR table. The first nibble
 	 * represents the bound interrupt vector of the cause, the second
 	 * represents no auto clear for this cause. This will be set if its
 	 * interrupt vector is bound to serve other causes.
 	 */
 	iwl_pcie_map_rx_causes(trans);
 
 	iwl_pcie_map_non_rx_causes(trans);
 }
 
 static void iwl_pcie_init_msix(struct iwl_trans_pcie *trans_pcie)
 {
 	struct iwl_trans *trans = trans_pcie->trans;
 
 	iwl_pcie_conf_msix_hw(trans_pcie);
 
 	if (!trans_pcie->msix_enabled)
 		return;
 
 	trans_pcie->fh_init_mask = ~iwl_read32(trans, CSR_MSIX_FH_INT_MASK_AD);
 	trans_pcie->fh_mask = trans_pcie->fh_init_mask;
 	trans_pcie->hw_init_mask = ~iwl_read32(trans, CSR_MSIX_HW_INT_MASK_AD);
 	trans_pcie->hw_mask = trans_pcie->hw_init_mask;
 }
 
 static void _iwl_trans_pcie_stop_device(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	lockdep_assert_held(&trans_pcie->mutex);
 
 	if (trans_pcie->is_down)
 		return;
 
 	trans_pcie->is_down = true;
 
 	/* tell the device to stop sending interrupts */
 	iwl_disable_interrupts(trans);
 
 	/* device going down, Stop using ICT table */
 	iwl_pcie_disable_ict(trans);
 
 	/*
 	 * If a HW restart happens during firmware loading,
 	 * then the firmware loading might call this function
 	 * and later it might be called again due to the
 	 * restart. So don't process again if the device is
 	 * already dead.
 	 */
 	if (test_and_clear_bit(STATUS_DEVICE_ENABLED, &trans->status)) {
 		IWL_DEBUG_INFO(trans,
 			       "DEVICE_ENABLED bit was set and is now cleared\n");
 		iwl_pcie_rx_napi_sync(trans);
 		iwl_pcie_tx_stop(trans);
 		iwl_pcie_rx_stop(trans);
 
 		/* Power-down device's busmaster DMA clocks */
 		if (!trans->cfg->apmg_not_supported) {
 			iwl_write_prph(trans, APMG_CLK_DIS_REG,
 				       APMG_CLK_VAL_DMA_CLK_RQT);
 			udelay(5);
 		}
 	}
 
 	/* Make sure (redundant) we've released our request to stay awake */
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
 		iwl_clear_bit(trans, CSR_GP_CNTRL,
 			      CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ);
 	else
 		iwl_clear_bit(trans, CSR_GP_CNTRL,
 			      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
 
 	/* Stop the device, and put it in low power state */
 	iwl_pcie_apm_stop(trans, false);
 
 	/* re-take ownership to prevent other users from stealing the device */
 	iwl_trans_pcie_sw_reset(trans, true);
 
 	/*
 	 * Upon stop, the IVAR table gets erased, so msi-x won't
 	 * work. This causes a bug in RF-KILL flows, since the interrupt
 	 * that enables radio won't fire on the correct irq, and the
 	 * driver won't be able to handle the interrupt.
 	 * Configure the IVAR table again after reset.
 	 */
 	iwl_pcie_conf_msix_hw(trans_pcie);
 
 	/*
 	 * Upon stop, the APM issues an interrupt if HW RF kill is set.
 	 * This is a bug in certain verions of the hardware.
 	 * Certain devices also keep sending HW RF kill interrupt all
 	 * the time, unless the interrupt is ACKed even if the interrupt
 	 * should be masked. Re-ACK all the interrupts here.
 	 */
 	iwl_disable_interrupts(trans);
 
 	/* clear all status bits */
 	clear_bit(STATUS_SYNC_HCMD_ACTIVE, &trans->status);
 	clear_bit(STATUS_INT_ENABLED, &trans->status);
 	clear_bit(STATUS_TPOWER_PMI, &trans->status);
 
 	/*
 	 * Even if we stop the HW, we still want the RF kill
 	 * interrupt
 	 */
 	iwl_enable_rfkill_int(trans);
 }
 
 void iwl_pcie_synchronize_irqs(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	if (trans_pcie->msix_enabled) {
 		int i;
 
 		for (i = 0; i < trans_pcie->alloc_vecs; i++)
 			synchronize_irq(trans_pcie->msix_entries[i].vector);
 	} else {
 		synchronize_irq(trans_pcie->pci_dev->irq);
 	}
 }
 
 static int iwl_trans_pcie_start_fw(struct iwl_trans *trans,
 				   const struct fw_img *fw, bool run_in_rfkill)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	bool hw_rfkill;
 	int ret;
 
 	/* This may fail if AMT took ownership of the device */
 	if (iwl_pcie_prepare_card_hw(trans)) {
 		IWL_WARN(trans, "Exit HW not ready\n");
 		return -EIO;
 	}
 
 	iwl_enable_rfkill_int(trans);
 
 	iwl_write32(trans, CSR_INT, 0xFFFFFFFF);
 
 	/*
 	 * We enabled the RF-Kill interrupt and the handler may very
 	 * well be running. Disable the interrupts to make sure no other
 	 * interrupt can be fired.
 	 */
 	iwl_disable_interrupts(trans);
 
 	/* Make sure it finished running */
 	iwl_pcie_synchronize_irqs(trans);
 
 	mutex_lock(&trans_pcie->mutex);
 
 	/* If platform's RF_KILL switch is NOT set to KILL */
 	hw_rfkill = iwl_pcie_check_hw_rf_kill(trans);
 	if (hw_rfkill && !run_in_rfkill) {
 		ret = -ERFKILL;
 		goto out;
 	}
 
 	/* Someone called stop_device, don't try to start_fw */
 	if (trans_pcie->is_down) {
 		IWL_WARN(trans,
 			 "Can't start_fw since the HW hasn't been started\n");
 		ret = -EIO;
 		goto out;
 	}
 
 	/* make sure rfkill handshake bits are cleared */
 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR,
 		    CSR_UCODE_DRV_GP1_BIT_CMD_BLOCKED);
 
 	/* clear (again), then enable host interrupts */
 	iwl_write32(trans, CSR_INT, 0xFFFFFFFF);
 
 	ret = iwl_pcie_nic_init(trans);
 	if (ret) {
 		IWL_ERR(trans, "Unable to init nic\n");
 		goto out;
 	}
 
 	/*
 	 * Now, we load the firmware and don't want to be interrupted, even
 	 * by the RF-Kill interrupt (hence mask all the interrupt besides the
 	 * FH_TX interrupt which is needed to load the firmware). If the
 	 * RF-Kill switch is toggled, we will find out after having loaded
 	 * the firmware and return the proper value to the caller.
 	 */
 	iwl_enable_fw_load_int(trans);
 
 	/* really make sure rfkill handshake bits are cleared */
 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
 	iwl_write32(trans, CSR_UCODE_DRV_GP1_CLR, CSR_UCODE_SW_BIT_RFKILL);
 
 	/* Load the given image to the HW */
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
 		ret = iwl_pcie_load_given_ucode_8000(trans, fw);
 	else
 		ret = iwl_pcie_load_given_ucode(trans, fw);
 
 	/* re-check RF-Kill state since we may have missed the interrupt */
 	hw_rfkill = iwl_pcie_check_hw_rf_kill(trans);
 	if (hw_rfkill && !run_in_rfkill)
 		ret = -ERFKILL;
 
 out:
 	mutex_unlock(&trans_pcie->mutex);
 	return ret;
 }
 
 static void iwl_trans_pcie_fw_alive(struct iwl_trans *trans, u32 scd_addr)
 {
 	iwl_pcie_reset_ict(trans);
 	iwl_pcie_tx_start(trans, scd_addr);
 }
 
 void iwl_trans_pcie_handle_stop_rfkill(struct iwl_trans *trans,
 				       bool was_in_rfkill)
 {
 	bool hw_rfkill;
 
 	/*
 	 * Check again since the RF kill state may have changed while
 	 * all the interrupts were disabled, in this case we couldn't
 	 * receive the RF kill interrupt and update the state in the
 	 * op_mode.
 	 * Don't call the op_mode if the rkfill state hasn't changed.
 	 * This allows the op_mode to call stop_device from the rfkill
 	 * notification without endless recursion. Under very rare
 	 * circumstances, we might have a small recursion if the rfkill
 	 * state changed exactly now while we were called from stop_device.
 	 * This is very unlikely but can happen and is supported.
 	 */
 	hw_rfkill = iwl_is_rfkill_set(trans);
 	if (hw_rfkill) {
 		set_bit(STATUS_RFKILL_HW, &trans->status);
 		set_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	} else {
 		clear_bit(STATUS_RFKILL_HW, &trans->status);
 		clear_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	}
 	if (hw_rfkill != was_in_rfkill)
 		iwl_trans_pcie_rf_kill(trans, hw_rfkill);
 }
 
 static void iwl_trans_pcie_stop_device(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	bool was_in_rfkill;
 
 	iwl_op_mode_time_point(trans->op_mode,
 			       IWL_FW_INI_TIME_POINT_HOST_DEVICE_DISABLE,
 			       NULL);
 
 	mutex_lock(&trans_pcie->mutex);
 	trans_pcie->opmode_down = true;
 	was_in_rfkill = test_bit(STATUS_RFKILL_OPMODE, &trans->status);
 	_iwl_trans_pcie_stop_device(trans);
 	iwl_trans_pcie_handle_stop_rfkill(trans, was_in_rfkill);
 	mutex_unlock(&trans_pcie->mutex);
 }
 
 void iwl_trans_pcie_rf_kill(struct iwl_trans *trans, bool state)
 {
 	struct iwl_trans_pcie __maybe_unused *trans_pcie =
 		IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	lockdep_assert_held(&trans_pcie->mutex);
 
 	IWL_WARN(trans, "reporting RF_KILL (radio %s)\n",
 		 state ? "disabled" : "enabled");
 	if (iwl_op_mode_hw_rf_kill(trans->op_mode, state)) {
 		if (trans->trans_cfg->gen2)
 			_iwl_trans_pcie_gen2_stop_device(trans);
 		else
 			_iwl_trans_pcie_stop_device(trans);
 	}
 }
 
 void iwl_pcie_d3_complete_suspend(struct iwl_trans *trans,
 				  bool test, bool reset)
 {
 	iwl_disable_interrupts(trans);
 
 	/*
 	 * in testing mode, the host stays awake and the
 	 * hardware won't be reset (not even partially)
 	 */
 	if (test)
 		return;
 
 	iwl_pcie_disable_ict(trans);
 
 	iwl_pcie_synchronize_irqs(trans);
 
 	iwl_clear_bit(trans, CSR_GP_CNTRL,
 		      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
 	iwl_clear_bit(trans, CSR_GP_CNTRL, CSR_GP_CNTRL_REG_FLAG_INIT_DONE);
 
 	if (reset) {
 		/*
 		 * reset TX queues -- some of their registers reset during S3
 		 * so if we don't reset everything here the D3 image would try
 		 * to execute some invalid memory upon resume
 		 */
 		iwl_trans_pcie_tx_reset(trans);
 	}
 
 	iwl_pcie_set_pwr(trans, true);
 }
 
 static int iwl_pcie_d3_handshake(struct iwl_trans *trans, bool suspend)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int ret;
 
 	if (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_AX210)
 		iwl_write_umac_prph(trans, UREG_DOORBELL_TO_ISR6,
 				    suspend ? UREG_DOORBELL_TO_ISR6_SUSPEND :
 					      UREG_DOORBELL_TO_ISR6_RESUME);
 	else if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
 		iwl_write32(trans, CSR_IPC_SLEEP_CONTROL,
 			    suspend ? CSR_IPC_SLEEP_CONTROL_SUSPEND :
 				      CSR_IPC_SLEEP_CONTROL_RESUME);
 	else
 		return 0;
 
 	ret = wait_event_timeout(trans_pcie->sx_waitq,
 				 trans_pcie->sx_complete, 2 * HZ);
 
 	/* Invalidate it toward next suspend or resume */
 	trans_pcie->sx_complete = false;
 
 	if (!ret) {
 		IWL_ERR(trans, "Timeout %s D3\n",
 			suspend ? "entering" : "exiting");
 		return -ETIMEDOUT;
 	}
 
 	return 0;
 }
 
 static int iwl_trans_pcie_d3_suspend(struct iwl_trans *trans, bool test,
 				     bool reset)
 {
 	int ret;
 
 	if (!reset)
 		/* Enable persistence mode to avoid reset */
 		iwl_set_bit(trans, CSR_HW_IF_CONFIG_REG,
 			    CSR_HW_IF_CONFIG_REG_PERSIST_MODE);
 
 	ret = iwl_pcie_d3_handshake(trans, true);
 	if (ret)
 		return ret;
 
 	iwl_pcie_d3_complete_suspend(trans, test, reset);
 
 	return 0;
 }
 
 static int iwl_trans_pcie_d3_resume(struct iwl_trans *trans,
 				    enum iwl_d3_status *status,
 				    bool test,  bool reset)
 {
 	struct iwl_trans_pcie *trans_pcie =  IWL_TRANS_GET_PCIE_TRANS(trans);
 	u32 val;
 	int ret;
 
 	if (test) {
 		iwl_enable_interrupts(trans);
 		*status = IWL_D3_STATUS_ALIVE;
 		ret = 0;
 		goto out;
 	}
 
 	iwl_set_bit(trans, CSR_GP_CNTRL,
 		    CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
 
 	ret = iwl_finish_nic_init(trans);
 	if (ret)
 		return ret;
 
 	/*
 	 * Reconfigure IVAR table in case of MSIX or reset ict table in
 	 * MSI mode since HW reset erased it.
 	 * Also enables interrupts - none will happen as
 	 * the device doesn't know we're waking it up, only when
 	 * the opmode actually tells it after this call.
 	 */
 	iwl_pcie_conf_msix_hw(trans_pcie);
 	if (!trans_pcie->msix_enabled)
 		iwl_pcie_reset_ict(trans);
 	iwl_enable_interrupts(trans);
 
 	iwl_pcie_set_pwr(trans, false);
 
 	if (!reset) {
 		iwl_clear_bit(trans, CSR_GP_CNTRL,
 			      CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
 	} else {
 		iwl_trans_pcie_tx_reset(trans);
 
 		ret = iwl_pcie_rx_init(trans);
 		if (ret) {
 			IWL_ERR(trans,
 				"Failed to resume the device (RX reset)\n");
 			return ret;
 		}
 	}
 
 	IWL_DEBUG_POWER(trans, "WFPM value upon resume = 0x%08X\n",
 			iwl_read_umac_prph(trans, WFPM_GP2));
 
 	val = iwl_read32(trans, CSR_RESET);
 	if (val & CSR_RESET_REG_FLAG_NEVO_RESET)
 		*status = IWL_D3_STATUS_RESET;
 	else
 		*status = IWL_D3_STATUS_ALIVE;
 
 out:
 	if (*status == IWL_D3_STATUS_ALIVE)
 		ret = iwl_pcie_d3_handshake(trans, false);
 
 	return ret;
 }
 
 static void
 iwl_pcie_set_interrupt_capa(struct pci_dev *pdev,
 			    struct iwl_trans *trans,
 			    const struct iwl_cfg_trans_params *cfg_trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int max_irqs, num_irqs, i, ret;
 	u16 pci_cmd;
 	u32 max_rx_queues = IWL_MAX_RX_HW_QUEUES;
 
 	if (!cfg_trans->mq_rx_supported)
 		goto enable_msi;
 
 	if (cfg_trans->device_family <= IWL_DEVICE_FAMILY_9000)
 		max_rx_queues = IWL_9000_MAX_RX_HW_QUEUES;
 
 	max_irqs = min_t(u32, num_online_cpus() + 2, max_rx_queues);
 	for (i = 0; i < max_irqs; i++)
 		trans_pcie->msix_entries[i].entry = i;
 
 	num_irqs = pci_enable_msix_range(pdev, trans_pcie->msix_entries,
 					 MSIX_MIN_INTERRUPT_VECTORS,
 					 max_irqs);
 	if (num_irqs < 0) {
 		IWL_DEBUG_INFO(trans,
 			       "Failed to enable msi-x mode (ret %d). Moving to msi mode.\n",
 			       num_irqs);
 		goto enable_msi;
 	}
 	trans_pcie->def_irq = (num_irqs == max_irqs) ? num_irqs - 1 : 0;
 
 	IWL_DEBUG_INFO(trans,
 		       "MSI-X enabled. %d interrupt vectors were allocated\n",
 		       num_irqs);
 
 	/*
 	 * In case the OS provides fewer interrupts than requested, different
 	 * causes will share the same interrupt vector as follows:
 	 * One interrupt less: non rx causes shared with FBQ.
 	 * Two interrupts less: non rx causes shared with FBQ and RSS.
 	 * More than two interrupts: we will use fewer RSS queues.
 	 */
 	if (num_irqs <= max_irqs - 2) {
 		trans_pcie->trans->num_rx_queues = num_irqs + 1;
 		trans_pcie->shared_vec_mask = IWL_SHARED_IRQ_NON_RX |
 			IWL_SHARED_IRQ_FIRST_RSS;
 	} else if (num_irqs == max_irqs - 1) {
 		trans_pcie->trans->num_rx_queues = num_irqs;
 		trans_pcie->shared_vec_mask = IWL_SHARED_IRQ_NON_RX;
 	} else {
 		trans_pcie->trans->num_rx_queues = num_irqs - 1;
 	}
 
 	IWL_DEBUG_INFO(trans,
 		       "MSI-X enabled with rx queues %d, vec mask 0x%x\n",
 		       trans_pcie->trans->num_rx_queues, trans_pcie->shared_vec_mask);
 
 	WARN_ON(trans_pcie->trans->num_rx_queues > IWL_MAX_RX_HW_QUEUES);
 
 	trans_pcie->alloc_vecs = num_irqs;
 	trans_pcie->msix_enabled = true;
 	return;
 
 enable_msi:
 	ret = pci_enable_msi(pdev);
 	if (ret) {
 		dev_err(&pdev->dev, "pci_enable_msi failed - %d\n", ret);
 		/* enable rfkill interrupt: hw bug w/a */
 		pci_read_config_word(pdev, PCI_COMMAND, &pci_cmd);
 		if (pci_cmd & PCI_COMMAND_INTX_DISABLE) {
 			pci_cmd &= ~PCI_COMMAND_INTX_DISABLE;
 			pci_write_config_word(pdev, PCI_COMMAND, pci_cmd);
 		}
 	}
 }
 
 static void iwl_pcie_irq_set_affinity(struct iwl_trans *trans)
 {
 	int iter_rx_q, i, ret, cpu, offset;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	i = trans_pcie->shared_vec_mask & IWL_SHARED_IRQ_FIRST_RSS ? 0 : 1;
 	iter_rx_q = trans_pcie->trans->num_rx_queues - 1 + i;
 	offset = 1 + i;
 	for (; i < iter_rx_q ; i++) {
 		/*
 		 * Get the cpu prior to the place to search
 		 * (i.e. return will be > i - 1).
 		 */
 		cpu = cpumask_next(i - offset, cpu_online_mask);
 		cpumask_set_cpu(cpu, &trans_pcie->affinity_mask[i]);
 		ret = irq_set_affinity_hint(trans_pcie->msix_entries[i].vector,
 					    &trans_pcie->affinity_mask[i]);
 		if (ret)
 			IWL_ERR(trans_pcie->trans,
 				"Failed to set affinity mask for IRQ %d\n",
 				trans_pcie->msix_entries[i].vector);
 	}
 }
 
 static int iwl_pcie_init_msix_handler(struct pci_dev *pdev,
 				      struct iwl_trans_pcie *trans_pcie)
 {
 	int i;
 
 	for (i = 0; i < trans_pcie->alloc_vecs; i++) {
 		int ret;
 		struct msix_entry *msix_entry;
 		const char *qname = queue_name(&pdev->dev, trans_pcie, i);
 
 		if (!qname)
 			return -ENOMEM;
 
 		msix_entry = &trans_pcie->msix_entries[i];
 		ret = devm_request_threaded_irq(&pdev->dev,
 						msix_entry->vector,
 						iwl_pcie_msix_isr,
 						(i == trans_pcie->def_irq) ?
 						iwl_pcie_irq_msix_handler :
 						iwl_pcie_irq_rx_msix_handler,
 						IRQF_SHARED,
 						qname,
 						msix_entry);
 		if (ret) {
 			IWL_ERR(trans_pcie->trans,
 				"Error allocating IRQ %d\n", i);
 
 			return ret;
 		}
 	}
 	iwl_pcie_irq_set_affinity(trans_pcie->trans);
 
 	return 0;
 }
 
 static int iwl_trans_pcie_clear_persistence_bit(struct iwl_trans *trans)
 {
 	u32 hpm, wprot;
 
 	switch (trans->trans_cfg->device_family) {
 	case IWL_DEVICE_FAMILY_9000:
 		wprot = PREG_PRPH_WPROT_9000;
 		break;
 	case IWL_DEVICE_FAMILY_22000:
 		wprot = PREG_PRPH_WPROT_22000;
 		break;
 	default:
 		return 0;
 	}
 
 	hpm = iwl_read_umac_prph_no_grab(trans, HPM_DEBUG);
 	if (!iwl_trans_is_hw_error_value(hpm) && (hpm & PERSISTENCE_BIT)) {
 		u32 wprot_val = iwl_read_umac_prph_no_grab(trans, wprot);
 
 		if (wprot_val & PREG_WFPM_ACCESS) {
 			IWL_ERR(trans,
 				"Error, can not clear persistence bit\n");
 			return -EPERM;
 		}
 		iwl_write_umac_prph_no_grab(trans, HPM_DEBUG,
 					    hpm & ~PERSISTENCE_BIT);
 	}
 
 	return 0;
 }
 
 static int iwl_pcie_gen2_force_power_gating(struct iwl_trans *trans)
 {
 	int ret;
 
 	ret = iwl_finish_nic_init(trans);
 	if (ret < 0)
 		return ret;
 
 	iwl_set_bits_prph(trans, HPM_HIPM_GEN_CFG,
 			  HPM_HIPM_GEN_CFG_CR_FORCE_ACTIVE);
 	udelay(20);
 	iwl_set_bits_prph(trans, HPM_HIPM_GEN_CFG,
 			  HPM_HIPM_GEN_CFG_CR_PG_EN |
 			  HPM_HIPM_GEN_CFG_CR_SLP_EN);
 	udelay(20);
 	iwl_clear_bits_prph(trans, HPM_HIPM_GEN_CFG,
 			    HPM_HIPM_GEN_CFG_CR_FORCE_ACTIVE);
 
 	return iwl_trans_pcie_sw_reset(trans, true);
 }
 
 static int _iwl_trans_pcie_start_hw(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int err;
 
 	lockdep_assert_held(&trans_pcie->mutex);
 
 	err = iwl_pcie_prepare_card_hw(trans);
 	if (err) {
 		IWL_ERR(trans, "Error while preparing HW: %d\n", err);
 		return err;
 	}
 
 	err = iwl_trans_pcie_clear_persistence_bit(trans);
 	if (err)
 		return err;
 
 	err = iwl_trans_pcie_sw_reset(trans, true);
 	if (err)
 		return err;
 
 	if (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_22000 &&
 	    trans->trans_cfg->integrated) {
 		err = iwl_pcie_gen2_force_power_gating(trans);
 		if (err)
 			return err;
 	}
 
 	err = iwl_pcie_apm_init(trans);
 	if (err)
 		return err;
 
 	iwl_pcie_init_msix(trans_pcie);
 
 	/* From now on, the op_mode will be kept updated about RF kill state */
 	iwl_enable_rfkill_int(trans);
 
 	trans_pcie->opmode_down = false;
 
 	/* Set is_down to false here so that...*/
 	trans_pcie->is_down = false;
 
 	/* ...rfkill can call stop_device and set it false if needed */
 	iwl_pcie_check_hw_rf_kill(trans);
 
 	return 0;
 }
 
 static int iwl_trans_pcie_start_hw(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int ret;
 
 	mutex_lock(&trans_pcie->mutex);
 	ret = _iwl_trans_pcie_start_hw(trans);
 	mutex_unlock(&trans_pcie->mutex);
 
 	return ret;
 }
 
 static void iwl_trans_pcie_op_mode_leave(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	mutex_lock(&trans_pcie->mutex);
 
 	/* disable interrupts - don't enable HW RF kill interrupt */
 	iwl_disable_interrupts(trans);
 
 	iwl_pcie_apm_stop(trans, true);
 
 	iwl_disable_interrupts(trans);
 
 	iwl_pcie_disable_ict(trans);
 
 	mutex_unlock(&trans_pcie->mutex);
 
 	iwl_pcie_synchronize_irqs(trans);
 }
 
 #if defined(__linux__)
 static void iwl_trans_pcie_write8(struct iwl_trans *trans, u32 ofs, u8 val)
 {
 	writeb(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
 }
 
 static void iwl_trans_pcie_write32(struct iwl_trans *trans, u32 ofs, u32 val)
 {
 	writel(val, IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
 }
 
 static u32 iwl_trans_pcie_read32(struct iwl_trans *trans, u32 ofs)
 {
 	return readl(IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base + ofs);
 }
 #elif defined(__FreeBSD__)
 static void iwl_trans_pcie_write8(struct iwl_trans *trans, u32 ofs, u8 val)
 {
 
 	IWL_DEBUG_PCI_RW(trans, "W1 %#010x %#04x\n", ofs, val);
 	bus_write_1((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs, val);
 }
 
 static void iwl_trans_pcie_write32(struct iwl_trans *trans, u32 ofs, u32 val)
 {
 
 	IWL_DEBUG_PCI_RW(trans, "W4 %#010x %#010x\n", ofs, val);
 	bus_write_4((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs, val);
 }
 
 static u32 iwl_trans_pcie_read32(struct iwl_trans *trans, u32 ofs)
 {
 	u32 v;
 
 	v = bus_read_4((struct resource *)IWL_TRANS_GET_PCIE_TRANS(trans)->hw_base, ofs);
 	IWL_DEBUG_PCI_RW(trans, "R4 %#010x %#010x\n", ofs, v);
 	return (v);
 }
 #endif
 
 static u32 iwl_trans_pcie_prph_msk(struct iwl_trans *trans)
 {
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210)
 		return 0x00FFFFFF;
 	else
 		return 0x000FFFFF;
 }
 
 static u32 iwl_trans_pcie_read_prph(struct iwl_trans *trans, u32 reg)
 {
 	u32 mask = iwl_trans_pcie_prph_msk(trans);
 
 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_RADDR,
 			       ((reg & mask) | (3 << 24)));
 	return iwl_trans_pcie_read32(trans, HBUS_TARG_PRPH_RDAT);
 }
 
 static void iwl_trans_pcie_write_prph(struct iwl_trans *trans, u32 addr,
 				      u32 val)
 {
 	u32 mask = iwl_trans_pcie_prph_msk(trans);
 
 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_WADDR,
 			       ((addr & mask) | (3 << 24)));
 	iwl_trans_pcie_write32(trans, HBUS_TARG_PRPH_WDAT, val);
 }
 
 static void iwl_trans_pcie_configure(struct iwl_trans *trans,
 				     const struct iwl_trans_config *trans_cfg)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	/* free all first - we might be reconfigured for a different size */
 	iwl_pcie_free_rbs_pool(trans);
 
 	trans->txqs.cmd.q_id = trans_cfg->cmd_queue;
 	trans->txqs.cmd.fifo = trans_cfg->cmd_fifo;
 	trans->txqs.cmd.wdg_timeout = trans_cfg->cmd_q_wdg_timeout;
 	trans->txqs.page_offs = trans_cfg->cb_data_offs;
 	trans->txqs.dev_cmd_offs = trans_cfg->cb_data_offs + sizeof(void *);
 	trans->txqs.queue_alloc_cmd_ver = trans_cfg->queue_alloc_cmd_ver;
 
 	if (WARN_ON(trans_cfg->n_no_reclaim_cmds > MAX_NO_RECLAIM_CMDS))
 		trans_pcie->n_no_reclaim_cmds = 0;
 	else
 		trans_pcie->n_no_reclaim_cmds = trans_cfg->n_no_reclaim_cmds;
 	if (trans_pcie->n_no_reclaim_cmds)
 		memcpy(trans_pcie->no_reclaim_cmds, trans_cfg->no_reclaim_cmds,
 		       trans_pcie->n_no_reclaim_cmds * sizeof(u8));
 
 	trans_pcie->rx_buf_size = trans_cfg->rx_buf_size;
 	trans_pcie->rx_page_order =
 		iwl_trans_get_rb_size_order(trans_pcie->rx_buf_size);
 	trans_pcie->rx_buf_bytes =
 		iwl_trans_get_rb_size(trans_pcie->rx_buf_size);
 	trans_pcie->supported_dma_mask = DMA_BIT_MASK(12);
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210)
 		trans_pcie->supported_dma_mask = DMA_BIT_MASK(11);
 
 	trans->txqs.bc_table_dword = trans_cfg->bc_table_dword;
 	trans_pcie->scd_set_active = trans_cfg->scd_set_active;
 
 	trans->command_groups = trans_cfg->command_groups;
 	trans->command_groups_size = trans_cfg->command_groups_size;
 
 	/* Initialize NAPI here - it should be before registering to mac80211
 	 * in the opmode but after the HW struct is allocated.
 	 * As this function may be called again in some corner cases don't
 	 * do anything if NAPI was already initialized.
 	 */
 	if (trans_pcie->napi_dev.reg_state != NETREG_DUMMY)
 		init_dummy_netdev(&trans_pcie->napi_dev);
 
 	trans_pcie->fw_reset_handshake = trans_cfg->fw_reset_handshake;
 }
 
 void iwl_trans_pcie_free_pnvm_dram_regions(struct iwl_dram_regions *dram_regions,
 					   struct device *dev)
 {
 	u8 i;
 	struct iwl_dram_data *desc_dram = &dram_regions->prph_scratch_mem_desc;
 
 	/* free DRAM payloads */
 	for (i = 0; i < dram_regions->n_regions; i++) {
 		dma_free_coherent(dev, dram_regions->drams[i].size,
 				  dram_regions->drams[i].block,
 				  dram_regions->drams[i].physical);
 	}
 	dram_regions->n_regions = 0;
 
 	/* free DRAM addresses array */
 	if (desc_dram->block) {
 		dma_free_coherent(dev, desc_dram->size,
 				  desc_dram->block,
 				  desc_dram->physical);
 	}
 	memset(desc_dram, 0, sizeof(*desc_dram));
 }
 
 void iwl_trans_pcie_free(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int i;
 
 	iwl_pcie_synchronize_irqs(trans);
 
 	if (trans->trans_cfg->gen2)
 		iwl_txq_gen2_tx_free(trans);
 	else
 		iwl_pcie_tx_free(trans);
 	iwl_pcie_rx_free(trans);
 
 	if (trans_pcie->rba.alloc_wq) {
 		destroy_workqueue(trans_pcie->rba.alloc_wq);
 		trans_pcie->rba.alloc_wq = NULL;
 	}
 
 	if (trans_pcie->msix_enabled) {
 		for (i = 0; i < trans_pcie->alloc_vecs; i++) {
 			irq_set_affinity_hint(
 				trans_pcie->msix_entries[i].vector,
 				NULL);
 		}
 
 		trans_pcie->msix_enabled = false;
 	} else {
 		iwl_pcie_free_ict(trans);
 	}
 
 	iwl_pcie_free_fw_monitor(trans);
 
 	iwl_trans_pcie_free_pnvm_dram_regions(&trans_pcie->pnvm_data,
 					      trans->dev);
 	iwl_trans_pcie_free_pnvm_dram_regions(&trans_pcie->reduced_tables_data,
 					      trans->dev);
 
 	mutex_destroy(&trans_pcie->mutex);
 	iwl_trans_free(trans);
 }
 
 static void iwl_trans_pcie_set_pmi(struct iwl_trans *trans, bool state)
 {
 	if (state)
 		set_bit(STATUS_TPOWER_PMI, &trans->status);
 	else
 		clear_bit(STATUS_TPOWER_PMI, &trans->status);
 }
 
 struct iwl_trans_pcie_removal {
 	struct pci_dev *pdev;
 	struct work_struct work;
 	bool rescan;
 };
 
 static void iwl_trans_pcie_removal_wk(struct work_struct *wk)
 {
 	struct iwl_trans_pcie_removal *removal =
 		container_of(wk, struct iwl_trans_pcie_removal, work);
 	struct pci_dev *pdev = removal->pdev;
 	static char *prop[] = {"EVENT=INACCESSIBLE", NULL};
 	struct pci_bus *bus = pdev->bus;
 
 	dev_err(&pdev->dev, "Device gone - attempting removal\n");
 	kobject_uevent_env(&pdev->dev.kobj, KOBJ_CHANGE, prop);
 	pci_lock_rescan_remove();
 	pci_dev_put(pdev);
 	pci_stop_and_remove_bus_device(pdev);
 	if (removal->rescan)
 #if defined(__linux__)
 		pci_rescan_bus(bus->parent);
 #elif defined(__FreeBSD__)
 		pci_rescan_bus(bus);
 #endif
 	pci_unlock_rescan_remove();
 
 	kfree(removal);
 	module_put(THIS_MODULE);
 }
 
 void iwl_trans_pcie_remove(struct iwl_trans *trans, bool rescan)
 {
 	struct iwl_trans_pcie_removal *removal;
 
 	if (test_bit(STATUS_TRANS_DEAD, &trans->status))
 		return;
 
 	IWL_ERR(trans, "Device gone - scheduling removal!\n");
 
 	/*
 	 * get a module reference to avoid doing this
 	 * while unloading anyway and to avoid
 	 * scheduling a work with code that's being
 	 * removed.
 	 */
 	if (!try_module_get(THIS_MODULE)) {
 		IWL_ERR(trans,
 			"Module is being unloaded - abort\n");
 		return;
 	}
 
 	removal = kzalloc(sizeof(*removal), GFP_ATOMIC);
 	if (!removal) {
 		module_put(THIS_MODULE);
 		return;
 	}
 	/*
 	 * we don't need to clear this flag, because
 	 * the trans will be freed and reallocated.
 	 */
 	set_bit(STATUS_TRANS_DEAD, &trans->status);
 
 	removal->pdev = to_pci_dev(trans->dev);
 	removal->rescan = rescan;
 	INIT_WORK(&removal->work, iwl_trans_pcie_removal_wk);
 	pci_dev_get(removal->pdev);
 	schedule_work(&removal->work);
 }
 EXPORT_SYMBOL(iwl_trans_pcie_remove);
 
 /*
  * This version doesn't disable BHs but rather assumes they're
  * already disabled.
  */
 bool __iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)
 {
 	int ret;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	u32 write = CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ;
 	u32 mask = CSR_GP_CNTRL_REG_FLAG_MAC_CLOCK_READY |
 		   CSR_GP_CNTRL_REG_FLAG_GOING_TO_SLEEP;
 	u32 poll = CSR_GP_CNTRL_REG_VAL_MAC_ACCESS_EN;
 
 	spin_lock(&trans_pcie->reg_lock);
 
 	if (trans_pcie->cmd_hold_nic_awake)
 		goto out;
 
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ) {
 		write = CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ;
 		mask = CSR_GP_CNTRL_REG_FLAG_MAC_STATUS;
 		poll = CSR_GP_CNTRL_REG_FLAG_MAC_STATUS;
 	}
 
 	/* this bit wakes up the NIC */
 	__iwl_trans_pcie_set_bit(trans, CSR_GP_CNTRL, write);
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_8000)
 		udelay(2);
 
 	/*
 	 * These bits say the device is running, and should keep running for
 	 * at least a short while (at least as long as MAC_ACCESS_REQ stays 1),
 	 * but they do not indicate that embedded SRAM is restored yet;
 	 * HW with volatile SRAM must save/restore contents to/from
 	 * host DRAM when sleeping/waking for power-saving.
 	 * Each direction takes approximately 1/4 millisecond; with this
 	 * overhead, it's a good idea to grab and hold MAC_ACCESS_REQUEST if a
 	 * series of register accesses are expected (e.g. reading Event Log),
 	 * to keep device from sleeping.
 	 *
 	 * CSR_UCODE_DRV_GP1 register bit MAC_SLEEP == 0 indicates that
 	 * SRAM is okay/restored.  We don't check that here because this call
 	 * is just for hardware register access; but GP1 MAC_SLEEP
 	 * check is a good idea before accessing the SRAM of HW with
 	 * volatile SRAM (e.g. reading Event Log).
 	 *
 	 * 5000 series and later (including 1000 series) have non-volatile SRAM,
 	 * and do not save/restore SRAM when power cycling.
 	 */
 	ret = iwl_poll_bit(trans, CSR_GP_CNTRL, poll, mask, 15000);
 	if (unlikely(ret < 0)) {
 		u32 cntrl = iwl_read32(trans, CSR_GP_CNTRL);
 
 		WARN_ONCE(1,
 			  "Timeout waiting for hardware access (CSR_GP_CNTRL 0x%08x)\n",
 			  cntrl);
 
 		iwl_trans_pcie_dump_regs(trans);
 
 		if (iwlwifi_mod_params.remove_when_gone && cntrl == ~0U)
 			iwl_trans_pcie_remove(trans, false);
 		else
 			iwl_write32(trans, CSR_RESET,
 				    CSR_RESET_REG_FLAG_FORCE_NMI);
 
 		spin_unlock(&trans_pcie->reg_lock);
 		return false;
 	}
 
 out:
 	/*
 	 * Fool sparse by faking we release the lock - sparse will
 	 * track nic_access anyway.
 	 */
 	__release(&trans_pcie->reg_lock);
 	return true;
 }
 
 static bool iwl_trans_pcie_grab_nic_access(struct iwl_trans *trans)
 {
 	bool ret;
 
 	local_bh_disable();
 	ret = __iwl_trans_pcie_grab_nic_access(trans);
 	if (ret) {
 		/* keep BHs disabled until iwl_trans_pcie_release_nic_access */
 		return ret;
 	}
 	local_bh_enable();
 	return false;
 }
 
 static void iwl_trans_pcie_release_nic_access(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	lockdep_assert_held(&trans_pcie->reg_lock);
 
 	/*
 	 * Fool sparse by faking we acquiring the lock - sparse will
 	 * track nic_access anyway.
 	 */
 	__acquire(&trans_pcie->reg_lock);
 
 	if (trans_pcie->cmd_hold_nic_awake)
 		goto out;
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
 					   CSR_GP_CNTRL_REG_FLAG_BZ_MAC_ACCESS_REQ);
 	else
 		__iwl_trans_pcie_clear_bit(trans, CSR_GP_CNTRL,
 					   CSR_GP_CNTRL_REG_FLAG_MAC_ACCESS_REQ);
 	/*
 	 * Above we read the CSR_GP_CNTRL register, which will flush
 	 * any previous writes, but we need the write that clears the
 	 * MAC_ACCESS_REQ bit to be performed before any other writes
 	 * scheduled on different CPUs (after we drop reg_lock).
 	 */
 out:
 	spin_unlock_bh(&trans_pcie->reg_lock);
 }
 
 static int iwl_trans_pcie_read_mem(struct iwl_trans *trans, u32 addr,
 				   void *buf, int dwords)
 {
 	int offs = 0;
 	u32 *vals = buf;
 
 	while (offs < dwords) {
 		/* limit the time we spin here under lock to 1/2s */
 		unsigned long end = jiffies + HZ / 2;
 		bool resched = false;
 
 		if (iwl_trans_grab_nic_access(trans)) {
 			iwl_write32(trans, HBUS_TARG_MEM_RADDR,
 				    addr + 4 * offs);
 
 			while (offs < dwords) {
 				vals[offs] = iwl_read32(trans,
 							HBUS_TARG_MEM_RDAT);
 				offs++;
 
 				if (time_after(jiffies, end)) {
 					resched = true;
 					break;
 				}
 			}
 			iwl_trans_release_nic_access(trans);
 
 			if (resched)
 				cond_resched();
 		} else {
 			return -EBUSY;
 		}
 	}
 
 	return 0;
 }
 
 static int iwl_trans_pcie_write_mem(struct iwl_trans *trans, u32 addr,
 				    const void *buf, int dwords)
 {
 	int offs, ret = 0;
 	const u32 *vals = buf;
 
 	if (iwl_trans_grab_nic_access(trans)) {
 		iwl_write32(trans, HBUS_TARG_MEM_WADDR, addr);
 		for (offs = 0; offs < dwords; offs++)
 			iwl_write32(trans, HBUS_TARG_MEM_WDAT,
 				    vals ? vals[offs] : 0);
 		iwl_trans_release_nic_access(trans);
 	} else {
 		ret = -EBUSY;
 	}
 	return ret;
 }
 
 static int iwl_trans_pcie_read_config32(struct iwl_trans *trans, u32 ofs,
 					u32 *val)
 {
 	return pci_read_config_dword(IWL_TRANS_GET_PCIE_TRANS(trans)->pci_dev,
 				     ofs, val);
 }
 
 static void iwl_trans_pcie_block_txq_ptrs(struct iwl_trans *trans, bool block)
 {
 	int i;
 
 	for (i = 0; i < trans->trans_cfg->base_params->num_of_queues; i++) {
 		struct iwl_txq *txq = trans->txqs.txq[i];
 
 		if (i == trans->txqs.cmd.q_id)
 			continue;
 
 		spin_lock_bh(&txq->lock);
 
 		if (!block && !(WARN_ON_ONCE(!txq->block))) {
 			txq->block--;
 			if (!txq->block) {
 				iwl_write32(trans, HBUS_TARG_WRPTR,
 					    txq->write_ptr | (i << 8));
 			}
 		} else if (block) {
 			txq->block++;
 		}
 
 		spin_unlock_bh(&txq->lock);
 	}
 }
 
 #define IWL_FLUSH_WAIT_MS	2000
 
 static int iwl_trans_pcie_rxq_dma_data(struct iwl_trans *trans, int queue,
 				       struct iwl_trans_rxq_dma_data *data)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	if (queue >= trans->num_rx_queues || !trans_pcie->rxq)
 		return -EINVAL;
 
 	data->fr_bd_cb = trans_pcie->rxq[queue].bd_dma;
 	data->urbd_stts_wrptr = trans_pcie->rxq[queue].rb_stts_dma;
 	data->ur_bd_cb = trans_pcie->rxq[queue].used_bd_dma;
 	data->fr_bd_wid = 0;
 
 	return 0;
 }
 
 static int iwl_trans_pcie_wait_txq_empty(struct iwl_trans *trans, int txq_idx)
 {
 	struct iwl_txq *txq;
 	unsigned long now = jiffies;
 	bool overflow_tx;
 	u8 wr_ptr;
 
 	/* Make sure the NIC is still alive in the bus */
 	if (test_bit(STATUS_TRANS_DEAD, &trans->status))
 		return -ENODEV;
 
 	if (!test_bit(txq_idx, trans->txqs.queue_used))
 		return -EINVAL;
 
 	IWL_DEBUG_TX_QUEUES(trans, "Emptying queue %d...\n", txq_idx);
 	txq = trans->txqs.txq[txq_idx];
 
 	spin_lock_bh(&txq->lock);
 	overflow_tx = txq->overflow_tx ||
 		      !skb_queue_empty(&txq->overflow_q);
 	spin_unlock_bh(&txq->lock);
 
 	wr_ptr = READ_ONCE(txq->write_ptr);
 
 	while ((txq->read_ptr != READ_ONCE(txq->write_ptr) ||
 		overflow_tx) &&
 	       !time_after(jiffies,
 			   now + msecs_to_jiffies(IWL_FLUSH_WAIT_MS))) {
 		u8 write_ptr = READ_ONCE(txq->write_ptr);
 
 		/*
 		 * If write pointer moved during the wait, warn only
 		 * if the TX came from op mode. In case TX came from
 		 * trans layer (overflow TX) don't warn.
 		 */
 		if (WARN_ONCE(wr_ptr != write_ptr && !overflow_tx,
 			      "WR pointer moved while flushing %d -> %d\n",
 			      wr_ptr, write_ptr))
 			return -ETIMEDOUT;
 		wr_ptr = write_ptr;
 
 		usleep_range(1000, 2000);
 
 		spin_lock_bh(&txq->lock);
 		overflow_tx = txq->overflow_tx ||
 			      !skb_queue_empty(&txq->overflow_q);
 		spin_unlock_bh(&txq->lock);
 	}
 
 	if (txq->read_ptr != txq->write_ptr) {
 		IWL_ERR(trans,
 			"fail to flush all tx fifo queues Q %d\n", txq_idx);
 		iwl_txq_log_scd_error(trans, txq);
 		return -ETIMEDOUT;
 	}
 
 	IWL_DEBUG_TX_QUEUES(trans, "Queue %d is now empty.\n", txq_idx);
 
 	return 0;
 }
 
 static int iwl_trans_pcie_wait_txqs_empty(struct iwl_trans *trans, u32 txq_bm)
 {
 	int cnt;
 	int ret = 0;
 
 	/* waiting for all the tx frames complete might take a while */
 	for (cnt = 0;
 	     cnt < trans->trans_cfg->base_params->num_of_queues;
 	     cnt++) {
 
 		if (cnt == trans->txqs.cmd.q_id)
 			continue;
 		if (!test_bit(cnt, trans->txqs.queue_used))
 			continue;
 		if (!(BIT(cnt) & txq_bm))
 			continue;
 
 		ret = iwl_trans_pcie_wait_txq_empty(trans, cnt);
 		if (ret)
 			break;
 	}
 
 	return ret;
 }
 
 static void iwl_trans_pcie_set_bits_mask(struct iwl_trans *trans, u32 reg,
 					 u32 mask, u32 value)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	spin_lock_bh(&trans_pcie->reg_lock);
 	__iwl_trans_pcie_set_bits_mask(trans, reg, mask, value);
 	spin_unlock_bh(&trans_pcie->reg_lock);
 }
 
 static const char *get_csr_string(int cmd)
 {
 #define IWL_CMD(x) case x: return #x
 	switch (cmd) {
 	IWL_CMD(CSR_HW_IF_CONFIG_REG);
 	IWL_CMD(CSR_INT_COALESCING);
 	IWL_CMD(CSR_INT);
 	IWL_CMD(CSR_INT_MASK);
 	IWL_CMD(CSR_FH_INT_STATUS);
 	IWL_CMD(CSR_GPIO_IN);
 	IWL_CMD(CSR_RESET);
 	IWL_CMD(CSR_GP_CNTRL);
 	IWL_CMD(CSR_HW_REV);
 	IWL_CMD(CSR_EEPROM_REG);
 	IWL_CMD(CSR_EEPROM_GP);
 	IWL_CMD(CSR_OTP_GP_REG);
 	IWL_CMD(CSR_GIO_REG);
 	IWL_CMD(CSR_GP_UCODE_REG);
 	IWL_CMD(CSR_GP_DRIVER_REG);
 	IWL_CMD(CSR_UCODE_DRV_GP1);
 	IWL_CMD(CSR_UCODE_DRV_GP2);
 	IWL_CMD(CSR_LED_REG);
 	IWL_CMD(CSR_DRAM_INT_TBL_REG);
 	IWL_CMD(CSR_GIO_CHICKEN_BITS);
 	IWL_CMD(CSR_ANA_PLL_CFG);
 	IWL_CMD(CSR_HW_REV_WA_REG);
 	IWL_CMD(CSR_MONITOR_STATUS_REG);
 	IWL_CMD(CSR_DBG_HPET_MEM_REG);
 	default:
 		return "UNKNOWN";
 	}
 #undef IWL_CMD
 }
 
 void iwl_pcie_dump_csr(struct iwl_trans *trans)
 {
 	int i;
 	static const u32 csr_tbl[] = {
 		CSR_HW_IF_CONFIG_REG,
 		CSR_INT_COALESCING,
 		CSR_INT,
 		CSR_INT_MASK,
 		CSR_FH_INT_STATUS,
 		CSR_GPIO_IN,
 		CSR_RESET,
 		CSR_GP_CNTRL,
 		CSR_HW_REV,
 		CSR_EEPROM_REG,
 		CSR_EEPROM_GP,
 		CSR_OTP_GP_REG,
 		CSR_GIO_REG,
 		CSR_GP_UCODE_REG,
 		CSR_GP_DRIVER_REG,
 		CSR_UCODE_DRV_GP1,
 		CSR_UCODE_DRV_GP2,
 		CSR_LED_REG,
 		CSR_DRAM_INT_TBL_REG,
 		CSR_GIO_CHICKEN_BITS,
 		CSR_ANA_PLL_CFG,
 		CSR_MONITOR_STATUS_REG,
 		CSR_HW_REV_WA_REG,
 		CSR_DBG_HPET_MEM_REG
 	};
 	IWL_ERR(trans, "CSR values:\n");
 	IWL_ERR(trans, "(2nd byte of CSR_INT_COALESCING is "
 		"CSR_INT_PERIODIC_REG)\n");
 	for (i = 0; i <  ARRAY_SIZE(csr_tbl); i++) {
 		IWL_ERR(trans, "  %25s: 0X%08x\n",
 			get_csr_string(csr_tbl[i]),
 			iwl_read32(trans, csr_tbl[i]));
 	}
 }
 
 #ifdef CONFIG_IWLWIFI_DEBUGFS
 /* create and remove of files */
 #define DEBUGFS_ADD_FILE(name, parent, mode) do {			\
 	debugfs_create_file(#name, mode, parent, trans,			\
 			    &iwl_dbgfs_##name##_ops);			\
 } while (0)
 
 /* file operation */
 #define DEBUGFS_READ_FILE_OPS(name)					\
 static const struct file_operations iwl_dbgfs_##name##_ops = {		\
 	.read = iwl_dbgfs_##name##_read,				\
 	.open = simple_open,						\
 	.llseek = generic_file_llseek,					\
 };
 
 #define DEBUGFS_WRITE_FILE_OPS(name)                                    \
 static const struct file_operations iwl_dbgfs_##name##_ops = {          \
 	.write = iwl_dbgfs_##name##_write,                              \
 	.open = simple_open,						\
 	.llseek = generic_file_llseek,					\
 };
 
 #define DEBUGFS_READ_WRITE_FILE_OPS(name)				\
 static const struct file_operations iwl_dbgfs_##name##_ops = {		\
 	.write = iwl_dbgfs_##name##_write,				\
 	.read = iwl_dbgfs_##name##_read,				\
 	.open = simple_open,						\
 	.llseek = generic_file_llseek,					\
 };
 
 struct iwl_dbgfs_tx_queue_priv {
 	struct iwl_trans *trans;
 };
 
 struct iwl_dbgfs_tx_queue_state {
 	loff_t pos;
 };
 
 static void *iwl_dbgfs_tx_queue_seq_start(struct seq_file *seq, loff_t *pos)
 {
 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
 	struct iwl_dbgfs_tx_queue_state *state;
 
 	if (*pos >= priv->trans->trans_cfg->base_params->num_of_queues)
 		return NULL;
 
 	state = kmalloc(sizeof(*state), GFP_KERNEL);
 	if (!state)
 		return NULL;
 	state->pos = *pos;
 	return state;
 }
 
 static void *iwl_dbgfs_tx_queue_seq_next(struct seq_file *seq,
 					 void *v, loff_t *pos)
 {
 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
 	struct iwl_dbgfs_tx_queue_state *state = v;
 
 	*pos = ++state->pos;
 
 	if (*pos >= priv->trans->trans_cfg->base_params->num_of_queues)
 		return NULL;
 
 	return state;
 }
 
 static void iwl_dbgfs_tx_queue_seq_stop(struct seq_file *seq, void *v)
 {
 	kfree(v);
 }
 
 static int iwl_dbgfs_tx_queue_seq_show(struct seq_file *seq, void *v)
 {
 	struct iwl_dbgfs_tx_queue_priv *priv = seq->private;
 	struct iwl_dbgfs_tx_queue_state *state = v;
 	struct iwl_trans *trans = priv->trans;
 	struct iwl_txq *txq = trans->txqs.txq[state->pos];
 
 	seq_printf(seq, "hwq %.3u: used=%d stopped=%d ",
 		   (unsigned int)state->pos,
 		   !!test_bit(state->pos, trans->txqs.queue_used),
 		   !!test_bit(state->pos, trans->txqs.queue_stopped));
 	if (txq)
 		seq_printf(seq,
 			   "read=%u write=%u need_update=%d frozen=%d n_window=%d ampdu=%d",
 			   txq->read_ptr, txq->write_ptr,
 			   txq->need_update, txq->frozen,
 			   txq->n_window, txq->ampdu);
 	else
 		seq_puts(seq, "(unallocated)");
 
 	if (state->pos == trans->txqs.cmd.q_id)
 		seq_puts(seq, " (HCMD)");
 	seq_puts(seq, "\n");
 
 	return 0;
 }
 
 static const struct seq_operations iwl_dbgfs_tx_queue_seq_ops = {
 	.start = iwl_dbgfs_tx_queue_seq_start,
 	.next = iwl_dbgfs_tx_queue_seq_next,
 	.stop = iwl_dbgfs_tx_queue_seq_stop,
 	.show = iwl_dbgfs_tx_queue_seq_show,
 };
 
 static int iwl_dbgfs_tx_queue_open(struct inode *inode, struct file *filp)
 {
 	struct iwl_dbgfs_tx_queue_priv *priv;
 
 	priv = __seq_open_private(filp, &iwl_dbgfs_tx_queue_seq_ops,
 				  sizeof(*priv));
 
 	if (!priv)
 		return -ENOMEM;
 
 	priv->trans = inode->i_private;
 	return 0;
 }
 
 static ssize_t iwl_dbgfs_rx_queue_read(struct file *file,
 				       char __user *user_buf,
 				       size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	char *buf;
 	int pos = 0, i, ret;
 	size_t bufsz;
 
 	bufsz = sizeof(char) * 121 * trans->num_rx_queues;
 
 	if (!trans_pcie->rxq)
 		return -EAGAIN;
 
 	buf = kzalloc(bufsz, GFP_KERNEL);
 	if (!buf)
 		return -ENOMEM;
 
 	for (i = 0; i < trans->num_rx_queues && pos < bufsz; i++) {
 		struct iwl_rxq *rxq = &trans_pcie->rxq[i];
 
 		pos += scnprintf(buf + pos, bufsz - pos, "queue#: %2d\n",
 				 i);
 		pos += scnprintf(buf + pos, bufsz - pos, "\tread: %u\n",
 				 rxq->read);
 		pos += scnprintf(buf + pos, bufsz - pos, "\twrite: %u\n",
 				 rxq->write);
 		pos += scnprintf(buf + pos, bufsz - pos, "\twrite_actual: %u\n",
 				 rxq->write_actual);
 		pos += scnprintf(buf + pos, bufsz - pos, "\tneed_update: %2d\n",
 				 rxq->need_update);
 		pos += scnprintf(buf + pos, bufsz - pos, "\tfree_count: %u\n",
 				 rxq->free_count);
 		if (rxq->rb_stts) {
 			u32 r =	__le16_to_cpu(iwl_get_closed_rb_stts(trans,
 								     rxq));
 			pos += scnprintf(buf + pos, bufsz - pos,
 					 "\tclosed_rb_num: %u\n",
 					 r & 0x0FFF);
 		} else {
 			pos += scnprintf(buf + pos, bufsz - pos,
 					 "\tclosed_rb_num: Not Allocated\n");
 		}
 	}
 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
 	kfree(buf);
 
 	return ret;
 }
 
 static ssize_t iwl_dbgfs_interrupt_read(struct file *file,
 					char __user *user_buf,
 					size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	struct isr_statistics *isr_stats = &trans_pcie->isr_stats;
 
 	int pos = 0;
 	char *buf;
 	int bufsz = 24 * 64; /* 24 items * 64 char per item */
 	ssize_t ret;
 
 	buf = kzalloc(bufsz, GFP_KERNEL);
 	if (!buf)
 		return -ENOMEM;
 
 	pos += scnprintf(buf + pos, bufsz - pos,
 			"Interrupt Statistics Report:\n");
 
 	pos += scnprintf(buf + pos, bufsz - pos, "HW Error:\t\t\t %u\n",
 		isr_stats->hw);
 	pos += scnprintf(buf + pos, bufsz - pos, "SW Error:\t\t\t %u\n",
 		isr_stats->sw);
 	if (isr_stats->sw || isr_stats->hw) {
 		pos += scnprintf(buf + pos, bufsz - pos,
 			"\tLast Restarting Code:  0x%X\n",
 			isr_stats->err_code);
 	}
 #ifdef CONFIG_IWLWIFI_DEBUG
 	pos += scnprintf(buf + pos, bufsz - pos, "Frame transmitted:\t\t %u\n",
 		isr_stats->sch);
 	pos += scnprintf(buf + pos, bufsz - pos, "Alive interrupt:\t\t %u\n",
 		isr_stats->alive);
 #endif
 	pos += scnprintf(buf + pos, bufsz - pos,
 		"HW RF KILL switch toggled:\t %u\n", isr_stats->rfkill);
 
 	pos += scnprintf(buf + pos, bufsz - pos, "CT KILL:\t\t\t %u\n",
 		isr_stats->ctkill);
 
 	pos += scnprintf(buf + pos, bufsz - pos, "Wakeup Interrupt:\t\t %u\n",
 		isr_stats->wakeup);
 
 	pos += scnprintf(buf + pos, bufsz - pos,
 		"Rx command responses:\t\t %u\n", isr_stats->rx);
 
 	pos += scnprintf(buf + pos, bufsz - pos, "Tx/FH interrupt:\t\t %u\n",
 		isr_stats->tx);
 
 	pos += scnprintf(buf + pos, bufsz - pos, "Unexpected INTA:\t\t %u\n",
 		isr_stats->unhandled);
 
 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, pos);
 	kfree(buf);
 	return ret;
 }
 
 static ssize_t iwl_dbgfs_interrupt_write(struct file *file,
 					 const char __user *user_buf,
 					 size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	struct isr_statistics *isr_stats = &trans_pcie->isr_stats;
 	u32 reset_flag;
 	int ret;
 
 	ret = kstrtou32_from_user(user_buf, count, 16, &reset_flag);
 	if (ret)
 		return ret;
 	if (reset_flag == 0)
 		memset(isr_stats, 0, sizeof(*isr_stats));
 
 	return count;
 }
 
 static ssize_t iwl_dbgfs_csr_write(struct file *file,
 				   const char __user *user_buf,
 				   size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 
 	iwl_pcie_dump_csr(trans);
 
 	return count;
 }
 
 static ssize_t iwl_dbgfs_fh_reg_read(struct file *file,
 				     char __user *user_buf,
 				     size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	char *buf = NULL;
 	ssize_t ret;
 
 	ret = iwl_dump_fh(trans, &buf);
 	if (ret < 0)
 		return ret;
 	if (!buf)
 		return -EINVAL;
 	ret = simple_read_from_buffer(user_buf, count, ppos, buf, ret);
 	kfree(buf);
 	return ret;
 }
 
 static ssize_t iwl_dbgfs_rfkill_read(struct file *file,
 				     char __user *user_buf,
 				     size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	char buf[100];
 	int pos;
 
 	pos = scnprintf(buf, sizeof(buf), "debug: %d\nhw: %d\n",
 			trans_pcie->debug_rfkill,
 			!(iwl_read32(trans, CSR_GP_CNTRL) &
 				CSR_GP_CNTRL_REG_FLAG_HW_RF_KILL_SW));
 
 	return simple_read_from_buffer(user_buf, count, ppos, buf, pos);
 }
 
 static ssize_t iwl_dbgfs_rfkill_write(struct file *file,
 				      const char __user *user_buf,
 				      size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	bool new_value;
 	int ret;
 
 	ret = kstrtobool_from_user(user_buf, count, &new_value);
 	if (ret)
 		return ret;
 	if (new_value == trans_pcie->debug_rfkill)
 		return count;
 	IWL_WARN(trans, "changing debug rfkill %d->%d\n",
 		 trans_pcie->debug_rfkill, new_value);
 	trans_pcie->debug_rfkill = new_value;
 	iwl_pcie_handle_rfkill_irq(trans);
 
 	return count;
 }
 
 static int iwl_dbgfs_monitor_data_open(struct inode *inode,
 				       struct file *file)
 {
 	struct iwl_trans *trans = inode->i_private;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	if (!trans->dbg.dest_tlv ||
 	    trans->dbg.dest_tlv->monitor_mode != EXTERNAL_MODE) {
 		IWL_ERR(trans, "Debug destination is not set to DRAM\n");
 		return -ENOENT;
 	}
 
 	if (trans_pcie->fw_mon_data.state != IWL_FW_MON_DBGFS_STATE_CLOSED)
 		return -EBUSY;
 
 	trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_OPEN;
 	return simple_open(inode, file);
 }
 
 static int iwl_dbgfs_monitor_data_release(struct inode *inode,
 					  struct file *file)
 {
 	struct iwl_trans_pcie *trans_pcie =
 		IWL_TRANS_GET_PCIE_TRANS(inode->i_private);
 
 	if (trans_pcie->fw_mon_data.state == IWL_FW_MON_DBGFS_STATE_OPEN)
 		trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;
 	return 0;
 }
 
 static bool iwl_write_to_user_buf(char __user *user_buf, ssize_t count,
 				  void *buf, ssize_t *size,
 				  ssize_t *bytes_copied)
 {
 	ssize_t buf_size_left = count - *bytes_copied;
 
 	buf_size_left = buf_size_left - (buf_size_left % sizeof(u32));
 	if (*size > buf_size_left)
 		*size = buf_size_left;
 
 	*size -= copy_to_user(user_buf, buf, *size);
 	*bytes_copied += *size;
 
 	if (buf_size_left == *size)
 		return true;
 	return false;
 }
 
 static ssize_t iwl_dbgfs_monitor_data_read(struct file *file,
 					   char __user *user_buf,
 					   size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	u8 *cpu_addr = (void *)trans->dbg.fw_mon.block, *curr_buf;
 	struct cont_rec *data = &trans_pcie->fw_mon_data;
 	u32 write_ptr_addr, wrap_cnt_addr, write_ptr, wrap_cnt;
 	ssize_t size, bytes_copied = 0;
 	bool b_full;
 
 	if (trans->dbg.dest_tlv) {
 		write_ptr_addr =
 			le32_to_cpu(trans->dbg.dest_tlv->write_ptr_reg);
 		wrap_cnt_addr = le32_to_cpu(trans->dbg.dest_tlv->wrap_count);
 	} else {
 		write_ptr_addr = MON_BUFF_WRPTR;
 		wrap_cnt_addr = MON_BUFF_CYCLE_CNT;
 	}
 
 	if (unlikely(!trans->dbg.rec_on))
 		return 0;
 
 	mutex_lock(&data->mutex);
 	if (data->state ==
 	    IWL_FW_MON_DBGFS_STATE_DISABLED) {
 		mutex_unlock(&data->mutex);
 		return 0;
 	}
 
 	/* write_ptr position in bytes rather then DW */
 	write_ptr = iwl_read_prph(trans, write_ptr_addr) * sizeof(u32);
 	wrap_cnt = iwl_read_prph(trans, wrap_cnt_addr);
 
 	if (data->prev_wrap_cnt == wrap_cnt) {
 		size = write_ptr - data->prev_wr_ptr;
 		curr_buf = cpu_addr + data->prev_wr_ptr;
 		b_full = iwl_write_to_user_buf(user_buf, count,
 					       curr_buf, &size,
 					       &bytes_copied);
 		data->prev_wr_ptr += size;
 
 	} else if (data->prev_wrap_cnt == wrap_cnt - 1 &&
 		   write_ptr < data->prev_wr_ptr) {
 		size = trans->dbg.fw_mon.size - data->prev_wr_ptr;
 		curr_buf = cpu_addr + data->prev_wr_ptr;
 		b_full = iwl_write_to_user_buf(user_buf, count,
 					       curr_buf, &size,
 					       &bytes_copied);
 		data->prev_wr_ptr += size;
 
 		if (!b_full) {
 			size = write_ptr;
 			b_full = iwl_write_to_user_buf(user_buf, count,
 						       cpu_addr, &size,
 						       &bytes_copied);
 			data->prev_wr_ptr = size;
 			data->prev_wrap_cnt++;
 		}
 	} else {
 		if (data->prev_wrap_cnt == wrap_cnt - 1 &&
 		    write_ptr > data->prev_wr_ptr)
 			IWL_WARN(trans,
 				 "write pointer passed previous write pointer, start copying from the beginning\n");
 		else if (!unlikely(data->prev_wrap_cnt == 0 &&
 				   data->prev_wr_ptr == 0))
 			IWL_WARN(trans,
 				 "monitor data is out of sync, start copying from the beginning\n");
 
 		size = write_ptr;
 		b_full = iwl_write_to_user_buf(user_buf, count,
 					       cpu_addr, &size,
 					       &bytes_copied);
 		data->prev_wr_ptr = size;
 		data->prev_wrap_cnt = wrap_cnt;
 	}
 
 	mutex_unlock(&data->mutex);
 
 	return bytes_copied;
 }
 
 static ssize_t iwl_dbgfs_rf_read(struct file *file,
 				 char __user *user_buf,
 				 size_t count, loff_t *ppos)
 {
 	struct iwl_trans *trans = file->private_data;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	if (!trans_pcie->rf_name[0])
 		return -ENODEV;
 
 	return simple_read_from_buffer(user_buf, count, ppos,
 				       trans_pcie->rf_name,
 				       strlen(trans_pcie->rf_name));
 }
 
 DEBUGFS_READ_WRITE_FILE_OPS(interrupt);
 DEBUGFS_READ_FILE_OPS(fh_reg);
 DEBUGFS_READ_FILE_OPS(rx_queue);
 DEBUGFS_WRITE_FILE_OPS(csr);
 DEBUGFS_READ_WRITE_FILE_OPS(rfkill);
 DEBUGFS_READ_FILE_OPS(rf);
 
 static const struct file_operations iwl_dbgfs_tx_queue_ops = {
 	.owner = THIS_MODULE,
 	.open = iwl_dbgfs_tx_queue_open,
 	.read = seq_read,
 	.llseek = seq_lseek,
 	.release = seq_release_private,
 };
 
 static const struct file_operations iwl_dbgfs_monitor_data_ops = {
 	.read = iwl_dbgfs_monitor_data_read,
 	.open = iwl_dbgfs_monitor_data_open,
 	.release = iwl_dbgfs_monitor_data_release,
 };
 
 /* Create the debugfs files and directories */
 void iwl_trans_pcie_dbgfs_register(struct iwl_trans *trans)
 {
 	struct dentry *dir = trans->dbgfs_dir;
 
 	DEBUGFS_ADD_FILE(rx_queue, dir, 0400);
 	DEBUGFS_ADD_FILE(tx_queue, dir, 0400);
 	DEBUGFS_ADD_FILE(interrupt, dir, 0600);
 	DEBUGFS_ADD_FILE(csr, dir, 0200);
 	DEBUGFS_ADD_FILE(fh_reg, dir, 0400);
 	DEBUGFS_ADD_FILE(rfkill, dir, 0600);
 	DEBUGFS_ADD_FILE(monitor_data, dir, 0400);
 	DEBUGFS_ADD_FILE(rf, dir, 0400);
 }
 
 static void iwl_trans_pcie_debugfs_cleanup(struct iwl_trans *trans)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	struct cont_rec *data = &trans_pcie->fw_mon_data;
 
 	mutex_lock(&data->mutex);
 	data->state = IWL_FW_MON_DBGFS_STATE_DISABLED;
 	mutex_unlock(&data->mutex);
 }
 #endif /*CONFIG_IWLWIFI_DEBUGFS */
 
 static u32 iwl_trans_pcie_get_cmdlen(struct iwl_trans *trans, void *tfd)
 {
 	u32 cmdlen = 0;
 	int i;
 
 	for (i = 0; i < trans->txqs.tfd.max_tbs; i++)
 		cmdlen += iwl_txq_gen1_tfd_tb_get_len(trans, tfd, i);
 
 	return cmdlen;
 }
 
 static u32 iwl_trans_pcie_dump_rbs(struct iwl_trans *trans,
 				   struct iwl_fw_error_dump_data **data,
 				   int allocated_rb_nums)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int max_len = trans_pcie->rx_buf_bytes;
 	/* Dump RBs is supported only for pre-9000 devices (1 queue) */
 	struct iwl_rxq *rxq = &trans_pcie->rxq[0];
 	u32 i, r, j, rb_len = 0;
 
 	spin_lock(&rxq->lock);
 
 	r = le16_to_cpu(iwl_get_closed_rb_stts(trans, rxq)) & 0x0FFF;
 
 	for (i = rxq->read, j = 0;
 	     i != r && j < allocated_rb_nums;
 	     i = (i + 1) & RX_QUEUE_MASK, j++) {
 		struct iwl_rx_mem_buffer *rxb = rxq->queue[i];
 		struct iwl_fw_error_dump_rb *rb;
 
 		dma_sync_single_for_cpu(trans->dev, rxb->page_dma,
 					max_len, DMA_FROM_DEVICE);
 
 		rb_len += sizeof(**data) + sizeof(*rb) + max_len;
 
 		(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_RB);
 		(*data)->len = cpu_to_le32(sizeof(*rb) + max_len);
 		rb = (void *)(*data)->data;
 		rb->index = cpu_to_le32(i);
 		memcpy(rb->data, page_address(rxb->page), max_len);
 
 		*data = iwl_fw_error_next_data(*data);
 	}
 
 	spin_unlock(&rxq->lock);
 
 	return rb_len;
 }
 #define IWL_CSR_TO_DUMP (0x250)
 
 static u32 iwl_trans_pcie_dump_csr(struct iwl_trans *trans,
 				   struct iwl_fw_error_dump_data **data)
 {
 	u32 csr_len = sizeof(**data) + IWL_CSR_TO_DUMP;
 	__le32 *val;
 	int i;
 
 	(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_CSR);
 	(*data)->len = cpu_to_le32(IWL_CSR_TO_DUMP);
 	val = (void *)(*data)->data;
 
 	for (i = 0; i < IWL_CSR_TO_DUMP; i += 4)
 		*val++ = cpu_to_le32(iwl_trans_pcie_read32(trans, i));
 
 	*data = iwl_fw_error_next_data(*data);
 
 	return csr_len;
 }
 
 static u32 iwl_trans_pcie_fh_regs_dump(struct iwl_trans *trans,
 				       struct iwl_fw_error_dump_data **data)
 {
 	u32 fh_regs_len = FH_MEM_UPPER_BOUND - FH_MEM_LOWER_BOUND;
 	__le32 *val;
 	int i;
 
 	if (!iwl_trans_grab_nic_access(trans))
 		return 0;
 
 	(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_FH_REGS);
 	(*data)->len = cpu_to_le32(fh_regs_len);
 	val = (void *)(*data)->data;
 
 	if (!trans->trans_cfg->gen2)
 		for (i = FH_MEM_LOWER_BOUND; i < FH_MEM_UPPER_BOUND;
 		     i += sizeof(u32))
 			*val++ = cpu_to_le32(iwl_trans_pcie_read32(trans, i));
 	else
 		for (i = iwl_umac_prph(trans, FH_MEM_LOWER_BOUND_GEN2);
 		     i < iwl_umac_prph(trans, FH_MEM_UPPER_BOUND_GEN2);
 		     i += sizeof(u32))
 			*val++ = cpu_to_le32(iwl_trans_pcie_read_prph(trans,
 								      i));
 
 	iwl_trans_release_nic_access(trans);
 
 	*data = iwl_fw_error_next_data(*data);
 
 	return sizeof(**data) + fh_regs_len;
 }
 
 static u32
 iwl_trans_pci_dump_marbh_monitor(struct iwl_trans *trans,
 				 struct iwl_fw_error_dump_fw_mon *fw_mon_data,
 				 u32 monitor_len)
 {
 	u32 buf_size_in_dwords = (monitor_len >> 2);
 	u32 *buffer = (u32 *)fw_mon_data->data;
 	u32 i;
 
 	if (!iwl_trans_grab_nic_access(trans))
 		return 0;
 
 	iwl_write_umac_prph_no_grab(trans, MON_DMARB_RD_CTL_ADDR, 0x1);
 	for (i = 0; i < buf_size_in_dwords; i++)
 		buffer[i] = iwl_read_umac_prph_no_grab(trans,
 						       MON_DMARB_RD_DATA_ADDR);
 	iwl_write_umac_prph_no_grab(trans, MON_DMARB_RD_CTL_ADDR, 0x0);
 
 	iwl_trans_release_nic_access(trans);
 
 	return monitor_len;
 }
 
 static void
 iwl_trans_pcie_dump_pointers(struct iwl_trans *trans,
 			     struct iwl_fw_error_dump_fw_mon *fw_mon_data)
 {
 	u32 base, base_high, write_ptr, write_ptr_val, wrap_cnt;
 
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
 		base = DBGC_CUR_DBGBUF_BASE_ADDR_LSB;
 		base_high = DBGC_CUR_DBGBUF_BASE_ADDR_MSB;
 		write_ptr = DBGC_CUR_DBGBUF_STATUS;
 		wrap_cnt = DBGC_DBGBUF_WRAP_AROUND;
 	} else if (trans->dbg.dest_tlv) {
 		write_ptr = le32_to_cpu(trans->dbg.dest_tlv->write_ptr_reg);
 		wrap_cnt = le32_to_cpu(trans->dbg.dest_tlv->wrap_count);
 		base = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
 	} else {
 		base = MON_BUFF_BASE_ADDR;
 		write_ptr = MON_BUFF_WRPTR;
 		wrap_cnt = MON_BUFF_CYCLE_CNT;
 	}
 
 	write_ptr_val = iwl_read_prph(trans, write_ptr);
 	fw_mon_data->fw_mon_cycle_cnt =
 		cpu_to_le32(iwl_read_prph(trans, wrap_cnt));
 	fw_mon_data->fw_mon_base_ptr =
 		cpu_to_le32(iwl_read_prph(trans, base));
 	if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210) {
 		fw_mon_data->fw_mon_base_high_ptr =
 			cpu_to_le32(iwl_read_prph(trans, base_high));
 		write_ptr_val &= DBGC_CUR_DBGBUF_STATUS_OFFSET_MSK;
 		/* convert wrtPtr to DWs, to align with all HWs */
 		write_ptr_val >>= 2;
 	}
 	fw_mon_data->fw_mon_wr_ptr = cpu_to_le32(write_ptr_val);
 }
 
 static u32
 iwl_trans_pcie_dump_monitor(struct iwl_trans *trans,
 			    struct iwl_fw_error_dump_data **data,
 			    u32 monitor_len)
 {
 	struct iwl_dram_data *fw_mon = &trans->dbg.fw_mon;
 	u32 len = 0;
 
 	if (trans->dbg.dest_tlv ||
 	    (fw_mon->size &&
 	     (trans->trans_cfg->device_family == IWL_DEVICE_FAMILY_7000 ||
 	      trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_AX210))) {
 		struct iwl_fw_error_dump_fw_mon *fw_mon_data;
 
 		(*data)->type = cpu_to_le32(IWL_FW_ERROR_DUMP_FW_MONITOR);
 		fw_mon_data = (void *)(*data)->data;
 
 		iwl_trans_pcie_dump_pointers(trans, fw_mon_data);
 
 		len += sizeof(**data) + sizeof(*fw_mon_data);
 		if (fw_mon->size) {
 			memcpy(fw_mon_data->data, fw_mon->block, fw_mon->size);
 			monitor_len = fw_mon->size;
 		} else if (trans->dbg.dest_tlv->monitor_mode == SMEM_MODE) {
 			u32 base = le32_to_cpu(fw_mon_data->fw_mon_base_ptr);
 			/*
 			 * Update pointers to reflect actual values after
 			 * shifting
 			 */
 			if (trans->dbg.dest_tlv->version) {
 				base = (iwl_read_prph(trans, base) &
 					IWL_LDBG_M2S_BUF_BA_MSK) <<
 				       trans->dbg.dest_tlv->base_shift;
 				base *= IWL_M2S_UNIT_SIZE;
 				base += trans->cfg->smem_offset;
 			} else {
 				base = iwl_read_prph(trans, base) <<
 				       trans->dbg.dest_tlv->base_shift;
 			}
 
 			iwl_trans_read_mem(trans, base, fw_mon_data->data,
 					   monitor_len / sizeof(u32));
 		} else if (trans->dbg.dest_tlv->monitor_mode == MARBH_MODE) {
 			monitor_len =
 				iwl_trans_pci_dump_marbh_monitor(trans,
 								 fw_mon_data,
 								 monitor_len);
 		} else {
 			/* Didn't match anything - output no monitor data */
 			monitor_len = 0;
 		}
 
 		len += monitor_len;
 		(*data)->len = cpu_to_le32(monitor_len + sizeof(*fw_mon_data));
 	}
 
 	return len;
 }
 
 static int iwl_trans_get_fw_monitor_len(struct iwl_trans *trans, u32 *len)
 {
 	if (trans->dbg.fw_mon.size) {
 		*len += sizeof(struct iwl_fw_error_dump_data) +
 			sizeof(struct iwl_fw_error_dump_fw_mon) +
 			trans->dbg.fw_mon.size;
 		return trans->dbg.fw_mon.size;
 	} else if (trans->dbg.dest_tlv) {
 		u32 base, end, cfg_reg, monitor_len;
 
 		if (trans->dbg.dest_tlv->version == 1) {
 			cfg_reg = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
 			cfg_reg = iwl_read_prph(trans, cfg_reg);
 			base = (cfg_reg & IWL_LDBG_M2S_BUF_BA_MSK) <<
 				trans->dbg.dest_tlv->base_shift;
 			base *= IWL_M2S_UNIT_SIZE;
 			base += trans->cfg->smem_offset;
 
 			monitor_len =
 				(cfg_reg & IWL_LDBG_M2S_BUF_SIZE_MSK) >>
 				trans->dbg.dest_tlv->end_shift;
 			monitor_len *= IWL_M2S_UNIT_SIZE;
 		} else {
 			base = le32_to_cpu(trans->dbg.dest_tlv->base_reg);
 			end = le32_to_cpu(trans->dbg.dest_tlv->end_reg);
 
 			base = iwl_read_prph(trans, base) <<
 			       trans->dbg.dest_tlv->base_shift;
 			end = iwl_read_prph(trans, end) <<
 			      trans->dbg.dest_tlv->end_shift;
 
 			/* Make "end" point to the actual end */
 			if (trans->trans_cfg->device_family >=
 			    IWL_DEVICE_FAMILY_8000 ||
 			    trans->dbg.dest_tlv->monitor_mode == MARBH_MODE)
 				end += (1 << trans->dbg.dest_tlv->end_shift);
 			monitor_len = end - base;
 		}
 		*len += sizeof(struct iwl_fw_error_dump_data) +
 			sizeof(struct iwl_fw_error_dump_fw_mon) +
 			monitor_len;
 		return monitor_len;
 	}
 	return 0;
 }
 
 static struct iwl_trans_dump_data *
 iwl_trans_pcie_dump_data(struct iwl_trans *trans,
 			 u32 dump_mask,
 			 const struct iwl_dump_sanitize_ops *sanitize_ops,
 			 void *sanitize_ctx)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	struct iwl_fw_error_dump_data *data;
 	struct iwl_txq *cmdq = trans->txqs.txq[trans->txqs.cmd.q_id];
 	struct iwl_fw_error_dump_txcmd *txcmd;
 	struct iwl_trans_dump_data *dump_data;
 	u32 len, num_rbs = 0, monitor_len = 0;
 	int i, ptr;
 	bool dump_rbs = test_bit(STATUS_FW_ERROR, &trans->status) &&
 			!trans->trans_cfg->mq_rx_supported &&
 			dump_mask & BIT(IWL_FW_ERROR_DUMP_RB);
 
 	if (!dump_mask)
 		return NULL;
 
 	/* transport dump header */
 	len = sizeof(*dump_data);
 
 	/* host commands */
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_TXCMD) && cmdq)
 		len += sizeof(*data) +
 			cmdq->n_window * (sizeof(*txcmd) +
 					  TFD_MAX_PAYLOAD_SIZE);
 
 	/* FW monitor */
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FW_MONITOR))
 		monitor_len = iwl_trans_get_fw_monitor_len(trans, &len);
 
 	/* CSR registers */
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_CSR))
 		len += sizeof(*data) + IWL_CSR_TO_DUMP;
 
 	/* FH registers */
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FH_REGS)) {
 		if (trans->trans_cfg->gen2)
 			len += sizeof(*data) +
 			       (iwl_umac_prph(trans, FH_MEM_UPPER_BOUND_GEN2) -
 				iwl_umac_prph(trans, FH_MEM_LOWER_BOUND_GEN2));
 		else
 			len += sizeof(*data) +
 			       (FH_MEM_UPPER_BOUND -
 				FH_MEM_LOWER_BOUND);
 	}
 
 	if (dump_rbs) {
 		/* Dump RBs is supported only for pre-9000 devices (1 queue) */
 		struct iwl_rxq *rxq = &trans_pcie->rxq[0];
 		/* RBs */
 		num_rbs =
 			le16_to_cpu(iwl_get_closed_rb_stts(trans, rxq))
 			& 0x0FFF;
 		num_rbs = (num_rbs - rxq->read) & RX_QUEUE_MASK;
 		len += num_rbs * (sizeof(*data) +
 				  sizeof(struct iwl_fw_error_dump_rb) +
 				  (PAGE_SIZE << trans_pcie->rx_page_order));
 	}
 
 	/* Paged memory for gen2 HW */
 	if (trans->trans_cfg->gen2 && dump_mask & BIT(IWL_FW_ERROR_DUMP_PAGING))
 		for (i = 0; i < trans->init_dram.paging_cnt; i++)
 			len += sizeof(*data) +
 			       sizeof(struct iwl_fw_error_dump_paging) +
 			       trans->init_dram.paging[i].size;
 
 	dump_data = vzalloc(len);
 	if (!dump_data)
 		return NULL;
 
 	len = 0;
 	data = (void *)dump_data->data;
 
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_TXCMD) && cmdq) {
 		u16 tfd_size = trans->txqs.tfd.size;
 
 		data->type = cpu_to_le32(IWL_FW_ERROR_DUMP_TXCMD);
 		txcmd = (void *)data->data;
 		spin_lock_bh(&cmdq->lock);
 		ptr = cmdq->write_ptr;
 		for (i = 0; i < cmdq->n_window; i++) {
 			u8 idx = iwl_txq_get_cmd_index(cmdq, ptr);
 			u8 tfdidx;
 			u32 caplen, cmdlen;
 
 			if (trans->trans_cfg->gen2)
 				tfdidx = idx;
 			else
 				tfdidx = ptr;
 
 			cmdlen = iwl_trans_pcie_get_cmdlen(trans,
 							   (u8 *)cmdq->tfds +
 							   tfd_size * tfdidx);
 			caplen = min_t(u32, TFD_MAX_PAYLOAD_SIZE, cmdlen);
 
 			if (cmdlen) {
 				len += sizeof(*txcmd) + caplen;
 				txcmd->cmdlen = cpu_to_le32(cmdlen);
 				txcmd->caplen = cpu_to_le32(caplen);
 				memcpy(txcmd->data, cmdq->entries[idx].cmd,
 				       caplen);
 				if (sanitize_ops && sanitize_ops->frob_hcmd)
 					sanitize_ops->frob_hcmd(sanitize_ctx,
 								txcmd->data,
 								caplen);
 				txcmd = (void *)((u8 *)txcmd->data + caplen);
 			}
 
 			ptr = iwl_txq_dec_wrap(trans, ptr);
 		}
 		spin_unlock_bh(&cmdq->lock);
 
 		data->len = cpu_to_le32(len);
 		len += sizeof(*data);
 		data = iwl_fw_error_next_data(data);
 	}
 
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_CSR))
 		len += iwl_trans_pcie_dump_csr(trans, &data);
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FH_REGS))
 		len += iwl_trans_pcie_fh_regs_dump(trans, &data);
 	if (dump_rbs)
 		len += iwl_trans_pcie_dump_rbs(trans, &data, num_rbs);
 
 	/* Paged memory for gen2 HW */
 	if (trans->trans_cfg->gen2 &&
 	    dump_mask & BIT(IWL_FW_ERROR_DUMP_PAGING)) {
 		for (i = 0; i < trans->init_dram.paging_cnt; i++) {
 			struct iwl_fw_error_dump_paging *paging;
 			u32 page_len = trans->init_dram.paging[i].size;
 
 			data->type = cpu_to_le32(IWL_FW_ERROR_DUMP_PAGING);
 			data->len = cpu_to_le32(sizeof(*paging) + page_len);
 			paging = (void *)data->data;
 			paging->index = cpu_to_le32(i);
 			memcpy(paging->data,
 			       trans->init_dram.paging[i].block, page_len);
 			data = iwl_fw_error_next_data(data);
 
 			len += sizeof(*data) + sizeof(*paging) + page_len;
 		}
 	}
 	if (dump_mask & BIT(IWL_FW_ERROR_DUMP_FW_MONITOR))
 		len += iwl_trans_pcie_dump_monitor(trans, &data, monitor_len);
 
 	dump_data->len = len;
 
 	return dump_data;
 }
 
 static void iwl_trans_pci_interrupts(struct iwl_trans *trans, bool enable)
 {
 	if (enable)
 		iwl_enable_interrupts(trans);
 	else
 		iwl_disable_interrupts(trans);
 }
 
 static void iwl_trans_pcie_sync_nmi(struct iwl_trans *trans)
 {
 	u32 inta_addr, sw_err_bit;
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	if (trans_pcie->msix_enabled) {
 		inta_addr = CSR_MSIX_HW_INT_CAUSES_AD;
 		if (trans->trans_cfg->device_family >= IWL_DEVICE_FAMILY_BZ)
 			sw_err_bit = MSIX_HW_INT_CAUSES_REG_SW_ERR_BZ;
 		else
 			sw_err_bit = MSIX_HW_INT_CAUSES_REG_SW_ERR;
 	} else {
 		inta_addr = CSR_INT;
 		sw_err_bit = CSR_INT_BIT_SW_ERR;
 	}
 
 	iwl_trans_sync_nmi_with_addr(trans, inta_addr, sw_err_bit);
 }
 
 #define IWL_TRANS_COMMON_OPS						\
 	.op_mode_leave = iwl_trans_pcie_op_mode_leave,			\
 	.write8 = iwl_trans_pcie_write8,				\
 	.write32 = iwl_trans_pcie_write32,				\
 	.read32 = iwl_trans_pcie_read32,				\
 	.read_prph = iwl_trans_pcie_read_prph,				\
 	.write_prph = iwl_trans_pcie_write_prph,			\
 	.read_mem = iwl_trans_pcie_read_mem,				\
 	.write_mem = iwl_trans_pcie_write_mem,				\
 	.read_config32 = iwl_trans_pcie_read_config32,			\
 	.configure = iwl_trans_pcie_configure,				\
 	.set_pmi = iwl_trans_pcie_set_pmi,				\
 	.sw_reset = iwl_trans_pcie_sw_reset,				\
 	.grab_nic_access = iwl_trans_pcie_grab_nic_access,		\
 	.release_nic_access = iwl_trans_pcie_release_nic_access,	\
 	.set_bits_mask = iwl_trans_pcie_set_bits_mask,			\
 	.dump_data = iwl_trans_pcie_dump_data,				\
 	.d3_suspend = iwl_trans_pcie_d3_suspend,			\
 	.d3_resume = iwl_trans_pcie_d3_resume,				\
 	.interrupts = iwl_trans_pci_interrupts,				\
 	.sync_nmi = iwl_trans_pcie_sync_nmi,				\
 	.imr_dma_data = iwl_trans_pcie_copy_imr				\
 
 static const struct iwl_trans_ops trans_ops_pcie = {
 	IWL_TRANS_COMMON_OPS,
 	.start_hw = iwl_trans_pcie_start_hw,
 	.fw_alive = iwl_trans_pcie_fw_alive,
 	.start_fw = iwl_trans_pcie_start_fw,
 	.stop_device = iwl_trans_pcie_stop_device,
 
 	.send_cmd = iwl_pcie_enqueue_hcmd,
 
 	.tx = iwl_trans_pcie_tx,
 	.reclaim = iwl_txq_reclaim,
 
 	.txq_disable = iwl_trans_pcie_txq_disable,
 	.txq_enable = iwl_trans_pcie_txq_enable,
 
 	.txq_set_shared_mode = iwl_trans_pcie_txq_set_shared_mode,
 
 	.wait_tx_queues_empty = iwl_trans_pcie_wait_txqs_empty,
 
 	.freeze_txq_timer = iwl_trans_txq_freeze_timer,
 	.block_txq_ptrs = iwl_trans_pcie_block_txq_ptrs,
 #ifdef CONFIG_IWLWIFI_DEBUGFS
 	.debugfs_cleanup = iwl_trans_pcie_debugfs_cleanup,
 #endif
 };
 
 static const struct iwl_trans_ops trans_ops_pcie_gen2 = {
 	IWL_TRANS_COMMON_OPS,
 	.start_hw = iwl_trans_pcie_start_hw,
 	.fw_alive = iwl_trans_pcie_gen2_fw_alive,
 	.start_fw = iwl_trans_pcie_gen2_start_fw,
 	.stop_device = iwl_trans_pcie_gen2_stop_device,
 
 	.send_cmd = iwl_pcie_gen2_enqueue_hcmd,
 
 	.tx = iwl_txq_gen2_tx,
 	.reclaim = iwl_txq_reclaim,
 
 	.set_q_ptrs = iwl_txq_set_q_ptrs,
 
 	.txq_alloc = iwl_txq_dyn_alloc,
 	.txq_free = iwl_txq_dyn_free,
 	.wait_txq_empty = iwl_trans_pcie_wait_txq_empty,
 	.rxq_dma_data = iwl_trans_pcie_rxq_dma_data,
 	.load_pnvm = iwl_trans_pcie_ctx_info_gen3_load_pnvm,
 	.set_pnvm = iwl_trans_pcie_ctx_info_gen3_set_pnvm,
 	.load_reduce_power = iwl_trans_pcie_ctx_info_gen3_load_reduce_power,
 	.set_reduce_power = iwl_trans_pcie_ctx_info_gen3_set_reduce_power,
 #ifdef CONFIG_IWLWIFI_DEBUGFS
 	.debugfs_cleanup = iwl_trans_pcie_debugfs_cleanup,
 #endif
 };
 
 struct iwl_trans *iwl_trans_pcie_alloc(struct pci_dev *pdev,
 			       const struct pci_device_id *ent,
 			       const struct iwl_cfg_trans_params *cfg_trans)
 {
 	struct iwl_trans_pcie *trans_pcie;
 	struct iwl_trans *trans;
 	int ret, addr_size;
 	const struct iwl_trans_ops *ops = &trans_ops_pcie_gen2;
 	void __iomem * const *table;
 
 	if (!cfg_trans->gen2)
 		ops = &trans_ops_pcie;
 
 	ret = pcim_enable_device(pdev);
 	if (ret)
 		return ERR_PTR(ret);
 
 	trans = iwl_trans_alloc(sizeof(struct iwl_trans_pcie), &pdev->dev, ops,
 				cfg_trans);
 	if (!trans)
 		return ERR_PTR(-ENOMEM);
 
 	trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 
 	trans_pcie->trans = trans;
 	trans_pcie->opmode_down = true;
 	spin_lock_init(&trans_pcie->irq_lock);
 	spin_lock_init(&trans_pcie->reg_lock);
 	spin_lock_init(&trans_pcie->alloc_page_lock);
 	mutex_init(&trans_pcie->mutex);
 	init_waitqueue_head(&trans_pcie->ucode_write_waitq);
 	init_waitqueue_head(&trans_pcie->fw_reset_waitq);
 	init_waitqueue_head(&trans_pcie->imr_waitq);
 
 	trans_pcie->rba.alloc_wq = alloc_workqueue("rb_allocator",
 						   WQ_HIGHPRI | WQ_UNBOUND, 0);
 	if (!trans_pcie->rba.alloc_wq) {
 		ret = -ENOMEM;
 		goto out_free_trans;
 	}
 	INIT_WORK(&trans_pcie->rba.rx_alloc, iwl_pcie_rx_allocator_work);
 
 	trans_pcie->debug_rfkill = -1;
 
 	if (!cfg_trans->base_params->pcie_l1_allowed) {
 		/*
 		 * W/A - seems to solve weird behavior. We need to remove this
 		 * if we don't want to stay in L1 all the time. This wastes a
 		 * lot of power.
 		 */
 		pci_disable_link_state(pdev, PCIE_LINK_STATE_L0S |
 				       PCIE_LINK_STATE_L1 |
 				       PCIE_LINK_STATE_CLKPM);
 	}
 
 	trans_pcie->def_rx_queue = 0;
 
 	pci_set_master(pdev);
 
 	addr_size = trans->txqs.tfd.addr_size;
 	ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(addr_size));
 	if (ret) {
 		ret = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
 		/* both attempts failed: */
 		if (ret) {
 			dev_err(&pdev->dev, "No suitable DMA available\n");
 			goto out_no_pci;
 		}
 	}
 
 	ret = pcim_iomap_regions_request_all(pdev, BIT(0), DRV_NAME);
 	if (ret) {
 		dev_err(&pdev->dev, "pcim_iomap_regions_request_all failed\n");
 		goto out_no_pci;
 	}
 
 #if defined(__FreeBSD__)
 	linuxkpi_pcim_want_to_use_bus_functions(pdev);
 #endif
 	table = pcim_iomap_table(pdev);
 	if (!table) {
 		dev_err(&pdev->dev, "pcim_iomap_table failed\n");
 		ret = -ENOMEM;
 		goto out_no_pci;
 	}
 
 	trans_pcie->hw_base = table[0];
 	if (!trans_pcie->hw_base) {
 		dev_err(&pdev->dev, "couldn't find IO mem in first BAR\n");
 		ret = -ENODEV;
 		goto out_no_pci;
 	}
 
 	/* We disable the RETRY_TIMEOUT register (0x41) to keep
 	 * PCI Tx retries from interfering with C3 CPU state */
 	pci_write_config_byte(pdev, PCI_CFG_RETRY_TIMEOUT, 0x00);
 
 	trans_pcie->pci_dev = pdev;
 	iwl_disable_interrupts(trans);
 
 	trans->hw_rev = iwl_read32(trans, CSR_HW_REV);
 	if (trans->hw_rev == 0xffffffff) {
 		dev_err(&pdev->dev, "HW_REV=0xFFFFFFFF, PCI issues?\n");
 		ret = -EIO;
 		goto out_no_pci;
 	}
 
 	/*
 	 * In the 8000 HW family the format of the 4 bytes of CSR_HW_REV have
 	 * changed, and now the revision step also includes bit 0-1 (no more
 	 * "dash" value). To keep hw_rev backwards compatible - we'll store it
 	 * in the old format.
 	 */
 	if (cfg_trans->device_family >= IWL_DEVICE_FAMILY_8000)
 		trans->hw_rev_step = trans->hw_rev & 0xF;
 	else
 		trans->hw_rev_step = (trans->hw_rev & 0xC) >> 2;
 
 	IWL_DEBUG_INFO(trans, "HW REV: 0x%0x\n", trans->hw_rev);
 
 	iwl_pcie_set_interrupt_capa(pdev, trans, cfg_trans);
 	trans->hw_id = (pdev->device << 16) + pdev->subsystem_device;
 	snprintf(trans->hw_id_str, sizeof(trans->hw_id_str),
 		 "PCI ID: 0x%04X:0x%04X", pdev->device, pdev->subsystem_device);
 
 	init_waitqueue_head(&trans_pcie->sx_waitq);
 
 
 	if (trans_pcie->msix_enabled) {
 		ret = iwl_pcie_init_msix_handler(pdev, trans_pcie);
 		if (ret)
 			goto out_no_pci;
 	 } else {
 		ret = iwl_pcie_alloc_ict(trans);
 		if (ret)
 			goto out_no_pci;
 
 		ret = devm_request_threaded_irq(&pdev->dev, pdev->irq,
 						iwl_pcie_isr,
 						iwl_pcie_irq_handler,
 						IRQF_SHARED, DRV_NAME, trans);
 		if (ret) {
 			IWL_ERR(trans, "Error allocating IRQ %d\n", pdev->irq);
 			goto out_free_ict;
 		}
 	 }
 
 #ifdef CONFIG_IWLWIFI_DEBUGFS
 	trans_pcie->fw_mon_data.state = IWL_FW_MON_DBGFS_STATE_CLOSED;
 	mutex_init(&trans_pcie->fw_mon_data.mutex);
 #endif
 
 	iwl_dbg_tlv_init(trans);
 
 	return trans;
 
 out_free_ict:
 	iwl_pcie_free_ict(trans);
 out_no_pci:
 	destroy_workqueue(trans_pcie->rba.alloc_wq);
 out_free_trans:
 	iwl_trans_free(trans);
 	return ERR_PTR(ret);
 }
 
 void iwl_trans_pcie_copy_imr_fh(struct iwl_trans *trans,
 				u32 dst_addr, u64 src_addr, u32 byte_cnt)
 {
 	iwl_write_prph(trans, IMR_UREG_CHICK,
 		       iwl_read_prph(trans, IMR_UREG_CHICK) |
 		       IMR_UREG_CHICK_HALT_UMAC_PERMANENTLY_MSK);
 	iwl_write_prph(trans, IMR_TFH_SRV_DMA_CHNL0_SRAM_ADDR, dst_addr);
 	iwl_write_prph(trans, IMR_TFH_SRV_DMA_CHNL0_DRAM_ADDR_LSB,
 		       (u32)(src_addr & 0xFFFFFFFF));
 	iwl_write_prph(trans, IMR_TFH_SRV_DMA_CHNL0_DRAM_ADDR_MSB,
 		       iwl_get_dma_hi_addr(src_addr));
 	iwl_write_prph(trans, IMR_TFH_SRV_DMA_CHNL0_BC, byte_cnt);
 	iwl_write_prph(trans, IMR_TFH_SRV_DMA_CHNL0_CTRL,
 		       IMR_TFH_SRV_DMA_CHNL0_CTRL_D2S_IRQ_TARGET_POS |
 		       IMR_TFH_SRV_DMA_CHNL0_CTRL_D2S_DMA_EN_POS |
 		       IMR_TFH_SRV_DMA_CHNL0_CTRL_D2S_RS_MSK);
 }
 
 int iwl_trans_pcie_copy_imr(struct iwl_trans *trans,
 			    u32 dst_addr, u64 src_addr, u32 byte_cnt)
 {
 	struct iwl_trans_pcie *trans_pcie = IWL_TRANS_GET_PCIE_TRANS(trans);
 	int ret = -1;
 
 	trans_pcie->imr_status = IMR_D2S_REQUESTED;
 	iwl_trans_pcie_copy_imr_fh(trans, dst_addr, src_addr, byte_cnt);
 	ret = wait_event_timeout(trans_pcie->imr_waitq,
 				 trans_pcie->imr_status !=
 				 IMR_D2S_REQUESTED, 5 * HZ);
 	if (!ret || trans_pcie->imr_status == IMR_D2S_ERROR) {
 		IWL_ERR(trans, "Failed to copy IMR Memory chunk!\n");
 		iwl_trans_pcie_dump_regs(trans);
 		return -ETIMEDOUT;
 	}
 	trans_pcie->imr_status = IMR_D2S_IDLE;
 	return 0;
 }
diff --git a/sys/contrib/dev/rtw88/pci.c b/sys/contrib/dev/rtw88/pci.c
index d3980e0e97c4..7554bac4902a 100644
--- a/sys/contrib/dev/rtw88/pci.c
+++ b/sys/contrib/dev/rtw88/pci.c
@@ -1,1918 +1,1919 @@
 // SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
 /* Copyright(c) 2018-2019  Realtek Corporation
  */
 
 #if defined(__FreeBSD__)
 #define	LINUXKPI_PARAM_PREFIX	rtw88_pci_
 #endif
 
 #include <linux/module.h>
 #include <linux/pci.h>
 #include "main.h"
 #include "pci.h"
 #include "reg.h"
 #include "tx.h"
 #include "rx.h"
 #include "fw.h"
 #include "ps.h"
 #include "debug.h"
 #if defined(__FreeBSD__)
+#include <sys/rman.h>
 #include <linux/pm.h>
 #endif
 
 static bool rtw_disable_msi;
 static bool rtw_pci_disable_aspm;
 module_param_named(disable_msi, rtw_disable_msi, bool, 0644);
 module_param_named(disable_aspm, rtw_pci_disable_aspm, bool, 0644);
 MODULE_PARM_DESC(disable_msi, "Set Y to disable MSI interrupt support");
 MODULE_PARM_DESC(disable_aspm, "Set Y to disable PCI ASPM support");
 
 static u32 rtw_pci_tx_queue_idx_addr[] = {
 	[RTW_TX_QUEUE_BK]	= RTK_PCI_TXBD_IDX_BKQ,
 	[RTW_TX_QUEUE_BE]	= RTK_PCI_TXBD_IDX_BEQ,
 	[RTW_TX_QUEUE_VI]	= RTK_PCI_TXBD_IDX_VIQ,
 	[RTW_TX_QUEUE_VO]	= RTK_PCI_TXBD_IDX_VOQ,
 	[RTW_TX_QUEUE_MGMT]	= RTK_PCI_TXBD_IDX_MGMTQ,
 	[RTW_TX_QUEUE_HI0]	= RTK_PCI_TXBD_IDX_HI0Q,
 	[RTW_TX_QUEUE_H2C]	= RTK_PCI_TXBD_IDX_H2CQ,
 };
 
 static u8 rtw_pci_get_tx_qsel(struct sk_buff *skb,
 			      enum rtw_tx_queue_type queue)
 {
 	switch (queue) {
 	case RTW_TX_QUEUE_BCN:
 		return TX_DESC_QSEL_BEACON;
 	case RTW_TX_QUEUE_H2C:
 		return TX_DESC_QSEL_H2C;
 	case RTW_TX_QUEUE_MGMT:
 		return TX_DESC_QSEL_MGMT;
 	case RTW_TX_QUEUE_HI0:
 		return TX_DESC_QSEL_HIGH;
 	default:
 		return skb->priority;
 	}
 };
 
 static u8 rtw_pci_read8(struct rtw_dev *rtwdev, u32 addr)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	return readb(rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	u8 val;
 
 	val = bus_read_1((struct resource *)rtwpci->mmap, addr);
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "R08 (%#010x) -> %#04x\n", addr, val);
 	return (val);
 #endif
 }
 
 static u16 rtw_pci_read16(struct rtw_dev *rtwdev, u32 addr)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	return readw(rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	u16 val;
 
 	val = bus_read_2((struct resource *)rtwpci->mmap, addr);
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "R16 (%#010x) -> %#06x\n", addr, val);
 	return (val);
 #endif
 }
 
 static u32 rtw_pci_read32(struct rtw_dev *rtwdev, u32 addr)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	return readl(rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	u32 val;
 
 	val = bus_read_4((struct resource *)rtwpci->mmap, addr);
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "R32 (%#010x) -> %#010x\n", addr, val);
 	return (val);
 #endif
 }
 
 static void rtw_pci_write8(struct rtw_dev *rtwdev, u32 addr, u8 val)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	writeb(val, rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "W08 (%#010x) <- %#04x\n", addr, val);
 	return (bus_write_1((struct resource *)rtwpci->mmap, addr, val));
 #endif
 }
 
 static void rtw_pci_write16(struct rtw_dev *rtwdev, u32 addr, u16 val)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	writew(val, rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "W16 (%#010x) <- %#06x\n", addr, val);
 	return (bus_write_2((struct resource *)rtwpci->mmap, addr, val));
 #endif
 }
 
 static void rtw_pci_write32(struct rtw_dev *rtwdev, u32 addr, u32 val)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 #if defined(__linux__)
 	writel(val, rtwpci->mmap + addr);
 #elif defined(__FreeBSD__)
 	rtw_dbg(rtwdev, RTW_DBG_IO_RW, "W32 (%#010x) <- %#010x\n", addr, val);
 	return (bus_write_4((struct resource *)rtwpci->mmap, addr, val));
 #endif
 }
 
 static void rtw_pci_free_tx_ring_skbs(struct rtw_dev *rtwdev,
 				      struct rtw_pci_tx_ring *tx_ring)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	struct rtw_pci_tx_data *tx_data;
 	struct sk_buff *skb, *tmp;
 	dma_addr_t dma;
 
 	/* free every skb remained in tx list */
 	skb_queue_walk_safe(&tx_ring->queue, skb, tmp) {
 		__skb_unlink(skb, &tx_ring->queue);
 		tx_data = rtw_pci_get_tx_data(skb);
 		dma = tx_data->dma;
 
 		dma_unmap_single(&pdev->dev, dma, skb->len, DMA_TO_DEVICE);
 		dev_kfree_skb_any(skb);
 	}
 }
 
 static void rtw_pci_free_tx_ring(struct rtw_dev *rtwdev,
 				 struct rtw_pci_tx_ring *tx_ring)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	u8 *head = tx_ring->r.head;
 	u32 len = tx_ring->r.len;
 	int ring_sz = len * tx_ring->r.desc_size;
 
 	rtw_pci_free_tx_ring_skbs(rtwdev, tx_ring);
 
 	/* free the ring itself */
 	dma_free_coherent(&pdev->dev, ring_sz, head, tx_ring->r.dma);
 	tx_ring->r.head = NULL;
 }
 
 static void rtw_pci_free_rx_ring_skbs(struct rtw_dev *rtwdev,
 				      struct rtw_pci_rx_ring *rx_ring)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	struct sk_buff *skb;
 	int buf_sz = RTK_PCI_RX_BUF_SIZE;
 	dma_addr_t dma;
 	int i;
 
 	for (i = 0; i < rx_ring->r.len; i++) {
 		skb = rx_ring->buf[i];
 		if (!skb)
 			continue;
 
 		dma = *((dma_addr_t *)skb->cb);
 		dma_unmap_single(&pdev->dev, dma, buf_sz, DMA_FROM_DEVICE);
 		dev_kfree_skb(skb);
 		rx_ring->buf[i] = NULL;
 	}
 }
 
 static void rtw_pci_free_rx_ring(struct rtw_dev *rtwdev,
 				 struct rtw_pci_rx_ring *rx_ring)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	u8 *head = rx_ring->r.head;
 	int ring_sz = rx_ring->r.desc_size * rx_ring->r.len;
 
 	rtw_pci_free_rx_ring_skbs(rtwdev, rx_ring);
 
 	dma_free_coherent(&pdev->dev, ring_sz, head, rx_ring->r.dma);
 }
 
 static void rtw_pci_free_trx_ring(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *tx_ring;
 	struct rtw_pci_rx_ring *rx_ring;
 	int i;
 
 	for (i = 0; i < RTK_MAX_TX_QUEUE_NUM; i++) {
 		tx_ring = &rtwpci->tx_rings[i];
 		rtw_pci_free_tx_ring(rtwdev, tx_ring);
 	}
 
 	for (i = 0; i < RTK_MAX_RX_QUEUE_NUM; i++) {
 		rx_ring = &rtwpci->rx_rings[i];
 		rtw_pci_free_rx_ring(rtwdev, rx_ring);
 	}
 }
 
 static int rtw_pci_init_tx_ring(struct rtw_dev *rtwdev,
 				struct rtw_pci_tx_ring *tx_ring,
 				u8 desc_size, u32 len)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	int ring_sz = desc_size * len;
 	dma_addr_t dma;
 	u8 *head;
 
 	if (len > TRX_BD_IDX_MASK) {
 		rtw_err(rtwdev, "len %d exceeds maximum TX entries\n", len);
 		return -EINVAL;
 	}
 
 	head = dma_alloc_coherent(&pdev->dev, ring_sz, &dma, GFP_KERNEL);
 	if (!head) {
 		rtw_err(rtwdev, "failed to allocate tx ring\n");
 		return -ENOMEM;
 	}
 
 	skb_queue_head_init(&tx_ring->queue);
 	tx_ring->r.head = head;
 	tx_ring->r.dma = dma;
 	tx_ring->r.len = len;
 	tx_ring->r.desc_size = desc_size;
 	tx_ring->r.wp = 0;
 	tx_ring->r.rp = 0;
 
 	return 0;
 }
 
 static int rtw_pci_reset_rx_desc(struct rtw_dev *rtwdev, struct sk_buff *skb,
 				 struct rtw_pci_rx_ring *rx_ring,
 				 u32 idx, u32 desc_sz)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	struct rtw_pci_rx_buffer_desc *buf_desc;
 	int buf_sz = RTK_PCI_RX_BUF_SIZE;
 	dma_addr_t dma;
 
 	if (!skb)
 		return -EINVAL;
 
 	dma = dma_map_single(&pdev->dev, skb->data, buf_sz, DMA_FROM_DEVICE);
 	if (dma_mapping_error(&pdev->dev, dma))
 		return -EBUSY;
 
 	*((dma_addr_t *)skb->cb) = dma;
 	buf_desc = (struct rtw_pci_rx_buffer_desc *)(rx_ring->r.head +
 						     idx * desc_sz);
 	memset(buf_desc, 0, sizeof(*buf_desc));
 	buf_desc->buf_size = cpu_to_le16(RTK_PCI_RX_BUF_SIZE);
 	buf_desc->dma = cpu_to_le32(dma);
 
 	return 0;
 }
 
 static void rtw_pci_sync_rx_desc_device(struct rtw_dev *rtwdev, dma_addr_t dma,
 					struct rtw_pci_rx_ring *rx_ring,
 					u32 idx, u32 desc_sz)
 {
 	struct device *dev = rtwdev->dev;
 	struct rtw_pci_rx_buffer_desc *buf_desc;
 	int buf_sz = RTK_PCI_RX_BUF_SIZE;
 
 	dma_sync_single_for_device(dev, dma, buf_sz, DMA_FROM_DEVICE);
 
 	buf_desc = (struct rtw_pci_rx_buffer_desc *)(rx_ring->r.head +
 						     idx * desc_sz);
 	memset(buf_desc, 0, sizeof(*buf_desc));
 	buf_desc->buf_size = cpu_to_le16(RTK_PCI_RX_BUF_SIZE);
 	buf_desc->dma = cpu_to_le32(dma);
 }
 
 static int rtw_pci_init_rx_ring(struct rtw_dev *rtwdev,
 				struct rtw_pci_rx_ring *rx_ring,
 				u8 desc_size, u32 len)
 {
 	struct pci_dev *pdev = to_pci_dev(rtwdev->dev);
 	struct sk_buff *skb = NULL;
 	dma_addr_t dma;
 	u8 *head;
 	int ring_sz = desc_size * len;
 	int buf_sz = RTK_PCI_RX_BUF_SIZE;
 	int i, allocated;
 	int ret = 0;
 
 	head = dma_alloc_coherent(&pdev->dev, ring_sz, &dma, GFP_KERNEL);
 	if (!head) {
 		rtw_err(rtwdev, "failed to allocate rx ring\n");
 		return -ENOMEM;
 	}
 	rx_ring->r.head = head;
 
 	for (i = 0; i < len; i++) {
 		skb = dev_alloc_skb(buf_sz);
 		if (!skb) {
 			allocated = i;
 			ret = -ENOMEM;
 			goto err_out;
 		}
 
 		memset(skb->data, 0, buf_sz);
 		rx_ring->buf[i] = skb;
 		ret = rtw_pci_reset_rx_desc(rtwdev, skb, rx_ring, i, desc_size);
 		if (ret) {
 			allocated = i;
 			dev_kfree_skb_any(skb);
 			goto err_out;
 		}
 	}
 
 	rx_ring->r.dma = dma;
 	rx_ring->r.len = len;
 	rx_ring->r.desc_size = desc_size;
 	rx_ring->r.wp = 0;
 	rx_ring->r.rp = 0;
 
 	return 0;
 
 err_out:
 	for (i = 0; i < allocated; i++) {
 		skb = rx_ring->buf[i];
 		if (!skb)
 			continue;
 		dma = *((dma_addr_t *)skb->cb);
 		dma_unmap_single(&pdev->dev, dma, buf_sz, DMA_FROM_DEVICE);
 		dev_kfree_skb_any(skb);
 		rx_ring->buf[i] = NULL;
 	}
 	dma_free_coherent(&pdev->dev, ring_sz, head, dma);
 
 	rtw_err(rtwdev, "failed to init rx buffer\n");
 
 	return ret;
 }
 
 static int rtw_pci_init_trx_ring(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *tx_ring;
 	struct rtw_pci_rx_ring *rx_ring;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	int i = 0, j = 0, tx_alloced = 0, rx_alloced = 0;
 	int tx_desc_size, rx_desc_size;
 	u32 len;
 	int ret;
 
 	tx_desc_size = chip->tx_buf_desc_sz;
 
 	for (i = 0; i < RTK_MAX_TX_QUEUE_NUM; i++) {
 		tx_ring = &rtwpci->tx_rings[i];
 		len = max_num_of_tx_queue(i);
 		ret = rtw_pci_init_tx_ring(rtwdev, tx_ring, tx_desc_size, len);
 		if (ret)
 			goto out;
 	}
 
 	rx_desc_size = chip->rx_buf_desc_sz;
 
 	for (j = 0; j < RTK_MAX_RX_QUEUE_NUM; j++) {
 		rx_ring = &rtwpci->rx_rings[j];
 		ret = rtw_pci_init_rx_ring(rtwdev, rx_ring, rx_desc_size,
 					   RTK_MAX_RX_DESC_NUM);
 		if (ret)
 			goto out;
 	}
 
 	return 0;
 
 out:
 	tx_alloced = i;
 	for (i = 0; i < tx_alloced; i++) {
 		tx_ring = &rtwpci->tx_rings[i];
 		rtw_pci_free_tx_ring(rtwdev, tx_ring);
 	}
 
 	rx_alloced = j;
 	for (j = 0; j < rx_alloced; j++) {
 		rx_ring = &rtwpci->rx_rings[j];
 		rtw_pci_free_rx_ring(rtwdev, rx_ring);
 	}
 
 	return ret;
 }
 
 static void rtw_pci_deinit(struct rtw_dev *rtwdev)
 {
 	rtw_pci_free_trx_ring(rtwdev);
 }
 
 static int rtw_pci_init(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	int ret = 0;
 
 	rtwpci->irq_mask[0] = IMR_HIGHDOK |
 			      IMR_MGNTDOK |
 			      IMR_BKDOK |
 			      IMR_BEDOK |
 			      IMR_VIDOK |
 			      IMR_VODOK |
 			      IMR_ROK |
 			      IMR_BCNDMAINT_E |
 			      IMR_C2HCMD |
 			      0;
 	rtwpci->irq_mask[1] = IMR_TXFOVW |
 			      0;
 	rtwpci->irq_mask[3] = IMR_H2CDOK |
 			      0;
 	spin_lock_init(&rtwpci->irq_lock);
 	spin_lock_init(&rtwpci->hwirq_lock);
 	ret = rtw_pci_init_trx_ring(rtwdev);
 
 	return ret;
 }
 
 static void rtw_pci_reset_buf_desc(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	u32 len;
 	u8 tmp;
 	dma_addr_t dma;
 
 	tmp = rtw_read8(rtwdev, RTK_PCI_CTRL + 3);
 	rtw_write8(rtwdev, RTK_PCI_CTRL + 3, tmp | 0xf7);
 
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_BCN].r.dma;
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_BCNQ, dma);
 
 	if (!rtw_chip_wcpu_11n(rtwdev)) {
 		len = rtwpci->tx_rings[RTW_TX_QUEUE_H2C].r.len;
 		dma = rtwpci->tx_rings[RTW_TX_QUEUE_H2C].r.dma;
 		rtwpci->tx_rings[RTW_TX_QUEUE_H2C].r.rp = 0;
 		rtwpci->tx_rings[RTW_TX_QUEUE_H2C].r.wp = 0;
 		rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_H2CQ, len & TRX_BD_IDX_MASK);
 		rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_H2CQ, dma);
 	}
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_BK].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_BK].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_BK].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_BK].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_BKQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_BKQ, dma);
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_BE].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_BE].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_BE].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_BE].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_BEQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_BEQ, dma);
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_VO].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_VO].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_VO].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_VO].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_VOQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_VOQ, dma);
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_VI].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_VI].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_VI].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_VI].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_VIQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_VIQ, dma);
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_MGMT].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_MGMT].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_MGMT].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_MGMT].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_MGMTQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_MGMTQ, dma);
 
 	len = rtwpci->tx_rings[RTW_TX_QUEUE_HI0].r.len;
 	dma = rtwpci->tx_rings[RTW_TX_QUEUE_HI0].r.dma;
 	rtwpci->tx_rings[RTW_TX_QUEUE_HI0].r.rp = 0;
 	rtwpci->tx_rings[RTW_TX_QUEUE_HI0].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_TXBD_NUM_HI0Q, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_TXBD_DESA_HI0Q, dma);
 
 	len = rtwpci->rx_rings[RTW_RX_QUEUE_MPDU].r.len;
 	dma = rtwpci->rx_rings[RTW_RX_QUEUE_MPDU].r.dma;
 	rtwpci->rx_rings[RTW_RX_QUEUE_MPDU].r.rp = 0;
 	rtwpci->rx_rings[RTW_RX_QUEUE_MPDU].r.wp = 0;
 	rtw_write16(rtwdev, RTK_PCI_RXBD_NUM_MPDUQ, len & TRX_BD_IDX_MASK);
 	rtw_write32(rtwdev, RTK_PCI_RXBD_DESA_MPDUQ, dma);
 
 	/* reset read/write point */
 	rtw_write32(rtwdev, RTK_PCI_TXBD_RWPTR_CLR, 0xffffffff);
 
 	/* reset H2C Queue index in a single write */
 	if (rtw_chip_wcpu_11ac(rtwdev))
 		rtw_write32_set(rtwdev, RTK_PCI_TXBD_H2CQ_CSR,
 				BIT_CLR_H2CQ_HOST_IDX | BIT_CLR_H2CQ_HW_IDX);
 }
 
 static void rtw_pci_reset_trx_ring(struct rtw_dev *rtwdev)
 {
 	rtw_pci_reset_buf_desc(rtwdev);
 }
 
 static void rtw_pci_enable_interrupt(struct rtw_dev *rtwdev,
 				     struct rtw_pci *rtwpci, bool exclude_rx)
 {
 	unsigned long flags;
 	u32 imr0_unmask = exclude_rx ? IMR_ROK : 0;
 
 	spin_lock_irqsave(&rtwpci->hwirq_lock, flags);
 
 	rtw_write32(rtwdev, RTK_PCI_HIMR0, rtwpci->irq_mask[0] & ~imr0_unmask);
 	rtw_write32(rtwdev, RTK_PCI_HIMR1, rtwpci->irq_mask[1]);
 	if (rtw_chip_wcpu_11ac(rtwdev))
 		rtw_write32(rtwdev, RTK_PCI_HIMR3, rtwpci->irq_mask[3]);
 
 	rtwpci->irq_enabled = true;
 
 	spin_unlock_irqrestore(&rtwpci->hwirq_lock, flags);
 }
 
 static void rtw_pci_disable_interrupt(struct rtw_dev *rtwdev,
 				      struct rtw_pci *rtwpci)
 {
 	unsigned long flags;
 
 	spin_lock_irqsave(&rtwpci->hwirq_lock, flags);
 
 	if (!rtwpci->irq_enabled)
 		goto out;
 
 	rtw_write32(rtwdev, RTK_PCI_HIMR0, 0);
 	rtw_write32(rtwdev, RTK_PCI_HIMR1, 0);
 	if (rtw_chip_wcpu_11ac(rtwdev))
 		rtw_write32(rtwdev, RTK_PCI_HIMR3, 0);
 
 	rtwpci->irq_enabled = false;
 
 out:
 	spin_unlock_irqrestore(&rtwpci->hwirq_lock, flags);
 }
 
 static void rtw_pci_dma_reset(struct rtw_dev *rtwdev, struct rtw_pci *rtwpci)
 {
 	/* reset dma and rx tag */
 	rtw_write32_set(rtwdev, RTK_PCI_CTRL,
 			BIT_RST_TRXDMA_INTF | BIT_RX_TAG_EN);
 	rtwpci->rx_tag = 0;
 }
 
 static int rtw_pci_setup(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	rtw_pci_reset_trx_ring(rtwdev);
 	rtw_pci_dma_reset(rtwdev, rtwpci);
 
 	return 0;
 }
 
 static void rtw_pci_dma_release(struct rtw_dev *rtwdev, struct rtw_pci *rtwpci)
 {
 	struct rtw_pci_tx_ring *tx_ring;
 	enum rtw_tx_queue_type queue;
 
 	rtw_pci_reset_trx_ring(rtwdev);
 	for (queue = 0; queue < RTK_MAX_TX_QUEUE_NUM; queue++) {
 		tx_ring = &rtwpci->tx_rings[queue];
 		rtw_pci_free_tx_ring_skbs(rtwdev, tx_ring);
 	}
 }
 
 static void rtw_pci_napi_start(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	if (test_and_set_bit(RTW_PCI_FLAG_NAPI_RUNNING, rtwpci->flags))
 		return;
 
 	napi_enable(&rtwpci->napi);
 }
 
 static void rtw_pci_napi_stop(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	if (!test_and_clear_bit(RTW_PCI_FLAG_NAPI_RUNNING, rtwpci->flags))
 		return;
 
 	napi_synchronize(&rtwpci->napi);
 	napi_disable(&rtwpci->napi);
 }
 
 static int rtw_pci_start(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	rtw_pci_napi_start(rtwdev);
 
 	spin_lock_bh(&rtwpci->irq_lock);
 	rtwpci->running = true;
 	rtw_pci_enable_interrupt(rtwdev, rtwpci, false);
 	spin_unlock_bh(&rtwpci->irq_lock);
 
 	return 0;
 }
 
 static void rtw_pci_stop(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct pci_dev *pdev = rtwpci->pdev;
 
 	spin_lock_bh(&rtwpci->irq_lock);
 	rtwpci->running = false;
 	rtw_pci_disable_interrupt(rtwdev, rtwpci);
 	spin_unlock_bh(&rtwpci->irq_lock);
 
 	synchronize_irq(pdev->irq);
 	rtw_pci_napi_stop(rtwdev);
 
 	spin_lock_bh(&rtwpci->irq_lock);
 	rtw_pci_dma_release(rtwdev, rtwpci);
 	spin_unlock_bh(&rtwpci->irq_lock);
 }
 
 static void rtw_pci_deep_ps_enter(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *tx_ring;
 	enum rtw_tx_queue_type queue;
 	bool tx_empty = true;
 
 	if (rtw_fw_feature_check(&rtwdev->fw, FW_FEATURE_TX_WAKE))
 		goto enter_deep_ps;
 
 	lockdep_assert_held(&rtwpci->irq_lock);
 
 	/* Deep PS state is not allowed to TX-DMA */
 	for (queue = 0; queue < RTK_MAX_TX_QUEUE_NUM; queue++) {
 		/* BCN queue is rsvd page, does not have DMA interrupt
 		 * H2C queue is managed by firmware
 		 */
 		if (queue == RTW_TX_QUEUE_BCN ||
 		    queue == RTW_TX_QUEUE_H2C)
 			continue;
 
 		tx_ring = &rtwpci->tx_rings[queue];
 
 		/* check if there is any skb DMAing */
 		if (skb_queue_len(&tx_ring->queue)) {
 			tx_empty = false;
 			break;
 		}
 	}
 
 	if (!tx_empty) {
 		rtw_dbg(rtwdev, RTW_DBG_PS,
 			"TX path not empty, cannot enter deep power save state\n");
 		return;
 	}
 enter_deep_ps:
 	set_bit(RTW_FLAG_LEISURE_PS_DEEP, rtwdev->flags);
 	rtw_power_mode_change(rtwdev, true);
 }
 
 static void rtw_pci_deep_ps_leave(struct rtw_dev *rtwdev)
 {
 #if defined(__linux__)
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	lockdep_assert_held(&rtwpci->irq_lock);
 #elif defined(__FreeBSD__)
 	lockdep_assert_held(&((struct rtw_pci *)rtwdev->priv)->irq_lock);
 #endif
 
 	if (test_and_clear_bit(RTW_FLAG_LEISURE_PS_DEEP, rtwdev->flags))
 		rtw_power_mode_change(rtwdev, false);
 }
 
 static void rtw_pci_deep_ps(struct rtw_dev *rtwdev, bool enter)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	spin_lock_bh(&rtwpci->irq_lock);
 
 	if (enter && !test_bit(RTW_FLAG_LEISURE_PS_DEEP, rtwdev->flags))
 		rtw_pci_deep_ps_enter(rtwdev);
 
 	if (!enter && test_bit(RTW_FLAG_LEISURE_PS_DEEP, rtwdev->flags))
 		rtw_pci_deep_ps_leave(rtwdev);
 
 	spin_unlock_bh(&rtwpci->irq_lock);
 }
 
 static void rtw_pci_release_rsvd_page(struct rtw_pci *rtwpci,
 				      struct rtw_pci_tx_ring *ring)
 {
 	struct sk_buff *prev = skb_dequeue(&ring->queue);
 	struct rtw_pci_tx_data *tx_data;
 	dma_addr_t dma;
 
 	if (!prev)
 		return;
 
 	tx_data = rtw_pci_get_tx_data(prev);
 	dma = tx_data->dma;
 	dma_unmap_single(&rtwpci->pdev->dev, dma, prev->len, DMA_TO_DEVICE);
 	dev_kfree_skb_any(prev);
 }
 
 static void rtw_pci_dma_check(struct rtw_dev *rtwdev,
 			      struct rtw_pci_rx_ring *rx_ring,
 			      u32 idx)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct rtw_pci_rx_buffer_desc *buf_desc;
 	u32 desc_sz = chip->rx_buf_desc_sz;
 	u16 total_pkt_size;
 
 	buf_desc = (struct rtw_pci_rx_buffer_desc *)(rx_ring->r.head +
 						     idx * desc_sz);
 	total_pkt_size = le16_to_cpu(buf_desc->total_pkt_size);
 
 	/* rx tag mismatch, throw a warning */
 	if (total_pkt_size != rtwpci->rx_tag)
 		rtw_warn(rtwdev, "pci bus timeout, check dma status\n");
 
 	rtwpci->rx_tag = (rtwpci->rx_tag + 1) % RX_TAG_MAX;
 }
 
 static u32 __pci_get_hw_tx_ring_rp(struct rtw_dev *rtwdev, u8 pci_q)
 {
 	u32 bd_idx_addr = rtw_pci_tx_queue_idx_addr[pci_q];
 	u32 bd_idx = rtw_read16(rtwdev, bd_idx_addr + 2);
 
 	return FIELD_GET(TRX_BD_IDX_MASK, bd_idx);
 }
 
 static void __pci_flush_queue(struct rtw_dev *rtwdev, u8 pci_q, bool drop)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *ring = &rtwpci->tx_rings[pci_q];
 	u32 cur_rp;
 	u8 i;
 
 	/* Because the time taked by the I/O in __pci_get_hw_tx_ring_rp is a
 	 * bit dynamic, it's hard to define a reasonable fixed total timeout to
 	 * use read_poll_timeout* helper. Instead, we can ensure a reasonable
 	 * polling times, so we just use for loop with udelay here.
 	 */
 	for (i = 0; i < 30; i++) {
 		cur_rp = __pci_get_hw_tx_ring_rp(rtwdev, pci_q);
 		if (cur_rp == ring->r.wp)
 			return;
 
 		udelay(1);
 	}
 
 	if (!drop)
 		rtw_warn(rtwdev, "timed out to flush pci tx ring[%d]\n", pci_q);
 }
 
 static void __rtw_pci_flush_queues(struct rtw_dev *rtwdev, u32 pci_queues,
 				   bool drop)
 {
 	u8 q;
 
 	for (q = 0; q < RTK_MAX_TX_QUEUE_NUM; q++) {
 		/* Unnecessary to flush BCN, H2C and HI tx queues. */
 		if (q == RTW_TX_QUEUE_BCN || q == RTW_TX_QUEUE_H2C ||
 		    q == RTW_TX_QUEUE_HI0)
 			continue;
 
 		if (pci_queues & BIT(q))
 			__pci_flush_queue(rtwdev, q, drop);
 	}
 }
 
 static void rtw_pci_flush_queues(struct rtw_dev *rtwdev, u32 queues, bool drop)
 {
 	u32 pci_queues = 0;
 	u8 i;
 
 	/* If all of the hardware queues are requested to flush,
 	 * flush all of the pci queues.
 	 */
 	if (queues == BIT(rtwdev->hw->queues) - 1) {
 		pci_queues = BIT(RTK_MAX_TX_QUEUE_NUM) - 1;
 	} else {
 		for (i = 0; i < rtwdev->hw->queues; i++)
 			if (queues & BIT(i))
 				pci_queues |= BIT(rtw_tx_ac_to_hwq(i));
 	}
 
 	__rtw_pci_flush_queues(rtwdev, pci_queues, drop);
 }
 
 static void rtw_pci_tx_kick_off_queue(struct rtw_dev *rtwdev,
 				      enum rtw_tx_queue_type queue)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *ring;
 	u32 bd_idx;
 
 	ring = &rtwpci->tx_rings[queue];
 	bd_idx = rtw_pci_tx_queue_idx_addr[queue];
 
 	spin_lock_bh(&rtwpci->irq_lock);
 	if (!rtw_fw_feature_check(&rtwdev->fw, FW_FEATURE_TX_WAKE))
 		rtw_pci_deep_ps_leave(rtwdev);
 	rtw_write16(rtwdev, bd_idx, ring->r.wp & TRX_BD_IDX_MASK);
 	spin_unlock_bh(&rtwpci->irq_lock);
 }
 
 static void rtw_pci_tx_kick_off(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	enum rtw_tx_queue_type queue;
 
 	for (queue = 0; queue < RTK_MAX_TX_QUEUE_NUM; queue++)
 		if (test_and_clear_bit(queue, rtwpci->tx_queued))
 			rtw_pci_tx_kick_off_queue(rtwdev, queue);
 }
 
 static int rtw_pci_tx_write_data(struct rtw_dev *rtwdev,
 				 struct rtw_tx_pkt_info *pkt_info,
 				 struct sk_buff *skb,
 				 enum rtw_tx_queue_type queue)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct rtw_pci_tx_ring *ring;
 	struct rtw_pci_tx_data *tx_data;
 	dma_addr_t dma;
 	u32 tx_pkt_desc_sz = chip->tx_pkt_desc_sz;
 	u32 tx_buf_desc_sz = chip->tx_buf_desc_sz;
 	u32 size;
 	u32 psb_len;
 	u8 *pkt_desc;
 	struct rtw_pci_tx_buffer_desc *buf_desc;
 
 	ring = &rtwpci->tx_rings[queue];
 
 	size = skb->len;
 
 	if (queue == RTW_TX_QUEUE_BCN)
 		rtw_pci_release_rsvd_page(rtwpci, ring);
 	else if (!avail_desc(ring->r.wp, ring->r.rp, ring->r.len))
 		return -ENOSPC;
 
 	pkt_desc = skb_push(skb, chip->tx_pkt_desc_sz);
 	memset(pkt_desc, 0, tx_pkt_desc_sz);
 	pkt_info->qsel = rtw_pci_get_tx_qsel(skb, queue);
 	rtw_tx_fill_tx_desc(pkt_info, skb);
 	dma = dma_map_single(&rtwpci->pdev->dev, skb->data, skb->len,
 			     DMA_TO_DEVICE);
 	if (dma_mapping_error(&rtwpci->pdev->dev, dma))
 		return -EBUSY;
 
 	/* after this we got dma mapped, there is no way back */
 	buf_desc = get_tx_buffer_desc(ring, tx_buf_desc_sz);
 	memset(buf_desc, 0, tx_buf_desc_sz);
 	psb_len = (skb->len - 1) / 128 + 1;
 	if (queue == RTW_TX_QUEUE_BCN)
 		psb_len |= 1 << RTK_PCI_TXBD_OWN_OFFSET;
 
 	buf_desc[0].psb_len = cpu_to_le16(psb_len);
 	buf_desc[0].buf_size = cpu_to_le16(tx_pkt_desc_sz);
 	buf_desc[0].dma = cpu_to_le32(dma);
 	buf_desc[1].buf_size = cpu_to_le16(size);
 	buf_desc[1].dma = cpu_to_le32(dma + tx_pkt_desc_sz);
 
 	tx_data = rtw_pci_get_tx_data(skb);
 	tx_data->dma = dma;
 	tx_data->sn = pkt_info->sn;
 
 	spin_lock_bh(&rtwpci->irq_lock);
 
 	skb_queue_tail(&ring->queue, skb);
 
 	if (queue == RTW_TX_QUEUE_BCN)
 		goto out_unlock;
 
 	/* update write-index, and kick it off later */
 	set_bit(queue, rtwpci->tx_queued);
 	if (++ring->r.wp >= ring->r.len)
 		ring->r.wp = 0;
 
 out_unlock:
 	spin_unlock_bh(&rtwpci->irq_lock);
 
 	return 0;
 }
 
 static int rtw_pci_write_data_rsvd_page(struct rtw_dev *rtwdev, u8 *buf,
 					u32 size)
 {
 	struct sk_buff *skb;
 	struct rtw_tx_pkt_info pkt_info = {0};
 	u8 reg_bcn_work;
 	int ret;
 
 	skb = rtw_tx_write_data_rsvd_page_get(rtwdev, &pkt_info, buf, size);
 	if (!skb)
 		return -ENOMEM;
 
 	ret = rtw_pci_tx_write_data(rtwdev, &pkt_info, skb, RTW_TX_QUEUE_BCN);
 	if (ret) {
 #if defined(__FreeBSD__)
 		dev_kfree_skb_any(skb);
 #endif
 		rtw_err(rtwdev, "failed to write rsvd page data\n");
 		return ret;
 	}
 
 	/* reserved pages go through beacon queue */
 	reg_bcn_work = rtw_read8(rtwdev, RTK_PCI_TXBD_BCN_WORK);
 	reg_bcn_work |= BIT_PCI_BCNQ_FLAG;
 	rtw_write8(rtwdev, RTK_PCI_TXBD_BCN_WORK, reg_bcn_work);
 
 	return 0;
 }
 
 static int rtw_pci_write_data_h2c(struct rtw_dev *rtwdev, u8 *buf, u32 size)
 {
 	struct sk_buff *skb;
 	struct rtw_tx_pkt_info pkt_info = {0};
 	int ret;
 
 	skb = rtw_tx_write_data_h2c_get(rtwdev, &pkt_info, buf, size);
 	if (!skb)
 		return -ENOMEM;
 
 	ret = rtw_pci_tx_write_data(rtwdev, &pkt_info, skb, RTW_TX_QUEUE_H2C);
 	if (ret) {
 #if defined(__FreeBSD__)
 		dev_kfree_skb_any(skb);
 #endif
 		rtw_err(rtwdev, "failed to write h2c data\n");
 		return ret;
 	}
 
 	rtw_pci_tx_kick_off_queue(rtwdev, RTW_TX_QUEUE_H2C);
 
 	return 0;
 }
 
 static int rtw_pci_tx_write(struct rtw_dev *rtwdev,
 			    struct rtw_tx_pkt_info *pkt_info,
 			    struct sk_buff *skb)
 {
 	enum rtw_tx_queue_type queue = rtw_tx_queue_mapping(skb);
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct rtw_pci_tx_ring *ring;
 	int ret;
 
 	ret = rtw_pci_tx_write_data(rtwdev, pkt_info, skb, queue);
 	if (ret)
 		return ret;
 
 	ring = &rtwpci->tx_rings[queue];
 	spin_lock_bh(&rtwpci->irq_lock);
 	if (avail_desc(ring->r.wp, ring->r.rp, ring->r.len) < 2) {
 		ieee80211_stop_queue(rtwdev->hw, skb_get_queue_mapping(skb));
 		ring->queue_stopped = true;
 	}
 	spin_unlock_bh(&rtwpci->irq_lock);
 
 	return 0;
 }
 
 static void rtw_pci_tx_isr(struct rtw_dev *rtwdev, struct rtw_pci *rtwpci,
 			   u8 hw_queue)
 {
 	struct ieee80211_hw *hw = rtwdev->hw;
 	struct ieee80211_tx_info *info;
 	struct rtw_pci_tx_ring *ring;
 	struct rtw_pci_tx_data *tx_data;
 	struct sk_buff *skb;
 	u32 count;
 	u32 bd_idx_addr;
 	u32 bd_idx, cur_rp, rp_idx;
 	u16 q_map;
 
 	ring = &rtwpci->tx_rings[hw_queue];
 
 	bd_idx_addr = rtw_pci_tx_queue_idx_addr[hw_queue];
 	bd_idx = rtw_read32(rtwdev, bd_idx_addr);
 	cur_rp = bd_idx >> 16;
 	cur_rp &= TRX_BD_IDX_MASK;
 	rp_idx = ring->r.rp;
 	if (cur_rp >= ring->r.rp)
 		count = cur_rp - ring->r.rp;
 	else
 		count = ring->r.len - (ring->r.rp - cur_rp);
 
 	while (count--) {
 		skb = skb_dequeue(&ring->queue);
 		if (!skb) {
 			rtw_err(rtwdev, "failed to dequeue %d skb TX queue %d, BD=0x%08x, rp %d -> %d\n",
 				count, hw_queue, bd_idx, ring->r.rp, cur_rp);
 			break;
 		}
 		tx_data = rtw_pci_get_tx_data(skb);
 		dma_unmap_single(&rtwpci->pdev->dev, tx_data->dma, skb->len,
 				 DMA_TO_DEVICE);
 
 		/* just free command packets from host to card */
 		if (hw_queue == RTW_TX_QUEUE_H2C) {
 			dev_kfree_skb_irq(skb);
 			continue;
 		}
 
 		if (ring->queue_stopped &&
 		    avail_desc(ring->r.wp, rp_idx, ring->r.len) > 4) {
 			q_map = skb_get_queue_mapping(skb);
 			ieee80211_wake_queue(hw, q_map);
 			ring->queue_stopped = false;
 		}
 
 		if (++rp_idx >= ring->r.len)
 			rp_idx = 0;
 
 		skb_pull(skb, rtwdev->chip->tx_pkt_desc_sz);
 
 		info = IEEE80211_SKB_CB(skb);
 
 		/* enqueue to wait for tx report */
 		if (info->flags & IEEE80211_TX_CTL_REQ_TX_STATUS) {
 			rtw_tx_report_enqueue(rtwdev, skb, tx_data->sn);
 			continue;
 		}
 
 		/* always ACK for others, then they won't be marked as drop */
 		if (info->flags & IEEE80211_TX_CTL_NO_ACK)
 			info->flags |= IEEE80211_TX_STAT_NOACK_TRANSMITTED;
 		else
 			info->flags |= IEEE80211_TX_STAT_ACK;
 
 		ieee80211_tx_info_clear_status(info);
 		ieee80211_tx_status_irqsafe(hw, skb);
 	}
 
 	ring->r.rp = cur_rp;
 }
 
 static void rtw_pci_rx_isr(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct napi_struct *napi = &rtwpci->napi;
 
 	napi_schedule(napi);
 }
 
 static int rtw_pci_get_hw_rx_ring_nr(struct rtw_dev *rtwdev,
 				     struct rtw_pci *rtwpci)
 {
 	struct rtw_pci_rx_ring *ring;
 	int count = 0;
 	u32 tmp, cur_wp;
 
 	ring = &rtwpci->rx_rings[RTW_RX_QUEUE_MPDU];
 	tmp = rtw_read32(rtwdev, RTK_PCI_RXBD_IDX_MPDUQ);
 	cur_wp = u32_get_bits(tmp, TRX_BD_HW_IDX_MASK);
 	if (cur_wp >= ring->r.wp)
 		count = cur_wp - ring->r.wp;
 	else
 		count = ring->r.len - (ring->r.wp - cur_wp);
 
 	return count;
 }
 
 static u32 rtw_pci_rx_napi(struct rtw_dev *rtwdev, struct rtw_pci *rtwpci,
 			   u8 hw_queue, u32 limit)
 {
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct napi_struct *napi = &rtwpci->napi;
 	struct rtw_pci_rx_ring *ring = &rtwpci->rx_rings[RTW_RX_QUEUE_MPDU];
 	struct rtw_rx_pkt_stat pkt_stat;
 	struct ieee80211_rx_status rx_status;
 	struct sk_buff *skb, *new;
 	u32 cur_rp = ring->r.rp;
 	u32 count, rx_done = 0;
 	u32 pkt_offset;
 	u32 pkt_desc_sz = chip->rx_pkt_desc_sz;
 	u32 buf_desc_sz = chip->rx_buf_desc_sz;
 	u32 new_len;
 	u8 *rx_desc;
 	dma_addr_t dma;
 
 	count = rtw_pci_get_hw_rx_ring_nr(rtwdev, rtwpci);
 	count = min(count, limit);
 
 	while (count--) {
 		rtw_pci_dma_check(rtwdev, ring, cur_rp);
 		skb = ring->buf[cur_rp];
 		dma = *((dma_addr_t *)skb->cb);
 		dma_sync_single_for_cpu(rtwdev->dev, dma, RTK_PCI_RX_BUF_SIZE,
 					DMA_FROM_DEVICE);
 		rx_desc = skb->data;
 		chip->ops->query_rx_desc(rtwdev, rx_desc, &pkt_stat, &rx_status);
 
 		/* offset from rx_desc to payload */
 		pkt_offset = pkt_desc_sz + pkt_stat.drv_info_sz +
 			     pkt_stat.shift;
 
 		/* allocate a new skb for this frame,
 		 * discard the frame if none available
 		 */
 		new_len = pkt_stat.pkt_len + pkt_offset;
 		new = dev_alloc_skb(new_len);
 		if (WARN_ONCE(!new, "rx routine starvation\n"))
 			goto next_rp;
 
 		/* put the DMA data including rx_desc from phy to new skb */
 		skb_put_data(new, skb->data, new_len);
 
 		if (pkt_stat.is_c2h) {
 			rtw_fw_c2h_cmd_rx_irqsafe(rtwdev, pkt_offset, new);
 		} else {
 			/* remove rx_desc */
 			skb_pull(new, pkt_offset);
 
 			rtw_rx_stats(rtwdev, pkt_stat.vif, new);
 			memcpy(new->cb, &rx_status, sizeof(rx_status));
 			ieee80211_rx_napi(rtwdev->hw, NULL, new, napi);
 			rx_done++;
 		}
 
 next_rp:
 		/* new skb delivered to mac80211, re-enable original skb DMA */
 		rtw_pci_sync_rx_desc_device(rtwdev, dma, ring, cur_rp,
 					    buf_desc_sz);
 
 		/* host read next element in ring */
 		if (++cur_rp >= ring->r.len)
 			cur_rp = 0;
 	}
 
 	ring->r.rp = cur_rp;
 	/* 'rp', the last position we have read, is seen as previous posistion
 	 * of 'wp' that is used to calculate 'count' next time.
 	 */
 	ring->r.wp = cur_rp;
 	rtw_write16(rtwdev, RTK_PCI_RXBD_IDX_MPDUQ, ring->r.rp);
 
 	return rx_done;
 }
 
 static void rtw_pci_irq_recognized(struct rtw_dev *rtwdev,
 				   struct rtw_pci *rtwpci, u32 *irq_status)
 {
 	unsigned long flags;
 
 	spin_lock_irqsave(&rtwpci->hwirq_lock, flags);
 
 	irq_status[0] = rtw_read32(rtwdev, RTK_PCI_HISR0);
 	irq_status[1] = rtw_read32(rtwdev, RTK_PCI_HISR1);
 	if (rtw_chip_wcpu_11ac(rtwdev))
 		irq_status[3] = rtw_read32(rtwdev, RTK_PCI_HISR3);
 	else
 		irq_status[3] = 0;
 	irq_status[0] &= rtwpci->irq_mask[0];
 	irq_status[1] &= rtwpci->irq_mask[1];
 	irq_status[3] &= rtwpci->irq_mask[3];
 	rtw_write32(rtwdev, RTK_PCI_HISR0, irq_status[0]);
 	rtw_write32(rtwdev, RTK_PCI_HISR1, irq_status[1]);
 	if (rtw_chip_wcpu_11ac(rtwdev))
 		rtw_write32(rtwdev, RTK_PCI_HISR3, irq_status[3]);
 
 	spin_unlock_irqrestore(&rtwpci->hwirq_lock, flags);
 }
 
 static irqreturn_t rtw_pci_interrupt_handler(int irq, void *dev)
 {
 	struct rtw_dev *rtwdev = dev;
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	/* disable RTW PCI interrupt to avoid more interrupts before the end of
 	 * thread function
 	 *
 	 * disable HIMR here to also avoid new HISR flag being raised before
 	 * the HISRs have been Write-1-cleared for MSI. If not all of the HISRs
 	 * are cleared, the edge-triggered interrupt will not be generated when
 	 * a new HISR flag is set.
 	 */
 	rtw_pci_disable_interrupt(rtwdev, rtwpci);
 
 	return IRQ_WAKE_THREAD;
 }
 
 static irqreturn_t rtw_pci_interrupt_threadfn(int irq, void *dev)
 {
 	struct rtw_dev *rtwdev = dev;
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	u32 irq_status[4];
 	bool rx = false;
 
 	spin_lock_bh(&rtwpci->irq_lock);
 	rtw_pci_irq_recognized(rtwdev, rtwpci, irq_status);
 
 	if (irq_status[0] & IMR_MGNTDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_MGMT);
 	if (irq_status[0] & IMR_HIGHDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_HI0);
 	if (irq_status[0] & IMR_BEDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_BE);
 	if (irq_status[0] & IMR_BKDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_BK);
 	if (irq_status[0] & IMR_VODOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_VO);
 	if (irq_status[0] & IMR_VIDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_VI);
 	if (irq_status[3] & IMR_H2CDOK)
 		rtw_pci_tx_isr(rtwdev, rtwpci, RTW_TX_QUEUE_H2C);
 	if (irq_status[0] & IMR_ROK) {
 		rtw_pci_rx_isr(rtwdev);
 		rx = true;
 	}
 	if (unlikely(irq_status[0] & IMR_C2HCMD))
 		rtw_fw_c2h_cmd_isr(rtwdev);
 
 	/* all of the jobs for this interrupt have been done */
 	if (rtwpci->running)
 		rtw_pci_enable_interrupt(rtwdev, rtwpci, rx);
 	spin_unlock_bh(&rtwpci->irq_lock);
 
 	return IRQ_HANDLED;
 }
 
 static int rtw_pci_io_mapping(struct rtw_dev *rtwdev,
 			      struct pci_dev *pdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	unsigned long len;
 	u8 bar_id = 2;
 	int ret;
 
 	ret = pci_request_regions(pdev, KBUILD_MODNAME);
 	if (ret) {
 		rtw_err(rtwdev, "failed to request pci regions\n");
 		return ret;
 	}
 
 #if defined(__FreeBSD__)
 	ret = dma_set_mask(&pdev->dev, DMA_BIT_MASK(32));
 	if (ret) {
 		rtw_err(rtwdev, "failed to set dma mask to 32-bit\n");
 		goto err_release_regions;
 	}
 
 	ret = dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(32));
 	if (ret) {
 		rtw_err(rtwdev, "failed to set consistent dma mask to 32-bit\n");
 		goto err_release_regions;
 	}
 #endif
 
 	len = pci_resource_len(pdev, bar_id);
 #if defined(__FreeBSD__)
 	linuxkpi_pcim_want_to_use_bus_functions(pdev);
 #endif
 	rtwpci->mmap = pci_iomap(pdev, bar_id, len);
 	if (!rtwpci->mmap) {
 		pci_release_regions(pdev);
 		rtw_err(rtwdev, "failed to map pci memory\n");
 		return -ENOMEM;
 	}
 
 	return 0;
 #if defined(__FreeBSD__)
 err_release_regions:
 	pci_release_regions(pdev);
 	return ret;
 #endif
 }
 
 static void rtw_pci_io_unmapping(struct rtw_dev *rtwdev,
 				 struct pci_dev *pdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	if (rtwpci->mmap) {
 		pci_iounmap(pdev, rtwpci->mmap);
 		pci_release_regions(pdev);
 	}
 }
 
 static void rtw_dbi_write8(struct rtw_dev *rtwdev, u16 addr, u8 data)
 {
 	u16 write_addr;
 	u16 remainder = addr & ~(BITS_DBI_WREN | BITS_DBI_ADDR_MASK);
 	u8 flag;
 	u8 cnt;
 
 	write_addr = addr & BITS_DBI_ADDR_MASK;
 	write_addr |= u16_encode_bits(BIT(remainder), BITS_DBI_WREN);
 	rtw_write8(rtwdev, REG_DBI_WDATA_V1 + remainder, data);
 	rtw_write16(rtwdev, REG_DBI_FLAG_V1, write_addr);
 	rtw_write8(rtwdev, REG_DBI_FLAG_V1 + 2, BIT_DBI_WFLAG >> 16);
 
 	for (cnt = 0; cnt < RTW_PCI_WR_RETRY_CNT; cnt++) {
 		flag = rtw_read8(rtwdev, REG_DBI_FLAG_V1 + 2);
 		if (flag == 0)
 			return;
 
 		udelay(10);
 	}
 
 	WARN(flag, "failed to write to DBI register, addr=0x%04x\n", addr);
 }
 
 static int rtw_dbi_read8(struct rtw_dev *rtwdev, u16 addr, u8 *value)
 {
 	u16 read_addr = addr & BITS_DBI_ADDR_MASK;
 	u8 flag;
 	u8 cnt;
 
 	rtw_write16(rtwdev, REG_DBI_FLAG_V1, read_addr);
 	rtw_write8(rtwdev, REG_DBI_FLAG_V1 + 2, BIT_DBI_RFLAG >> 16);
 
 	for (cnt = 0; cnt < RTW_PCI_WR_RETRY_CNT; cnt++) {
 		flag = rtw_read8(rtwdev, REG_DBI_FLAG_V1 + 2);
 		if (flag == 0) {
 			read_addr = REG_DBI_RDATA_V1 + (addr & 3);
 			*value = rtw_read8(rtwdev, read_addr);
 			return 0;
 		}
 
 		udelay(10);
 	}
 
 	WARN(1, "failed to read DBI register, addr=0x%04x\n", addr);
 	return -EIO;
 }
 
 static void rtw_mdio_write(struct rtw_dev *rtwdev, u8 addr, u16 data, bool g1)
 {
 	u8 page;
 	u8 wflag;
 	u8 cnt;
 
 	rtw_write16(rtwdev, REG_MDIO_V1, data);
 
 	page = addr < RTW_PCI_MDIO_PG_SZ ? 0 : 1;
 	page += g1 ? RTW_PCI_MDIO_PG_OFFS_G1 : RTW_PCI_MDIO_PG_OFFS_G2;
 	rtw_write8(rtwdev, REG_PCIE_MIX_CFG, addr & BITS_MDIO_ADDR_MASK);
 	rtw_write8(rtwdev, REG_PCIE_MIX_CFG + 3, page);
 	rtw_write32_mask(rtwdev, REG_PCIE_MIX_CFG, BIT_MDIO_WFLAG_V1, 1);
 
 	for (cnt = 0; cnt < RTW_PCI_WR_RETRY_CNT; cnt++) {
 		wflag = rtw_read32_mask(rtwdev, REG_PCIE_MIX_CFG,
 					BIT_MDIO_WFLAG_V1);
 		if (wflag == 0)
 			return;
 
 		udelay(10);
 	}
 
 	WARN(wflag, "failed to write to MDIO register, addr=0x%02x\n", addr);
 }
 
 static void rtw_pci_clkreq_set(struct rtw_dev *rtwdev, bool enable)
 {
 	u8 value;
 	int ret;
 
 	if (rtw_pci_disable_aspm)
 		return;
 
 	ret = rtw_dbi_read8(rtwdev, RTK_PCIE_LINK_CFG, &value);
 	if (ret) {
 		rtw_err(rtwdev, "failed to read CLKREQ_L1, ret=%d", ret);
 		return;
 	}
 
 	if (enable)
 		value |= BIT_CLKREQ_SW_EN;
 	else
 		value &= ~BIT_CLKREQ_SW_EN;
 
 	rtw_dbi_write8(rtwdev, RTK_PCIE_LINK_CFG, value);
 }
 
 static void rtw_pci_clkreq_pad_low(struct rtw_dev *rtwdev, bool enable)
 {
 	u8 value;
 	int ret;
 
 	ret = rtw_dbi_read8(rtwdev, RTK_PCIE_LINK_CFG, &value);
 	if (ret) {
 		rtw_err(rtwdev, "failed to read CLKREQ_L1, ret=%d", ret);
 		return;
 	}
 
 	if (enable)
 		value &= ~BIT_CLKREQ_N_PAD;
 	else
 		value |= BIT_CLKREQ_N_PAD;
 
 	rtw_dbi_write8(rtwdev, RTK_PCIE_LINK_CFG, value);
 }
 
 static void rtw_pci_aspm_set(struct rtw_dev *rtwdev, bool enable)
 {
 	u8 value;
 	int ret;
 
 	if (rtw_pci_disable_aspm)
 		return;
 
 	ret = rtw_dbi_read8(rtwdev, RTK_PCIE_LINK_CFG, &value);
 	if (ret) {
 		rtw_err(rtwdev, "failed to read ASPM, ret=%d", ret);
 		return;
 	}
 
 	if (enable)
 		value |= BIT_L1_SW_EN;
 	else
 		value &= ~BIT_L1_SW_EN;
 
 	rtw_dbi_write8(rtwdev, RTK_PCIE_LINK_CFG, value);
 }
 
 static void rtw_pci_link_ps(struct rtw_dev *rtwdev, bool enter)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	/* Like CLKREQ, ASPM is also implemented by two HW modules, and can
 	 * only be enabled when host supports it.
 	 *
 	 * And ASPM mechanism should be enabled when driver/firmware enters
 	 * power save mode, without having heavy traffic. Because we've
 	 * experienced some inter-operability issues that the link tends
 	 * to enter L1 state on the fly even when driver is having high
 	 * throughput. This is probably because the ASPM behavior slightly
 	 * varies from different SOC.
 	 */
 	if (!(rtwpci->link_ctrl & PCI_EXP_LNKCTL_ASPM_L1))
 		return;
 
 	if ((enter && atomic_dec_if_positive(&rtwpci->link_usage) == 0) ||
 	    (!enter && atomic_inc_return(&rtwpci->link_usage) == 1))
 		rtw_pci_aspm_set(rtwdev, enter);
 }
 
 static void rtw_pci_link_cfg(struct rtw_dev *rtwdev)
 {
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	struct pci_dev *pdev = rtwpci->pdev;
 	u16 link_ctrl;
 	int ret;
 
 	/* RTL8822CE has enabled REFCLK auto calibration, it does not need
 	 * to add clock delay to cover the REFCLK timing gap.
 	 */
 	if (chip->id == RTW_CHIP_TYPE_8822C)
 		rtw_dbi_write8(rtwdev, RTK_PCIE_CLKDLY_CTRL, 0);
 
 	/* Though there is standard PCIE configuration space to set the
 	 * link control register, but by Realtek's design, driver should
 	 * check if host supports CLKREQ/ASPM to enable the HW module.
 	 *
 	 * These functions are implemented by two HW modules associated,
 	 * one is responsible to access PCIE configuration space to
 	 * follow the host settings, and another is in charge of doing
 	 * CLKREQ/ASPM mechanisms, it is default disabled. Because sometimes
 	 * the host does not support it, and due to some reasons or wrong
 	 * settings (ex. CLKREQ# not Bi-Direction), it could lead to device
 	 * loss if HW misbehaves on the link.
 	 *
 	 * Hence it's designed that driver should first check the PCIE
 	 * configuration space is sync'ed and enabled, then driver can turn
 	 * on the other module that is actually working on the mechanism.
 	 */
 	ret = pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &link_ctrl);
 	if (ret) {
 		rtw_err(rtwdev, "failed to read PCI cap, ret=%d\n", ret);
 		return;
 	}
 
 	if (link_ctrl & PCI_EXP_LNKCTL_CLKREQ_EN)
 		rtw_pci_clkreq_set(rtwdev, true);
 
 	rtwpci->link_ctrl = link_ctrl;
 }
 
 static void rtw_pci_interface_cfg(struct rtw_dev *rtwdev)
 {
 	const struct rtw_chip_info *chip = rtwdev->chip;
 
 	switch (chip->id) {
 	case RTW_CHIP_TYPE_8822C:
 		if (rtwdev->hal.cut_version >= RTW_CHIP_VER_CUT_D)
 			rtw_write32_mask(rtwdev, REG_HCI_MIX_CFG,
 					 BIT_PCIE_EMAC_PDN_AUX_TO_FAST_CLK, 1);
 		break;
 	default:
 		break;
 	}
 }
 
 static void rtw_pci_phy_cfg(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct pci_dev *pdev = rtwpci->pdev;
 	const struct rtw_intf_phy_para *para;
 	u16 cut;
 	u16 value;
 	u16 offset;
 	int i;
 	int ret;
 
 	cut = BIT(0) << rtwdev->hal.cut_version;
 
 	for (i = 0; i < chip->intf_table->n_gen1_para; i++) {
 		para = &chip->intf_table->gen1_para[i];
 		if (!(para->cut_mask & cut))
 			continue;
 		if (para->offset == 0xffff)
 			break;
 		offset = para->offset;
 		value = para->value;
 		if (para->ip_sel == RTW_IP_SEL_PHY)
 			rtw_mdio_write(rtwdev, offset, value, true);
 		else
 			rtw_dbi_write8(rtwdev, offset, value);
 	}
 
 	for (i = 0; i < chip->intf_table->n_gen2_para; i++) {
 		para = &chip->intf_table->gen2_para[i];
 		if (!(para->cut_mask & cut))
 			continue;
 		if (para->offset == 0xffff)
 			break;
 		offset = para->offset;
 		value = para->value;
 		if (para->ip_sel == RTW_IP_SEL_PHY)
 			rtw_mdio_write(rtwdev, offset, value, false);
 		else
 			rtw_dbi_write8(rtwdev, offset, value);
 	}
 
 	rtw_pci_link_cfg(rtwdev);
 
 	/* Disable 8821ce completion timeout by default */
 	if (chip->id == RTW_CHIP_TYPE_8821C) {
 		ret = pcie_capability_set_word(pdev, PCI_EXP_DEVCTL2,
 					       PCI_EXP_DEVCTL2_COMP_TMOUT_DIS);
 		if (ret)
 			rtw_err(rtwdev, "failed to set PCI cap, ret = %d\n",
 				ret);
 	}
 }
 
 static int __maybe_unused rtw_pci_suspend(struct device *dev)
 {
 	struct ieee80211_hw *hw = dev_get_drvdata(dev);
 	struct rtw_dev *rtwdev = hw->priv;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct rtw_efuse *efuse = &rtwdev->efuse;
 
 	if (chip->id == RTW_CHIP_TYPE_8822C && efuse->rfe_option == 6)
 		rtw_pci_clkreq_pad_low(rtwdev, true);
 	return 0;
 }
 
 static int __maybe_unused rtw_pci_resume(struct device *dev)
 {
 	struct ieee80211_hw *hw = dev_get_drvdata(dev);
 	struct rtw_dev *rtwdev = hw->priv;
 	const struct rtw_chip_info *chip = rtwdev->chip;
 	struct rtw_efuse *efuse = &rtwdev->efuse;
 
 	if (chip->id == RTW_CHIP_TYPE_8822C && efuse->rfe_option == 6)
 		rtw_pci_clkreq_pad_low(rtwdev, false);
 	return 0;
 }
 
 SIMPLE_DEV_PM_OPS(rtw_pm_ops, rtw_pci_suspend, rtw_pci_resume);
 EXPORT_SYMBOL(rtw_pm_ops);
 
 static int rtw_pci_claim(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	int ret;
 
 	ret = pci_enable_device(pdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to enable pci device\n");
 		return ret;
 	}
 
 	pci_set_master(pdev);
 	pci_set_drvdata(pdev, rtwdev->hw);
 	SET_IEEE80211_DEV(rtwdev->hw, &pdev->dev);
 
 	return 0;
 }
 
 static void rtw_pci_declaim(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	pci_disable_device(pdev);
 }
 
 static int rtw_pci_setup_resource(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	struct rtw_pci *rtwpci;
 	int ret;
 
 	rtwpci = (struct rtw_pci *)rtwdev->priv;
 	rtwpci->pdev = pdev;
 
 	/* after this driver can access to hw registers */
 	ret = rtw_pci_io_mapping(rtwdev, pdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to request pci io region\n");
 		goto err_out;
 	}
 
 	ret = rtw_pci_init(rtwdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to allocate pci resources\n");
 		goto err_io_unmap;
 	}
 
 	return 0;
 
 err_io_unmap:
 	rtw_pci_io_unmapping(rtwdev, pdev);
 
 err_out:
 	return ret;
 }
 
 static void rtw_pci_destroy(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	rtw_pci_deinit(rtwdev);
 	rtw_pci_io_unmapping(rtwdev, pdev);
 }
 
 static struct rtw_hci_ops rtw_pci_ops = {
 	.tx_write = rtw_pci_tx_write,
 	.tx_kick_off = rtw_pci_tx_kick_off,
 	.flush_queues = rtw_pci_flush_queues,
 	.setup = rtw_pci_setup,
 	.start = rtw_pci_start,
 	.stop = rtw_pci_stop,
 	.deep_ps = rtw_pci_deep_ps,
 	.link_ps = rtw_pci_link_ps,
 	.interface_cfg = rtw_pci_interface_cfg,
 
 	.read8 = rtw_pci_read8,
 	.read16 = rtw_pci_read16,
 	.read32 = rtw_pci_read32,
 	.write8 = rtw_pci_write8,
 	.write16 = rtw_pci_write16,
 	.write32 = rtw_pci_write32,
 	.write_data_rsvd_page = rtw_pci_write_data_rsvd_page,
 	.write_data_h2c = rtw_pci_write_data_h2c,
 };
 
 static int rtw_pci_request_irq(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	unsigned int flags = PCI_IRQ_LEGACY;
 	int ret;
 
 	if (!rtw_disable_msi)
 		flags |= PCI_IRQ_MSI;
 
 	ret = pci_alloc_irq_vectors(pdev, 1, 1, flags);
 	if (ret < 0) {
 		rtw_err(rtwdev, "failed to alloc PCI irq vectors\n");
 		return ret;
 	}
 
 	ret = devm_request_threaded_irq(rtwdev->dev, pdev->irq,
 					rtw_pci_interrupt_handler,
 					rtw_pci_interrupt_threadfn,
 					IRQF_SHARED, KBUILD_MODNAME, rtwdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to request irq %d\n", ret);
 		pci_free_irq_vectors(pdev);
 	}
 
 	return ret;
 }
 
 static void rtw_pci_free_irq(struct rtw_dev *rtwdev, struct pci_dev *pdev)
 {
 	devm_free_irq(rtwdev->dev, pdev->irq, rtwdev);
 	pci_free_irq_vectors(pdev);
 }
 
 static int rtw_pci_napi_poll(struct napi_struct *napi, int budget)
 {
 	struct rtw_pci *rtwpci = container_of(napi, struct rtw_pci, napi);
 	struct rtw_dev *rtwdev = container_of((void *)rtwpci, struct rtw_dev,
 					      priv);
 	int work_done = 0;
 
 	if (rtwpci->rx_no_aspm)
 		rtw_pci_link_ps(rtwdev, false);
 
 	while (work_done < budget) {
 		u32 work_done_once;
 
 		work_done_once = rtw_pci_rx_napi(rtwdev, rtwpci, RTW_RX_QUEUE_MPDU,
 						 budget - work_done);
 		if (work_done_once == 0)
 			break;
 		work_done += work_done_once;
 	}
 	if (work_done < budget) {
 		napi_complete_done(napi, work_done);
 		spin_lock_bh(&rtwpci->irq_lock);
 		if (rtwpci->running)
 			rtw_pci_enable_interrupt(rtwdev, rtwpci, false);
 		spin_unlock_bh(&rtwpci->irq_lock);
 		/* When ISR happens during polling and before napi_complete
 		 * while no further data is received. Data on the dma_ring will
 		 * not be processed immediately. Check whether dma ring is
 		 * empty and perform napi_schedule accordingly.
 		 */
 		if (rtw_pci_get_hw_rx_ring_nr(rtwdev, rtwpci))
 			napi_schedule(napi);
 	}
 	if (rtwpci->rx_no_aspm)
 		rtw_pci_link_ps(rtwdev, true);
 
 	return work_done;
 }
 
 static void rtw_pci_napi_init(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	init_dummy_netdev(&rtwpci->netdev);
 	netif_napi_add(&rtwpci->netdev, &rtwpci->napi, rtw_pci_napi_poll);
 }
 
 static void rtw_pci_napi_deinit(struct rtw_dev *rtwdev)
 {
 	struct rtw_pci *rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	rtw_pci_napi_stop(rtwdev);
 	netif_napi_del(&rtwpci->napi);
 }
 
 int rtw_pci_probe(struct pci_dev *pdev,
 		  const struct pci_device_id *id)
 {
 	struct pci_dev *bridge = pci_upstream_bridge(pdev);
 	struct ieee80211_hw *hw;
 	struct rtw_dev *rtwdev;
 	struct rtw_pci *rtwpci;
 	int drv_data_size;
 	int ret;
 
 	drv_data_size = sizeof(struct rtw_dev) + sizeof(struct rtw_pci);
 	hw = ieee80211_alloc_hw(drv_data_size, &rtw_ops);
 	if (!hw) {
 		dev_err(&pdev->dev, "failed to allocate hw\n");
 		return -ENOMEM;
 	}
 
 	rtwdev = hw->priv;
 	rtwdev->hw = hw;
 	rtwdev->dev = &pdev->dev;
 	rtwdev->chip = (struct rtw_chip_info *)id->driver_data;
 	rtwdev->hci.ops = &rtw_pci_ops;
 	rtwdev->hci.type = RTW_HCI_TYPE_PCIE;
 
 	rtwpci = (struct rtw_pci *)rtwdev->priv;
 	atomic_set(&rtwpci->link_usage, 1);
 
 	ret = rtw_core_init(rtwdev);
 	if (ret)
 		goto err_release_hw;
 
 	rtw_dbg(rtwdev, RTW_DBG_PCI,
 		"rtw88 pci probe: vendor=0x%4.04X device=0x%4.04X rev=%d\n",
 		pdev->vendor, pdev->device, pdev->revision);
 
 	ret = rtw_pci_claim(rtwdev, pdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to claim pci device\n");
 		goto err_deinit_core;
 	}
 
 	ret = rtw_pci_setup_resource(rtwdev, pdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to setup pci resources\n");
 		goto err_pci_declaim;
 	}
 
 	rtw_pci_napi_init(rtwdev);
 
 	ret = rtw_chip_info_setup(rtwdev);
 	if (ret) {
 		rtw_err(rtwdev, "failed to setup chip information\n");
 		goto err_destroy_pci;
 	}
 
 	/* Disable PCIe ASPM L1 while doing NAPI poll for 8821CE */
 	if (rtwdev->chip->id == RTW_CHIP_TYPE_8821C && bridge->vendor == PCI_VENDOR_ID_INTEL)
 		rtwpci->rx_no_aspm = true;
 
 	rtw_pci_phy_cfg(rtwdev);
 
 	ret = rtw_register_hw(rtwdev, hw);
 	if (ret) {
 		rtw_err(rtwdev, "failed to register hw\n");
 		goto err_destroy_pci;
 	}
 
 	ret = rtw_pci_request_irq(rtwdev, pdev);
 	if (ret) {
 		ieee80211_unregister_hw(hw);
 		goto err_destroy_pci;
 	}
 
 	return 0;
 
 err_destroy_pci:
 	rtw_pci_napi_deinit(rtwdev);
 	rtw_pci_destroy(rtwdev, pdev);
 
 err_pci_declaim:
 	rtw_pci_declaim(rtwdev, pdev);
 
 err_deinit_core:
 	rtw_core_deinit(rtwdev);
 
 err_release_hw:
 	ieee80211_free_hw(hw);
 
 	return ret;
 }
 EXPORT_SYMBOL(rtw_pci_probe);
 
 void rtw_pci_remove(struct pci_dev *pdev)
 {
 	struct ieee80211_hw *hw = pci_get_drvdata(pdev);
 	struct rtw_dev *rtwdev;
 	struct rtw_pci *rtwpci;
 
 	if (!hw)
 		return;
 
 	rtwdev = hw->priv;
 	rtwpci = (struct rtw_pci *)rtwdev->priv;
 
 	rtw_unregister_hw(rtwdev, hw);
 	rtw_pci_disable_interrupt(rtwdev, rtwpci);
 	rtw_pci_napi_deinit(rtwdev);
 	rtw_pci_destroy(rtwdev, pdev);
 	rtw_pci_declaim(rtwdev, pdev);
 	rtw_pci_free_irq(rtwdev, pdev);
 	rtw_core_deinit(rtwdev);
 	ieee80211_free_hw(hw);
 }
 EXPORT_SYMBOL(rtw_pci_remove);
 
 void rtw_pci_shutdown(struct pci_dev *pdev)
 {
 	struct ieee80211_hw *hw = pci_get_drvdata(pdev);
 	struct rtw_dev *rtwdev;
 	const struct rtw_chip_info *chip;
 
 	if (!hw)
 		return;
 
 	rtwdev = hw->priv;
 	chip = rtwdev->chip;
 
 	if (chip->ops->shutdown)
 		chip->ops->shutdown(rtwdev);
 
 	pci_set_power_state(pdev, PCI_D3hot);
 }
 EXPORT_SYMBOL(rtw_pci_shutdown);
 
 MODULE_AUTHOR("Realtek Corporation");
 MODULE_DESCRIPTION("Realtek 802.11ac wireless PCI driver");
 MODULE_LICENSE("Dual BSD/GPL");
 #if defined(__FreeBSD__)
 MODULE_VERSION(rtw_pci, 1);
 MODULE_DEPEND(rtw_pci, linuxkpi, 1, 1, 1);
 MODULE_DEPEND(rtw_pci, linuxkpi_wlan, 1, 1, 1);
 #ifdef CONFIG_RTW88_DEBUGFS
 MODULE_DEPEND(rtw_pci, lindebugfs, 1, 1, 1);
 #endif
 #endif
diff --git a/sys/dev/irdma/irdma_main.h b/sys/dev/irdma/irdma_main.h
index aa5bbee2fb77..46ab49bfde8d 100644
--- a/sys/dev/irdma/irdma_main.h
+++ b/sys/dev/irdma/irdma_main.h
@@ -1,614 +1,615 @@
 /*-
  * SPDX-License-Identifier: GPL-2.0 or Linux-OpenIB
  *
  * Copyright (c) 2015 - 2023 Intel Corporation
  *
  * This software is available to you under a choice of one of two
  * licenses.  You may choose to be licensed under the terms of the GNU
  * General Public License (GPL) Version 2, available from the file
  * COPYING in the main directory of this source tree, or the
  * OpenFabrics.org BSD license below:
  *
  *   Redistribution and use in source and binary forms, with or
  *   without modification, are permitted provided that the following
  *   conditions are met:
  *
  *    - Redistributions of source code must retain the above
  *	copyright notice, this list of conditions and the following
  *	disclaimer.
  *
  *    - Redistributions in binary form must reproduce the above
  *	copyright notice, this list of conditions and the following
  *	disclaimer in the documentation and/or other materials
  *	provided with the distribution.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  * SOFTWARE.
  */
 
 #ifndef IRDMA_MAIN_H
 #define IRDMA_MAIN_H
 
 #include <linux/in.h>
 #include <netinet/ip6.h>
 #include <netinet/udp.h>
 #include <netinet/tcp.h>
+#include <sys/rman.h>
 #include <sys/socket.h>
 #include <netinet/if_ether.h>
 #include <linux/slab.h>
 #include <linux/rculist.h>
 #if __FreeBSD_version >= 1400000
 #include <rdma/uverbs_ioctl.h>
 #endif
 #include <rdma/ib_smi.h>
 #include <rdma/ib_verbs.h>
 #include <rdma/ib_pack.h>
 #include <rdma/rdma_cm.h>
 #include <rdma/iw_cm.h>
 #include <rdma/ib_user_verbs.h>
 #include <rdma/ib_umem.h>
 #include <rdma/ib_cache.h>
 #include "osdep.h"
 #include "irdma_defs.h"
 #include "irdma_hmc.h"
 #include "irdma_type.h"
 #include "irdma_ws.h"
 #include "irdma_protos.h"
 #include "irdma_pble.h"
 #include "irdma_cm.h"
 #include "fbsd_kcompat.h"
 #include "irdma-abi.h"
 #include "irdma_verbs.h"
 #include "irdma_user.h"
 #include "irdma_puda.h"
 
 extern struct list_head irdma_handlers;
 extern spinlock_t irdma_handler_lock;
 extern bool irdma_upload_context;
 
 #define IRDMA_FW_VER_DEFAULT	2
 #define IRDMA_HW_VER	        2
 
 #define IRDMA_ARP_ADD		1
 #define IRDMA_ARP_DELETE	2
 #define IRDMA_ARP_RESOLVE	3
 
 #define IRDMA_MACIP_ADD		1
 #define IRDMA_MACIP_DELETE	2
 
 #define IW_CCQ_SIZE	(IRDMA_CQP_SW_SQSIZE_2048 + 1)
 #define IW_CEQ_SIZE	2048
 #define IW_AEQ_SIZE	2048
 
 #define RX_BUF_SIZE	(1536 + 8)
 #define IW_REG0_SIZE	(4 * 1024)
 #define IW_TX_TIMEOUT	(6 * HZ)
 #define IW_FIRST_QPN	1
 
 #define IW_SW_CONTEXT_ALIGN	1024
 
 #define MAX_DPC_ITERATIONS	128
 
 #define IRDMA_EVENT_TIMEOUT_MS		5000
 #define IRDMA_VCHNL_EVENT_TIMEOUT_MS	10000
 #define IRDMA_RST_TIMEOUT_HZ		4
 
 #define	IRDMA_NO_QSET	0xffff
 
 #define IW_CFG_FPM_QP_COUNT		32768
 #define IRDMA_MAX_PAGES_PER_FMR		262144
 #define IRDMA_MIN_PAGES_PER_FMR		1
 #define IRDMA_CQP_COMPL_RQ_WQE_FLUSHED	2
 #define IRDMA_CQP_COMPL_SQ_WQE_FLUSHED	3
 
 #define IRDMA_Q_TYPE_PE_AEQ	0x80
 #define IRDMA_Q_INVALID_IDX	0xffff
 #define IRDMA_REM_ENDPOINT_TRK_QPID	3
 
 #define IRDMA_DRV_OPT_ENA_MPA_VER_0		0x00000001
 #define IRDMA_DRV_OPT_DISABLE_MPA_CRC		0x00000002
 #define IRDMA_DRV_OPT_DISABLE_FIRST_WRITE	0x00000004
 #define IRDMA_DRV_OPT_DISABLE_INTF		0x00000008
 #define IRDMA_DRV_OPT_ENA_MSI			0x00000010
 #define IRDMA_DRV_OPT_DUAL_LOGICAL_PORT		0x00000020
 #define IRDMA_DRV_OPT_NO_INLINE_DATA		0x00000080
 #define IRDMA_DRV_OPT_DISABLE_INT_MOD		0x00000100
 #define IRDMA_DRV_OPT_DISABLE_VIRT_WQ		0x00000200
 #define IRDMA_DRV_OPT_ENA_PAU			0x00000400
 #define IRDMA_DRV_OPT_MCAST_LOGPORT_MAP		0x00000800
 
 #define IW_HMC_OBJ_TYPE_NUM	ARRAY_SIZE(iw_hmc_obj_types)
 #define IRDMA_ROCE_CWND_DEFAULT			0x400
 #define IRDMA_ROCE_ACKCREDS_DEFAULT		0x1E
 
 #define IRDMA_FLUSH_SQ		BIT(0)
 #define IRDMA_FLUSH_RQ		BIT(1)
 #define IRDMA_REFLUSH		BIT(2)
 #define IRDMA_FLUSH_WAIT	BIT(3)
 
 #define IRDMA_IRQ_NAME_STR_LEN 64
 
 enum init_completion_state {
 	INVALID_STATE = 0,
 	INITIAL_STATE,
 	CQP_CREATED,
 	HMC_OBJS_CREATED,
 	HW_RSRC_INITIALIZED,
 	CCQ_CREATED,
 	CEQ0_CREATED, /* Last state of probe */
 	ILQ_CREATED,
 	IEQ_CREATED,
 	REM_ENDPOINT_TRK_CREATED,
 	CEQS_CREATED,
 	PBLE_CHUNK_MEM,
 	AEQ_CREATED,
 	IP_ADDR_REGISTERED,  /* Last state of open */
 };
 
 struct ae_desc {
 	u16 id;
 	const char *desc;
 };
 
 struct irdma_rsrc_limits {
 	u32 qplimit;
 	u32 mrlimit;
 	u32 cqlimit;
 };
 
 struct irdma_cqp_err_info {
 	u16 maj;
 	u16 min;
 	const char *desc;
 };
 
 struct irdma_cqp_compl_info {
 	u32 op_ret_val;
 	u16 maj_err_code;
 	u16 min_err_code;
 	bool error;
 	u8 op_code;
 };
 
 struct irdma_cqp_request {
 	struct cqp_cmds_info info;
 	wait_queue_head_t waitq;
 	struct list_head list;
 	atomic_t refcnt;
 	void (*callback_fcn)(struct irdma_cqp_request *cqp_request);
 	void *param;
 	struct irdma_cqp_compl_info compl_info;
 	bool request_done; /* READ/WRITE_ONCE macros operate on it */
 	bool waiting:1;
 	bool dynamic:1;
 };
 
 struct irdma_cqp {
 	struct irdma_sc_cqp sc_cqp;
 	spinlock_t req_lock; /* protect CQP request list */
 	spinlock_t compl_lock; /* protect CQP completion processing */
 	wait_queue_head_t waitq;
 	wait_queue_head_t remove_wq;
 	struct irdma_dma_mem sq;
 	struct irdma_dma_mem host_ctx;
 	u64 *scratch_array;
 	struct irdma_cqp_request *cqp_requests;
 	struct list_head cqp_avail_reqs;
 	struct list_head cqp_pending_reqs;
 };
 
 struct irdma_ccq {
 	struct irdma_sc_cq sc_cq;
 	struct irdma_dma_mem mem_cq;
 	struct irdma_dma_mem shadow_area;
 };
 
 struct irdma_ceq {
 	struct irdma_sc_ceq sc_ceq;
 	struct irdma_dma_mem mem;
 	u32 irq;
 	u32 msix_idx;
 	struct irdma_pci_f *rf;
 	struct tasklet_struct dpc_tasklet;
 	spinlock_t ce_lock; /* sync cq destroy with cq completion event notification */
 };
 
 struct irdma_aeq {
 	struct irdma_sc_aeq sc_aeq;
 	struct irdma_dma_mem mem;
 	struct irdma_pble_alloc palloc;
 	bool virtual_map;
 };
 
 struct irdma_arp_entry {
 	u32 ip_addr[4];
 	u8 mac_addr[ETHER_ADDR_LEN];
 };
 
 struct irdma_msix_vector {
 	u32 idx;
 	u32 irq;
 	u32 cpu_affinity;
 	u32 ceq_id;
 	char name[IRDMA_IRQ_NAME_STR_LEN];
 	struct resource *res;
 	void  *tag;
 };
 
 struct irdma_mc_table_info {
 	u32 mgn;
 	u32 dest_ip[4];
 	bool lan_fwd:1;
 	bool ipv4_valid:1;
 };
 
 struct mc_table_list {
 	struct list_head list;
 	struct irdma_mc_table_info mc_info;
 	struct irdma_mcast_grp_info mc_grp_ctx;
 };
 
 struct irdma_qv_info {
 	u32 v_idx; /* msix_vector */
 	u16 ceq_idx;
 	u16 aeq_idx;
 	u8 itr_idx;
 };
 
 struct irdma_qvlist_info {
 	u32 num_vectors;
 	struct irdma_qv_info qv_info[1];
 };
 
 struct irdma_gen_ops {
 	void (*request_reset)(struct irdma_pci_f *rf);
 	int (*register_qset)(struct irdma_sc_vsi *vsi,
 			     struct irdma_ws_node *tc_node);
 	void (*unregister_qset)(struct irdma_sc_vsi *vsi,
 				struct irdma_ws_node *tc_node);
 };
 
 struct irdma_pci_f {
 	bool reset:1;
 	bool rsrc_created:1;
 	bool msix_shared:1;
 	bool ftype:1;
 	u8 rsrc_profile;
 	u8 *hmc_info_mem;
 	u8 *mem_rsrc;
 	u8 rdma_ver;
 	u8 rst_to;
 	/* Not used in SRIOV VF mode */
 	u8 pf_id;
 	enum irdma_protocol_used protocol_used;
 	bool en_rem_endpoint_trk:1;
 	bool dcqcn_ena:1;
 	u32 sd_type;
 	u32 msix_count;
 	u32 max_mr;
 	u32 max_qp;
 	u32 max_cq;
 	u32 max_ah;
 	u32 next_ah;
 	u32 max_mcg;
 	u32 next_mcg;
 	u32 max_pd;
 	u32 next_qp;
 	u32 next_cq;
 	u32 next_pd;
 	u32 max_mr_size;
 	u32 max_cqe;
 	u32 mr_stagmask;
 	u32 used_pds;
 	u32 used_cqs;
 	u32 used_mrs;
 	u32 used_qps;
 	u32 arp_table_size;
 	u32 next_arp_index;
 	u32 ceqs_count;
 	u32 next_ws_node_id;
 	u32 max_ws_node_id;
 	u32 limits_sel;
 	unsigned long *allocated_ws_nodes;
 	unsigned long *allocated_qps;
 	unsigned long *allocated_cqs;
 	unsigned long *allocated_mrs;
 	unsigned long *allocated_pds;
 	unsigned long *allocated_mcgs;
 	unsigned long *allocated_ahs;
 	unsigned long *allocated_arps;
 	enum init_completion_state init_state;
 	struct irdma_sc_dev sc_dev;
 	struct irdma_dev_ctx dev_ctx;
 	struct irdma_tunable_info tun_info;
 	eventhandler_tag irdma_ifaddr_event;
 	struct irdma_handler *hdl;
 	struct pci_dev *pcidev;
 	struct ice_rdma_peer *peer_info;
 	struct irdma_hw hw;
 	struct irdma_cqp cqp;
 	struct irdma_ccq ccq;
 	struct irdma_aeq aeq;
 	struct irdma_ceq *ceqlist;
 	struct irdma_hmc_pble_rsrc *pble_rsrc;
 	struct irdma_arp_entry *arp_table;
 	spinlock_t arp_lock; /*protect ARP table access*/
 	spinlock_t rsrc_lock; /* protect HW resource array access */
 	spinlock_t qptable_lock; /*protect QP table access*/
 	spinlock_t cqtable_lock; /*protect CQ table access*/
 	struct irdma_qp **qp_table;
 	struct irdma_cq **cq_table;
 	spinlock_t qh_list_lock; /* protect mc_qht_list */
 	struct mc_table_list mc_qht_list;
 	struct irdma_msix_vector *iw_msixtbl;
 	struct irdma_qvlist_info *iw_qvlist;
 	struct tasklet_struct dpc_tasklet;
 	struct msix_entry msix_info;
 	struct irdma_dma_mem obj_mem;
 	struct irdma_dma_mem obj_next;
 	atomic_t vchnl_msgs;
 	wait_queue_head_t vchnl_waitq;
 	struct workqueue_struct *cqp_cmpl_wq;
 	struct work_struct cqp_cmpl_work;
 	struct irdma_sc_vsi default_vsi;
 	void *back_fcn;
 	struct irdma_gen_ops gen_ops;
 	void (*check_fc)(struct irdma_sc_vsi *vsi, struct irdma_sc_qp *sc_qp);
 	struct irdma_dcqcn_cc_params dcqcn_params;
 	struct irdma_device *iwdev;
 };
 
 struct irdma_device {
 	struct ib_device ibdev;
 	struct irdma_pci_f *rf;
 	if_t netdev;
 	struct notifier_block nb_netdevice_event;
 	struct irdma_handler *hdl;
 	struct workqueue_struct *cleanup_wq;
 	struct irdma_sc_vsi vsi;
 	struct irdma_cm_core cm_core;
 	u32 roce_cwnd;
 	u32 roce_ackcreds;
 	u32 vendor_id;
 	u32 vendor_part_id;
 	u32 push_mode;
 	u32 rcv_wnd;
 	u16 mac_ip_table_idx;
 	u16 vsi_num;
 	u8 rcv_wscale;
 	u8 iw_status;
 	u8 roce_rtomin;
 	u8 rd_fence_rate;
 	bool override_rcv_wnd:1;
 	bool override_cwnd:1;
 	bool override_ackcreds:1;
 	bool override_ooo:1;
 	bool override_rd_fence_rate:1;
 	bool override_rtomin:1;
 	bool roce_mode:1;
 	bool roce_dcqcn_en:1;
 	bool dcb_vlan_mode:1;
 	bool iw_ooo:1;
 	enum init_completion_state init_state;
 
 	wait_queue_head_t suspend_wq;
 };
 
 struct irdma_handler {
 	struct list_head list;
 	struct irdma_device *iwdev;
 	struct task deferred_task;
 	struct taskqueue *deferred_tq;
 	bool shared_res_created;
 };
 
 static inline struct irdma_device *to_iwdev(struct ib_device *ibdev)
 {
 	return container_of(ibdev, struct irdma_device, ibdev);
 }
 
 static inline struct irdma_ucontext *to_ucontext(struct ib_ucontext *ibucontext)
 {
 	return container_of(ibucontext, struct irdma_ucontext, ibucontext);
 }
 
 #if __FreeBSD_version >= 1400026
 static inline struct irdma_user_mmap_entry *
 to_irdma_mmap_entry(struct rdma_user_mmap_entry *rdma_entry)
 {
 	return container_of(rdma_entry, struct irdma_user_mmap_entry,
 			    rdma_entry);
 }
 
 #endif
 static inline struct irdma_pd *to_iwpd(struct ib_pd *ibpd)
 {
 	return container_of(ibpd, struct irdma_pd, ibpd);
 }
 
 static inline struct irdma_ah *to_iwah(struct ib_ah *ibah)
 {
 	return container_of(ibah, struct irdma_ah, ibah);
 }
 
 static inline struct irdma_mr *to_iwmr(struct ib_mr *ibmr)
 {
 	return container_of(ibmr, struct irdma_mr, ibmr);
 }
 
 static inline struct irdma_mr *to_iwmw(struct ib_mw *ibmw)
 {
 	return container_of(ibmw, struct irdma_mr, ibmw);
 }
 
 static inline struct irdma_cq *to_iwcq(struct ib_cq *ibcq)
 {
 	return container_of(ibcq, struct irdma_cq, ibcq);
 }
 
 static inline struct irdma_qp *to_iwqp(struct ib_qp *ibqp)
 {
 	return container_of(ibqp, struct irdma_qp, ibqp);
 }
 
 static inline struct irdma_pci_f *dev_to_rf(struct irdma_sc_dev *dev)
 {
 	return container_of(dev, struct irdma_pci_f, sc_dev);
 }
 
 /**
  * irdma_alloc_resource - allocate a resource
  * @iwdev: device pointer
  * @resource_array: resource bit array:
  * @max_resources: maximum resource number
  * @req_resources_num: Allocated resource number
  * @next: next free id
  **/
 static inline int irdma_alloc_rsrc(struct irdma_pci_f *rf,
 				   unsigned long *rsrc_array, u32 max_rsrc,
 				   u32 *req_rsrc_num, u32 *next)
 {
 	u32 rsrc_num;
 	unsigned long flags;
 
 	spin_lock_irqsave(&rf->rsrc_lock, flags);
 	rsrc_num = find_next_zero_bit(rsrc_array, max_rsrc, *next);
 	if (rsrc_num >= max_rsrc) {
 		rsrc_num = find_first_zero_bit(rsrc_array, max_rsrc);
 		if (rsrc_num >= max_rsrc) {
 			spin_unlock_irqrestore(&rf->rsrc_lock, flags);
 			irdma_debug(&rf->sc_dev, IRDMA_DEBUG_ERR,
 				    "resource [%d] allocation failed\n",
 				    rsrc_num);
 			return -EOVERFLOW;
 		}
 	}
 	__set_bit(rsrc_num, rsrc_array);
 	*next = rsrc_num + 1;
 	if (*next == max_rsrc)
 		*next = 0;
 	*req_rsrc_num = rsrc_num;
 	spin_unlock_irqrestore(&rf->rsrc_lock, flags);
 
 	return 0;
 }
 
 /**
  * irdma_free_resource - free a resource
  * @iwdev: device pointer
  * @resource_array: resource array for the resource_num
  * @resource_num: resource number to free
  **/
 static inline void irdma_free_rsrc(struct irdma_pci_f *rf,
 				   unsigned long *rsrc_array, u32 rsrc_num)
 {
 	unsigned long flags;
 
 	spin_lock_irqsave(&rf->rsrc_lock, flags);
 	__clear_bit(rsrc_num, rsrc_array);
 	spin_unlock_irqrestore(&rf->rsrc_lock, flags);
 }
 
 int irdma_ctrl_init_hw(struct irdma_pci_f *rf);
 void irdma_ctrl_deinit_hw(struct irdma_pci_f *rf);
 int irdma_rt_init_hw(struct irdma_device *iwdev,
 		     struct irdma_l2params *l2params);
 void irdma_rt_deinit_hw(struct irdma_device *iwdev);
 void irdma_qp_add_ref(struct ib_qp *ibqp);
 void irdma_qp_rem_ref(struct ib_qp *ibqp);
 void irdma_free_lsmm_rsrc(struct irdma_qp *iwqp);
 struct ib_qp *irdma_get_qp(struct ib_device *ibdev, int qpn);
 void irdma_flush_wqes(struct irdma_qp *iwqp, u32 flush_mask);
 void irdma_manage_arp_cache(struct irdma_pci_f *rf, const unsigned char *mac_addr,
 			    u32 *ip_addr, u32 action);
 struct irdma_apbvt_entry *irdma_add_apbvt(struct irdma_device *iwdev, u16 port);
 void irdma_del_apbvt(struct irdma_device *iwdev,
 		     struct irdma_apbvt_entry *entry);
 struct irdma_cqp_request *irdma_alloc_and_get_cqp_request(struct irdma_cqp *cqp,
 							  bool wait);
 void irdma_free_cqp_request(struct irdma_cqp *cqp,
 			    struct irdma_cqp_request *cqp_request);
 void irdma_put_cqp_request(struct irdma_cqp *cqp,
 			   struct irdma_cqp_request *cqp_request);
 int irdma_alloc_local_mac_entry(struct irdma_pci_f *rf, u16 *mac_tbl_idx);
 int irdma_add_local_mac_entry(struct irdma_pci_f *rf, const u8 *mac_addr, u16 idx);
 void irdma_del_local_mac_entry(struct irdma_pci_f *rf, u16 idx);
 const char *irdma_get_ae_desc(u16 ae_id);
 
 u32 irdma_initialize_hw_rsrc(struct irdma_pci_f *rf);
 void irdma_port_ibevent(struct irdma_device *iwdev);
 void irdma_cm_disconn(struct irdma_qp *qp);
 
 bool irdma_cqp_crit_err(struct irdma_sc_dev *dev, u8 cqp_cmd,
 			u16 maj_err_code, u16 min_err_code);
 int irdma_handle_cqp_op(struct irdma_pci_f *rf,
 			struct irdma_cqp_request *cqp_request);
 
 int irdma_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask,
 		    struct ib_udata *udata);
 int irdma_modify_qp_roce(struct ib_qp *ibqp, struct ib_qp_attr *attr,
 			 int attr_mask, struct ib_udata *udata);
 void irdma_cq_add_ref(struct ib_cq *ibcq);
 void irdma_cq_rem_ref(struct ib_cq *ibcq);
 void irdma_cq_wq_destroy(struct irdma_pci_f *rf, struct irdma_sc_cq *cq);
 
 void irdma_cleanup_pending_cqp_op(struct irdma_pci_f *rf);
 int irdma_hw_modify_qp(struct irdma_device *iwdev, struct irdma_qp *iwqp,
 		       struct irdma_modify_qp_info *info, bool wait);
 int irdma_qp_suspend_resume(struct irdma_sc_qp *qp, bool suspend);
 int irdma_manage_qhash(struct irdma_device *iwdev, struct irdma_cm_info *cminfo,
 		       enum irdma_quad_entry_type etype,
 		       enum irdma_quad_hash_manage_type mtype, void *cmnode,
 		       bool wait);
 void irdma_receive_ilq(struct irdma_sc_vsi *vsi, struct irdma_puda_buf *rbuf);
 void irdma_free_sqbuf(struct irdma_sc_vsi *vsi, void *bufp);
 void irdma_free_qp_rsrc(struct irdma_qp *iwqp);
 int irdma_setup_cm_core(struct irdma_device *iwdev, u8 ver);
 void irdma_cleanup_cm_core(struct irdma_cm_core *cm_core);
 void irdma_next_iw_state(struct irdma_qp *iwqp, u8 state, u8 del_hash, u8 term,
 			 u8 term_len);
 int irdma_send_syn(struct irdma_cm_node *cm_node, u32 sendack);
 int irdma_send_reset(struct irdma_cm_node *cm_node);
 struct irdma_cm_node *irdma_find_node(struct irdma_cm_core *cm_core,
 				      u16 rem_port, u32 *rem_addr, u16 loc_port,
 				      u32 *loc_addr, u16 vlan_id);
 int irdma_hw_flush_wqes(struct irdma_pci_f *rf, struct irdma_sc_qp *qp,
 			struct irdma_qp_flush_info *info, bool wait);
 void irdma_gen_ae(struct irdma_pci_f *rf, struct irdma_sc_qp *qp,
 		  struct irdma_gen_ae_info *info, bool wait);
 void irdma_copy_ip_ntohl(u32 *dst, __be32 *src);
 void irdma_copy_ip_htonl(__be32 *dst, u32 *src);
 u16 irdma_get_vlan_ipv4(struct iw_cm_id *cm_id, u32 *addr);
 if_t irdma_netdev_vlan_ipv6(struct iw_cm_id *cm_id, u32 *addr, u16 *vlan_id,
 			    u8 *mac);
 struct ib_mr *irdma_reg_phys_mr(struct ib_pd *ib_pd, u64 addr, u64 size,
 				int acc, u64 *iova_start);
 int irdma_upload_qp_context(struct irdma_qp *iwqp, bool freeze, bool raw);
 void irdma_del_hmc_objects(struct irdma_sc_dev *dev,
 			   struct irdma_hmc_info *hmc_info, bool privileged,
 			   bool reset, enum irdma_vers vers);
 void irdma_cqp_ce_handler(struct irdma_pci_f *rf, struct irdma_sc_cq *cq);
 int irdma_ah_cqp_op(struct irdma_pci_f *rf, struct irdma_sc_ah *sc_ah, u8 cmd,
 		    bool wait,
 		    void (*callback_fcn)(struct irdma_cqp_request *cqp_request),
 		    void *cb_param);
 void irdma_gsi_ud_qp_ah_cb(struct irdma_cqp_request *cqp_request);
 void irdma_udqp_qs_worker(struct work_struct *work);
 bool irdma_cq_empty(struct irdma_cq *iwcq);
 int irdma_netdevice_event(struct notifier_block *notifier, unsigned long event,
 			  void *ptr);
 void irdma_unregister_notifiers(struct irdma_device *iwdev);
 int irdma_register_notifiers(struct irdma_device *iwdev);
 void irdma_set_rf_user_cfg_params(struct irdma_pci_f *rf);
 void irdma_add_ip(struct irdma_device *iwdev);
 void irdma_add_handler(struct irdma_handler *hdl);
 void irdma_del_handler(struct irdma_handler *hdl);
 void cqp_compl_worker(struct work_struct *work);
 void irdma_cleanup_dead_qps(struct irdma_sc_vsi *vsi);
 #endif /* IRDMA_MAIN_H */