1 /*
2  * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 /**
7  * @file esp_pbuf reference
8  * This file handles lwip custom pbufs interfacing with esp_netif
9  * and the L2 free function esp_netif_free_rx_buffer()
10  */
11 
12 #include "lwip/mem.h"
13 #include "lwip/esp_pbuf_ref.h"
14 #include "esp_netif_net_stack.h"
15 
16 /**
17  * @brief Specific pbuf structure for pbufs allocated by ESP netif
18  * of PBUF_REF type
19  */
20 typedef struct esp_custom_pbuf
21 {
22     struct pbuf_custom p;
23     esp_netif_t *esp_netif;
24     void* l2_buf;
25 } esp_custom_pbuf_t;
26 
27 /**
28  * @brief Free custom pbuf containing the L2 layer buffer allocated in the driver
29  *
30  * @param pbuf Custom pbuf holding the packet passed to lwip input
31  * @note This function called as a custom_free_function() upon pbuf_free()
32  */
esp_pbuf_free(struct pbuf * pbuf)33 static void esp_pbuf_free(struct pbuf *pbuf)
34 {
35     esp_custom_pbuf_t* esp_pbuf = (esp_custom_pbuf_t*)pbuf;
36     esp_netif_free_rx_buffer(esp_pbuf->esp_netif, esp_pbuf->l2_buf);
37     mem_free(pbuf);
38 }
39 
40 /**
41  * @brief Allocate custom pbuf for supplied sp_netif
42  * @param esp_netif esp-netif handle
43  * @param buffer Buffer to allocate
44  * @param len Size of the buffer
45  * @param l2_buff External l2 buffe
46  * @return Custom pbuf pointer on success; NULL if no free heap
47  */
esp_pbuf_allocate(esp_netif_t * esp_netif,void * buffer,size_t len,void * l2_buff)48 struct pbuf* esp_pbuf_allocate(esp_netif_t *esp_netif, void *buffer, size_t len, void *l2_buff)
49 {
50     struct pbuf *p;
51 
52     esp_custom_pbuf_t* esp_pbuf  = mem_malloc(sizeof(esp_custom_pbuf_t));
53     if (esp_pbuf == NULL) {
54         return NULL;
55     }
56     esp_pbuf->p.custom_free_function = esp_pbuf_free;
57     esp_pbuf->esp_netif = esp_netif;
58     esp_pbuf->l2_buf = l2_buff;
59     p = pbuf_alloced_custom(PBUF_RAW, len, PBUF_REF, &esp_pbuf->p, buffer, len);
60     if (p == NULL) {
61         mem_free(esp_pbuf);
62         return NULL;
63     }
64     return p;
65 }
66