1 /* hci_stm32wba.c - HCI driver for stm32wba */
2 
3 /*
4  * Copyright (c) 2022, Telink Semiconductor (Shanghai) Co., Ltd.
5  * Copyright (c) 2023 STMicroelectronics
6  *
7  * SPDX-License-Identifier: Apache-2.0
8  */
9 
10 #include <zephyr/init.h>
11 #include <zephyr/sys/util.h>
12 #include <zephyr/bluetooth/hci.h>
13 #include <zephyr/drivers/bluetooth.h>
14 #include <zephyr/bluetooth/addr.h>
15 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
16 #include <linklayer_plat_local.h>
17 
18 #include <zephyr/sys/byteorder.h>
19 
20 #include "blestack.h"
21 #include "app_conf.h"
22 #include "ll_sys.h"
23 #include "flash_driver.h"
24 
25 #define LOG_LEVEL CONFIG_BT_HCI_DRIVER_LOG_LEVEL
26 #include <zephyr/logging/log.h>
27 LOG_MODULE_REGISTER(hci_wba);
28 
29 #define DT_DRV_COMPAT st_hci_stm32wba
30 
31 struct hci_data {
32 	bt_hci_recv_t recv;
33 };
34 
35 static K_SEM_DEFINE(hci_sem, 1, 1);
36 
37 #define BLE_CTRLR_STACK_BUFFER_SIZE 300
38 
39 #define MBLOCK_COUNT	(BLE_MBLOCKS_CALC(PREP_WRITE_LIST_SIZE, \
40 					  CFG_BLE_ATT_MTU_MAX, \
41 					  CFG_BLE_NUM_LINK) \
42 			 + CFG_BLE_MBLOCK_COUNT_MARGIN)
43 
44 #define BLE_DYN_ALLOC_SIZE \
45 	(BLE_TOTAL_BUFFER_SIZE(CFG_BLE_NUM_LINK, MBLOCK_COUNT))
46 
47 /* GATT buffer size (in bytes)*/
48 #define BLE_GATT_BUF_SIZE \
49 	BLE_TOTAL_BUFFER_SIZE_GATT(CFG_BLE_NUM_GATT_ATTRIBUTES, \
50 				   CFG_BLE_NUM_GATT_SERVICES, \
51 				   CFG_BLE_ATT_VALUE_ARRAY_SIZE)
52 
53 #define DIVC(x, y)         (((x)+(y)-1)/(y))
54 
55 #if defined(CONFIG_BT_HCI_SETUP)
56 /* Bluetooth LE public STM32WBA default device address (if udn not available) */
57 static bt_addr_t bd_addr_dflt = {{0x65, 0x43, 0x21, 0x1E, 0x08, 0x00}};
58 
59 #define ACI_HAL_WRITE_CONFIG_DATA	   BT_OP(BT_OGF_VS, 0xFC0C)
60 #define HCI_CONFIG_DATA_PUBADDR_OFFSET	   0
61 static bt_addr_t bd_addr_udn;
62 struct aci_set_ble_addr {
63 	uint8_t config_offset;
64 	uint8_t length;
65 	uint8_t value[6];
66 } __packed;
67 #endif
68 
69 static uint32_t __noinit buffer[DIVC(BLE_DYN_ALLOC_SIZE, 4)];
70 static uint32_t __noinit gatt_buffer[DIVC(BLE_GATT_BUF_SIZE, 4)];
71 
72 extern uint8_t ll_state_busy;
73 
is_hci_event_discardable(const uint8_t * evt_data)74 static bool is_hci_event_discardable(const uint8_t *evt_data)
75 {
76 	uint8_t evt_type = evt_data[0];
77 
78 	switch (evt_type) {
79 #if defined(CONFIG_BT_CLASSIC)
80 	case BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI:
81 	case BT_HCI_EVT_EXTENDED_INQUIRY_RESULT:
82 		return true;
83 #endif
84 	case BT_HCI_EVT_LE_META_EVENT: {
85 		uint8_t subevt_type = evt_data[sizeof(struct bt_hci_evt_hdr)];
86 
87 		switch (subevt_type) {
88 		case BT_HCI_EVT_LE_ADVERTISING_REPORT:
89 			return true;
90 		default:
91 			return false;
92 		}
93 	}
94 	default:
95 		return false;
96 	}
97 }
98 
treat_evt(const uint8_t * data,size_t len)99 static struct net_buf *treat_evt(const uint8_t *data, size_t len)
100 {
101 	bool discardable;
102 	struct bt_hci_evt_hdr hdr;
103 	struct net_buf *buf;
104 	size_t buf_tailroom;
105 
106 	if (len < sizeof(hdr)) {
107 		LOG_ERR("Not enough data for event header");
108 		return NULL;
109 	}
110 
111 	discardable = is_hci_event_discardable(data);
112 
113 	memcpy((void *)&hdr, data, sizeof(hdr));
114 	data += sizeof(hdr);
115 	len -= sizeof(hdr);
116 
117 	if (len != hdr.len) {
118 		LOG_ERR("Event payload length is not correct.\n");
119 		LOG_ERR("len: %d, hdr.len: %d\n", len, hdr.len);
120 		return NULL;
121 	}
122 	LOG_DBG("len %u", hdr.len);
123 
124 	buf = bt_buf_get_evt(hdr.evt, discardable, discardable ? K_NO_WAIT : K_SECONDS(3));
125 	if (!buf) {
126 		if (discardable) {
127 			LOG_DBG("Discardable buffer pool full, ignoring event");
128 		} else {
129 			LOG_ERR("No available event buffers!");
130 
131 		}
132 		__ASSERT_NO_MSG(buf);
133 		return buf;
134 	}
135 
136 	net_buf_add_mem(buf, &hdr, sizeof(hdr));
137 
138 	buf_tailroom = net_buf_tailroom(buf);
139 	if (buf_tailroom < len) {
140 		LOG_ERR("Not enough space in buffer %zu/%zu", len, buf_tailroom);
141 		net_buf_unref(buf);
142 		return NULL;
143 	}
144 
145 	net_buf_add_mem(buf, data, len);
146 
147 	return buf;
148 }
149 
treat_acl(const uint8_t * data,size_t len,const uint8_t * ext_data,size_t ext_len)150 static struct net_buf *treat_acl(const uint8_t *data, size_t len,
151 				 const uint8_t *ext_data, size_t ext_len)
152 {
153 	struct bt_hci_acl_hdr hdr;
154 	struct net_buf *buf;
155 	size_t buf_tailroom;
156 
157 	if (len < sizeof(hdr)) {
158 		LOG_ERR("Not enough data for ACL header");
159 		return NULL;
160 	}
161 
162 	buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
163 	if (buf) {
164 		memcpy((void *)&hdr, data, sizeof(hdr));
165 		data += sizeof(hdr);
166 		len -= sizeof(hdr);
167 	} else {
168 		LOG_ERR("No available ACL buffers!");
169 		return NULL;
170 	}
171 
172 	if (ext_len != sys_le16_to_cpu(hdr.len)) {
173 		LOG_ERR("ACL payload length is not correct");
174 		net_buf_unref(buf);
175 		return NULL;
176 	}
177 
178 	net_buf_add_mem(buf, &hdr, sizeof(hdr));
179 	buf_tailroom = net_buf_tailroom(buf);
180 	if (buf_tailroom < len) {
181 		LOG_ERR("Not enough space in buffer %zu/%zu", len, buf_tailroom);
182 		net_buf_unref(buf);
183 		return NULL;
184 	}
185 
186 	LOG_DBG("ext_len %u", ext_len);
187 	net_buf_add_mem(buf, ext_data, ext_len);
188 
189 	return buf;
190 }
191 
treat_iso(const uint8_t * data,size_t len,const uint8_t * ext_data,size_t ext_len)192 static struct net_buf *treat_iso(const uint8_t *data, size_t len,
193 				 const uint8_t *ext_data, size_t ext_len)
194 {
195 	struct bt_hci_iso_hdr hdr;
196 	struct net_buf *buf;
197 	size_t buf_tailroom;
198 
199 	if (len < sizeof(hdr)) {
200 		LOG_ERR("Not enough data for ISO header");
201 		return NULL;
202 	}
203 
204 	buf = bt_buf_get_rx(BT_BUF_ISO_IN, K_NO_WAIT);
205 	if (buf) {
206 		memcpy((void *)&hdr, data, sizeof(hdr));
207 		data += sizeof(hdr);
208 		len -= sizeof(hdr);
209 	} else {
210 		LOG_ERR("No available ISO buffers!");
211 		return NULL;
212 	}
213 
214 	if (ext_len != bt_iso_hdr_len(sys_le16_to_cpu(hdr.len))) {
215 		LOG_ERR("ISO payload length is not correct");
216 		net_buf_unref(buf);
217 		return NULL;
218 	}
219 
220 	net_buf_add_mem(buf, &hdr, sizeof(hdr));
221 	buf_tailroom = net_buf_tailroom(buf);
222 	if (buf_tailroom < len) {
223 		LOG_ERR("Not enough space in buffer %zu/%zu", len, buf_tailroom);
224 		net_buf_unref(buf);
225 		return NULL;
226 	}
227 
228 	LOG_DBG("ext_len %zu", ext_len);
229 	net_buf_add_mem(buf, ext_data, ext_len);
230 
231 	return buf;
232 }
233 
receive_data(const struct device * dev,const uint8_t * data,size_t len,const uint8_t * ext_data,size_t ext_len)234 static int receive_data(const struct device *dev, const uint8_t *data, size_t len,
235 			const uint8_t *ext_data, size_t ext_len)
236 {
237 	struct hci_data *hci = dev->data;
238 	uint8_t pkt_indicator;
239 	struct net_buf *buf;
240 	int err = 0;
241 
242 	LOG_HEXDUMP_DBG(data, len, "host packet data:");
243 	LOG_HEXDUMP_DBG(ext_data, ext_len, "host packet ext_data:");
244 
245 	pkt_indicator = *data++;
246 	len -= sizeof(pkt_indicator);
247 
248 	switch (pkt_indicator) {
249 	case BT_HCI_H4_EVT:
250 		buf = treat_evt(data, len);
251 		break;
252 	case BT_HCI_H4_ACL:
253 		buf = treat_acl(data, len + 1, ext_data, ext_len);
254 		break;
255 	case BT_HCI_H4_ISO:
256 	case BT_HCI_H4_SCO:
257 		buf = treat_iso(data, len + 1, ext_data, ext_len);
258 		break;
259 	default:
260 		buf = NULL;
261 		LOG_ERR("Unknown HCI type %u", pkt_indicator);
262 	}
263 
264 	if (buf) {
265 		hci->recv(dev, buf);
266 	} else {
267 		err = -ENOMEM;
268 		ll_state_busy = 1;
269 	}
270 
271 	return err;
272 }
273 
BLECB_Indication(const uint8_t * data,uint16_t length,const uint8_t * ext_data,uint16_t ext_length)274 uint8_t BLECB_Indication(const uint8_t *data, uint16_t length,
275 			 const uint8_t *ext_data, uint16_t ext_length)
276 {
277 	const struct device *dev = DEVICE_DT_GET(DT_DRV_INST(0));
278 	int ret = 0;
279 	int err;
280 
281 	LOG_DBG("length: %d", length);
282 	if (ext_length != 0) {
283 		LOG_DBG("ext_length: %d", ext_length);
284 	}
285 
286 	k_sem_take(&hci_sem, K_FOREVER);
287 
288 	err = receive_data(dev, data, (size_t)length - 1,
289 			   ext_data, (size_t)ext_length);
290 
291 	k_sem_give(&hci_sem);
292 
293 	HostStack_Process();
294 
295 	if (err) {
296 		ret = 1;
297 	}
298 
299 	return ret;
300 }
301 
bt_hci_stm32wba_send(const struct device * dev,struct net_buf * buf)302 static int bt_hci_stm32wba_send(const struct device *dev, struct net_buf *buf)
303 {
304 	uint16_t event_length;
305 	uint8_t pkt_indicator;
306 	uint8_t tx_buffer[BLE_CTRLR_STACK_BUFFER_SIZE];
307 
308 	ARG_UNUSED(dev);
309 
310 	k_sem_take(&hci_sem, K_FOREVER);
311 
312 	LOG_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len);
313 
314 	switch (bt_buf_get_type(buf)) {
315 	case BT_BUF_ACL_OUT:
316 		pkt_indicator = BT_HCI_H4_ACL;
317 		break;
318 	case BT_BUF_CMD:
319 		pkt_indicator = BT_HCI_H4_CMD;
320 		break;
321 	case BT_BUF_ISO_OUT:
322 		pkt_indicator = BT_HCI_H4_ISO;
323 		break;
324 	default:
325 		LOG_ERR("Unknown type %u", bt_buf_get_type(buf));
326 		k_sem_give(&hci_sem);
327 		return -EIO;
328 	}
329 	net_buf_push_u8(buf, pkt_indicator);
330 
331 	memcpy(&tx_buffer, buf->data, buf->len);
332 
333 	event_length = BleStack_Request(tx_buffer);
334 	LOG_DBG("event_length: %u", event_length);
335 
336 	if (event_length) {
337 		receive_data(dev, (uint8_t *)&tx_buffer, (size_t)event_length, NULL, 0);
338 	}
339 
340 	k_sem_give(&hci_sem);
341 
342 	net_buf_unref(buf);
343 
344 	return 0;
345 }
346 
bt_ble_ctlr_init(void)347 static int bt_ble_ctlr_init(void)
348 {
349 	BleStack_init_t init_params_p = {0};
350 
351 	init_params_p.numAttrRecord           = CFG_BLE_NUM_GATT_ATTRIBUTES;
352 	init_params_p.numAttrServ             = CFG_BLE_NUM_GATT_SERVICES;
353 	init_params_p.attrValueArrSize        = CFG_BLE_ATT_VALUE_ARRAY_SIZE;
354 	init_params_p.prWriteListSize         = CFG_BLE_ATTR_PREPARE_WRITE_VALUE_SIZE;
355 	init_params_p.attMtu                  = CFG_BLE_ATT_MTU_MAX;
356 	init_params_p.max_coc_nbr             = CFG_BLE_COC_NBR_MAX;
357 	init_params_p.max_coc_mps             = CFG_BLE_COC_MPS_MAX;
358 	init_params_p.max_coc_initiator_nbr   = CFG_BLE_COC_INITIATOR_NBR_MAX;
359 	init_params_p.numOfLinks              = CFG_BLE_NUM_LINK;
360 	init_params_p.mblockCount             = CFG_BLE_MBLOCK_COUNT;
361 	init_params_p.bleStartRamAddress      = (uint8_t *)buffer;
362 	init_params_p.total_buffer_size       = BLE_DYN_ALLOC_SIZE;
363 	init_params_p.bleStartRamAddress_GATT = (uint8_t *)gatt_buffer;
364 	init_params_p.total_buffer_size_GATT  = BLE_GATT_BUF_SIZE;
365 	init_params_p.options                 = CFG_BLE_OPTIONS;
366 	init_params_p.debug                   = 0U;
367 
368 	if (BleStack_Init(&init_params_p) != BLE_STATUS_SUCCESS) {
369 		return -EIO;
370 	}
371 
372 	return 0;
373 }
374 
bt_hci_stm32wba_open(const struct device * dev,bt_hci_recv_t recv)375 static int bt_hci_stm32wba_open(const struct device *dev, bt_hci_recv_t recv)
376 {
377 	struct hci_data *data = dev->data;
378 	int ret = 0;
379 
380 	link_layer_register_isr();
381 
382 	ll_sys_config_params();
383 
384 	ret = bt_ble_ctlr_init();
385 	if (ret == 0) {
386 		data->recv = recv;
387 	}
388 
389 	/* TODO. Enable Flash manager once available */
390 	if (IS_ENABLED(CONFIG_FLASH)) {
391 		FD_SetStatus(FD_FLASHACCESS_RFTS_BYPASS, LL_FLASH_DISABLE);
392 	}
393 
394 	return ret;
395 }
396 
397 #if defined(CONFIG_BT_HCI_SETUP)
398 
bt_get_ble_addr(void)399 bt_addr_t *bt_get_ble_addr(void)
400 {
401 	bt_addr_t *bd_addr;
402 	uint32_t udn;
403 	uint32_t company_id;
404 	uint32_t device_id;
405 
406 	/* Get the 64 bit Unique Device Number UID */
407 	/* The UID is used by firmware to derive */
408 	/* 48-bit Device Address EUI-48 */
409 	udn = LL_FLASH_GetUDN();
410 
411 	if (udn != 0xFFFFFFFF) {
412 		/* Get the ST Company ID */
413 		company_id = LL_FLASH_GetSTCompanyID();
414 		/* Get the STM32 Device ID */
415 		device_id = LL_FLASH_GetDeviceID();
416 
417 		/*
418 		 * Public Address with the ST company ID
419 		 * bit[47:24] : 24bits (OUI) equal to the company ID
420 		 * bit[23:16] : Device ID.
421 		 * bit[15:0] : The last 16bits from the UDN
422 		 * Note: In order to use the Public Address in a final product, a dedicated
423 		 * 24bits company ID (OUI) shall be bought.
424 		 */
425 
426 		bd_addr_udn.val[0] = (uint8_t)(udn & 0x000000FF);
427 		bd_addr_udn.val[1] = (uint8_t)((udn & 0x0000FF00) >> 8);
428 		bd_addr_udn.val[2] = (uint8_t)device_id;
429 		bd_addr_udn.val[3] = (uint8_t)(company_id & 0x000000FF);
430 		bd_addr_udn.val[4] = (uint8_t)((company_id & 0x0000FF00) >> 8);
431 		bd_addr_udn.val[5] = (uint8_t)((company_id & 0x00FF0000) >> 16);
432 		bd_addr = &bd_addr_udn;
433 	} else {
434 		bd_addr = &bd_addr_dflt;
435 	}
436 
437 	return bd_addr;
438 }
439 
bt_hci_stm32wba_setup(const struct device * dev,const struct bt_hci_setup_params * params)440 static int bt_hci_stm32wba_setup(const struct device *dev,
441 				 const struct bt_hci_setup_params *params)
442 {
443 	bt_addr_t *uid_addr;
444 	struct aci_set_ble_addr *param;
445 	struct net_buf *buf;
446 	int err;
447 
448 	uid_addr = bt_get_ble_addr();
449 	if (!uid_addr) {
450 		return -ENOMSG;
451 	}
452 
453 	buf = bt_hci_cmd_create(ACI_HAL_WRITE_CONFIG_DATA, sizeof(*param));
454 	if (!buf) {
455 		return -ENOBUFS;
456 	}
457 
458 	param = net_buf_add(buf, sizeof(*param));
459 	param->config_offset = HCI_CONFIG_DATA_PUBADDR_OFFSET;
460 	param->length = 6;
461 
462 	if (bt_addr_eq(&params->public_addr, BT_ADDR_ANY)) {
463 		bt_addr_copy((bt_addr_t *)param->value, uid_addr);
464 	} else {
465 		bt_addr_copy((bt_addr_t *)param->value, &(params->public_addr));
466 	}
467 
468 	err = bt_hci_cmd_send_sync(ACI_HAL_WRITE_CONFIG_DATA, buf, NULL);
469 	if (err) {
470 		return err;
471 	}
472 
473 	return 0;
474 }
475 #endif /* CONFIG_BT_HCI_SETUP */
476 
477 static DEVICE_API(bt_hci, drv) = {
478 #if defined(CONFIG_BT_HCI_SETUP)
479 	.setup          = bt_hci_stm32wba_setup,
480 #endif
481 	.open           = bt_hci_stm32wba_open,
482 	.send           = bt_hci_stm32wba_send,
483 };
484 
485 #define HCI_DEVICE_INIT(inst) \
486 	static struct hci_data hci_data_##inst = { \
487 	}; \
488 	DEVICE_DT_INST_DEFINE(inst, NULL, NULL, &hci_data_##inst, NULL, \
489 			      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &drv)
490 
491 /* Only one instance supported */
492 HCI_DEVICE_INIT(0)
493