1 /*
2  * Copyright 2023-2024 NXP
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /* -------------------------------------------------------------------------- */
8 /*                                  Includes                                  */
9 /* -------------------------------------------------------------------------- */
10 
11 #include <zephyr/init.h>
12 #include <zephyr/drivers/bluetooth.h>
13 #include <zephyr/logging/log.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/device.h>
16 #include <zephyr/drivers/flash.h>
17 #include <zephyr/bluetooth/hci_types.h>
18 #include <soc.h>
19 
20 #include <fwk_platform_ble.h>
21 #include <fwk_platform.h>
22 
23 /* -------------------------------------------------------------------------- */
24 /*                                  Definitions                               */
25 /* -------------------------------------------------------------------------- */
26 
27 #define DT_DRV_COMPAT nxp_hci_ble
28 
29 struct bt_nxp_data {
30 	bt_hci_recv_t recv;
31 };
32 
33 struct hci_data {
34 	uint8_t packetType;
35 	uint8_t *data;
36 	uint16_t len;
37 };
38 
39 #define LOG_LEVEL CONFIG_BT_HCI_DRIVER_LOG_LEVEL
40 LOG_MODULE_REGISTER(bt_driver);
41 
42 /* Vendor specific commands */
43 #define HCI_CMD_STORE_BT_CAL_DATA_OCF                   0x61U
44 #define HCI_CMD_STORE_BT_CAL_DATA_PARAM_LENGTH          32U
45 #define HCI_CMD_STORE_BT_CAL_DATA_ANNEX100_OCF          0xFFU
46 #define HCI_CMD_STORE_BT_CAL_DATA_PARAM_ANNEX100_LENGTH 16U
47 #define HCI_CMD_SET_BT_SLEEP_MODE_OCF                   0x23U
48 #define HCI_CMD_SET_BT_SLEEP_MODE_PARAM_LENGTH          3U
49 #define HCI_CMD_BT_HOST_SLEEP_CONFIG_OCF                0x59U
50 #define HCI_CMD_BT_HOST_SLEEP_CONFIG_PARAM_LENGTH       2U
51 #define HCI_CMD_BT_HOST_SET_MAC_ADDR_PARAM_LENGTH       8U
52 #define HCI_SET_MAC_ADDR_CMD                            0x0022U
53 #define BT_USER_BD                                      254
54 #define BD_ADDR_OUI                                     0x37U, 0x60U, 0x00U
55 #define BD_ADDR_OUI_PART_SIZE                           3U
56 #define BD_ADDR_UUID_PART_SIZE                          3U
57 
58 #if !defined(CONFIG_HCI_NXP_SET_CAL_DATA)
59 #define bt_nxp_set_calibration_data() 0
60 #endif
61 
62 #if !defined(CONFIG_HCI_NXP_SET_CAL_DATA_ANNEX100)
63 #define bt_nxp_set_calibration_data_annex100() 0
64 #endif
65 
66 #if !defined(CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP)
67 #define nxp_bt_set_host_sleep_config()       0
68 #define nxp_bt_enable_controller_autosleep() 0
69 #endif
70 
71 #if !defined(CONFIG_BT_HCI_SET_PUBLIC_ADDR)
72 #define bt_nxp_set_mac_address(public_addr) 0
73 #endif
74 /* -------------------------------------------------------------------------- */
75 /*                              Public prototypes                             */
76 /* -------------------------------------------------------------------------- */
77 
78 /* -------------------------------------------------------------------------- */
79 /*                             Private functions                              */
80 /* -------------------------------------------------------------------------- */
81 
82 #if defined(CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP) || defined(CONFIG_HCI_NXP_SET_CAL_DATA)
nxp_bt_send_vs_command(uint16_t opcode,const uint8_t * params,uint8_t params_len)83 static int nxp_bt_send_vs_command(uint16_t opcode, const uint8_t *params, uint8_t params_len)
84 {
85 	if (IS_ENABLED(CONFIG_BT_HCI_HOST)) {
86 		struct net_buf *buf;
87 
88 		/* Allocate buffer for the hci command */
89 		buf = bt_hci_cmd_create(opcode, params_len);
90 		if (buf == NULL) {
91 			LOG_ERR("Unable to allocate command buffer");
92 			return -ENOMEM;
93 		}
94 
95 		/* Add data part of packet */
96 		net_buf_add_mem(buf, params, params_len);
97 
98 		/* Send the command */
99 		return bt_hci_cmd_send_sync(opcode, buf, NULL);
100 	} else {
101 		return 0;
102 	}
103 }
104 #endif /* CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP || CONFIG_HCI_NXP_SET_CAL_DATA */
105 
106 #if defined(CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP)
nxp_bt_enable_controller_autosleep(void)107 static int nxp_bt_enable_controller_autosleep(void)
108 {
109 	uint16_t opcode = BT_OP(BT_OGF_VS, HCI_CMD_SET_BT_SLEEP_MODE_OCF);
110 	const uint8_t params[HCI_CMD_SET_BT_SLEEP_MODE_PARAM_LENGTH] = {
111 		0x02U, /* Auto sleep enable */
112 		0x00U, /* Idle timeout LSB */
113 		0x00U  /* Idle timeout MSB */
114 	};
115 
116 	/* Send the command */
117 	return nxp_bt_send_vs_command(opcode, params, HCI_CMD_SET_BT_SLEEP_MODE_PARAM_LENGTH);
118 }
119 
nxp_bt_set_host_sleep_config(void)120 static int nxp_bt_set_host_sleep_config(void)
121 {
122 	uint16_t opcode = BT_OP(BT_OGF_VS, HCI_CMD_BT_HOST_SLEEP_CONFIG_OCF);
123 	const uint8_t params[HCI_CMD_BT_HOST_SLEEP_CONFIG_PARAM_LENGTH] = {
124 		0xFFU, /* BT_HIU_WAKEUP_INBAND */
125 		0xFFU, /* BT_HIU_WAKE_GAP_WAIT_FOR_IRQ */
126 	};
127 
128 	/* Send the command */
129 	return nxp_bt_send_vs_command(opcode, params, HCI_CMD_BT_HOST_SLEEP_CONFIG_PARAM_LENGTH);
130 }
131 #endif /* CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP */
132 
133 #if defined(CONFIG_HCI_NXP_SET_CAL_DATA)
bt_nxp_set_calibration_data(void)134 static int bt_nxp_set_calibration_data(void)
135 {
136 	uint16_t opcode = BT_OP(BT_OGF_VS, HCI_CMD_STORE_BT_CAL_DATA_OCF);
137 	extern const uint8_t hci_cal_data_params[HCI_CMD_STORE_BT_CAL_DATA_PARAM_LENGTH];
138 
139 	/* Send the command */
140 	return nxp_bt_send_vs_command(opcode, hci_cal_data_params,
141 				      HCI_CMD_STORE_BT_CAL_DATA_PARAM_LENGTH);
142 }
143 
144 #if defined(CONFIG_HCI_NXP_SET_CAL_DATA_ANNEX100)
bt_nxp_set_calibration_data_annex100(void)145 static int bt_nxp_set_calibration_data_annex100(void)
146 {
147 	uint16_t opcode = BT_OP(BT_OGF_VS, HCI_CMD_STORE_BT_CAL_DATA_ANNEX100_OCF);
148 
149 	extern const uint8_t
150 		hci_cal_data_annex100_params[HCI_CMD_STORE_BT_CAL_DATA_PARAM_ANNEX100_LENGTH];
151 
152 	/* Send the command */
153 	return nxp_bt_send_vs_command(opcode, hci_cal_data_annex100_params,
154 				      HCI_CMD_STORE_BT_CAL_DATA_PARAM_ANNEX100_LENGTH);
155 }
156 #endif /* CONFIG_HCI_NXP_SET_CAL_DATA_ANNEX100 */
157 
158 #endif /* CONFIG_HCI_NXP_SET_CAL_DATA */
159 
160 #if defined(CONFIG_BT_HCI_SET_PUBLIC_ADDR)
161 /* Currently, we cannot use nxp_bt_send_vs_command because the controller
162  * fails to send the command complete event expected by Zephyr Host stack.
163  * To workaround it, we directly send the message using our PLATFORM API.
164  * This will be reworked once it is fixed on the controller side.
165  */
bt_nxp_set_mac_address(const bt_addr_t * public_addr)166 static int bt_nxp_set_mac_address(const bt_addr_t *public_addr)
167 {
168 	uint8_t bleDeviceAddress[BT_ADDR_SIZE] = {0};
169 	uint16_t opcode = BT_OP(BT_OGF_VS, HCI_SET_MAC_ADDR_CMD);
170 	uint8_t addrOUI[BD_ADDR_OUI_PART_SIZE] = {BD_ADDR_OUI};
171 	uint8_t uid[16] = {0};
172 	uint8_t uuidLen;
173 	uint8_t hciBuffer[12];
174 
175 	/* If no public address is provided by the user, use a unique address made
176 	 * from the device's UID (unique ID)
177 	 */
178 	if (bt_addr_eq(public_addr, BT_ADDR_ANY) || bt_addr_eq(public_addr, BT_ADDR_NONE)) {
179 		PLATFORM_GetMCUUid(uid, &uuidLen);
180 		/* Set 3 LSB of MAC address from UUID */
181 		if (uuidLen > BD_ADDR_UUID_PART_SIZE) {
182 			memcpy((void *)bleDeviceAddress,
183 			       (void *)(uid + uuidLen - (BD_ADDR_UUID_PART_SIZE + 1)),
184 			       BD_ADDR_UUID_PART_SIZE);
185 		}
186 		/* Set 3 MSB of MAC address from OUI */
187 		memcpy((void *)(bleDeviceAddress + BD_ADDR_UUID_PART_SIZE), (void *)addrOUI,
188 		       BD_ADDR_OUI_PART_SIZE);
189 	} else {
190 		bt_addr_copy((bt_addr_t *)bleDeviceAddress, public_addr);
191 	}
192 
193 	hciBuffer[0] = BT_HCI_H4_CMD;
194 	memcpy((void *)&hciBuffer[1], (const void *)&opcode, 2U);
195 	/* Set HCI parameter length */
196 	hciBuffer[3] = HCI_CMD_BT_HOST_SET_MAC_ADDR_PARAM_LENGTH;
197 	/* Set command parameter ID */
198 	hciBuffer[4] = BT_USER_BD;
199 	/* Set command parameter length */
200 	hciBuffer[5] = (uint8_t)6U;
201 	memcpy(hciBuffer + 6U, (const void *)bleDeviceAddress,
202 	       BD_ADDR_UUID_PART_SIZE + BD_ADDR_OUI_PART_SIZE);
203 	/* Send the command */
204 	return PLATFORM_SendHciMessage(hciBuffer, 12U);
205 }
206 #endif /* CONFIG_BT_HCI_SET_PUBLIC_ADDR */
207 
is_hci_event_discardable(const uint8_t * evt_data)208 static bool is_hci_event_discardable(const uint8_t *evt_data)
209 {
210 	bool ret = false;
211 	uint8_t evt_type = evt_data[0];
212 
213 	switch (evt_type) {
214 	case BT_HCI_EVT_LE_META_EVENT: {
215 		uint8_t subevt_type = evt_data[sizeof(struct bt_hci_evt_hdr)];
216 
217 		switch (subevt_type) {
218 		case BT_HCI_EVT_LE_ADVERTISING_REPORT:
219 		case BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT:
220 			ret = true;
221 			break;
222 		default:
223 			break;
224 		}
225 	} break;
226 
227 	default:
228 		break;
229 	}
230 
231 	return ret;
232 }
233 
bt_evt_recv(uint8_t * data,size_t len)234 static struct net_buf *bt_evt_recv(uint8_t *data, size_t len)
235 {
236 	struct net_buf *buf;
237 	uint8_t payload_len;
238 	uint8_t evt_hdr;
239 	bool discardable_evt;
240 	size_t space_in_buffer;
241 
242 	payload_len = data[1];
243 	evt_hdr = data[0];
244 	discardable_evt = false;
245 
246 	/* Data Check */
247 	if (len < BT_HCI_EVT_HDR_SIZE) {
248 		LOG_ERR("Event header is missing");
249 		return NULL;
250 	}
251 	if ((len - BT_HCI_EVT_HDR_SIZE) != payload_len) {
252 		LOG_ERR("Event payload length is incorrect");
253 		return NULL;
254 	}
255 
256 	discardable_evt = is_hci_event_discardable(data);
257 
258 	/* Allocate a buffer for the HCI Event */
259 	buf = bt_buf_get_evt(evt_hdr, discardable_evt, (discardable_evt ? K_NO_WAIT : K_FOREVER));
260 
261 	if (buf) {
262 		space_in_buffer = net_buf_tailroom(buf);
263 		if (len > space_in_buffer) {
264 			LOG_ERR("Buffer size error,INFO : evt_hdr=%d, data_len=%zu, buf_size=%zu",
265 				evt_hdr, len, space_in_buffer);
266 			net_buf_unref(buf);
267 			return NULL;
268 		}
269 		/* Copy the data to the buffer */
270 		net_buf_add_mem(buf, data, len);
271 	} else {
272 		if (discardable_evt) {
273 			LOG_DBG("Discardable buffer pool full, ignoring event");
274 		} else {
275 			LOG_ERR("No available event buffers!");
276 		}
277 		return NULL;
278 	}
279 
280 	return buf;
281 }
282 
bt_acl_recv(uint8_t * data,size_t len)283 static struct net_buf *bt_acl_recv(uint8_t *data, size_t len)
284 {
285 	struct net_buf *buf;
286 	uint16_t payload_len;
287 
288 	/* Data Check */
289 	if (len < BT_HCI_ACL_HDR_SIZE) {
290 		LOG_ERR("ACL header is missing");
291 		return NULL;
292 	}
293 	memcpy((void *)&payload_len, (void *)&data[2], 2);
294 	if ((len - BT_HCI_ACL_HDR_SIZE) != payload_len) {
295 		LOG_ERR("ACL payload length is incorrect");
296 		return NULL;
297 	}
298 	/* Allocate a buffer for the received data */
299 	buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
300 
301 	if (buf) {
302 		if (len > net_buf_tailroom(buf)) {
303 			LOG_ERR("Buffer doesn't have enough space to store the data");
304 			net_buf_unref(buf);
305 			return NULL;
306 		}
307 		/* Copy the data to the buffer */
308 		net_buf_add_mem(buf, data, len);
309 	} else {
310 		LOG_ERR("ACL buffer is empty");
311 		return NULL;
312 	}
313 
314 	return buf;
315 }
316 
process_rx(uint8_t packetType,uint8_t * data,uint16_t len)317 static void process_rx(uint8_t packetType, uint8_t *data, uint16_t len)
318 {
319 	const struct device *dev = DEVICE_DT_GET(DT_DRV_INST(0));
320 	struct bt_nxp_data *hci = dev->data;
321 	struct net_buf *buf;
322 
323 	switch (packetType) {
324 	case BT_HCI_H4_EVT:
325 		/* create a buffer and fill it out with event data  */
326 		buf = bt_evt_recv(data, len);
327 		break;
328 	case BT_HCI_H4_ACL:
329 		/* create a buffer and fill it out with ACL data  */
330 		buf = bt_acl_recv(data, len);
331 		break;
332 	default:
333 		buf = NULL;
334 		LOG_ERR("Unknown HCI type");
335 	}
336 
337 	if (buf) {
338 		/* Provide the buffer to the host */
339 		hci->recv(dev, buf);
340 	}
341 }
342 
343 #if defined(CONFIG_HCI_NXP_RX_THREAD)
344 
345 K_MSGQ_DEFINE(rx_msgq, sizeof(struct hci_data), CONFIG_HCI_NXP_RX_MSG_QUEUE_SIZE, 4);
346 
bt_rx_thread(void * p1,void * p2,void * p3)347 static void bt_rx_thread(void *p1, void *p2, void *p3)
348 {
349 	ARG_UNUSED(p1);
350 	ARG_UNUSED(p2);
351 	ARG_UNUSED(p3);
352 
353 	struct hci_data hci_rx_frame;
354 
355 	while (true) {
356 		if (k_msgq_get(&rx_msgq, &hci_rx_frame, K_FOREVER) < 0) {
357 			LOG_ERR("Failed to get RX data from message queue");
358 			continue;
359 		}
360 		process_rx(hci_rx_frame.packetType, hci_rx_frame.data, hci_rx_frame.len);
361 		k_free(hci_rx_frame.data);
362 	}
363 }
364 
365 K_THREAD_DEFINE(nxp_hci_rx_thread, CONFIG_BT_DRV_RX_STACK_SIZE, bt_rx_thread, NULL, NULL, NULL,
366 		K_PRIO_COOP(CONFIG_BT_DRIVER_RX_HIGH_PRIO), 0, 0);
367 
hci_rx_cb(uint8_t packetType,uint8_t * data,uint16_t len)368 static void hci_rx_cb(uint8_t packetType, uint8_t *data, uint16_t len)
369 {
370 	struct hci_data hci_rx_frame;
371 
372 	hci_rx_frame.packetType = packetType;
373 	hci_rx_frame.data = k_malloc(len);
374 
375 	if (!hci_rx_frame.data) {
376 		LOG_ERR("Failed to allocate RX buffer");
377 	}
378 
379 	memcpy(hci_rx_frame.data, data, len);
380 	hci_rx_frame.len = len;
381 
382 	if (k_msgq_put(&rx_msgq, &hci_rx_frame, K_NO_WAIT) < 0) {
383 		LOG_ERR("Failed to push RX data to message queue");
384 	}
385 }
386 
387 #else  /* CONFIG_HCI_NXP_RX_THREAD */
388 
hci_rx_cb(uint8_t packetType,uint8_t * data,uint16_t len)389 static void hci_rx_cb(uint8_t packetType, uint8_t *data, uint16_t len)
390 {
391 	process_rx(packetType, data, len);
392 }
393 #endif /* CONFIG_HCI_NXP_RX_THREAD */
394 
bt_nxp_send(const struct device * dev,struct net_buf * buf)395 static int bt_nxp_send(const struct device *dev, struct net_buf *buf)
396 {
397 	uint8_t packetType;
398 
399 	ARG_UNUSED(dev);
400 
401 	switch (bt_buf_get_type(buf)) {
402 	case BT_BUF_CMD:
403 		packetType = BT_HCI_H4_CMD;
404 		break;
405 	case BT_BUF_ACL_OUT:
406 		packetType = BT_HCI_H4_ACL;
407 		break;
408 	default:
409 		LOG_ERR("Not supported type");
410 		return -1;
411 	}
412 
413 	net_buf_push_u8(buf, packetType);
414 	PLATFORM_SendHciMessage(buf->data, buf->len);
415 
416 	net_buf_unref(buf);
417 
418 	return 0;
419 }
420 
bt_nxp_open(const struct device * dev,bt_hci_recv_t recv)421 static int bt_nxp_open(const struct device *dev, bt_hci_recv_t recv)
422 {
423 	struct bt_nxp_data *hci = dev->data;
424 	int ret = 0;
425 
426 	do {
427 		ret = PLATFORM_InitBle();
428 		if (ret < 0) {
429 			LOG_ERR("Failed to initialize BLE controller");
430 			break;
431 		}
432 
433 		ret = PLATFORM_SetHciRxCallback(hci_rx_cb);
434 		if (ret < 0) {
435 			LOG_ERR("BLE HCI RX callback registration failed");
436 			break;
437 		}
438 
439 		ret = PLATFORM_StartHci();
440 		if (ret < 0) {
441 			LOG_ERR("HCI open failed");
442 			break;
443 		}
444 
445 		hci->recv = recv;
446 	} while (false);
447 
448 	return ret;
449 }
450 
bt_nxp_setup(const struct device * dev,const struct bt_hci_setup_params * params)451 int bt_nxp_setup(const struct device *dev, const struct bt_hci_setup_params *params)
452 {
453 	ARG_UNUSED(dev);
454 
455 	int ret = 0;
456 
457 	do {
458 		if (IS_ENABLED(CONFIG_HCI_NXP_SET_CAL_DATA)) {
459 			ret = bt_nxp_set_calibration_data();
460 			if (ret < 0) {
461 				LOG_ERR("Failed to set calibration data");
462 				break;
463 			}
464 			if (IS_ENABLED(CONFIG_HCI_NXP_SET_CAL_DATA_ANNEX100)) {
465 				/* After send annex55 to CPU2, CPU2 need reset,
466 				 * a delay of at least 20ms is required to continue sending annex100
467 				 */
468 				k_sleep(Z_TIMEOUT_MS(20));
469 
470 				ret = bt_nxp_set_calibration_data_annex100();
471 				if (ret < 0) {
472 					LOG_ERR("Failed to set calibration data");
473 					break;
474 				}
475 			}
476 		}
477 
478 		if (IS_ENABLED(CONFIG_HCI_NXP_ENABLE_AUTO_SLEEP)) {
479 			ret = nxp_bt_set_host_sleep_config();
480 			if (ret < 0) {
481 				LOG_ERR("Failed to set host sleep config");
482 				break;
483 			}
484 
485 			ret = nxp_bt_enable_controller_autosleep();
486 			if (ret < 0) {
487 				LOG_ERR("Failed to configure controller autosleep");
488 				break;
489 			}
490 		}
491 
492 		if (IS_ENABLED(CONFIG_BT_HCI_SET_PUBLIC_ADDR)) {
493 			ret = bt_nxp_set_mac_address(&(params->public_addr));
494 			if (ret < 0) {
495 				LOG_ERR("Failed to set MAC address");
496 				break;
497 			}
498 		}
499 	} while (false);
500 
501 	return ret;
502 }
503 
bt_nxp_close(const struct device * dev)504 static int bt_nxp_close(const struct device *dev)
505 {
506 	struct bt_nxp_data *hci = dev->data;
507 	int ret = 0;
508 	/* Reset the Controller */
509 	if (IS_ENABLED(CONFIG_BT_HCI_HOST)) {
510 		ret = bt_hci_cmd_send_sync(BT_HCI_OP_RESET, NULL, NULL);
511 		if (ret) {
512 			LOG_ERR("Failed to reset BLE controller");
513 		}
514 		k_sleep(K_SECONDS(1));
515 
516 		ret = PLATFORM_TerminateBle();
517 		if (ret < 0) {
518 			LOG_ERR("Failed to shutdown BLE controller");
519 		}
520 	}
521 	hci->recv = NULL;
522 
523 	return ret;
524 }
525 
526 static DEVICE_API(bt_hci, drv) = {
527 	.open = bt_nxp_open,
528 	.setup = bt_nxp_setup,
529 	.close = bt_nxp_close,
530 	.send = bt_nxp_send,
531 };
532 
bt_nxp_init(const struct device * dev)533 static int bt_nxp_init(const struct device *dev)
534 {
535 	int status;
536 	int ret = 0;
537 
538 	ARG_UNUSED(dev);
539 
540 	do {
541 		status = PLATFORM_InitBle();
542 		if (status < 0) {
543 			LOG_ERR("BLE Controller initialization failed");
544 			ret = status;
545 			break;
546 		}
547 	} while (0);
548 
549 	return ret;
550 }
551 
552 #define HCI_DEVICE_INIT(inst) \
553 	static struct bt_nxp_data hci_data_##inst = { \
554 	}; \
555 	DEVICE_DT_INST_DEFINE(inst, bt_nxp_init, NULL, &hci_data_##inst, NULL, \
556 			      POST_KERNEL, CONFIG_BT_HCI_INIT_PRIORITY, &drv)
557 
558 /* Only one instance supported right now */
559 HCI_DEVICE_INIT(0)
560