common.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * SPDX-FileCopyrightText: 2017-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <errno.h>
  8. #include "esp_random.h"
  9. #include "mesh/main.h"
  10. #include "mesh/client_common.h"
  11. #include "mesh/common.h"
  12. IRAM_ATTR void *bt_mesh_malloc(size_t size)
  13. {
  14. #ifdef CONFIG_BLE_MESH_MEM_ALLOC_MODE_INTERNAL
  15. return heap_caps_malloc(size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  16. #elif CONFIG_BLE_MESH_MEM_ALLOC_MODE_EXTERNAL
  17. return heap_caps_malloc_prefer(size, 2, MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  18. #elif CONFIG_BLE_MESH_MEM_ALLOC_MODE_IRAM_8BIT
  19. return heap_caps_malloc_prefer(size, 2, MALLOC_CAP_INTERNAL|MALLOC_CAP_IRAM_8BIT, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  20. #else
  21. return malloc(size);
  22. #endif
  23. }
  24. IRAM_ATTR void *bt_mesh_calloc(size_t size)
  25. {
  26. #ifdef CONFIG_BLE_MESH_MEM_ALLOC_MODE_INTERNAL
  27. return heap_caps_calloc(1, size, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  28. #elif CONFIG_BLE_MESH_MEM_ALLOC_MODE_EXTERNAL
  29. return heap_caps_calloc_prefer(1, size, 2, MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  30. #elif CONFIG_BLE_MESH_MEM_ALLOC_MODE_IRAM_8BIT
  31. return heap_caps_calloc_prefer(1, size, 2, MALLOC_CAP_INTERNAL|MALLOC_CAP_IRAM_8BIT, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
  32. #else
  33. return calloc(1, size);
  34. #endif
  35. }
  36. IRAM_ATTR void bt_mesh_free(void *ptr)
  37. {
  38. heap_caps_free(ptr);
  39. }
  40. struct net_buf_simple *bt_mesh_alloc_buf(uint16_t size)
  41. {
  42. struct net_buf_simple *buf = NULL;
  43. uint8_t *data = NULL;
  44. buf = (struct net_buf_simple *)bt_mesh_calloc(sizeof(struct net_buf_simple) + size);
  45. if (!buf) {
  46. BT_ERR("%s, Out of memory", __func__);
  47. return NULL;
  48. }
  49. data = (uint8_t *)buf + sizeof(struct net_buf_simple);
  50. buf->data = data;
  51. buf->len = 0;
  52. buf->size = size;
  53. buf->__buf = data;
  54. return buf;
  55. }
  56. void bt_mesh_free_buf(struct net_buf_simple *buf)
  57. {
  58. if (buf) {
  59. bt_mesh_free(buf);
  60. }
  61. }
  62. int bt_mesh_rand(void *buf, size_t len)
  63. {
  64. if (buf == NULL || len == 0) {
  65. BT_ERR("%s, Invalid parameter", __func__);
  66. return -EINVAL;
  67. }
  68. esp_fill_random(buf, len);
  69. BT_DBG("Random %s", bt_hex(buf, len));
  70. return 0;
  71. }