Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / lwip / repo / lwip / src / core / pbuf.c
1 /**
2  * @file
3  * Packet buffer management
4  */
5
6 /**
7  * @defgroup pbuf Packet buffers (PBUF)
8  * @ingroup infrastructure
9  *
10  * Packets are built from the pbuf data structure. It supports dynamic
11  * memory allocation for packet contents or can reference externally
12  * managed packet contents both in RAM and ROM. Quick allocation for
13  * incoming packets is provided through pools with fixed sized pbufs.
14  *
15  * A packet may span over multiple pbufs, chained as a singly linked
16  * list. This is called a "pbuf chain".
17  *
18  * Multiple packets may be queued, also using this singly linked list.
19  * This is called a "packet queue".
20  *
21  * So, a packet queue consists of one or more pbuf chains, each of
22  * which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE
23  * NOT SUPPORTED!!! Use helper structs to queue multiple packets.
24  *
25  * The differences between a pbuf chain and a packet queue are very
26  * precise but subtle.
27  *
28  * The last pbuf of a packet has a ->tot_len field that equals the
29  * ->len field. It can be found by traversing the list. If the last
30  * pbuf of a packet has a ->next field other than NULL, more packets
31  * are on the queue.
32  *
33  * Therefore, looping through a pbuf of a single packet, has an
34  * loop end condition (tot_len == p->len), NOT (next == NULL).
35  *
36  * Example of custom pbuf usage for zero-copy RX:
37   @code{.c}
38 typedef struct my_custom_pbuf
39 {
40    struct pbuf_custom p;
41    void* dma_descriptor;
42 } my_custom_pbuf_t;
43
44 LWIP_MEMPOOL_DECLARE(RX_POOL, 10, sizeof(my_custom_pbuf_t), "Zero-copy RX PBUF pool");
45
46 void my_pbuf_free_custom(void* p)
47 {
48   my_custom_pbuf_t* my_puf = (my_custom_pbuf_t*)p;
49
50   LOCK_INTERRUPTS();
51   free_rx_dma_descriptor(my_pbuf->dma_descriptor);
52   LWIP_MEMPOOL_FREE(RX_POOL, my_pbuf);
53   UNLOCK_INTERRUPTS();
54 }
55
56 void eth_rx_irq()
57 {
58   dma_descriptor*   dma_desc = get_RX_DMA_descriptor_from_ethernet();
59   my_custom_pbuf_t* my_pbuf  = (my_custom_pbuf_t*)LWIP_MEMPOOL_ALLOC(RX_POOL);
60
61   my_pbuf->p.custom_free_function = my_pbuf_free_custom;
62   my_pbuf->dma_descriptor         = dma_desc;
63
64   invalidate_cpu_cache(dma_desc->rx_data, dma_desc->rx_length);
65   
66   struct pbuf* p = pbuf_alloced_custom(PBUF_RAW,
67      dma_desc->rx_length,
68      PBUF_REF,
69      &my_pbuf->p,
70      dma_desc->rx_data,
71      dma_desc->max_buffer_size);
72
73   if(netif->input(p, netif) != ERR_OK) {
74     pbuf_free(p);
75   }
76 }
77   @endcode
78  */
79
80 /*
81  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
82  * All rights reserved.
83  *
84  * Redistribution and use in source and binary forms, with or without modification,
85  * are permitted provided that the following conditions are met:
86  *
87  * 1. Redistributions of source code must retain the above copyright notice,
88  *    this list of conditions and the following disclaimer.
89  * 2. Redistributions in binary form must reproduce the above copyright notice,
90  *    this list of conditions and the following disclaimer in the documentation
91  *    and/or other materials provided with the distribution.
92  * 3. The name of the author may not be used to endorse or promote products
93  *    derived from this software without specific prior written permission.
94  *
95  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
96  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
97  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
98  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
99  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
100  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
101  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
102  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
103  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
104  * OF SUCH DAMAGE.
105  *
106  * This file is part of the lwIP TCP/IP stack.
107  *
108  * Author: Adam Dunkels <adam@sics.se>
109  *
110  */
111
112 #include "lwip/opt.h"
113
114 #include "lwip/stats.h"
115 #include "lwip/def.h"
116 #include "lwip/mem.h"
117 #include "lwip/memp.h"
118 #include "lwip/pbuf.h"
119 #include "lwip/sys.h"
120 #if LWIP_PERF || LWIP_PBUF_CALLOUTS
121 #include "arch/perf.h"
122 #endif
123 #if LWIP_TCP && TCP_QUEUE_OOSEQ
124 #include "lwip/priv/tcp_priv.h"
125 #endif
126 #if LWIP_CHECKSUM_ON_COPY
127 #include "lwip/inet_chksum.h"
128 #endif
129
130 #include <string.h>
131
132 #define SIZEOF_STRUCT_PBUF        LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf))
133
134 #if LWIP_PBUF_FROM_CUSTOM_POOLS
135 #define GET_ALIGNED_PBUF_POOL_SIZE(x) (LWIP_MEM_ALIGN_SIZE(memp_sizes[x]) - SIZEOF_STRUCT_PBUF)
136 #else
137 #define GET_ALIGNED_PBUF_POOL_SIZE(x) LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
138 #endif
139
140 #if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ
141 #define PBUF_POOL_IS_EMPTY()
142 #else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
143
144 #if !NO_SYS
145 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
146 #include "lwip/tcpip.h"
147 #define PBUF_POOL_FREE_OOSEQ_QUEUE_CALL()  do { \
148   if (tcpip_callback_with_block(pbuf_free_ooseq_callback, NULL, 0) != ERR_OK) { \
149       SYS_ARCH_PROTECT(old_level); \
150       pbuf_free_ooseq_pending = 0; \
151       SYS_ARCH_UNPROTECT(old_level); \
152   } } while(0)
153 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
154 #endif /* !NO_SYS */
155
156 volatile u8_t pbuf_free_ooseq_pending;
157 #define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
158
159 /**
160  * Attempt to reclaim some memory from queued out-of-sequence TCP segments
161  * if we run out of pool pbufs. It's better to give priority to new packets
162  * if we're running out.
163  *
164  * This must be done in the correct thread context therefore this function
165  * can only be used with NO_SYS=0 and through tcpip_callback.
166  */
167 #if !NO_SYS
168 static
169 #endif /* !NO_SYS */
170 void
171 pbuf_free_ooseq(void)
172 {
173   struct tcp_pcb* pcb;
174   SYS_ARCH_SET(pbuf_free_ooseq_pending, 0);
175
176   for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
177     if (NULL != pcb->ooseq) {
178       /** Free the ooseq pbufs of one PCB only */
179       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
180       tcp_segs_free(pcb->ooseq);
181       pcb->ooseq = NULL;
182       return;
183     }
184   }
185 }
186
187 #if !NO_SYS
188 /**
189  * Just a callback function for tcpip_callback() that calls pbuf_free_ooseq().
190  */
191 static void
192 pbuf_free_ooseq_callback(void *arg)
193 {
194   LWIP_UNUSED_ARG(arg);
195   pbuf_free_ooseq();
196 }
197 #endif /* !NO_SYS */
198
199 /** Queue a call to pbuf_free_ooseq if not already queued. */
200 static void
201 pbuf_pool_is_empty(void)
202 {
203 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
204   SYS_ARCH_SET(pbuf_free_ooseq_pending, 1);
205 #else /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
206   u8_t queued;
207   SYS_ARCH_DECL_PROTECT(old_level);
208   SYS_ARCH_PROTECT(old_level);
209   queued = pbuf_free_ooseq_pending;
210   pbuf_free_ooseq_pending = 1;
211   SYS_ARCH_UNPROTECT(old_level);
212
213   if (!queued) {
214     /* queue a call to pbuf_free_ooseq if not already queued */
215     PBUF_POOL_FREE_OOSEQ_QUEUE_CALL();
216   }
217 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
218 }
219 #endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
220
221 /**
222  * Decide which pbuf pool to draw from
223  */
224 memp_t
225 pbuf_get_target_pool(u16_t length, u16_t offset)
226 {
227   memp_t target_pool;
228 #if LWIP_PBUF_FROM_CUSTOM_POOLS
229   u32_t total_length;
230   target_pool = PBUF_CUSTOM_POOL_IDX_START;
231   total_length = (u32_t)LWIP_MEM_ALIGN(length + offset + SIZEOF_STRUCT_PBUF);
232
233   /* Start at smallest pool, try to find a pbuf pool whose
234    * pbufs will accommodate the requested size.  Stop when we
235    * find a pool or when we reach the largest pool */
236   while (1) {
237     if (total_length <= memp_sizes[target_pool] || target_pool == PBUF_CUSTOM_POOL_IDX_END) {
238         LWIP_DEBUGF(PBUF_DEBUG| LWIP_DBG_TRACE, ("pbuf_get_target_pool: total_len %u memp_sizes %u\n", total_length, memp_sizes[target_pool]));
239         break;
240     }
241     target_pool--;
242   }
243 #else
244   target_pool = MEMP_PBUF_POOL;
245 #endif
246   return target_pool;
247 }
248
249 static struct pbuf *
250 pbuf_allocate_from_target_pool(memp_t *target_pool)
251 {
252   struct pbuf *p;
253 #if LWIP_PBUF_FROM_CUSTOM_POOLS
254   while (1) {
255     /* allocate head of pbuf chain into p,
256      * if allocation fails, scan all pbuf pools
257      * for a suitable pool to use instead */
258     p = (struct pbuf *)memp_malloc(*target_pool);
259     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p (%u)\n", (void *)p, *target_pool));
260
261     /* We have successfully allocated, or we have no more
262      * pools to try if we failed */
263     if (p != NULL) {
264       p->pool = *target_pool;
265 #if LWIP_PERF
266       sys_profile_pbuf_allocate(p);
267 #endif
268       break;
269     }
270
271     if(*target_pool == PBUF_CUSTOM_POOL_IDX_END) {
272       break;
273     }
274
275     (*target_pool)--;
276   }
277 #else
278   p = (struct pbuf *)memp_malloc(*target_pool);
279 #endif
280   return p;
281 }
282
283 /**
284  * @ingroup pbuf
285  * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
286  *
287  * The actual memory allocated for the pbuf is determined by the
288  * layer at which the pbuf is allocated and the requested size
289  * (from the size parameter).
290  *
291  * @param layer flag to define header size
292  * @param length size of the pbuf's payload
293  * @param type this parameter decides how and where the pbuf
294  * should be allocated as follows:
295  *
296  * - PBUF_RAM: buffer memory for pbuf is allocated as one large
297  *             chunk. This includes protocol headers as well.
298  * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
299  *             protocol headers. Additional headers must be prepended
300  *             by allocating another pbuf and chain in to the front of
301  *             the ROM pbuf. It is assumed that the memory used is really
302  *             similar to ROM in that it is immutable and will not be
303  *             changed. Memory which is dynamic should generally not
304  *             be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
305  * - PBUF_REF: no buffer memory is allocated for the pbuf, even for
306  *             protocol headers. It is assumed that the pbuf is only
307  *             being used in a single thread. If the pbuf gets queued,
308  *             then pbuf_take should be called to copy the buffer.
309  * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
310  *              the pbuf pool that is allocated during pbuf_init().
311  *
312  * @return the allocated pbuf. If multiple pbufs where allocated, this
313  * is the first pbuf of a pbuf chain.
314  */
315 struct pbuf *
316 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
317 {
318   struct pbuf *p, *q, *r;
319   u16_t offset;
320   s32_t rem_len; /* remaining length */
321   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
322   u32_t aligned_size;
323   memp_t target_pool;
324
325   /* determine header offset */
326   switch (layer) {
327   case PBUF_TRANSPORT:
328     /* add room for transport (often TCP) layer header */
329     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
330     break;
331   case PBUF_IP:
332     /* add room for IP layer header */
333     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN;
334     break;
335   case PBUF_LINK:
336     /* add room for link layer header */
337     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN;
338     break;
339   case PBUF_RAW_TX:
340     /* add room for encapsulating link layer headers (e.g. 802.11) */
341     offset = PBUF_LINK_ENCAPSULATION_HLEN;
342     break;
343   case PBUF_RAW:
344     /* no offset (e.g. RX buffers or chain successors) */
345     offset = 0;
346     break;
347   default:
348     LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
349     return NULL;
350   }
351
352   switch (type) {
353   case PBUF_POOL:
354     target_pool = pbuf_get_target_pool(length, offset);
355     p = pbuf_allocate_from_target_pool(&target_pool);
356
357     if (p == NULL) {
358       PBUF_POOL_IS_EMPTY();
359       return NULL;
360     }
361
362     aligned_size = GET_ALIGNED_PBUF_POOL_SIZE(target_pool);
363     p->type = type;
364     p->next = NULL;
365
366     /* make the payload pointer point 'offset' bytes into pbuf data memory */
367     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
368     LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
369             ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
370     /* the total length of the pbuf chain is the requested size */
371     p->tot_len = length;
372     /* set the length of the first pbuf in the chain */
373     p->len = LWIP_MIN(length, aligned_size - LWIP_MEM_ALIGN_SIZE(offset));
374     LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
375                 ((u8_t*)p->payload + p->len <=
376                  (u8_t*)p + SIZEOF_STRUCT_PBUF + aligned_size));
377     LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
378       (aligned_size - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
379     /* set reference count (needed here in case we fail) */
380     p->ref = 1;
381     /* set flags */
382     p->flags = 0;
383
384     /* now allocate the tail of the pbuf chain */
385
386     /* remember first pbuf for linkage in next iteration */
387     r = p;
388     /* remaining length to be allocated */
389     rem_len = length - p->len;
390     /* any remaining pbufs to be allocated? */
391     while (rem_len > 0) {
392       target_pool = pbuf_get_target_pool(rem_len, 0);
393       q = pbuf_allocate_from_target_pool(&target_pool);
394       if (q == NULL) {
395         PBUF_POOL_IS_EMPTY();
396         /* free chain so far allocated */
397         pbuf_free(p);
398         /* bail out unsuccessfully */
399         return NULL;
400       }
401       aligned_size = GET_ALIGNED_PBUF_POOL_SIZE(target_pool);
402       q->type = type;
403       q->flags = 0;
404       q->next = NULL;
405       /* make previous pbuf point to this pbuf */
406       r->next = q;
407       /* set total length of this pbuf and next in chain */
408       LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
409       q->tot_len = (u16_t)rem_len;
410       /* this pbuf length is pool size, unless smaller sized tail */
411       q->len = LWIP_MIN((u16_t)rem_len, aligned_size);
412       q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
413       LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
414               ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
415       LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
416                   ((u8_t*)p->payload + p->len <=
417                    (u8_t*)p + SIZEOF_STRUCT_PBUF + aligned_size));
418       q->ref = 1;
419       /* calculate remaining length to be allocated */
420       rem_len -= q->len;
421       /* remember this pbuf for linkage in next iteration */
422       r = q;
423     }
424     /* end of chain */
425     /*r->next = NULL;*/
426
427     break;
428   case PBUF_RAM:
429     {
430       u16_t payload_len = (u16_t)(LWIP_MEM_ALIGN_SIZE(offset) + LWIP_MEM_ALIGN_SIZE(length));
431       mem_size_t alloc_len = (mem_size_t)(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF) + payload_len);
432
433       /* bug #50040: Check for integer overflow when calculating alloc_len */
434       if ((payload_len < LWIP_MEM_ALIGN_SIZE(length)) ||
435           (alloc_len < LWIP_MEM_ALIGN_SIZE(length))) {
436         return NULL;
437       }
438
439       /* If pbuf is to be allocated in RAM, allocate memory for it. */
440       p = (struct pbuf*)mem_malloc(alloc_len);
441     }
442
443     if (p == NULL) {
444       return NULL;
445     }
446     /* Set up internal structure of the pbuf. */
447     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
448     p->len = p->tot_len = length;
449     p->next = NULL;
450     p->type = type;
451
452     LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
453            ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
454     break;
455   /* pbuf references existing (non-volatile static constant) ROM payload? */
456   case PBUF_ROM:
457   /* pbuf references existing (externally allocated) RAM payload? */
458   case PBUF_REF:
459     /* only allocate memory for the pbuf structure */
460     p = (struct pbuf *)memp_malloc(MEMP_PBUF);
461     if (p == NULL) {
462       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
463                   ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
464                   (type == PBUF_ROM) ? "ROM" : "REF"));
465       return NULL;
466     }
467     /* caller must set this field properly, afterwards */
468     p->payload = NULL;
469     p->len = p->tot_len = length;
470     p->next = NULL;
471     p->type = type;
472     break;
473   default:
474     LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
475     return NULL;
476   }
477   /* set reference count */
478   p->ref = 1;
479   /* set flags */
480   p->flags = 0;
481   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
482   return p;
483 }
484
485 #if LWIP_SUPPORT_CUSTOM_PBUF
486 /**
487  * @ingroup pbuf
488  * Initialize a custom pbuf (already allocated).
489  *
490  * @param l flag to define header size
491  * @param length size of the pbuf's payload
492  * @param type type of the pbuf (only used to treat the pbuf accordingly, as
493  *        this function allocates no memory)
494  * @param p pointer to the custom pbuf to initialize (already allocated)
495  * @param payload_mem pointer to the buffer that is used for payload and headers,
496  *        must be at least big enough to hold 'length' plus the header size,
497  *        may be NULL if set later.
498  *        ATTENTION: The caller is responsible for correct alignment of this buffer!!
499  * @param payload_mem_len the size of the 'payload_mem' buffer, must be at least
500  *        big enough to hold 'length' plus the header size
501  */
502 struct pbuf*
503 pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p,
504                     void *payload_mem, u16_t payload_mem_len)
505 {
506   u16_t offset;
507   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloced_custom(length=%"U16_F")\n", length));
508
509   /* determine header offset */
510   switch (l) {
511   case PBUF_TRANSPORT:
512     /* add room for transport (often TCP) layer header */
513     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
514     break;
515   case PBUF_IP:
516     /* add room for IP layer header */
517     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN;
518     break;
519   case PBUF_LINK:
520     /* add room for link layer header */
521     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN;
522     break;
523   case PBUF_RAW_TX:
524     /* add room for encapsulating link layer headers (e.g. 802.11) */
525     offset = PBUF_LINK_ENCAPSULATION_HLEN;
526     break;
527   case PBUF_RAW:
528     offset = 0;
529     break;
530   default:
531     LWIP_ASSERT("pbuf_alloced_custom: bad pbuf layer", 0);
532     return NULL;
533   }
534
535   if (LWIP_MEM_ALIGN_SIZE(offset) + length > payload_mem_len) {
536     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_WARNING, ("pbuf_alloced_custom(length=%"U16_F") buffer too short\n", length));
537     return NULL;
538   }
539
540   p->pbuf.next = NULL;
541   if (payload_mem != NULL) {
542     p->pbuf.payload = (u8_t *)payload_mem + LWIP_MEM_ALIGN_SIZE(offset);
543   } else {
544     p->pbuf.payload = NULL;
545   }
546   p->pbuf.flags = PBUF_FLAG_IS_CUSTOM;
547   p->pbuf.len = p->pbuf.tot_len = length;
548   p->pbuf.type = type;
549   p->pbuf.ref = 1;
550   return &p->pbuf;
551 }
552 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
553
554 /**
555  * @ingroup pbuf
556  * Shrink a pbuf chain to a desired length.
557  *
558  * @param p pbuf to shrink.
559  * @param new_len desired new length of pbuf chain
560  *
561  * Depending on the desired length, the first few pbufs in a chain might
562  * be skipped and left unchanged. The new last pbuf in the chain will be
563  * resized, and any remaining pbufs will be freed.
564  *
565  * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
566  * @note May not be called on a packet queue.
567  *
568  * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
569  */
570 void
571 pbuf_realloc(struct pbuf *p, u16_t new_len)
572 {
573   struct pbuf *q;
574   u16_t rem_len; /* remaining length */
575   s32_t grow;
576
577   LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
578   LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
579               p->type == PBUF_ROM ||
580               p->type == PBUF_RAM ||
581               p->type == PBUF_REF);
582
583   /* desired length larger than current length? */
584   if (new_len >= p->tot_len) {
585     /* enlarging not yet supported */
586     return;
587   }
588
589   /* the pbuf chain grows by (new_len - p->tot_len) bytes
590    * (which may be negative in case of shrinking) */
591   grow = new_len - p->tot_len;
592
593   /* first, step over any pbufs that should remain in the chain */
594   rem_len = new_len;
595   q = p;
596   /* should this pbuf be kept? */
597   while (rem_len > q->len) {
598     /* decrease remaining length by pbuf length */
599     rem_len -= q->len;
600     /* decrease total length indicator */
601     LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
602     q->tot_len += (u16_t)grow;
603     /* proceed to next pbuf in chain */
604     q = q->next;
605     LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
606   }
607   /* we have now reached the new last pbuf (in q) */
608   /* rem_len == desired length for pbuf q */
609
610   /* shrink allocated memory for PBUF_RAM */
611   /* (other types merely adjust their length fields */
612   if ((q->type == PBUF_RAM) && (rem_len != q->len)
613 #if LWIP_SUPPORT_CUSTOM_PBUF
614       && ((q->flags & PBUF_FLAG_IS_CUSTOM) == 0)
615 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
616      ) {
617     /* reallocate and adjust the length of the pbuf that will be split */
618     q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len);
619     LWIP_ASSERT("mem_trim returned q == NULL", q != NULL);
620   }
621   /* adjust length fields for new last pbuf */
622   q->len = rem_len;
623   q->tot_len = q->len;
624
625   /* any remaining pbufs in chain? */
626   if (q->next != NULL) {
627     /* free remaining pbufs in chain */
628     pbuf_free(q->next);
629   }
630   /* q is last packet in chain */
631   q->next = NULL;
632
633 }
634
635 /**
636  * Adjusts the payload pointer to hide or reveal headers in the payload.
637  * @see pbuf_header.
638  *
639  * @param p pbuf to change the header size.
640  * @param header_size_increment Number of bytes to increment header size.
641  * @param force Allow 'header_size_increment > 0' for PBUF_REF/PBUF_ROM types
642  *
643  * @return non-zero on failure, zero on success.
644  *
645  */
646 static u8_t
647 pbuf_header_impl(struct pbuf *p, s16_t header_size_increment, u8_t force)
648 {
649   u16_t type;
650   void *payload;
651   u16_t increment_magnitude;
652
653   LWIP_ASSERT("p != NULL", p != NULL);
654   if ((header_size_increment == 0) || (p == NULL)) {
655     return 0;
656   }
657
658   if (header_size_increment < 0) {
659     increment_magnitude = (u16_t)-header_size_increment;
660     /* Check that we aren't going to move off the end of the pbuf */
661     LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
662   } else {
663     increment_magnitude = (u16_t)header_size_increment;
664 #if 0
665     /* Can't assert these as some callers speculatively call
666          pbuf_header() to see if it's OK.  Will return 1 below instead. */
667     /* Check that we've got the correct type of pbuf to work with */
668     LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL",
669                 p->type == PBUF_RAM || p->type == PBUF_POOL);
670     /* Check that we aren't going to move off the beginning of the pbuf */
671     LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
672                 (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
673 #endif
674   }
675
676   type = p->type;
677   /* remember current payload pointer */
678   payload = p->payload;
679
680   /* pbuf types containing payloads? */
681   if (type == PBUF_RAM || type == PBUF_POOL) {
682     /* set new payload pointer */
683     p->payload = (u8_t *)p->payload - header_size_increment;
684     /* boundary check fails? */
685     if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
686       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE,
687         ("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
688         (void *)p->payload, (void *)((u8_t *)p + SIZEOF_STRUCT_PBUF)));
689       /* restore old payload pointer */
690       p->payload = payload;
691       /* bail out unsuccessfully */
692       return 1;
693     }
694   /* pbuf types referring to external payloads? */
695   } else if (type == PBUF_REF || type == PBUF_ROM) {
696     /* hide a header in the payload? */
697     if ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
698       /* increase payload pointer */
699       p->payload = (u8_t *)p->payload - header_size_increment;
700     } else if ((header_size_increment > 0) && force) {
701       p->payload = (u8_t *)p->payload - header_size_increment;
702     } else {
703       /* cannot expand payload to front (yet!)
704        * bail out unsuccessfully */
705       return 1;
706     }
707   } else {
708     /* Unknown type */
709     LWIP_ASSERT("bad pbuf type", 0);
710     return 1;
711   }
712   /* modify pbuf length fields */
713   p->len += header_size_increment;
714   p->tot_len += header_size_increment;
715
716   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
717     (void *)payload, (void *)p->payload, header_size_increment));
718
719   return 0;
720 }
721
722 /**
723  * Adjusts the payload pointer to hide or reveal headers in the payload.
724  *
725  * Adjusts the ->payload pointer so that space for a header
726  * (dis)appears in the pbuf payload.
727  *
728  * The ->payload, ->tot_len and ->len fields are adjusted.
729  *
730  * @param p pbuf to change the header size.
731  * @param header_size_increment Number of bytes to increment header size which
732  * increases the size of the pbuf. New space is on the front.
733  * (Using a negative value decreases the header size.)
734  * If hdr_size_inc is 0, this function does nothing and returns successful.
735  *
736  * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
737  * the call will fail. A check is made that the increase in header size does
738  * not move the payload pointer in front of the start of the buffer.
739  * @return non-zero on failure, zero on success.
740  *
741  */
742 u8_t
743 pbuf_header(struct pbuf *p, s16_t header_size_increment)
744 {
745    return pbuf_header_impl(p, header_size_increment, 0);
746 }
747
748 /**
749  * Same as pbuf_header but does not check if 'header_size > 0' is allowed.
750  * This is used internally only, to allow PBUF_REF for RX.
751  */
752 u8_t
753 pbuf_header_force(struct pbuf *p, s16_t header_size_increment)
754 {
755    return pbuf_header_impl(p, header_size_increment, 1);
756 }
757
758 /**
759  * @ingroup pbuf
760  * Dereference a pbuf chain or queue and deallocate any no-longer-used
761  * pbufs at the head of this chain or queue.
762  *
763  * Decrements the pbuf reference count. If it reaches zero, the pbuf is
764  * deallocated.
765  *
766  * For a pbuf chain, this is repeated for each pbuf in the chain,
767  * up to the first pbuf which has a non-zero reference count after
768  * decrementing. So, when all reference counts are one, the whole
769  * chain is free'd.
770  *
771  * @param p The pbuf (chain) to be dereferenced.
772  *
773  * @return the number of pbufs that were de-allocated
774  * from the head of the chain.
775  *
776  * @note MUST NOT be called on a packet queue (Not verified to work yet).
777  * @note the reference counter of a pbuf equals the number of pointers
778  * that refer to the pbuf (or into the pbuf).
779  *
780  * @internal examples:
781  *
782  * Assuming existing chains a->b->c with the following reference
783  * counts, calling pbuf_free(a) results in:
784  *
785  * 1->2->3 becomes ...1->3
786  * 3->3->3 becomes 2->3->3
787  * 1->1->2 becomes ......1
788  * 2->1->1 becomes 1->1->1
789  * 1->1->1 becomes .......
790  *
791  */
792 u8_t
793 pbuf_free(struct pbuf *p)
794 {
795   u16_t type;
796   struct pbuf *q;
797   u8_t count;
798   memp_t target_pool;
799
800   if (p == NULL) {
801     LWIP_ASSERT("p != NULL", p != NULL);
802     /* if assertions are disabled, proceed with debug output */
803     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
804       ("pbuf_free(p == NULL) was called.\n"));
805     return 0;
806   }
807   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
808
809   PERF_START;
810
811   LWIP_ASSERT("pbuf_free: sane type",
812     p->type == PBUF_RAM || p->type == PBUF_ROM ||
813     p->type == PBUF_REF || p->type == PBUF_POOL);
814
815   count = 0;
816   /* de-allocate all consecutive pbufs from the head of the chain that
817    * obtain a zero reference count after decrementing*/
818   while (p != NULL) {
819     u16_t ref;
820     SYS_ARCH_DECL_PROTECT(old_level);
821     /* Since decrementing ref cannot be guaranteed to be a single machine operation
822      * we must protect it. We put the new ref into a local variable to prevent
823      * further protection. */
824     SYS_ARCH_PROTECT(old_level);
825     /* all pbufs in a chain are referenced at least once */
826     LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
827 #if LWIP_PBUF_CALLOUTS
828     sys_pbuf_free_callout(p);
829 #endif /* LWIP_PBUF_CALLOUTS */
830     /* decrease reference count (number of pointers to pbuf) */
831     ref = --(p->ref);
832     SYS_ARCH_UNPROTECT(old_level);
833     /* this pbuf is no longer referenced to? */
834     if (ref == 0) {
835       /* remember next pbuf in chain for next iteration */
836       q = p->next;
837       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
838       type = p->type;
839 #if LWIP_SUPPORT_CUSTOM_PBUF
840       /* is this a custom pbuf? */
841       if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) {
842         struct pbuf_custom *pc = (struct pbuf_custom*)p;
843         LWIP_ASSERT("pc->custom_free_function != NULL", pc->custom_free_function != NULL);
844         pc->custom_free_function(p);
845       } else
846 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
847       {
848         /* is this a pbuf from the pool? */
849         if (type == PBUF_POOL) {
850 #if LWIP_PBUF_FROM_CUSTOM_POOLS
851           target_pool = p->pool;
852 #if LWIP_PERF
853           // Record free of buffer before actually freeing for 2 reasons:
854           // - Pool pointer still valid
855           // - Prevent buf from being re-allocated before recording free
856           sys_profile_pbuf_free(p);
857 #endif
858 #else
859           target_pool = MEMP_PBUF_POOL;
860 #endif
861
862           memp_free(target_pool, p);
863         /* is this a ROM or RAM referencing pbuf? */
864         } else if (type == PBUF_ROM || type == PBUF_REF) {
865           memp_free(MEMP_PBUF, p);
866         /* type == PBUF_RAM */
867         } else {
868           mem_free(p);
869         }
870       }
871       count++;
872       /* proceed to next pbuf */
873       p = q;
874     /* p->ref > 0, this pbuf is still referenced to */
875     /* (and so the remaining pbufs in chain as well) */
876     } else {
877       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
878       /* stop walking through the chain */
879       p = NULL;
880     }
881   }
882   PERF_STOP("pbuf_free");
883   /* return number of de-allocated pbufs */
884   return count;
885 }
886
887 /**
888  * Count number of pbufs in a chain
889  *
890  * @param p first pbuf of chain
891  * @return the number of pbufs in a chain
892  */
893 u16_t
894 pbuf_clen(const struct pbuf *p)
895 {
896   u16_t len;
897
898   len = 0;
899   while (p != NULL) {
900     ++len;
901     p = p->next;
902   }
903   return len;
904 }
905
906 /**
907  * @ingroup pbuf
908  * Increment the reference count of the pbuf.
909  *
910  * @param p pbuf to increase reference counter of
911  *
912  */
913 void
914 pbuf_ref(struct pbuf *p)
915 {
916   /* pbuf given? */
917   if (p != NULL) {
918     SYS_ARCH_INC(p->ref, 1);
919     LWIP_ASSERT("pbuf ref overflow", p->ref > 0);
920   }
921 }
922
923 /**
924  * @ingroup pbuf
925  * Concatenate two pbufs (each may be a pbuf chain) and take over
926  * the caller's reference of the tail pbuf.
927  *
928  * @note The caller MAY NOT reference the tail pbuf afterwards.
929  * Use pbuf_chain() for that purpose.
930  *
931  * @see pbuf_chain()
932  */
933 void
934 pbuf_cat(struct pbuf *h, struct pbuf *t)
935 {
936   struct pbuf *p;
937
938   LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
939              ((h != NULL) && (t != NULL)), return;);
940
941   /* proceed to last pbuf of chain */
942   for (p = h; p->next != NULL; p = p->next) {
943     /* add total length of second chain to all totals of first chain */
944     p->tot_len += t->tot_len;
945   }
946   /* { p is last pbuf of first h chain, p->next == NULL } */
947   LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
948   LWIP_ASSERT("p->next == NULL", p->next == NULL);
949   /* add total length of second chain to last pbuf total of first chain */
950   p->tot_len += t->tot_len;
951   /* chain last pbuf of head (p) with first of tail (t) */
952   p->next = t;
953   /* p->next now references t, but the caller will drop its reference to t,
954    * so netto there is no change to the reference count of t.
955    */
956 }
957
958 /**
959  * @ingroup pbuf
960  * Chain two pbufs (or pbuf chains) together.
961  *
962  * The caller MUST call pbuf_free(t) once it has stopped
963  * using it. Use pbuf_cat() instead if you no longer use t.
964  *
965  * @param h head pbuf (chain)
966  * @param t tail pbuf (chain)
967  * @note The pbufs MUST belong to the same packet.
968  * @note MAY NOT be called on a packet queue.
969  *
970  * The ->tot_len fields of all pbufs of the head chain are adjusted.
971  * The ->next field of the last pbuf of the head chain is adjusted.
972  * The ->ref field of the first pbuf of the tail chain is adjusted.
973  *
974  */
975 void
976 pbuf_chain(struct pbuf *h, struct pbuf *t)
977 {
978   pbuf_cat(h, t);
979   /* t is now referenced by h */
980   pbuf_ref(t);
981   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
982 }
983
984 /**
985  * Dechains the first pbuf from its succeeding pbufs in the chain.
986  *
987  * Makes p->tot_len field equal to p->len.
988  * @param p pbuf to dechain
989  * @return remainder of the pbuf chain, or NULL if it was de-allocated.
990  * @note May not be called on a packet queue.
991  */
992 struct pbuf *
993 pbuf_dechain(struct pbuf *p)
994 {
995   struct pbuf *q;
996   u8_t tail_gone = 1;
997   /* tail */
998   q = p->next;
999   /* pbuf has successor in chain? */
1000   if (q != NULL) {
1001     /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
1002     LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
1003     /* enforce invariant if assertion is disabled */
1004     q->tot_len = p->tot_len - p->len;
1005     /* decouple pbuf from remainder */
1006     p->next = NULL;
1007     /* total length of pbuf p is its own length only */
1008     p->tot_len = p->len;
1009     /* q is no longer referenced by p, free it */
1010     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
1011     tail_gone = pbuf_free(q);
1012     if (tail_gone > 0) {
1013       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
1014                   ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
1015     }
1016     /* return remaining tail or NULL if deallocated */
1017   }
1018   /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
1019   LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
1020   return ((tail_gone > 0) ? NULL : q);
1021 }
1022
1023 /**
1024  * @ingroup pbuf
1025  * Create PBUF_RAM copies of pbufs.
1026  *
1027  * Used to queue packets on behalf of the lwIP stack, such as
1028  * ARP based queueing.
1029  *
1030  * @note You MUST explicitly use p = pbuf_take(p);
1031  *
1032  * @note Only one packet is copied, no packet queue!
1033  *
1034  * @param p_to pbuf destination of the copy
1035  * @param p_from pbuf source of the copy
1036  *
1037  * @return ERR_OK if pbuf was copied
1038  *         ERR_ARG if one of the pbufs is NULL or p_to is not big
1039  *                 enough to hold p_from
1040  */
1041 err_t
1042 pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from)
1043 {
1044   u16_t offset_to=0, offset_from=0, len;
1045
1046   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
1047     (const void*)p_to, (const void*)p_from));
1048
1049   /* is the target big enough to hold the source? */
1050   LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
1051              (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
1052
1053   /* iterate through pbuf chain */
1054   do
1055   {
1056     /* copy one part of the original chain */
1057     if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
1058       /* complete current p_from fits into current p_to */
1059       len = p_from->len - offset_from;
1060     } else {
1061       /* current p_from does not fit into current p_to */
1062       len = p_to->len - offset_to;
1063     }
1064     MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
1065     offset_to += len;
1066     offset_from += len;
1067     LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
1068     LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
1069     if (offset_from >= p_from->len) {
1070       /* on to next p_from (if any) */
1071       offset_from = 0;
1072       p_from = p_from->next;
1073     }
1074     if (offset_to == p_to->len) {
1075       /* on to next p_to (if any) */
1076       offset_to = 0;
1077       p_to = p_to->next;
1078       LWIP_ERROR("p_to != NULL", (p_to != NULL) || (p_from == NULL) , return ERR_ARG;);
1079     }
1080
1081     if ((p_from != NULL) && (p_from->len == p_from->tot_len)) {
1082       /* don't copy more than one packet! */
1083       LWIP_ERROR("pbuf_copy() does not allow packet queues!",
1084                  (p_from->next == NULL), return ERR_VAL;);
1085     }
1086     if ((p_to != NULL) && (p_to->len == p_to->tot_len)) {
1087       /* don't copy more than one packet! */
1088       LWIP_ERROR("pbuf_copy() does not allow packet queues!",
1089                   (p_to->next == NULL), return ERR_VAL;);
1090     }
1091   } while (p_from);
1092   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
1093   return ERR_OK;
1094 }
1095
1096 /**
1097  * @ingroup pbuf
1098  * Copy (part of) the contents of a packet buffer
1099  * to an application supplied buffer.
1100  *
1101  * @param buf the pbuf from which to copy data
1102  * @param dataptr the application supplied buffer
1103  * @param len length of data to copy (dataptr must be big enough). No more
1104  * than buf->tot_len will be copied, irrespective of len
1105  * @param offset offset into the packet buffer from where to begin copying len bytes
1106  * @return the number of bytes copied, or 0 on failure
1107  */
1108 u16_t
1109 pbuf_copy_partial(const struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
1110 {
1111   const struct pbuf *p;
1112   u16_t left;
1113   u16_t buf_copy_len;
1114   u16_t copied_total = 0;
1115
1116   LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
1117   LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
1118
1119   left = 0;
1120
1121   if ((buf == NULL) || (dataptr == NULL)) {
1122     return 0;
1123   }
1124
1125   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
1126   for (p = buf; len != 0 && p != NULL; p = p->next) {
1127     if ((offset != 0) && (offset >= p->len)) {
1128       /* don't copy from this buffer -> on to the next */
1129       offset -= p->len;
1130     } else {
1131       /* copy from this buffer. maybe only partially. */
1132       buf_copy_len = p->len - offset;
1133       if (buf_copy_len > len) {
1134         buf_copy_len = len;
1135       }
1136       /* copy the necessary parts of the buffer */
1137       MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
1138       copied_total += buf_copy_len;
1139       left += buf_copy_len;
1140       len -= buf_copy_len;
1141       offset = 0;
1142     }
1143   }
1144   return copied_total;
1145 }
1146
1147 #if LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
1148 /**
1149  * This method modifies a 'pbuf chain', so that its total length is
1150  * smaller than 64K. The remainder of the original pbuf chain is stored
1151  * in *rest.
1152  * This function never creates new pbufs, but splits an existing chain
1153  * in two parts. The tot_len of the modified packet queue will likely be
1154  * smaller than 64K.
1155  * 'packet queues' are not supported by this function.
1156  *
1157  * @param p the pbuf queue to be split
1158  * @param rest pointer to store the remainder (after the first 64K)
1159  */
1160 void pbuf_split_64k(struct pbuf *p, struct pbuf **rest)
1161 {
1162   *rest = NULL;
1163   if ((p != NULL) && (p->next != NULL)) {
1164     u16_t tot_len_front = p->len;
1165     struct pbuf *i = p;
1166     struct pbuf *r = p->next;
1167
1168     /* continue until the total length (summed up as u16_t) overflows */
1169     while ((r != NULL) && ((u16_t)(tot_len_front + r->len) > tot_len_front)) {
1170       tot_len_front = (u16_t)(tot_len_front + r->len);
1171       i = r;
1172       r = r->next;
1173     }
1174     /* i now points to last packet of the first segment. Set next
1175        pointer to NULL */
1176     i->next = NULL;
1177
1178     if (r != NULL) {
1179       /* Update the tot_len field in the first part */
1180       for (i = p; i != NULL; i = i->next) {
1181         i->tot_len = (u16_t)(i->tot_len - r->tot_len);
1182         LWIP_ASSERT("tot_len/len mismatch in last pbuf",
1183                     (i->next != NULL) || (i->tot_len == i->len));
1184       }
1185       if (p->flags & PBUF_FLAG_TCP_FIN) {
1186         r->flags |= PBUF_FLAG_TCP_FIN;
1187       }
1188
1189       /* tot_len field in rest does not need modifications */
1190       /* reference counters do not need modifications */
1191       *rest = r;
1192     }
1193   }
1194 }
1195 #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
1196
1197 /* Actual implementation of pbuf_skip() but returning const pointer... */
1198 static const struct pbuf*
1199 pbuf_skip_const(const struct pbuf* in, u16_t in_offset, u16_t* out_offset)
1200 {
1201   u16_t offset_left = in_offset;
1202   const struct pbuf* q = in;
1203
1204   /* get the correct pbuf */
1205   while ((q != NULL) && (q->len <= offset_left)) {
1206     offset_left -= q->len;
1207     q = q->next;
1208   }
1209   if (out_offset != NULL) {
1210     *out_offset = offset_left;
1211   }
1212   return q;
1213 }
1214
1215 /**
1216  * @ingroup pbuf
1217  * Skip a number of bytes at the start of a pbuf
1218  *
1219  * @param in input pbuf
1220  * @param in_offset offset to skip
1221  * @param out_offset resulting offset in the returned pbuf
1222  * @return the pbuf in the queue where the offset is
1223  */
1224 struct pbuf*
1225 pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset)
1226 {
1227   const struct pbuf* out = pbuf_skip_const(in, in_offset, out_offset);
1228   return LWIP_CONST_CAST(struct pbuf*, out);
1229 }
1230
1231 /**
1232  * @ingroup pbuf
1233  * Copy application supplied data into a pbuf.
1234  * This function can only be used to copy the equivalent of buf->tot_len data.
1235  *
1236  * @param buf pbuf to fill with data
1237  * @param dataptr application supplied data buffer
1238  * @param len length of the application supplied data buffer
1239  *
1240  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
1241  */
1242 err_t
1243 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
1244 {
1245   struct pbuf *p;
1246   u16_t buf_copy_len;
1247   u16_t total_copy_len = len;
1248   u16_t copied_total = 0;
1249
1250   LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return ERR_ARG;);
1251   LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return ERR_ARG;);
1252   LWIP_ERROR("pbuf_take: buf not large enough", (buf->tot_len >= len), return ERR_MEM;);
1253
1254   if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
1255     return ERR_ARG;
1256   }
1257
1258   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
1259   for (p = buf; total_copy_len != 0; p = p->next) {
1260     LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
1261     buf_copy_len = total_copy_len;
1262     if (buf_copy_len > p->len) {
1263       /* this pbuf cannot hold all remaining data */
1264       buf_copy_len = p->len;
1265     }
1266     /* copy the necessary parts of the buffer */
1267     MEMCPY(p->payload, &((const char*)dataptr)[copied_total], buf_copy_len);
1268     total_copy_len -= buf_copy_len;
1269     copied_total += buf_copy_len;
1270   }
1271   LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
1272   return ERR_OK;
1273 }
1274
1275 /**
1276  * @ingroup pbuf
1277  * Same as pbuf_take() but puts data at an offset
1278  *
1279  * @param buf pbuf to fill with data
1280  * @param dataptr application supplied data buffer
1281  * @param len length of the application supplied data buffer
1282  * @param offset offset in pbuf where to copy dataptr to
1283  *
1284  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
1285  */
1286 err_t
1287 pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset)
1288 {
1289   u16_t target_offset;
1290   struct pbuf* q = pbuf_skip(buf, offset, &target_offset);
1291
1292   /* return requested data if pbuf is OK */
1293   if ((q != NULL) && (q->tot_len >= target_offset + len)) {
1294     u16_t remaining_len = len;
1295     const u8_t* src_ptr = (const u8_t*)dataptr;
1296     /* copy the part that goes into the first pbuf */
1297     u16_t first_copy_len = LWIP_MIN(q->len - target_offset, len);
1298     MEMCPY(((u8_t*)q->payload) + target_offset, dataptr, first_copy_len);
1299     remaining_len -= first_copy_len;
1300     src_ptr += first_copy_len;
1301     if (remaining_len > 0) {
1302       return pbuf_take(q->next, src_ptr, remaining_len);
1303     }
1304     return ERR_OK;
1305   }
1306   return ERR_MEM;
1307 }
1308
1309 /**
1310  * @ingroup pbuf
1311  * Creates a single pbuf out of a queue of pbufs.
1312  *
1313  * @remark: Either the source pbuf 'p' is freed by this function or the original
1314  *          pbuf 'p' is returned, therefore the caller has to check the result!
1315  *
1316  * @param p the source pbuf
1317  * @param layer pbuf_layer of the new pbuf
1318  *
1319  * @return a new, single pbuf (p->next is NULL)
1320  *         or the old pbuf if allocation fails
1321  */
1322 struct pbuf*
1323 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
1324 {
1325   struct pbuf *q;
1326   err_t err;
1327   if (p->next == NULL) {
1328     return p;
1329   }
1330   q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
1331   if (q == NULL) {
1332     /* @todo: what do we do now? */
1333     return p;
1334   }
1335   err = pbuf_copy(q, p);
1336   LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
1337   LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
1338   pbuf_free(p);
1339   return q;
1340 }
1341
1342 #if LWIP_CHECKSUM_ON_COPY
1343 /**
1344  * Copies data into a single pbuf (*not* into a pbuf queue!) and updates
1345  * the checksum while copying
1346  *
1347  * @param p the pbuf to copy data into
1348  * @param start_offset offset of p->payload where to copy the data to
1349  * @param dataptr data to copy into the pbuf
1350  * @param len length of data to copy into the pbuf
1351  * @param chksum pointer to the checksum which is updated
1352  * @return ERR_OK if successful, another error if the data does not fit
1353  *         within the (first) pbuf (no pbuf queues!)
1354  */
1355 err_t
1356 pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
1357                  u16_t len, u16_t *chksum)
1358 {
1359   u32_t acc;
1360   u16_t copy_chksum;
1361   char *dst_ptr;
1362   LWIP_ASSERT("p != NULL", p != NULL);
1363   LWIP_ASSERT("dataptr != NULL", dataptr != NULL);
1364   LWIP_ASSERT("chksum != NULL", chksum != NULL);
1365   LWIP_ASSERT("len != 0", len != 0);
1366
1367   if ((start_offset >= p->len) || (start_offset + len > p->len)) {
1368     return ERR_ARG;
1369   }
1370
1371   dst_ptr = ((char*)p->payload) + start_offset;
1372   copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len);
1373   if ((start_offset & 1) != 0) {
1374     copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum);
1375   }
1376   acc = *chksum;
1377   acc += copy_chksum;
1378   *chksum = FOLD_U32T(acc);
1379   return ERR_OK;
1380 }
1381 #endif /* LWIP_CHECKSUM_ON_COPY */
1382
1383 /**
1384  * @ingroup pbuf
1385  * Get one byte from the specified position in a pbuf
1386  * WARNING: returns zero for offset >= p->tot_len
1387  *
1388  * @param p pbuf to parse
1389  * @param offset offset into p of the byte to return
1390  * @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len
1391  */
1392 u8_t
1393 pbuf_get_at(const struct pbuf* p, u16_t offset)
1394 {
1395   int ret = pbuf_try_get_at(p, offset);
1396   if (ret >= 0) {
1397     return (u8_t)ret;
1398   }
1399   return 0;
1400 }
1401
1402 /**
1403  * @ingroup pbuf
1404  * Get one byte from the specified position in a pbuf
1405  *
1406  * @param p pbuf to parse
1407  * @param offset offset into p of the byte to return
1408  * @return byte at an offset into p [0..0xFF] OR negative if 'offset' >= p->tot_len
1409  */
1410 int
1411 pbuf_try_get_at(const struct pbuf* p, u16_t offset)
1412 {
1413   u16_t q_idx;
1414   const struct pbuf* q = pbuf_skip_const(p, offset, &q_idx);
1415
1416   /* return requested data if pbuf is OK */
1417   if ((q != NULL) && (q->len > q_idx)) {
1418     return ((u8_t*)q->payload)[q_idx];
1419   }
1420   return -1;
1421 }
1422
1423 /**
1424  * @ingroup pbuf
1425  * Put one byte to the specified position in a pbuf
1426  * WARNING: silently ignores offset >= p->tot_len
1427  *
1428  * @param p pbuf to fill
1429  * @param offset offset into p of the byte to write
1430  * @param data byte to write at an offset into p
1431  */
1432 void
1433 pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data)
1434 {
1435   u16_t q_idx;
1436   struct pbuf* q = pbuf_skip(p, offset, &q_idx);
1437
1438   /* write requested data if pbuf is OK */
1439   if ((q != NULL) && (q->len > q_idx)) {
1440     ((u8_t*)q->payload)[q_idx] = data;
1441   }
1442 }
1443
1444 /**
1445  * @ingroup pbuf
1446  * Compare pbuf contents at specified offset with memory s2, both of length n
1447  *
1448  * @param p pbuf to compare
1449  * @param offset offset into p at which to start comparing
1450  * @param s2 buffer to compare
1451  * @param n length of buffer to compare
1452  * @return zero if equal, nonzero otherwise
1453  *         (0xffff if p is too short, diffoffset+1 otherwise)
1454  */
1455 u16_t
1456 pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n)
1457 {
1458   u16_t start = offset;
1459   const struct pbuf* q = p;
1460   u16_t i;
1461  
1462   /* pbuf long enough to perform check? */
1463   if(p->tot_len < (offset + n)) {
1464     return 0xffff;
1465   }
1466  
1467   /* get the correct pbuf from chain. We know it succeeds because of p->tot_len check above. */
1468   while ((q != NULL) && (q->len <= start)) {
1469     start -= q->len;
1470     q = q->next;
1471   }
1472  
1473   /* return requested data if pbuf is OK */
1474   for (i = 0; i < n; i++) {
1475     /* We know pbuf_get_at() succeeds because of p->tot_len check above. */
1476     u8_t a = pbuf_get_at(q, start + i);
1477     u8_t b = ((const u8_t*)s2)[i];
1478     if (a != b) {
1479       return i+1;
1480     }
1481   }
1482   return 0;
1483 }
1484
1485 /**
1486  * @ingroup pbuf
1487  * Find occurrence of mem (with length mem_len) in pbuf p, starting at offset
1488  * start_offset.
1489  *
1490  * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
1491  *        return value 'not found'
1492  * @param mem search for the contents of this buffer
1493  * @param mem_len length of 'mem'
1494  * @param start_offset offset into p at which to start searching
1495  * @return 0xFFFF if substr was not found in p or the index where it was found
1496  */
1497 u16_t
1498 pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
1499 {
1500   u16_t i;
1501   u16_t max = p->tot_len - mem_len;
1502   if (p->tot_len >= mem_len + start_offset) {
1503     for (i = start_offset; i <= max; i++) {
1504       u16_t plus = pbuf_memcmp(p, i, mem, mem_len);
1505       if (plus == 0) {
1506         return i;
1507       }
1508     }
1509   }
1510   return 0xFFFF;
1511 }
1512
1513 /**
1514  * Find occurrence of substr with length substr_len in pbuf p, start at offset
1515  * start_offset
1516  * WARNING: in contrast to strstr(), this one does not stop at the first \0 in
1517  * the pbuf/source string!
1518  *
1519  * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
1520  *        return value 'not found'
1521  * @param substr string to search for in p, maximum length is 0xFFFE
1522  * @return 0xFFFF if substr was not found in p or the index where it was found
1523  */
1524 u16_t
1525 pbuf_strstr(const struct pbuf* p, const char* substr)
1526 {
1527   size_t substr_len;
1528   if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) {
1529     return 0xFFFF;
1530   }
1531   substr_len = strlen(substr);
1532   if (substr_len >= 0xFFFF) {
1533     return 0xFFFF;
1534   }
1535   return pbuf_memfind(p, substr, (u16_t)substr_len, 0);
1536 }
1537
1538 /** Check if the passed pbuf is allocated from the target pool.
1539  * If not, check for availability of pbuf in the target or a larger pool
1540  * that is smaller than the passed pbuf.
1541  * If available, allocate the new pbuf, copy the contents and free the
1542  * passed pbuf. If there is a valid offset passed, make the 'payload'
1543  * pointer offset bytes from start.
1544  *
1545  * @param p pbuf to evaluate
1546  * @param offset number of bytes to offset the payload pointer. If negative,
1547  *               use same offset as in the passed pbuf
1548  * @return the new pbuf if allocated, or passed pbuf otherwise
1549  */
1550 struct pbuf *
1551 pbuf_rightsize(struct pbuf *p, s16_t offset)
1552 {
1553 #if LWIP_PBUF_FROM_CUSTOM_POOLS
1554     struct pbuf* q = NULL;
1555
1556     /* Allow right-sizing only if given pbuf is not chained and
1557      * its reference count is 1*/
1558     if ((p != NULL) && (p->type == PBUF_POOL) &&
1559         (p->len == p->tot_len) && (p->ref == 1)) {
1560         memp_t target_pool;
1561
1562         if (offset < 0) {
1563             offset = ((u8_t*)p->payload - ((u8_t*)p + SIZEOF_STRUCT_PBUF));
1564         }
1565         target_pool = pbuf_get_target_pool(p->len, offset);
1566         /* check if p is drawn from the target pool */
1567         while ((p->pool < target_pool) && (target_pool > PBUF_CUSTOM_POOL_IDX_END)) {
1568             /* check if there is room in the target pool */
1569             if (memp_is_not_empty(target_pool)) {
1570                 q = pbuf_allocate_from_target_pool(&target_pool);
1571                 if (q != NULL) {
1572                     q->type = PBUF_POOL;
1573                     q->next = NULL;
1574                     q->ref = 1;
1575                     q->flags = p->flags;
1576                     /* make the payload pointer point 'offset' bytes into pbuf data memory */
1577                     q->payload = (void *)((u8_t *)q + (SIZEOF_STRUCT_PBUF + offset));
1578                     /* copy payload bytes*/
1579                     MEMCPY((u8_t*)(q->payload), (u8_t*)(p->payload), p->len);
1580                     /* set the len */
1581                     q->len = q->tot_len = p->len;
1582 #if LWIP_PERF
1583                     /* record transfer of pbuf */
1584                     sys_profile_pbuf_transfer(q, p);
1585 #endif
1586                     /* free the passed pbuf */
1587                     pbuf_free(p);
1588                     p = NULL;
1589                     break;
1590                 }
1591             }
1592             target_pool--;
1593         }
1594     }
1595     if (p == NULL)
1596         p = q;
1597 #endif
1598     return p;
1599 }