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 || NO_SYS
88 #define PBUF_POOL_IS_EMPTY()
89 #else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS */
90 /** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */
91 #ifndef PBUF_POOL_FREE_OOSEQ
92 #define PBUF_POOL_FREE_OOSEQ 1
93 #endif /* PBUF_POOL_FREE_OOSEQ */
95 #if PBUF_POOL_FREE_OOSEQ
96 #include "lwip/tcpip.h"
97 #define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
98 static u8_t pbuf_free_ooseq_queued;
100 * Attempt to reclaim some memory from queued out-of-sequence TCP segments
101 * if we run out of pool pbufs. It's better to give priority to new packets
102 * if we're running out.
104 * This must be done in the correct thread context therefore this function
105 * can only be used with NO_SYS=0 and through tcpip_callback.
108 pbuf_free_ooseq(void* arg)
111 SYS_ARCH_DECL_PROTECT(old_level);
112 LWIP_UNUSED_ARG(arg);
114 SYS_ARCH_PROTECT(old_level);
115 pbuf_free_ooseq_queued = 0;
116 SYS_ARCH_UNPROTECT(old_level);
118 for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
119 if (NULL != pcb->ooseq) {
120 /** Free the ooseq pbufs of one PCB only */
121 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
122 tcp_segs_free(pcb->ooseq);
129 /** Queue a call to pbuf_free_ooseq if not already queued. */
131 pbuf_pool_is_empty(void)
134 SYS_ARCH_DECL_PROTECT(old_level);
136 SYS_ARCH_PROTECT(old_level);
137 queued = pbuf_free_ooseq_queued;
138 pbuf_free_ooseq_queued = 1;
139 SYS_ARCH_UNPROTECT(old_level);
142 /* queue a call to pbuf_free_ooseq if not already queued */
143 if(tcpip_callback_with_block(pbuf_free_ooseq, NULL, 0) != ERR_OK) {
144 SYS_ARCH_PROTECT(old_level);
145 pbuf_free_ooseq_queued = 0;
146 SYS_ARCH_UNPROTECT(old_level);
150 #endif /* PBUF_POOL_FREE_OOSEQ */
151 #endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS */
154 * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
156 * The actual memory allocated for the pbuf is determined by the
157 * layer at which the pbuf is allocated and the requested size
158 * (from the size parameter).
160 * @param layer flag to define header size
161 * @param length size of the pbuf's payload
162 * @param type this parameter decides how and where the pbuf
163 * should be allocated as follows:
165 * - PBUF_RAM: buffer memory for pbuf is allocated as one large
166 * chunk. This includes protocol headers as well.
167 * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
168 * protocol headers. Additional headers must be prepended
169 * by allocating another pbuf and chain in to the front of
170 * the ROM pbuf. It is assumed that the memory used is really
171 * similar to ROM in that it is immutable and will not be
172 * changed. Memory which is dynamic should generally not
173 * be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
174 * - PBUF_REF: no buffer memory is allocated for the pbuf, even for
175 * protocol headers. It is assumed that the pbuf is only
176 * being used in a single thread. If the pbuf gets queued,
177 * then pbuf_take should be called to copy the buffer.
178 * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
179 * the pbuf pool that is allocated during pbuf_init().
181 * @return the allocated pbuf. If multiple pbufs where allocated, this
182 * is the first pbuf of a pbuf chain.
185 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
187 struct pbuf *p, *q, *r;
189 s32_t rem_len; /* remaining length */
190 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
192 /* determine header offset */
196 /* add room for transport (often TCP) layer header */
197 offset += PBUF_TRANSPORT_HLEN;
200 /* add room for IP layer header */
201 offset += PBUF_IP_HLEN;
204 /* add room for link layer header */
205 offset += PBUF_LINK_HLEN;
210 LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
216 /* allocate head of pbuf chain into p */
217 p = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
218 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p));
220 PBUF_POOL_IS_EMPTY();
226 /* make the payload pointer point 'offset' bytes into pbuf data memory */
227 p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
228 LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
229 ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
230 /* the total length of the pbuf chain is the requested size */
232 /* set the length of the first pbuf in the chain */
233 p->len = LWIP_MIN(length, PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset));
234 LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
235 ((u8_t*)p->payload + p->len <=
236 (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
237 LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
238 (PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
239 /* set reference count (needed here in case we fail) */
242 /* now allocate the tail of the pbuf chain */
244 /* remember first pbuf for linkage in next iteration */
246 /* remaining length to be allocated */
247 rem_len = length - p->len;
248 /* any remaining pbufs to be allocated? */
249 while (rem_len > 0) {
250 q = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
252 PBUF_POOL_IS_EMPTY();
253 /* free chain so far allocated */
255 /* bail out unsuccesfully */
261 /* make previous pbuf point to this pbuf */
263 /* set total length of this pbuf and next in chain */
264 LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
265 q->tot_len = (u16_t)rem_len;
266 /* this pbuf length is pool size, unless smaller sized tail */
267 q->len = LWIP_MIN((u16_t)rem_len, PBUF_POOL_BUFSIZE_ALIGNED);
268 q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
269 LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
270 ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
271 LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
272 ((u8_t*)p->payload + p->len <=
273 (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
275 /* calculate remaining length to be allocated */
277 /* remember this pbuf for linkage in next iteration */
285 /* If pbuf is to be allocated in RAM, allocate memory for it. */
286 p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
290 /* Set up internal structure of the pbuf. */
291 p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
292 p->len = p->tot_len = length;
296 LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
297 ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
299 /* pbuf references existing (non-volatile static constant) ROM payload? */
301 /* pbuf references existing (externally allocated) RAM payload? */
303 /* only allocate memory for the pbuf structure */
304 p = (struct pbuf *)memp_malloc(MEMP_PBUF);
306 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
307 ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
308 (type == PBUF_ROM) ? "ROM" : "REF"));
311 /* caller must set this field properly, afterwards */
313 p->len = p->tot_len = length;
318 LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
321 /* set reference count */
325 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
331 * Shrink a pbuf chain to a desired length.
333 * @param p pbuf to shrink.
334 * @param new_len desired new length of pbuf chain
336 * Depending on the desired length, the first few pbufs in a chain might
337 * be skipped and left unchanged. The new last pbuf in the chain will be
338 * resized, and any remaining pbufs will be freed.
340 * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
341 * @note May not be called on a packet queue.
343 * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
346 pbuf_realloc(struct pbuf *p, u16_t new_len)
349 u16_t rem_len; /* remaining length */
352 LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
353 LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
354 p->type == PBUF_ROM ||
355 p->type == PBUF_RAM ||
356 p->type == PBUF_REF);
358 /* desired length larger than current length? */
359 if (new_len >= p->tot_len) {
360 /* enlarging not yet supported */
364 /* the pbuf chain grows by (new_len - p->tot_len) bytes
365 * (which may be negative in case of shrinking) */
366 grow = new_len - p->tot_len;
368 /* first, step over any pbufs that should remain in the chain */
371 /* should this pbuf be kept? */
372 while (rem_len > q->len) {
373 /* decrease remaining length by pbuf length */
375 /* decrease total length indicator */
376 LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
377 q->tot_len += (u16_t)grow;
378 /* proceed to next pbuf in chain */
380 LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
382 /* we have now reached the new last pbuf (in q) */
383 /* rem_len == desired length for pbuf q */
385 /* shrink allocated memory for PBUF_RAM */
386 /* (other types merely adjust their length fields */
387 if ((q->type == PBUF_RAM) && (rem_len != q->len)) {
388 /* reallocate and adjust the length of the pbuf that will be split */
389 q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len);
390 LWIP_ASSERT("mem_trim returned q == NULL", q != NULL);
392 /* adjust length fields for new last pbuf */
396 /* any remaining pbufs in chain? */
397 if (q->next != NULL) {
398 /* free remaining pbufs in chain */
401 /* q is last packet in chain */
407 * Adjusts the payload pointer to hide or reveal headers in the payload.
409 * Adjusts the ->payload pointer so that space for a header
410 * (dis)appears in the pbuf payload.
412 * The ->payload, ->tot_len and ->len fields are adjusted.
414 * @param p pbuf to change the header size.
415 * @param header_size_increment Number of bytes to increment header size which
416 * increases the size of the pbuf. New space is on the front.
417 * (Using a negative value decreases the header size.)
418 * If hdr_size_inc is 0, this function does nothing and returns succesful.
420 * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
421 * the call will fail. A check is made that the increase in header size does
422 * not move the payload pointer in front of the start of the buffer.
423 * @return non-zero on failure, zero on success.
427 pbuf_header(struct pbuf *p, s16_t header_size_increment)
431 u16_t increment_magnitude;
433 LWIP_ASSERT("p != NULL", p != NULL);
434 if ((header_size_increment == 0) || (p == NULL)) {
438 if (header_size_increment < 0){
439 increment_magnitude = -header_size_increment;
440 /* Check that we aren't going to move off the end of the pbuf */
441 LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
443 increment_magnitude = header_size_increment;
445 /* Can't assert these as some callers speculatively call
446 pbuf_header() to see if it's OK. Will return 1 below instead. */
447 /* Check that we've got the correct type of pbuf to work with */
448 LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL",
449 p->type == PBUF_RAM || p->type == PBUF_POOL);
450 /* Check that we aren't going to move off the beginning of the pbuf */
451 LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
452 (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
457 /* remember current payload pointer */
458 payload = p->payload;
460 /* pbuf types containing payloads? */
461 if (type == PBUF_RAM || type == PBUF_POOL) {
462 /* set new payload pointer */
463 p->payload = (u8_t *)p->payload - header_size_increment;
464 /* boundary check fails? */
465 if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
466 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
467 ("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
468 (void *)p->payload, (void *)(p + 1)));
469 /* restore old payload pointer */
470 p->payload = payload;
471 /* bail out unsuccesfully */
474 /* pbuf types refering to external payloads? */
475 } else if (type == PBUF_REF || type == PBUF_ROM) {
476 /* hide a header in the payload? */
477 if ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
478 /* increase payload pointer */
479 p->payload = (u8_t *)p->payload - header_size_increment;
481 /* cannot expand payload to front (yet!)
482 * bail out unsuccesfully */
487 LWIP_ASSERT("bad pbuf type", 0);
490 /* modify pbuf length fields */
491 p->len += header_size_increment;
492 p->tot_len += header_size_increment;
494 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
495 (void *)payload, (void *)p->payload, header_size_increment));
501 * Dereference a pbuf chain or queue and deallocate any no-longer-used
502 * pbufs at the head of this chain or queue.
504 * Decrements the pbuf reference count. If it reaches zero, the pbuf is
507 * For a pbuf chain, this is repeated for each pbuf in the chain,
508 * up to the first pbuf which has a non-zero reference count after
509 * decrementing. So, when all reference counts are one, the whole
512 * @param p The pbuf (chain) to be dereferenced.
514 * @return the number of pbufs that were de-allocated
515 * from the head of the chain.
517 * @note MUST NOT be called on a packet queue (Not verified to work yet).
518 * @note the reference counter of a pbuf equals the number of pointers
519 * that refer to the pbuf (or into the pbuf).
521 * @internal examples:
523 * Assuming existing chains a->b->c with the following reference
524 * counts, calling pbuf_free(a) results in:
526 * 1->2->3 becomes ...1->3
527 * 3->3->3 becomes 2->3->3
528 * 1->1->2 becomes ......1
529 * 2->1->1 becomes 1->1->1
530 * 1->1->1 becomes .......
534 pbuf_free(struct pbuf *p)
541 LWIP_ASSERT("p != NULL", p != NULL);
542 /* if assertions are disabled, proceed with debug output */
543 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
544 ("pbuf_free(p == NULL) was called.\n"));
547 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
551 LWIP_ASSERT("pbuf_free: sane type",
552 p->type == PBUF_RAM || p->type == PBUF_ROM ||
553 p->type == PBUF_REF || p->type == PBUF_POOL);
556 /* de-allocate all consecutive pbufs from the head of the chain that
557 * obtain a zero reference count after decrementing*/
560 SYS_ARCH_DECL_PROTECT(old_level);
561 /* Since decrementing ref cannot be guaranteed to be a single machine operation
562 * we must protect it. We put the new ref into a local variable to prevent
563 * further protection. */
564 SYS_ARCH_PROTECT(old_level);
565 /* all pbufs in a chain are referenced at least once */
566 LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
567 /* decrease reference count (number of pointers to pbuf) */
569 SYS_ARCH_UNPROTECT(old_level);
570 /* this pbuf is no longer referenced to? */
572 /* remember next pbuf in chain for next iteration */
574 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
576 /* is this a pbuf from the pool? */
577 if (type == PBUF_POOL) {
578 memp_free(MEMP_PBUF_POOL, p);
579 /* is this a ROM or RAM referencing pbuf? */
580 } else if (type == PBUF_ROM || type == PBUF_REF) {
581 memp_free(MEMP_PBUF, p);
582 /* type == PBUF_RAM */
587 /* proceed to next pbuf */
589 /* p->ref > 0, this pbuf is still referenced to */
590 /* (and so the remaining pbufs in chain as well) */
592 LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
593 /* stop walking through the chain */
597 PERF_STOP("pbuf_free");
598 /* return number of de-allocated pbufs */
603 * Count number of pbufs in a chain
605 * @param p first pbuf of chain
606 * @return the number of pbufs in a chain
610 pbuf_clen(struct pbuf *p)
623 * Increment the reference count of the pbuf.
625 * @param p pbuf to increase reference counter of
629 pbuf_ref(struct pbuf *p)
631 SYS_ARCH_DECL_PROTECT(old_level);
634 SYS_ARCH_PROTECT(old_level);
636 SYS_ARCH_UNPROTECT(old_level);
641 * Concatenate two pbufs (each may be a pbuf chain) and take over
642 * the caller's reference of the tail pbuf.
644 * @note The caller MAY NOT reference the tail pbuf afterwards.
645 * Use pbuf_chain() for that purpose.
651 pbuf_cat(struct pbuf *h, struct pbuf *t)
655 LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
656 ((h != NULL) && (t != NULL)), return;);
658 /* proceed to last pbuf of chain */
659 for (p = h; p->next != NULL; p = p->next) {
660 /* add total length of second chain to all totals of first chain */
661 p->tot_len += t->tot_len;
663 /* { p is last pbuf of first h chain, p->next == NULL } */
664 LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
665 LWIP_ASSERT("p->next == NULL", p->next == NULL);
666 /* add total length of second chain to last pbuf total of first chain */
667 p->tot_len += t->tot_len;
668 /* chain last pbuf of head (p) with first of tail (t) */
670 /* p->next now references t, but the caller will drop its reference to t,
671 * so netto there is no change to the reference count of t.
676 * Chain two pbufs (or pbuf chains) together.
678 * The caller MUST call pbuf_free(t) once it has stopped
679 * using it. Use pbuf_cat() instead if you no longer use t.
681 * @param h head pbuf (chain)
682 * @param t tail pbuf (chain)
683 * @note The pbufs MUST belong to the same packet.
684 * @note MAY NOT be called on a packet queue.
686 * The ->tot_len fields of all pbufs of the head chain are adjusted.
687 * The ->next field of the last pbuf of the head chain is adjusted.
688 * The ->ref field of the first pbuf of the tail chain is adjusted.
692 pbuf_chain(struct pbuf *h, struct pbuf *t)
695 /* t is now referenced by h */
697 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
701 * Dechains the first pbuf from its succeeding pbufs in the chain.
703 * Makes p->tot_len field equal to p->len.
704 * @param p pbuf to dechain
705 * @return remainder of the pbuf chain, or NULL if it was de-allocated.
706 * @note May not be called on a packet queue.
709 pbuf_dechain(struct pbuf *p)
715 /* pbuf has successor in chain? */
717 /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
718 LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
719 /* enforce invariant if assertion is disabled */
720 q->tot_len = p->tot_len - p->len;
721 /* decouple pbuf from remainder */
723 /* total length of pbuf p is its own length only */
725 /* q is no longer referenced by p, free it */
726 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
727 tail_gone = pbuf_free(q);
729 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
730 ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
732 /* return remaining tail or NULL if deallocated */
734 /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
735 LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
736 return ((tail_gone > 0) ? NULL : q);
741 * Create PBUF_RAM copies of pbufs.
743 * Used to queue packets on behalf of the lwIP stack, such as
744 * ARP based queueing.
746 * @note You MUST explicitly use p = pbuf_take(p);
748 * @note Only one packet is copied, no packet queue!
750 * @param p_to pbuf destination of the copy
751 * @param p_from pbuf source of the copy
753 * @return ERR_OK if pbuf was copied
754 * ERR_ARG if one of the pbufs is NULL or p_to is not big
755 * enough to hold p_from
758 pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
760 u16_t offset_to=0, offset_from=0, len;
762 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
763 (void*)p_to, (void*)p_from));
765 /* is the target big enough to hold the source? */
766 LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
767 (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
769 /* iterate through pbuf chain */
772 LWIP_ASSERT("p_to != NULL", p_to != NULL);
773 /* copy one part of the original chain */
774 if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
775 /* complete current p_from fits into current p_to */
776 len = p_from->len - offset_from;
778 /* current p_from does not fit into current p_to */
779 len = p_to->len - offset_to;
781 MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
784 LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
785 if (offset_to == p_to->len) {
786 /* on to next p_to (if any) */
790 LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
791 if (offset_from >= p_from->len) {
792 /* on to next p_from (if any) */
794 p_from = p_from->next;
797 if((p_from != NULL) && (p_from->len == p_from->tot_len)) {
798 /* don't copy more than one packet! */
799 LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
800 (p_from->next == NULL), return ERR_VAL;);
802 if((p_to != NULL) && (p_to->len == p_to->tot_len)) {
803 /* don't copy more than one packet! */
804 LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
805 (p_to->next == NULL), return ERR_VAL;);
808 LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
813 * Copy (part of) the contents of a packet buffer
814 * to an application supplied buffer.
816 * @param buf the pbuf from which to copy data
817 * @param dataptr the application supplied buffer
818 * @param len length of data to copy (dataptr must be big enough). No more
819 * than buf->tot_len will be copied, irrespective of len
820 * @param offset offset into the packet buffer from where to begin copying len bytes
821 * @return the number of bytes copied, or 0 on failure
824 pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
829 u16_t copied_total = 0;
831 LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
832 LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
836 if((buf == NULL) || (dataptr == NULL)) {
840 /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
841 for(p = buf; len != 0 && p != NULL; p = p->next) {
842 if ((offset != 0) && (offset >= p->len)) {
843 /* don't copy from this buffer -> on to the next */
846 /* copy from this buffer. maybe only partially. */
847 buf_copy_len = p->len - offset;
848 if (buf_copy_len > len)
850 /* copy the necessary parts of the buffer */
851 MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
852 copied_total += buf_copy_len;
853 left += buf_copy_len;
862 * Copy application supplied data into a pbuf.
863 * This function can only be used to copy the equivalent of buf->tot_len data.
865 * @param buf pbuf to fill with data
866 * @param dataptr application supplied data buffer
867 * @param len length of the application supplied data buffer
869 * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
872 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
876 u16_t total_copy_len = len;
877 u16_t copied_total = 0;
879 LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;);
880 LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;);
882 if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
886 /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
887 for(p = buf; total_copy_len != 0; p = p->next) {
888 LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
889 buf_copy_len = total_copy_len;
890 if (buf_copy_len > p->len) {
891 /* this pbuf cannot hold all remaining data */
892 buf_copy_len = p->len;
894 /* copy the necessary parts of the buffer */
895 MEMCPY(p->payload, &((char*)dataptr)[copied_total], buf_copy_len);
896 total_copy_len -= buf_copy_len;
897 copied_total += buf_copy_len;
899 LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
904 * Creates a single pbuf out of a queue of pbufs.
906 * @remark: The source pbuf 'p' is not freed by this function because that can
907 * be illegal in some places!
909 * @param p the source pbuf
910 * @param layer pbuf_layer of the new pbuf
912 * @return a new, single pbuf (p->next is NULL)
913 * or the old pbuf if allocation fails
916 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
920 if (p->next == NULL) {
923 q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
925 /* @todo: what do we do now? */
928 err = pbuf_copy(q, p);
929 LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
934 #if LWIP_CHECKSUM_ON_COPY
936 * Copies data into a single pbuf (*not* into a pbuf queue!) and updates
937 * the checksum while copying
939 * @param p the pbuf to copy data into
940 * @param start_offset offset of p->payload where to copy the data to
941 * @param dataptr data to copy into the pbuf
942 * @param len length of data to copy into the pbuf
943 * @param chksum pointer to the checksum which is updated
944 * @return ERR_OK if successful, another error if the data does not fit
945 * within the (first) pbuf (no pbuf queues!)
948 pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
949 u16_t len, u16_t *chksum)
954 LWIP_ASSERT("p != NULL", p != NULL);
955 LWIP_ASSERT("dataptr != NULL", dataptr != NULL);
956 LWIP_ASSERT("chksum != NULL", chksum != NULL);
957 LWIP_ASSERT("len != 0", len != 0);
959 if ((start_offset >= p->len) || (start_offset + len > p->len)) {
963 dst_ptr = ((char*)p->payload) + start_offset;
964 copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len);
965 if ((start_offset & 1) != 0) {
966 copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum);
970 *chksum = FOLD_U32T(acc);
973 #endif /* LWIP_CHECKSUM_ON_COPY */