Back to home page

Quest Cross Reference

 
 

    


Warning, cross-references for /kernel/lwip/core/pbuf.c need to be fixed.

0001 /**
0002  * @file
0003  * Packet buffer management
0004  *
0005  * Packets are built from the pbuf data structure. It supports dynamic
0006  * memory allocation for packet contents or can reference externally
0007  * managed packet contents both in RAM and ROM. Quick allocation for
0008  * incoming packets is provided through pools with fixed sized pbufs.
0009  *
0010  * A packet may span over multiple pbufs, chained as a singly linked
0011  * list. This is called a "pbuf chain".
0012  *
0013  * Multiple packets may be queued, also using this singly linked list.
0014  * This is called a "packet queue".
0015  * 
0016  * So, a packet queue consists of one or more pbuf chains, each of
0017  * which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE
0018  * NOT SUPPORTED!!! Use helper structs to queue multiple packets.
0019  * 
0020  * The differences between a pbuf chain and a packet queue are very
0021  * precise but subtle. 
0022  *
0023  * The last pbuf of a packet has a ->tot_len field that equals the
0024  * ->len field. It can be found by traversing the list. If the last
0025  * pbuf of a packet has a ->next field other than NULL, more packets
0026  * are on the queue.
0027  *
0028  * Therefore, looping through a pbuf of a single packet, has an
0029  * loop end condition (tot_len == p->len), NOT (next == NULL).
0030  */
0031 
0032 /*
0033  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
0034  * All rights reserved.
0035  *
0036  * Redistribution and use in source and binary forms, with or without modification,
0037  * are permitted provided that the following conditions are met:
0038  *
0039  * 1. Redistributions of source code must retain the above copyright notice,
0040  *    this list of conditions and the following disclaimer.
0041  * 2. Redistributions in binary form must reproduce the above copyright notice,
0042  *    this list of conditions and the following disclaimer in the documentation
0043  *    and/or other materials provided with the distribution.
0044  * 3. The name of the author may not be used to endorse or promote products
0045  *    derived from this software without specific prior written permission.
0046  *
0047  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
0048  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
0049  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
0050  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
0051  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
0052  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
0053  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
0054  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
0055  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
0056  * OF SUCH DAMAGE.
0057  *
0058  * This file is part of the lwIP TCP/IP stack.
0059  *
0060  * Author: Adam Dunkels <adam@sics.se>
0061  *
0062  */
0063 
0064 #include "lwip/opt.h"
0065 
0066 #include "lwip/stats.h"
0067 #include "lwip/def.h"
0068 #include "lwip/mem.h"
0069 #include "lwip/memp.h"
0070 #include "lwip/pbuf.h"
0071 #include "lwip/sys.h"
0072 #include "arch/perf.h"
0073 #if TCP_QUEUE_OOSEQ
0074 #include "lwip/tcp.h"
0075 #endif
0076 
0077 #include <string.h>
0078 
0079 #define SIZEOF_STRUCT_PBUF        LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf))
0080 /* Since the pool is created in memp, PBUF_POOL_BUFSIZE will be automatically
0081    aligned there. Therefore, PBUF_POOL_BUFSIZE_ALIGNED can be used here. */
0082 #define PBUF_POOL_BUFSIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
0083 
0084 #if !TCP_QUEUE_OOSEQ || NO_SYS
0085 #define PBUF_POOL_IS_EMPTY()
0086 #else /* !TCP_QUEUE_OOSEQ || NO_SYS */
0087 /** Define this to 0 to prevent freeing ooseq pbufs when the PBUF_POOL is empty */
0088 #ifndef PBUF_POOL_FREE_OOSEQ
0089 #define PBUF_POOL_FREE_OOSEQ 1
0090 #endif /* PBUF_POOL_FREE_OOSEQ */
0091 
0092 #if PBUF_POOL_FREE_OOSEQ
0093 #include "lwip/tcpip.h"
0094 #define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
0095 static u8_t pbuf_free_ooseq_queued;
0096 /**
0097  * Attempt to reclaim some memory from queued out-of-sequence TCP segments
0098  * if we run out of pool pbufs. It's better to give priority to new packets
0099  * if we're running out.
0100  *
0101  * This must be done in the correct thread context therefore this function
0102  * can only be used with NO_SYS=0 and through tcpip_callback.
0103  */
0104 static void
0105 pbuf_free_ooseq(void* arg)
0106 {
0107   struct tcp_pcb* pcb;
0108   SYS_ARCH_DECL_PROTECT(old_level);
0109   LWIP_UNUSED_ARG(arg);
0110 
0111   SYS_ARCH_PROTECT(old_level);
0112   pbuf_free_ooseq_queued = 0;
0113   SYS_ARCH_UNPROTECT(old_level);
0114 
0115   for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
0116     if (NULL != pcb->ooseq) {
0117       /** Free the ooseq pbufs of one PCB only */
0118       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
0119       tcp_segs_free(pcb->ooseq);
0120       pcb->ooseq = NULL;
0121       return;
0122     }
0123   }
0124 }
0125 
0126 /** Queue a call to pbuf_free_ooseq if not already queued. */
0127 static void
0128 pbuf_pool_is_empty(void)
0129 {
0130   u8_t queued;
0131   SYS_ARCH_DECL_PROTECT(old_level);
0132 
0133   SYS_ARCH_PROTECT(old_level);
0134   queued = pbuf_free_ooseq_queued;
0135   pbuf_free_ooseq_queued = 1;
0136   SYS_ARCH_UNPROTECT(old_level);
0137 
0138   if(!queued) {
0139     /* queue a call to pbuf_free_ooseq if not already queued */
0140     if(tcpip_callback_with_block(pbuf_free_ooseq, NULL, 0) != ERR_OK) {
0141       SYS_ARCH_PROTECT(old_level);
0142       pbuf_free_ooseq_queued = 0;
0143       SYS_ARCH_UNPROTECT(old_level);
0144     }
0145   }
0146 }
0147 #endif /* PBUF_POOL_FREE_OOSEQ */
0148 #endif /* !TCP_QUEUE_OOSEQ || NO_SYS */
0149 
0150 /**
0151  * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
0152  *
0153  * The actual memory allocated for the pbuf is determined by the
0154  * layer at which the pbuf is allocated and the requested size
0155  * (from the size parameter).
0156  *
0157  * @param layer flag to define header size
0158  * @param length size of the pbuf's payload
0159  * @param type this parameter decides how and where the pbuf
0160  * should be allocated as follows:
0161  *
0162  * - PBUF_RAM: buffer memory for pbuf is allocated as one large
0163  *             chunk. This includes protocol headers as well.
0164  * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
0165  *             protocol headers. Additional headers must be prepended
0166  *             by allocating another pbuf and chain in to the front of
0167  *             the ROM pbuf. It is assumed that the memory used is really
0168  *             similar to ROM in that it is immutable and will not be
0169  *             changed. Memory which is dynamic should generally not
0170  *             be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
0171  * - PBUF_REF: no buffer memory is allocated for the pbuf, even for
0172  *             protocol headers. It is assumed that the pbuf is only
0173  *             being used in a single thread. If the pbuf gets queued,
0174  *             then pbuf_take should be called to copy the buffer.
0175  * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
0176  *              the pbuf pool that is allocated during pbuf_init().
0177  *
0178  * @return the allocated pbuf. If multiple pbufs where allocated, this
0179  * is the first pbuf of a pbuf chain.
0180  */
0181 struct pbuf *
0182 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
0183 {
0184   struct pbuf *p, *q, *r;
0185   u16_t offset;
0186   s32_t rem_len; /* remaining length */
0187   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
0188 
0189   /* determine header offset */
0190   offset = 0;
0191   switch (layer) {
0192   case PBUF_TRANSPORT:
0193     /* add room for transport (often TCP) layer header */
0194     offset += PBUF_TRANSPORT_HLEN;
0195     /* FALLTHROUGH */
0196   case PBUF_IP:
0197     /* add room for IP layer header */
0198     offset += PBUF_IP_HLEN;
0199     /* FALLTHROUGH */
0200   case PBUF_LINK:
0201     /* add room for link layer header */
0202     offset += PBUF_LINK_HLEN;
0203     break;
0204   case PBUF_RAW:
0205     break;
0206   default:
0207     LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
0208     return NULL;
0209   }
0210 
0211   switch (type) {
0212   case PBUF_POOL:
0213     /* allocate head of pbuf chain into p */
0214     p = memp_malloc(MEMP_PBUF_POOL);
0215     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p));
0216     if (p == NULL) {
0217       PBUF_POOL_IS_EMPTY();
0218       return NULL;
0219     }
0220     p->type = type;
0221     p->next = NULL;
0222 
0223     /* make the payload pointer point 'offset' bytes into pbuf data memory */
0224     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
0225     LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
0226             ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
0227     /* the total length of the pbuf chain is the requested size */
0228     p->tot_len = length;
0229     /* set the length of the first pbuf in the chain */
0230     p->len = LWIP_MIN(length, PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset));
0231     LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
0232                 ((u8_t*)p->payload + p->len <=
0233                  (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
0234     LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
0235       (PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
0236     /* set reference count (needed here in case we fail) */
0237     p->ref = 1;
0238 
0239     /* now allocate the tail of the pbuf chain */
0240 
0241     /* remember first pbuf for linkage in next iteration */
0242     r = p;
0243     /* remaining length to be allocated */
0244     rem_len = length - p->len;
0245     /* any remaining pbufs to be allocated? */
0246     while (rem_len > 0) {
0247       q = memp_malloc(MEMP_PBUF_POOL);
0248       if (q == NULL) {
0249         PBUF_POOL_IS_EMPTY();
0250         /* free chain so far allocated */
0251         pbuf_free(p);
0252         /* bail out unsuccesfully */
0253         return NULL;
0254       }
0255       q->type = type;
0256       q->flags = 0;
0257       q->next = NULL;
0258       /* make previous pbuf point to this pbuf */
0259       r->next = q;
0260       /* set total length of this pbuf and next in chain */
0261       LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
0262       q->tot_len = (u16_t)rem_len;
0263       /* this pbuf length is pool size, unless smaller sized tail */
0264       q->len = LWIP_MIN((u16_t)rem_len, PBUF_POOL_BUFSIZE_ALIGNED);
0265       q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
0266       LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
0267               ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
0268       LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
0269                   ((u8_t*)p->payload + p->len <=
0270                    (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
0271       q->ref = 1;
0272       /* calculate remaining length to be allocated */
0273       rem_len -= q->len;
0274       /* remember this pbuf for linkage in next iteration */
0275       r = q;
0276     }
0277     /* end of chain */
0278     /*r->next = NULL;*/
0279 
0280     break;
0281   case PBUF_RAM:
0282     /* If pbuf is to be allocated in RAM, allocate memory for it. */
0283     p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
0284     if (p == NULL) {
0285       return NULL;
0286     }
0287     /* Set up internal structure of the pbuf. */
0288     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
0289     p->len = p->tot_len = length;
0290     p->next = NULL;
0291     p->type = type;
0292 
0293     LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
0294            ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
0295     break;
0296   /* pbuf references existing (non-volatile static constant) ROM payload? */
0297   case PBUF_ROM:
0298   /* pbuf references existing (externally allocated) RAM payload? */
0299   case PBUF_REF:
0300     /* only allocate memory for the pbuf structure */
0301     p = memp_malloc(MEMP_PBUF);
0302     if (p == NULL) {
0303       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
0304                   ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
0305                   (type == PBUF_ROM) ? "ROM" : "REF"));
0306       return NULL;
0307     }
0308     /* caller must set this field properly, afterwards */
0309     p->payload = NULL;
0310     p->len = p->tot_len = length;
0311     p->next = NULL;
0312     p->type = type;
0313     break;
0314   default:
0315     LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
0316     return NULL;
0317   }
0318   /* set reference count */
0319   p->ref = 1;
0320   /* set flags */
0321   p->flags = 0;
0322   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
0323   return p;
0324 }
0325 
0326 
0327 /**
0328  * Shrink a pbuf chain to a desired length.
0329  *
0330  * @param p pbuf to shrink.
0331  * @param new_len desired new length of pbuf chain
0332  *
0333  * Depending on the desired length, the first few pbufs in a chain might
0334  * be skipped and left unchanged. The new last pbuf in the chain will be
0335  * resized, and any remaining pbufs will be freed.
0336  *
0337  * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
0338  * @note May not be called on a packet queue.
0339  *
0340  * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
0341  */
0342 void
0343 pbuf_realloc(struct pbuf *p, u16_t new_len)
0344 {
0345   struct pbuf *q;
0346   u16_t rem_len; /* remaining length */
0347   s32_t grow;
0348 
0349   LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
0350   LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
0351               p->type == PBUF_ROM ||
0352               p->type == PBUF_RAM ||
0353               p->type == PBUF_REF);
0354 
0355   /* desired length larger than current length? */
0356   if (new_len >= p->tot_len) {
0357     /* enlarging not yet supported */
0358     return;
0359   }
0360 
0361   /* the pbuf chain grows by (new_len - p->tot_len) bytes
0362    * (which may be negative in case of shrinking) */
0363   grow = new_len - p->tot_len;
0364 
0365   /* first, step over any pbufs that should remain in the chain */
0366   rem_len = new_len;
0367   q = p;
0368   /* should this pbuf be kept? */
0369   while (rem_len > q->len) {
0370     /* decrease remaining length by pbuf length */
0371     rem_len -= q->len;
0372     /* decrease total length indicator */
0373     LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
0374     q->tot_len += (u16_t)grow;
0375     /* proceed to next pbuf in chain */
0376     q = q->next;
0377     LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
0378   }
0379   /* we have now reached the new last pbuf (in q) */
0380   /* rem_len == desired length for pbuf q */
0381 
0382   /* shrink allocated memory for PBUF_RAM */
0383   /* (other types merely adjust their length fields */
0384   if ((q->type == PBUF_RAM) && (rem_len != q->len)) {
0385     /* reallocate and adjust the length of the pbuf that will be split */
0386     q = mem_realloc(q, (u8_t *)q->payload - (u8_t *)q + rem_len);
0387     LWIP_ASSERT("mem_realloc give q == NULL", q != NULL);
0388   }
0389   /* adjust length fields for new last pbuf */
0390   q->len = rem_len;
0391   q->tot_len = q->len;
0392 
0393   /* any remaining pbufs in chain? */
0394   if (q->next != NULL) {
0395     /* free remaining pbufs in chain */
0396     pbuf_free(q->next);
0397   }
0398   /* q is last packet in chain */
0399   q->next = NULL;
0400 
0401 }
0402 
0403 /**
0404  * Adjusts the payload pointer to hide or reveal headers in the payload.
0405  *
0406  * Adjusts the ->payload pointer so that space for a header
0407  * (dis)appears in the pbuf payload.
0408  *
0409  * The ->payload, ->tot_len and ->len fields are adjusted.
0410  *
0411  * @param p pbuf to change the header size.
0412  * @param header_size_increment Number of bytes to increment header size which
0413  * increases the size of the pbuf. New space is on the front.
0414  * (Using a negative value decreases the header size.)
0415  * If hdr_size_inc is 0, this function does nothing and returns succesful.
0416  *
0417  * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
0418  * the call will fail. A check is made that the increase in header size does
0419  * not move the payload pointer in front of the start of the buffer.
0420  * @return non-zero on failure, zero on success.
0421  *
0422  */
0423 u8_t
0424 pbuf_header(struct pbuf *p, s16_t header_size_increment)
0425 {
0426   u16_t type;
0427   void *payload;
0428   u16_t increment_magnitude;
0429 
0430   LWIP_ASSERT("p != NULL", p != NULL);
0431   if ((header_size_increment == 0) || (p == NULL))
0432     return 0;
0433  
0434   if (header_size_increment < 0){
0435     increment_magnitude = -header_size_increment;
0436     /* Check that we aren't going to move off the end of the pbuf */
0437     LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
0438   } else {
0439     increment_magnitude = header_size_increment;
0440 #if 0
0441     /* Can't assert these as some callers speculatively call
0442          pbuf_header() to see if it's OK.  Will return 1 below instead. */
0443     /* Check that we've got the correct type of pbuf to work with */
0444     LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL", 
0445                 p->type == PBUF_RAM || p->type == PBUF_POOL);
0446     /* Check that we aren't going to move off the beginning of the pbuf */
0447     LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
0448                 (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
0449 #endif
0450   }
0451 
0452   type = p->type;
0453   /* remember current payload pointer */
0454   payload = p->payload;
0455 
0456   /* pbuf types containing payloads? */
0457   if (type == PBUF_RAM || type == PBUF_POOL) {
0458     /* set new payload pointer */
0459     p->payload = (u8_t *)p->payload - header_size_increment;
0460     /* boundary check fails? */
0461     if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
0462       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
0463         ("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
0464         (void *)p->payload, (void *)(p + 1)));
0465       /* restore old payload pointer */
0466       p->payload = payload;
0467       /* bail out unsuccesfully */
0468       return 1;
0469     }
0470   /* pbuf types refering to external payloads? */
0471   } else if (type == PBUF_REF || type == PBUF_ROM) {
0472     /* hide a header in the payload? */
0473     if ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
0474       /* increase payload pointer */
0475       p->payload = (u8_t *)p->payload - header_size_increment;
0476     } else {
0477       /* cannot expand payload to front (yet!)
0478        * bail out unsuccesfully */
0479       return 1;
0480     }
0481   }
0482   else {
0483     /* Unknown type */
0484     LWIP_ASSERT("bad pbuf type", 0);
0485     return 1;
0486   }
0487   /* modify pbuf length fields */
0488   p->len += header_size_increment;
0489   p->tot_len += header_size_increment;
0490 
0491   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
0492     (void *)payload, (void *)p->payload, header_size_increment));
0493 
0494   return 0;
0495 }
0496 
0497 /**
0498  * Dereference a pbuf chain or queue and deallocate any no-longer-used
0499  * pbufs at the head of this chain or queue.
0500  *
0501  * Decrements the pbuf reference count. If it reaches zero, the pbuf is
0502  * deallocated.
0503  *
0504  * For a pbuf chain, this is repeated for each pbuf in the chain,
0505  * up to the first pbuf which has a non-zero reference count after
0506  * decrementing. So, when all reference counts are one, the whole
0507  * chain is free'd.
0508  *
0509  * @param p The pbuf (chain) to be dereferenced.
0510  *
0511  * @return the number of pbufs that were de-allocated
0512  * from the head of the chain.
0513  *
0514  * @note MUST NOT be called on a packet queue (Not verified to work yet).
0515  * @note the reference counter of a pbuf equals the number of pointers
0516  * that refer to the pbuf (or into the pbuf).
0517  *
0518  * @internal examples:
0519  *
0520  * Assuming existing chains a->b->c with the following reference
0521  * counts, calling pbuf_free(a) results in:
0522  * 
0523  * 1->2->3 becomes ...1->3
0524  * 3->3->3 becomes 2->3->3
0525  * 1->1->2 becomes ......1
0526  * 2->1->1 becomes 1->1->1
0527  * 1->1->1 becomes .......
0528  *
0529  */
0530 u8_t
0531 pbuf_free(struct pbuf *p)
0532 {
0533   u16_t type;
0534   struct pbuf *q;
0535   u8_t count;
0536 
0537   if (p == NULL) {
0538     LWIP_ASSERT("p != NULL", p != NULL);
0539     /* if assertions are disabled, proceed with debug output */
0540     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
0541       ("pbuf_free(p == NULL) was called.\n"));
0542     return 0;
0543   }
0544   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
0545 
0546   PERF_START;
0547 
0548   LWIP_ASSERT("pbuf_free: sane type",
0549     p->type == PBUF_RAM || p->type == PBUF_ROM ||
0550     p->type == PBUF_REF || p->type == PBUF_POOL);
0551 
0552   count = 0;
0553   /* de-allocate all consecutive pbufs from the head of the chain that
0554    * obtain a zero reference count after decrementing*/
0555   while (p != NULL) {
0556     u16_t ref;
0557     SYS_ARCH_DECL_PROTECT(old_level);
0558     /* Since decrementing ref cannot be guaranteed to be a single machine operation
0559      * we must protect it. We put the new ref into a local variable to prevent
0560      * further protection. */
0561     SYS_ARCH_PROTECT(old_level);
0562     /* all pbufs in a chain are referenced at least once */
0563     LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
0564     /* decrease reference count (number of pointers to pbuf) */
0565     ref = --(p->ref);
0566     SYS_ARCH_UNPROTECT(old_level);
0567     /* this pbuf is no longer referenced to? */
0568     if (ref == 0) {
0569       /* remember next pbuf in chain for next iteration */
0570       q = p->next;
0571       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
0572       type = p->type;
0573       /* is this a pbuf from the pool? */
0574       if (type == PBUF_POOL) {
0575         memp_free(MEMP_PBUF_POOL, p);
0576       /* is this a ROM or RAM referencing pbuf? */
0577       } else if (type == PBUF_ROM || type == PBUF_REF) {
0578         memp_free(MEMP_PBUF, p);
0579       /* type == PBUF_RAM */
0580       } else {
0581         mem_free(p);
0582       }
0583       count++;
0584       /* proceed to next pbuf */
0585       p = q;
0586     /* p->ref > 0, this pbuf is still referenced to */
0587     /* (and so the remaining pbufs in chain as well) */
0588     } else {
0589       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
0590       /* stop walking through the chain */
0591       p = NULL;
0592     }
0593   }
0594   PERF_STOP("pbuf_free");
0595   /* return number of de-allocated pbufs */
0596   return count;
0597 }
0598 
0599 /**
0600  * Count number of pbufs in a chain
0601  *
0602  * @param p first pbuf of chain
0603  * @return the number of pbufs in a chain
0604  */
0605 
0606 u8_t
0607 pbuf_clen(struct pbuf *p)
0608 {
0609   u8_t len;
0610 
0611   len = 0;
0612   while (p != NULL) {
0613     ++len;
0614     p = p->next;
0615   }
0616   return len;
0617 }
0618 
0619 /**
0620  * Increment the reference count of the pbuf.
0621  *
0622  * @param p pbuf to increase reference counter of
0623  *
0624  */
0625 void
0626 pbuf_ref(struct pbuf *p)
0627 {
0628   SYS_ARCH_DECL_PROTECT(old_level);
0629   /* pbuf given? */
0630   if (p != NULL) {
0631     SYS_ARCH_PROTECT(old_level);
0632     ++(p->ref);
0633     SYS_ARCH_UNPROTECT(old_level);
0634   }
0635 }
0636 
0637 /**
0638  * Concatenate two pbufs (each may be a pbuf chain) and take over
0639  * the caller's reference of the tail pbuf.
0640  * 
0641  * @note The caller MAY NOT reference the tail pbuf afterwards.
0642  * Use pbuf_chain() for that purpose.
0643  * 
0644  * @see pbuf_chain()
0645  */
0646 
0647 void
0648 pbuf_cat(struct pbuf *h, struct pbuf *t)
0649 {
0650   struct pbuf *p;
0651 
0652   LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
0653              ((h != NULL) && (t != NULL)), return;);
0654 
0655   /* proceed to last pbuf of chain */
0656   for (p = h; p->next != NULL; p = p->next) {
0657     /* add total length of second chain to all totals of first chain */
0658     p->tot_len += t->tot_len;
0659   }
0660   /* { p is last pbuf of first h chain, p->next == NULL } */
0661   LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
0662   LWIP_ASSERT("p->next == NULL", p->next == NULL);
0663   /* add total length of second chain to last pbuf total of first chain */
0664   p->tot_len += t->tot_len;
0665   /* chain last pbuf of head (p) with first of tail (t) */
0666   p->next = t;
0667   /* p->next now references t, but the caller will drop its reference to t,
0668    * so netto there is no change to the reference count of t.
0669    */
0670 }
0671 
0672 /**
0673  * Chain two pbufs (or pbuf chains) together.
0674  * 
0675  * The caller MUST call pbuf_free(t) once it has stopped
0676  * using it. Use pbuf_cat() instead if you no longer use t.
0677  * 
0678  * @param h head pbuf (chain)
0679  * @param t tail pbuf (chain)
0680  * @note The pbufs MUST belong to the same packet.
0681  * @note MAY NOT be called on a packet queue.
0682  *
0683  * The ->tot_len fields of all pbufs of the head chain are adjusted.
0684  * The ->next field of the last pbuf of the head chain is adjusted.
0685  * The ->ref field of the first pbuf of the tail chain is adjusted.
0686  *
0687  */
0688 void
0689 pbuf_chain(struct pbuf *h, struct pbuf *t)
0690 {
0691   pbuf_cat(h, t);
0692   /* t is now referenced by h */
0693   pbuf_ref(t);
0694   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
0695 }
0696 
0697 /**
0698  * Dechains the first pbuf from its succeeding pbufs in the chain.
0699  *
0700  * Makes p->tot_len field equal to p->len.
0701  * @param p pbuf to dechain
0702  * @return remainder of the pbuf chain, or NULL if it was de-allocated.
0703  * @note May not be called on a packet queue.
0704  */
0705 struct pbuf *
0706 pbuf_dechain(struct pbuf *p)
0707 {
0708   struct pbuf *q;
0709   u8_t tail_gone = 1;
0710   /* tail */
0711   q = p->next;
0712   /* pbuf has successor in chain? */
0713   if (q != NULL) {
0714     /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
0715     LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
0716     /* enforce invariant if assertion is disabled */
0717     q->tot_len = p->tot_len - p->len;
0718     /* decouple pbuf from remainder */
0719     p->next = NULL;
0720     /* total length of pbuf p is its own length only */
0721     p->tot_len = p->len;
0722     /* q is no longer referenced by p, free it */
0723     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
0724     tail_gone = pbuf_free(q);
0725     if (tail_gone > 0) {
0726       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
0727                   ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
0728     }
0729     /* return remaining tail or NULL if deallocated */
0730   }
0731   /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
0732   LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
0733   return ((tail_gone > 0) ? NULL : q);
0734 }
0735 
0736 /**
0737  *
0738  * Create PBUF_RAM copies of pbufs.
0739  *
0740  * Used to queue packets on behalf of the lwIP stack, such as
0741  * ARP based queueing.
0742  *
0743  * @note You MUST explicitly use p = pbuf_take(p);
0744  *
0745  * @note Only one packet is copied, no packet queue!
0746  *
0747  * @param p_to pbuf destination of the copy
0748  * @param p_from pbuf source of the copy
0749  *
0750  * @return ERR_OK if pbuf was copied
0751  *         ERR_ARG if one of the pbufs is NULL or p_to is not big
0752  *                 enough to hold p_from
0753  */
0754 err_t
0755 pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
0756 {
0757   u16_t offset_to=0, offset_from=0, len;
0758 
0759   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
0760     (void*)p_to, (void*)p_from));
0761 
0762   /* is the target big enough to hold the source? */
0763   LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
0764              (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
0765 
0766   /* iterate through pbuf chain */
0767   do
0768   {
0769     LWIP_ASSERT("p_to != NULL", p_to != NULL);
0770     /* copy one part of the original chain */
0771     if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
0772       /* complete current p_from fits into current p_to */
0773       len = p_from->len - offset_from;
0774     } else {
0775       /* current p_from does not fit into current p_to */
0776       len = p_to->len - offset_to;
0777     }
0778     MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
0779     offset_to += len;
0780     offset_from += len;
0781     LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
0782     if (offset_to == p_to->len) {
0783       /* on to next p_to (if any) */
0784       offset_to = 0;
0785       p_to = p_to->next;
0786     }
0787     LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
0788     if (offset_from >= p_from->len) {
0789       /* on to next p_from (if any) */
0790       offset_from = 0;
0791       p_from = p_from->next;
0792     }
0793 
0794     if((p_from != NULL) && (p_from->len == p_from->tot_len)) {
0795       /* don't copy more than one packet! */
0796       LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
0797                  (p_from->next == NULL), return ERR_VAL;);
0798     }
0799     if((p_to != NULL) && (p_to->len == p_to->tot_len)) {
0800       /* don't copy more than one packet! */
0801       LWIP_ERROR("pbuf_copy() does not allow packet queues!\n",
0802                   (p_to->next == NULL), return ERR_VAL;);
0803     }
0804   } while (p_from);
0805   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
0806   return ERR_OK;
0807 }
0808 
0809 /**
0810  * Copy (part of) the contents of a packet buffer
0811  * to an application supplied buffer.
0812  *
0813  * @param buf the pbuf from which to copy data
0814  * @param dataptr the application supplied buffer
0815  * @param len length of data to copy (dataptr must be big enough). No more 
0816  * than buf->tot_len will be copied, irrespective of len
0817  * @param offset offset into the packet buffer from where to begin copying len bytes
0818  * @return the number of bytes copied, or 0 on failure
0819  */
0820 u16_t
0821 pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
0822 {
0823   struct pbuf *p;
0824   u16_t left;
0825   u16_t buf_copy_len;
0826   u16_t copied_total = 0;
0827 
0828   LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
0829   LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
0830 
0831   left = 0;
0832 
0833   if((buf == NULL) || (dataptr == NULL)) {
0834     return 0;
0835   }
0836 
0837   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
0838   for(p = buf; len != 0 && p != NULL; p = p->next) {
0839     if ((offset != 0) && (offset >= p->len)) {
0840       /* don't copy from this buffer -> on to the next */
0841       offset -= p->len;
0842     } else {
0843       /* copy from this buffer. maybe only partially. */
0844       buf_copy_len = p->len - offset;
0845       if (buf_copy_len > len)
0846           buf_copy_len = len;
0847       /* copy the necessary parts of the buffer */
0848       MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
0849       copied_total += buf_copy_len;
0850       left += buf_copy_len;
0851       len -= buf_copy_len;
0852       offset = 0;
0853     }
0854   }
0855   return copied_total;
0856 }
0857 
0858 /**
0859  * Copy application supplied data into a pbuf.
0860  * This function can only be used to copy the equivalent of buf->tot_len data.
0861  *
0862  * @param buf pbuf to fill with data
0863  * @param dataptr application supplied data buffer
0864  * @param len length of the application supplied data buffer
0865  *
0866  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
0867  */
0868 err_t
0869 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
0870 {
0871   struct pbuf *p;
0872   u16_t buf_copy_len;
0873   u16_t total_copy_len = len;
0874   u16_t copied_total = 0;
0875 
0876   LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;);
0877   LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;);
0878 
0879   if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
0880     return ERR_ARG;
0881   }
0882 
0883   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
0884   for(p = buf; total_copy_len != 0; p = p->next) {
0885     LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
0886     buf_copy_len = total_copy_len;
0887     if (buf_copy_len > p->len) {
0888       /* this pbuf cannot hold all remaining data */
0889       buf_copy_len = p->len;
0890     }
0891     /* copy the necessary parts of the buffer */
0892     MEMCPY(p->payload, &((char*)dataptr)[copied_total], buf_copy_len);
0893     total_copy_len -= buf_copy_len;
0894     copied_total += buf_copy_len;
0895   }
0896   LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
0897   return ERR_OK;
0898 }
0899 
0900 /**
0901  * Creates a single pbuf out of a queue of pbufs.
0902  *
0903  * @remark: The source pbuf 'p' is not freed by this function because that can
0904  *          be illegal in some places!
0905  *
0906  * @param p the source pbuf
0907  * @param layer pbuf_layer of the new pbuf
0908  *
0909  * @return a new, single pbuf (p->next is NULL)
0910  *         or the old pbuf if allocation fails
0911  */
0912 struct pbuf*
0913 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
0914 {
0915   struct pbuf *q;
0916   err_t err;
0917   if (p->next == NULL) {
0918     return p;
0919   }
0920   q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
0921   if (q == NULL) {
0922     /* @todo: what do we do now? */
0923     return p;
0924   }
0925   err = pbuf_copy(q, p);
0926   LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
0927   pbuf_free(p);
0928   return q;
0929 }