1 /*
2  * Copyright (c) 2024 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 
9 #include <errno.h>
10 #include <zephyr/tc_util.h>
11 #include <zephyr/ztest.h>
12 
13 #include <zephyr/bluetooth/hci.h>
14 #include <zephyr/bluetooth/buf.h>
15 #include <zephyr/bluetooth/bluetooth.h>
16 #include <zephyr/drivers/bluetooth.h>
17 #include <zephyr/sys/byteorder.h>
18 
19 static enum bt_buf_type freed_buf_type;
20 static K_SEM_DEFINE(rx_sem, 0, 1);
21 
bt_buf_rx_freed_cb(enum bt_buf_type type)22 void bt_buf_rx_freed_cb(enum bt_buf_type type)
23 {
24 	freed_buf_type = type;
25 	k_sem_give(&rx_sem);
26 }
27 
28 ZTEST_SUITE(test_buf_data_api, NULL, NULL, NULL, NULL, NULL);
29 
ZTEST(test_buf_data_api,test_buf_freed_cb)30 ZTEST(test_buf_data_api, test_buf_freed_cb)
31 {
32 	struct net_buf *buf;
33 	int err;
34 
35 	bt_buf_rx_freed_cb_set(bt_buf_rx_freed_cb);
36 
37 	/* Test that the callback is called for the BT_BUF_EVT type */
38 	buf = bt_buf_get_rx(BT_BUF_EVT, K_NO_WAIT);
39 	zassert_not_null(buf, "Failed to get event buffer");
40 
41 	net_buf_unref(buf);
42 	/* The freed buf cb is called from net_buf_unref, therefore the semaphore should
43 	 * already by given.
44 	 */
45 	err = k_sem_take(&rx_sem, K_NO_WAIT);
46 	zassert_equal(err, 0, "Timeout while waiting for event buffer to be freed");
47 	zassert_equal(BT_BUF_EVT, BT_BUF_EVT & freed_buf_type, "Event buffer wasn't freed");
48 
49 	/* Test that the callback is called for the BT_BUF_ACL_IN type */
50 	buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_NO_WAIT);
51 	zassert_not_null(buf, "Failed to get ACL buffer");
52 
53 	net_buf_unref(buf);
54 	/* The freed buf cb is called from net_buf_unref, therefore the semaphore should
55 	 * already by given.
56 	 */
57 	err = k_sem_take(&rx_sem, K_NO_WAIT);
58 	zassert_equal(err, 0, "Timeout while waiting for ACL buffer to be freed");
59 	zassert_equal(BT_BUF_ACL_IN, BT_BUF_ACL_IN & freed_buf_type, "ACL buffer wasn't freed");
60 
61 	/* Test that the callback is called for the BT_BUF_ISO_IN type */
62 	buf = bt_buf_get_rx(BT_BUF_ISO_IN, K_NO_WAIT);
63 	zassert_not_null(buf, "Failed to get ISO buffer");
64 
65 	net_buf_unref(buf);
66 	/* The freed buf cb is called from net_buf_unref, therefore the semaphore should
67 	 * already by given.
68 	 */
69 	err = k_sem_take(&rx_sem, K_NO_WAIT);
70 	zassert_equal(err, 0, "Timeout while waiting for ISO buffer to be freed");
71 	zassert_equal(BT_BUF_ISO_IN, BT_BUF_ISO_IN & freed_buf_type, "ISO buffer wasn't freed");
72 }
73