3 * Packet buffer management
5 * Packets are built from the pbuf data structure. It supports dynamic
6 * memory allocation for packet contents or can reference externally
7 * managed packet contents both in RAM and ROM. Quick allocation for
8 * incoming packets is provided through pools with fixed sized pbufs.
10 * A packet may span over multiple pbufs, chained as a singly linked
11 * list. This is called a "pbuf chain".
13 * Multiple packets may be queued, also using this singly linked list.
14 * This is called a "packet queue".
16 * So, a packet queue consists of one or more pbuf chains, each of
17 * which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE
18 * NOT SUPPORTED!!! Use helper structs to queue multiple packets.
20 * The differences between a pbuf chain and a packet queue are very
23 * The last pbuf of a packet has a ->tot_len field that equals the
24 * ->len field. It can be found by traversing the list. If the last
25 * pbuf of a packet has a ->next field other than NULL, more packets
28 * Therefore, looping through a pbuf of a single packet, has an
29 * loop end condition (tot_len == p->len), NOT (next == NULL).
33 * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
34 * All rights reserved.
36 * Redistribution and use in source and binary forms, with or without modification,
37 * are permitted provided that the following conditions are met:
39 * 1. Redistributions of source code must retain the above copyright notice,
40 * this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright notice,
42 * this list of conditions and the following disclaimer in the documentation
43 * and/or other materials provided with the distribution.
44 * 3. The name of the author may not be used to endorse or promote products
45 * derived from this software without specific prior written permission.
47 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
48 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
49 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
50 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
51 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
52 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
53 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
54 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
55 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
58 * This file is part of the lwIP TCP/IP stack.
60 * Author: Adam Dunkels <adam@sics.se>
66 #include "lwip/stats.h"
69 #include "lwip/memp.h"
70 #include "lwip/pbuf.h"
72 #include "arch/perf.h"
74 #include "lwip/tcp_impl.h"
76 #if LWIP_CHECKSUM_ON_COPY
77 #include "lwip/inet_chksum.h"
82 #define SIZEOF_STRUCT_PBUF LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf))
83 /* Since the pool is created in memp, PBUF_POOL_BUFSIZE will be automatically
84 aligned there. Therefore, PBUF_POOL_BUFSIZE_ALIGNED can be used here. */
85 #define PBUF_POOL_BUFSIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
87 #if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ
88 #define PBUF_POOL_IS_EMPTY()
89 #else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
92 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
93 #include "lwip/tcpip.h"
94 #define PBUF_POOL_FREE_OOSEQ_QUEUE_CALL() do { \
95 if(tcpip_callback_with_block(pbuf_free_ooseq_callback, NULL, 0) != ERR_OK) { \
96 SYS_ARCH_PROTECT(old_level); \
97 pbuf_free_ooseq_pending = 0; \
98 SYS_ARCH_UNPROTECT(old_level); \
100 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
103 volatile u8_t pbuf_free_ooseq_pending;
104 #define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
107 * Attempt to reclaim some memory from queued out-of-sequence TCP segments
108 * if we run out of pool pbufs. It's better to give priority to new packets
109 * if we're running out.
111 * This must be done in the correct thread context therefore this function
112 * can only be used with NO_SYS=0 and through tcpip_callback.
118 pbuf_free_ooseq(void)
121 SYS_ARCH_DECL_PROTECT(old_level);
123 SYS_ARCH_PROTECT(old_level);
124 pbuf_free_ooseq_pending = 0;
125 SYS_ARCH_UNPROTECT(old_level);
127 for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
128 if (NULL != pcb->ooseq) {
129 /** Free the ooseq pbufs of one PCB only */
130 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
131 tcp_segs_free(pcb->ooseq);
140 * Just a callback function for tcpip_timeout() that calls pbuf_free_ooseq().
143 pbuf_free_ooseq_callback(void *arg)
145 LWIP_UNUSED_ARG(arg);
150 /** Queue a call to pbuf_free_ooseq if not already queued. */
152 pbuf_pool_is_empty(void)
154 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
155 SYS_ARCH_DECL_PROTECT(old_level);
156 SYS_ARCH_PROTECT(old_level);
157 pbuf_free_ooseq_pending = 1;
158 SYS_ARCH_UNPROTECT(old_level);
159 #else /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
161 SYS_ARCH_DECL_PROTECT(old_level);
162 SYS_ARCH_PROTECT(old_level);
163 queued = pbuf_free_ooseq_pending;
164 pbuf_free_ooseq_pending = 1;
165 SYS_ARCH_UNPROTECT(old_level);
168 /* queue a call to pbuf_free_ooseq if not already queued */
169 PBUF_POOL_FREE_OOSEQ_QUEUE_CALL();
171 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
173 #endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
176 * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
178 * The actual memory allocated for the pbuf is determined by the
179 * layer at which the pbuf is allocated and the requested size
180 * (from the size parameter).
182 * @param layer flag to define header size
183 * @param length size of the pbuf's payload
184 * @param type this parameter decides how and where the pbuf
185 * should be allocated as follows:
187 * - PBUF_RAM: buffer memory for pbuf is allocated as one large
188 * chunk. This includes protocol headers as well.
189 * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
190 * protocol headers. Additional headers must be prepended
191 * by allocating another pbuf and chain in to the front of
192 * the ROM pbuf. It is assumed that the memory used is really
193 * similar to ROM in that it is immutable and will not be
194 * changed. Memory which is dynamic should generally not
195 * be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
196 * - PBUF_REF: no buffer memory is allocated for the pbuf, even for
197 * protocol headers. It is assumed that the pbuf is only
198 * being used in a single thread. If the pbuf gets queued,
199 * then pbuf_take should be called to copy the buffer.
200 * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
201 * the pbuf pool that is allocated during pbuf_init().
203 * @return the allocated pbuf. If multiple pbufs where allocated, this
204 * is the first pbuf of a pbuf chain.
207 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
209 struct pbuf *p, *q, *r;
211 s32_t rem_len; /* remaining length */
212 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
214 /* determine header offset */
217 /* add room for transport (often TCP) layer header */
218 offset = PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
221 /* add room for IP layer header */
222 offset = PBUF_LINK_HLEN + PBUF_IP_HLEN;
225 /* add room for link layer header */
226 offset = PBUF_LINK_HLEN;
232 LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
238 /* allocate head of pbuf chain into p */
239 p = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
240 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p));
242 PBUF_POOL_IS_EMPTY();
248 /* make the payload pointer point 'offset' bytes into pbuf data memory */
249 p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
250 LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
251 ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
252 /* the total length of the pbuf chain is the requested size */
254 /* set the length of the first pbuf in the chain */
255 p->len = LWIP_MIN(length, PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset));
256 LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
257 ((u8_t*)p->payload + p->len <=
258 (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
259 LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
260 (PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
261 /* set reference count (needed here in case we fail) */
264 /* now allocate the tail of the pbuf chain */
266 /* remember first pbuf for linkage in next iteration */
268 /* remaining length to be allocated */
269 rem_len = length - p->len;
270 /* any remaining pbufs to be allocated? */
271 while (rem_len > 0) {
272 q = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
274 PBUF_POOL_IS_EMPTY();
275 /* free chain so far allocated */
277 /* bail out unsuccesfully */
283 /* make previous pbuf point to this pbuf */
285 /* set total length of this pbuf and next in chain */
286 LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
287 q->tot_len = (u16_t)rem_len;
288 /* this pbuf length is pool size, unless smaller sized tail */
289 q->len = LWIP_MIN((u16_t)rem_len, PBUF_POOL_BUFSIZE_ALIGNED);
290 q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
291 LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
292 ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
293 LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
294 ((u8_t*)p->payload + p->len <=
295 (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
297 /* calculate remaining length to be allocated */
299 /* remember this pbuf for linkage in next iteration */
307 /* If pbuf is to be allocated in RAM, allocate memory for it. */
308 p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
312 /* Set up internal structure of the pbuf. */
313 p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
314 p->len = p->tot_len = length;
318 LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
319 ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
321 /* pbuf references existing (non-volatile static constant) ROM payload? */
323 /* pbuf references existing (externally allocated) RAM payload? */
325 /* only allocate memory for the pbuf structure */
326 p = (struct pbuf *)memp_malloc(MEMP_PBUF);
328 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
329 ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
330 (type == PBUF_ROM) ? "ROM" : "REF"));
333 /* caller must set this field properly, afterwards */
335 p->len = p->tot_len = length;
340 LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
343 /* set reference count */
347 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
351 #if LWIP_SUPPORT_CUSTOM_PBUF
352 /** Initialize a custom pbuf (already allocated).
354 * @param layer flag to define header size
355 * @param length size of the pbuf's payload
356 * @param type type of the pbuf (only used to treat the pbuf accordingly, as
357 * this function allocates no memory)
358 * @param p pointer to the custom pbuf to initialize (already allocated)
359 * @param payload_mem pointer to the buffer that is used for payload and headers,
360 * must be at least big enough to hold 'length' plus the header size,
361 * may be NULL if set later
362 * @param payload_mem_len the size of the 'payload_mem' buffer, must be at least
363 * big enough to hold 'length' plus the header size
366 pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p,
367 void *payload_mem, u16_t payload_mem_len)
370 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloced_custom(length=%"U16_F")\n", length));
372 /* determine header offset */
375 /* add room for transport (often TCP) layer header */
376 offset = PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
379 /* add room for IP layer header */
380 offset = PBUF_LINK_HLEN + PBUF_IP_HLEN;
383 /* add room for link layer header */
384 offset = PBUF_LINK_HLEN;
390 LWIP_ASSERT("pbuf_alloced_custom: bad pbuf layer", 0);
394 if (LWIP_MEM_ALIGN_SIZE(offset) + length < payload_mem_len) {
395 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_WARNING, ("pbuf_alloced_custom(length=%"U16_F") buffer too short\n", length));
400 if (payload_mem != NULL) {
401 p->pbuf.payload = LWIP_MEM_ALIGN((void *)((u8_t *)payload_mem + offset));
403 p->pbuf.payload = NULL;
405 p->pbuf.flags = PBUF_FLAG_IS_CUSTOM;
406 p->pbuf.len = p->pbuf.tot_len = length;
411 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
414 * Shrink a pbuf chain to a desired length.
416 * @param p pbuf to shrink.
417 * @param new_len desired new length of pbuf chain
419 * Depending on the desired length, the first few pbufs in a chain might
420 * be skipped and left unchanged. The new last pbuf in the chain will be
421 * resized, and any remaining pbufs will be freed.
423 * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
424 * @note May not be called on a packet queue.
426 * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
429 pbuf_realloc(struct pbuf *p, u16_t new_len)
432 u16_t rem_len; /* remaining length */
435 LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
436 LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
437 p->type == PBUF_ROM ||
438 p->type == PBUF_RAM ||
439 p->type == PBUF_REF);
441 /* desired length larger than current length? */
442 if (new_len >= p->tot_len) {
443 /* enlarging not yet supported */
447 /* the pbuf chain grows by (new_len - p->tot_len) bytes
448 * (which may be negative in case of shrinking) */
449 grow = new_len - p->tot_len;
451 /* first, step over any pbufs that should remain in the chain */
454 /* should this pbuf be kept? */
455 while (rem_len > q->len) {
456 /* decrease remaining length by pbuf length */
458 /* decrease total length indicator */
459 LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
460 q->tot_len += (u16_t)grow;
461 /* proceed to next pbuf in chain */
463 LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
465 /* we have now reached the new last pbuf (in q) */
466 /* rem_len == desired length for pbuf q */
468 /* shrink allocated memory for PBUF_RAM */
469 /* (other types merely adjust their length fields */
470 if ((q->type == PBUF_RAM) && (rem_len != q->len)) {
471 /* reallocate and adjust the length of the pbuf that will be split */
472 q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len);
473 LWIP_ASSERT("mem_trim returned q == NULL", q != NULL);
475 /* adjust length fields for new last pbuf */
479 /* any remaining pbufs in chain? */
480 if (q->next != NULL) {
481 /* free remaining pbufs in chain */
484 /* q is last packet in chain */
490 * Adjusts the payload pointer to hide or reveal headers in the payload.
492 * Adjusts the ->payload pointer so that space for a header
493 * (dis)appears in the pbuf payload.
495 * The ->payload, ->tot_len and ->len fields are adjusted.
497 * @param p pbuf to change the header size.
498 * @param header_size_increment Number of bytes to increment header size which
499 * increases the size of the pbuf. New space is on the front.
500 * (Using a negative value decreases the header size.)
501 * If hdr_size_inc is 0, this function does nothing and returns succesful.
503 * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
504 * the call will fail. A check is made that the increase in header size does
505 * not move the payload pointer in front of the start of the buffer.
506 * @return non-zero on failure, zero on success.
510 pbuf_header(struct pbuf *p, s16_t header_size_increment)
514 u16_t increment_magnitude;
516 LWIP_ASSERT("p != NULL", p != NULL);
517 if ((header_size_increment == 0) || (p == NULL)) {
521 if (header_size_increment < 0){
522 increment_magnitude = -header_size_increment;
523 /* Check that we aren't going to move off the end of the pbuf */
524 LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
526 increment_magnitude = header_size_increment;
528 /* Can't assert these as some callers speculatively call
529 pbuf_header() to see if it's OK. Will return 1 below instead. */
530 /* Check that we've got the correct type of pbuf to work with */
531 LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL",
532 p->type == PBUF_RAM || p->type == PBUF_POOL);
533 /* Check that we aren't going to move off the beginning of the pbuf */
534 LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
535 (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
540 /* remember current payload pointer */
541 payload = p->payload;
543 /* pbuf types containing payloads? */
544 if (type == PBUF_RAM || type == PBUF_POOL) {
545 /* set new payload pointer */
546 p->payload = (u8_t *)p->payload - header_size_increment;
547 /* boundary check fails? */
548 if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
549 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
550 ("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
551 (void *)p->payload, (void *)(p + 1)));
552 /* restore old payload pointer */
553 p->payload = payload;
554 /* bail out unsuccesfully */
557 /* pbuf types refering to external payloads? */
558 } else if (type == PBUF_REF || type == PBUF_ROM) {
559 /* hide a header in the payload? */
560 if ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
561 /* increase payload pointer */
562 p->payload = (u8_t *)p->payload - header_size_increment;
564 /* cannot expand payload to front (yet!)
565 * bail out unsuccesfully */
570 LWIP_ASSERT("bad pbuf type", 0);
573 /* modify pbuf length fields */
574 p->len += header_size_increment;
575 p->tot_len += header_size_increment;
577 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
578 (void *)payload, (void *)p->payload, header_size_increment));
584 * Dereference a pbuf chain or queue and deallocate any no-longer-used
585 * pbufs at the head of this chain or queue.
587 * Decrements the pbuf reference count. If it reaches zero, the pbuf is
590 * For a pbuf chain, this is repeated for each pbuf in the chain,
591 * up to the first pbuf which has a non-zero reference count after
592 * decrementing. So, when all reference counts are one, the whole
595 * @param p The pbuf (chain) to be dereferenced.
597 * @return the number of pbufs that were de-allocated
598 * from the head of the chain.
600 * @note MUST NOT be called on a packet queue (Not verified to work yet).
601 * @note the reference counter of a pbuf equals the number of pointers
602 * that refer to the pbuf (or into the pbuf).
604 * @internal examples:
606 * Assuming existing chains a->b->c with the following reference
607 * counts, calling pbuf_free(a) results in:
609 * 1->2->3 becomes ...1->3
610 * 3->3->3 becomes 2->3->3
611 * 1->1->2 becomes ......1
612 * 2->1->1 becomes 1->1->1
613 * 1->1->1 becomes .......
617 pbuf_free(struct pbuf *p)
624 LWIP_ASSERT("p != NULL", p != NULL);
625 /* if assertions are disabled, proceed with debug output */
626 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
627 ("pbuf_free(p == NULL) was called.\n"));
630 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
634 LWIP_ASSERT("pbuf_free: sane type",
635 p->type == PBUF_RAM || p->type == PBUF_ROM ||
636 p->type == PBUF_REF || p->type == PBUF_POOL);
639 /* de-allocate all consecutive pbufs from the head of the chain that
640 * obtain a zero reference count after decrementing*/
643 SYS_ARCH_DECL_PROTECT(old_level);
644 /* Since decrementing ref cannot be guaranteed to be a single machine operation
645 * we must protect it. We put the new ref into a local variable to prevent
646 * further protection. */
647 SYS_ARCH_PROTECT(old_level);
648 /* all pbufs in a chain are referenced at least once */
649 LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
650 /* decrease reference count (number of pointers to pbuf) */
652 SYS_ARCH_UNPROTECT(old_level);
653 /* this pbuf is no longer referenced to? */
655 /* remember next pbuf in chain for next iteration */
657 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
659 #if LWIP_SUPPORT_CUSTOM_PBUF
660 /* is this a custom pbuf? */
661 if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) {
662 struct pbuf_custom *pc = (struct pbuf_custom*)p;
663 LWIP_ASSERT("pc->custom_free_function != NULL", pc->custom_free_function != NULL);
664 pc->custom_free_function(p);
666 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
668 /* is this a pbuf from the pool? */
669 if (type == PBUF_POOL) {
670 memp_free(MEMP_PBUF_POOL, p);
671 /* is this a ROM or RAM referencing pbuf? */
672 } else if (type == PBUF_ROM || type == PBUF_REF) {
673 memp_free(MEMP_PBUF, p);
674 /* type == PBUF_RAM */
680 /* proceed to next pbuf */
682 /* p->ref > 0, this pbuf is still referenced to */
683 /* (and so the remaining pbufs in chain as well) */
685 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
686 /* stop walking through the chain */
690 PERF_STOP("pbuf_free");
691 /* return number of de-allocated pbufs */
696 * Count number of pbufs in a chain
698 * @param p first pbuf of chain
699 * @return the number of pbufs in a chain
703 pbuf_clen(struct pbuf *p)
716 * Increment the reference count of the pbuf.
718 * @param p pbuf to increase reference counter of
722 pbuf_ref(struct pbuf *p)
724 SYS_ARCH_DECL_PROTECT(old_level);
727 SYS_ARCH_PROTECT(old_level);
729 SYS_ARCH_UNPROTECT(old_level);
734 * Concatenate two pbufs (each may be a pbuf chain) and take over
735 * the caller's reference of the tail pbuf.
737 * @note The caller MAY NOT reference the tail pbuf afterwards.
738 * Use pbuf_chain() for that purpose.
744 pbuf_cat(struct pbuf *h, struct pbuf *t)
748 LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
749 ((h != NULL) && (t != NULL)), return;);
751 /* proceed to last pbuf of chain */
752 for (p = h; p->next != NULL; p = p->next) {
753 /* add total length of second chain to all totals of first chain */
754 p->tot_len += t->tot_len;
756 /* { p is last pbuf of first h chain, p->next == NULL } */
757 LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
758 LWIP_ASSERT("p->next == NULL", p->next == NULL);
759 /* add total length of second chain to last pbuf total of first chain */
760 p->tot_len += t->tot_len;
761 /* chain last pbuf of head (p) with first of tail (t) */
763 /* p->next now references t, but the caller will drop its reference to t,
764 * so netto there is no change to the reference count of t.
769 * Chain two pbufs (or pbuf chains) together.
771 * The caller MUST call pbuf_free(t) once it has stopped
772 * using it. Use pbuf_cat() instead if you no longer use t.
774 * @param h head pbuf (chain)
775 * @param t tail pbuf (chain)
776 * @note The pbufs MUST belong to the same packet.
777 * @note MAY NOT be called on a packet queue.
779 * The ->tot_len fields of all pbufs of the head chain are adjusted.
780 * The ->next field of the last pbuf of the head chain is adjusted.
781 * The ->ref field of the first pbuf of the tail chain is adjusted.
785 pbuf_chain(struct pbuf *h, struct pbuf *t)
788 /* t is now referenced by h */
790 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
794 * Dechains the first pbuf from its succeeding pbufs in the chain.
796 * Makes p->tot_len field equal to p->len.
797 * @param p pbuf to dechain
798 * @return remainder of the pbuf chain, or NULL if it was de-allocated.
799 * @note May not be called on a packet queue.
802 pbuf_dechain(struct pbuf *p)
808 /* pbuf has successor in chain? */
810 /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
811 LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
812 /* enforce invariant if assertion is disabled */
813 q->tot_len = p->tot_len - p->len;
814 /* decouple pbuf from remainder */
816 /* total length of pbuf p is its own length only */
818 /* q is no longer referenced by p, free it */
819 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
820 tail_gone = pbuf_free(q);
822 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
823 ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
825 /* return remaining tail or NULL if deallocated */
827 /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
828 LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
829 return ((tail_gone > 0) ? NULL : q);
834 * Create PBUF_RAM copies of pbufs.
836 * Used to queue packets on behalf of the lwIP stack, such as
837 * ARP based queueing.
839 * @note You MUST explicitly use p = pbuf_take(p);
841 * @note Only one packet is copied, no packet queue!
843 * @param p_to pbuf destination of the copy
844 * @param p_from pbuf source of the copy
846 * @return ERR_OK if pbuf was copied
847 * ERR_ARG if one of the pbufs is NULL or p_to is not big
848 * enough to hold p_from
851 pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
853 u16_t offset_to=0, offset_from=0, len;
855 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
856 (void*)p_to, (void*)p_from));
858 /* is the target big enough to hold the source? */
859 LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
860 (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
862 /* iterate through pbuf chain */
865 LWIP_ASSERT("p_to != NULL", p_to != NULL);
866 /* copy one part of the original chain */
867 if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
868 /* complete current p_from fits into current p_to */
869 len = p_from->len - offset_from;
871 /* current p_from does not fit into current p_to */
872 len = p_to->len - offset_to;
874 MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
877 LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
878 if (offset_to == p_to->len) {
879 /* on to next p_to (if any) */
883 LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
884 if (offset_from >= p_from->len) {
885 /* on to next p_from (if any) */
887 p_from = p_from->next;
890 if((p_from != NULL) && (p_from->len == p_from->tot_len)) {
891 /* don't copy more than one packet! */
892 LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
893 (p_from->next == NULL), return ERR_VAL;);
895 if((p_to != NULL) && (p_to->len == p_to->tot_len)) {
896 /* don't copy more than one packet! */
897 LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
898 (p_to->next == NULL), return ERR_VAL;);
901 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
906 * Copy (part of) the contents of a packet buffer
907 * to an application supplied buffer.
909 * @param buf the pbuf from which to copy data
910 * @param dataptr the application supplied buffer
911 * @param len length of data to copy (dataptr must be big enough). No more
912 * than buf->tot_len will be copied, irrespective of len
913 * @param offset offset into the packet buffer from where to begin copying len bytes
914 * @return the number of bytes copied, or 0 on failure
917 pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
922 u16_t copied_total = 0;
924 LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
925 LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
929 if((buf == NULL) || (dataptr == NULL)) {
933 /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
934 for(p = buf; len != 0 && p != NULL; p = p->next) {
935 if ((offset != 0) && (offset >= p->len)) {
936 /* don't copy from this buffer -> on to the next */
939 /* copy from this buffer. maybe only partially. */
940 buf_copy_len = p->len - offset;
941 if (buf_copy_len > len)
943 /* copy the necessary parts of the buffer */
944 MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
945 copied_total += buf_copy_len;
946 left += buf_copy_len;
955 * Copy application supplied data into a pbuf.
956 * This function can only be used to copy the equivalent of buf->tot_len data.
958 * @param buf pbuf to fill with data
959 * @param dataptr application supplied data buffer
960 * @param len length of the application supplied data buffer
962 * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
965 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
969 u16_t total_copy_len = len;
970 u16_t copied_total = 0;
972 LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;);
973 LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;);
975 if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
979 /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
980 for(p = buf; total_copy_len != 0; p = p->next) {
981 LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
982 buf_copy_len = total_copy_len;
983 if (buf_copy_len > p->len) {
984 /* this pbuf cannot hold all remaining data */
985 buf_copy_len = p->len;
987 /* copy the necessary parts of the buffer */
988 MEMCPY(p->payload, &((char*)dataptr)[copied_total], buf_copy_len);
989 total_copy_len -= buf_copy_len;
990 copied_total += buf_copy_len;
992 LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
997 * Creates a single pbuf out of a queue of pbufs.
999 * @remark: Either the source pbuf 'p' is freed by this function or the original
1000 * pbuf 'p' is returned, therefore the caller has to check the result!
1002 * @param p the source pbuf
1003 * @param layer pbuf_layer of the new pbuf
1005 * @return a new, single pbuf (p->next is NULL)
1006 * or the old pbuf if allocation fails
1009 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
1013 if (p->next == NULL) {
1016 q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
1018 /* @todo: what do we do now? */
1021 err = pbuf_copy(q, p);
1022 LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
1027 #if LWIP_CHECKSUM_ON_COPY
1029 * Copies data into a single pbuf (*not* into a pbuf queue!) and updates
1030 * the checksum while copying
1032 * @param p the pbuf to copy data into
1033 * @param start_offset offset of p->payload where to copy the data to
1034 * @param dataptr data to copy into the pbuf
1035 * @param len length of data to copy into the pbuf
1036 * @param chksum pointer to the checksum which is updated
1037 * @return ERR_OK if successful, another error if the data does not fit
1038 * within the (first) pbuf (no pbuf queues!)
1041 pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
1042 u16_t len, u16_t *chksum)
1047 LWIP_ASSERT("p != NULL", p != NULL);
1048 LWIP_ASSERT("dataptr != NULL", dataptr != NULL);
1049 LWIP_ASSERT("chksum != NULL", chksum != NULL);
1050 LWIP_ASSERT("len != 0", len != 0);
1052 if ((start_offset >= p->len) || (start_offset + len > p->len)) {
1056 dst_ptr = ((char*)p->payload) + start_offset;
1057 copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len);
1058 if ((start_offset & 1) != 0) {
1059 copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum);
1063 *chksum = FOLD_U32T(acc);
1066 #endif /* LWIP_CHECKSUM_ON_COPY */
1068 /** Get one byte from the specified position in a pbuf
1069 * WARNING: returns zero for offset >= p->tot_len
1071 * @param p pbuf to parse
1072 * @param offset offset into p of the byte to return
1073 * @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len
1076 pbuf_get_at(struct pbuf* p, u16_t offset)
1078 u16_t copy_from = offset;
1081 /* get the correct pbuf */
1082 while ((q != NULL) && (q->len <= copy_from)) {
1083 copy_from -= q->len;
1086 /* return requested data if pbuf is OK */
1087 if ((q != NULL) && (q->len > copy_from)) {
1088 return ((u8_t*)q->payload)[copy_from];
1093 /** Compare pbuf contents at specified offset with memory s2, both of length n
1095 * @param p pbuf to compare
1096 * @param offset offset into p at wich to start comparing
1097 * @param s2 buffer to compare
1098 * @param n length of buffer to compare
1099 * @return zero if equal, nonzero otherwise
1100 * (0xffff if p is too short, diffoffset+1 otherwise)
1103 pbuf_memcmp(struct pbuf* p, u16_t offset, const void* s2, u16_t n)
1105 u16_t start = offset;
1108 /* get the correct pbuf */
1109 while ((q != NULL) && (q->len <= start)) {
1113 /* return requested data if pbuf is OK */
1114 if ((q != NULL) && (q->len > start)) {
1116 for(i = 0; i < n; i++) {
1117 u8_t a = pbuf_get_at(q, start + i);
1118 u8_t b = ((u8_t*)s2)[i];
1128 /** Find occurrence of mem (with length mem_len) in pbuf p, starting at offset
1131 * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
1132 * return value 'not found'
1133 * @param mem search for the contents of this buffer
1134 * @param mem_len length of 'mem'
1135 * @param start_offset offset into p at which to start searching
1136 * @return 0xFFFF if substr was not found in p or the index where it was found
1139 pbuf_memfind(struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
1142 u16_t max = p->tot_len - mem_len;
1143 if (p->tot_len >= mem_len + start_offset) {
1144 for(i = start_offset; i <= max; ) {
1145 u16_t plus = pbuf_memcmp(p, i, mem, mem_len);
1156 /** Find occurrence of substr with length substr_len in pbuf p, start at offset
1158 * WARNING: in contrast to strstr(), this one does not stop at the first \0 in
1159 * the pbuf/source string!
1161 * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
1162 * return value 'not found'
1163 * @param substr string to search for in p, maximum length is 0xFFFE
1164 * @return 0xFFFF if substr was not found in p or the index where it was found
1167 pbuf_strstr(struct pbuf* p, const char* substr)
1170 if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) {
1173 substr_len = strlen(substr);
1174 if (substr_len >= 0xFFFF) {
1177 return pbuf_memfind(p, substr, (u16_t)substr_len, 0);