xref: /linux/drivers/bluetooth/btintel_pcie.c (revision 639a75a3539f621e4437ffeec7ab51bf8a1fb170)
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 #include <linux/suspend.h>
20 
21 #include <linux/unaligned.h>
22 #include <linux/devcoredump.h>
23 #include <linux/scatterlist.h>
24 
25 #include <net/bluetooth/bluetooth.h>
26 #include <net/bluetooth/hci_core.h>
27 #include <net/bluetooth/hci_drv.h>
28 
29 #include "btintel.h"
30 #include "btintel_pcie.h"
31 
32 #define VERSION "0.1"
33 
34 #define BTINTEL_PCI_DEVICE(dev, subdev)	\
35 	.vendor = PCI_VENDOR_ID_INTEL,	\
36 	.device = (dev),		\
37 	.subvendor = PCI_ANY_ID,	\
38 	.subdevice = (subdev),		\
39 	.driver_data = 0
40 
41 #define POLL_INTERVAL_US	10
42 
43 #define BTINTEL_PCIE_DMA_ALIGN_128B	128 /* 128 byte aligned */
44 
45 /* Intel Bluetooth PCIe device id table */
46 static const struct pci_device_id btintel_pcie_table[] = {
47 	/* BlazarI, Wildcat Lake */
48 	{ BTINTEL_PCI_DEVICE(0x4D76, PCI_ANY_ID) },
49 	/* BlazarI, Lunar Lake */
50 	{ BTINTEL_PCI_DEVICE(0xA876, PCI_ANY_ID) },
51 	/* Scorpious, Panther Lake-H484 */
52 	{ BTINTEL_PCI_DEVICE(0xE376, PCI_ANY_ID) },
53 	 /* Scorpious, Panther Lake-H404 */
54 	{ BTINTEL_PCI_DEVICE(0xE476, PCI_ANY_ID) },
55 	 /* Scorpious2, Nova Lake-PCD-H */
56 	{ BTINTEL_PCI_DEVICE(0xD346, PCI_ANY_ID) },
57 	 /* Scorpious2, Nova Lake-PCD-S */
58 	{ BTINTEL_PCI_DEVICE(0x6E74, PCI_ANY_ID) },
59 	 /* Draco */
60 	{ BTINTEL_PCI_DEVICE(0x2731, PCI_ANY_ID) },
61 	{ BTINTEL_PCI_DEVICE(0x2732, PCI_ANY_ID) },
62 	/* Scorpious Peak2 C0, Titan Lake */
63 	{ BTINTEL_PCI_DEVICE(0x9329, PCI_ANY_ID) },
64 	{ 0 }
65 };
66 MODULE_DEVICE_TABLE(pci, btintel_pcie_table);
67 
68 struct btintel_pcie_dev_recovery {
69 	struct list_head list;
70 	u8 count;
71 	time64_t last_error;
72 	char name[];
73 };
74 
75 /* Intel PCIe uses 4 bytes of HCI type instead of 1 byte BT SIG HCI type */
76 #define BTINTEL_PCIE_HCI_TYPE_LEN	4
77 #define BTINTEL_PCIE_HCI_CMD_PKT	0x00000001
78 #define BTINTEL_PCIE_HCI_ACL_PKT	0x00000002
79 #define BTINTEL_PCIE_HCI_SCO_PKT	0x00000003
80 #define BTINTEL_PCIE_HCI_EVT_PKT	0x00000004
81 #define BTINTEL_PCIE_HCI_ISO_PKT	0x00000005
82 
83 #define BTINTEL_PCIE_MAGIC_NUM	0xA5A5A5A5
84 
85 #define BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER	0x17A2
86 #define BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT		0x1E61
87 
88 #define BTINTEL_PCIE_RESET_WINDOW_SECS		5
89 #define BTINTEL_PCIE_FLR_MAX_RETRY	1
90 
91 /* Alive interrupt context */
92 enum {
93 	BTINTEL_PCIE_ROM,
94 	BTINTEL_PCIE_FW_DL,
95 	BTINTEL_PCIE_HCI_RESET,
96 	BTINTEL_PCIE_INTEL_HCI_RESET1,
97 	BTINTEL_PCIE_INTEL_HCI_RESET2,
98 	BTINTEL_PCIE_D0,
99 	BTINTEL_PCIE_D3
100 };
101 
102 enum {
103 	BTINTEL_PCIE_DSM_SET_RESET_TIMING = 1,
104 	BTINTEL_PCIE_DSM_GET_RESET_TIMING = 2,
105 	BTINTEL_PCIE_DSM_BT_PLDR_CONFIG = 3,
106 	BTINTEL_PCIE_DSM_GET_RESET_TYPE = 4,
107 	BTINTEL_PCIE_DSM_DYNAMIC_PLDR = 5,
108 	BTINTEL_PCIE_DSM_GET_RESET_METHOD = 6,
109 	BTINTEL_PCIE_DSM_SET_PLDR_DELAY = 7,
110 };
111 
112 enum btintel_dsm_internal_product_reset_mode {
113 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_PROD_RESET	= BIT(0),
114 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_WIFI_FLR		= BIT(1),
115 	BTINTEL_PCIE_DSM_PLDR_MODE_EN_BT_OFF_ON		= BIT(2),
116 };
117 
118 /* Structure for dbgc fragment buffer
119  * @buf_addr_lsb: LSB of the buffer's physical address
120  * @buf_addr_msb: MSB of the buffer's physical address
121  * @buf_size: Total size of the buffer
122  */
123 struct btintel_pcie_dbgc_ctxt_buf {
124 	u32	buf_addr_lsb;
125 	u32	buf_addr_msb;
126 	u32	buf_size;
127 };
128 
129 /* Structure for dbgc fragment
130  * @magic_num: 0XA5A5A5A5
131  * @ver: For Driver-FW compatibility
132  * @total_size: Total size of the payload debug info
133  * @num_buf: Num of allocated debug bufs
134  * @bufs: All buffer's addresses and sizes
135  */
136 struct btintel_pcie_dbgc_ctxt {
137 	u32	magic_num;
138 	u32     ver;
139 	u32     total_size;
140 	u32     num_buf;
141 	struct btintel_pcie_dbgc_ctxt_buf bufs[BTINTEL_PCIE_DBGC_BUFFER_COUNT];
142 };
143 
144 struct btintel_pcie_mdbgc_ctxt {
145 	u32     magic_num;
146 	u32     ver;
147 	u32     buf1_index;
148 	u32     buf1_count;
149 	struct btintel_pcie_dbgc_ctxt_buf buf1[BTINTEL_PCIE_DBGC_BUFFER_COUNT];
150 	u32     buf2_index;
151 	u32     buf2_count;
152 	struct btintel_pcie_dbgc_ctxt_buf buf2[BTINTEL_PCIE_DBGC_BUFFER_COUNT];
153 	u32     buf3_index;
154 	u32     buf3_count;
155 	struct btintel_pcie_dbgc_ctxt_buf buf3[BTINTEL_PCIE_DBGC_BUFFER_COUNT];
156 };
157 
158 struct btintel_pcie_trigger_evt {
159 	u8 type;
160 	u8 len;
161 	__le32 addr;
162 	__le32 size;
163 } __packed;
164 
165 struct btintel_pcie_fwtrigger_evt {
166 	__le32 reserved;
167 	u8	type; /* Debug Trigger event */
168 	__le16	len;
169 	u8	event_type;
170 	__le16	event_id;
171 	__le16	reserved2;
172 } __packed;
173 
174 static LIST_HEAD(btintel_pcie_recovery_list);
175 static DEFINE_SPINLOCK(btintel_pcie_recovery_lock);
176 
177 static inline char *btintel_pcie_alivectxt_state2str(u32 alive_intr_ctxt)
178 {
179 	switch (alive_intr_ctxt) {
180 	case BTINTEL_PCIE_ROM:
181 		return "rom";
182 	case BTINTEL_PCIE_FW_DL:
183 		return "fw_dl";
184 	case BTINTEL_PCIE_D0:
185 		return "d0";
186 	case BTINTEL_PCIE_D3:
187 		return "d3";
188 	case BTINTEL_PCIE_HCI_RESET:
189 		return "hci_reset";
190 	case BTINTEL_PCIE_INTEL_HCI_RESET1:
191 		return "intel_reset1";
192 	case BTINTEL_PCIE_INTEL_HCI_RESET2:
193 		return "intel_reset2";
194 	default:
195 		return "unknown";
196 	}
197 }
198 
199 /* Returns true when firmware traces are routed to the WiFi DBGC. In that
200  * mode the host must not allocate DBGC buffers and must not publish their
201  * addresses in the context info.
202  */
203 static inline bool btintel_pcie_dbg_to_wifi(struct btintel_pcie_data *data)
204 {
205 	return data->dbg_path_cache != BTINTEL_PCIE_DRAM;
206 }
207 
208 /* Helper function to allocate and setup a debug buffer group
209  * @data: driver data structure
210  * @buf: pointer to data_buf array pointer
211  * @p_addr: pointer to physical DMA address
212  * @v_addr: pointer to virtual address
213  * @frag: pointer to fragment buffer array
214  * @buf_index: buffer index (for error messages)
215  * @buf_count: number of buffers to allocate
216  */
217 static int btintel_pcie_alloc_dbgc_buf(struct btintel_pcie_data *data,
218 				       struct data_buf **buf,
219 				       dma_addr_t *p_addr,
220 				       void **v_addr,
221 				       struct btintel_pcie_dbgc_ctxt_buf *frag,
222 				       u32 buf_index,
223 				       u32 buf_count)
224 {
225 	struct data_buf *b;
226 	int i;
227 
228 	*buf = devm_kzalloc_objs(&data->pdev->dev, **buf, buf_count);
229 	if (!*buf) {
230 		BT_ERR("Failed to allocate dbgc buf: %u", buf_index + 1);
231 		return -ENOMEM;
232 	}
233 
234 	*v_addr = dmam_alloc_coherent(&data->pdev->dev,
235 				      buf_count *
236 					BTINTEL_PCIE_DBGC_BUFFER_SIZE,
237 					p_addr,
238 					GFP_KERNEL | __GFP_NOWARN);
239 	if (!*v_addr) {
240 		BT_ERR("Failed to allocate dbgc buf: %u DMA", buf_index + 1);
241 		return -ENOMEM;
242 	}
243 
244 	for (i = 0; i < buf_count; i++) {
245 		b = &(*buf)[i];
246 		b->data_p_addr = *p_addr + i * BTINTEL_PCIE_DBGC_BUFFER_SIZE;
247 		b->data = *v_addr + i * BTINTEL_PCIE_DBGC_BUFFER_SIZE;
248 		frag[i].buf_addr_lsb = lower_32_bits(b->data_p_addr);
249 		frag[i].buf_addr_msb = upper_32_bits(b->data_p_addr);
250 		frag[i].buf_size = BTINTEL_PCIE_DBGC_BUFFER_SIZE;
251 	}
252 
253 	return 0;
254 }
255 
256 /* This function initializes the memory for MDBGC buffers and formats the
257  * DBGC fragment which consists header info and DBGC buffer's LSB, MSB and
258  * size as the payload
259  */
260 static int btintel_pcie_setup_mdbgc(struct btintel_pcie_data *data)
261 {
262 	struct btintel_pcie_mdbgc_ctxt db_frag;
263 	u32 frag_size = sizeof(db_frag);
264 	void *frag_v_addr;
265 	int err;
266 
267 	data->mdbgc.count = BTINTEL_PCIE_DBGC_BUFFER_COUNT;
268 
269 	/* Allocate fragment context structure */
270 	frag_v_addr = dmam_alloc_coherent(&data->pdev->dev, frag_size,
271 					  &data->mdbgc.frag_p_addr,
272 					  GFP_KERNEL | __GFP_NOWARN);
273 	if (!frag_v_addr) {
274 		BT_ERR("Failed to allocate mdbgc context");
275 		return -ENOMEM;
276 	}
277 
278 	data->mdbgc.frag_v_addr = frag_v_addr;
279 	data->mdbgc.frag_size = frag_size;
280 
281 	/* Initialize fragment header */
282 	memset(&db_frag, 0, sizeof(db_frag));
283 	db_frag.magic_num = BTINTEL_PCIE_MAGIC_NUM;
284 	db_frag.ver = BTINTEL_PCIE_MDBGC_FRAG_VERSION;
285 
286 	/* Allocate DBGC buffer 1 */
287 	db_frag.buf1_index = BTINTEL_PCIE_MDBGC_ALLOCATIONID_1;
288 	db_frag.buf1_count = data->mdbgc.count;
289 	err = btintel_pcie_alloc_dbgc_buf(data,
290 					  &data->mdbgc.buf1,
291 					  &data->mdbgc.buf1_p_addr,
292 					  &data->mdbgc.buf1_v_addr,
293 					  db_frag.buf1,
294 					  0,
295 					  data->mdbgc.count);
296 	if (err)
297 		return err;
298 
299 	/* Allocate DBGC buffer 2 */
300 	db_frag.buf2_index = BTINTEL_PCIE_MDBGC_ALLOCATIONID_2;
301 	db_frag.buf2_count = data->mdbgc.count;
302 	err = btintel_pcie_alloc_dbgc_buf(data,
303 					  &data->mdbgc.buf2,
304 					  &data->mdbgc.buf2_p_addr,
305 					  &data->mdbgc.buf2_v_addr,
306 					  db_frag.buf2,
307 					  1,
308 					  data->mdbgc.count);
309 	if (err)
310 		return err;
311 
312 	/* Allocate DBGC buffer 3 */
313 	db_frag.buf3_index = BTINTEL_PCIE_MDBGC_ALLOCATIONID_3;
314 	db_frag.buf3_count = data->mdbgc.count;
315 	err = btintel_pcie_alloc_dbgc_buf(data,
316 					  &data->mdbgc.buf3,
317 					  &data->mdbgc.buf3_p_addr,
318 					  &data->mdbgc.buf3_v_addr,
319 					  db_frag.buf3,
320 					  2,
321 					  data->mdbgc.count);
322 	if (err)
323 		return err;
324 
325 	/* Copy fragment to DMA coherent memory */
326 	memcpy(data->mdbgc.frag_v_addr, &db_frag, sizeof(db_frag));
327 	return 0;
328 }
329 
330 /* This function initializes the memory for DBGC buffers and formats the
331  * DBGC fragment which consists header info and DBGC buffer's LSB, MSB and
332  * size as the payload
333  */
334 static int btintel_pcie_setup_dbgc(struct btintel_pcie_data *data)
335 {
336 	struct btintel_pcie_dbgc_ctxt db_frag;
337 	u32 frag_size = sizeof(db_frag);
338 	int err;
339 
340 	data->dbgc.count = BTINTEL_PCIE_DBGC_BUFFER_COUNT;
341 
342 	/* Allocate fragment context structure */
343 	data->dbgc.frag_v_addr = dmam_alloc_coherent(&data->pdev->dev,
344 						     frag_size,
345 						     &data->dbgc.frag_p_addr,
346 						     GFP_KERNEL | __GFP_NOWARN);
347 	if (!data->dbgc.frag_v_addr) {
348 		BT_ERR("Failed to allocate dbgc context");
349 		return -ENOMEM;
350 	}
351 
352 	data->dbgc.frag_size = sizeof(struct btintel_pcie_dbgc_ctxt);
353 
354 	/* Initialize fragment header */
355 	memset(&db_frag, 0, sizeof(db_frag));
356 	db_frag.magic_num = BTINTEL_PCIE_MAGIC_NUM;
357 	db_frag.ver = BTINTEL_PCIE_DBGC_FRAG_VERSION;
358 	db_frag.total_size = BTINTEL_PCIE_DBGC_FRAG_PAYLOAD_SIZE;
359 	db_frag.num_buf = BTINTEL_PCIE_DBGC_FRAG_BUFFER_COUNT;
360 
361 	/* Allocate DBGC buffers */
362 	err = btintel_pcie_alloc_dbgc_buf(data,
363 					  &data->dbgc.bufs,
364 					  &data->dbgc.buf_p_addr,
365 					  &data->dbgc.buf_v_addr,
366 					  db_frag.bufs,
367 					  0,
368 					  data->dbgc.count);
369 	if (err)
370 		return err;
371 
372 	/* Copy fragment to DMA coherent memory */
373 	memcpy(data->dbgc.frag_v_addr, &db_frag, sizeof(db_frag));
374 	return 0;
375 }
376 
377 static inline void ipc_print_ia_ring(struct hci_dev *hdev, struct ia *ia,
378 				     u16 queue_num)
379 {
380 	bt_dev_dbg(hdev, "IA: %s: tr-h:%02u  tr-t:%02u  cr-h:%02u  cr-t:%02u",
381 		   queue_num == BTINTEL_PCIE_TXQ_NUM ? "TXQ" : "RXQ",
382 		   ia->tr_hia[queue_num], ia->tr_tia[queue_num],
383 		   ia->cr_hia[queue_num], ia->cr_tia[queue_num]);
384 }
385 
386 static inline void ipc_print_urbd1(struct hci_dev *hdev, struct urbd1 *urbd1,
387 				   u16 index)
388 {
389 	bt_dev_dbg(hdev, "RXQ:urbd1(%u) frbd_tag:%u status: 0x%x fixed:0x%x",
390 		   index, urbd1->frbd_tag, urbd1->status, urbd1->fixed);
391 }
392 
393 static struct btintel_pcie_data *btintel_pcie_get_data(struct msix_entry *entry)
394 {
395 	u8 queue = entry->entry;
396 	struct msix_entry *entries = entry - queue;
397 
398 	return container_of(entries, struct btintel_pcie_data, msix_entries[0]);
399 }
400 
401 /* Set the doorbell for TXQ to notify the device that @index (actually index-1)
402  * of the TFD is updated and ready to transmit.
403  */
404 static void btintel_pcie_set_tx_db(struct btintel_pcie_data *data, u16 index)
405 {
406 	u32 val;
407 
408 	val = index;
409 	val |= (BTINTEL_PCIE_TX_DB_VEC << 16);
410 
411 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_HBUS_TARG_WRPTR, val);
412 }
413 
414 /* Copy the data to next(@tfd_index) data buffer and update the TFD(transfer
415  * descriptor) with the data length and the DMA address of the data buffer.
416  */
417 static void btintel_pcie_prepare_tx(struct txq *txq, u16 tfd_index,
418 				    struct sk_buff *skb)
419 {
420 	struct data_buf *buf;
421 	struct tfd *tfd;
422 
423 	tfd = &txq->tfds[tfd_index];
424 	memset(tfd, 0, sizeof(*tfd));
425 
426 	buf = &txq->bufs[tfd_index];
427 
428 	tfd->size = skb->len;
429 	tfd->addr = buf->data_p_addr;
430 
431 	/* Copy the outgoing data to DMA buffer */
432 	memcpy(buf->data, skb->data, tfd->size);
433 }
434 
435 static inline void btintel_pcie_dump_debug_registers(struct hci_dev *hdev)
436 {
437 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
438 	u16 cr_hia, cr_tia;
439 	u32 reg, mbox_reg;
440 	struct sk_buff *skb;
441 	u8 buf[80];
442 
443 	skb = alloc_skb(1024, GFP_ATOMIC);
444 	if (!skb)
445 		return;
446 
447 	strscpy(buf, "---- Dump of debug registers ---");
448 	bt_dev_dbg(hdev, "%s", buf);
449 	skb_put_data(skb, buf, strlen(buf));
450 
451 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
452 	snprintf(buf, sizeof(buf), "boot stage: 0x%8.8x", reg);
453 	bt_dev_dbg(hdev, "%s", buf);
454 	skb_put_data(skb, buf, strlen(buf));
455 	data->boot_stage_cache = reg;
456 
457 	if (reg & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_WARNING)
458 		bt_dev_warn(hdev, "Controller device warning (boot_stage: 0x%8.8x)", reg);
459 
460 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_STATUS_REG);
461 	snprintf(buf, sizeof(buf), "ipc status: 0x%8.8x", reg);
462 	skb_put_data(skb, buf, strlen(buf));
463 	bt_dev_dbg(hdev, "%s", buf);
464 
465 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_CONTROL_REG);
466 	snprintf(buf, sizeof(buf), "ipc control: 0x%8.8x", reg);
467 	skb_put_data(skb, buf, strlen(buf));
468 	bt_dev_dbg(hdev, "%s", buf);
469 
470 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IPC_SLEEP_CTL_REG);
471 	snprintf(buf, sizeof(buf), "ipc sleep control: 0x%8.8x", reg);
472 	skb_put_data(skb, buf, strlen(buf));
473 	bt_dev_dbg(hdev, "%s", buf);
474 
475 	/*Read the Mail box status and registers*/
476 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_STATUS_REG);
477 	snprintf(buf, sizeof(buf), "mbox status: 0x%8.8x", reg);
478 	skb_put_data(skb, buf, strlen(buf));
479 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX1) {
480 		mbox_reg = btintel_pcie_rd_reg32(data,
481 						 BTINTEL_PCIE_CSR_MBOX_1_REG);
482 		snprintf(buf, sizeof(buf), "mbox_1: 0x%8.8x", mbox_reg);
483 		skb_put_data(skb, buf, strlen(buf));
484 		bt_dev_dbg(hdev, "%s", buf);
485 	}
486 
487 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX2) {
488 		mbox_reg = btintel_pcie_rd_reg32(data,
489 						 BTINTEL_PCIE_CSR_MBOX_2_REG);
490 		snprintf(buf, sizeof(buf), "mbox_2: 0x%8.8x", mbox_reg);
491 		skb_put_data(skb, buf, strlen(buf));
492 		bt_dev_dbg(hdev, "%s", buf);
493 	}
494 
495 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX3) {
496 		mbox_reg = btintel_pcie_rd_reg32(data,
497 						 BTINTEL_PCIE_CSR_MBOX_3_REG);
498 		snprintf(buf, sizeof(buf), "mbox_3: 0x%8.8x", mbox_reg);
499 		skb_put_data(skb, buf, strlen(buf));
500 		bt_dev_dbg(hdev, "%s", buf);
501 	}
502 
503 	if (reg & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX4) {
504 		mbox_reg = btintel_pcie_rd_reg32(data,
505 						 BTINTEL_PCIE_CSR_MBOX_4_REG);
506 		snprintf(buf, sizeof(buf), "mbox_4: 0x%8.8x", mbox_reg);
507 		skb_put_data(skb, buf, strlen(buf));
508 		bt_dev_dbg(hdev, "%s", buf);
509 	}
510 
511 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM];
512 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
513 	snprintf(buf, sizeof(buf), "rxq: cr_tia: %u cr_hia: %u", cr_tia, cr_hia);
514 	skb_put_data(skb, buf, strlen(buf));
515 	bt_dev_dbg(hdev, "%s", buf);
516 
517 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
518 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM];
519 	snprintf(buf, sizeof(buf), "txq: cr_tia: %u cr_hia: %u", cr_tia, cr_hia);
520 	skb_put_data(skb, buf, strlen(buf));
521 	bt_dev_dbg(hdev, "%s", buf);
522 	strscpy(buf, "--------------------------------");
523 	bt_dev_dbg(hdev, "%s", buf);
524 
525 	hci_recv_diag(hdev, skb);
526 }
527 
528 static int btintel_pcie_send_sync(struct btintel_pcie_data *data,
529 				  struct sk_buff *skb, u32 pkt_type, u16 opcode)
530 {
531 	int ret;
532 	u16 tfd_index;
533 	u32 old_ctxt;
534 	bool wait_on_alive = false;
535 	struct hci_dev *hdev = data->hdev;
536 
537 	struct txq *txq = &data->txq;
538 
539 	tfd_index = data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM];
540 
541 	if (tfd_index >= txq->count)
542 		return -ERANGE;
543 
544 	if (skb->len > BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN) {
545 		bt_dev_err(hdev, "TX skb too large (%u > %u)", skb->len,
546 			   BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN);
547 		return -EMSGSIZE;
548 	}
549 
550 	/* Firmware raises alive interrupt on HCI_OP_RESET or
551 	 * BTINTEL_HCI_OP_RESET
552 	 */
553 	wait_on_alive = (pkt_type == BTINTEL_PCIE_HCI_CMD_PKT &&
554 		(opcode == BTINTEL_HCI_OP_RESET || opcode == HCI_OP_RESET));
555 
556 	if (wait_on_alive) {
557 		data->gp0_received = false;
558 		old_ctxt = data->alive_intr_ctxt;
559 		data->alive_intr_ctxt =
560 			(opcode == BTINTEL_HCI_OP_RESET ? BTINTEL_PCIE_INTEL_HCI_RESET1 :
561 				BTINTEL_PCIE_HCI_RESET);
562 		bt_dev_dbg(data->hdev, "sending cmd: 0x%4.4x alive context changed: %s  ->  %s",
563 			   opcode, btintel_pcie_alivectxt_state2str(old_ctxt),
564 			   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
565 	}
566 
567 	memcpy(skb_push(skb, BTINTEL_PCIE_HCI_TYPE_LEN), &pkt_type,
568 	       BTINTEL_PCIE_HCI_TYPE_LEN);
569 
570 	/* Prepare for TX. It updates the TFD with the length of data and
571 	 * address of the DMA buffer, and copy the data to the DMA buffer
572 	 */
573 	btintel_pcie_prepare_tx(txq, tfd_index, skb);
574 
575 	tfd_index = (tfd_index + 1) % txq->count;
576 	data->ia.tr_hia[BTINTEL_PCIE_TXQ_NUM] = tfd_index;
577 
578 	/* Arm wait event condition */
579 	data->tx_wait_done = false;
580 
581 	/* Set the doorbell to notify the device */
582 	btintel_pcie_set_tx_db(data, tfd_index);
583 
584 	/* Wait for the complete interrupt - URBD0 */
585 	ret = wait_event_timeout(data->tx_wait_q, data->tx_wait_done,
586 				 msecs_to_jiffies(BTINTEL_PCIE_TX_WAIT_TIMEOUT_MS));
587 	if (!ret) {
588 		bt_dev_err(data->hdev, "Timeout (%u ms) on tx completion",
589 			   BTINTEL_PCIE_TX_WAIT_TIMEOUT_MS);
590 		btintel_pcie_dump_debug_registers(data->hdev);
591 		return -ETIME;
592 	}
593 
594 	if (wait_on_alive) {
595 		ret = wait_event_timeout(data->gp0_wait_q,
596 					 data->gp0_received,
597 					 msecs_to_jiffies(BTINTEL_DEFAULT_INTR_TIMEOUT_MS));
598 		if (!ret) {
599 			hdev->stat.err_tx++;
600 			bt_dev_err(hdev, "Timeout (%u ms)  on alive interrupt, alive context: %s",
601 				   BTINTEL_DEFAULT_INTR_TIMEOUT_MS,
602 				   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
603 			return  -ETIME;
604 		}
605 	}
606 	return 0;
607 }
608 
609 /* Set the doorbell for RXQ to notify the device that @index (actually index-1)
610  * is available to receive the data
611  */
612 static void btintel_pcie_set_rx_db(struct btintel_pcie_data *data, u16 index)
613 {
614 	u32 val;
615 
616 	val = index;
617 	val |= (BTINTEL_PCIE_RX_DB_VEC << 16);
618 
619 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_HBUS_TARG_WRPTR, val);
620 }
621 
622 /* Update the FRBD (free buffer descriptor) with the @frbd_index and the
623  * DMA address of the free buffer.
624  */
625 static void btintel_pcie_prepare_rx(struct rxq *rxq, u16 frbd_index)
626 {
627 	struct data_buf *buf;
628 	struct frbd *frbd;
629 
630 	/* Get the buffer of the FRBD for DMA */
631 	buf = &rxq->bufs[frbd_index];
632 
633 	frbd = &rxq->frbds[frbd_index];
634 	memset(frbd, 0, sizeof(*frbd));
635 
636 	/* Update FRBD */
637 	frbd->tag = frbd_index;
638 	frbd->addr = buf->data_p_addr;
639 }
640 
641 static int btintel_pcie_submit_rx(struct btintel_pcie_data *data)
642 {
643 	u16 frbd_index;
644 	struct rxq *rxq = &data->rxq;
645 
646 	frbd_index = data->ia.tr_hia[BTINTEL_PCIE_RXQ_NUM];
647 
648 	if (frbd_index >= rxq->count)
649 		return -ERANGE;
650 
651 	/* Prepare for RX submit. It updates the FRBD with the address of DMA
652 	 * buffer
653 	 */
654 	btintel_pcie_prepare_rx(rxq, frbd_index);
655 
656 	frbd_index = (frbd_index + 1) % rxq->count;
657 	data->ia.tr_hia[BTINTEL_PCIE_RXQ_NUM] = frbd_index;
658 	ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_RXQ_NUM);
659 
660 	/* Set the doorbell to notify the device */
661 	btintel_pcie_set_rx_db(data, frbd_index);
662 
663 	return 0;
664 }
665 
666 static int btintel_pcie_start_rx(struct btintel_pcie_data *data)
667 {
668 	int i, ret;
669 	struct rxq *rxq = &data->rxq;
670 
671 	/* Post (BTINTEL_PCIE_RX_DESCS_COUNT - 3) buffers to overcome the
672 	 * hardware issues leading to race condition at the firmware.
673 	 */
674 
675 	for (i = 0; i < rxq->count - 3; i++) {
676 		ret = btintel_pcie_submit_rx(data);
677 		if (ret)
678 			return ret;
679 	}
680 
681 	return 0;
682 }
683 
684 static void btintel_pcie_reset_ia(struct btintel_pcie_data *data)
685 {
686 	memset(data->ia.tr_hia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
687 	memset(data->ia.tr_tia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
688 	memset(data->ia.cr_hia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
689 	memset(data->ia.cr_tia, 0, sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES);
690 }
691 
692 static int btintel_pcie_reset_bt(struct btintel_pcie_data *data)
693 {
694 	u32 reg;
695 	int retry = 3;
696 
697 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
698 
699 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
700 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT |
701 			BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
702 	reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON;
703 
704 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
705 
706 	do {
707 		reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
708 		if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_STS)
709 			break;
710 		usleep_range(10000, 12000);
711 
712 	} while (--retry > 0);
713 	usleep_range(10000, 12000);
714 
715 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
716 
717 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
718 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT |
719 			BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
720 	reg |= BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET;
721 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
722 	usleep_range(10000, 12000);
723 
724 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
725 	bt_dev_dbg(data->hdev, "csr register after reset: 0x%8.8x", reg);
726 
727 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
728 
729 	/* If shared hardware reset is success then boot stage register shall be
730 	 * set to 0
731 	 */
732 	return reg == 0 ? 0 : -ENODEV;
733 }
734 
735 static int btintel_pcie_get_mac_access(struct btintel_pcie_data *data)
736 {
737 	u32 reg, val;
738 	int retry = 15;
739 	const u32 req = BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT |
740 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ;
741 
742 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
743 
744 	val = reg | req;
745 	if (val != reg)
746 		btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, val);
747 
748 	do {
749 		reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
750 		if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_STS)
751 			return 0;
752 		/* Need delay here for Target Access harwdware to settle down*/
753 		usleep_range(1000, 1200);
754 
755 	} while (--retry > 0);
756 
757 	return -ETIME;
758 }
759 
760 static void btintel_pcie_release_mac_access(struct btintel_pcie_data *data)
761 {
762 	u32 reg;
763 
764 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
765 
766 	if (reg & BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ) {
767 		reg &= ~BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_ACCESS_REQ;
768 		btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
769 	}
770 }
771 
772 static struct scatterlist *btintel_pcie_alloc_sgtable(ssize_t size)
773 {
774 	int nents;
775 	struct page *page;
776 	struct scatterlist *sg, *result;
777 
778 	if (size <= 0)
779 		return NULL;
780 
781 	nents = DIV_ROUND_UP(size, PAGE_SIZE);
782 	result = kzalloc_objs(*result, nents);
783 	if (!result)
784 		return NULL;
785 
786 	sg_init_table(result, nents);
787 	sg = result;
788 
789 	while (size > 0) {
790 		ssize_t bytes = min_t(ssize_t, size, PAGE_SIZE);
791 
792 		page = alloc_page(GFP_KERNEL | __GFP_ZERO);
793 		if (!page)
794 			goto err_free;
795 
796 		sg_set_page(sg, page, bytes, 0);
797 		sg = sg_next(sg);
798 		size -= bytes;
799 	}
800 	return result;
801 
802 err_free:
803 	for (sg = result; sg; sg = sg_next(sg)) {
804 		page = sg_page(sg);
805 		if (page)
806 			__free_page(page);
807 	}
808 	kfree(result);
809 	return NULL;
810 }
811 
812 static struct btintel_pcie_dump_entry *
813 btintel_pcie_dump_entry_alloc(u32 data_size)
814 {
815 	struct btintel_pcie_dump_entry *entry;
816 
817 	entry = vzalloc(sizeof(*entry) + data_size);
818 	if (!entry)
819 		return NULL;
820 
821 	entry->size = data_size;
822 	INIT_LIST_HEAD(&entry->list);
823 	return entry;
824 }
825 
826 static void btintel_pcie_dump_list_free(struct list_head *list)
827 {
828 	struct btintel_pcie_dump_entry *entry, *tmp;
829 
830 	list_for_each_entry_safe(entry, tmp, list, list) {
831 		list_del(&entry->list);
832 		vfree(entry);
833 	}
834 }
835 
836 static u32 btintel_pcie_dump_list_total_size(struct list_head *list)
837 {
838 	struct btintel_pcie_dump_entry *entry;
839 	u32 total = 0;
840 
841 	list_for_each_entry(entry, list, list)
842 		total += entry->size;
843 
844 	return total;
845 }
846 
847 static int btintel_pcie_dump_dram(struct list_head *list,
848 				  u8 count, struct data_buf *bufs,
849 				  u32 write_ptr, u32 wrap_ctr, u32 cur_frag,
850 				  u32 region_id, const char *name)
851 {
852 	struct btintel_pcie_dump_entry *entry;
853 	struct btintel_pcie_ini_dump_data *dump_data;
854 	struct btintel_pcie_ini_monitor_dump *mon_dump;
855 	struct btintel_pcie_dump_range *range;
856 	u32 mon_hdr_size, ranges_size, payload_size, total_size;
857 	int i;
858 
859 	mon_hdr_size = sizeof(*mon_dump);
860 	ranges_size = count * (sizeof(*range) + BTINTEL_PCIE_DBGC_BUFFER_SIZE);
861 	payload_size = mon_hdr_size + ranges_size;
862 	total_size = sizeof(*dump_data) + payload_size;
863 
864 	entry = btintel_pcie_dump_entry_alloc(total_size);
865 	if (!entry)
866 		return -ENOMEM;
867 
868 	dump_data = (void *)entry->data;
869 	dump_data->type = BTINTEL_PCIE_INI_REGION_DRAM_BUFFER;
870 	dump_data->sub_type = 0;
871 	dump_data->sub_type_ver = 0;
872 	dump_data->reserved = 0;
873 	dump_data->len = cpu_to_le32(payload_size);
874 
875 	mon_dump = (void *)dump_data->data;
876 	mon_dump->header.version = cpu_to_le32(BTINTEL_PCIE_INI_DUMP_VER);
877 	mon_dump->header.region_id = cpu_to_le32(region_id);
878 	mon_dump->header.num_of_ranges = cpu_to_le32(count);
879 	mon_dump->header.name_len = cpu_to_le32(BTINTEL_PCIE_INI_MAX_NAME);
880 	memset(mon_dump->header.name, 0, BTINTEL_PCIE_INI_MAX_NAME);
881 	strscpy(mon_dump->header.name, name, BTINTEL_PCIE_INI_MAX_NAME);
882 
883 	mon_dump->write_ptr = cpu_to_le32(write_ptr);
884 	mon_dump->cycle_cnt = cpu_to_le32(wrap_ctr);
885 	mon_dump->cur_frag = cpu_to_le32(cur_frag);
886 
887 	range = (void *)mon_dump->data;
888 	for (i = 0; i < count; i++) {
889 		range->range_data_size =
890 			cpu_to_le32(BTINTEL_PCIE_DBGC_BUFFER_SIZE);
891 		range->dram_base_addr = cpu_to_le64(bufs[i].data_p_addr);
892 		memcpy(range->data, bufs[i].data,
893 		       BTINTEL_PCIE_DBGC_BUFFER_SIZE);
894 		range = (void *)range->data + BTINTEL_PCIE_DBGC_BUFFER_SIZE;
895 	}
896 
897 	list_add_tail(&entry->list, list);
898 	return 0;
899 }
900 
901 static int
902 btintel_pcie_dump_dram_monitor(struct btintel_pcie_data *data,
903 			       struct list_head *list, u8 count,
904 			       struct data_buf *bufs, u32 status_reg,
905 			       u32 wrap_reg, u8 allocation_id, u32 region_id,
906 			       const char *name)
907 {
908 	u32 allocation_offset, write_ptr, wrap_ctr, wr_ptr_status;
909 	u8 cur_frag;
910 
911 	allocation_offset = allocation_id *
912 			    BTINTEL_PCIE_DBGC_ALLOCATION_OFFSET;
913 	wr_ptr_status = btintel_pcie_rd_dev_mem(data, status_reg +
914 						allocation_offset);
915 	wrap_ctr = btintel_pcie_rd_dev_mem(data, wrap_reg +
916 					  allocation_offset);
917 
918 	write_ptr = wr_ptr_status & BTINTEL_PCIE_DBG_OFFSET_BIT_MASK;
919 	write_ptr >>= 2;
920 	cur_frag = BTINTEL_PCIE_DBGC_DBG_BUF_IDX(wr_ptr_status);
921 	if (cur_frag >= count) {
922 		bt_dev_warn(data->hdev,
923 			    "Invalid DRAM monitor fragment %u for allocation %u",
924 			    cur_frag, allocation_id);
925 		return -EINVAL;
926 	}
927 
928 	bt_dev_dbg(data->hdev,
929 		   "allocation=%u wr_ptr_status=0x%08x write_ptr=0x%06x cur_frag=%u wrap_ctr=0x%08x",
930 		   allocation_id, wr_ptr_status, write_ptr, cur_frag, wrap_ctr);
931 
932 	return btintel_pcie_dump_dram(list, count, bufs, write_ptr, wrap_ctr,
933 				      cur_frag, region_id, name);
934 }
935 
936 static int btintel_pcie_dump_target_region(struct btintel_pcie_data *data,
937 					   struct list_head *list,
938 					   u32 region_id, const char *name,
939 					   u32 addr_start, u32 size)
940 {
941 	struct btintel_pcie_dump_entry *entry;
942 	struct btintel_pcie_ini_dump_data *dump_data;
943 	struct btintel_pcie_ini_dump_header *hdr;
944 	struct btintel_pcie_dump_range *range;
945 	u32 payload_size, total_size, target_mem_offset, tempdata;
946 	u8 *dest;
947 	int i;
948 
949 	if (!size) {
950 		bt_dev_warn(data->hdev, "Skipping empty dump region: %s", name);
951 		return 1;
952 	}
953 
954 	if (!addr_start) {
955 		bt_dev_warn(data->hdev,
956 			    "Skipping dump region with zero address: %s",
957 			    name);
958 		return 1;
959 	}
960 
961 	if (addr_start > U32_MAX - size) {
962 		bt_dev_warn(data->hdev,
963 			    "Skipping dump region %s: addr_start 0x%08x + size %u would overflow",
964 			    name, addr_start, size);
965 		return 1;
966 	}
967 
968 	/* Align to 4 bytes - target access reads 32-bit words */
969 	size = round_down(size, sizeof(u32));
970 	if (!size) {
971 		bt_dev_warn(data->hdev,
972 			    "Skipping dump region %s: size is smaller than 4-byte access",
973 			    name);
974 		return 1;
975 	}
976 
977 	bt_dev_dbg(data->hdev,
978 		   "Target access: region=%s start=0x%08x size=%u",
979 		   name, addr_start, size);
980 
981 	payload_size = sizeof(*hdr) + sizeof(*range) + size;
982 	total_size = sizeof(*dump_data) + payload_size;
983 	entry = btintel_pcie_dump_entry_alloc(total_size);
984 	if (!entry)
985 		return -ENOMEM;
986 
987 	dump_data = (void *)entry->data;
988 	dump_data->type = BTINTEL_PCIE_INI_REGION_DEVICE_MEMORY;
989 	dump_data->sub_type = 0;
990 	dump_data->sub_type_ver = 0;
991 	dump_data->reserved = 0;
992 	dump_data->len = cpu_to_le32(payload_size);
993 
994 	hdr = (void *)dump_data->data;
995 	hdr->version = cpu_to_le32(BTINTEL_PCIE_INI_DUMP_VER);
996 	hdr->region_id = cpu_to_le32(region_id);
997 	hdr->num_of_ranges = cpu_to_le32(1);
998 	hdr->name_len = cpu_to_le32(BTINTEL_PCIE_INI_MAX_NAME);
999 	memset(hdr->name, 0, BTINTEL_PCIE_INI_MAX_NAME);
1000 	strscpy(hdr->name, name, BTINTEL_PCIE_INI_MAX_NAME);
1001 
1002 	range = (void *)(hdr + 1);
1003 	range->range_data_size = cpu_to_le32(size);
1004 	range->internal_base_addr = cpu_to_le32(addr_start);
1005 
1006 	dest = (u8 *)range->data;
1007 	target_mem_offset = size / sizeof(u32);
1008 	for (i = 0; i < target_mem_offset; i++) {
1009 		u32 offset = BTINTEL_PCIE_TARGET_ACCESS_FRAG_OFFSET * i;
1010 
1011 		tempdata = btintel_pcie_rd_dev_mem(data,
1012 						   addr_start + offset);
1013 		memcpy(dest, &tempdata, sizeof(tempdata));
1014 		dest += sizeof(tempdata);
1015 	}
1016 
1017 	list_add_tail(&entry->list, list);
1018 	return 0;
1019 }
1020 
1021 static int btintel_pcie_dump_smem_monitor_region(struct btintel_pcie_data *data,
1022 						 struct list_head *list,
1023 						 u32 region_id,
1024 						 const char *name,
1025 						 u32 addr_start, u32 size)
1026 {
1027 	struct btintel_pcie_dump_entry *entry;
1028 	struct btintel_pcie_ini_dump_data *dump_data;
1029 	struct btintel_pcie_ini_monitor_dump *mon;
1030 	struct btintel_pcie_dump_range *range;
1031 	u32 payload_size, total_size, target_mem_offset, tempdata;
1032 	u8 *dest;
1033 	int i;
1034 
1035 	if (!size || !addr_start) {
1036 		bt_dev_err(data->hdev, "Skipping smem dump: size = %u addr = %8.8x",
1037 			   size, addr_start);
1038 		return -EINVAL;
1039 	}
1040 
1041 	payload_size = sizeof(*mon) + sizeof(*range) + size;
1042 	total_size = sizeof(*dump_data) + payload_size;
1043 	entry = btintel_pcie_dump_entry_alloc(total_size);
1044 	if (!entry)
1045 		return -ENOMEM;
1046 
1047 	dump_data = (void *)entry->data;
1048 	dump_data->type = BTINTEL_PCIE_INI_REGION_INTERNAL_BUFFER;
1049 	dump_data->sub_type = 0;
1050 	dump_data->sub_type_ver = 0;
1051 	dump_data->reserved = 0;
1052 	dump_data->len = cpu_to_le32(payload_size);
1053 
1054 	mon = (void *)dump_data->data;
1055 	mon->header.version = cpu_to_le32(BTINTEL_PCIE_INI_DUMP_VER);
1056 	mon->header.region_id = cpu_to_le32(region_id);
1057 	mon->header.num_of_ranges = cpu_to_le32(1);
1058 	mon->header.name_len = cpu_to_le32(BTINTEL_PCIE_INI_MAX_NAME);
1059 	memset(mon->header.name, 0, BTINTEL_PCIE_INI_MAX_NAME);
1060 	strscpy(mon->header.name, name, BTINTEL_PCIE_INI_MAX_NAME);
1061 
1062 	mon->write_ptr = cpu_to_le32(0);
1063 	mon->cycle_cnt = cpu_to_le32(0);
1064 	mon->cur_frag = cpu_to_le32(0);
1065 
1066 	range = (void *)mon->data;
1067 	range->range_data_size = cpu_to_le32(size);
1068 	range->internal_base_addr = cpu_to_le32(addr_start);
1069 
1070 	dest = (u8 *)range->data;
1071 	target_mem_offset = size / sizeof(u32);
1072 	for (i = 0; i < target_mem_offset; i++) {
1073 		u32 offset = BTINTEL_PCIE_TARGET_ACCESS_FRAG_OFFSET * i;
1074 
1075 		tempdata = btintel_pcie_rd_dev_mem(data,
1076 						   addr_start + offset);
1077 		memcpy(dest, &tempdata, sizeof(tempdata));
1078 		dest += sizeof(tempdata);
1079 	}
1080 
1081 	list_add_tail(&entry->list, list);
1082 	return 0;
1083 }
1084 
1085 static int btintel_pcie_dump_info(struct btintel_pcie_data *data,
1086 				  struct list_head *list,
1087 				  u64 regions_mask)
1088 {
1089 	struct btintel_pcie_dump_entry *entry;
1090 	struct btintel_pcie_error_dump_data *tlv;
1091 	struct btintel_pcie_ini_dump_info *dump;
1092 	u32 size = sizeof(*tlv) + sizeof(*dump);
1093 	char build_tag[64];
1094 
1095 	entry = btintel_pcie_dump_entry_alloc(size);
1096 	if (!entry)
1097 		return -ENOMEM;
1098 
1099 	tlv = (void *)entry->data;
1100 	tlv->type = cpu_to_le32(BTINTEL_PCIE_INI_DUMP_INFO_TYPE);
1101 	tlv->len = cpu_to_le32(sizeof(*dump));
1102 
1103 	dump = (void *)tlv->data;
1104 	memset(dump, 0, sizeof(*dump));
1105 
1106 	dump->version = cpu_to_le32(BTINTEL_PCIE_INI_DUMP_VER);
1107 	dump->trigger_reason = cpu_to_le32(data->dmp_hdr.trigger_reason);
1108 
1109 	if (data->dmp_hdr.trigger_reason ==
1110 	    BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT)
1111 		dump->time_point =
1112 			cpu_to_le32(BTINTEL_PCIE_TIME_POINT_FW_ASSERT);
1113 	else if (data->dmp_hdr.trigger_reason ==
1114 		 BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER)
1115 		dump->time_point =
1116 			cpu_to_le32(BTINTEL_PCIE_TIME_POINT_USER_TRIGGER);
1117 
1118 	dump->hw_type = cpu_to_le32(INTEL_CNVX_TOP_TYPE(data->dmp_hdr.cnvi_top));
1119 	dump->hw_step = cpu_to_le32(INTEL_CNVX_TOP_STEP(data->dmp_hdr.cnvi_top));
1120 	bt_dev_dbg(data->hdev, "hw_type=0x%x hw_step=0x%x (cnvi_top=0x%x)",
1121 		   le32_to_cpu(dump->hw_type), le32_to_cpu(dump->hw_step),
1122 		   data->dmp_hdr.cnvi_top);
1123 
1124 	dump->ver_type = cpu_to_le32(data->dmp_hdr.cnvi_bt);
1125 	dump->ver_subtype = cpu_to_le32(data->dmp_hdr.fw_sha);
1126 	dump->rf_id_type = cpu_to_le32(INTEL_CNVX_TOP_TYPE(data->dmp_hdr.cnvr_top));
1127 	dump->rf_id_dash = cpu_to_le32(INTEL_CNVX_TOP_DASH(data->dmp_hdr.cnvr_top));
1128 	dump->rf_id_step = cpu_to_le32(INTEL_CNVX_TOP_STEP(data->dmp_hdr.cnvr_top));
1129 	dump->rf_id_flavor = cpu_to_le32(INTEL_CNVX_TOP_FLAVOR(data->dmp_hdr.cnvr_top));
1130 	bt_dev_dbg(data->hdev,
1131 		   "rf_id_type=0x%x rf_id_dash=0x%x rf_id_step=0x%x rf_id_flavor=0x%x (cnvr_top=0x%x)",
1132 		   le32_to_cpu(dump->rf_id_type),
1133 		   le32_to_cpu(dump->rf_id_dash),
1134 		   le32_to_cpu(dump->rf_id_step),
1135 		   le32_to_cpu(dump->rf_id_flavor),
1136 		   data->dmp_hdr.cnvr_top);
1137 	dump->lmac_major = cpu_to_le32(0);
1138 	dump->lmac_minor = cpu_to_le32(0);
1139 	dump->umac_major = cpu_to_le32(0);
1140 	dump->umac_minor = cpu_to_le32(0);
1141 	dump->fw_mon_mode = cpu_to_le32(BTINTEL_PCIE_FW_MON_MODE_DRAM);
1142 
1143 	dump->regions_mask = cpu_to_le64(regions_mask);
1144 
1145 	bt_dev_dbg(data->hdev, "ExpectedRegionIDs regions_mask=0x%016llx",
1146 		   le64_to_cpu(dump->regions_mask));
1147 
1148 	snprintf(build_tag, sizeof(build_tag), "%08X", data->dmp_hdr.fw_sha);
1149 
1150 	dump->build_tag_len = cpu_to_le32(strlen(build_tag));
1151 	memcpy(dump->build_tag, build_tag, min(strlen(build_tag),
1152 					       sizeof(dump->build_tag)));
1153 
1154 	dump->num_of_cfg_names = cpu_to_le32(0);
1155 
1156 	bt_dev_dbg(data->hdev,
1157 		   "HwType=0x%08x HwStep=0x%08x RfIdType=0x%08x RfIdDash=0x%08x RfIdStep=0x%08x RfIdFlavor=0x%08x",
1158 		   le32_to_cpu(dump->hw_type), le32_to_cpu(dump->hw_step),
1159 		   le32_to_cpu(dump->rf_id_type),
1160 		   le32_to_cpu(dump->rf_id_dash),
1161 		   le32_to_cpu(dump->rf_id_step),
1162 		   le32_to_cpu(dump->rf_id_flavor));
1163 	bt_dev_dbg(data->hdev, "VerType=0x%08x VerSubType=0x%08x",
1164 		   le32_to_cpu(dump->ver_type), le32_to_cpu(dump->ver_subtype));
1165 	bt_dev_dbg(data->hdev,
1166 		   "LmacMajor=0x%08x LmacMinor=0x%08x UmacMajor=0x%08x UmacMinor=0x%08x",
1167 		   le32_to_cpu(dump->lmac_major), le32_to_cpu(dump->lmac_minor),
1168 		   le32_to_cpu(dump->umac_major),
1169 		   le32_to_cpu(dump->umac_minor));
1170 	bt_dev_dbg(data->hdev, "TriggerReason=0x%04x MonMode=%u BuildTag=%.64s",
1171 		   le32_to_cpu(dump->trigger_reason),
1172 		   le32_to_cpu(dump->fw_mon_mode),
1173 		   dump->build_tag);
1174 
1175 	list_add(&entry->list, list);
1176 
1177 	return 0;
1178 }
1179 
1180 static bool btintel_pcie_is_mdbgc_supported(struct btintel_pcie_data *data)
1181 {
1182 	return data->pdev->device == BTINTEL_PCIE_DEVICE_ID_NVL_S_SCP2 ||
1183 		data->pdev->device == BTINTEL_PCIE_DEVICE_ID_NVL_Hx_SCP2 ||
1184 		data->pdev->device == BTINTEL_PCIE_DEVICE_ID_PTL_FMP2;
1185 }
1186 
1187 static void btintel_pcie_dump_mem_range(struct btintel_pcie_data *data,
1188 					struct list_head *list, u32 region_id,
1189 					const char *name, u32 addr_start,
1190 					u32 region_size, u64 *regions_mask)
1191 {
1192 	if (!region_size)
1193 		return;
1194 
1195 	if (!btintel_pcie_dump_target_region(data, list, region_id, name,
1196 					     addr_start, region_size))
1197 		*regions_mask |= BIT_ULL(region_id);
1198 }
1199 
1200 static int btintel_pcie_read_debug_regions(struct btintel_pcie_data *data)
1201 {
1202 	struct btintel_pcie_dbgc *dbgc = NULL;
1203 	struct btintel_pcie_mdbgc *mdbgc = NULL;
1204 	struct btintel_pcie_dump_mem_info *dump_info = &data->dump_info;
1205 	struct hci_dev *hdev = data->hdev;
1206 	struct btintel_pcie_dump_entry *entry;
1207 	struct btintel_pcie_dump_file_hdr *file_hdr;
1208 	struct scatterlist *sg_dump_data;
1209 	u32 status_reg, wrap_reg;
1210 	u64 regions_mask = 0;
1211 	u8 hw_variant;
1212 	u32 file_len;
1213 	u8 count;
1214 	int ret;
1215 	LIST_HEAD(dump_list);
1216 
1217 	if (!IS_ENABLED(CONFIG_DEV_COREDUMP))
1218 		return -EOPNOTSUPP;
1219 
1220 	if (btintel_pcie_is_mdbgc_supported(data)) {
1221 		mdbgc = &data->mdbgc;
1222 		count = mdbgc->count;
1223 	} else {
1224 		dbgc = &data->dbgc;
1225 		count = dbgc->count;
1226 	}
1227 
1228 	hw_variant = INTEL_HW_VARIANT(data->cnvi);
1229 
1230 	if (hw_variant == BTINTEL_HWID_BZRI ||
1231 	    hw_variant == BTINTEL_HWID_BZRIW) {
1232 		status_reg = BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS;
1233 		wrap_reg = BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND;
1234 	} else if (hw_variant >= BTINTEL_HWID_SCP) {
1235 		status_reg = BTINTEL_PCIE_DBGC_CUR_DBGBUFF_STATUS_SCP;
1236 		wrap_reg = BTINTEL_PCIE_DBGC_DBGBUFF_WRAP_ARND_SCP;
1237 	} else {
1238 		bt_dev_err(hdev,
1239 			   "Unsupported Intel hardware variant (0x%2.2x)",
1240 			   hw_variant);
1241 		return -EINVAL;
1242 	}
1243 
1244 	if (btintel_pcie_is_mdbgc_supported(data)) {
1245 		ret = btintel_pcie_dump_dram_monitor(data, &dump_list, count,
1246 						     mdbgc->buf1, status_reg,
1247 						     wrap_reg,
1248 						     BTINTEL_PCIE_MDBGC_ALLOCATIONID_1,
1249 						     BTINTEL_PCIE_INI_ID_DRAM_MONITOR1,
1250 						     "monitor");
1251 		if (!ret)
1252 			regions_mask |=
1253 				BIT_ULL(BTINTEL_PCIE_INI_ID_DRAM_MONITOR1);
1254 		else
1255 			bt_dev_warn(hdev, "Failed to dump DRAM buf1: %d", ret);
1256 
1257 		ret = btintel_pcie_dump_dram_monitor(data, &dump_list, count,
1258 						     mdbgc->buf2, status_reg,
1259 						     wrap_reg,
1260 						     BTINTEL_PCIE_MDBGC_ALLOCATIONID_2,
1261 						     BTINTEL_PCIE_INI_ID_DRAM_MONITOR2,
1262 						     "monitor2");
1263 		if (!ret)
1264 			regions_mask |=
1265 				BIT_ULL(BTINTEL_PCIE_INI_ID_DRAM_MONITOR2);
1266 		else
1267 			bt_dev_warn(hdev, "Failed to dump DRAM buf2: %d", ret);
1268 
1269 		ret = btintel_pcie_dump_dram_monitor(data, &dump_list, count,
1270 						     mdbgc->buf3, status_reg,
1271 						     wrap_reg,
1272 						     BTINTEL_PCIE_MDBGC_ALLOCATIONID_3,
1273 						     BTINTEL_PCIE_INI_ID_DRAM_MONITOR3,
1274 						     "monitor3");
1275 		if (!ret)
1276 			regions_mask |=
1277 				BIT_ULL(BTINTEL_PCIE_INI_ID_DRAM_MONITOR3);
1278 		else
1279 			bt_dev_warn(hdev, "Failed to dump DRAM buf3: %d", ret);
1280 	} else {
1281 		ret = btintel_pcie_dump_dram_monitor(data, &dump_list, count,
1282 						     dbgc->bufs, status_reg,
1283 						     wrap_reg,
1284 						     BTINTEL_PCIE_MDBGC_ALLOCATIONID_1,
1285 						     BTINTEL_PCIE_INI_ID_DRAM_MONITOR1,
1286 						     "monitor");
1287 		if (!ret)
1288 			regions_mask |=
1289 				BIT_ULL(BTINTEL_PCIE_INI_ID_DRAM_MONITOR1);
1290 		else
1291 			bt_dev_warn(hdev,
1292 				    "Failed to dump DRAM region: %d", ret);
1293 	}
1294 
1295 	if (dump_info->smem_size &&
1296 	    !btintel_pcie_dump_smem_monitor_region(data, &dump_list,
1297 						   BTINTEL_PCIE_INI_ID_SMEM,
1298 						   "monitor_smem",
1299 						   dump_info->smem_addr_start,
1300 						   dump_info->smem_size))
1301 		regions_mask |= BIT_ULL(BTINTEL_PCIE_INI_ID_SMEM);
1302 
1303 	if (dump_info->exception_dump_addr && dump_info->exception_dump_len) {
1304 		ret = btintel_pcie_dump_target_region(data, &dump_list,
1305 						      BTINTEL_PCIE_INI_ID_EXCEPTION_EVT,
1306 						      "EXCEPTION_EVT_BUFFER",
1307 						      dump_info->exception_dump_addr,
1308 						      dump_info->exception_dump_len);
1309 		if (!ret)
1310 			regions_mask |= BIT_ULL(BTINTEL_PCIE_INI_ID_EXCEPTION_EVT);
1311 	}
1312 
1313 	btintel_pcie_dump_mem_range(data, &dump_list,
1314 				    BTINTEL_PCIE_INI_ID_DCCM, "DCCM",
1315 				    dump_info->dccm_addr_start,
1316 				    dump_info->dccm_size,
1317 				    &regions_mask);
1318 
1319 	btintel_pcie_dump_mem_range(data, &dump_list,
1320 				    BTINTEL_PCIE_INI_ID_SDS, "SDS",
1321 				    dump_info->sds_start_addr_start,
1322 				    dump_info->sds_start_size,
1323 				    &regions_mask);
1324 
1325 	btintel_pcie_dump_mem_range(data, &dump_list,
1326 				    BTINTEL_PCIE_INI_ID_SDS_IOSF, "SDS_IOSF",
1327 				    dump_info->sds_iosf_data_addr_start,
1328 				    dump_info->sds_iosf_data_size,
1329 				    &regions_mask);
1330 
1331 	btintel_pcie_dump_mem_range(data, &dump_list,
1332 				    BTINTEL_PCIE_INI_ID_ECL, "ECL_REGION",
1333 				    dump_info->ecl_addr_start,
1334 				    dump_info->ecl_size,
1335 				    &regions_mask);
1336 
1337 	ret = btintel_pcie_dump_info(data, &dump_list, regions_mask);
1338 	if (ret) {
1339 		btintel_pcie_dump_list_free(&dump_list);
1340 		return ret;
1341 	}
1342 
1343 	file_len = sizeof(*file_hdr) +
1344 		   btintel_pcie_dump_list_total_size(&dump_list);
1345 	entry = btintel_pcie_dump_entry_alloc(sizeof(*file_hdr));
1346 	if (!entry) {
1347 		btintel_pcie_dump_list_free(&dump_list);
1348 		return -ENOMEM;
1349 	}
1350 
1351 	file_hdr = (void *)entry->data;
1352 	file_hdr->barker = cpu_to_le32(BTINTEL_PCIE_INI_ERROR_DUMP_BARKER);
1353 	file_hdr->file_len = cpu_to_le32(file_len);
1354 	list_add(&entry->list, &dump_list);
1355 
1356 	sg_dump_data = btintel_pcie_alloc_sgtable(file_len);
1357 	if (sg_dump_data) {
1358 		int sg_entries = sg_nents(sg_dump_data);
1359 		u32 offs = 0;
1360 
1361 		list_for_each_entry(entry, &dump_list, list) {
1362 			sg_pcopy_from_buffer(sg_dump_data, sg_entries,
1363 					     entry->data, entry->size, offs);
1364 			offs += entry->size;
1365 		}
1366 
1367 		bt_dev_dbg(hdev, "triggering dev_coredumpsg()");
1368 		dev_coredumpsg(&hdev->dev, sg_dump_data, file_len, GFP_KERNEL);
1369 	} else {
1370 		bt_dev_err(hdev, "Failed to allocate scatter-gather table for coredump");
1371 		ret = -ENOMEM;
1372 	}
1373 
1374 	btintel_pcie_dump_list_free(&dump_list);
1375 	return ret;
1376 }
1377 
1378 static void btintel_pcie_dump_traces(struct hci_dev *hdev)
1379 {
1380 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
1381 	int ret;
1382 
1383 	ret = btintel_pcie_get_mac_access(data);
1384 	if (ret) {
1385 		bt_dev_err(hdev, "Failed to get mac access: (%d)", ret);
1386 		return;
1387 	}
1388 
1389 	ret = btintel_pcie_read_debug_regions(data);
1390 
1391 	btintel_pcie_release_mac_access(data);
1392 
1393 	if (ret)
1394 		bt_dev_err(hdev, "Failed to dump traces: (%d)", ret);
1395 }
1396 
1397 static bool btintel_pcie_is_blazariw(struct pci_dev *pdev)
1398 {
1399 	return pdev->device == 0x4D76;
1400 }
1401 
1402 /* This function enables BT function by setting BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT bit in
1403  * BTINTEL_PCIE_CSR_FUNC_CTRL_REG register and wait for MSI-X with
1404  * BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0.
1405  * Then the host reads firmware version from BTINTEL_CSR_F2D_MBX and the boot stage
1406  * from BTINTEL_PCIE_CSR_BOOT_STAGE_REG.
1407  */
1408 static int btintel_pcie_enable_bt(struct btintel_pcie_data *data)
1409 {
1410 	int err;
1411 	u32 reg;
1412 
1413 	data->gp0_received = false;
1414 
1415 	/* Update the DMA address of CI struct to CSR */
1416 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_CI_ADDR_LSB_REG,
1417 			      data->ci_p_addr & 0xffffffff);
1418 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_CI_ADDR_MSB_REG,
1419 			      (u64)data->ci_p_addr >> 32);
1420 
1421 	/* On BlazarIW, the D0 entry to MAC init does not complete in
1422 	 * time. Wait 50 ms (worst case as per HW analysis) for the
1423 	 * shared hardware reset flow to complete before proceeding with
1424 	 * MAC init.
1425 	 */
1426 	if (btintel_pcie_is_blazariw(data->pdev))
1427 		msleep(50);
1428 
1429 	/* Reset the cached value of boot stage. it is updated by the MSI-X
1430 	 * gp0 interrupt handler.
1431 	 */
1432 	data->boot_stage_cache = 0x0;
1433 
1434 	/* Set MAC_INIT bit to start primary bootloader */
1435 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
1436 	reg &= ~(BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT |
1437 			BTINTEL_PCIE_CSR_FUNC_CTRL_BUS_MASTER_DISCON |
1438 			BTINTEL_PCIE_CSR_FUNC_CTRL_SW_RESET);
1439 	reg |= (BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_ENA |
1440 			BTINTEL_PCIE_CSR_FUNC_CTRL_MAC_INIT);
1441 
1442 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG, reg);
1443 
1444 	/* MAC is ready. Enable BT FUNC */
1445 	btintel_pcie_set_reg_bits(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG,
1446 				  BTINTEL_PCIE_CSR_FUNC_CTRL_FUNC_INIT);
1447 
1448 	btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_FUNC_CTRL_REG);
1449 
1450 	/* wait for interrupt from the device after booting up to primary
1451 	 * bootloader.
1452 	 */
1453 	data->alive_intr_ctxt = BTINTEL_PCIE_ROM;
1454 	err = wait_event_timeout(data->gp0_wait_q, data->gp0_received,
1455 				 msecs_to_jiffies(BTINTEL_DEFAULT_INTR_TIMEOUT_MS));
1456 	if (!err)
1457 		return -ETIME;
1458 
1459 	/* Check cached boot stage is BTINTEL_PCIE_CSR_BOOT_STAGE_ROM(BIT(0)) */
1460 	if (~data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_ROM)
1461 		return -ENODEV;
1462 
1463 	return 0;
1464 }
1465 
1466 static inline bool btintel_pcie_in_op(struct btintel_pcie_data *data)
1467 {
1468 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_OPFW;
1469 }
1470 
1471 static inline bool btintel_pcie_in_iml(struct btintel_pcie_data *data)
1472 {
1473 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_IML &&
1474 		!(data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_OPFW);
1475 }
1476 
1477 static inline bool btintel_pcie_in_d3(struct btintel_pcie_data *data)
1478 {
1479 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_D3_STATE_READY;
1480 }
1481 
1482 static inline bool btintel_pcie_in_d0(struct btintel_pcie_data *data)
1483 {
1484 	return !(data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_D3_STATE_READY);
1485 }
1486 
1487 static inline bool btintel_pcie_in_device_halt(struct btintel_pcie_data *data)
1488 {
1489 	return data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_HALTED;
1490 }
1491 
1492 static void btintel_pcie_wr_sleep_cntrl(struct btintel_pcie_data *data,
1493 					u32 dxstate)
1494 {
1495 	bt_dev_dbg(data->hdev, "writing sleep_ctl_reg: 0x%8.8x", dxstate);
1496 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_IPC_SLEEP_CTL_REG, dxstate);
1497 }
1498 
1499 static int btintel_pcie_read_device_mem(struct btintel_pcie_data *data,
1500 					void *buf, u32 dev_addr, int len)
1501 {
1502 	int err;
1503 	u32 *val = buf;
1504 
1505 	/* Get device mac access */
1506 	err = btintel_pcie_get_mac_access(data);
1507 	if (err) {
1508 		bt_dev_err(data->hdev, "Failed to get mac access %d", err);
1509 		return err;
1510 	}
1511 
1512 	for (; len > 0; len -= 4, dev_addr += 4, val++)
1513 		*val = btintel_pcie_rd_dev_mem(data, dev_addr);
1514 
1515 	btintel_pcie_release_mac_access(data);
1516 
1517 	return 0;
1518 }
1519 
1520 static inline bool btintel_pcie_in_lockdown(struct btintel_pcie_data *data)
1521 {
1522 	return (data->boot_stage_cache &
1523 		BTINTEL_PCIE_CSR_BOOT_STAGE_ROM_LOCKDOWN) ||
1524 		(data->boot_stage_cache &
1525 		 BTINTEL_PCIE_CSR_BOOT_STAGE_IML_LOCKDOWN);
1526 }
1527 
1528 static inline bool btintel_pcie_in_error(struct btintel_pcie_data *data)
1529 {
1530 	if (data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_DEVICE_WARNING)
1531 		bt_dev_warn(data->hdev, "Controller device warning (boot_stage: 0x%8.8x)",
1532 			    data->boot_stage_cache);
1533 
1534 	return	data->boot_stage_cache & BTINTEL_PCIE_CSR_BOOT_STAGE_ABORT_HANDLER;
1535 }
1536 
1537 static u32 btintel_pcie_region_size(struct hci_dev *hdev, const char *name,
1538 				    u32 start, u32 end)
1539 {
1540 	u64 size;
1541 
1542 	if (!start || !end)
1543 		return 0;
1544 
1545 	if (end < start) {
1546 		bt_dev_warn(hdev, "%s region invalid: start=0x%08x end=0x%08x",
1547 			    name, start, end);
1548 		return 0;
1549 	}
1550 
1551 	size = (u64)end + 0x04 - start;
1552 	if (size % sizeof(u32))
1553 		bt_dev_warn(hdev, "%s region size %llu is not 4-byte aligned",
1554 			    name, size);
1555 
1556 	if (size > BTINTEL_PCIE_REGION_MAX_SIZE) {
1557 		bt_dev_warn(hdev, "%s region size %llu exceeds cap %u, ignoring",
1558 			    name, size, BTINTEL_PCIE_REGION_MAX_SIZE);
1559 		return 0;
1560 	}
1561 
1562 	return (u32)size;
1563 }
1564 
1565 static const char *btintel_pcie_tlv_str(u8 tlv_type)
1566 {
1567 	switch (tlv_type) {
1568 	case BTINTEL_PCIE_TLV_TYPE_EXCEPTION_DUMP_ADDRESS:
1569 		return "EXCEPTION_DUMP_ADDRESS";
1570 	case BTINTEL_PCIE_TLV_TYPE_DCCM_MEM_ADDRESS:
1571 		return "DCCM_MEM_ADDRESS";
1572 	case BTINTEL_PCIE_TLV_TYPE_SDS_MEM_ADDRESS:
1573 		return "SDS_MEM_ADDRESS";
1574 	case BTINTEL_PCIE_TLV_TYPE_ECL_MEM_ADDRESS:
1575 		return "ECL_MEM_ADDRESS";
1576 	case BTINTEL_PCIE_TLV_TYPE_SMEM_ADDRESS:
1577 		return "SMEM_ADDRESS";
1578 	default:
1579 		return "UNKNOWN";
1580 	}
1581 }
1582 
1583 static int btintel_parse_mbox_tlv(struct btintel_pcie_data *data)
1584 {
1585 	/* Custom TLV structure for mailbox parsing
1586 	 * len is __le16 as per agreement with FW
1587 	 */
1588 	struct mbox_tlv {
1589 		u8 type;
1590 		__le16 len;
1591 		u8 val[];
1592 	} __packed;
1593 
1594 	u8 *buffer, *ptr;
1595 	u32 buffer_len, remaining;
1596 	int err;
1597 	u32 tbl_addr, tbl_size;
1598 	struct mbox_tlv *tlv;
1599 	struct btintel_data *cnvi_data = hci_get_priv(data->hdev);
1600 	u8 hw_variant = INTEL_HW_VARIANT(cnvi_data->cnvi_bt);
1601 	long t;
1602 
1603 	/* Wait for GP0 alive interrupt to post RX buffers */
1604 	t = wait_event_timeout(data->mbox_parse_wait_q,
1605 			       test_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags),
1606 			       msecs_to_jiffies(BTINTEL_PCIE_MBOX_INTR_TIMEOUT_MS));
1607 	if (!t) {
1608 		bt_dev_warn(data->hdev,
1609 			    "Timeout (%u ms) waiting for alive interrupt before mbox TLV parse; skipping",
1610 			    BTINTEL_PCIE_MBOX_INTR_TIMEOUT_MS);
1611 		return 0;
1612 	}
1613 	clear_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags);
1614 
1615 	bt_dev_info(data->hdev,
1616 		    "mbox TLV parse started at %lld ns (%lld us after mbox interrupt)",
1617 		    ktime_to_ns(ktime_get()),
1618 		    ktime_to_us(ktime_sub(ktime_get(), data->mbox_intr_ts)));
1619 
1620 	memset(&data->dump_info, 0, sizeof(data->dump_info));
1621 
1622 	/* Snapshot to avoid TOCTOU with the GP1 IRQ handler */
1623 	tbl_size = READ_ONCE(data->debug_table_size);
1624 	tbl_addr = READ_ONCE(data->debug_table_addr);
1625 
1626 	if (!tbl_size || !tbl_addr)
1627 		return -EINVAL;
1628 
1629 	/* Ensure size is 4-byte aligned; btintel_pcie_read_device_mem()
1630 	 * reads device memory in 4-byte units.
1631 	 */
1632 	tbl_size = ALIGN_DOWN(tbl_size, 4);
1633 
1634 	if (!tbl_size)
1635 		return -EINVAL;
1636 
1637 	if (tbl_size > SZ_1M) {
1638 		bt_dev_err(data->hdev, "Debug table size too large: %u",
1639 			   tbl_size);
1640 		return -EINVAL;
1641 	}
1642 
1643 	buffer_len = tbl_size;
1644 
1645 	buffer = vmalloc(buffer_len);
1646 	if (!buffer)
1647 		return -ENOMEM;
1648 
1649 	err = btintel_pcie_read_device_mem(data, buffer, tbl_addr,
1650 					   buffer_len);
1651 	if (err)
1652 		goto exit_on_error;
1653 
1654 	print_hex_dump(KERN_INFO, "Bluetooth: mbox_tlv: ", DUMP_PREFIX_OFFSET, 16, 1,
1655 		       buffer, buffer_len, false);
1656 
1657 	ptr = buffer;
1658 	remaining = buffer_len;
1659 
1660 	/* Parse TLV structures: 1 byte type + 2 bytes length +
1661 	 * variable value
1662 	 */
1663 	while (remaining >= sizeof(struct mbox_tlv)) {
1664 		u16 tlv_len;
1665 		u32 tlv_total;
1666 
1667 		tlv = (struct mbox_tlv *)ptr;
1668 		tlv_len = le16_to_cpu(tlv->len);
1669 		tlv_total = sizeof(tlv->type) + sizeof(tlv->len) + tlv_len;
1670 
1671 		if (tlv_total > remaining) {
1672 			bt_dev_err(data->hdev, "TLV parse error: not enough data for TLV value (type=%u, len=%u)",
1673 				   tlv->type, tlv_len);
1674 			break;
1675 		}
1676 
1677 		switch (tlv->type) {
1678 		case BTINTEL_PCIE_TLV_TYPE_EXCEPTION_DUMP_ADDRESS:
1679 			if (tlv_len < 8) {
1680 				bt_dev_err(data->hdev,
1681 					   "TLV %s too short: len=%u (need 8)",
1682 					   btintel_pcie_tlv_str(tlv->type),
1683 					   tlv_len);
1684 				break;
1685 			}
1686 			data->dump_info.exception_dump_addr =
1687 				get_unaligned_le32(&tlv->val[0]);
1688 			data->dump_info.exception_dump_len =
1689 				get_unaligned_le32(&tlv->val[4]);
1690 			if (data->dump_info.exception_dump_len >
1691 			    BTINTEL_PCIE_REGION_MAX_SIZE) {
1692 				bt_dev_warn(data->hdev,
1693 					    "EXCEPTION_EVT_BUFFER size %u exceeds cap %u, ignoring",
1694 					    data->dump_info.exception_dump_len,
1695 					    BTINTEL_PCIE_REGION_MAX_SIZE);
1696 				data->dump_info.exception_dump_addr = 0;
1697 				data->dump_info.exception_dump_len = 0;
1698 			}
1699 			break;
1700 		case BTINTEL_PCIE_TLV_TYPE_DCCM_MEM_ADDRESS:
1701 			if (tlv_len < 8) {
1702 				bt_dev_err(data->hdev,
1703 					   "TLV %s too short: len=%u (need 8)",
1704 					   btintel_pcie_tlv_str(tlv->type),
1705 					   tlv_len);
1706 				break;
1707 			}
1708 			data->dump_info.dccm_addr_start =
1709 				get_unaligned_le32(&tlv->val[0]);
1710 			data->dump_info.dccm_size =
1711 				btintel_pcie_region_size(data->hdev, "DCCM",
1712 							 data->dump_info.dccm_addr_start,
1713 							 get_unaligned_le32(&tlv->val[4]));
1714 			if (!data->dump_info.dccm_size)
1715 				data->dump_info.dccm_addr_start = 0;
1716 			break;
1717 		case BTINTEL_PCIE_TLV_TYPE_SDS_MEM_ADDRESS: {
1718 			struct btintel_pcie_dump_mem_info *di = &data->dump_info;
1719 
1720 			/* hw_variant comes from cnvi_bt which is set during
1721 			 * setup. If mailbox fires before setup completes,
1722 			 * hw_variant is 0. Skip SDS parsing in that case.
1723 			 */
1724 			if (!hw_variant) {
1725 				bt_dev_dbg(data->hdev, "SDS TLV: skipped, hw_variant not yet known");
1726 				break;
1727 			}
1728 			if (tlv_len == 16 && hw_variant > BTINTEL_HWID_BZRI) {
1729 				di->sds_start_addr_start =
1730 					get_unaligned_le32(&tlv->val[0]);
1731 				di->sds_start_size =
1732 					btintel_pcie_region_size(data->hdev, "SDS",
1733 								 di->sds_start_addr_start,
1734 								 get_unaligned_le32(&tlv->val[4]));
1735 				di->sds_iosf_data_addr_start =
1736 					get_unaligned_le32(&tlv->val[8]);
1737 				di->sds_iosf_data_size =
1738 					btintel_pcie_region_size(data->hdev, "SDS_IOSF",
1739 								 di->sds_iosf_data_addr_start,
1740 								 get_unaligned_le32(&tlv->val[12]));
1741 			} else if (tlv_len == 24 &&
1742 				   (hw_variant == BTINTEL_HWID_BZRI ||
1743 				    hw_variant == BTINTEL_HWID_BZRIW)) {
1744 				di->sds_fixed_rom_addr_start =
1745 					get_unaligned_le32(&tlv->val[0]);
1746 				di->sds_fixed_rom_size =
1747 					btintel_pcie_region_size(data->hdev, "SDS_FIXED_ROM",
1748 								 di->sds_fixed_rom_addr_start,
1749 								 get_unaligned_le32(&tlv->val[4]));
1750 				di->sds_start_addr_start =
1751 					get_unaligned_le32(&tlv->val[8]);
1752 				di->sds_start_size =
1753 					btintel_pcie_region_size(data->hdev, "SDS",
1754 								 di->sds_start_addr_start,
1755 								 get_unaligned_le32(&tlv->val[12]));
1756 				di->sds_iosf_data_addr_start =
1757 					get_unaligned_le32(&tlv->val[16]);
1758 				di->sds_iosf_data_size =
1759 					btintel_pcie_region_size(data->hdev, "SDS_IOSF",
1760 								 di->sds_iosf_data_addr_start,
1761 								 get_unaligned_le32(&tlv->val[20]));
1762 			} else {
1763 				bt_dev_err(data->hdev,
1764 					   "SDS TLV: hw=0x%2.2x len=%u",
1765 					   hw_variant, tlv_len);
1766 			}
1767 			if (!di->sds_start_size)
1768 				di->sds_start_addr_start = 0;
1769 			if (!di->sds_iosf_data_size)
1770 				di->sds_iosf_data_addr_start = 0;
1771 			if (!di->sds_fixed_rom_size)
1772 				di->sds_fixed_rom_addr_start = 0;
1773 			break;
1774 		}
1775 		case BTINTEL_PCIE_TLV_TYPE_ECL_MEM_ADDRESS:
1776 			if (tlv_len < 8) {
1777 				bt_dev_err(data->hdev,
1778 					   "TLV %s too short: len=%u (need 8)",
1779 					   btintel_pcie_tlv_str(tlv->type),
1780 					   tlv_len);
1781 				break;
1782 			}
1783 			data->dump_info.ecl_addr_start =
1784 				get_unaligned_le32(&tlv->val[0]);
1785 			data->dump_info.ecl_size =
1786 				btintel_pcie_region_size(data->hdev, "ECL",
1787 							 data->dump_info.ecl_addr_start,
1788 							 get_unaligned_le32(&tlv->val[4]));
1789 			if (!data->dump_info.ecl_size)
1790 				data->dump_info.ecl_addr_start = 0;
1791 			break;
1792 		case BTINTEL_PCIE_TLV_TYPE_SMEM_ADDRESS:
1793 			if (tlv_len < 8) {
1794 				bt_dev_err(data->hdev,
1795 					   "TLV %s too short: len=%u (need 8)",
1796 					   btintel_pcie_tlv_str(tlv->type),
1797 					   tlv_len);
1798 				break;
1799 			}
1800 			data->dump_info.smem_addr_start =
1801 				get_unaligned_le32(&tlv->val[0]);
1802 			data->dump_info.smem_size =
1803 				btintel_pcie_region_size(data->hdev, "SMEM",
1804 							 data->dump_info.smem_addr_start,
1805 							 get_unaligned_le32(&tlv->val[4]));
1806 			if (!data->dump_info.smem_size)
1807 				data->dump_info.smem_addr_start = 0;
1808 			break;
1809 		default:
1810 			bt_dev_dbg(data->hdev, "Unknown TLV type: %u length: %u",
1811 				   tlv->type, tlv_len);
1812 			break;
1813 		}
1814 
1815 		/* Move to next TLV */
1816 		ptr += tlv_total;
1817 		remaining -= tlv_total;
1818 	}
1819 
1820 	bt_dev_info(data->hdev,
1821 		   "exception_dump: addr:0x%08x len:0x%08x",
1822 		   data->dump_info.exception_dump_addr,
1823 		   data->dump_info.exception_dump_len);
1824 	bt_dev_info(data->hdev,
1825 		   "dccm: start:0x%8.8x size:%u",
1826 		   data->dump_info.dccm_addr_start,
1827 		   data->dump_info.dccm_size);
1828 	bt_dev_info(data->hdev,
1829 		   "sds_fixed_rom: start:0x%8.8x size:%u",
1830 		   data->dump_info.sds_fixed_rom_addr_start,
1831 		   data->dump_info.sds_fixed_rom_size);
1832 	bt_dev_info(data->hdev,
1833 		   "sds: start:0x%8.8x size:%u",
1834 		   data->dump_info.sds_start_addr_start,
1835 		   data->dump_info.sds_start_size);
1836 	bt_dev_info(data->hdev,
1837 		   "sds_iosf: start:0x%8.8x size:%u",
1838 		   data->dump_info.sds_iosf_data_addr_start,
1839 		   data->dump_info.sds_iosf_data_size);
1840 	bt_dev_info(data->hdev,
1841 		   "ecl: start:0x%8.8x size:%u",
1842 		   data->dump_info.ecl_addr_start,
1843 		   data->dump_info.ecl_size);
1844 	bt_dev_info(data->hdev,
1845 		   "smem: start:0x%8.8x size:%u",
1846 		   data->dump_info.smem_addr_start,
1847 		   data->dump_info.smem_size);
1848 
1849 	vfree(buffer);
1850 	return 0;
1851 
1852 exit_on_error:
1853 	vfree(buffer);
1854 	return err;
1855 }
1856 
1857 static void btintel_pcie_msix_gp1_handler(struct btintel_pcie_data *data)
1858 {
1859 	bool target_access = false;
1860 	u32 addr = 0, size = 0;
1861 
1862 	/* Read the Mail box status and registers */
1863 	data->mbox.mbox_status = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_STATUS_REG);
1864 	if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX1) {
1865 		data->mbox.mbox1 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_1_REG);
1866 		if (data->mbox.mbox1 ==
1867 		    BTINTEL_PCIE_BUILD_SPECIFIC_RESOURCES_MAPPING) {
1868 			bt_dev_info(data->hdev,
1869 				    "mailbox for target access");
1870 			target_access = true;
1871 		}
1872 	}
1873 
1874 	if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX2) {
1875 		data->mbox.mbox2 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_2_REG);
1876 		if (target_access)
1877 			addr = data->mbox.mbox2;
1878 	}
1879 
1880 	if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX3) {
1881 		data->mbox.mbox3 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_3_REG);
1882 		if (target_access)
1883 			size = data->mbox.mbox3;
1884 	}
1885 
1886 	if (data->mbox.mbox_status & BTINTEL_PCIE_CSR_MBOX_STATUS_MBOX4)
1887 		data->mbox.mbox4 = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MBOX_4_REG);
1888 
1889 	bt_dev_dbg(data->hdev,
1890 		   "GP1: sts:0x%08x mb1:0x%08x mb2:0x%08x mb3:0x%08x mb4:0x%08x",
1891 		   data->mbox.mbox_status, data->mbox.mbox1,
1892 		   data->mbox.mbox2, data->mbox.mbox3,
1893 		   data->mbox.mbox4);
1894 
1895 	if (target_access &&
1896 	    !test_and_set_bit(BTINTEL_PCIE_MAIL_BOX_INTR,
1897 				   &data->flags)) {
1898 		/* Arm the mbox<->alive handshake */
1899 		clear_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags);
1900 		set_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags);
1901 		data->mbox_intr_ts = ktime_get();
1902 
1903 		bt_dev_info(data->hdev,
1904 			    "mbox interrupt received at %lld ns; queuing mbox_work",
1905 			    ktime_to_ns(data->mbox_intr_ts));
1906 
1907 		WRITE_ONCE(data->debug_table_addr, addr);
1908 		WRITE_ONCE(data->debug_table_size, size);
1909 		if (!queue_work(data->dump_workqueue,
1910 				&data->mbox_work)) {
1911 			clear_bit(BTINTEL_PCIE_MAIL_BOX_INTR, &data->flags);
1912 			clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags);
1913 		}
1914 	}
1915 
1916 	/* Mailbox is read, ack to FW */
1917 	btintel_pcie_set_reg_bits(data,
1918 				  BTINTEL_PCIE_CSR_IPC_DOORBELL_VEC_REG,
1919 				  BTINTEL_PCIE_CSR_DOORBELL_MBOX_READ_CONFIRM);
1920 }
1921 
1922 /* This function handles the MSI-X interrupt for gp0 cause (bit 0 in
1923  * BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES) which is sent for boot stage and image response.
1924  */
1925 static void btintel_pcie_msix_gp0_handler(struct btintel_pcie_data *data)
1926 {
1927 	bool submit_rx, signal_waitq;
1928 	u32 reg, old_ctxt;
1929 
1930 	/* This interrupt is for three different causes and it is not easy to
1931 	 * know what causes the interrupt. So, it compares each register value
1932 	 * with cached value and update it before it wake up the queue.
1933 	 */
1934 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
1935 	if (reg != data->boot_stage_cache)
1936 		data->boot_stage_cache = reg;
1937 
1938 	bt_dev_dbg(data->hdev, "Alive context: %s old_boot_stage: 0x%8.8x new_boot_stage: 0x%8.8x",
1939 		   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt),
1940 		   data->boot_stage_cache, reg);
1941 	reg = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_IMG_RESPONSE_REG);
1942 	if (reg != data->img_resp_cache)
1943 		data->img_resp_cache = reg;
1944 
1945 	if (btintel_pcie_in_error(data)) {
1946 		bt_dev_err(data->hdev, "Controller in error state (boot_stage: 0x%8.8x)",
1947 			   data->boot_stage_cache);
1948 		btintel_pcie_dump_debug_registers(data->hdev);
1949 		return;
1950 	}
1951 
1952 	if (btintel_pcie_in_lockdown(data)) {
1953 		bt_dev_err(data->hdev, "Controller in lockdown state");
1954 		btintel_pcie_dump_debug_registers(data->hdev);
1955 		return;
1956 	}
1957 
1958 	data->gp0_received = true;
1959 
1960 	old_ctxt = data->alive_intr_ctxt;
1961 	submit_rx = false;
1962 	signal_waitq = false;
1963 
1964 	/* Serialize the alive_intr_ctxt claim against set_dxstate()'s
1965 	 * register-based fallback, which can run concurrently.
1966 	 */
1967 	spin_lock(&data->irq_lock);
1968 	switch (data->alive_intr_ctxt) {
1969 	case BTINTEL_PCIE_ROM:
1970 		data->alive_intr_ctxt = BTINTEL_PCIE_FW_DL;
1971 		signal_waitq = true;
1972 		break;
1973 	case BTINTEL_PCIE_FW_DL:
1974 		/* Error case is already handled. Ideally control shall not
1975 		 * reach here
1976 		 */
1977 		break;
1978 	case BTINTEL_PCIE_INTEL_HCI_RESET1:
1979 		if (btintel_pcie_in_op(data)) {
1980 			submit_rx = true;
1981 			signal_waitq = true;
1982 			break;
1983 		}
1984 
1985 		if (btintel_pcie_in_iml(data)) {
1986 			submit_rx = true;
1987 			signal_waitq = true;
1988 			data->alive_intr_ctxt = BTINTEL_PCIE_FW_DL;
1989 			break;
1990 		}
1991 		break;
1992 	case BTINTEL_PCIE_INTEL_HCI_RESET2:
1993 		if (btintel_test_and_clear_flag(data->hdev, INTEL_WAIT_FOR_D0)) {
1994 			btintel_wake_up_flag(data->hdev, INTEL_WAIT_FOR_D0);
1995 			data->alive_intr_ctxt = BTINTEL_PCIE_D0;
1996 		}
1997 		break;
1998 	case BTINTEL_PCIE_D0:
1999 		if (btintel_pcie_in_d3(data)) {
2000 			data->alive_intr_ctxt = BTINTEL_PCIE_D3;
2001 			signal_waitq = true;
2002 			break;
2003 		}
2004 		break;
2005 	case BTINTEL_PCIE_D3:
2006 		if (btintel_pcie_in_d0(data)) {
2007 			data->alive_intr_ctxt = BTINTEL_PCIE_D0;
2008 			submit_rx = true;
2009 			signal_waitq = true;
2010 			break;
2011 		}
2012 		break;
2013 	case BTINTEL_PCIE_HCI_RESET:
2014 		data->alive_intr_ctxt = BTINTEL_PCIE_D0;
2015 		submit_rx = true;
2016 		signal_waitq = true;
2017 		break;
2018 	default:
2019 		bt_dev_err(data->hdev, "Unknown state: 0x%2.2x",
2020 			   data->alive_intr_ctxt);
2021 		break;
2022 	}
2023 	spin_unlock(&data->irq_lock);
2024 
2025 	if (submit_rx) {
2026 		btintel_pcie_reset_ia(data);
2027 		btintel_pcie_start_rx(data);
2028 
2029 		/* Complete the mbox<->alive handshake */
2030 		if (test_and_clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING, &data->flags)) {
2031 			set_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags);
2032 			wake_up(&data->mbox_parse_wait_q);
2033 		}
2034 	}
2035 
2036 	if (signal_waitq) {
2037 		bt_dev_dbg(data->hdev, "wake up gp0 wait_q");
2038 		wake_up(&data->gp0_wait_q);
2039 	}
2040 
2041 	if (old_ctxt != data->alive_intr_ctxt)
2042 		bt_dev_dbg(data->hdev, "alive context changed: %s  ->  %s",
2043 			   btintel_pcie_alivectxt_state2str(old_ctxt),
2044 			   btintel_pcie_alivectxt_state2str(data->alive_intr_ctxt));
2045 }
2046 
2047 /* This function handles the MSX-X interrupt for rx queue 0 which is for TX
2048  */
2049 static void btintel_pcie_msix_tx_handle(struct btintel_pcie_data *data)
2050 {
2051 	u16 cr_tia, cr_hia;
2052 	struct txq *txq;
2053 	struct urbd0 *urbd0;
2054 
2055 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM];
2056 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
2057 
2058 	if (cr_tia == cr_hia)
2059 		return;
2060 
2061 	txq = &data->txq;
2062 
2063 	if (cr_hia >= txq->count) {
2064 		bt_dev_err(data->hdev, "TXQ: invalid cr_hia %u", cr_hia);
2065 		return;
2066 	}
2067 
2068 	while (cr_tia != cr_hia) {
2069 		data->tx_wait_done = true;
2070 		wake_up(&data->tx_wait_q);
2071 
2072 		urbd0 = &txq->urbd0s[cr_tia];
2073 
2074 		if (urbd0->tfd_index >= txq->count)
2075 			return;
2076 
2077 		cr_tia = (cr_tia + 1) % txq->count;
2078 		data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM] = cr_tia;
2079 		ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_TXQ_NUM);
2080 	}
2081 }
2082 
2083 static int btintel_pcie_recv_event(struct hci_dev *hdev, struct sk_buff *skb)
2084 {
2085 	struct hci_event_hdr *hdr = (void *)skb->data;
2086 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
2087 
2088 	if (skb->len > HCI_EVENT_HDR_SIZE && hdr->evt == 0xff &&
2089 	    hdr->plen > 0) {
2090 		const void *ptr = skb->data + HCI_EVENT_HDR_SIZE + 1;
2091 		unsigned int len = skb->len - HCI_EVENT_HDR_SIZE - 1;
2092 
2093 		if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
2094 			switch (skb->data[2]) {
2095 			case 0x02:
2096 				/* When switching to the operational firmware
2097 				 * the device sends a vendor specific event
2098 				 * indicating that the bootup completed.
2099 				 */
2100 				btintel_bootup(hdev, ptr, len);
2101 
2102 				/* If bootup event is from operational image,
2103 				 * driver needs to write sleep control register to
2104 				 * move into D0 state
2105 				 */
2106 				if (btintel_pcie_in_op(data)) {
2107 					btintel_pcie_wr_sleep_cntrl(data, BTINTEL_PCIE_STATE_D0);
2108 					data->alive_intr_ctxt = BTINTEL_PCIE_INTEL_HCI_RESET2;
2109 					kfree_skb(skb);
2110 					return 0;
2111 				}
2112 
2113 				if (btintel_pcie_in_iml(data)) {
2114 					/* In case of IML, there is no concept
2115 					 * of D0 transition. Just mimic as if
2116 					 * IML moved to D0 by clearing INTEL_WAIT_FOR_D0
2117 					 * bit and waking up the task waiting on
2118 					 * INTEL_WAIT_FOR_D0. This is required
2119 					 * as intel_boot() is common function for
2120 					 * both IML and OP image loading.
2121 					 */
2122 					if (btintel_test_and_clear_flag(data->hdev,
2123 									INTEL_WAIT_FOR_D0))
2124 						btintel_wake_up_flag(data->hdev,
2125 								     INTEL_WAIT_FOR_D0);
2126 				}
2127 				kfree_skb(skb);
2128 				return 0;
2129 			case 0x06:
2130 				/* When the firmware loading completes the
2131 				 * device sends out a vendor specific event
2132 				 * indicating the result of the firmware
2133 				 * loading.
2134 				 */
2135 				btintel_secure_send_result(hdev, ptr, len);
2136 				kfree_skb(skb);
2137 				return 0;
2138 			}
2139 		}
2140 
2141 		/* This is a debug event that comes from IML and OP image when it
2142 		 * starts execution. There is no need pass this event to stack.
2143 		 */
2144 		if (skb->data[2] == 0x97) {
2145 			hci_recv_diag(hdev, skb);
2146 			return 0;
2147 		}
2148 	}
2149 
2150 	return hci_recv_frame(hdev, skb);
2151 }
2152 /* Process the received rx data
2153  * It check the frame header to identify the data type and create skb
2154  * and calling HCI API
2155  */
2156 static int btintel_pcie_recv_frame(struct btintel_pcie_data *data,
2157 				       struct sk_buff *skb)
2158 {
2159 	int ret;
2160 	u8 pkt_type;
2161 	u32 plen;
2162 	u32 pcie_pkt_type;
2163 	void *pdata;
2164 	struct hci_dev *hdev = data->hdev;
2165 
2166 	spin_lock(&data->hci_rx_lock);
2167 
2168 	/* The first 4 bytes indicates the Intel PCIe specific packet type */
2169 	pdata = skb_pull_data(skb, BTINTEL_PCIE_HCI_TYPE_LEN);
2170 	if (!pdata) {
2171 		bt_dev_err(hdev, "Corrupted packet received");
2172 		ret = -EILSEQ;
2173 		goto exit_error;
2174 	}
2175 
2176 	pcie_pkt_type = get_unaligned_le32(pdata);
2177 
2178 	switch (pcie_pkt_type) {
2179 	case BTINTEL_PCIE_HCI_ACL_PKT:
2180 		if (skb->len >= HCI_ACL_HDR_SIZE) {
2181 			plen = HCI_ACL_HDR_SIZE + __le16_to_cpu(hci_acl_hdr(skb)->dlen);
2182 			pkt_type = HCI_ACLDATA_PKT;
2183 		} else {
2184 			bt_dev_err(hdev, "ACL packet is too short");
2185 			ret = -EILSEQ;
2186 			goto exit_error;
2187 		}
2188 		break;
2189 
2190 	case BTINTEL_PCIE_HCI_SCO_PKT:
2191 		if (skb->len >= HCI_SCO_HDR_SIZE) {
2192 			plen = HCI_SCO_HDR_SIZE + hci_sco_hdr(skb)->dlen;
2193 			pkt_type = HCI_SCODATA_PKT;
2194 		} else {
2195 			bt_dev_err(hdev, "SCO packet is too short");
2196 			ret = -EILSEQ;
2197 			goto exit_error;
2198 		}
2199 		break;
2200 
2201 	case BTINTEL_PCIE_HCI_EVT_PKT:
2202 		if (skb->len >= HCI_EVENT_HDR_SIZE) {
2203 			plen = HCI_EVENT_HDR_SIZE + hci_event_hdr(skb)->plen;
2204 			pkt_type = HCI_EVENT_PKT;
2205 		} else {
2206 			bt_dev_err(hdev, "Event packet is too short");
2207 			ret = -EILSEQ;
2208 			goto exit_error;
2209 		}
2210 		break;
2211 
2212 	case BTINTEL_PCIE_HCI_ISO_PKT:
2213 		if (skb->len >= HCI_ISO_HDR_SIZE) {
2214 			plen = HCI_ISO_HDR_SIZE + __le16_to_cpu(hci_iso_hdr(skb)->dlen);
2215 			pkt_type = HCI_ISODATA_PKT;
2216 		} else {
2217 			bt_dev_err(hdev, "ISO packet is too short");
2218 			ret = -EILSEQ;
2219 			goto exit_error;
2220 		}
2221 		break;
2222 
2223 	default:
2224 		bt_dev_err(hdev, "Invalid packet type received: 0x%4.4x",
2225 			   pcie_pkt_type);
2226 		ret = -EINVAL;
2227 		goto exit_error;
2228 	}
2229 
2230 	if (skb->len < plen) {
2231 		bt_dev_err(hdev, "Received corrupted packet. type: 0x%2.2x",
2232 			   pkt_type);
2233 		ret = -EILSEQ;
2234 		goto exit_error;
2235 	}
2236 
2237 	bt_dev_dbg(hdev, "pkt_type: 0x%2.2x len: %u", pkt_type, plen);
2238 
2239 	hci_skb_pkt_type(skb) = pkt_type;
2240 	hdev->stat.byte_rx += plen;
2241 	skb_trim(skb, plen);
2242 
2243 	if (pcie_pkt_type == BTINTEL_PCIE_HCI_EVT_PKT)
2244 		ret = btintel_pcie_recv_event(hdev, skb);
2245 	else
2246 		ret = hci_recv_frame(hdev, skb);
2247 	skb = NULL; /* skb is freed in the callee  */
2248 
2249 exit_error:
2250 	kfree_skb(skb);
2251 
2252 	if (ret)
2253 		hdev->stat.err_rx++;
2254 
2255 	spin_unlock(&data->hci_rx_lock);
2256 
2257 	return ret;
2258 }
2259 
2260 static void btintel_pcie_read_hwexp(struct btintel_pcie_data *data)
2261 {
2262 	int err, offset, pending;
2263 	u32 len;
2264 	struct sk_buff *skb;
2265 	u8 *buf, prefix[64];
2266 	u32 addr, val;
2267 	u16 pkt_len;
2268 
2269 	struct tlv {
2270 		u8	type;
2271 		__le16	len;
2272 		u8	val[];
2273 	} __packed;
2274 
2275 	struct tlv *tlv;
2276 
2277 	switch (data->dmp_hdr.cnvi_top & 0xfff) {
2278 	case BTINTEL_CNVI_BLAZARI:
2279 	case BTINTEL_CNVI_BLAZARIW:
2280 		/* only from step B0 onwards */
2281 		if (INTEL_CNVX_TOP_STEP(data->dmp_hdr.cnvi_top) != 0x01)
2282 			return;
2283 		break;
2284 	case BTINTEL_CNVI_SCP:
2285 	case BTINTEL_CNVI_SCP2:
2286 	case BTINTEL_CNVI_SCP2_C0:
2287 	case BTINTEL_CNVI_SCP2F:
2288 	case BTINTEL_CNVI_DRACO:
2289 		break;
2290 	default:
2291 		bt_dev_err(data->hdev, "Unsupported cnvi 0x%8.8x", data->dmp_hdr.cnvi_top);
2292 		return;
2293 	}
2294 
2295 	len = data->dump_info.exception_dump_len;
2296 	addr = data->dump_info.exception_dump_addr;
2297 
2298 	if (!addr || len < sizeof(__le32) || len > SZ_4K) {
2299 		bt_dev_err(data->hdev, "Invalid exception address: 0x%8.8x or length: %u",
2300 			   addr, len);
2301 		return;
2302 	}
2303 
2304 	/* Ensure size is 4-byte aligned; btintel_pcie_read_device_mem()
2305 	 * reads device memory in 4-byte units.
2306 	 */
2307 	len = ALIGN_DOWN(len, 4);
2308 
2309 	buf = kzalloc(len, GFP_KERNEL);
2310 	if (!buf)
2311 		goto exit_on_error;
2312 
2313 	err = btintel_pcie_read_device_mem(data, buf, addr, len);
2314 	if (err)
2315 		goto exit_on_error;
2316 
2317 	val = get_unaligned_le32(buf);
2318 	if (val != BTINTEL_PCIE_MAGIC_NUM) {
2319 		bt_dev_err(data->hdev, "Invalid exception dump signature: 0x%8.8x",
2320 			   val);
2321 		goto exit_on_error;
2322 	}
2323 
2324 	snprintf(prefix, sizeof(prefix), "Bluetooth: %s: ", bt_dev_name(data->hdev));
2325 
2326 	offset = 4;
2327 	do {
2328 		pending = len - offset;
2329 		if (pending < sizeof(*tlv))
2330 			break;
2331 		tlv = (struct tlv *)(buf + offset);
2332 
2333 		/* If type == 0, then there are no more TLVs to be parsed */
2334 		if (!tlv->type) {
2335 			bt_dev_dbg(data->hdev, "Invalid TLV type 0");
2336 			break;
2337 		}
2338 		pkt_len = le16_to_cpu(tlv->len);
2339 		offset += sizeof(*tlv);
2340 		pending = len - offset;
2341 		if (pkt_len > pending)
2342 			break;
2343 
2344 		offset += pkt_len;
2345 
2346 		 /* Only TLVs of type == 1 are HCI events, no need to process other
2347 		  * TLVs
2348 		  */
2349 		if (tlv->type != 1)
2350 			continue;
2351 
2352 		bt_dev_dbg(data->hdev, "TLV packet length: %u", pkt_len);
2353 		if (pkt_len > HCI_MAX_EVENT_SIZE)
2354 			break;
2355 		skb = bt_skb_alloc(pkt_len, GFP_KERNEL);
2356 		if (!skb)
2357 			goto exit_on_error;
2358 		hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
2359 		skb_put_data(skb, tlv->val, pkt_len);
2360 
2361 		/* copy Intel specific pcie packet type */
2362 		val = BTINTEL_PCIE_HCI_EVT_PKT;
2363 		memcpy(skb_push(skb, BTINTEL_PCIE_HCI_TYPE_LEN), &val,
2364 		       BTINTEL_PCIE_HCI_TYPE_LEN);
2365 
2366 		print_hex_dump(KERN_DEBUG, prefix, DUMP_PREFIX_OFFSET, 16, 1,
2367 			       tlv->val, pkt_len, false);
2368 
2369 		btintel_pcie_recv_frame(data, skb);
2370 	} while (offset < len);
2371 
2372 exit_on_error:
2373 	kfree(buf);
2374 }
2375 
2376 static int btintel_pcie_dump_fwtrigger_event(struct btintel_pcie_data *data)
2377 {
2378 	struct btintel_pcie_fwtrigger_evt *evt;
2379 	struct sk_buff *skb;
2380 	unsigned int len;
2381 	int err;
2382 	u8 *buf;
2383 
2384 	if (!data->debug_evt_size || !data->debug_evt_addr)
2385 		return -EINVAL;
2386 
2387 	len = data->debug_evt_size;
2388 
2389 	len = ALIGN_DOWN(len, 4);
2390 
2391 	if (len < sizeof(*evt) || len > HCI_MAX_EVENT_SIZE) {
2392 		bt_dev_err(data->hdev, "Invalid FW trigger data size (%u bytes)", len);
2393 		return -EINVAL;
2394 	}
2395 
2396 	buf = kzalloc(len, GFP_KERNEL);
2397 	if (!buf)
2398 		return -ENOMEM;
2399 
2400 	err = btintel_pcie_read_device_mem(data, buf, data->debug_evt_addr,
2401 					   len);
2402 	if (err)
2403 		goto exit_on_error;
2404 
2405 	evt = (void *)buf;
2406 	bt_dev_dbg(data->hdev, "event type: 0x%2.2x event id: 0x%4.4x len: %u",
2407 		   evt->event_type, le16_to_cpu(evt->event_id), len);
2408 
2409 	skb = bt_skb_alloc(len, GFP_KERNEL);
2410 	if (!skb) {
2411 		err = -ENOMEM;
2412 		goto exit_on_error;
2413 	}
2414 	skb_put_data(skb, buf, len);
2415 
2416 	hci_recv_diag(data->hdev, skb);
2417 	err = 0;
2418 
2419 exit_on_error:
2420 	kfree(buf);
2421 	return err;
2422 }
2423 
2424 /* Queue a coredump dump_traces() pass.
2425  *
2426  * Returns true if a new coredump was queued, false if one was already
2427  * in-flight (the BTINTEL_PCIE_COREDUMP_INPROGRESS bit serves as the
2428  * single-writer guard for the @coredump_work item) or the workqueue is
2429  * disabled (reset / remove in progress).
2430  *
2431  * Always queue this AFTER any companion event-reader work (hwexp /
2432  * fwtrigger) so that, on the ordered @dump_workqueue, the event reader
2433  * runs first and the trigger metadata is populated before dump_traces
2434  * consumes it.
2435  */
2436 static bool btintel_pcie_queue_coredump(struct btintel_pcie_data *data,
2437 					u16 trigger_reason)
2438 {
2439 	if (test_and_set_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags))
2440 		return false;
2441 
2442 	data->dmp_hdr.trigger_reason = trigger_reason;
2443 
2444 	if (queue_work(data->dump_workqueue, &data->coredump_work))
2445 		return true;
2446 
2447 	/* Workqueue is disabled (reset/remove drained it). Release the
2448 	 * guard so a later trigger, after re-probe, can succeed.
2449 	 */
2450 	clear_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags);
2451 	return false;
2452 }
2453 
2454 static void btintel_pcie_msix_fw_trigger_handler(struct btintel_pcie_data *data)
2455 {
2456 	bt_dev_dbg(data->hdev, "Received firmware smart trigger cause");
2457 
2458 	/* Per-work guard: deduplicate concurrent FW-trigger interrupts.
2459 	 * Cleared at the tail of btintel_pcie_fwtrigger_worker().
2460 	 */
2461 	if (test_and_set_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS,
2462 			     &data->flags))
2463 		return;
2464 
2465 	if (!queue_work(data->dump_workqueue, &data->fwtrigger_work)) {
2466 		clear_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags);
2467 		return;
2468 	}
2469 
2470 	/* Queue coredump after the fwtrigger event reader so dmp_hdr.event_*
2471 	 * is populated before dump_traces consumes it.
2472 	 */
2473 	btintel_pcie_queue_coredump(data, BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT);
2474 }
2475 
2476 static void btintel_pcie_msix_hw_exp_handler(struct btintel_pcie_data *data)
2477 {
2478 	bt_dev_err(data->hdev, "Received hw exception interrupt");
2479 
2480 	/* CORE_HALTED is the single-writer guard for this handler. It is
2481 	 * set once on first HW exception and cleared only by re-probe
2482 	 * (data is reallocated), so it also serializes hwexp_work
2483 	 * scheduling without needing a separate bit.
2484 	 */
2485 	if (test_and_set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags))
2486 		return;
2487 
2488 	/* Queue companion coredump first so it is appended after hwexp_work
2489 	 * on the ordered @dump_workqueue (preserves the original
2490 	 * coredump-then-hwexp ordering).
2491 	 */
2492 	btintel_pcie_queue_coredump(data, BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT);
2493 
2494 	queue_work(data->dump_workqueue, &data->hwexp_work);
2495 }
2496 
2497 static void btintel_pcie_coredump_worker(struct work_struct *work)
2498 {
2499 	struct btintel_pcie_data *data = container_of(work,
2500 					struct btintel_pcie_data, coredump_work);
2501 
2502 	/* hdev is NULL until setup_hdev() succeeds, and is cleared on
2503 	 * teardown after disable_work_sync() drains us; bail in that case.
2504 	 */
2505 	if (!data->hdev)
2506 		goto out;
2507 
2508 	/* When firmware routes debug traces to the WiFi DBGC, no host
2509 	 * DBGC buffers were allocated, so there is nothing to dump here.
2510 	 */
2511 	if (btintel_pcie_dbg_to_wifi(data)) {
2512 		bt_dev_info(data->hdev,
2513 			    "Skipping coredump: debug traces routed to WiFi DBGC");
2514 		goto out;
2515 	}
2516 
2517 	btintel_pcie_dump_traces(data->hdev);
2518 out:
2519 	/* Release guard last so a new trigger can run only after this
2520 	 * pass has fully completed (including dev_coredumpv()).
2521 	 */
2522 	clear_bit(BTINTEL_PCIE_COREDUMP_INPROGRESS, &data->flags);
2523 }
2524 
2525 static void btintel_pcie_hwexp_worker(struct work_struct *work)
2526 {
2527 	struct btintel_pcie_data *data = container_of(work,
2528 					struct btintel_pcie_data, hwexp_work);
2529 
2530 	if (!data->hdev)
2531 		return;
2532 
2533 	/* Unlike usb products, controller will not send hardware exception
2534 	 * event on exception. Instead controller writes the hardware event
2535 	 * to device memory along with optional debug events, raises MSIX
2536 	 * and halts. Driver shall read the exception event from device
2537 	 * memory and passes it to the stack for further processing.
2538 	 *
2539 	 * Re-entry is gated by BTINTEL_PCIE_CORE_HALTED in the IRQ
2540 	 * handler, which is only cleared by re-probe; no per-work bit
2541 	 * is needed here.
2542 	 */
2543 	btintel_pcie_read_hwexp(data);
2544 }
2545 
2546 static void btintel_pcie_fwtrigger_worker(struct work_struct *work)
2547 {
2548 	struct btintel_pcie_data *data = container_of(work,
2549 					struct btintel_pcie_data, fwtrigger_work);
2550 	int err;
2551 
2552 	if (!data->hdev)
2553 		goto out;
2554 
2555 	err = btintel_pcie_dump_fwtrigger_event(data);
2556 	if (err)
2557 		bt_dev_warn(data->hdev, "failed to log fwtrigger event");
2558 out:
2559 	/* Release guard last; matches set in fw_trigger handler. */
2560 	clear_bit(BTINTEL_PCIE_FWTRIGGER_DUMP_INPROGRESS, &data->flags);
2561 }
2562 
2563 static void btintel_pcie_mbox_worker(struct work_struct *work)
2564 {
2565 	struct btintel_pcie_data *data = container_of(work,
2566 					struct btintel_pcie_data, mbox_work);
2567 
2568 	if (!data->hdev)
2569 		goto out;
2570 
2571 	btintel_parse_mbox_tlv(data);
2572 out:
2573 	/* Release guard last; matches set in gp1 handler. */
2574 	clear_bit(BTINTEL_PCIE_MAIL_BOX_INTR, &data->flags);
2575 }
2576 
2577 static void btintel_pcie_rx_work(struct work_struct *work)
2578 {
2579 	struct btintel_pcie_data *data = container_of(work,
2580 					struct btintel_pcie_data, rx_work);
2581 	struct sk_buff *skb;
2582 
2583 	/* Process the sk_buf in queue and send to the HCI layer */
2584 	while ((skb = skb_dequeue(&data->rx_skb_q))) {
2585 		btintel_pcie_recv_frame(data, skb);
2586 	}
2587 }
2588 
2589 /* create sk_buff with data and save it to queue and start RX work */
2590 static int btintel_pcie_submit_rx_work(struct btintel_pcie_data *data, u8 status,
2591 				       void *buf)
2592 {
2593 	int ret, len;
2594 	struct rfh_hdr *rfh_hdr;
2595 	struct sk_buff *skb;
2596 
2597 	rfh_hdr = buf;
2598 
2599 	len = rfh_hdr->packet_len;
2600 	if (len == 0 || len > BTINTEL_PCIE_BUFFER_SIZE - sizeof(*rfh_hdr)) {
2601 		bt_dev_err(data->hdev, "Invalid packet_len %d (max %zu)", len,
2602 			   BTINTEL_PCIE_BUFFER_SIZE - sizeof(*rfh_hdr));
2603 		ret = -EINVAL;
2604 		goto resubmit;
2605 	}
2606 
2607 	/* Remove RFH header */
2608 	buf += sizeof(*rfh_hdr);
2609 
2610 	skb = alloc_skb(len, GFP_ATOMIC);
2611 	if (!skb)
2612 		goto resubmit;
2613 
2614 	skb_put_data(skb, buf, len);
2615 	skb_queue_tail(&data->rx_skb_q, skb);
2616 	queue_work(data->workqueue, &data->rx_work);
2617 
2618 resubmit:
2619 	ret = btintel_pcie_submit_rx(data);
2620 
2621 	return ret;
2622 }
2623 
2624 /* Handles the MSI-X interrupt for rx queue 1 which is for RX */
2625 static void btintel_pcie_msix_rx_handle(struct btintel_pcie_data *data)
2626 {
2627 	u16 cr_hia, cr_tia;
2628 	struct rxq *rxq;
2629 	struct urbd1 *urbd1;
2630 	struct data_buf *buf;
2631 	int ret;
2632 	struct hci_dev *hdev = data->hdev;
2633 
2634 	cr_hia = data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM];
2635 	cr_tia = data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
2636 
2637 	bt_dev_dbg(hdev, "RXQ: cr_hia: %u  cr_tia: %u", cr_hia, cr_tia);
2638 
2639 	/* Check CR_TIA and CR_HIA for change */
2640 	if (cr_tia == cr_hia)
2641 		return;
2642 
2643 	rxq = &data->rxq;
2644 
2645 	if (cr_hia >= rxq->count) {
2646 		bt_dev_err(hdev, "RXQ: invalid cr_hia %u", cr_hia);
2647 		return;
2648 	}
2649 
2650 	/* The firmware sends multiple CD in a single MSI-X and it needs to
2651 	 * process all received CDs in this interrupt.
2652 	 */
2653 	while (cr_tia != cr_hia) {
2654 		urbd1 = &rxq->urbd1s[cr_tia];
2655 		ipc_print_urbd1(data->hdev, urbd1, cr_tia);
2656 
2657 		if (urbd1->frbd_tag >= rxq->count) {
2658 			bt_dev_err(hdev, "RXQ: invalid frbd_tag %u",
2659 				   urbd1->frbd_tag);
2660 			return;
2661 		}
2662 
2663 		buf = &rxq->bufs[urbd1->frbd_tag];
2664 		if (!buf) {
2665 			bt_dev_err(hdev, "RXQ: failed to get the DMA buffer for %d",
2666 				   urbd1->frbd_tag);
2667 			return;
2668 		}
2669 
2670 		ret = btintel_pcie_submit_rx_work(data, urbd1->status,
2671 						  buf->data);
2672 		if (ret) {
2673 			bt_dev_err(hdev, "RXQ: failed to submit rx request");
2674 			return;
2675 		}
2676 
2677 		cr_tia = (cr_tia + 1) % rxq->count;
2678 		data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM] = cr_tia;
2679 		ipc_print_ia_ring(data->hdev, &data->ia, BTINTEL_PCIE_RXQ_NUM);
2680 	}
2681 }
2682 
2683 static inline bool btintel_pcie_is_rxq_empty(struct btintel_pcie_data *data)
2684 {
2685 	return data->ia.cr_hia[BTINTEL_PCIE_RXQ_NUM] == data->ia.cr_tia[BTINTEL_PCIE_RXQ_NUM];
2686 }
2687 
2688 static inline bool btintel_pcie_is_txackq_empty(struct btintel_pcie_data *data)
2689 {
2690 	return data->ia.cr_tia[BTINTEL_PCIE_TXQ_NUM] == data->ia.cr_hia[BTINTEL_PCIE_TXQ_NUM];
2691 }
2692 
2693 static irqreturn_t btintel_pcie_irq_msix_handler(int irq, void *dev_id)
2694 {
2695 	struct msix_entry *entry = dev_id;
2696 	struct btintel_pcie_data *data = btintel_pcie_get_data(entry);
2697 	u32 intr_fh, intr_hw;
2698 
2699 	spin_lock(&data->irq_lock);
2700 	intr_fh = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_CAUSES);
2701 	intr_hw = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES);
2702 
2703 	/* Clear causes registers to avoid being handling the same cause */
2704 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_CAUSES, intr_fh);
2705 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES, intr_hw);
2706 	spin_unlock(&data->irq_lock);
2707 
2708 	if (unlikely(!(intr_fh | intr_hw))) {
2709 		/* Ignore interrupt, inta == 0 */
2710 		bt_warn_ratelimited("Bluetooth: btintel_pcie: Received spurious interrupt\n");
2711 		btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_AUTOMASK_ST,
2712 				      BIT(entry->entry));
2713 		return IRQ_NONE;
2714 	}
2715 
2716 	/* This interrupt is raised when there is an hardware exception */
2717 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_HWEXP)
2718 		btintel_pcie_msix_hw_exp_handler(data);
2719 
2720 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP1)
2721 		btintel_pcie_msix_gp1_handler(data);
2722 
2723 
2724 	/* For TX */
2725 	if (intr_fh & BTINTEL_PCIE_MSIX_FH_INT_CAUSES_0) {
2726 		btintel_pcie_msix_tx_handle(data);
2727 		if (!btintel_pcie_is_rxq_empty(data))
2728 			btintel_pcie_msix_rx_handle(data);
2729 	}
2730 
2731 	/* For RX */
2732 	if (intr_fh & BTINTEL_PCIE_MSIX_FH_INT_CAUSES_1) {
2733 		btintel_pcie_msix_rx_handle(data);
2734 		if (!btintel_pcie_is_txackq_empty(data))
2735 			btintel_pcie_msix_tx_handle(data);
2736 	}
2737 
2738 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_FWTRIG)
2739 		btintel_pcie_msix_fw_trigger_handler(data);
2740 
2741 	/* This interrupt is triggered by the firmware after updating
2742 	 * boot_stage register and image_response register
2743 	 */
2744 	if (intr_hw & BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0)
2745 		btintel_pcie_msix_gp0_handler(data);
2746 
2747 	/*
2748 	 * Before sending the interrupt the HW disables it to prevent a nested
2749 	 * interrupt. This is done by writing 1 to the corresponding bit in
2750 	 * the mask register. After handling the interrupt, it should be
2751 	 * re-enabled by clearing this bit. This register is defined as write 1
2752 	 * clear (W1C) register, meaning that it's cleared by writing 1
2753 	 * to the bit.
2754 	 */
2755 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_AUTOMASK_ST,
2756 			      BIT(entry->entry));
2757 
2758 	return IRQ_HANDLED;
2759 }
2760 
2761 /* This function requests the irq for MSI-X and registers the handlers per irq.
2762  * Currently, it requests only 1 irq for all interrupt causes.
2763  */
2764 static int btintel_pcie_setup_irq(struct btintel_pcie_data *data)
2765 {
2766 	int err;
2767 	int num_irqs, i, j;
2768 
2769 	for (i = 0; i < BTINTEL_PCIE_MSIX_VEC_MAX; i++)
2770 		data->msix_entries[i].entry = i;
2771 
2772 	num_irqs = pci_alloc_irq_vectors(data->pdev, BTINTEL_PCIE_MSIX_VEC_MIN,
2773 					 BTINTEL_PCIE_MSIX_VEC_MAX, PCI_IRQ_MSIX);
2774 	if (num_irqs < 0)
2775 		return num_irqs;
2776 
2777 	data->alloc_vecs = num_irqs;
2778 	data->msix_enabled = 1;
2779 	data->def_irq = 0;
2780 
2781 	/* setup irq handler */
2782 	for (i = 0; i < data->alloc_vecs; i++) {
2783 		struct msix_entry *msix_entry;
2784 
2785 		msix_entry = &data->msix_entries[i];
2786 		msix_entry->vector = pci_irq_vector(data->pdev, i);
2787 
2788 		err = devm_request_threaded_irq(&data->pdev->dev,
2789 						msix_entry->vector,
2790 						NULL,
2791 						btintel_pcie_irq_msix_handler,
2792 						IRQF_ONESHOT | IRQF_SHARED,
2793 						KBUILD_MODNAME,
2794 						msix_entry);
2795 		if (err) {
2796 			for (j = 0; j < i; j++)
2797 				devm_free_irq(&data->pdev->dev,
2798 					      data->msix_entries[j].vector,
2799 					      &data->msix_entries[j]);
2800 			pci_free_irq_vectors(data->pdev);
2801 			data->alloc_vecs = 0;
2802 			return err;
2803 		}
2804 	}
2805 	return 0;
2806 }
2807 
2808 struct btintel_pcie_causes_list {
2809 	u32 cause;
2810 	u32 mask_reg;
2811 	u8 cause_num;
2812 };
2813 
2814 static struct btintel_pcie_causes_list causes_list[] = {
2815 	{ BTINTEL_PCIE_MSIX_FH_INT_CAUSES_0,	BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK,	0x00 },
2816 	{ BTINTEL_PCIE_MSIX_FH_INT_CAUSES_1,	BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK,	0x01 },
2817 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0,	BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x20 },
2818 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_HWEXP, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x23 },
2819 	{ BTINTEL_PCIE_MSIX_HW_INT_CAUSES_FWTRIG, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK,	0x25 },
2820 };
2821 
2822 /* This function configures the interrupt masks for both HW_INT_CAUSES and
2823  * FH_INT_CAUSES which are meaningful to us.
2824  *
2825  * After resetting BT function via PCIE FLR or FUNC_CTRL reset, the driver
2826  * need to call this function again to configure since the masks
2827  * are reset to 0xFFFFFFFF after reset.
2828  */
2829 static void btintel_pcie_config_msix(struct btintel_pcie_data *data)
2830 {
2831 	int i;
2832 	int val = data->def_irq | BTINTEL_PCIE_MSIX_NON_AUTO_CLEAR_CAUSE;
2833 
2834 	/* Set Non Auto Clear Cause */
2835 	for (i = 0; i < ARRAY_SIZE(causes_list); i++) {
2836 		btintel_pcie_wr_reg8(data,
2837 				     BTINTEL_PCIE_CSR_MSIX_IVAR(causes_list[i].cause_num),
2838 				     val);
2839 		btintel_pcie_clr_reg_bits(data,
2840 					  causes_list[i].mask_reg,
2841 					  causes_list[i].cause);
2842 	}
2843 
2844 	/* Save the initial interrupt mask */
2845 	data->fh_init_mask = ~btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK);
2846 	data->hw_init_mask = ~btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK);
2847 }
2848 
2849 static int btintel_pcie_config_pcie(struct pci_dev *pdev,
2850 				    struct btintel_pcie_data *data)
2851 {
2852 	int err;
2853 
2854 	err = pcim_enable_device(pdev);
2855 	if (err)
2856 		return err;
2857 
2858 	pci_set_master(pdev);
2859 
2860 	err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64));
2861 	if (err) {
2862 		err = dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32));
2863 		if (err)
2864 			return err;
2865 	}
2866 
2867 	data->base_addr = pcim_iomap_region(pdev, 0, KBUILD_MODNAME);
2868 	if (IS_ERR(data->base_addr))
2869 		return PTR_ERR(data->base_addr);
2870 
2871 	/* Do shared hardware reset to ensure a clean start before
2872 	 * configuring interrupts.
2873 	 */
2874 	err = btintel_pcie_reset_bt(data);
2875 	if (err)
2876 		return err;
2877 
2878 	err = btintel_pcie_setup_irq(data);
2879 	if (err)
2880 		return err;
2881 
2882 	/* Configure MSI-X with causes list */
2883 	btintel_pcie_config_msix(data);
2884 
2885 	return 0;
2886 }
2887 
2888 static void btintel_pcie_init_ci(struct btintel_pcie_data *data,
2889 				 struct ctx_info *ci)
2890 {
2891 	ci->version = 0x1;
2892 	ci->size = sizeof(*ci);
2893 	ci->config = 0x0000;
2894 	ci->addr_cr_hia = data->ia.cr_hia_p_addr;
2895 	ci->addr_tr_tia = data->ia.tr_tia_p_addr;
2896 	ci->addr_cr_tia = data->ia.cr_tia_p_addr;
2897 	ci->addr_tr_hia = data->ia.tr_hia_p_addr;
2898 	ci->num_cr_ia = BTINTEL_PCIE_NUM_QUEUES;
2899 	ci->num_tr_ia = BTINTEL_PCIE_NUM_QUEUES;
2900 	ci->addr_urbdq0 = data->txq.urbd0s_p_addr;
2901 	ci->addr_tfdq = data->txq.tfds_p_addr;
2902 	ci->num_tfdq = data->txq.count;
2903 	ci->num_urbdq0 = data->txq.count;
2904 	ci->tfdq_db_vec = BTINTEL_PCIE_TXQ_NUM;
2905 	ci->urbdq0_db_vec = BTINTEL_PCIE_TXQ_NUM;
2906 	ci->rbd_size = BTINTEL_PCIE_RBD_SIZE_4K;
2907 	ci->addr_frbdq = data->rxq.frbds_p_addr;
2908 	ci->num_frbdq = data->rxq.count;
2909 	ci->frbdq_db_vec = BTINTEL_PCIE_RXQ_NUM;
2910 	ci->addr_urbdq1 = data->rxq.urbd1s_p_addr;
2911 	ci->num_urbdq1 = data->rxq.count;
2912 	ci->urbdq_db_vec = BTINTEL_PCIE_RXQ_NUM;
2913 
2914 	ci->dbg_output_mode = btintel_pcie_dbg_to_wifi(data) ?
2915 			      BTINTEL_PCIE_WIFI_DBGC : BTINTEL_PCIE_DRAM;
2916 	if (btintel_pcie_dbg_to_wifi(data)) {
2917 		/* Firmware forwards debug traces to the WiFi DBGC, so no
2918 		 * host DBGC buffer is needed; leave dbgc_addr/size as 0.
2919 		 */
2920 		ci->dbgc_addr = 0;
2921 		ci->dbgc_size = 0;
2922 	} else if (btintel_pcie_is_mdbgc_supported(data)) {
2923 		ci->dbgc_addr = data->mdbgc.frag_p_addr;
2924 		ci->dbgc_size = data->mdbgc.frag_size;
2925 	} else {
2926 		ci->dbgc_addr = data->dbgc.frag_p_addr;
2927 		ci->dbgc_size = data->dbgc.frag_size;
2928 	}
2929 
2930 	ci->dbg_preset = 0x00;
2931 }
2932 
2933 static void btintel_pcie_free_txq_bufs(struct btintel_pcie_data *data,
2934 				       struct txq *txq)
2935 {
2936 	/* Free data buffers first */
2937 	dma_free_coherent(&data->pdev->dev, txq->count * BTINTEL_PCIE_BUFFER_SIZE,
2938 			  txq->buf_v_addr, txq->buf_p_addr);
2939 	kfree(txq->bufs);
2940 }
2941 
2942 static int btintel_pcie_setup_txq_bufs(struct btintel_pcie_data *data,
2943 				       struct txq *txq)
2944 {
2945 	int i;
2946 	struct data_buf *buf;
2947 
2948 	/* Allocate the same number of buffers as the descriptor */
2949 	txq->bufs = kmalloc_objs(*buf, txq->count);
2950 	if (!txq->bufs)
2951 		return -ENOMEM;
2952 
2953 	/* Allocate full chunk of data buffer for DMA first and do indexing and
2954 	 * initialization next, so it can be freed easily
2955 	 */
2956 	txq->buf_v_addr = dma_alloc_coherent(&data->pdev->dev,
2957 					     txq->count * BTINTEL_PCIE_BUFFER_SIZE,
2958 					     &txq->buf_p_addr,
2959 					     GFP_KERNEL | __GFP_NOWARN);
2960 	if (!txq->buf_v_addr) {
2961 		kfree(txq->bufs);
2962 		return -ENOMEM;
2963 	}
2964 
2965 	/* Setup the allocated DMA buffer to bufs. Each data_buf should
2966 	 * have virtual address and physical address
2967 	 */
2968 	for (i = 0; i < txq->count; i++) {
2969 		buf = &txq->bufs[i];
2970 		buf->data_p_addr = txq->buf_p_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
2971 		buf->data = txq->buf_v_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
2972 	}
2973 
2974 	return 0;
2975 }
2976 
2977 static void btintel_pcie_free_rxq_bufs(struct btintel_pcie_data *data,
2978 				       struct rxq *rxq)
2979 {
2980 	/* Free data buffers first */
2981 	dma_free_coherent(&data->pdev->dev, rxq->count * BTINTEL_PCIE_BUFFER_SIZE,
2982 			  rxq->buf_v_addr, rxq->buf_p_addr);
2983 	kfree(rxq->bufs);
2984 }
2985 
2986 static int btintel_pcie_setup_rxq_bufs(struct btintel_pcie_data *data,
2987 				       struct rxq *rxq)
2988 {
2989 	int i;
2990 	struct data_buf *buf;
2991 
2992 	/* Allocate the same number of buffers as the descriptor */
2993 	rxq->bufs = kmalloc_objs(*buf, rxq->count);
2994 	if (!rxq->bufs)
2995 		return -ENOMEM;
2996 
2997 	/* Allocate full chunk of data buffer for DMA first and do indexing and
2998 	 * initialization next, so it can be freed easily
2999 	 */
3000 	rxq->buf_v_addr = dma_alloc_coherent(&data->pdev->dev,
3001 					     rxq->count * BTINTEL_PCIE_BUFFER_SIZE,
3002 					     &rxq->buf_p_addr,
3003 					     GFP_KERNEL | __GFP_NOWARN);
3004 	if (!rxq->buf_v_addr) {
3005 		kfree(rxq->bufs);
3006 		return -ENOMEM;
3007 	}
3008 
3009 	/* Setup the allocated DMA buffer to bufs. Each data_buf should
3010 	 * have virtual address and physical address
3011 	 */
3012 	for (i = 0; i < rxq->count; i++) {
3013 		buf = &rxq->bufs[i];
3014 		buf->data_p_addr = rxq->buf_p_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
3015 		buf->data = rxq->buf_v_addr + (i * BTINTEL_PCIE_BUFFER_SIZE);
3016 	}
3017 
3018 	return 0;
3019 }
3020 
3021 static void btintel_pcie_free(struct btintel_pcie_data *data)
3022 {
3023 	btintel_pcie_free_rxq_bufs(data, &data->rxq);
3024 	btintel_pcie_free_txq_bufs(data, &data->txq);
3025 
3026 	dma_pool_free(data->dma_pool, data->dma_v_addr, data->dma_p_addr);
3027 	dma_pool_destroy(data->dma_pool);
3028 }
3029 
3030 /* Allocate tx and rx queues, any related data structures and buffers.
3031  */
3032 static int btintel_pcie_alloc(struct btintel_pcie_data *data)
3033 {
3034 	int err = 0;
3035 	size_t total;
3036 	dma_addr_t p_addr;
3037 	void *v_addr;
3038 	size_t tfd_size, frbd_size, ctx_size, ci_size, urbd0_size, urbd1_size;
3039 
3040 	/* Allocate the chunk of DMA memory for descriptors, index array, and
3041 	 * context information, instead of allocating individually.
3042 	 * The DMA memory for data buffer is allocated while setting up the
3043 	 * each queue.
3044 	 *
3045 	 * Total size is sum of the following and each of the individual sizes
3046 	 * are aligned to 128 bytes before adding up.
3047 	 *
3048 	 *  + size of TFD * Number of descriptors in queue
3049 	 *  + size of URBD0 * Number of descriptors in queue
3050 	 *  + size of FRBD * Number of descriptors in queue
3051 	 *  + size of URBD1 * Number of descriptors in queue
3052 	 *  + size of index * Number of queues(2) * type of index array(4)
3053 	 *  + size of context information
3054 	 */
3055 	tfd_size = ALIGN(sizeof(struct tfd) * BTINTEL_PCIE_TX_DESCS_COUNT,
3056 			 BTINTEL_PCIE_DMA_ALIGN_128B);
3057 	urbd0_size = ALIGN(sizeof(struct urbd0) * BTINTEL_PCIE_TX_DESCS_COUNT,
3058 			   BTINTEL_PCIE_DMA_ALIGN_128B);
3059 
3060 	frbd_size = ALIGN(sizeof(struct frbd) * BTINTEL_PCIE_RX_DESCS_COUNT,
3061 			  BTINTEL_PCIE_DMA_ALIGN_128B);
3062 	urbd1_size = ALIGN(sizeof(struct urbd1) * BTINTEL_PCIE_RX_DESCS_COUNT,
3063 			   BTINTEL_PCIE_DMA_ALIGN_128B);
3064 
3065 	ci_size = ALIGN(sizeof(u16) * BTINTEL_PCIE_NUM_QUEUES,
3066 			BTINTEL_PCIE_DMA_ALIGN_128B);
3067 
3068 	ctx_size = ALIGN(sizeof(struct ctx_info), BTINTEL_PCIE_DMA_ALIGN_128B);
3069 
3070 	total = tfd_size + urbd0_size + frbd_size + urbd1_size + ctx_size + ci_size * 4;
3071 
3072 	data->dma_pool = dma_pool_create(KBUILD_MODNAME, &data->pdev->dev,
3073 					 total, BTINTEL_PCIE_DMA_ALIGN_128B, 0);
3074 	if (!data->dma_pool) {
3075 		err = -ENOMEM;
3076 		goto exit_error;
3077 	}
3078 
3079 	v_addr = dma_pool_zalloc(data->dma_pool, GFP_KERNEL | __GFP_NOWARN,
3080 				 &p_addr);
3081 	if (!v_addr) {
3082 		dma_pool_destroy(data->dma_pool);
3083 		err = -ENOMEM;
3084 		goto exit_error;
3085 	}
3086 
3087 	data->dma_p_addr = p_addr;
3088 	data->dma_v_addr = v_addr;
3089 
3090 	/* Setup descriptor count */
3091 	data->txq.count = BTINTEL_PCIE_TX_DESCS_COUNT;
3092 	data->rxq.count = BTINTEL_PCIE_RX_DESCS_COUNT;
3093 
3094 	/* Setup tfds */
3095 	data->txq.tfds_p_addr = p_addr;
3096 	data->txq.tfds = v_addr;
3097 
3098 	p_addr += tfd_size;
3099 	v_addr += tfd_size;
3100 
3101 	/* Setup urbd0 */
3102 	data->txq.urbd0s_p_addr = p_addr;
3103 	data->txq.urbd0s = v_addr;
3104 
3105 	p_addr += urbd0_size;
3106 	v_addr += urbd0_size;
3107 
3108 	/* Setup FRBD*/
3109 	data->rxq.frbds_p_addr = p_addr;
3110 	data->rxq.frbds = v_addr;
3111 
3112 	p_addr += frbd_size;
3113 	v_addr += frbd_size;
3114 
3115 	/* Setup urbd1 */
3116 	data->rxq.urbd1s_p_addr = p_addr;
3117 	data->rxq.urbd1s = v_addr;
3118 
3119 	p_addr += urbd1_size;
3120 	v_addr += urbd1_size;
3121 
3122 	/* Setup data buffers for txq */
3123 	err = btintel_pcie_setup_txq_bufs(data, &data->txq);
3124 	if (err)
3125 		goto exit_error_pool;
3126 
3127 	/* Setup data buffers for rxq */
3128 	err = btintel_pcie_setup_rxq_bufs(data, &data->rxq);
3129 	if (err)
3130 		goto exit_error_txq;
3131 
3132 	/* TR Head Index Array */
3133 	data->ia.tr_hia_p_addr = p_addr;
3134 	data->ia.tr_hia = v_addr;
3135 	p_addr += ci_size;
3136 	v_addr += ci_size;
3137 
3138 	/* TR Tail Index Array */
3139 	data->ia.tr_tia_p_addr = p_addr;
3140 	data->ia.tr_tia = v_addr;
3141 	p_addr += ci_size;
3142 	v_addr += ci_size;
3143 
3144 	/* CR Head index Array */
3145 	data->ia.cr_hia_p_addr = p_addr;
3146 	data->ia.cr_hia = v_addr;
3147 	p_addr += ci_size;
3148 	v_addr += ci_size;
3149 
3150 	/* CR Tail Index Array */
3151 	data->ia.cr_tia_p_addr = p_addr;
3152 	data->ia.cr_tia = v_addr;
3153 	p_addr += ci_size;
3154 	v_addr += ci_size;
3155 
3156 	/* Setup data buffers for dbgc */
3157 	if (btintel_pcie_dbg_to_wifi(data)) {
3158 		/* Firmware routes traces to the WiFi DBGC; skip host DBGC
3159 		 * buffer allocation entirely.
3160 		 */
3161 		err = 0;
3162 	} else if (btintel_pcie_is_mdbgc_supported(data)) {
3163 		err = btintel_pcie_setup_mdbgc(data);
3164 	} else {
3165 		err = btintel_pcie_setup_dbgc(data);
3166 	}
3167 	if (err)
3168 		goto exit_error_txq;
3169 
3170 	/* Setup Context Information */
3171 	data->ci = v_addr;
3172 	data->ci_p_addr = p_addr;
3173 
3174 	/* Initialize the CI */
3175 	btintel_pcie_init_ci(data, data->ci);
3176 
3177 	return 0;
3178 
3179 exit_error_txq:
3180 	btintel_pcie_free_txq_bufs(data, &data->txq);
3181 exit_error_pool:
3182 	dma_pool_free(data->dma_pool, data->dma_v_addr, data->dma_p_addr);
3183 	dma_pool_destroy(data->dma_pool);
3184 exit_error:
3185 	return err;
3186 }
3187 
3188 static int btintel_pcie_open(struct hci_dev *hdev)
3189 {
3190 	bt_dev_dbg(hdev, "");
3191 
3192 	return 0;
3193 }
3194 
3195 static int btintel_pcie_close(struct hci_dev *hdev)
3196 {
3197 	bt_dev_dbg(hdev, "");
3198 
3199 	return 0;
3200 }
3201 
3202 static int btintel_pcie_inject_cmd_complete(struct hci_dev *hdev, __u16 opcode)
3203 {
3204 	struct sk_buff *skb;
3205 	struct hci_event_hdr *hdr;
3206 	struct hci_ev_cmd_complete *evt;
3207 
3208 	skb = bt_skb_alloc(sizeof(*hdr) + sizeof(*evt) + 1, GFP_KERNEL);
3209 	if (!skb)
3210 		return -ENOMEM;
3211 
3212 	hdr = (struct hci_event_hdr *)skb_put(skb, sizeof(*hdr));
3213 	hdr->evt = HCI_EV_CMD_COMPLETE;
3214 	hdr->plen = sizeof(*evt) + 1;
3215 
3216 	evt = (struct hci_ev_cmd_complete *)skb_put(skb, sizeof(*evt));
3217 	evt->ncmd = 0x01;
3218 	evt->opcode = cpu_to_le16(opcode);
3219 
3220 	*(u8 *)skb_put(skb, 1) = 0x00;
3221 
3222 	hci_skb_pkt_type(skb) = HCI_EVENT_PKT;
3223 
3224 	return hci_recv_frame(hdev, skb);
3225 }
3226 
3227 static int btintel_pcie_send_frame(struct hci_dev *hdev,
3228 				       struct sk_buff *skb)
3229 {
3230 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3231 	struct hci_command_hdr *cmd;
3232 	__u16 opcode = ~0;
3233 	int ret;
3234 	u32 type;
3235 
3236 	if (test_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags))
3237 		return -ENODEV;
3238 
3239 	if (test_bit(BTINTEL_PCIE_RECOVERY_IN_PROGRESS, &data->flags))
3240 		return -ENODEV;
3241 
3242 	/* Account for the 4-byte PCIe type header prepended before the
3243 	 * DMA copy.  Written as a subtraction to avoid wrap-around on
3244 	 * attacker-controlled skb->len.
3245 	 */
3246 	if (skb->len > BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN) {
3247 		bt_dev_err(hdev, "Packet too large: %u > %u", skb->len,
3248 			   BTINTEL_PCIE_BUFFER_SIZE - BTINTEL_PCIE_HCI_TYPE_LEN);
3249 		return -EMSGSIZE;
3250 	}
3251 
3252 	/* Due to the fw limitation, the type header of the packet should be
3253 	 * 4 bytes unlike 1 byte for UART. In UART, the firmware can read
3254 	 * the first byte to get the packet type and redirect the rest of data
3255 	 * packet to the right handler.
3256 	 *
3257 	 * But for PCIe, THF(Transfer Flow Handler) fetches the 4 bytes of data
3258 	 * from DMA memory and by the time it reads the first 4 bytes, it has
3259 	 * already consumed some part of packet. Thus the packet type indicator
3260 	 * for iBT PCIe is 4 bytes.
3261 	 *
3262 	 * Luckily, when HCI core creates the skb, it allocates 8 bytes of
3263 	 * head room for profile and driver use, and before sending the data
3264 	 * to the device, append the iBT PCIe packet type in the front.
3265 	 */
3266 	switch (hci_skb_pkt_type(skb)) {
3267 	case HCI_COMMAND_PKT:
3268 		type = BTINTEL_PCIE_HCI_CMD_PKT;
3269 		cmd = (void *)skb->data;
3270 		opcode = le16_to_cpu(cmd->opcode);
3271 		if (btintel_test_flag(hdev, INTEL_BOOTLOADER)) {
3272 			struct hci_command_hdr *cmd = (void *)skb->data;
3273 			__u16 opcode = le16_to_cpu(cmd->opcode);
3274 
3275 			/* When the BTINTEL_HCI_OP_RESET command is issued to
3276 			 * boot into the operational firmware, it will actually
3277 			 * not send a command complete event. To keep the flow
3278 			 * control working inject that event here.
3279 			 */
3280 			if (opcode == BTINTEL_HCI_OP_RESET)
3281 				btintel_pcie_inject_cmd_complete(hdev, opcode);
3282 		}
3283 
3284 		hdev->stat.cmd_tx++;
3285 		break;
3286 	case HCI_ACLDATA_PKT:
3287 		type = BTINTEL_PCIE_HCI_ACL_PKT;
3288 		hdev->stat.acl_tx++;
3289 		break;
3290 	case HCI_SCODATA_PKT:
3291 		type = BTINTEL_PCIE_HCI_SCO_PKT;
3292 		hdev->stat.sco_tx++;
3293 		break;
3294 	case HCI_ISODATA_PKT:
3295 		type = BTINTEL_PCIE_HCI_ISO_PKT;
3296 		break;
3297 	default:
3298 		bt_dev_err(hdev, "Unknown HCI packet type");
3299 		return -EILSEQ;
3300 	}
3301 
3302 	ret = btintel_pcie_send_sync(data, skb, type, opcode);
3303 	if (ret) {
3304 		hdev->stat.err_tx++;
3305 		bt_dev_err(hdev, "Failed to send frame (%d)", ret);
3306 		goto exit_error;
3307 	}
3308 
3309 	hdev->stat.byte_tx += skb->len;
3310 	kfree_skb(skb);
3311 
3312 exit_error:
3313 	return ret;
3314 }
3315 
3316 static void btintel_pcie_release_hdev(struct btintel_pcie_data *data)
3317 {
3318 	struct hci_dev *hdev = data->hdev;
3319 
3320 	if (!hdev)
3321 		return;
3322 
3323 	hci_unregister_dev(hdev);
3324 	hci_free_dev(hdev);
3325 	data->hdev = NULL;
3326 }
3327 
3328 static void btintel_pcie_disable_interrupts(struct btintel_pcie_data *data)
3329 {
3330 	spin_lock(&data->irq_lock);
3331 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK, data->fh_init_mask);
3332 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK, data->hw_init_mask);
3333 	spin_unlock(&data->irq_lock);
3334 }
3335 
3336 static void btintel_pcie_enable_interrupts(struct btintel_pcie_data *data)
3337 {
3338 	spin_lock(&data->irq_lock);
3339 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_FH_INT_MASK, ~data->fh_init_mask);
3340 	btintel_pcie_wr_reg32(data, BTINTEL_PCIE_CSR_MSIX_HW_INT_MASK, ~data->hw_init_mask);
3341 	spin_unlock(&data->irq_lock);
3342 }
3343 
3344 static void btintel_pcie_synchronize_irqs(struct btintel_pcie_data *data)
3345 {
3346 	for (int i = 0; i < data->alloc_vecs; i++)
3347 		synchronize_irq(data->msix_entries[i].vector);
3348 }
3349 
3350 static int btintel_pcie_get_debug_info_addr(struct hci_dev *hdev)
3351 {
3352 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3353 	struct btintel_pcie_trigger_evt *evt;
3354 	u8 param[1] = {0x10};
3355 	struct sk_buff *skb;
3356 	int err = 0;
3357 
3358 	skb = __hci_cmd_sync(hdev, BTINTEL_HCI_OP_DEBUG, 1, param,
3359 			     HCI_CMD_TIMEOUT);
3360 	if (IS_ERR(skb)) {
3361 		bt_dev_err(hdev, "Reading Intel read debug info address command failed (%ld)",
3362 			   PTR_ERR(skb));
3363 		/* Not all Intel products supports this command */
3364 		if (PTR_ERR(skb) == -EOPNOTSUPP)
3365 			return 0;
3366 		return PTR_ERR(skb);
3367 	}
3368 
3369 	if (skb->len < (1 + sizeof(*evt))) {
3370 		bt_dev_err(hdev, "Debug info response too short (%u bytes)", skb->len);
3371 		err = -EIO;
3372 		goto exit_error;
3373 	}
3374 
3375 	/* Check the status */
3376 	if (skb->data[0]) {
3377 		bt_dev_err(hdev, "Reading Intel read debug info command failed (0x%2.2x)",
3378 			   skb->data[0]);
3379 		err = -EIO;
3380 		goto exit_error;
3381 	}
3382 
3383 	/* Consume Command Complete Status field */
3384 	skb_pull(skb, 1);
3385 
3386 	evt = (void *)skb->data;
3387 
3388 	data->debug_evt_addr = le32_to_cpu(evt->addr);
3389 	data->debug_evt_size = le32_to_cpu(evt->size);
3390 
3391 	bt_dev_dbg(hdev, "config type: %u config len: %u debug event addr: 0x%8.8x size: 0x%8.8x",
3392 		   evt->type, evt->len, data->debug_evt_addr,
3393 		   data->debug_evt_size);
3394 exit_error:
3395 	kfree_skb(skb);
3396 	return err;
3397 }
3398 
3399 static int btintel_pcie_setup_internal(struct hci_dev *hdev)
3400 {
3401 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3402 	const u8 param[1] = { 0xFF };
3403 	struct intel_version_tlv ver_tlv;
3404 	struct sk_buff *skb;
3405 	int err;
3406 
3407 	BT_DBG("%s", hdev->name);
3408 
3409 	skb = __hci_cmd_sync(hdev, 0xfc05, 1, param, HCI_CMD_TIMEOUT);
3410 	if (IS_ERR(skb)) {
3411 		bt_dev_err(hdev, "Reading Intel version command failed (%ld)",
3412 			   PTR_ERR(skb));
3413 		return PTR_ERR(skb);
3414 	}
3415 
3416 	/* Check the status */
3417 	if (skb->data[0]) {
3418 		bt_dev_err(hdev, "Intel Read Version command failed (%02x)",
3419 			   skb->data[0]);
3420 		err = -EIO;
3421 		goto exit_error;
3422 	}
3423 
3424 	/* Apply the common HCI quirks for Intel device */
3425 	hci_set_quirk(hdev, HCI_QUIRK_STRICT_DUPLICATE_FILTER);
3426 	hci_set_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY);
3427 	hci_set_quirk(hdev, HCI_QUIRK_NON_PERSISTENT_DIAG);
3428 
3429 	/* Set up the quality report callback for Intel devices */
3430 	hdev->set_quality_report = btintel_set_quality_report;
3431 
3432 	memset(&ver_tlv, 0, sizeof(ver_tlv));
3433 	/* For TLV type device, parse the tlv data */
3434 	err = btintel_parse_version_tlv(hdev, &ver_tlv, skb);
3435 	if (err) {
3436 		bt_dev_err(hdev, "Failed to parse TLV version information");
3437 		goto exit_error;
3438 	}
3439 
3440 	data->dmp_hdr.cnvi_bt = ver_tlv.cnvi_bt;
3441 	switch (INTEL_HW_PLATFORM(ver_tlv.cnvi_bt)) {
3442 	case 0x37:
3443 		break;
3444 	default:
3445 		bt_dev_err(hdev, "Unsupported Intel hardware platform (0x%2x)",
3446 			   INTEL_HW_PLATFORM(ver_tlv.cnvi_bt));
3447 		err = -EINVAL;
3448 		goto exit_error;
3449 	}
3450 
3451 	/* Check for supported iBT hardware variants of this firmware
3452 	 * loading method.
3453 	 *
3454 	 * This check has been put in place to ensure correct forward
3455 	 * compatibility options when newer hardware variants come
3456 	 * along.
3457 	 */
3458 	switch (INTEL_HW_VARIANT(ver_tlv.cnvi_bt)) {
3459 	case 0x1e:	/* BzrI */
3460 	case 0x1f:	/* ScP  */
3461 	case 0x20:	/* ScP2 */
3462 	case 0x21:	/* ScP2 F */
3463 	case 0x22:	/* BzrIW */
3464 	case 0x23:	/* DrC */
3465 		/* Display version information of TLV type */
3466 		btintel_version_info_tlv(hdev, &ver_tlv);
3467 
3468 		/* Apply the device specific HCI quirks for TLV based devices
3469 		 *
3470 		 * All TLV based devices support WBS
3471 		 */
3472 		hci_set_quirk(hdev, HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED);
3473 
3474 		/* Setup MSFT Extension support */
3475 		btintel_set_msft_opcode(hdev,
3476 					INTEL_HW_VARIANT(ver_tlv.cnvi_bt));
3477 
3478 		err = btintel_bootloader_setup_tlv(hdev, &ver_tlv);
3479 		if (err)
3480 			goto exit_error;
3481 		break;
3482 	default:
3483 		bt_dev_err(hdev, "Unsupported Intel hw variant (%u)",
3484 			   INTEL_HW_VARIANT(ver_tlv.cnvi_bt));
3485 		err = -EINVAL;
3486 		goto exit_error;
3487 	}
3488 
3489 	data->dmp_hdr.cnvi_top = ver_tlv.cnvi_top;
3490 	data->dmp_hdr.cnvr_top = ver_tlv.cnvr_top;
3491 	data->dmp_hdr.fw_timestamp = ver_tlv.timestamp;
3492 	data->dmp_hdr.fw_build_type = ver_tlv.build_type;
3493 	data->dmp_hdr.fw_build_num = ver_tlv.build_num;
3494 
3495 	if (ver_tlv.img_type == 0x02 || ver_tlv.img_type == 0x03)
3496 		data->dmp_hdr.fw_sha = ver_tlv.git_sha1;
3497 
3498 	err = btintel_pcie_get_debug_info_addr(hdev);
3499 	if (err)
3500 		goto exit_error;
3501 
3502 	btintel_print_fseq_info(hdev);
3503 exit_error:
3504 	kfree_skb(skb);
3505 
3506 	return err;
3507 }
3508 
3509 static int btintel_pcie_setup(struct hci_dev *hdev)
3510 {
3511 	int err, fw_dl_retry = 0;
3512 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3513 
3514 	while ((err = btintel_pcie_setup_internal(hdev)) && fw_dl_retry++ < 1) {
3515 		bt_dev_err(hdev, "Firmware download retry count: %d",
3516 			   fw_dl_retry);
3517 		btintel_pcie_dump_debug_registers(hdev);
3518 		btintel_pcie_disable_interrupts(data);
3519 		btintel_pcie_synchronize_irqs(data);
3520 		err = btintel_pcie_reset_bt(data);
3521 		if (err) {
3522 			bt_dev_err(hdev, "Failed to do shr reset: %d", err);
3523 			break;
3524 		}
3525 		usleep_range(10000, 12000);
3526 		btintel_pcie_reset_ia(data);
3527 		btintel_pcie_enable_interrupts(data);
3528 		btintel_pcie_config_msix(data);
3529 		err = btintel_pcie_enable_bt(data);
3530 		if (err) {
3531 			bt_dev_err(hdev, "Failed to enable hardware: %d", err);
3532 			break;
3533 		}
3534 		btintel_pcie_start_rx(data);
3535 	}
3536 
3537 	if (!err)
3538 		set_bit(BTINTEL_PCIE_SETUP_DONE, &data->flags);
3539 	return err;
3540 }
3541 
3542 static struct btintel_pcie_dev_recovery *
3543 btintel_pcie_get_recovery(struct pci_dev *pdev, struct device *dev)
3544 {
3545 	struct btintel_pcie_dev_recovery *tmp, *data = NULL;
3546 	const char *name = pci_name(pdev);
3547 	const size_t name_len = strlen(name) + 1;
3548 	struct hci_dev *hdev = to_hci_dev(dev);
3549 
3550 	spin_lock(&btintel_pcie_recovery_lock);
3551 	list_for_each_entry(tmp, &btintel_pcie_recovery_list, list) {
3552 		if (strcmp(tmp->name, name))
3553 			continue;
3554 		data = tmp;
3555 		break;
3556 	}
3557 	spin_unlock(&btintel_pcie_recovery_lock);
3558 
3559 	if (data) {
3560 		bt_dev_dbg(hdev, "Found restart data for BDF: %s", data->name);
3561 		return data;
3562 	}
3563 
3564 	data = kzalloc_flex(*data, name, name_len, GFP_ATOMIC);
3565 	if (!data)
3566 		return NULL;
3567 
3568 	strscpy(data->name, name, name_len);
3569 	spin_lock(&btintel_pcie_recovery_lock);
3570 	list_add_tail(&data->list, &btintel_pcie_recovery_list);
3571 	spin_unlock(&btintel_pcie_recovery_lock);
3572 
3573 	return data;
3574 }
3575 
3576 static void btintel_pcie_free_restart_list(void)
3577 {
3578 	struct btintel_pcie_dev_recovery *tmp;
3579 
3580 	while ((tmp = list_first_entry_or_null(&btintel_pcie_recovery_list,
3581 					       typeof(*tmp), list))) {
3582 		list_del(&tmp->list);
3583 		kfree(tmp);
3584 	}
3585 }
3586 
3587 static void btintel_pcie_inc_recovery_count(struct pci_dev *pdev,
3588 					    struct device *dev)
3589 {
3590 	struct btintel_pcie_dev_recovery *data;
3591 	time64_t retry_window;
3592 
3593 	data = btintel_pcie_get_recovery(pdev, dev);
3594 	if (!data)
3595 		return;
3596 
3597 	retry_window = ktime_get_boottime_seconds() - data->last_error;
3598 	if (data->count == 0) {
3599 		data->last_error = ktime_get_boottime_seconds();
3600 		data->count++;
3601 	} else if (retry_window < BTINTEL_PCIE_RESET_WINDOW_SECS &&
3602 		   data->count <= BTINTEL_PCIE_FLR_MAX_RETRY) {
3603 		data->count++;
3604 	} else if (retry_window > BTINTEL_PCIE_RESET_WINDOW_SECS) {
3605 		data->last_error = 0;
3606 		data->count = 0;
3607 	}
3608 }
3609 
3610 static int btintel_pcie_acpi_reset_method(struct btintel_pcie_data *data)
3611 {
3612 	union acpi_object *obj, argv4;
3613 	acpi_handle handle;
3614 	int ret;
3615 	struct pldr_mode {
3616 		__le16	cmd_type;
3617 		__le16	cmd_payload;
3618 	} __packed;
3619 
3620 	/* set 1 for _PRR mode
3621 	 * Product Reset (PLDR Abort flow)
3622 	 */
3623 	static const struct pldr_mode mode = {
3624 		.cmd_type = cpu_to_le16(1),
3625 		.cmd_payload = cpu_to_le16(BTINTEL_PCIE_DSM_PLDR_MODE_EN_PROD_RESET |
3626 			       BTINTEL_PCIE_DSM_PLDR_MODE_EN_WIFI_FLR),
3627 	};
3628 	struct hci_dev *hdev = data->hdev;
3629 
3630 	handle = ACPI_HANDLE(GET_HCIDEV_DEV(data->hdev));
3631 	if (!handle) {
3632 		bt_dev_err(data->hdev, "No support for bluetooth device in ACPI firmware");
3633 		return -EACCES;
3634 	}
3635 
3636 	if (!acpi_has_method(handle, "_PRR")) {
3637 		bt_dev_err(data->hdev, "No support for _PRR ACPI method, cold boot");
3638 		return -ENODEV;
3639 	}
3640 
3641 	argv4.buffer.type = ACPI_TYPE_BUFFER;
3642 	argv4.buffer.length = sizeof(mode);
3643 	argv4.buffer.pointer = (void *)&mode;
3644 
3645 	obj = acpi_evaluate_dsm(handle, &btintel_guid_dsm, 0,
3646 				BTINTEL_PCIE_DSM_DYNAMIC_PLDR, &argv4);
3647 	if (!obj) {
3648 		bt_dev_err(data->hdev, "Failed to call dsm to set reset method");
3649 		return -EIO;
3650 	}
3651 	ACPI_FREE(obj);
3652 
3653 	pci_dev_lock(data->pdev);
3654 	pci_save_state(data->pdev);
3655 	ret = btintel_acpi_reset_method(hdev);
3656 	if (ret)
3657 		bt_dev_err(data->hdev, "ACPI _PRR reset failed (%d), PLDR incomplete",
3658 			   ret);
3659 	pci_restore_state(data->pdev);
3660 	pci_dev_unlock(data->pdev);
3661 	return ret;
3662 }
3663 
3664 static void btintel_pcie_perform_pldr(struct btintel_pcie_data *data)
3665 {
3666 	struct pci_dev *pdev = data->pdev;
3667 	struct pci_dev *wifi = NULL;
3668 	struct pci_bus *bus;
3669 	int ret;
3670 	/* on integrated we have to look up by ID (same bus) */
3671 	static const struct pci_device_id wifi_device_ids[] = {
3672 	#define WIFI_DEV(_id) { PCI_DEVICE(PCI_VENDOR_ID_INTEL, _id) }
3673 		WIFI_DEV(0xA840), /* LNL */
3674 		WIFI_DEV(0xE440), /* PTL-P */
3675 		WIFI_DEV(0xE340), /* PTL-H */
3676 		WIFI_DEV(0xD340), /* NVL-H */
3677 		WIFI_DEV(0x6E70), /* NVL-S */
3678 		WIFI_DEV(0x4D40), /* WCL */
3679 		{}
3680 	};
3681 	struct pci_dev *tmp = NULL;
3682 
3683 	bus = pdev->bus;
3684 	if (!bus)
3685 		return;
3686 
3687 	list_for_each_entry(tmp, &bus->devices, bus_list) {
3688 		if (pci_match_id(wifi_device_ids, tmp)) {
3689 			wifi = pci_dev_get(tmp);
3690 			break;
3691 		}
3692 	}
3693 
3694 	if (wifi)
3695 		device_release_driver(&wifi->dev);
3696 
3697 	/* Wi-Fi is fully unbound before the reset and fully reprobed after
3698 	 * the normal PCI probe path handles all state setup from scratch.
3699 	 * BT needs pci_save_state()/pci_restore_state() because the BT driver
3700 	 * is still partially attached when the _PRR runs (it hasn't been unbound yet).
3701 	 * The PCI device needs to remain minimally functional so that
3702 	 * device_reprobe(&pdev->dev) can work afterward
3703 	 */
3704 	ret = btintel_pcie_acpi_reset_method(data);
3705 
3706 	if (wifi) {
3707 		if (device_reprobe(&wifi->dev))
3708 			BT_ERR("WiFi reprobe failed for BDF:%s", pci_name(wifi));
3709 		pci_dev_put(wifi);
3710 	}
3711 
3712 	if (!ret) {
3713 		if (device_reprobe(&pdev->dev))
3714 			BT_ERR("BT reprobe failed for BDF:%s", pci_name(pdev));
3715 	}
3716 }
3717 
3718 /*
3719  * Issue a Function Level Reset and hand teardown/re-init off to the PCI
3720  * core via device_reprobe(), mirroring the PLDR path's contract.
3721  *
3722  * Caller must hold pci_lock_rescan_remove() and must have already
3723  * disabled interrupts and drained both rx_work and coredump_work.
3724  */
3725 static int btintel_pcie_perform_flr(struct btintel_pcie_data *data)
3726 {
3727 	struct pci_dev *pdev = data->pdev;
3728 	int err;
3729 
3730 	/* pci_try_reset_function() avoids the device_lock ABBA against
3731 	 * btintel_pcie_remove(): .remove() runs with device_lock held and
3732 	 * then waits for this work via disable_work_sync(); the blocking
3733 	 * pci_reset_function() would deadlock by trying to re-acquire
3734 	 * device_lock here.
3735 	 */
3736 	err = pci_try_reset_function(pdev);
3737 	if (err) {
3738 		BT_ERR("Failed resetting the pcie device (%d)", err);
3739 		return err;
3740 	}
3741 
3742 	/* device_reprobe() always detaches the driver first (running
3743 	 * .remove(), which frees 'data'); any re-probe failure leaves the
3744 	 * device unbound but 'data' is already gone, so just log it.
3745 	 */
3746 	if (device_reprobe(&pdev->dev))
3747 		BT_ERR("BT reprobe failed for BDF:%s", pci_name(pdev));
3748 
3749 	return 0;
3750 }
3751 
3752 static void btintel_pcie_reset_work(struct work_struct *wk)
3753 {
3754 	struct btintel_pcie_data *data =
3755 		container_of(wk, struct btintel_pcie_data, reset_work);
3756 	struct pci_dev *pdev = data->pdev;
3757 
3758 	pci_lock_rescan_remove();
3759 
3760 	if (!pdev->bus)
3761 		goto out;
3762 
3763 	if (!data)
3764 		goto out;
3765 
3766 	btintel_pcie_disable_interrupts(data);
3767 	btintel_pcie_synchronize_irqs(data);
3768 
3769 	flush_work(&data->rx_work);
3770 	/* Drain any in-flight dump workers and block new ones across reset.
3771 	 * Safe from self-deadlock: they all run on a separate wq.
3772 	 */
3773 	disable_work_sync(&data->coredump_work);
3774 	disable_work_sync(&data->hwexp_work);
3775 	disable_work_sync(&data->fwtrigger_work);
3776 	disable_work_sync(&data->mbox_work);
3777 
3778 	bt_dev_dbg(data->hdev, "Release bluetooth interface");
3779 
3780 	/* Both reset paths follow the same contract: on success they
3781 	 * destroy 'data' via device_reprobe() (a fresh probe re-INIT_WORKs
3782 	 * the dump workers with disable count 0), so enable_work() must
3783 	 * NOT be called on the success path. Only the FLR path can fail
3784 	 * with 'data' still alive, in which case we balance the
3785 	 * disable_work_sync() calls above so a later successful reset is
3786 	 * not permanently blocked.
3787 	 *
3788 	 * pci_lock_rescan_remove() (held above) serializes against PCI
3789 	 * device addition/removal (hotplug), so no device can be added to
3790 	 * or removed from the bus list while this code runs.
3791 	 */
3792 	if (data->reset_type == BTINTEL_PCIE_IOSF_PRR_PLDR) {
3793 		btintel_pcie_perform_pldr(data);
3794 		goto out;
3795 	}
3796 
3797 	if (btintel_pcie_perform_flr(data)) {
3798 		enable_work(&data->coredump_work);
3799 		enable_work(&data->hwexp_work);
3800 		enable_work(&data->fwtrigger_work);
3801 		enable_work(&data->mbox_work);
3802 	}
3803 
3804 out:
3805 	pci_dev_put(pdev);
3806 	pci_unlock_rescan_remove();
3807 }
3808 
3809 /* Schedule a device reset of the requested type.
3810  *
3811  * BTINTEL_PCIE_RECOVERY_IN_PROGRESS serializes all reset requesters
3812  * (sysfs reset attribute, hci_cmd_timeout(), hw_error, resume error
3813  * path, etc.) so that:
3814  *
3815  *   - dev_data->reset_type is written by exactly one caller (the
3816  *     thread that wins test_and_set_bit), eliminating the race where
3817  *     a second hw_error could clobber an already-scheduled reset's
3818  *     type;
3819  *   - the write happens AFTER the bit is set, so reset_work observes
3820  *     it through schedule_work()'s memory ordering;
3821  *   - losers return without touching reset_type or scheduling the
3822  *     work, so concurrent triggers are silently coalesced into the
3823  *     in-flight one (whose recovery will reinitialize the device
3824  *     regardless of the dropped trigger's variant).
3825  *
3826  * The bit is cleared only by .remove() / re-probe via fresh devm
3827  * allocation, which is the intended one-shot semantics: a reset
3828  * tears down and re-probes 'data', so there is no "in-flight"
3829  * reset to follow up after device_reprobe() succeeds.
3830  */
3831 static void btintel_pcie_request_reset(struct btintel_pcie_data *data,
3832 				       enum btintel_pcie_reset_type type)
3833 {
3834 	if (!test_bit(BTINTEL_PCIE_SETUP_DONE, &data->flags))
3835 		return;
3836 
3837 	if (test_and_set_bit(BTINTEL_PCIE_RECOVERY_IN_PROGRESS, &data->flags))
3838 		return;
3839 
3840 	data->reset_type = type;
3841 
3842 	pci_dev_get(data->pdev);
3843 	schedule_work(&data->reset_work);
3844 }
3845 
3846 static void btintel_pcie_hci_reset(struct hci_dev *hdev)
3847 {
3848 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3849 
3850 	btintel_pcie_request_reset(data, BTINTEL_PCIE_IOSF_PRR_FLR);
3851 }
3852 
3853 static ssize_t vendor_reset_store(struct device *dev,
3854 				  struct device_attribute *attr,
3855 				  const char *buf, size_t count)
3856 {
3857 	unsigned int val;
3858 	struct pci_dev *pdev = to_pci_dev(dev);
3859 	struct btintel_pcie_data *data = pci_get_drvdata(pdev);
3860 
3861 	if (!data || !data->hdev)
3862 		return -ENODEV;
3863 
3864 	if (kstrtouint(buf, 10, &val) || val != 0) {
3865 		bt_dev_warn(data->hdev, "PLDR rejected: invalid input");
3866 		return -EINVAL;
3867 	}
3868 
3869 	bt_dev_info(data->hdev, "PLDR triggered via sysfs");
3870 	btintel_pcie_request_reset(data, BTINTEL_PCIE_IOSF_PRR_PLDR);
3871 
3872 	return count;
3873 }
3874 
3875 static ssize_t vendor_reset_show(struct device *dev,
3876 				 struct device_attribute *attr, char *buf)
3877 {
3878 	return sysfs_emit(buf, "0 - PLDR\n");
3879 }
3880 
3881 static DEVICE_ATTR_RW(vendor_reset);
3882 
3883 static struct attribute *btintel_pcie_attrs[] = {
3884 	&dev_attr_vendor_reset.attr,
3885 	NULL,
3886 };
3887 
3888 ATTRIBUTE_GROUPS(btintel_pcie);
3889 
3890 static void btintel_pcie_hw_error(struct hci_dev *hdev, u8 code)
3891 {
3892 	struct btintel_pcie_dev_recovery *rec;
3893 	struct btintel_pcie_data *dev_data = hci_get_drvdata(hdev);
3894 	struct pci_dev *pdev = dev_data->pdev;
3895 	enum btintel_pcie_reset_type type;
3896 	time64_t retry_window;
3897 
3898 	if (test_bit(BTINTEL_PCIE_RECOVERY_IN_PROGRESS, &dev_data->flags))
3899 		return;
3900 
3901 	btintel_pcie_dump_debug_registers(hdev);
3902 
3903 	rec = btintel_pcie_get_recovery(pdev, &hdev->dev);
3904 	if (!rec)
3905 		return;
3906 
3907 	type = (code == 0x13) ? BTINTEL_PCIE_IOSF_PRR_PLDR
3908 			      : BTINTEL_PCIE_IOSF_PRR_FLR;
3909 
3910 	bt_dev_err(hdev, "Encountered exception err:0x%x triggering: %s", code,
3911 		   type == BTINTEL_PCIE_IOSF_PRR_PLDR ? "PLDR" : "FLR");
3912 	retry_window = ktime_get_boottime_seconds() - rec->last_error;
3913 
3914 	if (retry_window < BTINTEL_PCIE_RESET_WINDOW_SECS &&
3915 	    rec->count >= BTINTEL_PCIE_FLR_MAX_RETRY) {
3916 		bt_dev_err(hdev, "Exhausted maximum: %d recovery attempts: %d",
3917 			   BTINTEL_PCIE_FLR_MAX_RETRY, rec->count);
3918 		bt_dev_dbg(hdev, "Boot time: %lld seconds",
3919 			   ktime_get_boottime_seconds());
3920 		bt_dev_dbg(hdev, "last error at: %lld seconds",
3921 			   rec->last_error);
3922 		return;
3923 	}
3924 	btintel_pcie_inc_recovery_count(pdev, &hdev->dev);
3925 	btintel_pcie_request_reset(dev_data, type);
3926 }
3927 
3928 static bool btintel_pcie_wakeup(struct hci_dev *hdev)
3929 {
3930 	struct btintel_pcie_data *data = hci_get_drvdata(hdev);
3931 
3932 	return device_may_wakeup(&data->pdev->dev);
3933 }
3934 
3935 static const struct {
3936 	u16 opcode;
3937 	const char *desc;
3938 } btintel_pcie_hci_drv_supported_commands[] = {
3939 	/* Common commands */
3940 	{ HCI_DRV_OP_READ_INFO, "Read Info" },
3941 };
3942 
3943 static int btintel_pcie_hci_drv_read_info(struct hci_dev *hdev, void *data,
3944 					  u16 data_len)
3945 {
3946 	struct hci_drv_rp_read_info *rp;
3947 	size_t rp_size;
3948 	int err, i;
3949 	u16 opcode, num_supported_commands =
3950 		ARRAY_SIZE(btintel_pcie_hci_drv_supported_commands);
3951 
3952 	rp_size = struct_size(rp, supported_commands, num_supported_commands);
3953 
3954 	rp = kmalloc(rp_size, GFP_KERNEL);
3955 	if (!rp)
3956 		return -ENOMEM;
3957 
3958 	strscpy_pad(rp->driver_name, KBUILD_MODNAME);
3959 
3960 	rp->num_supported_commands = cpu_to_le16(num_supported_commands);
3961 	for (i = 0; i < num_supported_commands; i++) {
3962 		opcode = btintel_pcie_hci_drv_supported_commands[i].opcode;
3963 		bt_dev_dbg(hdev,
3964 			    "Supported HCI Drv command (0x%02x|0x%04x): %s",
3965 			    hci_opcode_ogf(opcode),
3966 			    hci_opcode_ocf(opcode),
3967 			    btintel_pcie_hci_drv_supported_commands[i].desc);
3968 		rp->supported_commands[i] = cpu_to_le16(opcode);
3969 	}
3970 
3971 	err = hci_drv_cmd_complete(hdev, HCI_DRV_OP_READ_INFO,
3972 				   HCI_DRV_STATUS_SUCCESS,
3973 				   rp, rp_size);
3974 
3975 	kfree(rp);
3976 	return err;
3977 }
3978 
3979 static const struct hci_drv_handler btintel_pcie_hci_drv_common_handlers[] = {
3980 	{ btintel_pcie_hci_drv_read_info,       HCI_DRV_READ_INFO_SIZE },
3981 };
3982 
3983 static const struct hci_drv_handler btintel_pcie_hci_drv_specific_handlers[] = {};
3984 
3985 static struct hci_drv btintel_pcie_hci_drv = {
3986 	.common_handler_count   = ARRAY_SIZE(btintel_pcie_hci_drv_common_handlers),
3987 	.common_handlers        = btintel_pcie_hci_drv_common_handlers,
3988 	.specific_handler_count = ARRAY_SIZE(btintel_pcie_hci_drv_specific_handlers),
3989 	.specific_handlers      = btintel_pcie_hci_drv_specific_handlers,
3990 };
3991 
3992 static int btintel_pcie_setup_hdev(struct btintel_pcie_data *data)
3993 {
3994 	int err;
3995 	struct hci_dev *hdev;
3996 
3997 	hdev = hci_alloc_dev_priv(sizeof(struct btintel_data));
3998 	if (!hdev)
3999 		return -ENOMEM;
4000 
4001 	hdev->bus = HCI_PCI;
4002 	hci_set_drvdata(hdev, data);
4003 
4004 	SET_HCIDEV_DEV(hdev, &data->pdev->dev);
4005 
4006 	hdev->manufacturer = 2;
4007 	hdev->open = btintel_pcie_open;
4008 	hdev->close = btintel_pcie_close;
4009 	hdev->send = btintel_pcie_send_frame;
4010 	hdev->setup = btintel_pcie_setup;
4011 	hdev->shutdown = btintel_shutdown_combined;
4012 	hdev->hw_error = btintel_pcie_hw_error;
4013 	hdev->set_diag = btintel_set_diag;
4014 	hdev->set_bdaddr = btintel_set_bdaddr;
4015 	hdev->reset = btintel_pcie_hci_reset;
4016 	hdev->wakeup = btintel_pcie_wakeup;
4017 	hdev->hci_drv = &btintel_pcie_hci_drv;
4018 
4019 	err = hci_register_dev(hdev);
4020 	if (err < 0) {
4021 		BT_ERR("Failed to register to hdev (%d)", err);
4022 		hci_free_dev(hdev);
4023 		return err;
4024 	}
4025 
4026 	/* Publish hdev only after successful registration; the coredump
4027 	 * worker bails on !data->hdev, so it never observes a half-set-up
4028 	 * device.
4029 	 */
4030 	data->hdev = hdev;
4031 	data->dmp_hdr.driver_name = KBUILD_MODNAME;
4032 	return 0;
4033 }
4034 
4035 static int btintel_pcie_probe(struct pci_dev *pdev,
4036 			      const struct pci_device_id *ent)
4037 {
4038 	int err;
4039 	struct btintel_pcie_data *data;
4040 
4041 	if (!pdev)
4042 		return -ENODEV;
4043 
4044 	data = devm_kzalloc_obj(&pdev->dev, *data);
4045 	if (!data)
4046 		return -ENOMEM;
4047 
4048 	data->pdev = pdev;
4049 
4050 	spin_lock_init(&data->irq_lock);
4051 	spin_lock_init(&data->hci_rx_lock);
4052 
4053 	init_waitqueue_head(&data->gp0_wait_q);
4054 	data->gp0_received = false;
4055 
4056 	init_waitqueue_head(&data->tx_wait_q);
4057 	data->tx_wait_done = false;
4058 
4059 	init_waitqueue_head(&data->mbox_parse_wait_q);
4060 
4061 	data->workqueue = alloc_ordered_workqueue(KBUILD_MODNAME, WQ_HIGHPRI);
4062 	if (!data->workqueue)
4063 		return -ENOMEM;
4064 
4065 	data->dump_workqueue = alloc_ordered_workqueue(KBUILD_MODNAME "_cd", 0);
4066 	if (!data->dump_workqueue) {
4067 		destroy_workqueue(data->workqueue);
4068 		return -ENOMEM;
4069 	}
4070 
4071 	skb_queue_head_init(&data->rx_skb_q);
4072 	INIT_WORK(&data->rx_work, btintel_pcie_rx_work);
4073 	INIT_WORK(&data->reset_work, btintel_pcie_reset_work);
4074 	INIT_WORK(&data->coredump_work, btintel_pcie_coredump_worker);
4075 	INIT_WORK(&data->hwexp_work, btintel_pcie_hwexp_worker);
4076 	INIT_WORK(&data->fwtrigger_work, btintel_pcie_fwtrigger_worker);
4077 	INIT_WORK(&data->mbox_work, btintel_pcie_mbox_worker);
4078 
4079 	data->boot_stage_cache = 0x00;
4080 	data->img_resp_cache = 0x00;
4081 	data->dbg_path_cache = BTINTEL_PCIE_WIFI_DBGC;
4082 	/* FLR can be invoked by echoing to debugfs path, so explicitly
4083 	 * initialized
4084 	 */
4085 	data->reset_type = BTINTEL_PCIE_IOSF_PRR_FLR;
4086 	err = btintel_pcie_config_pcie(pdev, data);
4087 	if (err)
4088 		goto exit_error;
4089 
4090 	pci_set_drvdata(pdev, data);
4091 
4092 	err = btintel_pcie_alloc(data);
4093 	if (err)
4094 		goto exit_error;
4095 
4096 	err = btintel_pcie_enable_bt(data);
4097 	if (err)
4098 		goto exit_error;
4099 
4100 	/* CNV information (CNVi and CNVr) is in CSR */
4101 	data->cnvi = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_HW_REV_REG);
4102 
4103 	data->cnvr = btintel_pcie_rd_reg32(data, BTINTEL_PCIE_CSR_RF_ID_REG);
4104 
4105 	err = btintel_pcie_start_rx(data);
4106 	if (err)
4107 		goto exit_error;
4108 
4109 	err = btintel_pcie_setup_hdev(data);
4110 	if (err)
4111 		goto exit_error;
4112 
4113 	bt_dev_dbg(data->hdev, "cnvi: 0x%8.8x cnvr: 0x%8.8x", data->cnvi,
4114 		   data->cnvr);
4115 	return 0;
4116 
4117 exit_error:
4118 	/* reset device before exit */
4119 	btintel_pcie_reset_bt(data);
4120 
4121 	destroy_workqueue(data->dump_workqueue);
4122 
4123 	pci_clear_master(pdev);
4124 
4125 	pci_set_drvdata(pdev, NULL);
4126 
4127 	return err;
4128 }
4129 
4130 static void btintel_pcie_remove(struct pci_dev *pdev)
4131 {
4132 	struct btintel_pcie_data *data;
4133 
4134 	data = pci_get_drvdata(pdev);
4135 	if (!data) {
4136 		BT_WARN("PCI driver data is NULL, aborting remove");
4137 		return;
4138 	}
4139 
4140 	/* Permanently block all dump triggers and drain the workers before
4141 	 * tearing down. Must run before disable_work_sync(&reset_work) so
4142 	 * the disable counters stay >= 1 even after reset_work()'s
4143 	 * balanced enable_work() (counter 2 -> 1, never reaching 0).
4144 	 */
4145 	disable_work_sync(&data->coredump_work);
4146 	disable_work_sync(&data->hwexp_work);
4147 	disable_work_sync(&data->fwtrigger_work);
4148 	disable_work_sync(&data->mbox_work);
4149 
4150 	/* Cancel pending reset work. Skip only when remove() is called from
4151 	 * within the reset work itself (PLDR device_reprobe path) to avoid
4152 	 * deadlock. current_work() returns the work_struct of the caller if
4153 	 * we are in a workqueue context.
4154 	 */
4155 	if (current_work() != &data->reset_work)
4156 		disable_work_sync(&data->reset_work);
4157 
4158 	btintel_pcie_disable_interrupts(data);
4159 
4160 	btintel_pcie_synchronize_irqs(data);
4161 
4162 	flush_work(&data->rx_work);
4163 
4164 	btintel_pcie_reset_bt(data);
4165 	for (int i = 0; i < data->alloc_vecs; i++) {
4166 		struct msix_entry *msix_entry;
4167 
4168 		msix_entry = &data->msix_entries[i];
4169 		devm_free_irq(&pdev->dev, msix_entry->vector, msix_entry);
4170 	}
4171 
4172 	pci_free_irq_vectors(pdev);
4173 
4174 	btintel_pcie_release_hdev(data);
4175 
4176 	destroy_workqueue(data->dump_workqueue);
4177 	destroy_workqueue(data->workqueue);
4178 
4179 	btintel_pcie_free(data);
4180 
4181 	pci_clear_master(pdev);
4182 
4183 	pci_set_drvdata(pdev, NULL);
4184 }
4185 
4186 #ifdef CONFIG_DEV_COREDUMP
4187 static void btintel_pcie_coredump(struct device *dev)
4188 {
4189 	struct  pci_dev *pdev = to_pci_dev(dev);
4190 	struct btintel_pcie_data *data = pci_get_drvdata(pdev);
4191 
4192 	if (!data)
4193 		return;
4194 
4195 	btintel_pcie_queue_coredump(data,
4196 				    BTINTEL_PCIE_TRIGGER_REASON_USER_TRIGGER);
4197 }
4198 #endif
4199 
4200 static int btintel_pcie_set_dxstate(struct btintel_pcie_data *data, u32 dxstate)
4201 {
4202 	int retry = 0, err;
4203 	long status;
4204 	u32 dx_intr_timeout_ms = 200;
4205 
4206 	do {
4207 		data->gp0_received = false;
4208 
4209 		btintel_pcie_wr_sleep_cntrl(data, dxstate);
4210 
4211 		status = wait_event_timeout(data->gp0_wait_q, data->gp0_received,
4212 			msecs_to_jiffies(dx_intr_timeout_ms));
4213 
4214 		if (!status) {
4215 			bt_dev_warn(data->hdev,
4216 				    "Timeout (%u ms) on alive interrupt for D%d entry, retry count %d",
4217 				    dx_intr_timeout_ms, dxstate, retry);
4218 
4219 			/* MSIX_HW_INT_CAUSES is W1C. Write only GP0 so other
4220 			 * pending causes are not acknowledged here.
4221 			 */
4222 			btintel_pcie_wr_reg32(data,
4223 					      BTINTEL_PCIE_CSR_MSIX_HW_INT_CAUSES,
4224 					      BTINTEL_PCIE_MSIX_HW_INT_CAUSES_GP0);
4225 		}
4226 
4227 		/* gp0_received is set at the top of the handler, before the switch on
4228 		 * alive_intr_ctxt. Error and lockdown are filtered out above it, but a
4229 		 * matched case can still complete without doing anything - D3 breaks
4230 		 * unchanged while the controller has not reached D0 - and a hardware
4231 		 * bug may drop the interrupt outright. Either way the flag says a gp0
4232 		 * was handled, not that the transition completed, and only the register
4233 		 * knows. Refresh the cache here and retry only if the state check still
4234 		 * fails.
4235 		 */
4236 		data->boot_stage_cache = btintel_pcie_rd_reg32(data,
4237 							       BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
4238 		if (dxstate == BTINTEL_PCIE_STATE_D0) {
4239 			if (btintel_pcie_in_d0(data)) {
4240 				bool armed;
4241 
4242 				/* Claim the transition under irq_lock so a
4243 				 * concurrent gp0 handler run cannot also arm RX.
4244 				 */
4245 				spin_lock(&data->irq_lock);
4246 				armed = data->alive_intr_ctxt == BTINTEL_PCIE_D0;
4247 				if (!armed)
4248 					data->alive_intr_ctxt = BTINTEL_PCIE_D0;
4249 				spin_unlock(&data->irq_lock);
4250 
4251 				if (armed)
4252 					return 0;
4253 
4254 				/* Do what the handler's D3 -> D0 branch
4255 				 * would have done, unless it already has.
4256 				 */
4257 				btintel_pcie_reset_ia(data);
4258 				err = btintel_pcie_start_rx(data);
4259 				if (err)
4260 					return err;
4261 
4262 				/* Complete the mbox<->alive handshake */
4263 				if (test_and_clear_bit(BTINTEL_PCIE_MBOX_PARSE_PENDING,
4264 						       &data->flags)) {
4265 					set_bit(BTINTEL_PCIE_MBOX_PARSE_READY, &data->flags);
4266 					wake_up(&data->mbox_parse_wait_q);
4267 				}
4268 
4269 				return 0;
4270 			}
4271 		} else {
4272 			if (btintel_pcie_in_d3(data)) {
4273 				/* Do what the handler's D0 -> D3 branch
4274 				 * would have done, unless it already has.
4275 				 */
4276 				spin_lock(&data->irq_lock);
4277 				if (data->alive_intr_ctxt != BTINTEL_PCIE_D3)
4278 					data->alive_intr_ctxt = BTINTEL_PCIE_D3;
4279 				spin_unlock(&data->irq_lock);
4280 
4281 				return 0;
4282 			}
4283 		}
4284 
4285 	} while (++retry < BTINTEL_PCIE_DX_TRANSITION_MAX_RETRIES);
4286 
4287 	return -EBUSY;
4288 }
4289 
4290 static int btintel_pcie_suspend_late(struct device *dev, pm_message_t mesg)
4291 {
4292 	struct pci_dev *pdev = to_pci_dev(dev);
4293 	struct btintel_pcie_data *data;
4294 	ktime_t start;
4295 	u32 dxstate;
4296 	int err;
4297 
4298 	data = pci_get_drvdata(pdev);
4299 
4300 	/* S0ix (s2idle) uses D3_HOT; S3, freeze and hibernate use D3_COLD. */
4301 	if (mesg.event == PM_EVENT_SUSPEND &&
4302 	    pm_suspend_target_state == PM_SUSPEND_TO_IDLE)
4303 		dxstate = BTINTEL_PCIE_STATE_D3_HOT;
4304 	else
4305 		dxstate = BTINTEL_PCIE_STATE_D3_COLD;
4306 
4307 	start = ktime_get();
4308 
4309 	/* Refer: 6.4.11.7 -> Platform power management */
4310 	err = btintel_pcie_set_dxstate(data, dxstate);
4311 
4312 	if (err) {
4313 		bt_dev_err(data->hdev, "Failed to set dxstate:%u (%d)",
4314 			   dxstate, err);
4315 		return err;
4316 	}
4317 
4318 	bt_dev_dbg(data->hdev,
4319 		   "device entered into d3 state from d0 in %lld us",
4320 		   ktime_to_us(ktime_get() - start));
4321 	return err;
4322 }
4323 
4324 static int btintel_pcie_suspend(struct device *dev)
4325 {
4326 	return btintel_pcie_suspend_late(dev, PMSG_SUSPEND);
4327 }
4328 
4329 static int btintel_pcie_hibernate(struct device *dev)
4330 {
4331 	return btintel_pcie_suspend_late(dev, PMSG_HIBERNATE);
4332 }
4333 
4334 static int btintel_pcie_freeze(struct device *dev)
4335 {
4336 	return btintel_pcie_suspend_late(dev, PMSG_FREEZE);
4337 }
4338 
4339 static int btintel_pcie_resume_event(struct device *dev, pm_message_t mesg)
4340 {
4341 	struct pci_dev *pdev = to_pci_dev(dev);
4342 	struct btintel_pcie_data *data;
4343 	ktime_t start;
4344 	int err;
4345 
4346 	data = pci_get_drvdata(pdev);
4347 
4348 	start = ktime_get();
4349 
4350 	/* S3 and S4 may cut power, erasing the firmware. Force FLR to recover
4351 	 * instead of a normal D0 transition.
4352 	 */
4353 	if (mesg.event == PM_EVENT_RESTORE ||
4354 	    (mesg.event == PM_EVENT_RESUME &&
4355 	     pm_suspend_target_state == PM_SUSPEND_MEM)) {
4356 		set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags);
4357 		btintel_pcie_request_reset(data, BTINTEL_PCIE_IOSF_PRR_FLR);
4358 		return 0;
4359 	}
4360 
4361 	/* Refer: 6.4.11.7 -> Platform power management */
4362 	err = btintel_pcie_set_dxstate(data, BTINTEL_PCIE_STATE_D0);
4363 
4364 	if (err) {
4365 		bt_dev_err(data->hdev, "Failed to set D0 state (%d)", err);
4366 	} else {
4367 		bt_dev_dbg(data->hdev,
4368 			   "device entered into d0 state from d3 in %lld us",
4369 			   ktime_to_us(ktime_get() - start));
4370 		return err;
4371 	}
4372 
4373 	/* Trigger function level reset if the controller is in error
4374 	 * state during resume() to bring back the controller to
4375 	 * operational mode
4376 	 */
4377 
4378 	data->boot_stage_cache = btintel_pcie_rd_reg32(data,
4379 			BTINTEL_PCIE_CSR_BOOT_STAGE_REG);
4380 	if (btintel_pcie_in_error(data) ||
4381 			btintel_pcie_in_device_halt(data)) {
4382 		bt_dev_err(data->hdev, "Controller in error state for D0 entry");
4383 		btintel_pcie_queue_coredump(data,
4384 					    BTINTEL_PCIE_TRIGGER_REASON_FW_ASSERT);
4385 		set_bit(BTINTEL_PCIE_CORE_HALTED, &data->flags);
4386 		btintel_pcie_request_reset(data, BTINTEL_PCIE_IOSF_PRR_FLR);
4387 	}
4388 	return err;
4389 }
4390 
4391 static int btintel_pcie_resume(struct device *dev)
4392 {
4393 	return btintel_pcie_resume_event(dev, PMSG_RESUME);
4394 }
4395 
4396 static int btintel_pcie_restore(struct device *dev)
4397 {
4398 	return btintel_pcie_resume_event(dev, PMSG_RESTORE);
4399 }
4400 
4401 static int btintel_pcie_thaw(struct device *dev)
4402 {
4403 	return btintel_pcie_resume_event(dev, PMSG_THAW);
4404 }
4405 
4406 static const struct dev_pm_ops btintel_pcie_pm_ops = {
4407 	.suspend = btintel_pcie_suspend,
4408 	.resume = btintel_pcie_resume,
4409 	.freeze = btintel_pcie_freeze,
4410 	.thaw = btintel_pcie_thaw,
4411 	.poweroff = btintel_pcie_hibernate,
4412 	.restore = btintel_pcie_restore,
4413 };
4414 
4415 static struct pci_driver btintel_pcie_driver = {
4416 	.name = KBUILD_MODNAME,
4417 	.id_table = btintel_pcie_table,
4418 	.probe = btintel_pcie_probe,
4419 	.remove = btintel_pcie_remove,
4420 	.driver.pm = pm_sleep_ptr(&btintel_pcie_pm_ops),
4421 	.dev_groups = btintel_pcie_groups,
4422 #ifdef CONFIG_DEV_COREDUMP
4423 	.driver.coredump = btintel_pcie_coredump
4424 #endif
4425 };
4426 
4427 static int __init btintel_pcie_init(void)
4428 {
4429 	return pci_register_driver(&btintel_pcie_driver);
4430 }
4431 
4432 static void __exit btintel_pcie_exit(void)
4433 {
4434 	pci_unregister_driver(&btintel_pcie_driver);
4435 	btintel_pcie_free_restart_list();
4436 }
4437 
4438 module_init(btintel_pcie_init);
4439 module_exit(btintel_pcie_exit);
4440 
4441 MODULE_AUTHOR("Tedd Ho-Jeong An <tedd.an@intel.com>");
4442 MODULE_DESCRIPTION("Intel Bluetooth PCIe transport driver ver " VERSION);
4443 MODULE_VERSION(VERSION);
4444 MODULE_LICENSE("GPL");
4445