xref: /linux/drivers/bluetooth/btintel_pcie.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *
4  *  Bluetooth support for Intel PCIe devices
5  *
6  *  Copyright (C) 2024  Intel Corporation
7  */
8 
9 #include <linux/kernel.h>
10 #include <linux/module.h>
11 #include <linux/firmware.h>
12 #include <linux/overflow.h>
13 #include <linux/pci.h>
14 #include <linux/string.h>
15 #include <linux/wait.h>
16 #include <linux/delay.h>
17 #include <linux/interrupt.h>
18 #include <linux/acpi.h>
19 
20 #include <linux/unaligned.h>
21 #include <linux/devcoredump.h>
22 
23 #include <net/bluetooth/bluetooth.h>
24 #include <net/bluetooth/hci_core.h>
25 #include <net/bluetooth/hci_drv.h>
26 
27 #include "btintel.h"
28 #include "btintel_pcie.h"
29 
30 #define VERSION "0.1"
31 
32 #define BTINTEL_PCI_DEVICE(dev, subdev)	\
33 	.vendor = PCI_VENDOR_ID_INTEL,	\
34 	.device = (dev),		\
35 	.subvendor = PCI_ANY_ID,	\
36 	.subdevice = (subdev),		\
37 	.driver_data = 0
38 
39 #define POLL_INTERVAL_US	10
40 
41 #define BTINTEL_PCIE_DMA_ALIGN_128B	128 /* 128 byte aligned */
42 
43 /* Intel Bluetooth PCIe device id table */
44 static const struct pci_device_id btintel_pcie_table[] = {
45 	/* BlazarI, Wildcat Lake */
46 	{ BTINTEL_PCI_DEVICE(0x4D76, PCI_ANY_ID) },
47 	/* BlazarI, Lunar Lake */
48 	{ BTINTEL_PCI_DEVICE(0xA876, PCI_ANY_ID) },
49 	/* Scorpious, Panther Lake-H484 */
50 	{ BTINTEL_PCI_DEVICE(0xE376, PCI_ANY_ID) },
51 	 /* Scorpious, Panther Lake-H404 */
52 	{ BTINTEL_PCI_DEVICE(0xE476, PCI_ANY_ID) },
53 	 /* Scorpious2, Nova Lake-PCD-H */
54 	{ BTINTEL_PCI_DEVICE(0xD346, PCI_ANY_ID) },
55 	 /* Scorpious2, Nova Lake-PCD-S */
56 	{ BTINTEL_PCI_DEVICE(0x6E74, PCI_ANY_ID) },
57 	{ 0 }
58 };
59 MODULE_DEVICE_TABLE(pci, btintel_pcie_table);
60 
61 struct btintel_pcie_dev_recovery {
62 	struct list_head list;
63 	u8 count;
64 	time64_t last_error;
65 	char name[];
66 };
67 
68 /* Intel PCIe uses 4 bytes of HCI type instead of 1 byte BT SIG HCI type */
69 #define BTINTEL_PCIE_HCI_TYPE_LEN	4
70 #define BTINTEL_PCIE_HCI_CMD_PKT	0x00000001
71 #define BTINTEL_PCIE_HCI_ACL_PKT	0x00000002
72 #define BTINTEL_PCIE_HCI_SCO_PKT	0x00000003
73 #define BTINTEL_PCIE_HCI_EVT_PKT	0x00000004
74 #define BTINTEL_PCIE_HCI_ISO_PKT	0x00000005
75 
76 #define BTINTEL_PCIE_MAGIC_NUM    0xA5A5A5A5
77 
78 #define BTINTEL_PCIE_BLZR_HWEXP_SIZE		1024
79 #define BTINTEL_PCIE_BLZR_HWEXP_DMP_ADDR	0xB00A7C00
80 
81 #define BTINTEL_PCIE_SCP_HWEXP_SIZE		4096
82 #define BTINTEL_PCIE_SCP_HWEXP_DMP_ADDR		0xB030F800
83 
84 #define BTINTEL_PCIE_SCP2_HWEXP_SIZE		4096
85 #define BTINTEL_PCIE_SCP2_HWEXP_DMP_ADDR	0xB031D000
86 
87 #define BTINTEL_PCIE_MAGIC_NUM	0xA5A5A5A5
88 
89 #define BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER	0x17A2
90 #define BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT		0x1E61
91 
92 #define BTINTEL_PCIE_RESET_WINDOW_SECS		5
93 #define BTINTEL_PCIE_FLR_MAX_RETRY	1
94 
95 /* Alive interrupt context */
96 enum {
97 	BTINTEL_PCIE_ROM,
98 	BTINTEL_PCIE_FW_DL,
99 	BTINTEL_PCIE_HCI_RESET,
100 	BTINTEL_PCIE_INTEL_HCI_RESET1,
101 	BTINTEL_PCIE_INTEL_HCI_RESET2,
102 	BTINTEL_PCIE_D0,
103 	BTINTEL_PCIE_D3
104 };
105 
106 enum {
107 	BTINTEL_PCIE_DSM_SET_RESET_TIMING = 1,
108 	BTINTEL_PCIE_DSM_GET_RESET_TIMING = 2,
109 	BTINTEL_PCIE_DSM_BT_PLDR_CONFIG = 3,
110 	BTINTEL_PCIE_DSM_GET_RESET_TYPE = 4,
111 	BTINTEL_PCIE_DSM_DYNAMIC_PLDR = 5,
112 	BTINTEL_PCIE_DSM_GET_RESET_METHOD = 6,
113 	BTINTEL_PCIE_DSM_SET_PLDR_DELAY = 7,
114 };
115 
116 enum btintel_dsm_internal_product_reset_mode {
117 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_PROD_RESET	= BIT(0),
118 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_WIFI_FLR		= BIT(1),
119 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_BT_OFF_ON		= BIT(2),
120 };
121 
122 /* Structure for dbgc fragment buffer
123  * @buf_addr_lsb: LSB of the buffer's physical address
124  * @buf_addr_msb: MSB of the buffer's physical address
125  * @buf_size: Total size of the buffer
126  */
127 struct btintel_pcie_dbgc_ctxt_buf {
128 	u32	buf_addr_lsb;
129 	u32	buf_addr_msb;
130 	u32	buf_size;
131 };
132 
133 /* Structure for dbgc fragment
134  * @magic_num: 0XA5A5A5A5
135  * @ver: For Driver-FW compatibility
136  * @total_size: Total size of the payload debug info
137  * @num_buf: Num of allocated debug bufs
138  * @bufs: All buffer's addresses and sizes
139  */
140 struct btintel_pcie_dbgc_ctxt {
141 	u32	magic_num;
142 	u32     ver;
143 	u32     total_size;
144 	u32     num_buf;
145 	struct btintel_pcie_dbgc_ctxt_buf bufs[BTINTEL_PCIE_DBGC_BUFFER_COUNT];
146 };
147 
148 struct btintel_pcie_trigger_evt {
149 	u8 type;
150 	u8 len;
151 	__le32 addr;
152 	__le32 size;
153 } __packed;
154 
155 struct btintel_pcie_fwtrigger_evt {
156 	__le32 reserved;
157 	u8	type; /* Debug Trigger event */
158 	__le16	len;
159 	u8	event_type;
160 	__le16	event_id;
161 	__le16	reserved2;
162 } __packed;
163 
164 static LIST_HEAD(btintel_pcie_recovery_list);
165 static DEFINE_SPINLOCK(btintel_pcie_recovery_lock);
166 
167 static inline char *btintel_pcie_alivectxt_state2str(u32 alive_intr_ctxt)
168 {
169 	switch (alive_intr_ctxt) {
170 	case BTINTEL_PCIE_ROM:
171 		return "rom";
172 	case BTINTEL_PCIE_FW_DL:
173 		return "fw_dl";
174 	case BTINTEL_PCIE_D0:
175 		return "d0";
176 	case BTINTEL_PCIE_D3:
177 		return "d3";
178 	case BTINTEL_PCIE_HCI_RESET:
179 		return "hci_reset";
180 	case BTINTEL_PCIE_INTEL_HCI_RESET1:
181 		return "intel_reset1";
182 	case BTINTEL_PCIE_INTEL_HCI_RESET2:
183 		return "intel_reset2";
184 	default:
185 		return "unknown";
186 	}
187 }
188 
189 /* This function initializes the memory for DBGC buffers and formats the
190  * DBGC fragment which consists header info and DBGC buffer's LSB, MSB and
191  * size as the payload
192  */
193 static int btintel_pcie_setup_dbgc(struct btintel_pcie_data *data)
194 {
195 	struct btintel_pcie_dbgc_ctxt db_frag;
196 	struct data_buf *buf;
197 	int i;
198 
199 	data->dbgc.count = BTINTEL_PCIE_DBGC_BUFFER_COUNT;
200 	data->dbgc.bufs = devm_kcalloc(&data->pdev->dev, data->dbgc.count,
201 				       sizeof(*buf), GFP_KERNEL);
202 	if (!data->dbgc.bufs)
203 		return -ENOMEM;
204 
205 	data->dbgc.buf_v_addr = dmam_alloc_coherent(&data->pdev->dev,
206 						    data->dbgc.count *
207 						    BTINTEL_PCIE_DBGC_BUFFER_SIZE,
208 						    &data->dbgc.buf_p_addr,
209 						    GFP_KERNEL | __GFP_NOWARN);
210 	if (!data->dbgc.buf_v_addr)
211 		return -ENOMEM;
212 
213 	data->dbgc.frag_v_addr = dmam_alloc_coherent(&data->pdev->dev,
214 						     sizeof(struct btintel_pcie_dbgc_ctxt),
215 						     &data->dbgc.frag_p_addr,
216 						     GFP_KERNEL | __GFP_NOWARN);
217 	if (!data->dbgc.frag_v_addr)
218 		return -ENOMEM;
219 
220 	data->dbgc.frag_size = sizeof(struct btintel_pcie_dbgc_ctxt);
221 
222 	db_frag.magic_num = BTINTEL_PCIE_MAGIC_NUM;
223 	db_frag.ver = BTINTEL_PCIE_DBGC_FRAG_VERSION;
224 	db_frag.total_size = BTINTEL_PCIE_DBGC_FRAG_PAYLOAD_SIZE;
225 	db_frag.num_buf = BTINTEL_PCIE_DBGC_FRAG_BUFFER_COUNT;
226 
227 	for (i = 0; i < data->dbgc.count; i++) {
228 		buf = &data->dbgc.bufs[i];
229 		buf->data_p_addr = data->dbgc.buf_p_addr + i * BTINTEL_PCIE_DBGC_BUFFER_SIZE;
230 		buf->data = data->dbgc.buf_v_addr + i * BTINTEL_PCIE_DBGC_BUFFER_SIZE;
231 		db_frag.bufs[i].buf_addr_lsb = lower_32_bits(buf->data_p_addr);
232 		db_frag.bufs[i].buf_addr_msb = upper_32_bits(buf->data_p_addr);
233 		db_frag.bufs[i].buf_size = BTINTEL_PCIE_DBGC_BUFFER_SIZE;
234 	}
235 
236 	memcpy(data->dbgc.frag_v_addr, &db_frag, sizeof(db_frag));
237 	return 0;
238 }
239 
240 static inline void ipc_print_ia_ring(struct hci_dev *hdev, struct ia *ia,
241 				     u16 queue_num)
242 {
243 	bt_dev_dbg(hdev, "IA: %s: tr-h:%02u  tr-t:%02u  cr-h:%02u  cr-t:%02u",
244 		   queue_num == BTINTEL_PCIE_TXQ_NUM ? "TXQ" : "RXQ",
245 		   ia->tr_hia[queue_num], ia->tr_tia[queue_num],
246 		   ia->cr_hia[queue_num], ia->cr_tia[queue_num]);
247 }
248 
249 static inline void ipc_print_urbd1(struct hci_dev *hdev, struct urbd1 *urbd1,
250 				   u16 index)
251 {
252 	bt_dev_dbg(hdev, "RXQ:urbd1(%u) frbd_tag:%u status: 0x%x fixed:0x%x",
253 		   index, urbd1->frbd_tag, urbd1->status, urbd1->fixed);
254 }
255 
256 static struct btintel_pcie_data *btintel_pcie_get_data(struct msix_entry *entry)
257 {
258 	u8 queue = entry->entry;
259 	struct msix_entry *entries = entry - queue;
260 
261 	return container_of(entries, struct btintel_pcie_data, msix_entries[0]);
262 }
263 
264 /* Set the doorbell for TXQ to notify the device that @index (actually index-1)
265  * of the TFD is updated and ready to transmit.
266  */
267 static void btintel_pcie_set_tx_db(struct btintel_pcie_data *data, u16 index)
268 {
269 	u32 val;
270 
271 	val = index;
272 	val |= (BTINTEL_PCIE_TX_DB_VEC << 16);
273 
274 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_HBUS_TARG_WRPTR, val);
275 }
276 
277 /* Copy the data to next(@tfd_index) data buffer and update the TFD(transfer
278  * descriptor) with the data length and the DMA address of the data buffer.
279  */
280 static void btintel_pcie_prepare_tx(struct txq *txq, u16 tfd_index,
281 				    struct sk_buff *skb)
282 {
283 	struct data_buf *buf;
284 	struct tfd *tfd;
285 
286 	tfd = &txq->tfds[tfd_index];
287 	memset(tfd, 0, sizeof(*tfd));
288 
289 	buf = &txq->bufs[tfd_index];
290 
291 	tfd->size = skb->len;
292 	tfd->addr = buf->data_p_addr;
293 
294 	/* Copy the outgoing data to DMA buffer */
295 	memcpy(buf->data, skb->data, tfd->size);
296 }
297 
298 static inline void btintel_pcie_dump_debug_registers(struct hci_dev *hdev)
299 {
300 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
301 	u16 cr_hia, cr_tia;
302 	u32 reg, mbox_reg;
303 	struct sk_buff *skb;
304 	u8 buf[80];
305 
306 	skb = alloc_skb(1024, GFP_ATOMIC);
307 	if (!skb)
308 		return;
309 
310 	strscpy(buf, "---- Dump of debug registers ---");
311 	bt_dev_dbg(hdev, "%s", buf);
312 	skb_put_data(skb, buf, strlen(buf));
313 
314 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
315 	snprintf(buf, sizeof(buf), "boot stage: 0x%8.8x", reg);
316 	bt_dev_dbg(hdev, "%s", buf);
317 	skb_put_data(skb, buf, strlen(buf));
318 	data->boot_stage_cache = reg;
319 
320 	if (reg & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_WARNING)
321 		bt_dev_warn(hdev, "Controller device warning (boot_stage: 0x%8.8x)", reg);
322 
323 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_STATUS_REG);
324 	snprintf(buf, sizeof(buf), "ipc status: 0x%8.8x", reg);
325 	skb_put_data(skb, buf, strlen(buf));
326 	bt_dev_dbg(hdev, "%s", buf);
327 
328 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_CONTROL_REG);
329 	snprintf(buf, sizeof(buf), "ipc control: 0x%8.8x", reg);
330 	skb_put_data(skb, buf, strlen(buf));
331 	bt_dev_dbg(hdev, "%s", buf);
332 
333 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_SLEEP_CTL_REG);
334 	snprintf(buf, sizeof(buf), "ipc sleep control: 0x%8.8x", reg);
335 	skb_put_data(skb, buf, strlen(buf));
336 	bt_dev_dbg(hdev, "%s", buf);
337 
338 	/*Read the Mail box status and registers*/
339 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_STATUS_REG);
340 	snprintf(buf, sizeof(buf), "mbox status: 0x%8.8x", reg);
341 	skb_put_data(skb, buf, strlen(buf));
342 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX1) {
343 		mbox_reg = btintel_pcie_rd_reg32(data,
344 						 BTINTEL_PCIE_CSR_MBOX_1_REG);
345 		snprintf(buf, sizeof(buf), "mbox_1: 0x%8.8x", mbox_reg);
346 		skb_put_data(skb, buf, strlen(buf));
347 		bt_dev_dbg(hdev, "%s", buf);
348 	}
349 
350 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX2) {
351 		mbox_reg = btintel_pcie_rd_reg32(data,
352 						 BTINTEL_PCIE_CSR_MBOX_2_REG);
353 		snprintf(buf, sizeof(buf), "mbox_2: 0x%8.8x", mbox_reg);
354 		skb_put_data(skb, buf, strlen(buf));
355 		bt_dev_dbg(hdev, "%s", buf);
356 	}
357 
358 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX3) {
359 		mbox_reg = btintel_pcie_rd_reg32(data,
360 						 BTINTEL_PCIE_CSR_MBOX_3_REG);
361 		snprintf(buf, sizeof(buf), "mbox_3: 0x%8.8x", mbox_reg);
362 		skb_put_data(skb, buf, strlen(buf));
363 		bt_dev_dbg(hdev, "%s", buf);
364 	}
365 
366 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX4) {
367 		mbox_reg = btintel_pcie_rd_reg32(data,
368 						 BTINTEL_PCIE_CSR_MBOX_4_REG);
369 		snprintf(buf, sizeof(buf), "mbox_4: 0x%8.8x", mbox_reg);
370 		skb_put_data(skb, buf, strlen(buf));
371 		bt_dev_dbg(hdev, "%s", buf);
372 	}
373 
374 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM];
375 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
376 	snprintf(buf, sizeof(buf), "rxq: cr_tia: %u cr_hia: %u", cr_tia, cr_hia);
377 	skb_put_data(skb, buf, strlen(buf));
378 	bt_dev_dbg(hdev, "%s", buf);
379 
380 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
381 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM];
382 	snprintf(buf, sizeof(buf), "txq: cr_tia: %u cr_hia: %u", cr_tia, cr_hia);
383 	skb_put_data(skb, buf, strlen(buf));
384 	bt_dev_dbg(hdev, "%s", buf);
385 	strscpy(buf, "--------------------------------");
386 	bt_dev_dbg(hdev, "%s", buf);
387 
388 	hci_recv_diag(hdev, skb);
389 }
390 
391 static int btintel_pcie_send_sync(struct btintel_pcie_data *data,
392 				  struct sk_buff *skb, u32 pkt_type, u16 opcode)
393 {
394 	int ret;
395 	u16 tfd_index;
396 	u32 old_ctxt;
397 	bool wait_on_alive = false;
398 	struct hci_dev *hdev = data->hdev;
399 
400 	struct txq *txq = &data->txq;
401 
402 	tfd_index = data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM];
403 
404 	if (tfd_index > txq->count)
405 		return -ERANGE;
406 
407 	/* Firmware raises alive interrupt on HCI_OP_RESET or
408 	 * BTINTEL_HCI_OP_RESET
409 	 */
410 	wait_on_alive = (pkt_type == BTINTEL_PCIE_HCI_CMD_PKT &&
411 		(opcode == BTINTEL_HCI_OP_RESET || opcode == HCI_OP_RESET));
412 
413 	if (wait_on_alive) {
414 		data->gp0_received = false;
415 		old_ctxt = data->alive_intr_ctxt;
416 		data->alive_intr_ctxt =
417 			(opcode == BTINTEL_HCI_OP_RESET ? BTINTEL_PCIE_INTEL_HCI_RESET1 :
418 				BTINTEL_PCIE_HCI_RESET);
419 		bt_dev_dbg(data->hdev, "sending cmd: 0x%4.4x alive context changed: %s  ->  %s",
420 			   opcode, btintel_pcie_alivectxt_state2str(old_ctxt),
421 			   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
422 	}
423 
424 	memcpy(skb_push(skb, BTINTEL_PCIE_HCI_TYPE_LEN), &pkt_type,
425 	       BTINTEL_PCIE_HCI_TYPE_LEN);
426 
427 	/* Prepare for TX. It updates the TFD with the length of data and
428 	 * address of the DMA buffer, and copy the data to the DMA buffer
429 	 */
430 	btintel_pcie_prepare_tx(txq, tfd_index, skb);
431 
432 	tfd_index = (tfd_index + 1) % txq->count;
433 	data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM] = tfd_index;
434 
435 	/* Arm wait event condition */
436 	data->tx_wait_done = false;
437 
438 	/* Set the doorbell to notify the device */
439 	btintel_pcie_set_tx_db(data, tfd_index);
440 
441 	/* Wait for the complete interrupt - URBD0 */
442 	ret = wait_event_timeout(data->tx_wait_q, data->tx_wait_done,
443 				 msecs_to_jiffies(BTINTEL_PCIE_TX_WAIT_TIMEOUT_MS));
444 	if (!ret) {
445 		bt_dev_err(data->hdev, "Timeout (%u ms) on tx completion",
446 			   BTINTEL_PCIE_TX_WAIT_TIMEOUT_MS);
447 		btintel_pcie_dump_debug_registers(data->hdev);
448 		return -ETIME;
449 	}
450 
451 	if (wait_on_alive) {
452 		ret = wait_event_timeout(data->gp0_wait_q,
453 					 data->gp0_received,
454 					 msecs_to_jiffies(BTINTEL_DEFAULT_INTR_TIMEOUT_MS));
455 		if (!ret) {
456 			hdev->stat.err_tx++;
457 			bt_dev_err(hdev, "Timeout (%u ms)  on alive interrupt, alive context: %s",
458 				   BTINTEL_DEFAULT_INTR_TIMEOUT_MS,
459 				   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
460 			return  -ETIME;
461 		}
462 	}
463 	return 0;
464 }
465 
466 /* Set the doorbell for RXQ to notify the device that @index (actually index-1)
467  * is available to receive the data
468  */
469 static void btintel_pcie_set_rx_db(struct btintel_pcie_data *data, u16 index)
470 {
471 	u32 val;
472 
473 	val = index;
474 	val |= (BTINTEL_PCIE_RX_DB_VEC << 16);
475 
476 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_HBUS_TARG_WRPTR, val);
477 }
478 
479 /* Update the FRBD (free buffer descriptor) with the @frbd_index and the
480  * DMA address of the free buffer.
481  */
482 static void btintel_pcie_prepare_rx(struct rxq *rxq, u16 frbd_index)
483 {
484 	struct data_buf *buf;
485 	struct frbd *frbd;
486 
487 	/* Get the buffer of the FRBD for DMA */
488 	buf = &rxq->bufs[frbd_index];
489 
490 	frbd = &rxq->frbds[frbd_index];
491 	memset(frbd, 0, sizeof(*frbd));
492 
493 	/* Update FRBD */
494 	frbd->tag = frbd_index;
495 	frbd->addr = buf->data_p_addr;
496 }
497 
498 static int btintel_pcie_submit_rx(struct btintel_pcie_data *data)
499 {
500 	u16 frbd_index;
501 	struct rxq *rxq = &data->rxq;
502 
503 	frbd_index = data->ia.tr_hia[BTINTEL_PCIE_RXQ_NUM];
504 
505 	if (frbd_index > rxq->count)
506 		return -ERANGE;
507 
508 	/* Prepare for RX submit. It updates the FRBD with the address of DMA
509 	 * buffer
510 	 */
511 	btintel_pcie_prepare_rx(rxq, frbd_index);
512 
513 	frbd_index = (frbd_index + 1) % rxq->count;
514 	data->ia.tr_hia[BTINTEL_PCIE_RXQ_NUM] = frbd_index;
515 	ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_RXQ_NUM);
516 
517 	/* Set the doorbell to notify the device */
518 	btintel_pcie_set_rx_db(data, frbd_index);
519 
520 	return 0;
521 }
522 
523 static int btintel_pcie_start_rx(struct btintel_pcie_data *data)
524 {
525 	int i, ret;
526 	struct rxq *rxq = &data->rxq;
527 
528 	/* Post (BTINTEL_PCIE_RX_DESCS_COUNT - 3) buffers to overcome the
529 	 * hardware issues leading to race condition at the firmware.
530 	 */
531 
532 	for (i = 0; i < rxq->count - 3; i++) {
533 		ret = btintel_pcie_submit_rx(data);
534 		if (ret)
535 			return ret;
536 	}
537 
538 	return 0;
539 }
540 
541 static void btintel_pcie_reset_ia(struct btintel_pcie_data *data)
542 {
543 	memset(data->ia.tr_hia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
544 	memset(data->ia.tr_tia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
545 	memset(data->ia.cr_hia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
546 	memset(data->ia.cr_tia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
547 }
548 
549 static int btintel_pcie_reset_bt(struct btintel_pcie_data *data)
550 {
551 	u32 reg;
552 	int retry = 3;
553 
554 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
555 
556 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
557 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT |
558 			BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
559 	reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON;
560 
561 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
562 
563 	do {
564 		reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
565 		if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_STS)
566 			break;
567 		usleep_range(10000, 12000);
568 
569 	} while (--retry > 0);
570 	usleep_range(10000, 12000);
571 
572 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
573 
574 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
575 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT |
576 			BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
577 	reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET;
578 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
579 	usleep_range(10000, 12000);
580 
581 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
582 	bt_dev_dbg(data->hdev, "csr register after reset: 0x%8.8x", reg);
583 
584 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
585 
586 	/* If shared hardware reset is success then boot stage register shall be
587 	 * set to 0
588 	 */
589 	return reg == 0 ? 0 : -ENODEV;
590 }
591 
592 static void btintel_pcie_mac_init(struct btintel_pcie_data *data)
593 {
594 	u32 reg;
595 
596 	/* Set MAC_INIT bit to start primary bootloader */
597 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
598 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT |
599 			BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON |
600 			BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET);
601 	reg |= (BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
602 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT);
603 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
604 }
605 
606 static int btintel_pcie_get_mac_access(struct btintel_pcie_data *data)
607 {
608 	u32 reg;
609 	int retry = 15;
610 
611 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
612 
613 	if (!(reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ)) {
614 		reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ;
615 		btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
616 	}
617 
618 	do {
619 		reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
620 		if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_STS)
621 			return 0;
622 		/* Need delay here for Target Access harwdware to settle down*/
623 		usleep_range(1000, 1200);
624 
625 	} while (--retry > 0);
626 
627 	return -ETIME;
628 }
629 
630 static void btintel_pcie_release_mac_access(struct btintel_pcie_data *data)
631 {
632 	u32 reg;
633 
634 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
635 
636 	if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ) {
637 		reg &= ~BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ;
638 		btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
639 	}
640 }
641 
642 static void *btintel_pcie_copy_tlv(void *dest, enum btintel_pcie_tlv_type type,
643 				   void *data, size_t size)
644 {
645 	struct intel_tlv *tlv;
646 
647 	tlv = dest;
648 	tlv->type = type;
649 	tlv->len = size;
650 	memcpy(tlv->val, data, tlv->len);
651 	return dest + sizeof(*tlv) + size;
652 }
653 
654 static int btintel_pcie_read_dram_buffers(struct btintel_pcie_data *data)
655 {
656 	u32 offset, prev_size, wr_ptr_status, dump_size, data_len;
657 	u32 status_reg, wrap_reg;
658 	struct btintel_pcie_dbgc *dbgc = &data->dbgc;
659 	struct hci_dev *hdev = data->hdev;
660 	u8 *pdata, *p, buf_idx, hw_variant;
661 	struct intel_tlv *tlv;
662 	struct timespec64 now;
663 	struct tm tm_now;
664 	char fw_build[128];
665 	char ts[128];
666 	char vendor[64];
667 	char driver[64];
668 
669 	if (!IS_ENABLED(CONFIG_DEV_COREDUMP))
670 		return -EOPNOTSUPP;
671 
672 
673 	hw_variant = INTEL_HW_VARIANT(data->cnvi);
674 	switch (hw_variant) {
675 	case BTINTEL_HWID_BZRI:
676 	case BTINTEL_HWID_BZRIW:
677 		status_reg = BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS;
678 		wrap_reg = BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND;
679 		break;
680 	case BTINTEL_HWID_SCP:
681 	case BTINTEL_HWID_SCP2:
682 	case BTINTEL_HWID_SCP2F:
683 		status_reg = BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS_SCP;
684 		wrap_reg = BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND_SCP;
685 		break;
686 	default:
687 		bt_dev_err(hdev, "Unsupported Intel hardware variant (0x%2.2x)",
688 			   hw_variant);
689 		return -EINVAL;
690 	}
691 
692 	wr_ptr_status = btintel_pcie_rd_dev_mem(data, status_reg);
693 	data->dmp_hdr.wrap_ctr = btintel_pcie_rd_dev_mem(data, wrap_reg);
694 
695 	offset = wr_ptr_status & BTINTEL_PCIE_DBG_OFFSET_BIT_MASK;
696 
697 	buf_idx = BTINTEL_PCIE_DBGC_DBG_BUF_IDX(wr_ptr_status);
698 	if (buf_idx > dbgc->count) {
699 		bt_dev_warn(hdev, "Buffer index is invalid");
700 		return -EINVAL;
701 	}
702 
703 	prev_size = buf_idx * BTINTEL_PCIE_DBGC_BUFFER_SIZE;
704 	if (prev_size + offset >= prev_size)
705 		data->dmp_hdr.write_ptr = prev_size + offset;
706 	else
707 		return -EINVAL;
708 
709 	strscpy(vendor, "Vendor: Intel\n");
710 	snprintf(driver, sizeof(driver), "Driver: %s\n",
711 		 data->dmp_hdr.driver_name);
712 
713 	ktime_get_real_ts64(&now);
714 	time64_to_tm(now.tv_sec, 0, &tm_now);
715 	snprintf(ts, sizeof(ts), "Dump Time: %02d-%02d-%04ld %02d:%02d:%02d",
716 				 tm_now.tm_mday, tm_now.tm_mon + 1, tm_now.tm_year + 1900,
717 				 tm_now.tm_hour, tm_now.tm_min, tm_now.tm_sec);
718 
719 	snprintf(fw_build, sizeof(fw_build),
720 			    "Firmware Timestamp: Year %u WW %02u buildtype %u build %u",
721 			    2000 + (data->dmp_hdr.fw_timestamp >> 8),
722 			    data->dmp_hdr.fw_timestamp & 0xff, data->dmp_hdr.fw_build_type,
723 			    data->dmp_hdr.fw_build_num);
724 
725 	data_len = sizeof(*tlv) + sizeof(data->dmp_hdr.cnvi_bt) +
726 		sizeof(*tlv) + sizeof(data->dmp_hdr.write_ptr) +
727 		sizeof(*tlv) + sizeof(data->dmp_hdr.wrap_ctr) +
728 		sizeof(*tlv) + sizeof(data->dmp_hdr.trigger_reason) +
729 		sizeof(*tlv) + sizeof(data->dmp_hdr.fw_git_sha1) +
730 		sizeof(*tlv) + sizeof(data->dmp_hdr.cnvr_top) +
731 		sizeof(*tlv) + sizeof(data->dmp_hdr.cnvi_top) +
732 		sizeof(*tlv) + strlen(ts) +
733 		sizeof(*tlv) + strlen(fw_build) +
734 		sizeof(*tlv) + strlen(vendor) +
735 		sizeof(*tlv) + strlen(driver);
736 
737 	if (data->dmp_hdr.event_type && data->dmp_hdr.event_id) {
738 		data_len += sizeof(*tlv) + sizeof(data->dmp_hdr.event_type);
739 		data_len += sizeof(*tlv) + sizeof(data->dmp_hdr.event_id);
740 	}
741 
742 	/*
743 	 * sizeof(u32) - signature
744 	 * sizeof(data_len) - to store tlv data size
745 	 * data_len - TLV data
746 	 */
747 	dump_size = sizeof(u32) + sizeof(data_len) + data_len;
748 
749 
750 	/* Add debug buffers data length to dump size */
751 	dump_size += BTINTEL_PCIE_DBGC_BUFFER_SIZE * dbgc->count;
752 
753 	pdata = vmalloc(dump_size);
754 	if (!pdata)
755 		return -ENOMEM;
756 	p = pdata;
757 
758 	*(u32 *)p = BTINTEL_PCIE_MAGIC_NUM;
759 	p += sizeof(u32);
760 
761 	*(u32 *)p = data_len;
762 	p += sizeof(u32);
763 
764 
765 	p = btintel_pcie_copy_tlv(p, BTINTEL_VENDOR, vendor, strlen(vendor));
766 	p = btintel_pcie_copy_tlv(p, BTINTEL_DRIVER, driver, strlen(driver));
767 	p = btintel_pcie_copy_tlv(p, BTINTEL_DUMP_TIME, ts, strlen(ts));
768 	p = btintel_pcie_copy_tlv(p, BTINTEL_FW_BUILD, fw_build,
769 				  strlen(fw_build));
770 	p = btintel_pcie_copy_tlv(p, BTINTEL_CNVI_BT, &data->dmp_hdr.cnvi_bt,
771 				  sizeof(data->dmp_hdr.cnvi_bt));
772 	p = btintel_pcie_copy_tlv(p, BTINTEL_WRITE_PTR, &data->dmp_hdr.write_ptr,
773 				  sizeof(data->dmp_hdr.write_ptr));
774 	p = btintel_pcie_copy_tlv(p, BTINTEL_WRAP_CTR, &data->dmp_hdr.wrap_ctr,
775 				  sizeof(data->dmp_hdr.wrap_ctr));
776 	p = btintel_pcie_copy_tlv(p, BTINTEL_TRIGGER_REASON, &data->dmp_hdr.trigger_reason,
777 				  sizeof(data->dmp_hdr.trigger_reason));
778 	p = btintel_pcie_copy_tlv(p, BTINTEL_FW_SHA, &data->dmp_hdr.fw_git_sha1,
779 				  sizeof(data->dmp_hdr.fw_git_sha1));
780 	p = btintel_pcie_copy_tlv(p, BTINTEL_CNVR_TOP, &data->dmp_hdr.cnvr_top,
781 				  sizeof(data->dmp_hdr.cnvr_top));
782 	p = btintel_pcie_copy_tlv(p, BTINTEL_CNVI_TOP, &data->dmp_hdr.cnvi_top,
783 				  sizeof(data->dmp_hdr.cnvi_top));
784 
785 	if (data->dmp_hdr.event_type && data->dmp_hdr.event_id) {
786 		p = btintel_pcie_copy_tlv(p, BTINTEL_EVENT_TYPE,
787 					  &data->dmp_hdr.event_type,
788 					  sizeof(data->dmp_hdr.event_type));
789 		p = btintel_pcie_copy_tlv(p, BTINTEL_EVENT_ID,
790 					  &data->dmp_hdr.event_id,
791 					  sizeof(data->dmp_hdr.event_id));
792 		data->dmp_hdr.event_type = 0;
793 		data->dmp_hdr.event_id = 0;
794 	}
795 
796 	memcpy(p, dbgc->bufs[0].data, dbgc->count * BTINTEL_PCIE_DBGC_BUFFER_SIZE);
797 	dev_coredumpv(&hdev->dev, pdata, dump_size, GFP_KERNEL);
798 	return 0;
799 }
800 
801 static void btintel_pcie_dump_traces(struct hci_dev *hdev)
802 {
803 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
804 	int ret = 0;
805 
806 	ret = btintel_pcie_get_mac_access(data);
807 	if (ret) {
808 		bt_dev_err(hdev, "Failed to get mac access: (%d)", ret);
809 		return;
810 	}
811 
812 	ret = btintel_pcie_read_dram_buffers(data);
813 
814 	btintel_pcie_release_mac_access(data);
815 
816 	if (ret)
817 		bt_dev_err(hdev, "Failed to dump traces: (%d)", ret);
818 }
819 
820 static bool btintel_pcie_is_blazariw(struct pci_dev *pdev)
821 {
822 	return pdev->device == 0x4D76;
823 }
824 
825 /* This function enables BT function by setting BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT bit in
826  * BTINTEL_PCIE_CSR_FUNC_CTRL_REG register and wait for MSI-X with
827  * BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0.
828  * Then the host reads firmware version from BTINTEL_CSR_F2D_MBX and the boot stage
829  * from BTINTEL_PCIE_CSR_BOOT_STAGE_REG.
830  */
831 static int btintel_pcie_enable_bt(struct btintel_pcie_data *data)
832 {
833 	int err;
834 	u32 reg;
835 
836 	data->gp0_received = false;
837 
838 	/* Update the DMA address of CI struct to CSR */
839 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_CI_ADDR_LSB_REG,
840 			      data->ci_p_addr & 0xffffffff);
841 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_CI_ADDR_MSB_REG,
842 			      (u64)data->ci_p_addr >> 32);
843 
844 	/* On BlazarIW, the D0 entry to MAC init does not complete in
845 	 * time. Wait 50 ms (worst case as per HW analysis) for the
846 	 * shared hardware reset flow to complete before proceeding with
847 	 * MAC init.
848 	 */
849 	if (btintel_pcie_is_blazariw(data->pdev))
850 		msleep(50);
851 
852 	/* Reset the cached value of boot stage. it is updated by the MSI-X
853 	 * gp0 interrupt handler.
854 	 */
855 	data->boot_stage_cache = 0x0;
856 
857 	/* Set MAC_INIT bit to start primary bootloader */
858 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
859 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT |
860 			BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON |
861 			BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET);
862 	reg |= (BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
863 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT);
864 
865 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
866 
867 	/* MAC is ready. Enable BT FUNC */
868 	btintel_pcie_set_reg_bits(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG,
869 				  BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
870 
871 	btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
872 
873 	/* wait for interrupt from the device after booting up to primary
874 	 * bootloader.
875 	 */
876 	data->alive_intr_ctxt = BTINTEL_PCIE_ROM;
877 	err = wait_event_timeout(data->gp0_wait_q, data->gp0_received,
878 				 msecs_to_jiffies(BTINTEL_DEFAULT_INTR_TIMEOUT_MS));
879 	if (!err)
880 		return -ETIME;
881 
882 	/* Check cached boot stage is BTINTEL_PCIE_CSR_BOOT_STAGE_ROM(BIT(0)) */
883 	if (~data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_ROM)
884 		return -ENODEV;
885 
886 	return 0;
887 }
888 
889 static inline bool btintel_pcie_in_op(struct btintel_pcie_data *data)
890 {
891 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_OPFW;
892 }
893 
894 static inline bool btintel_pcie_in_iml(struct btintel_pcie_data *data)
895 {
896 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_IML &&
897 		!(data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_OPFW);
898 }
899 
900 static inline bool btintel_pcie_in_d3(struct btintel_pcie_data *data)
901 {
902 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_D3_STATE_READY;
903 }
904 
905 static inline bool btintel_pcie_in_d0(struct btintel_pcie_data *data)
906 {
907 	return !(data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_D3_STATE_READY);
908 }
909 
910 static inline bool btintel_pcie_in_device_halt(struct btintel_pcie_data *data)
911 {
912 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_HALTED;
913 }
914 
915 static void btintel_pcie_wr_sleep_cntrl(struct btintel_pcie_data *data,
916 					u32 dxstate)
917 {
918 	bt_dev_dbg(data->hdev, "writing sleep_ctl_reg: 0x%8.8x", dxstate);
919 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_IPC_SLEEP_CTL_REG, dxstate);
920 }
921 
922 static int btintel_pcie_read_device_mem(struct btintel_pcie_data *data,
923 					void *buf, u32 dev_addr, int len)
924 {
925 	int err;
926 	u32 *val = buf;
927 
928 	/* Get device mac access */
929 	err = btintel_pcie_get_mac_access(data);
930 	if (err) {
931 		bt_dev_err(data->hdev, "Failed to get mac access %d", err);
932 		return err;
933 	}
934 
935 	for (; len > 0; len -= 4, dev_addr += 4, val++)
936 		*val = btintel_pcie_rd_dev_mem(data, dev_addr);
937 
938 	btintel_pcie_release_mac_access(data);
939 
940 	return 0;
941 }
942 
943 static inline bool btintel_pcie_in_lockdown(struct btintel_pcie_data *data)
944 {
945 	return (data->boot_stage_cache &
946 		BTINTEL_PCIE_CSR_BOOT_STAGE_ROM_LOCKDOWN) ||
947 		(data->boot_stage_cache &
948 		 BTINTEL_PCIE_CSR_BOOT_STAGE_IML_LOCKDOWN);
949 }
950 
951 static inline bool btintel_pcie_in_error(struct btintel_pcie_data *data)
952 {
953 	if (data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_WARNING)
954 		bt_dev_warn(data->hdev, "Controller device warning (boot_stage: 0x%8.8x)",
955 			    data->boot_stage_cache);
956 
957 	return	data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_ABORT_HANDLER;
958 }
959 
960 static void btintel_pcie_msix_gp1_handler(struct btintel_pcie_data *data)
961 {
962 	bt_dev_err(data->hdev, "Received gp1 mailbox interrupt");
963 	btintel_pcie_dump_debug_registers(data->hdev);
964 }
965 
966 /* This function handles the MSI-X interrupt for gp0 cause (bit 0 in
967  * BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES) which is sent for boot stage and image response.
968  */
969 static void btintel_pcie_msix_gp0_handler(struct btintel_pcie_data *data)
970 {
971 	bool submit_rx, signal_waitq;
972 	u32 reg, old_ctxt;
973 
974 	/* This interrupt is for three different causes and it is not easy to
975 	 * know what causes the interrupt. So, it compares each register value
976 	 * with cached value and update it before it wake up the queue.
977 	 */
978 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
979 	if (reg != data->boot_stage_cache)
980 		data->boot_stage_cache = reg;
981 
982 	bt_dev_dbg(data->hdev, "Alive context: %s old_boot_stage: 0x%8.8x new_boot_stage: 0x%8.8x",
983 		   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt),
984 		   data->boot_stage_cache, reg);
985 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IMG_RESPONSE_REG);
986 	if (reg != data->img_resp_cache)
987 		data->img_resp_cache = reg;
988 
989 	if (btintel_pcie_in_error(data)) {
990 		bt_dev_err(data->hdev, "Controller in error state (boot_stage: 0x%8.8x)",
991 			   data->boot_stage_cache);
992 		btintel_pcie_dump_debug_registers(data->hdev);
993 		return;
994 	}
995 
996 	if (btintel_pcie_in_lockdown(data)) {
997 		bt_dev_err(data->hdev, "Controller in lockdown state");
998 		btintel_pcie_dump_debug_registers(data->hdev);
999 		return;
1000 	}
1001 
1002 	data->gp0_received = true;
1003 
1004 	old_ctxt = data->alive_intr_ctxt;
1005 	submit_rx = false;
1006 	signal_waitq = false;
1007 
1008 	switch (data->alive_intr_ctxt) {
1009 	case BTINTEL_PCIE_ROM:
1010 		data->alive_intr_ctxt = BTINTEL_PCIE_FW_DL;
1011 		signal_waitq = true;
1012 		break;
1013 	case BTINTEL_PCIE_FW_DL:
1014 		/* Error case is already handled. Ideally control shall not
1015 		 * reach here
1016 		 */
1017 		break;
1018 	case BTINTEL_PCIE_INTEL_HCI_RESET1:
1019 		if (btintel_pcie_in_op(data)) {
1020 			submit_rx = true;
1021 			signal_waitq = true;
1022 			break;
1023 		}
1024 
1025 		if (btintel_pcie_in_iml(data)) {
1026 			submit_rx = true;
1027 			signal_waitq = true;
1028 			data->alive_intr_ctxt = BTINTEL_PCIE_FW_DL;
1029 			break;
1030 		}
1031 		break;
1032 	case BTINTEL_PCIE_INTEL_HCI_RESET2:
1033 		if (btintel_test_and_clear_flag(data->hdev, INTEL_WAIT_FOR_D0)) {
1034 			btintel_wake_up_flag(data->hdev, INTEL_WAIT_FOR_D0);
1035 			data->alive_intr_ctxt = BTINTEL_PCIE_D0;
1036 		}
1037 		break;
1038 	case BTINTEL_PCIE_D0:
1039 		if (btintel_pcie_in_d3(data)) {
1040 			data->alive_intr_ctxt = BTINTEL_PCIE_D3;
1041 			signal_waitq = true;
1042 			break;
1043 		}
1044 		break;
1045 	case BTINTEL_PCIE_D3:
1046 		if (btintel_pcie_in_d0(data)) {
1047 			data->alive_intr_ctxt = BTINTEL_PCIE_D0;
1048 			submit_rx = true;
1049 			signal_waitq = true;
1050 			break;
1051 		}
1052 		break;
1053 	case BTINTEL_PCIE_HCI_RESET:
1054 		data->alive_intr_ctxt = BTINTEL_PCIE_D0;
1055 		submit_rx = true;
1056 		signal_waitq = true;
1057 		break;
1058 	default:
1059 		bt_dev_err(data->hdev, "Unknown state: 0x%2.2x",
1060 			   data->alive_intr_ctxt);
1061 		break;
1062 	}
1063 
1064 	if (submit_rx) {
1065 		btintel_pcie_reset_ia(data);
1066 		btintel_pcie_start_rx(data);
1067 	}
1068 
1069 	if (signal_waitq) {
1070 		bt_dev_dbg(data->hdev, "wake up gp0 wait_q");
1071 		wake_up(&data->gp0_wait_q);
1072 	}
1073 
1074 	if (old_ctxt != data->alive_intr_ctxt)
1075 		bt_dev_dbg(data->hdev, "alive context changed: %s  ->  %s",
1076 			   btintel_pcie_alivectxt_state2str(old_ctxt),
1077 			   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
1078 }
1079 
1080 /* This function handles the MSX-X interrupt for rx queue 0 which is for TX
1081  */
1082 static void btintel_pcie_msix_tx_handle(struct btintel_pcie_data *data)
1083 {
1084 	u16 cr_tia, cr_hia;
1085 	struct txq *txq;
1086 	struct urbd0 *urbd0;
1087 
1088 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM];
1089 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
1090 
1091 	if (cr_tia == cr_hia)
1092 		return;
1093 
1094 	txq = &data->txq;
1095 
1096 	while (cr_tia != cr_hia) {
1097 		data->tx_wait_done = true;
1098 		wake_up(&data->tx_wait_q);
1099 
1100 		urbd0 = &txq->urbd0s[cr_tia];
1101 
1102 		if (urbd0->tfd_index > txq->count)
1103 			return;
1104 
1105 		cr_tia = (cr_tia + 1) % txq->count;
1106 		data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM] = cr_tia;
1107 		ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_TXQ_NUM);
1108 	}
1109 }
1110 
1111 static int btintel_pcie_recv_event(struct hci_dev *hdev, struct sk_buff *skb)
1112 {
1113 	struct hci_event_hdr *hdr = (void *)skb->data;
1114 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
1115 
1116 	if (skb->len > HCI_EVENT_HDR_SIZE && hdr->evt == 0xff &&
1117 	    hdr->plen > 0) {
1118 		const void *ptr = skb->data + HCI_EVENT_HDR_SIZE + 1;
1119 		unsigned int len = skb->len - HCI_EVENT_HDR_SIZE - 1;
1120 
1121 		if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
1122 			switch (skb->data[2]) {
1123 			case 0x02:
1124 				/* When switching to the operational firmware
1125 				 * the device sends a vendor specific event
1126 				 * indicating that the bootup completed.
1127 				 */
1128 				btintel_bootup(hdev, ptr, len);
1129 
1130 				/* If bootup event is from operational image,
1131 				 * driver needs to write sleep control register to
1132 				 * move into D0 state
1133 				 */
1134 				if (btintel_pcie_in_op(data)) {
1135 					btintel_pcie_wr_sleep_cntrl(data, BTINTEL_PCIE_STATE_D0);
1136 					data->alive_intr_ctxt = BTINTEL_PCIE_INTEL_HCI_RESET2;
1137 					kfree_skb(skb);
1138 					return 0;
1139 				}
1140 
1141 				if (btintel_pcie_in_iml(data)) {
1142 					/* In case of IML, there is no concept
1143 					 * of D0 transition. Just mimic as if
1144 					 * IML moved to D0 by clearing INTEL_WAIT_FOR_D0
1145 					 * bit and waking up the task waiting on
1146 					 * INTEL_WAIT_FOR_D0. This is required
1147 					 * as intel_boot() is common function for
1148 					 * both IML and OP image loading.
1149 					 */
1150 					if (btintel_test_and_clear_flag(data->hdev,
1151 									INTEL_WAIT_FOR_D0))
1152 						btintel_wake_up_flag(data->hdev,
1153 								     INTEL_WAIT_FOR_D0);
1154 				}
1155 				kfree_skb(skb);
1156 				return 0;
1157 			case 0x06:
1158 				/* When the firmware loading completes the
1159 				 * device sends out a vendor specific event
1160 				 * indicating the result of the firmware
1161 				 * loading.
1162 				 */
1163 				btintel_secure_send_result(hdev, ptr, len);
1164 				kfree_skb(skb);
1165 				return 0;
1166 			}
1167 		}
1168 
1169 		/* This is a debug event that comes from IML and OP image when it
1170 		 * starts execution. There is no need pass this event to stack.
1171 		 */
1172 		if (skb->data[2] == 0x97) {
1173 			hci_recv_diag(hdev, skb);
1174 			return 0;
1175 		}
1176 	}
1177 
1178 	return hci_recv_frame(hdev, skb);
1179 }
1180 /* Process the received rx data
1181  * It check the frame header to identify the data type and create skb
1182  * and calling HCI API
1183  */
1184 static int btintel_pcie_recv_frame(struct btintel_pcie_data *data,
1185 				       struct sk_buff *skb)
1186 {
1187 	int ret;
1188 	u8 pkt_type;
1189 	u16 plen;
1190 	u32 pcie_pkt_type;
1191 	void *pdata;
1192 	struct hci_dev *hdev = data->hdev;
1193 
1194 	spin_lock(&data->hci_rx_lock);
1195 
1196 	/* The first 4 bytes indicates the Intel PCIe specific packet type */
1197 	pdata = skb_pull_data(skb, BTINTEL_PCIE_HCI_TYPE_LEN);
1198 	if (!pdata) {
1199 		bt_dev_err(hdev, "Corrupted packet received");
1200 		ret = -EILSEQ;
1201 		goto exit_error;
1202 	}
1203 
1204 	pcie_pkt_type = get_unaligned_le32(pdata);
1205 
1206 	switch (pcie_pkt_type) {
1207 	case BTINTEL_PCIE_HCI_ACL_PKT:
1208 		if (skb->len >= HCI_ACL_HDR_SIZE) {
1209 			plen = HCI_ACL_HDR_SIZE + __le16_to_cpu(hci_acl_hdr(skb)->dlen);
1210 			pkt_type = HCI_ACLDATA_PKT;
1211 		} else {
1212 			bt_dev_err(hdev, "ACL packet is too short");
1213 			ret = -EILSEQ;
1214 			goto exit_error;
1215 		}
1216 		break;
1217 
1218 	case BTINTEL_PCIE_HCI_SCO_PKT:
1219 		if (skb->len >= HCI_SCO_HDR_SIZE) {
1220 			plen = HCI_SCO_HDR_SIZE + hci_sco_hdr(skb)->dlen;
1221 			pkt_type = HCI_SCODATA_PKT;
1222 		} else {
1223 			bt_dev_err(hdev, "SCO packet is too short");
1224 			ret = -EILSEQ;
1225 			goto exit_error;
1226 		}
1227 		break;
1228 
1229 	case BTINTEL_PCIE_HCI_EVT_PKT:
1230 		if (skb->len >= HCI_EVENT_HDR_SIZE) {
1231 			plen = HCI_EVENT_HDR_SIZE + hci_event_hdr(skb)->plen;
1232 			pkt_type = HCI_EVENT_PKT;
1233 		} else {
1234 			bt_dev_err(hdev, "Event packet is too short");
1235 			ret = -EILSEQ;
1236 			goto exit_error;
1237 		}
1238 		break;
1239 
1240 	case BTINTEL_PCIE_HCI_ISO_PKT:
1241 		if (skb->len >= HCI_ISO_HDR_SIZE) {
1242 			plen = HCI_ISO_HDR_SIZE + __le16_to_cpu(hci_iso_hdr(skb)->dlen);
1243 			pkt_type = HCI_ISODATA_PKT;
1244 		} else {
1245 			bt_dev_err(hdev, "ISO packet is too short");
1246 			ret = -EILSEQ;
1247 			goto exit_error;
1248 		}
1249 		break;
1250 
1251 	default:
1252 		bt_dev_err(hdev, "Invalid packet type received: 0x%4.4x",
1253 			   pcie_pkt_type);
1254 		ret = -EINVAL;
1255 		goto exit_error;
1256 	}
1257 
1258 	if (skb->len < plen) {
1259 		bt_dev_err(hdev, "Received corrupted packet. type: 0x%2.2x",
1260 			   pkt_type);
1261 		ret = -EILSEQ;
1262 		goto exit_error;
1263 	}
1264 
1265 	bt_dev_dbg(hdev, "pkt_type: 0x%2.2x len: %u", pkt_type, plen);
1266 
1267 	hci_skb_pkt_type(skb) = pkt_type;
1268 	hdev->stat.byte_rx += plen;
1269 	skb_trim(skb, plen);
1270 
1271 	if (pcie_pkt_type == BTINTEL_PCIE_HCI_EVT_PKT)
1272 		ret = btintel_pcie_recv_event(hdev, skb);
1273 	else
1274 		ret = hci_recv_frame(hdev, skb);
1275 	skb = NULL; /* skb is freed in the callee  */
1276 
1277 exit_error:
1278 	kfree_skb(skb);
1279 
1280 	if (ret)
1281 		hdev->stat.err_rx++;
1282 
1283 	spin_unlock(&data->hci_rx_lock);
1284 
1285 	return ret;
1286 }
1287 
1288 static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data)
1289 {
1290 	int len, err, offset, pending;
1291 	struct sk_buff *skb;
1292 	u8 *buf, prefix[64];
1293 	u32 addr, val;
1294 	u16 pkt_len;
1295 
1296 	struct tlv {
1297 		u8	type;
1298 		__le16	len;
1299 		u8	val[];
1300 	} __packed;
1301 
1302 	struct tlv *tlv;
1303 
1304 	switch (data->dmp_hdr.cnvi_top & 0xfff) {
1305 	case BTINTEL_CNVI_BLAZARI:
1306 	case BTINTEL_CNVI_BLAZARIW:
1307 		/* only from step B0 onwards */
1308 		if (INTEL_CNVX_TOP_STEP(data->dmp_hdr.cnvi_top) != 0x01)
1309 			return;
1310 		len = BTINTEL_PCIE_BLZR_HWEXP_SIZE; /* exception data length */
1311 		addr = BTINTEL_PCIE_BLZR_HWEXP_DMP_ADDR;
1312 		break;
1313 	case BTINTEL_CNVI_SCP:
1314 		len = BTINTEL_PCIE_SCP_HWEXP_SIZE;
1315 		addr = BTINTEL_PCIE_SCP_HWEXP_DMP_ADDR;
1316 		break;
1317 	case BTINTEL_CNVI_SCP2:
1318 	case BTINTEL_CNVI_SCP2F:
1319 		len = BTINTEL_PCIE_SCP2_HWEXP_SIZE;
1320 		addr = BTINTEL_PCIE_SCP2_HWEXP_DMP_ADDR;
1321 		break;
1322 	default:
1323 		bt_dev_err(data->hdev, "Unsupported cnvi 0x%8.8x", data->dmp_hdr.cnvi_top);
1324 		return;
1325 	}
1326 
1327 	buf = kzalloc(len, GFP_KERNEL);
1328 	if (!buf)
1329 		goto exit_on_error;
1330 
1331 	btintel_pcie_mac_init(data);
1332 
1333 	err = btintel_pcie_read_device_mem(data, buf, addr, len);
1334 	if (err)
1335 		goto exit_on_error;
1336 
1337 	val = get_unaligned_le32(buf);
1338 	if (val != BTINTEL_PCIE_MAGIC_NUM) {
1339 		bt_dev_err(data->hdev, "Invalid exception dump signature: 0x%8.8x",
1340 			   val);
1341 		goto exit_on_error;
1342 	}
1343 
1344 	snprintf(prefix, sizeof(prefix), "Bluetooth: %s: ", bt_dev_name(data->hdev));
1345 
1346 	offset = 4;
1347 	do {
1348 		pending = len - offset;
1349 		if (pending < sizeof(*tlv))
1350 			break;
1351 		tlv = (struct tlv *)(buf + offset);
1352 
1353 		/* If type == 0, then there are no more TLVs to be parsed */
1354 		if (!tlv->type) {
1355 			bt_dev_dbg(data->hdev, "Invalid TLV type 0");
1356 			break;
1357 		}
1358 		pkt_len = le16_to_cpu(tlv->len);
1359 		offset += sizeof(*tlv);
1360 		pending = len - offset;
1361 		if (pkt_len > pending)
1362 			break;
1363 
1364 		offset += pkt_len;
1365 
1366 		 /* Only TLVs of type == 1 are HCI events, no need to process other
1367 		  * TLVs
1368 		  */
1369 		if (tlv->type != 1)
1370 			continue;
1371 
1372 		bt_dev_dbg(data->hdev, "TLV packet length: %u", pkt_len);
1373 		if (pkt_len > HCI_MAX_EVENT_SIZE)
1374 			break;
1375 		skb = bt_skb_alloc(pkt_len, GFP_KERNEL);
1376 		if (!skb)
1377 			goto exit_on_error;
1378 		hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
1379 		skb_put_data(skb, tlv->val, pkt_len);
1380 
1381 		/* copy Intel specific pcie packet type */
1382 		val = BTINTEL_PCIE_HCI_EVT_PKT;
1383 		memcpy(skb_push(skb, BTINTEL_PCIE_HCI_TYPE_LEN), &val,
1384 		       BTINTEL_PCIE_HCI_TYPE_LEN);
1385 
1386 		print_hex_dump(KERN_DEBUG, prefix, DUMP_PREFIX_OFFSET, 16, 1,
1387 			       tlv->val, pkt_len, false);
1388 
1389 		btintel_pcie_recv_frame(data, skb);
1390 	} while (offset < len);
1391 
1392 exit_on_error:
1393 	kfree(buf);
1394 }
1395 
1396 static int btintel_pcie_dump_fwtrigger_event(struct btintel_pcie_data *data)
1397 {
1398 	struct btintel_pcie_fwtrigger_evt *evt;
1399 	struct sk_buff *skb;
1400 	unsigned int len;
1401 	int err;
1402 	u8 *buf;
1403 
1404 	if (!data->debug_evt_size || !data->debug_evt_addr)
1405 		return -EINVAL;
1406 
1407 	len = data->debug_evt_size;
1408 
1409 	len = ALIGN_DOWN(len, 4);
1410 
1411 	if (len < sizeof(*evt) || len > HCI_MAX_EVENT_SIZE) {
1412 		bt_dev_err(data->hdev, "Invalid FW trigger data size (%u bytes)", len);
1413 		return -EINVAL;
1414 	}
1415 
1416 	buf = kzalloc(len, GFP_KERNEL);
1417 	if (!buf)
1418 		return -ENOMEM;
1419 
1420 	btintel_pcie_mac_init(data);
1421 
1422 	err = btintel_pcie_read_device_mem(data, buf, data->debug_evt_addr,
1423 					   len);
1424 	if (err)
1425 		goto exit_on_error;
1426 
1427 	evt = (void *)buf;
1428 	data->dmp_hdr.event_type = evt->event_type;
1429 	data->dmp_hdr.event_id = le16_to_cpu(evt->event_id);
1430 
1431 	bt_dev_dbg(data->hdev, "event type: 0x%2.2x event id: 0x%4.4x len: %u",
1432 		   data->dmp_hdr.event_type, data->dmp_hdr.event_id, len);
1433 
1434 	skb = bt_skb_alloc(len, GFP_KERNEL);
1435 	if (!skb) {
1436 		err = -ENOMEM;
1437 		goto exit_on_error;
1438 	}
1439 	skb_put_data(skb, buf, len);
1440 
1441 	hci_recv_diag(data->hdev, skb);
1442 	err = 0;
1443 
1444 exit_on_error:
1445 	kfree(buf);
1446 	return err;
1447 }
1448 
1449 static void btintel_pcie_msix_fw_trigger_handler(struct btintel_pcie_data *data)
1450 {
1451 	bt_dev_dbg(data->hdev, "Received firmware smart trigger cause");
1452 
1453 	if (test_and_set_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags))
1454 		return;
1455 
1456 	/* Trigger device core dump when there is FW assert */
1457 	if (!test_and_set_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags))
1458 		data->dmp_hdr.trigger_reason = BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT;
1459 
1460 	queue_work(data->coredump_workqueue, &data->coredump_work);
1461 }
1462 
1463 static void btintel_pcie_msix_hw_exp_handler(struct btintel_pcie_data *data)
1464 {
1465 	bt_dev_err(data->hdev, "Received hw exception interrupt");
1466 
1467 	if (test_and_set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags))
1468 		return;
1469 
1470 	if (test_and_set_bit(BTINTEL_PCIE_HWEXP_INPROGRESS, &data->flags))
1471 		return;
1472 
1473 	/* Trigger device core dump when there is HW  exception */
1474 	if (!test_and_set_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags))
1475 		data->dmp_hdr.trigger_reason = BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT;
1476 
1477 	queue_work(data->coredump_workqueue, &data->coredump_work);
1478 }
1479 
1480 static void btintel_pcie_coredump_worker(struct work_struct *work)
1481 {
1482 	struct btintel_pcie_data *data = container_of(work,
1483 					struct btintel_pcie_data, coredump_work);
1484 	int err;
1485 
1486 	/* hdev is NULL until setup_hdev() succeeds, and is cleared on
1487 	 * teardown after disable_work_sync() drains us; bail in that case.
1488 	 */
1489 	if (!data->hdev)
1490 		return;
1491 
1492 	if (test_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags)) {
1493 		err = btintel_pcie_dump_fwtrigger_event(data);
1494 		if (err)
1495 			bt_dev_warn(data->hdev, "failed to log fwtrigger event");
1496 		clear_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags);
1497 	}
1498 
1499 	if (test_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags)) {
1500 		btintel_pcie_dump_traces(data->hdev);
1501 		clear_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags);
1502 	}
1503 
1504 	if (test_bit(BTINTEL_PCIE_HWEXP_INPROGRESS, &data->flags)) {
1505 		/* Unlike usb products, controller will not send hardware
1506 		 * exception event on exception. Instead controller writes the
1507 		 * hardware event to device memory along with optional debug
1508 		 * events, raises MSIX and halts. Driver shall read the
1509 		 * exception event from device memory and passes it stack for
1510 		 * further processing.
1511 		 */
1512 		btintel_pcie_read_hwexp(data);
1513 		clear_bit(BTINTEL_PCIE_HWEXP_INPROGRESS, &data->flags);
1514 	}
1515 }
1516 
1517 static void btintel_pcie_rx_work(struct work_struct *work)
1518 {
1519 	struct btintel_pcie_data *data = container_of(work,
1520 					struct btintel_pcie_data, rx_work);
1521 	struct sk_buff *skb;
1522 
1523 	/* Process the sk_buf in queue and send to the HCI layer */
1524 	while ((skb = skb_dequeue(&data->rx_skb_q))) {
1525 		btintel_pcie_recv_frame(data, skb);
1526 	}
1527 }
1528 
1529 /* create sk_buff with data and save it to queue and start RX work */
1530 static int btintel_pcie_submit_rx_work(struct btintel_pcie_data *data, u8 status,
1531 				       void *buf)
1532 {
1533 	int ret, len;
1534 	struct rfh_hdr *rfh_hdr;
1535 	struct sk_buff *skb;
1536 
1537 	rfh_hdr = buf;
1538 
1539 	len = rfh_hdr->packet_len;
1540 	if (len <= 0) {
1541 		ret = -EINVAL;
1542 		goto resubmit;
1543 	}
1544 
1545 	/* Remove RFH header */
1546 	buf += sizeof(*rfh_hdr);
1547 
1548 	skb = alloc_skb(len, GFP_ATOMIC);
1549 	if (!skb)
1550 		goto resubmit;
1551 
1552 	skb_put_data(skb, buf, len);
1553 	skb_queue_tail(&data->rx_skb_q, skb);
1554 	queue_work(data->workqueue, &data->rx_work);
1555 
1556 resubmit:
1557 	ret = btintel_pcie_submit_rx(data);
1558 
1559 	return ret;
1560 }
1561 
1562 /* Handles the MSI-X interrupt for rx queue 1 which is for RX */
1563 static void btintel_pcie_msix_rx_handle(struct btintel_pcie_data *data)
1564 {
1565 	u16 cr_hia, cr_tia;
1566 	struct rxq *rxq;
1567 	struct urbd1 *urbd1;
1568 	struct data_buf *buf;
1569 	int ret;
1570 	struct hci_dev *hdev = data->hdev;
1571 
1572 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM];
1573 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
1574 
1575 	bt_dev_dbg(hdev, "RXQ: cr_hia: %u  cr_tia: %u", cr_hia, cr_tia);
1576 
1577 	/* Check CR_TIA and CR_HIA for change */
1578 	if (cr_tia == cr_hia)
1579 		return;
1580 
1581 	rxq = &data->rxq;
1582 
1583 	/* The firmware sends multiple CD in a single MSI-X and it needs to
1584 	 * process all received CDs in this interrupt.
1585 	 */
1586 	while (cr_tia != cr_hia) {
1587 		urbd1 = &rxq->urbd1s[cr_tia];
1588 		ipc_print_urbd1(data->hdev, urbd1, cr_tia);
1589 
1590 		buf = &rxq->bufs[urbd1->frbd_tag];
1591 		if (!buf) {
1592 			bt_dev_err(hdev, "RXQ: failed to get the DMA buffer for %d",
1593 				   urbd1->frbd_tag);
1594 			return;
1595 		}
1596 
1597 		ret = btintel_pcie_submit_rx_work(data, urbd1->status,
1598 						  buf->data);
1599 		if (ret) {
1600 			bt_dev_err(hdev, "RXQ: failed to submit rx request");
1601 			return;
1602 		}
1603 
1604 		cr_tia = (cr_tia + 1) % rxq->count;
1605 		data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM] = cr_tia;
1606 		ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_RXQ_NUM);
1607 	}
1608 }
1609 
1610 static inline bool btintel_pcie_is_rxq_empty(struct btintel_pcie_data *data)
1611 {
1612 	return data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM] == data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
1613 }
1614 
1615 static inline bool btintel_pcie_is_txackq_empty(struct btintel_pcie_data *data)
1616 {
1617 	return data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM] == data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
1618 }
1619 
1620 static irqreturn_t btintel_pcie_irq_msix_handler(int irq, void *dev_id)
1621 {
1622 	struct msix_entry *entry = dev_id;
1623 	struct btintel_pcie_data *data = btintel_pcie_get_data(entry);
1624 	u32 intr_fh, intr_hw;
1625 
1626 	spin_lock(&data->irq_lock);
1627 	intr_fh = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_CAUSES);
1628 	intr_hw = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES);
1629 
1630 	/* Clear causes registers to avoid being handling the same cause */
1631 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_CAUSES, intr_fh);
1632 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES, intr_hw);
1633 	spin_unlock(&data->irq_lock);
1634 
1635 	if (unlikely(!(intr_fh | intr_hw))) {
1636 		/* Ignore interrupt, inta == 0 */
1637 		return IRQ_NONE;
1638 	}
1639 
1640 	/* This interrupt is raised when there is an hardware exception */
1641 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_HWEXP)
1642 		btintel_pcie_msix_hw_exp_handler(data);
1643 
1644 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP1)
1645 		btintel_pcie_msix_gp1_handler(data);
1646 
1647 
1648 	/* For TX */
1649 	if (intr_fh & BTINTEL_PCIE_MSIX_FH_INT_CAUSES_0) {
1650 		btintel_pcie_msix_tx_handle(data);
1651 		if (!btintel_pcie_is_rxq_empty(data))
1652 			btintel_pcie_msix_rx_handle(data);
1653 	}
1654 
1655 	/* For RX */
1656 	if (intr_fh & BTINTEL_PCIE_MSIX_FH_INT_CAUSES_1) {
1657 		btintel_pcie_msix_rx_handle(data);
1658 		if (!btintel_pcie_is_txackq_empty(data))
1659 			btintel_pcie_msix_tx_handle(data);
1660 	}
1661 
1662 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_FWTRIG)
1663 		btintel_pcie_msix_fw_trigger_handler(data);
1664 
1665 	/* This interrupt is triggered by the firmware after updating
1666 	 * boot_stage register and image_response register
1667 	 */
1668 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0)
1669 		btintel_pcie_msix_gp0_handler(data);
1670 
1671 	/*
1672 	 * Before sending the interrupt the HW disables it to prevent a nested
1673 	 * interrupt. This is done by writing 1 to the corresponding bit in
1674 	 * the mask register. After handling the interrupt, it should be
1675 	 * re-enabled by clearing this bit. This register is defined as write 1
1676 	 * clear (W1C) register, meaning that it's cleared by writing 1
1677 	 * to the bit.
1678 	 */
1679 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_AUTOMASK_ST,
1680 			      BIT(entry->entry));
1681 
1682 	return IRQ_HANDLED;
1683 }
1684 
1685 /* This function requests the irq for MSI-X and registers the handlers per irq.
1686  * Currently, it requests only 1 irq for all interrupt causes.
1687  */
1688 static int btintel_pcie_setup_irq(struct btintel_pcie_data *data)
1689 {
1690 	int err;
1691 	int num_irqs, i;
1692 
1693 	for (i = 0; i < BTINTEL_PCIE_MSIX_VEC_MAX; i++)
1694 		data->msix_entries[i].entry = i;
1695 
1696 	num_irqs = pci_alloc_irq_vectors(data->pdev, BTINTEL_PCIE_MSIX_VEC_MIN,
1697 					 BTINTEL_PCIE_MSIX_VEC_MAX, PCI_IRQ_MSIX);
1698 	if (num_irqs < 0)
1699 		return num_irqs;
1700 
1701 	data->alloc_vecs = num_irqs;
1702 	data->msix_enabled = 1;
1703 	data->def_irq = 0;
1704 
1705 	/* setup irq handler */
1706 	for (i = 0; i < data->alloc_vecs; i++) {
1707 		struct msix_entry *msix_entry;
1708 
1709 		msix_entry = &data->msix_entries[i];
1710 		msix_entry->vector = pci_irq_vector(data->pdev, i);
1711 
1712 		err = devm_request_threaded_irq(&data->pdev->dev,
1713 						msix_entry->vector,
1714 						NULL,
1715 						btintel_pcie_irq_msix_handler,
1716 						IRQF_ONESHOT | IRQF_SHARED,
1717 						KBUILD_MODNAME,
1718 						msix_entry);
1719 		if (err) {
1720 			pci_free_irq_vectors(data->pdev);
1721 			data->alloc_vecs = 0;
1722 			return err;
1723 		}
1724 	}
1725 	return 0;
1726 }
1727 
1728 struct btintel_pcie_causes_list {
1729 	u32 cause;
1730 	u32 mask_reg;
1731 	u8 cause_num;
1732 };
1733 
1734 static struct btintel_pcie_causes_list causes_list[] = {
1735 	{ BTINTEL_PCIE_MSIX_FH_INT_CAUSES_0,	BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK,	0x00 },
1736 	{ BTINTEL_PCIE_MSIX_FH_INT_CAUSES_1,	BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK,	0x01 },
1737 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0,	BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x20 },
1738 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_HWEXP, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x23 },
1739 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_FWTRIG, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x25 },
1740 };
1741 
1742 /* This function configures the interrupt masks for both HW_INT_CAUSES and
1743  * FH_INT_CAUSES which are meaningful to us.
1744  *
1745  * After resetting BT function via PCIE FLR or FUNC_CTRL reset, the driver
1746  * need to call this function again to configure since the masks
1747  * are reset to 0xFFFFFFFF after reset.
1748  */
1749 static void btintel_pcie_config_msix(struct btintel_pcie_data *data)
1750 {
1751 	int i;
1752 	int val = data->def_irq | BTINTEL_PCIE_MSIX_NON_AUTO_CLEAR_CAUSE;
1753 
1754 	/* Set Non Auto Clear Cause */
1755 	for (i = 0; i < ARRAY_SIZE(causes_list); i++) {
1756 		btintel_pcie_wr_reg8(data,
1757 				     BTINTEL_PCIE_CSR_MSIX_IVAR(causes_list[i].cause_num),
1758 				     val);
1759 		btintel_pcie_clr_reg_bits(data,
1760 					  causes_list[i].mask_reg,
1761 					  causes_list[i].cause);
1762 	}
1763 
1764 	/* Save the initial interrupt mask */
1765 	data->fh_init_mask = ~btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK);
1766 	data->hw_init_mask = ~btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK);
1767 }
1768 
1769 static int btintel_pcie_config_pcie(struct pci_dev *pdev,
1770 				    struct btintel_pcie_data *data)
1771 {
1772 	int err;
1773 
1774 	err = pcim_enable_device(pdev);
1775 	if (err)
1776 		return err;
1777 
1778 	pci_set_master(pdev);
1779 
1780 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
1781 	if (err) {
1782 		err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
1783 		if (err)
1784 			return err;
1785 	}
1786 
1787 	data->base_addr = pcim_iomap_region(pdev, 0, KBUILD_MODNAME);
1788 	if (IS_ERR(data->base_addr))
1789 		return PTR_ERR(data->base_addr);
1790 
1791 	err = btintel_pcie_setup_irq(data);
1792 	if (err)
1793 		return err;
1794 
1795 	/* Configure MSI-X with causes list */
1796 	btintel_pcie_config_msix(data);
1797 
1798 	return 0;
1799 }
1800 
1801 static void btintel_pcie_init_ci(struct btintel_pcie_data *data,
1802 				 struct ctx_info *ci)
1803 {
1804 	ci->version = 0x1;
1805 	ci->size = sizeof(*ci);
1806 	ci->config = 0x0000;
1807 	ci->addr_cr_hia = data->ia.cr_hia_p_addr;
1808 	ci->addr_tr_tia = data->ia.tr_tia_p_addr;
1809 	ci->addr_cr_tia = data->ia.cr_tia_p_addr;
1810 	ci->addr_tr_hia = data->ia.tr_hia_p_addr;
1811 	ci->num_cr_ia = BTINTEL_PCIE_NUM_QUEUES;
1812 	ci->num_tr_ia = BTINTEL_PCIE_NUM_QUEUES;
1813 	ci->addr_urbdq0 = data->txq.urbd0s_p_addr;
1814 	ci->addr_tfdq = data->txq.tfds_p_addr;
1815 	ci->num_tfdq = data->txq.count;
1816 	ci->num_urbdq0 = data->txq.count;
1817 	ci->tfdq_db_vec = BTINTEL_PCIE_TXQ_NUM;
1818 	ci->urbdq0_db_vec = BTINTEL_PCIE_TXQ_NUM;
1819 	ci->rbd_size = BTINTEL_PCIE_RBD_SIZE_4K;
1820 	ci->addr_frbdq = data->rxq.frbds_p_addr;
1821 	ci->num_frbdq = data->rxq.count;
1822 	ci->frbdq_db_vec = BTINTEL_PCIE_RXQ_NUM;
1823 	ci->addr_urbdq1 = data->rxq.urbd1s_p_addr;
1824 	ci->num_urbdq1 = data->rxq.count;
1825 	ci->urbdq_db_vec = BTINTEL_PCIE_RXQ_NUM;
1826 
1827 	ci->dbg_output_mode = 0x01;
1828 	ci->dbgc_addr = data->dbgc.frag_p_addr;
1829 	ci->dbgc_size = data->dbgc.frag_size;
1830 	ci->dbg_preset = 0x00;
1831 }
1832 
1833 static void btintel_pcie_free_txq_bufs(struct btintel_pcie_data *data,
1834 				       struct txq *txq)
1835 {
1836 	/* Free data buffers first */
1837 	dma_free_coherent(&data->pdev->dev, txq->count * BTINTEL_PCIE_BUFFER_SIZE,
1838 			  txq->buf_v_addr, txq->buf_p_addr);
1839 	kfree(txq->bufs);
1840 }
1841 
1842 static int btintel_pcie_setup_txq_bufs(struct btintel_pcie_data *data,
1843 				       struct txq *txq)
1844 {
1845 	int i;
1846 	struct data_buf *buf;
1847 
1848 	/* Allocate the same number of buffers as the descriptor */
1849 	txq->bufs = kmalloc_objs(*buf, txq->count);
1850 	if (!txq->bufs)
1851 		return -ENOMEM;
1852 
1853 	/* Allocate full chunk of data buffer for DMA first and do indexing and
1854 	 * initialization next, so it can be freed easily
1855 	 */
1856 	txq->buf_v_addr = dma_alloc_coherent(&data->pdev->dev,
1857 					     txq->count * BTINTEL_PCIE_BUFFER_SIZE,
1858 					     &txq->buf_p_addr,
1859 					     GFP_KERNEL | __GFP_NOWARN);
1860 	if (!txq->buf_v_addr) {
1861 		kfree(txq->bufs);
1862 		return -ENOMEM;
1863 	}
1864 
1865 	/* Setup the allocated DMA buffer to bufs. Each data_buf should
1866 	 * have virtual address and physical address
1867 	 */
1868 	for (i = 0; i < txq->count; i++) {
1869 		buf = &txq->bufs[i];
1870 		buf->data_p_addr = txq->buf_p_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
1871 		buf->data = txq->buf_v_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
1872 	}
1873 
1874 	return 0;
1875 }
1876 
1877 static void btintel_pcie_free_rxq_bufs(struct btintel_pcie_data *data,
1878 				       struct rxq *rxq)
1879 {
1880 	/* Free data buffers first */
1881 	dma_free_coherent(&data->pdev->dev, rxq->count * BTINTEL_PCIE_BUFFER_SIZE,
1882 			  rxq->buf_v_addr, rxq->buf_p_addr);
1883 	kfree(rxq->bufs);
1884 }
1885 
1886 static int btintel_pcie_setup_rxq_bufs(struct btintel_pcie_data *data,
1887 				       struct rxq *rxq)
1888 {
1889 	int i;
1890 	struct data_buf *buf;
1891 
1892 	/* Allocate the same number of buffers as the descriptor */
1893 	rxq->bufs = kmalloc_objs(*buf, rxq->count);
1894 	if (!rxq->bufs)
1895 		return -ENOMEM;
1896 
1897 	/* Allocate full chunk of data buffer for DMA first and do indexing and
1898 	 * initialization next, so it can be freed easily
1899 	 */
1900 	rxq->buf_v_addr = dma_alloc_coherent(&data->pdev->dev,
1901 					     rxq->count * BTINTEL_PCIE_BUFFER_SIZE,
1902 					     &rxq->buf_p_addr,
1903 					     GFP_KERNEL | __GFP_NOWARN);
1904 	if (!rxq->buf_v_addr) {
1905 		kfree(rxq->bufs);
1906 		return -ENOMEM;
1907 	}
1908 
1909 	/* Setup the allocated DMA buffer to bufs. Each data_buf should
1910 	 * have virtual address and physical address
1911 	 */
1912 	for (i = 0; i < rxq->count; i++) {
1913 		buf = &rxq->bufs[i];
1914 		buf->data_p_addr = rxq->buf_p_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
1915 		buf->data = rxq->buf_v_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
1916 	}
1917 
1918 	return 0;
1919 }
1920 
1921 static void btintel_pcie_free(struct btintel_pcie_data *data)
1922 {
1923 	btintel_pcie_free_rxq_bufs(data, &data->rxq);
1924 	btintel_pcie_free_txq_bufs(data, &data->txq);
1925 
1926 	dma_pool_free(data->dma_pool, data->dma_v_addr, data->dma_p_addr);
1927 	dma_pool_destroy(data->dma_pool);
1928 }
1929 
1930 /* Allocate tx and rx queues, any related data structures and buffers.
1931  */
1932 static int btintel_pcie_alloc(struct btintel_pcie_data *data)
1933 {
1934 	int err = 0;
1935 	size_t total;
1936 	dma_addr_t p_addr;
1937 	void *v_addr;
1938 	size_t tfd_size, frbd_size, ctx_size, ci_size, urbd0_size, urbd1_size;
1939 
1940 	/* Allocate the chunk of DMA memory for descriptors, index array, and
1941 	 * context information, instead of allocating individually.
1942 	 * The DMA memory for data buffer is allocated while setting up the
1943 	 * each queue.
1944 	 *
1945 	 * Total size is sum of the following and each of the individual sizes
1946 	 * are aligned to 128 bytes before adding up.
1947 	 *
1948 	 *  + size of TFD * Number of descriptors in queue
1949 	 *  + size of URBD0 * Number of descriptors in queue
1950 	 *  + size of FRBD * Number of descriptors in queue
1951 	 *  + size of URBD1 * Number of descriptors in queue
1952 	 *  + size of index * Number of queues(2) * type of index array(4)
1953 	 *  + size of context information
1954 	 */
1955 	tfd_size = ALIGN(sizeof(struct tfd) * BTINTEL_PCIE_TX_DESCS_COUNT,
1956 			 BTINTEL_PCIE_DMA_ALIGN_128B);
1957 	urbd0_size = ALIGN(sizeof(struct urbd0) * BTINTEL_PCIE_TX_DESCS_COUNT,
1958 			   BTINTEL_PCIE_DMA_ALIGN_128B);
1959 
1960 	frbd_size = ALIGN(sizeof(struct frbd) * BTINTEL_PCIE_RX_DESCS_COUNT,
1961 			  BTINTEL_PCIE_DMA_ALIGN_128B);
1962 	urbd1_size = ALIGN(sizeof(struct urbd1) * BTINTEL_PCIE_RX_DESCS_COUNT,
1963 			   BTINTEL_PCIE_DMA_ALIGN_128B);
1964 
1965 	ci_size = ALIGN(sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES,
1966 			BTINTEL_PCIE_DMA_ALIGN_128B);
1967 
1968 	ctx_size = ALIGN(sizeof(struct ctx_info), BTINTEL_PCIE_DMA_ALIGN_128B);
1969 
1970 	total = tfd_size + urbd0_size + frbd_size + urbd1_size + ctx_size + ci_size * 4;
1971 
1972 	data->dma_pool = dma_pool_create(KBUILD_MODNAME, &data->pdev->dev,
1973 					 total, BTINTEL_PCIE_DMA_ALIGN_128B, 0);
1974 	if (!data->dma_pool) {
1975 		err = -ENOMEM;
1976 		goto exit_error;
1977 	}
1978 
1979 	v_addr = dma_pool_zalloc(data->dma_pool, GFP_KERNEL | __GFP_NOWARN,
1980 				 &p_addr);
1981 	if (!v_addr) {
1982 		dma_pool_destroy(data->dma_pool);
1983 		err = -ENOMEM;
1984 		goto exit_error;
1985 	}
1986 
1987 	data->dma_p_addr = p_addr;
1988 	data->dma_v_addr = v_addr;
1989 
1990 	/* Setup descriptor count */
1991 	data->txq.count = BTINTEL_PCIE_TX_DESCS_COUNT;
1992 	data->rxq.count = BTINTEL_PCIE_RX_DESCS_COUNT;
1993 
1994 	/* Setup tfds */
1995 	data->txq.tfds_p_addr = p_addr;
1996 	data->txq.tfds = v_addr;
1997 
1998 	p_addr += tfd_size;
1999 	v_addr += tfd_size;
2000 
2001 	/* Setup urbd0 */
2002 	data->txq.urbd0s_p_addr = p_addr;
2003 	data->txq.urbd0s = v_addr;
2004 
2005 	p_addr += urbd0_size;
2006 	v_addr += urbd0_size;
2007 
2008 	/* Setup FRBD*/
2009 	data->rxq.frbds_p_addr = p_addr;
2010 	data->rxq.frbds = v_addr;
2011 
2012 	p_addr += frbd_size;
2013 	v_addr += frbd_size;
2014 
2015 	/* Setup urbd1 */
2016 	data->rxq.urbd1s_p_addr = p_addr;
2017 	data->rxq.urbd1s = v_addr;
2018 
2019 	p_addr += urbd1_size;
2020 	v_addr += urbd1_size;
2021 
2022 	/* Setup data buffers for txq */
2023 	err = btintel_pcie_setup_txq_bufs(data, &data->txq);
2024 	if (err)
2025 		goto exit_error_pool;
2026 
2027 	/* Setup data buffers for rxq */
2028 	err = btintel_pcie_setup_rxq_bufs(data, &data->rxq);
2029 	if (err)
2030 		goto exit_error_txq;
2031 
2032 	/* TR Head Index Array */
2033 	data->ia.tr_hia_p_addr = p_addr;
2034 	data->ia.tr_hia = v_addr;
2035 	p_addr += ci_size;
2036 	v_addr += ci_size;
2037 
2038 	/* TR Tail Index Array */
2039 	data->ia.tr_tia_p_addr = p_addr;
2040 	data->ia.tr_tia = v_addr;
2041 	p_addr += ci_size;
2042 	v_addr += ci_size;
2043 
2044 	/* CR Head index Array */
2045 	data->ia.cr_hia_p_addr = p_addr;
2046 	data->ia.cr_hia = v_addr;
2047 	p_addr += ci_size;
2048 	v_addr += ci_size;
2049 
2050 	/* CR Tail Index Array */
2051 	data->ia.cr_tia_p_addr = p_addr;
2052 	data->ia.cr_tia = v_addr;
2053 	p_addr += ci_size;
2054 	v_addr += ci_size;
2055 
2056 	/* Setup data buffers for dbgc */
2057 	err = btintel_pcie_setup_dbgc(data);
2058 	if (err)
2059 		goto exit_error_txq;
2060 
2061 	/* Setup Context Information */
2062 	data->ci = v_addr;
2063 	data->ci_p_addr = p_addr;
2064 
2065 	/* Initialize the CI */
2066 	btintel_pcie_init_ci(data, data->ci);
2067 
2068 	return 0;
2069 
2070 exit_error_txq:
2071 	btintel_pcie_free_txq_bufs(data, &data->txq);
2072 exit_error_pool:
2073 	dma_pool_free(data->dma_pool, data->dma_v_addr, data->dma_p_addr);
2074 	dma_pool_destroy(data->dma_pool);
2075 exit_error:
2076 	return err;
2077 }
2078 
2079 static int btintel_pcie_open(struct hci_dev *hdev)
2080 {
2081 	bt_dev_dbg(hdev, "");
2082 
2083 	return 0;
2084 }
2085 
2086 static int btintel_pcie_close(struct hci_dev *hdev)
2087 {
2088 	bt_dev_dbg(hdev, "");
2089 
2090 	return 0;
2091 }
2092 
2093 static int btintel_pcie_inject_cmd_complete(struct hci_dev *hdev, __u16 opcode)
2094 {
2095 	struct sk_buff *skb;
2096 	struct hci_event_hdr *hdr;
2097 	struct hci_ev_cmd_complete *evt;
2098 
2099 	skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL);
2100 	if (!skb)
2101 		return -ENOMEM;
2102 
2103 	hdr = (struct hci_event_hdr *)skb_put(skb, sizeof(*hdr));
2104 	hdr->evt = HCI_EV_CMD_COMPLETE;
2105 	hdr->plen = sizeof(*evt) + 1;
2106 
2107 	evt = (struct hci_ev_cmd_complete *)skb_put(skb, sizeof(*evt));
2108 	evt->ncmd = 0x01;
2109 	evt->opcode = cpu_to_le16(opcode);
2110 
2111 	*(u8 *)skb_put(skb, 1) = 0x00;
2112 
2113 	hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
2114 
2115 	return hci_recv_frame(hdev, skb);
2116 }
2117 
2118 static int btintel_pcie_send_frame(struct hci_dev *hdev,
2119 				       struct sk_buff *skb)
2120 {
2121 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2122 	struct hci_command_hdr *cmd;
2123 	__u16 opcode = ~0;
2124 	int ret;
2125 	u32 type;
2126 
2127 	if (test_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags))
2128 		return -ENODEV;
2129 
2130 	if (test_bit(BTINTEL_PCIE_RECOVERY_IN_PROGRESS, &data->flags))
2131 		return -ENODEV;
2132 
2133 	/* Due to the fw limitation, the type header of the packet should be
2134 	 * 4 bytes unlike 1 byte for UART. In UART, the firmware can read
2135 	 * the first byte to get the packet type and redirect the rest of data
2136 	 * packet to the right handler.
2137 	 *
2138 	 * But for PCIe, THF(Transfer Flow Handler) fetches the 4 bytes of data
2139 	 * from DMA memory and by the time it reads the first 4 bytes, it has
2140 	 * already consumed some part of packet. Thus the packet type indicator
2141 	 * for iBT PCIe is 4 bytes.
2142 	 *
2143 	 * Luckily, when HCI core creates the skb, it allocates 8 bytes of
2144 	 * head room for profile and driver use, and before sending the data
2145 	 * to the device, append the iBT PCIe packet type in the front.
2146 	 */
2147 	switch (hci_skb_pkt_type(skb)) {
2148 	case HCI_COMMAND_PKT:
2149 		type = BTINTEL_PCIE_HCI_CMD_PKT;
2150 		cmd = (void *)skb->data;
2151 		opcode = le16_to_cpu(cmd->opcode);
2152 		if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
2153 			struct hci_command_hdr *cmd = (void *)skb->data;
2154 			__u16 opcode = le16_to_cpu(cmd->opcode);
2155 
2156 			/* When the BTINTEL_HCI_OP_RESET command is issued to
2157 			 * boot into the operational firmware, it will actually
2158 			 * not send a command complete event. To keep the flow
2159 			 * control working inject that event here.
2160 			 */
2161 			if (opcode == BTINTEL_HCI_OP_RESET)
2162 				btintel_pcie_inject_cmd_complete(hdev, opcode);
2163 		}
2164 
2165 		hdev->stat.cmd_tx++;
2166 		break;
2167 	case HCI_ACLDATA_PKT:
2168 		type = BTINTEL_PCIE_HCI_ACL_PKT;
2169 		hdev->stat.acl_tx++;
2170 		break;
2171 	case HCI_SCODATA_PKT:
2172 		type = BTINTEL_PCIE_HCI_SCO_PKT;
2173 		hdev->stat.sco_tx++;
2174 		break;
2175 	case HCI_ISODATA_PKT:
2176 		type = BTINTEL_PCIE_HCI_ISO_PKT;
2177 		break;
2178 	default:
2179 		bt_dev_err(hdev, "Unknown HCI packet type");
2180 		return -EILSEQ;
2181 	}
2182 
2183 	ret = btintel_pcie_send_sync(data, skb, type, opcode);
2184 	if (ret) {
2185 		hdev->stat.err_tx++;
2186 		bt_dev_err(hdev, "Failed to send frame (%d)", ret);
2187 		goto exit_error;
2188 	}
2189 
2190 	hdev->stat.byte_tx += skb->len;
2191 	kfree_skb(skb);
2192 
2193 exit_error:
2194 	return ret;
2195 }
2196 
2197 static void btintel_pcie_release_hdev(struct btintel_pcie_data *data)
2198 {
2199 	struct hci_dev *hdev = data->hdev;
2200 
2201 	if (!hdev)
2202 		return;
2203 
2204 	hci_unregister_dev(hdev);
2205 	hci_free_dev(hdev);
2206 	data->hdev = NULL;
2207 }
2208 
2209 static void btintel_pcie_disable_interrupts(struct btintel_pcie_data *data)
2210 {
2211 	spin_lock(&data->irq_lock);
2212 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK, data->fh_init_mask);
2213 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK, data->hw_init_mask);
2214 	spin_unlock(&data->irq_lock);
2215 }
2216 
2217 static void btintel_pcie_enable_interrupts(struct btintel_pcie_data *data)
2218 {
2219 	spin_lock(&data->irq_lock);
2220 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK, ~data->fh_init_mask);
2221 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK, ~data->hw_init_mask);
2222 	spin_unlock(&data->irq_lock);
2223 }
2224 
2225 static void btintel_pcie_synchronize_irqs(struct btintel_pcie_data *data)
2226 {
2227 	for (int i = 0; i < data->alloc_vecs; i++)
2228 		synchronize_irq(data->msix_entries[i].vector);
2229 }
2230 
2231 static int btintel_pcie_get_debug_info_addr(struct hci_dev *hdev)
2232 {
2233 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2234 	struct btintel_pcie_trigger_evt *evt;
2235 	u8 param[1] = {0x10};
2236 	struct sk_buff *skb;
2237 	int err = 0;
2238 
2239 	skb = __hci_cmd_sync(hdev, BTINTEL_HCI_OP_DEBUG, 1, param,
2240 			     HCI_CMD_TIMEOUT);
2241 	if (IS_ERR(skb)) {
2242 		bt_dev_err(hdev, "Reading Intel read debug info address command failed (%ld)",
2243 			   PTR_ERR(skb));
2244 		/* Not all Intel products supports this command */
2245 		if (PTR_ERR(skb) == -EOPNOTSUPP)
2246 			return 0;
2247 		return PTR_ERR(skb);
2248 	}
2249 
2250 	if (skb->len < (1 + sizeof(*evt))) {
2251 		bt_dev_err(hdev, "Debug info response too short (%u bytes)", skb->len);
2252 		err = -EIO;
2253 		goto exit_error;
2254 	}
2255 
2256 	/* Check the status */
2257 	if (skb->data[0]) {
2258 		bt_dev_err(hdev, "Reading Intel read debug info command failed (0x%2.2x)",
2259 			   skb->data[0]);
2260 		err = -EIO;
2261 		goto exit_error;
2262 	}
2263 
2264 	/* Consume Command Complete Status field */
2265 	skb_pull(skb, 1);
2266 
2267 	evt = (void *)skb->data;
2268 
2269 	data->debug_evt_addr = le32_to_cpu(evt->addr);
2270 	data->debug_evt_size = le32_to_cpu(evt->size);
2271 
2272 	bt_dev_dbg(hdev, "config type: %u config len: %u debug event addr: 0x%8.8x size: 0x%8.8x",
2273 		   evt->type, evt->len, data->debug_evt_addr,
2274 		   data->debug_evt_size);
2275 exit_error:
2276 	kfree_skb(skb);
2277 	return err;
2278 }
2279 
2280 static int btintel_pcie_setup_internal(struct hci_dev *hdev)
2281 {
2282 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2283 	const u8 param[1] = { 0xFF };
2284 	struct intel_version_tlv ver_tlv;
2285 	struct sk_buff *skb;
2286 	int err;
2287 
2288 	BT_DBG("%s", hdev->name);
2289 
2290 	skb = __hci_cmd_sync(hdev, 0xfc05, 1, param, HCI_CMD_TIMEOUT);
2291 	if (IS_ERR(skb)) {
2292 		bt_dev_err(hdev, "Reading Intel version command failed (%ld)",
2293 			   PTR_ERR(skb));
2294 		return PTR_ERR(skb);
2295 	}
2296 
2297 	/* Check the status */
2298 	if (skb->data[0]) {
2299 		bt_dev_err(hdev, "Intel Read Version command failed (%02x)",
2300 			   skb->data[0]);
2301 		err = -EIO;
2302 		goto exit_error;
2303 	}
2304 
2305 	/* Apply the common HCI quirks for Intel device */
2306 	hci_set_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER);
2307 	hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY);
2308 	hci_set_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_DIAG);
2309 
2310 	/* Set up the quality report callback for Intel devices */
2311 	hdev->set_quality_report = btintel_set_quality_report;
2312 
2313 	memset(&ver_tlv, 0, sizeof(ver_tlv));
2314 	/* For TLV type device, parse the tlv data */
2315 	err = btintel_parse_version_tlv(hdev, &ver_tlv, skb);
2316 	if (err) {
2317 		bt_dev_err(hdev, "Failed to parse TLV version information");
2318 		goto exit_error;
2319 	}
2320 
2321 	switch (INTEL_HW_PLATFORM(ver_tlv.cnvi_bt)) {
2322 	case 0x37:
2323 		break;
2324 	default:
2325 		bt_dev_err(hdev, "Unsupported Intel hardware platform (0x%2x)",
2326 			   INTEL_HW_PLATFORM(ver_tlv.cnvi_bt));
2327 		err = -EINVAL;
2328 		goto exit_error;
2329 	}
2330 
2331 	/* Check for supported iBT hardware variants of this firmware
2332 	 * loading method.
2333 	 *
2334 	 * This check has been put in place to ensure correct forward
2335 	 * compatibility options when newer hardware variants come
2336 	 * along.
2337 	 */
2338 	switch (INTEL_HW_VARIANT(ver_tlv.cnvi_bt)) {
2339 	case 0x1e:	/* BzrI */
2340 	case 0x1f:	/* ScP  */
2341 	case 0x20:	/* ScP2 */
2342 	case 0x21:	/* ScP2 F */
2343 	case 0x22:	/* BzrIW */
2344 		/* Display version information of TLV type */
2345 		btintel_version_info_tlv(hdev, &ver_tlv);
2346 
2347 		/* Apply the device specific HCI quirks for TLV based devices
2348 		 *
2349 		 * All TLV based devices support WBS
2350 		 */
2351 		hci_set_quirk(hdev, HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED);
2352 
2353 		/* Setup MSFT Extension support */
2354 		btintel_set_msft_opcode(hdev,
2355 					INTEL_HW_VARIANT(ver_tlv.cnvi_bt));
2356 
2357 		err = btintel_bootloader_setup_tlv(hdev, &ver_tlv);
2358 		if (err)
2359 			goto exit_error;
2360 		break;
2361 	default:
2362 		bt_dev_err(hdev, "Unsupported Intel hw variant (%u)",
2363 			   INTEL_HW_VARIANT(ver_tlv.cnvi_bt));
2364 		err = -EINVAL;
2365 		goto exit_error;
2366 		break;
2367 	}
2368 
2369 	data->dmp_hdr.cnvi_top = ver_tlv.cnvi_top;
2370 	data->dmp_hdr.cnvr_top = ver_tlv.cnvr_top;
2371 	data->dmp_hdr.fw_timestamp = ver_tlv.timestamp;
2372 	data->dmp_hdr.fw_build_type = ver_tlv.build_type;
2373 	data->dmp_hdr.fw_build_num = ver_tlv.build_num;
2374 	data->dmp_hdr.cnvi_bt = ver_tlv.cnvi_bt;
2375 
2376 	if (ver_tlv.img_type == 0x02 || ver_tlv.img_type == 0x03)
2377 		data->dmp_hdr.fw_git_sha1 = ver_tlv.git_sha1;
2378 
2379 	err = btintel_pcie_get_debug_info_addr(hdev);
2380 	if (err)
2381 		goto exit_error;
2382 
2383 	btintel_print_fseq_info(hdev);
2384 exit_error:
2385 	kfree_skb(skb);
2386 
2387 	return err;
2388 }
2389 
2390 static int btintel_pcie_setup(struct hci_dev *hdev)
2391 {
2392 	int err, fw_dl_retry = 0;
2393 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2394 
2395 	while ((err = btintel_pcie_setup_internal(hdev)) && fw_dl_retry++ < 1) {
2396 		bt_dev_err(hdev, "Firmware download retry count: %d",
2397 			   fw_dl_retry);
2398 		btintel_pcie_dump_debug_registers(hdev);
2399 		btintel_pcie_disable_interrupts(data);
2400 		btintel_pcie_synchronize_irqs(data);
2401 		err = btintel_pcie_reset_bt(data);
2402 		if (err) {
2403 			bt_dev_err(hdev, "Failed to do shr reset: %d", err);
2404 			break;
2405 		}
2406 		usleep_range(10000, 12000);
2407 		btintel_pcie_reset_ia(data);
2408 		btintel_pcie_enable_interrupts(data);
2409 		btintel_pcie_config_msix(data);
2410 		err = btintel_pcie_enable_bt(data);
2411 		if (err) {
2412 			bt_dev_err(hdev, "Failed to enable hardware: %d", err);
2413 			break;
2414 		}
2415 		btintel_pcie_start_rx(data);
2416 	}
2417 
2418 	if (!err)
2419 		set_bit(BTINTEL_PCIE_SETUP_DONE, &data->flags);
2420 	return err;
2421 }
2422 
2423 static struct btintel_pcie_dev_recovery *
2424 btintel_pcie_get_recovery(struct pci_dev *pdev, struct device *dev)
2425 {
2426 	struct btintel_pcie_dev_recovery *tmp, *data = NULL;
2427 	const char *name = pci_name(pdev);
2428 	const size_t name_len = strlen(name) + 1;
2429 	struct hci_dev *hdev = to_hci_dev(dev);
2430 
2431 	spin_lock(&btintel_pcie_recovery_lock);
2432 	list_for_each_entry(tmp, &btintel_pcie_recovery_list, list) {
2433 		if (strcmp(tmp->name, name))
2434 			continue;
2435 		data = tmp;
2436 		break;
2437 	}
2438 	spin_unlock(&btintel_pcie_recovery_lock);
2439 
2440 	if (data) {
2441 		bt_dev_dbg(hdev, "Found restart data for BDF: %s", data->name);
2442 		return data;
2443 	}
2444 
2445 	data = kzalloc_flex(*data, name, name_len, GFP_ATOMIC);
2446 	if (!data)
2447 		return NULL;
2448 
2449 	strscpy(data->name, name, name_len);
2450 	spin_lock(&btintel_pcie_recovery_lock);
2451 	list_add_tail(&data->list, &btintel_pcie_recovery_list);
2452 	spin_unlock(&btintel_pcie_recovery_lock);
2453 
2454 	return data;
2455 }
2456 
2457 static void btintel_pcie_free_restart_list(void)
2458 {
2459 	struct btintel_pcie_dev_recovery *tmp;
2460 
2461 	while ((tmp = list_first_entry_or_null(&btintel_pcie_recovery_list,
2462 					       typeof(*tmp), list))) {
2463 		list_del(&tmp->list);
2464 		kfree(tmp);
2465 	}
2466 }
2467 
2468 static void btintel_pcie_inc_recovery_count(struct pci_dev *pdev,
2469 					    struct device *dev)
2470 {
2471 	struct btintel_pcie_dev_recovery *data;
2472 	time64_t retry_window;
2473 
2474 	data = btintel_pcie_get_recovery(pdev, dev);
2475 	if (!data)
2476 		return;
2477 
2478 	retry_window = ktime_get_boottime_seconds() - data->last_error;
2479 	if (data->count == 0) {
2480 		data->last_error = ktime_get_boottime_seconds();
2481 		data->count++;
2482 	} else if (retry_window < BTINTEL_PCIE_RESET_WINDOW_SECS &&
2483 		   data->count <= BTINTEL_PCIE_FLR_MAX_RETRY) {
2484 		data->count++;
2485 	} else if (retry_window > BTINTEL_PCIE_RESET_WINDOW_SECS) {
2486 		data->last_error = 0;
2487 		data->count = 0;
2488 	}
2489 }
2490 
2491 static void btintel_pcie_reset(struct hci_dev *hdev);
2492 
2493 static int btintel_pcie_acpi_reset_method(struct btintel_pcie_data *data)
2494 {
2495 	union acpi_object *obj, argv4;
2496 	acpi_handle handle;
2497 	int ret;
2498 	struct pldr_mode {
2499 		__le16	cmd_type;
2500 		__le16	cmd_payload;
2501 	} __packed;
2502 
2503 	/* set 1 for _PRR mode
2504 	 * Product Reset (PLDR Abort flow)
2505 	 */
2506 	static const struct pldr_mode mode = {
2507 		.cmd_type = cpu_to_le16(1),
2508 		.cmd_payload = cpu_to_le16(BTINTEL_PCIE_DSM_PLDR_MODE_EN_PROD_RESET |
2509 			       BTINTEL_PCIE_DSM_PLDR_MODE_EN_WIFI_FLR),
2510 	};
2511 	struct hci_dev *hdev = data->hdev;
2512 
2513 	handle = ACPI_HANDLE(GET_HCIDEV_DEV(data->hdev));
2514 	if (!handle) {
2515 		bt_dev_err(data->hdev, "No support for bluetooth device in ACPI firmware");
2516 		return -EACCES;
2517 	}
2518 
2519 	if (!acpi_has_method(handle, "_PRR")) {
2520 		bt_dev_err(data->hdev, "No support for _PRR ACPI method, cold boot");
2521 		return -ENODEV;
2522 	}
2523 
2524 	argv4.buffer.type = ACPI_TYPE_BUFFER;
2525 	argv4.buffer.length = sizeof(mode);
2526 	argv4.buffer.pointer = (void *)&mode;
2527 
2528 	obj = acpi_evaluate_dsm(handle, &btintel_guid_dsm, 0,
2529 				BTINTEL_PCIE_DSM_DYNAMIC_PLDR, &argv4);
2530 	if (!obj) {
2531 		bt_dev_err(data->hdev, "Failed to call dsm to set reset method");
2532 		return -EIO;
2533 	}
2534 	ACPI_FREE(obj);
2535 
2536 	pci_dev_lock(data->pdev);
2537 	pci_save_state(data->pdev);
2538 	ret = btintel_acpi_reset_method(hdev);
2539 	if (ret)
2540 		bt_dev_err(data->hdev, "ACPI _PRR reset failed (%d), PLDR incomplete",
2541 			   ret);
2542 	pci_restore_state(data->pdev);
2543 	pci_dev_unlock(data->pdev);
2544 	return ret;
2545 }
2546 
2547 static void btintel_pcie_perform_pldr(struct btintel_pcie_data *data)
2548 {
2549 	struct pci_dev *pdev = data->pdev;
2550 	struct pci_dev *wifi = NULL;
2551 	struct pci_bus *bus;
2552 	int ret;
2553 	/* on integrated we have to look up by ID (same bus) */
2554 	static const struct pci_device_id wifi_device_ids[] = {
2555 	#define WIFI_DEV(_id) { PCI_DEVICE(PCI_VENDOR_ID_INTEL, _id) }
2556 		WIFI_DEV(0xA840), /* LNL */
2557 		WIFI_DEV(0xE440), /* PTL-P */
2558 		WIFI_DEV(0xE340), /* PTL-H */
2559 		WIFI_DEV(0xD340), /* NVL-H */
2560 		WIFI_DEV(0x6E70), /* NVL-S */
2561 		WIFI_DEV(0x4D40), /* WCL */
2562 		{}
2563 	};
2564 	struct pci_dev *tmp = NULL;
2565 
2566 	bus = pdev->bus;
2567 	if (!bus)
2568 		return;
2569 
2570 	list_for_each_entry(tmp, &bus->devices, bus_list) {
2571 		if (pci_match_id(wifi_device_ids, tmp)) {
2572 			wifi = pci_dev_get(tmp);
2573 			break;
2574 		}
2575 	}
2576 
2577 	if (wifi)
2578 		device_release_driver(&wifi->dev);
2579 
2580 	/* Wi-Fi is fully unbound before the reset and fully reprobed after
2581 	 * the normal PCI probe path handles all state setup from scratch.
2582 	 * BT needs pci_save_state()/pci_restore_state() because the BT driver
2583 	 * is still partially attached when the _PRR runs (it hasn't been unbound yet).
2584 	 * The PCI device needs to remain minimally functional so that
2585 	 * device_reprobe(&pdev->dev) can work afterward
2586 	 */
2587 	ret = btintel_pcie_acpi_reset_method(data);
2588 
2589 	if (wifi) {
2590 		if (device_reprobe(&wifi->dev))
2591 			BT_ERR("WiFi reprobe failed for BDF:%s", pci_name(wifi));
2592 		pci_dev_put(wifi);
2593 	}
2594 
2595 	if (!ret) {
2596 		if (device_reprobe(&pdev->dev))
2597 			BT_ERR("BT reprobe failed for BDF:%s", pci_name(pdev));
2598 	}
2599 }
2600 
2601 /*
2602  * Issue a Function Level Reset and hand teardown/re-init off to the PCI
2603  * core via device_reprobe(), mirroring the PLDR path's contract.
2604  *
2605  * Caller must hold pci_lock_rescan_remove() and must have already
2606  * disabled interrupts and drained both rx_work and coredump_work.
2607  */
2608 static int btintel_pcie_perform_flr(struct btintel_pcie_data *data)
2609 {
2610 	struct pci_dev *pdev = data->pdev;
2611 	int err;
2612 
2613 	/* pci_try_reset_function() avoids the device_lock ABBA against
2614 	 * btintel_pcie_remove(): .remove() runs with device_lock held and
2615 	 * then waits for this work via disable_work_sync(); the blocking
2616 	 * pci_reset_function() would deadlock by trying to re-acquire
2617 	 * device_lock here.
2618 	 */
2619 	err = pci_try_reset_function(pdev);
2620 	if (err) {
2621 		BT_ERR("Failed resetting the pcie device (%d)", err);
2622 		return err;
2623 	}
2624 
2625 	/* device_reprobe() always detaches the driver first (running
2626 	 * .remove(), which frees 'data'); any re-probe failure leaves the
2627 	 * device unbound but 'data' is already gone, so just log it.
2628 	 */
2629 	if (device_reprobe(&pdev->dev))
2630 		BT_ERR("BT reprobe failed for BDF:%s", pci_name(pdev));
2631 
2632 	return 0;
2633 }
2634 
2635 static void btintel_pcie_reset_work(struct work_struct *wk)
2636 {
2637 	struct btintel_pcie_data *data =
2638 		container_of(wk, struct btintel_pcie_data, reset_work);
2639 	struct pci_dev *pdev = data->pdev;
2640 
2641 	pci_lock_rescan_remove();
2642 
2643 	if (!pdev->bus)
2644 		goto out;
2645 
2646 	if (!data)
2647 		goto out;
2648 
2649 	btintel_pcie_disable_interrupts(data);
2650 	btintel_pcie_synchronize_irqs(data);
2651 
2652 	flush_work(&data->rx_work);
2653 	/* Drain any in-flight coredump and block new ones across reset.
2654 	 * Safe from self-deadlock: coredump_work runs on a separate wq.
2655 	 */
2656 	disable_work_sync(&data->coredump_work);
2657 
2658 	bt_dev_dbg(data->hdev, "Release bluetooth interface");
2659 
2660 	/* Both reset paths follow the same contract: on success they
2661 	 * destroy 'data' via device_reprobe() (a fresh probe re-INIT_WORKs
2662 	 * the coredump_work with disable count 0), so enable_work() must
2663 	 * NOT be called on the success path. Only the FLR path can fail
2664 	 * with 'data' still alive, in which case we balance the
2665 	 * disable_work_sync() above so a later successful reset is not
2666 	 * permanently blocked.
2667 	 *
2668 	 * pci_lock_rescan_remove() (held above) serializes against PCI
2669 	 * device addition/removal (hotplug), so no device can be added to
2670 	 * or removed from the bus list while this code runs.
2671 	 */
2672 	if (data->reset_type == BTINTEL_PCIE_IOSF_PRR_PLDR) {
2673 		btintel_pcie_perform_pldr(data);
2674 		goto out;
2675 	}
2676 
2677 	if (btintel_pcie_perform_flr(data))
2678 		enable_work(&data->coredump_work);
2679 
2680 out:
2681 	pci_dev_put(pdev);
2682 	pci_unlock_rescan_remove();
2683 }
2684 
2685 static void btintel_pcie_reset(struct hci_dev *hdev)
2686 {
2687 	struct btintel_pcie_data *data;
2688 
2689 	data = hci_get_drvdata(hdev);
2690 
2691 	if (!test_bit(BTINTEL_PCIE_SETUP_DONE, &data->flags))
2692 		return;
2693 
2694 	if (test_and_set_bit(BTINTEL_PCIE_RECOVERY_IN_PROGRESS, &data->flags))
2695 		return;
2696 
2697 	pci_dev_get(data->pdev);
2698 	schedule_work(&data->reset_work);
2699 }
2700 
2701 static void btintel_pcie_hw_error(struct hci_dev *hdev, u8 code)
2702 {
2703 	struct btintel_pcie_dev_recovery *data;
2704 	struct btintel_pcie_data *dev_data = hci_get_drvdata(hdev);
2705 	struct pci_dev *pdev = dev_data->pdev;
2706 	time64_t retry_window;
2707 
2708 	btintel_pcie_dump_debug_registers(hdev);
2709 
2710 	data = btintel_pcie_get_recovery(pdev, &hdev->dev);
2711 	if (!data)
2712 		return;
2713 
2714 	if (code == 0x13)
2715 		dev_data->reset_type = BTINTEL_PCIE_IOSF_PRR_PLDR;
2716 	else
2717 		dev_data->reset_type = BTINTEL_PCIE_IOSF_PRR_FLR;
2718 
2719 	bt_dev_err(hdev, "Encountered exception err:0x%x triggering: %s", code,
2720 		   dev_data->reset_type == BTINTEL_PCIE_IOSF_PRR_PLDR ? "PLDR" : "FLR");
2721 	retry_window = ktime_get_boottime_seconds() - data->last_error;
2722 
2723 	if (retry_window < BTINTEL_PCIE_RESET_WINDOW_SECS &&
2724 	    data->count >= BTINTEL_PCIE_FLR_MAX_RETRY) {
2725 		bt_dev_err(hdev, "Exhausted maximum: %d recovery attempts: %d",
2726 			   BTINTEL_PCIE_FLR_MAX_RETRY, data->count);
2727 		bt_dev_dbg(hdev, "Boot time: %lld seconds",
2728 			   ktime_get_boottime_seconds());
2729 		bt_dev_dbg(hdev, "last error at: %lld seconds",
2730 			   data->last_error);
2731 		return;
2732 	}
2733 	btintel_pcie_inc_recovery_count(pdev, &hdev->dev);
2734 	btintel_pcie_reset(hdev);
2735 }
2736 
2737 static bool btintel_pcie_wakeup(struct hci_dev *hdev)
2738 {
2739 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2740 
2741 	return device_may_wakeup(&data->pdev->dev);
2742 }
2743 
2744 static const struct {
2745 	u16 opcode;
2746 	const char *desc;
2747 } btintel_pcie_hci_drv_supported_commands[] = {
2748 	/* Common commands */
2749 	{ HCI_DRV_OP_READ_INFO, "Read Info" },
2750 };
2751 
2752 static int btintel_pcie_hci_drv_read_info(struct hci_dev *hdev, void *data,
2753 					  u16 data_len)
2754 {
2755 	struct hci_drv_rp_read_info *rp;
2756 	size_t rp_size;
2757 	int err, i;
2758 	u16 opcode, num_supported_commands =
2759 		ARRAY_SIZE(btintel_pcie_hci_drv_supported_commands);
2760 
2761 	rp_size = struct_size(rp, supported_commands, num_supported_commands);
2762 
2763 	rp = kmalloc(rp_size, GFP_KERNEL);
2764 	if (!rp)
2765 		return -ENOMEM;
2766 
2767 	strscpy_pad(rp->driver_name, KBUILD_MODNAME);
2768 
2769 	rp->num_supported_commands = cpu_to_le16(num_supported_commands);
2770 	for (i = 0; i < num_supported_commands; i++) {
2771 		opcode = btintel_pcie_hci_drv_supported_commands[i].opcode;
2772 		bt_dev_dbg(hdev,
2773 			    "Supported HCI Drv command (0x%02x|0x%04x): %s",
2774 			    hci_opcode_ogf(opcode),
2775 			    hci_opcode_ocf(opcode),
2776 			    btintel_pcie_hci_drv_supported_commands[i].desc);
2777 		rp->supported_commands[i] = cpu_to_le16(opcode);
2778 	}
2779 
2780 	err = hci_drv_cmd_complete(hdev, HCI_DRV_OP_READ_INFO,
2781 				   HCI_DRV_STATUS_SUCCESS,
2782 				   rp, rp_size);
2783 
2784 	kfree(rp);
2785 	return err;
2786 }
2787 
2788 static const struct hci_drv_handler btintel_pcie_hci_drv_common_handlers[] = {
2789 	{ btintel_pcie_hci_drv_read_info,       HCI_DRV_READ_INFO_SIZE },
2790 };
2791 
2792 static const struct hci_drv_handler btintel_pcie_hci_drv_specific_handlers[] = {};
2793 
2794 static struct hci_drv btintel_pcie_hci_drv = {
2795 	.common_handler_count   = ARRAY_SIZE(btintel_pcie_hci_drv_common_handlers),
2796 	.common_handlers        = btintel_pcie_hci_drv_common_handlers,
2797 	.specific_handler_count = ARRAY_SIZE(btintel_pcie_hci_drv_specific_handlers),
2798 	.specific_handlers      = btintel_pcie_hci_drv_specific_handlers,
2799 };
2800 
2801 static int btintel_pcie_setup_hdev(struct btintel_pcie_data *data)
2802 {
2803 	int err;
2804 	struct hci_dev *hdev;
2805 
2806 	hdev = hci_alloc_dev_priv(sizeof(struct btintel_data));
2807 	if (!hdev)
2808 		return -ENOMEM;
2809 
2810 	hdev->bus = HCI_PCI;
2811 	hci_set_drvdata(hdev, data);
2812 
2813 	SET_HCIDEV_DEV(hdev, &data->pdev->dev);
2814 
2815 	hdev->manufacturer = 2;
2816 	hdev->open = btintel_pcie_open;
2817 	hdev->close = btintel_pcie_close;
2818 	hdev->send = btintel_pcie_send_frame;
2819 	hdev->setup = btintel_pcie_setup;
2820 	hdev->shutdown = btintel_shutdown_combined;
2821 	hdev->hw_error = btintel_pcie_hw_error;
2822 	hdev->set_diag = btintel_set_diag;
2823 	hdev->set_bdaddr = btintel_set_bdaddr;
2824 	hdev->reset = btintel_pcie_reset;
2825 	hdev->wakeup = btintel_pcie_wakeup;
2826 	hdev->hci_drv = &btintel_pcie_hci_drv;
2827 
2828 	err = hci_register_dev(hdev);
2829 	if (err < 0) {
2830 		BT_ERR("Failed to register to hdev (%d)", err);
2831 		hci_free_dev(hdev);
2832 		return err;
2833 	}
2834 
2835 	/* Publish hdev only after successful registration; the coredump
2836 	 * worker bails on !data->hdev, so it never observes a half-set-up
2837 	 * device.
2838 	 */
2839 	data->hdev = hdev;
2840 	data->dmp_hdr.driver_name = KBUILD_MODNAME;
2841 	return 0;
2842 }
2843 
2844 static int btintel_pcie_probe(struct pci_dev *pdev,
2845 			      const struct pci_device_id *ent)
2846 {
2847 	int err;
2848 	struct btintel_pcie_data *data;
2849 
2850 	if (!pdev)
2851 		return -ENODEV;
2852 
2853 	data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
2854 	if (!data)
2855 		return -ENOMEM;
2856 
2857 	data->pdev = pdev;
2858 
2859 	spin_lock_init(&data->irq_lock);
2860 	spin_lock_init(&data->hci_rx_lock);
2861 
2862 	init_waitqueue_head(&data->gp0_wait_q);
2863 	data->gp0_received = false;
2864 
2865 	init_waitqueue_head(&data->tx_wait_q);
2866 	data->tx_wait_done = false;
2867 
2868 	data->workqueue = alloc_ordered_workqueue(KBUILD_MODNAME, WQ_HIGHPRI);
2869 	if (!data->workqueue)
2870 		return -ENOMEM;
2871 
2872 	data->coredump_workqueue = alloc_ordered_workqueue(KBUILD_MODNAME "_cd", 0);
2873 	if (!data->coredump_workqueue) {
2874 		destroy_workqueue(data->workqueue);
2875 		return -ENOMEM;
2876 	}
2877 
2878 	skb_queue_head_init(&data->rx_skb_q);
2879 	INIT_WORK(&data->rx_work, btintel_pcie_rx_work);
2880 	INIT_WORK(&data->reset_work, btintel_pcie_reset_work);
2881 	INIT_WORK(&data->coredump_work, btintel_pcie_coredump_worker);
2882 
2883 	data->boot_stage_cache = 0x00;
2884 	data->img_resp_cache = 0x00;
2885 	/* FLR can be invoked by echoing to debugfs path, so explicitly
2886 	 * initialized
2887 	 */
2888 	data->reset_type = BTINTEL_PCIE_IOSF_PRR_FLR;
2889 	err = btintel_pcie_config_pcie(pdev, data);
2890 	if (err)
2891 		goto exit_error;
2892 
2893 	pci_set_drvdata(pdev, data);
2894 
2895 	err = btintel_pcie_alloc(data);
2896 	if (err)
2897 		goto exit_error;
2898 
2899 	err = btintel_pcie_enable_bt(data);
2900 	if (err)
2901 		goto exit_error;
2902 
2903 	/* CNV information (CNVi and CNVr) is in CSR */
2904 	data->cnvi = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_HW_REV_REG);
2905 
2906 	data->cnvr = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_RF_ID_REG);
2907 
2908 	err = btintel_pcie_start_rx(data);
2909 	if (err)
2910 		goto exit_error;
2911 
2912 	err = btintel_pcie_setup_hdev(data);
2913 	if (err)
2914 		goto exit_error;
2915 
2916 	bt_dev_dbg(data->hdev, "cnvi: 0x%8.8x cnvr: 0x%8.8x", data->cnvi,
2917 		   data->cnvr);
2918 	return 0;
2919 
2920 exit_error:
2921 	/* reset device before exit */
2922 	btintel_pcie_reset_bt(data);
2923 
2924 	destroy_workqueue(data->coredump_workqueue);
2925 
2926 	pci_clear_master(pdev);
2927 
2928 	pci_set_drvdata(pdev, NULL);
2929 
2930 	return err;
2931 }
2932 
2933 static void btintel_pcie_remove(struct pci_dev *pdev)
2934 {
2935 	struct btintel_pcie_data *data;
2936 
2937 	data = pci_get_drvdata(pdev);
2938 	if (!data) {
2939 		BT_WARN("PCI driver data is NULL, aborting remove");
2940 		return;
2941 	}
2942 
2943 	/* Permanently block coredump triggers and drain the worker before
2944 	 * tearing down. Must run before cancel_work_sync(&reset_work) so
2945 	 * the disable counter stays >= 1 even after reset_work()'s
2946 	 * balanced enable_work() (counter 2 -> 1, never reaching 0).
2947 	 */
2948 	disable_work_sync(&data->coredump_work);
2949 
2950 	/* Cancel pending reset work. Skip only when remove() is called from
2951 	 * within the reset work itself (PLDR device_reprobe path) to avoid
2952 	 * deadlock. current_work() returns the work_struct of the caller if
2953 	 * we are in a workqueue context.
2954 	 */
2955 	if (current_work() != &data->reset_work)
2956 		disable_work_sync(&data->reset_work);
2957 
2958 	btintel_pcie_disable_interrupts(data);
2959 
2960 	btintel_pcie_synchronize_irqs(data);
2961 
2962 	flush_work(&data->rx_work);
2963 
2964 	btintel_pcie_reset_bt(data);
2965 	for (int i = 0; i < data->alloc_vecs; i++) {
2966 		struct msix_entry *msix_entry;
2967 
2968 		msix_entry = &data->msix_entries[i];
2969 		free_irq(msix_entry->vector, msix_entry);
2970 	}
2971 
2972 	pci_free_irq_vectors(pdev);
2973 
2974 	btintel_pcie_release_hdev(data);
2975 
2976 	destroy_workqueue(data->coredump_workqueue);
2977 	destroy_workqueue(data->workqueue);
2978 
2979 	btintel_pcie_free(data);
2980 
2981 	pci_clear_master(pdev);
2982 
2983 	pci_set_drvdata(pdev, NULL);
2984 }
2985 
2986 #ifdef CONFIG_DEV_COREDUMP
2987 static void btintel_pcie_coredump(struct device *dev)
2988 {
2989 	struct  pci_dev *pdev = to_pci_dev(dev);
2990 	struct btintel_pcie_data *data = pci_get_drvdata(pdev);
2991 
2992 	if (!data)
2993 		return;
2994 
2995 	if (test_and_set_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags))
2996 		return;
2997 
2998 	data->dmp_hdr.trigger_reason  = BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER;
2999 	/* queue_work() returns false if the work is disabled (reset or
3000 	 * remove in progress); clear the in-progress bit so a later
3001 	 * trigger can succeed once the work is re-enabled.
3002 	 */
3003 	if (!queue_work(data->coredump_workqueue, &data->coredump_work))
3004 		clear_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags);
3005 }
3006 #endif
3007 
3008 static int btintel_pcie_set_dxstate(struct btintel_pcie_data *data, u32 dxstate)
3009 {
3010 	int retry = 0, status;
3011 	u32 dx_intr_timeout_ms = 200;
3012 
3013 	do {
3014 		data->gp0_received = false;
3015 
3016 		btintel_pcie_wr_sleep_cntrl(data, dxstate);
3017 
3018 		status = wait_event_timeout(data->gp0_wait_q, data->gp0_received,
3019 			msecs_to_jiffies(dx_intr_timeout_ms));
3020 
3021 		if (status)
3022 			return 0;
3023 
3024 		bt_dev_warn(data->hdev,
3025 			   "Timeout (%u ms) on alive interrupt for D%d entry, retry count %d",
3026 			   dx_intr_timeout_ms, dxstate, retry);
3027 
3028 		/* clear gp0 cause */
3029 		btintel_pcie_clr_reg_bits(data,
3030 					  BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES,
3031 					  BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0);
3032 
3033 		/* A hardware bug may cause the alive interrupt to be missed.
3034 		 * Check if the controller reached the expected state and retry
3035 		 * the operation only if it hasn't.
3036 		 */
3037 		if (dxstate == BTINTEL_PCIE_STATE_D0) {
3038 			if (btintel_pcie_in_d0(data))
3039 				return 0;
3040 		} else {
3041 			if (btintel_pcie_in_d3(data))
3042 				return 0;
3043 		}
3044 
3045 	} while (++retry < BTINTEL_PCIE_DX_TRANSITION_MAX_RETRIES);
3046 
3047 	return -EBUSY;
3048 }
3049 
3050 static int btintel_pcie_suspend_late(struct device *dev, pm_message_t mesg)
3051 {
3052 	struct pci_dev *pdev = to_pci_dev(dev);
3053 	struct btintel_pcie_data *data;
3054 	ktime_t start;
3055 	u32 dxstate;
3056 	int err;
3057 
3058 	data = pci_get_drvdata(pdev);
3059 
3060 	dxstate = (mesg.event == PM_EVENT_SUSPEND ?
3061 		   BTINTEL_PCIE_STATE_D3_HOT : BTINTEL_PCIE_STATE_D3_COLD);
3062 
3063 	data->pm_sx_event = mesg.event;
3064 
3065 	start = ktime_get();
3066 
3067 	/* Refer: 6.4.11.7 -> Platform power management */
3068 	err = btintel_pcie_set_dxstate(data, dxstate);
3069 
3070 	if (err)
3071 		return err;
3072 
3073 	bt_dev_dbg(data->hdev,
3074 		   "device entered into d3 state from d0 in %lld us",
3075 		   ktime_to_us(ktime_get() - start));
3076 	return err;
3077 }
3078 
3079 static int btintel_pcie_suspend(struct device *dev)
3080 {
3081 	return btintel_pcie_suspend_late(dev, PMSG_SUSPEND);
3082 }
3083 
3084 static int btintel_pcie_hibernate(struct device *dev)
3085 {
3086 	return btintel_pcie_suspend_late(dev, PMSG_HIBERNATE);
3087 }
3088 
3089 static int btintel_pcie_freeze(struct device *dev)
3090 {
3091 	return btintel_pcie_suspend_late(dev, PMSG_FREEZE);
3092 }
3093 
3094 static int btintel_pcie_resume(struct device *dev)
3095 {
3096 	struct pci_dev *pdev = to_pci_dev(dev);
3097 	struct btintel_pcie_data *data;
3098 	ktime_t start;
3099 	int err;
3100 
3101 	data = pci_get_drvdata(pdev);
3102 	data->gp0_received = false;
3103 
3104 	start = ktime_get();
3105 
3106 	/* When the system enters S4 (hibernate) mode, bluetooth device loses
3107 	 * power, which results in the erasure of its loaded firmware.
3108 	 * Consequently, function level reset (flr) is required on system
3109 	 * resume to bring the controller back into an operational state by
3110 	 * initiating a new firmware download.
3111 	 */
3112 
3113 	if (data->pm_sx_event == PM_EVENT_FREEZE ||
3114 	    data->pm_sx_event == PM_EVENT_HIBERNATE) {
3115 		set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags);
3116 		data->reset_type = BTINTEL_PCIE_IOSF_PRR_FLR;
3117 		btintel_pcie_reset(data->hdev);
3118 		return 0;
3119 	}
3120 
3121 	/* Refer: 6.4.11.7 -> Platform power management */
3122 	err = btintel_pcie_set_dxstate(data, BTINTEL_PCIE_STATE_D0);
3123 
3124 	if (err == 0) {
3125 		bt_dev_dbg(data->hdev,
3126 			   "device entered into d0 state from d3 in %lld us",
3127 			   ktime_to_us(ktime_get() - start));
3128 		return err;
3129 	}
3130 
3131 	/* Trigger function level reset if the controller is in error
3132 	 * state during resume() to bring back the controller to
3133 	 * operational mode
3134 	 */
3135 
3136 	data->boot_stage_cache = btintel_pcie_rd_reg32(data,
3137 			BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
3138 	if (btintel_pcie_in_error(data) ||
3139 			btintel_pcie_in_device_halt(data)) {
3140 		bt_dev_err(data->hdev, "Controller in error state for D0 entry");
3141 		if (!test_and_set_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS,
3142 				      &data->flags)) {
3143 			data->dmp_hdr.trigger_reason =
3144 				BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT;
3145 			queue_work(data->coredump_workqueue, &data->coredump_work);
3146 		}
3147 		set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags);
3148 		btintel_pcie_reset(data->hdev);
3149 	}
3150 	return err;
3151 }
3152 
3153 static const struct dev_pm_ops btintel_pcie_pm_ops = {
3154 	.suspend = btintel_pcie_suspend,
3155 	.resume = btintel_pcie_resume,
3156 	.freeze = btintel_pcie_freeze,
3157 	.thaw = btintel_pcie_resume,
3158 	.poweroff = btintel_pcie_hibernate,
3159 	.restore = btintel_pcie_resume,
3160 };
3161 
3162 static struct pci_driver btintel_pcie_driver = {
3163 	.name = KBUILD_MODNAME,
3164 	.id_table = btintel_pcie_table,
3165 	.probe = btintel_pcie_probe,
3166 	.remove = btintel_pcie_remove,
3167 	.driver.pm = pm_sleep_ptr(&btintel_pcie_pm_ops),
3168 #ifdef CONFIG_DEV_COREDUMP
3169 	.driver.coredump = btintel_pcie_coredump
3170 #endif
3171 };
3172 
3173 static int __init btintel_pcie_init(void)
3174 {
3175 	return pci_register_driver(&btintel_pcie_driver);
3176 }
3177 
3178 static void __exit btintel_pcie_exit(void)
3179 {
3180 	pci_unregister_driver(&btintel_pcie_driver);
3181 	btintel_pcie_free_restart_list();
3182 }
3183 
3184 module_init(btintel_pcie_init);
3185 module_exit(btintel_pcie_exit);
3186 
3187 MODULE_AUTHOR("Tedd Ho-Jeong An <tedd.an@intel.com>");
3188 MODULE_DESCRIPTION("Intel Bluetooth PCIe transport driver ver " VERSION);
3189 MODULE_VERSION(VERSION);
3190 MODULE_LICENSE("GPL");
3191