Daiki Kato / mbed-os-lychee

Dependents:   mbed-os-example-blinky-gr-lychee GR-Boads_Camera_sample GR-Boards_Audio_Recoder GR-Boads_Camera_DisplayApp ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers lwip_pbuf.c Source File

lwip_pbuf.c

Go to the documentation of this file.
00001 /**
00002  * @file
00003  * Packet buffer management
00004  */
00005 
00006 /**
00007  * @defgroup pbuf Packet buffers (PBUF)
00008  * @ingroup infrastructure
00009  *
00010  * Packets are built from the pbuf data structure. It supports dynamic
00011  * memory allocation for packet contents or can reference externally
00012  * managed packet contents both in RAM and ROM. Quick allocation for
00013  * incoming packets is provided through pools with fixed sized pbufs.
00014  *
00015  * A packet may span over multiple pbufs, chained as a singly linked
00016  * list. This is called a "pbuf chain".
00017  *
00018  * Multiple packets may be queued, also using this singly linked list.
00019  * This is called a "packet queue".
00020  *
00021  * So, a packet queue consists of one or more pbuf chains, each of
00022  * which consist of one or more pbufs. CURRENTLY, PACKET QUEUES ARE
00023  * NOT SUPPORTED!!! Use helper structs to queue multiple packets.
00024  *
00025  * The differences between a pbuf chain and a packet queue are very
00026  * precise but subtle.
00027  *
00028  * The last pbuf of a packet has a ->tot_len field that equals the
00029  * ->len field. It can be found by traversing the list. If the last
00030  * pbuf of a packet has a ->next field other than NULL, more packets
00031  * are on the queue.
00032  *
00033  * Therefore, looping through a pbuf of a single packet, has an
00034  * loop end condition (tot_len == p->len), NOT (next == NULL).
00035  *
00036  * Example of custom pbuf usage for zero-copy RX:
00037   @code{.c}
00038 typedef struct my_custom_pbuf
00039 {
00040    struct pbuf_custom p;
00041    void* dma_descriptor;
00042 } my_custom_pbuf_t;
00043 
00044 LWIP_MEMPOOL_DECLARE(RX_POOL, 10, sizeof(my_custom_pbuf_t), "Zero-copy RX PBUF pool");
00045 
00046 void my_pbuf_free_custom(void* p)
00047 {
00048   my_custom_pbuf_t* my_puf = (my_custom_pbuf_t*)p;
00049 
00050   LOCK_INTERRUPTS();
00051   free_rx_dma_descriptor(my_pbuf->dma_descriptor);
00052   LWIP_MEMPOOL_FREE(RX_POOL, my_pbuf);
00053   UNLOCK_INTERRUPTS();
00054 }
00055 
00056 void eth_rx_irq()
00057 {
00058   dma_descriptor*   dma_desc = get_RX_DMA_descriptor_from_ethernet();
00059   my_custom_pbuf_t* my_pbuf  = (my_custom_pbuf_t*)LWIP_MEMPOOL_ALLOC(RX_POOL);
00060 
00061   my_pbuf->p.custom_free_function = my_pbuf_free_custom;
00062   my_pbuf->dma_descriptor         = dma_desc;
00063 
00064   invalidate_cpu_cache(dma_desc->rx_data, dma_desc->rx_length);
00065   
00066   struct pbuf* p = pbuf_alloced_custom(PBUF_RAW,
00067      dma_desc->rx_length,
00068      PBUF_REF,
00069      &my_pbuf->p,
00070      dma_desc->rx_data,
00071      dma_desc->max_buffer_size);
00072 
00073   if(netif->input(p, netif) != ERR_OK) {
00074     pbuf_free(p);
00075   }
00076 }
00077   @endcode
00078  */
00079 
00080 /*
00081  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
00082  * All rights reserved.
00083  *
00084  * Redistribution and use in source and binary forms, with or without modification,
00085  * are permitted provided that the following conditions are met:
00086  *
00087  * 1. Redistributions of source code must retain the above copyright notice,
00088  *    this list of conditions and the following disclaimer.
00089  * 2. Redistributions in binary form must reproduce the above copyright notice,
00090  *    this list of conditions and the following disclaimer in the documentation
00091  *    and/or other materials provided with the distribution.
00092  * 3. The name of the author may not be used to endorse or promote products
00093  *    derived from this software without specific prior written permission.
00094  *
00095  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
00096  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
00097  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
00098  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00099  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
00100  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00101  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00102  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
00103  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
00104  * OF SUCH DAMAGE.
00105  *
00106  * This file is part of the lwIP TCP/IP stack.
00107  *
00108  * Author: Adam Dunkels <adam@sics.se>
00109  *
00110  */
00111 
00112 #include "lwip/opt.h"
00113 
00114 #include "lwip/stats.h"
00115 #include "lwip/def.h"
00116 #include "lwip/mem.h"
00117 #include "lwip/memp.h"
00118 #include "lwip/pbuf.h"
00119 #include "lwip/sys.h"
00120 #if LWIP_TCP && TCP_QUEUE_OOSEQ
00121 #include "lwip/priv/tcp_priv.h"
00122 #endif
00123 #if LWIP_CHECKSUM_ON_COPY
00124 #include "lwip/inet_chksum.h"
00125 #endif
00126 
00127 #include <string.h>
00128 
00129 #define SIZEOF_STRUCT_PBUF        LWIP_MEM_ALIGN_SIZE(sizeof(struct pbuf))
00130 /* Since the pool is created in memp, PBUF_POOL_BUFSIZE will be automatically
00131    aligned there. Therefore, PBUF_POOL_BUFSIZE_ALIGNED can be used here. */
00132 #define PBUF_POOL_BUFSIZE_ALIGNED LWIP_MEM_ALIGN_SIZE(PBUF_POOL_BUFSIZE)
00133 
00134 #if !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ
00135 #define PBUF_POOL_IS_EMPTY()
00136 #else /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
00137 
00138 #if !NO_SYS
00139 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
00140 #include "lwip/tcpip.h"
00141 #define PBUF_POOL_FREE_OOSEQ_QUEUE_CALL()  do { \
00142   if (tcpip_callback_with_block(pbuf_free_ooseq_callback, NULL, 0) != ERR_OK) { \
00143       SYS_ARCH_PROTECT(old_level); \
00144       pbuf_free_ooseq_pending = 0; \
00145       SYS_ARCH_UNPROTECT(old_level); \
00146   } } while(0)
00147 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
00148 #endif /* !NO_SYS */
00149 
00150 volatile u8_t pbuf_free_ooseq_pending;
00151 #define PBUF_POOL_IS_EMPTY() pbuf_pool_is_empty()
00152 
00153 /**
00154  * Attempt to reclaim some memory from queued out-of-sequence TCP segments
00155  * if we run out of pool pbufs. It's better to give priority to new packets
00156  * if we're running out.
00157  *
00158  * This must be done in the correct thread context therefore this function
00159  * can only be used with NO_SYS=0 and through tcpip_callback.
00160  */
00161 #if !NO_SYS
00162 static
00163 #endif /* !NO_SYS */
00164 void
00165 pbuf_free_ooseq(void)
00166 {
00167   struct tcp_pcb* pcb;
00168   SYS_ARCH_SET(pbuf_free_ooseq_pending, 0);
00169 
00170   for (pcb = tcp_active_pcbs; NULL != pcb; pcb = pcb->next) {
00171     if (NULL != pcb->ooseq) {
00172       /** Free the ooseq pbufs of one PCB only */
00173       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free_ooseq: freeing out-of-sequence pbufs\n"));
00174       tcp_segs_free(pcb->ooseq);
00175       pcb->ooseq = NULL;
00176       return;
00177     }
00178   }
00179 }
00180 
00181 #if !NO_SYS
00182 /**
00183  * Just a callback function for tcpip_callback() that calls pbuf_free_ooseq().
00184  */
00185 static void
00186 pbuf_free_ooseq_callback(void *arg)
00187 {
00188   LWIP_UNUSED_ARG(arg);
00189   pbuf_free_ooseq();
00190 }
00191 #endif /* !NO_SYS */
00192 
00193 /** Queue a call to pbuf_free_ooseq if not already queued. */
00194 static void
00195 pbuf_pool_is_empty(void)
00196 {
00197 #ifndef PBUF_POOL_FREE_OOSEQ_QUEUE_CALL
00198   SYS_ARCH_SET(pbuf_free_ooseq_pending, 1);
00199 #else /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
00200   u8_t queued;
00201   SYS_ARCH_DECL_PROTECT(old_level);
00202   SYS_ARCH_PROTECT(old_level);
00203   queued = pbuf_free_ooseq_pending;
00204   pbuf_free_ooseq_pending = 1;
00205   SYS_ARCH_UNPROTECT(old_level);
00206 
00207   if (!queued) {
00208     /* queue a call to pbuf_free_ooseq if not already queued */
00209     PBUF_POOL_FREE_OOSEQ_QUEUE_CALL();
00210   }
00211 #endif /* PBUF_POOL_FREE_OOSEQ_QUEUE_CALL */
00212 }
00213 #endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || !PBUF_POOL_FREE_OOSEQ */
00214 
00215 /**
00216  * @ingroup pbuf
00217  * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
00218  *
00219  * The actual memory allocated for the pbuf is determined by the
00220  * layer at which the pbuf is allocated and the requested size
00221  * (from the size parameter).
00222  *
00223  * @param layer flag to define header size
00224  * @param length size of the pbuf's payload
00225  * @param type this parameter decides how and where the pbuf
00226  * should be allocated as follows:
00227  *
00228  * - PBUF_RAM: buffer memory for pbuf is allocated as one large
00229  *             chunk. This includes protocol headers as well.
00230  * - PBUF_ROM: no buffer memory is allocated for the pbuf, even for
00231  *             protocol headers. Additional headers must be prepended
00232  *             by allocating another pbuf and chain in to the front of
00233  *             the ROM pbuf. It is assumed that the memory used is really
00234  *             similar to ROM in that it is immutable and will not be
00235  *             changed. Memory which is dynamic should generally not
00236  *             be attached to PBUF_ROM pbufs. Use PBUF_REF instead.
00237  * - PBUF_REF: no buffer memory is allocated for the pbuf, even for
00238  *             protocol headers. It is assumed that the pbuf is only
00239  *             being used in a single thread. If the pbuf gets queued,
00240  *             then pbuf_take should be called to copy the buffer.
00241  * - PBUF_POOL: the pbuf is allocated as a pbuf chain, with pbufs from
00242  *              the pbuf pool that is allocated during pbuf_init().
00243  *
00244  * @return the allocated pbuf. If multiple pbufs where allocated, this
00245  * is the first pbuf of a pbuf chain.
00246  */
00247 struct pbuf *
00248 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
00249 {
00250   struct pbuf *p, *q, *r;
00251   u16_t offset;
00252   s32_t rem_len; /* remaining length */
00253   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
00254 
00255   /* determine header offset */
00256   switch (layer) {
00257   case PBUF_TRANSPORT:
00258     /* add room for transport (often TCP) layer header */
00259     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
00260     break;
00261   case PBUF_IP:
00262     /* add room for IP layer header */
00263     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN;
00264     break;
00265   case PBUF_LINK:
00266     /* add room for link layer header */
00267     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN;
00268     break;
00269   case PBUF_RAW_TX:
00270     /* add room for encapsulating link layer headers (e.g. 802.11) */
00271     offset = PBUF_LINK_ENCAPSULATION_HLEN;
00272     break;
00273   case PBUF_RAW:
00274     /* no offset (e.g. RX buffers or chain successors) */
00275     offset = 0;
00276     break;
00277   default:
00278     LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
00279     return NULL;
00280   }
00281 
00282   switch (type) {
00283   case PBUF_POOL:
00284     /* allocate head of pbuf chain into p */
00285     p = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
00286     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc: allocated pbuf %p\n", (void *)p));
00287     if (p == NULL) {
00288       PBUF_POOL_IS_EMPTY();
00289       return NULL;
00290     }
00291     p->type = type;
00292     p->next = NULL;
00293 
00294     /* make the payload pointer point 'offset' bytes into pbuf data memory */
00295     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + (SIZEOF_STRUCT_PBUF + offset)));
00296     LWIP_ASSERT("pbuf_alloc: pbuf p->payload properly aligned",
00297             ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
00298     /* the total length of the pbuf chain is the requested size */
00299     p->tot_len = length;
00300     /* set the length of the first pbuf in the chain */
00301     p->len = LWIP_MIN(length, PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset));
00302     LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
00303                 ((u8_t*)p->payload + p->len <=
00304                  (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
00305     LWIP_ASSERT("PBUF_POOL_BUFSIZE must be bigger than MEM_ALIGNMENT",
00306       (PBUF_POOL_BUFSIZE_ALIGNED - LWIP_MEM_ALIGN_SIZE(offset)) > 0 );
00307     /* set reference count (needed here in case we fail) */
00308     p->ref = 1;
00309 
00310     /* now allocate the tail of the pbuf chain */
00311 
00312     /* remember first pbuf for linkage in next iteration */
00313     r = p;
00314     /* remaining length to be allocated */
00315     rem_len = length - p->len;
00316     /* any remaining pbufs to be allocated? */
00317     while (rem_len > 0) {
00318       q = (struct pbuf *)memp_malloc(MEMP_PBUF_POOL);
00319       if (q == NULL) {
00320         PBUF_POOL_IS_EMPTY();
00321         /* free chain so far allocated */
00322         pbuf_free(p);
00323         /* bail out unsuccessfully */
00324         return NULL;
00325       }
00326       q->type = type;
00327       q->flags = 0;
00328       q->next = NULL;
00329       /* make previous pbuf point to this pbuf */
00330       r->next = q;
00331       /* set total length of this pbuf and next in chain */
00332       LWIP_ASSERT("rem_len < max_u16_t", rem_len < 0xffff);
00333       q->tot_len = (u16_t)rem_len;
00334       /* this pbuf length is pool size, unless smaller sized tail */
00335       q->len = LWIP_MIN((u16_t)rem_len, PBUF_POOL_BUFSIZE_ALIGNED);
00336       q->payload = (void *)((u8_t *)q + SIZEOF_STRUCT_PBUF);
00337       LWIP_ASSERT("pbuf_alloc: pbuf q->payload properly aligned",
00338               ((mem_ptr_t)q->payload % MEM_ALIGNMENT) == 0);
00339       LWIP_ASSERT("check p->payload + p->len does not overflow pbuf",
00340                   ((u8_t*)p->payload + p->len <=
00341                    (u8_t*)p + SIZEOF_STRUCT_PBUF + PBUF_POOL_BUFSIZE_ALIGNED));
00342       q->ref = 1;
00343       /* calculate remaining length to be allocated */
00344       rem_len -= q->len;
00345       /* remember this pbuf for linkage in next iteration */
00346       r = q;
00347     }
00348     /* end of chain */
00349     /*r->next = NULL;*/
00350 
00351     break;
00352   case PBUF_RAM:
00353     /* If pbuf is to be allocated in RAM, allocate memory for it. */
00354     p = (struct pbuf*)mem_malloc(LWIP_MEM_ALIGN_SIZE(SIZEOF_STRUCT_PBUF + offset) + LWIP_MEM_ALIGN_SIZE(length));
00355     if (p == NULL) {
00356       return NULL;
00357     }
00358     /* Set up internal structure of the pbuf. */
00359     p->payload = LWIP_MEM_ALIGN((void *)((u8_t *)p + SIZEOF_STRUCT_PBUF + offset));
00360     p->len = p->tot_len = length;
00361     p->next = NULL;
00362     p->type = type;
00363 
00364     LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
00365            ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
00366     break;
00367   /* pbuf references existing (non-volatile static constant) ROM payload? */
00368   case PBUF_ROM:
00369   /* pbuf references existing (externally allocated) RAM payload? */
00370   case PBUF_REF:
00371     /* only allocate memory for the pbuf structure */
00372     p = (struct pbuf *)memp_malloc(MEMP_PBUF);
00373     if (p == NULL) {
00374       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
00375                   ("pbuf_alloc: Could not allocate MEMP_PBUF for PBUF_%s.\n",
00376                   (type == PBUF_ROM) ? "ROM" : "REF"));
00377       return NULL;
00378     }
00379     /* caller must set this field properly, afterwards */
00380     p->payload = NULL;
00381     p->len = p->tot_len = length;
00382     p->next = NULL;
00383     p->type = type;
00384     break;
00385   default:
00386     LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
00387     return NULL;
00388   }
00389   /* set reference count */
00390   p->ref = 1;
00391   /* set flags */
00392   p->flags = 0;
00393   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
00394   return p;
00395 }
00396 
00397 #if LWIP_SUPPORT_CUSTOM_PBUF
00398 /**
00399  * @ingroup pbuf
00400  * Initialize a custom pbuf (already allocated).
00401  *
00402  * @param l flag to define header size
00403  * @param length size of the pbuf's payload
00404  * @param type type of the pbuf (only used to treat the pbuf accordingly, as
00405  *        this function allocates no memory)
00406  * @param p pointer to the custom pbuf to initialize (already allocated)
00407  * @param payload_mem pointer to the buffer that is used for payload and headers,
00408  *        must be at least big enough to hold 'length' plus the header size,
00409  *        may be NULL if set later.
00410  *        ATTENTION: The caller is responsible for correct alignment of this buffer!!
00411  * @param payload_mem_len the size of the 'payload_mem' buffer, must be at least
00412  *        big enough to hold 'length' plus the header size
00413  */
00414 struct pbuf*
00415 pbuf_alloced_custom(pbuf_layer l, u16_t length, pbuf_type type, struct pbuf_custom *p,
00416                     void *payload_mem, u16_t payload_mem_len)
00417 {
00418   u16_t offset;
00419   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloced_custom(length=%"U16_F")\n", length));
00420 
00421   /* determine header offset */
00422   switch (l) {
00423   case PBUF_TRANSPORT:
00424     /* add room for transport (often TCP) layer header */
00425     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN;
00426     break;
00427   case PBUF_IP:
00428     /* add room for IP layer header */
00429     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN;
00430     break;
00431   case PBUF_LINK:
00432     /* add room for link layer header */
00433     offset = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN;
00434     break;
00435   case PBUF_RAW_TX:
00436     /* add room for encapsulating link layer headers (e.g. 802.11) */
00437     offset = PBUF_LINK_ENCAPSULATION_HLEN;
00438     break;
00439   case PBUF_RAW:
00440     offset = 0;
00441     break;
00442   default:
00443     LWIP_ASSERT("pbuf_alloced_custom: bad pbuf layer", 0);
00444     return NULL;
00445   }
00446 
00447   if (LWIP_MEM_ALIGN_SIZE(offset) + length > payload_mem_len) {
00448     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_WARNING, ("pbuf_alloced_custom(length=%"U16_F") buffer too short\n", length));
00449     return NULL;
00450   }
00451 
00452   p->pbuf.next = NULL;
00453   if (payload_mem != NULL) {
00454     p->pbuf.payload = (u8_t *)payload_mem + LWIP_MEM_ALIGN_SIZE(offset);
00455   } else {
00456     p->pbuf.payload = NULL;
00457   }
00458   p->pbuf.flags = PBUF_FLAG_IS_CUSTOM;
00459   p->pbuf.len = p->pbuf.tot_len = length;
00460   p->pbuf.type = type;
00461   p->pbuf.ref = 1;
00462   return &p->pbuf;
00463 }
00464 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
00465 
00466 /**
00467  * @ingroup pbuf
00468  * Shrink a pbuf chain to a desired length.
00469  *
00470  * @param p pbuf to shrink.
00471  * @param new_len desired new length of pbuf chain
00472  *
00473  * Depending on the desired length, the first few pbufs in a chain might
00474  * be skipped and left unchanged. The new last pbuf in the chain will be
00475  * resized, and any remaining pbufs will be freed.
00476  *
00477  * @note If the pbuf is ROM/REF, only the ->tot_len and ->len fields are adjusted.
00478  * @note May not be called on a packet queue.
00479  *
00480  * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
00481  */
00482 void
00483 pbuf_realloc(struct pbuf *p, u16_t new_len)
00484 {
00485   struct pbuf *q;
00486   u16_t rem_len; /* remaining length */
00487   s32_t grow;
00488 
00489   LWIP_ASSERT("pbuf_realloc: p != NULL", p != NULL);
00490   LWIP_ASSERT("pbuf_realloc: sane p->type", p->type == PBUF_POOL ||
00491               p->type == PBUF_ROM ||
00492               p->type == PBUF_RAM ||
00493               p->type == PBUF_REF);
00494 
00495   /* desired length larger than current length? */
00496   if (new_len >= p->tot_len) {
00497     /* enlarging not yet supported */
00498     return;
00499   }
00500 
00501   /* the pbuf chain grows by (new_len - p->tot_len) bytes
00502    * (which may be negative in case of shrinking) */
00503   grow = new_len - p->tot_len;
00504 
00505   /* first, step over any pbufs that should remain in the chain */
00506   rem_len = new_len;
00507   q = p;
00508   /* should this pbuf be kept? */
00509   while (rem_len > q->len) {
00510     /* decrease remaining length by pbuf length */
00511     rem_len -= q->len;
00512     /* decrease total length indicator */
00513     LWIP_ASSERT("grow < max_u16_t", grow < 0xffff);
00514     q->tot_len += (u16_t)grow;
00515     /* proceed to next pbuf in chain */
00516     q = q->next;
00517     LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
00518   }
00519   /* we have now reached the new last pbuf (in q) */
00520   /* rem_len == desired length for pbuf q */
00521 
00522   /* shrink allocated memory for PBUF_RAM */
00523   /* (other types merely adjust their length fields */
00524   if ((q->type == PBUF_RAM) && (rem_len != q->len)
00525 #if LWIP_SUPPORT_CUSTOM_PBUF
00526       && ((q->flags & PBUF_FLAG_IS_CUSTOM) == 0)
00527 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
00528      ) {
00529     /* reallocate and adjust the length of the pbuf that will be split */
00530     q = (struct pbuf *)mem_trim(q, (u16_t)((u8_t *)q->payload - (u8_t *)q) + rem_len);
00531     LWIP_ASSERT("mem_trim returned q == NULL", q != NULL);
00532   }
00533   /* adjust length fields for new last pbuf */
00534   q->len = rem_len;
00535   q->tot_len = q->len;
00536 
00537   /* any remaining pbufs in chain? */
00538   if (q->next != NULL) {
00539     /* free remaining pbufs in chain */
00540     pbuf_free(q->next);
00541   }
00542   /* q is last packet in chain */
00543   q->next = NULL;
00544 
00545 }
00546 
00547 /**
00548  * Adjusts the payload pointer to hide or reveal headers in the payload.
00549  * @see pbuf_header.
00550  *
00551  * @param p pbuf to change the header size.
00552  * @param header_size_increment Number of bytes to increment header size.
00553  * @param force Allow 'header_size_increment > 0' for PBUF_REF/PBUF_ROM types
00554  *
00555  * @return non-zero on failure, zero on success.
00556  *
00557  */
00558 static u8_t
00559 pbuf_header_impl(struct pbuf *p, s16_t header_size_increment, u8_t force)
00560 {
00561   u16_t type;
00562   void *payload;
00563   u16_t increment_magnitude;
00564 
00565   LWIP_ASSERT("p != NULL", p != NULL);
00566   if ((header_size_increment == 0) || (p == NULL)) {
00567     return 0;
00568   }
00569 
00570   if (header_size_increment < 0) {
00571     increment_magnitude = (u16_t)-header_size_increment;
00572     /* Check that we aren't going to move off the end of the pbuf */
00573     LWIP_ERROR("increment_magnitude <= p->len", (increment_magnitude <= p->len), return 1;);
00574   } else {
00575     increment_magnitude = (u16_t)header_size_increment;
00576 #if 0
00577     /* Can't assert these as some callers speculatively call
00578          pbuf_header() to see if it's OK.  Will return 1 below instead. */
00579     /* Check that we've got the correct type of pbuf to work with */
00580     LWIP_ASSERT("p->type == PBUF_RAM || p->type == PBUF_POOL",
00581                 p->type == PBUF_RAM || p->type == PBUF_POOL);
00582     /* Check that we aren't going to move off the beginning of the pbuf */
00583     LWIP_ASSERT("p->payload - increment_magnitude >= p + SIZEOF_STRUCT_PBUF",
00584                 (u8_t *)p->payload - increment_magnitude >= (u8_t *)p + SIZEOF_STRUCT_PBUF);
00585 #endif
00586   }
00587 
00588   type = p->type;
00589   /* remember current payload pointer */
00590   payload = p->payload;
00591 
00592   /* pbuf types containing payloads? */
00593   if (type == PBUF_RAM || type == PBUF_POOL) {
00594     /* set new payload pointer */
00595     p->payload = (u8_t *)p->payload - header_size_increment;
00596     /* boundary check fails? */
00597     if ((u8_t *)p->payload < (u8_t *)p + SIZEOF_STRUCT_PBUF) {
00598       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE,
00599         ("pbuf_header: failed as %p < %p (not enough space for new header size)\n",
00600         (void *)p->payload, (void *)((u8_t *)p + SIZEOF_STRUCT_PBUF)));
00601       /* restore old payload pointer */
00602       p->payload = payload;
00603       /* bail out unsuccessfully */
00604       return 1;
00605     }
00606   /* pbuf types referring to external payloads? */
00607   } else if (type == PBUF_REF || type == PBUF_ROM) {
00608     /* hide a header in the payload? */
00609     if ((header_size_increment < 0) && (increment_magnitude <= p->len)) {
00610       /* increase payload pointer */
00611       p->payload = (u8_t *)p->payload - header_size_increment;
00612     } else if ((header_size_increment > 0) && force) {
00613       p->payload = (u8_t *)p->payload - header_size_increment;
00614     } else {
00615       /* cannot expand payload to front (yet!)
00616        * bail out unsuccessfully */
00617       return 1;
00618     }
00619   } else {
00620     /* Unknown type */
00621     LWIP_ASSERT("bad pbuf type", 0);
00622     return 1;
00623   }
00624   /* modify pbuf length fields */
00625   p->len += header_size_increment;
00626   p->tot_len += header_size_increment;
00627 
00628   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_header: old %p new %p (%"S16_F")\n",
00629     (void *)payload, (void *)p->payload, header_size_increment));
00630 
00631   return 0;
00632 }
00633 
00634 /**
00635  * Adjusts the payload pointer to hide or reveal headers in the payload.
00636  *
00637  * Adjusts the ->payload pointer so that space for a header
00638  * (dis)appears in the pbuf payload.
00639  *
00640  * The ->payload, ->tot_len and ->len fields are adjusted.
00641  *
00642  * @param p pbuf to change the header size.
00643  * @param header_size_increment Number of bytes to increment header size which
00644  * increases the size of the pbuf. New space is on the front.
00645  * (Using a negative value decreases the header size.)
00646  * If hdr_size_inc is 0, this function does nothing and returns successful.
00647  *
00648  * PBUF_ROM and PBUF_REF type buffers cannot have their sizes increased, so
00649  * the call will fail. A check is made that the increase in header size does
00650  * not move the payload pointer in front of the start of the buffer.
00651  * @return non-zero on failure, zero on success.
00652  *
00653  */
00654 u8_t
00655 pbuf_header(struct pbuf *p, s16_t header_size_increment)
00656 {
00657    return pbuf_header_impl(p, header_size_increment, 0);
00658 }
00659 
00660 /**
00661  * Same as pbuf_header but does not check if 'header_size > 0' is allowed.
00662  * This is used internally only, to allow PBUF_REF for RX.
00663  */
00664 u8_t
00665 pbuf_header_force(struct pbuf *p, s16_t header_size_increment)
00666 {
00667    return pbuf_header_impl(p, header_size_increment, 1);
00668 }
00669 
00670 /**
00671  * @ingroup pbuf
00672  * Dereference a pbuf chain or queue and deallocate any no-longer-used
00673  * pbufs at the head of this chain or queue.
00674  *
00675  * Decrements the pbuf reference count. If it reaches zero, the pbuf is
00676  * deallocated.
00677  *
00678  * For a pbuf chain, this is repeated for each pbuf in the chain,
00679  * up to the first pbuf which has a non-zero reference count after
00680  * decrementing. So, when all reference counts are one, the whole
00681  * chain is free'd.
00682  *
00683  * @param p The pbuf (chain) to be dereferenced.
00684  *
00685  * @return the number of pbufs that were de-allocated
00686  * from the head of the chain.
00687  *
00688  * @note MUST NOT be called on a packet queue (Not verified to work yet).
00689  * @note the reference counter of a pbuf equals the number of pointers
00690  * that refer to the pbuf (or into the pbuf).
00691  *
00692  * @internal examples:
00693  *
00694  * Assuming existing chains a->b->c with the following reference
00695  * counts, calling pbuf_free(a) results in:
00696  *
00697  * 1->2->3 becomes ...1->3
00698  * 3->3->3 becomes 2->3->3
00699  * 1->1->2 becomes ......1
00700  * 2->1->1 becomes 1->1->1
00701  * 1->1->1 becomes .......
00702  *
00703  */
00704 u8_t
00705 pbuf_free(struct pbuf *p)
00706 {
00707   u16_t type;
00708   struct pbuf *q;
00709   u8_t count;
00710 
00711   if (p == NULL) {
00712     LWIP_ASSERT("p != NULL", p != NULL);
00713     /* if assertions are disabled, proceed with debug output */
00714     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
00715       ("pbuf_free(p == NULL) was called.\n"));
00716     return 0;
00717   }
00718   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
00719 
00720   PERF_START;
00721 
00722   LWIP_ASSERT("pbuf_free: sane type",
00723     p->type == PBUF_RAM || p->type == PBUF_ROM ||
00724     p->type == PBUF_REF || p->type == PBUF_POOL);
00725 
00726   count = 0;
00727   /* de-allocate all consecutive pbufs from the head of the chain that
00728    * obtain a zero reference count after decrementing*/
00729   while (p != NULL) {
00730     u16_t ref;
00731     SYS_ARCH_DECL_PROTECT(old_level);
00732     /* Since decrementing ref cannot be guaranteed to be a single machine operation
00733      * we must protect it. We put the new ref into a local variable to prevent
00734      * further protection. */
00735     SYS_ARCH_PROTECT(old_level);
00736     /* all pbufs in a chain are referenced at least once */
00737     LWIP_ASSERT("pbuf_free: p->ref > 0", p->ref > 0);
00738     /* decrease reference count (number of pointers to pbuf) */
00739     ref = --(p->ref);
00740     SYS_ARCH_UNPROTECT(old_level);
00741     /* this pbuf is no longer referenced to? */
00742     if (ref == 0) {
00743       /* remember next pbuf in chain for next iteration */
00744       q = p->next;
00745       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
00746       type = p->type;
00747 #if LWIP_SUPPORT_CUSTOM_PBUF
00748       /* is this a custom pbuf? */
00749       if ((p->flags & PBUF_FLAG_IS_CUSTOM) != 0) {
00750         struct pbuf_custom *pc = (struct pbuf_custom*)p;
00751         LWIP_ASSERT("pc->custom_free_function != NULL", pc->custom_free_function != NULL);
00752         pc->custom_free_function(p);
00753       } else
00754 #endif /* LWIP_SUPPORT_CUSTOM_PBUF */
00755       {
00756         /* is this a pbuf from the pool? */
00757         if (type == PBUF_POOL) {
00758           memp_free(MEMP_PBUF_POOL, p);
00759         /* is this a ROM or RAM referencing pbuf? */
00760         } else if (type == PBUF_ROM || type == PBUF_REF) {
00761           memp_free(MEMP_PBUF, p);
00762         /* type == PBUF_RAM */
00763         } else {
00764           mem_free(p);
00765         }
00766       }
00767       count++;
00768       /* proceed to next pbuf */
00769       p = q;
00770     /* p->ref > 0, this pbuf is still referenced to */
00771     /* (and so the remaining pbufs in chain as well) */
00772     } else {
00773       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: %p has ref %"U16_F", ending here.\n", (void *)p, ref));
00774       /* stop walking through the chain */
00775       p = NULL;
00776     }
00777   }
00778   PERF_STOP("pbuf_free");
00779   /* return number of de-allocated pbufs */
00780   return count;
00781 }
00782 
00783 /**
00784  * Count number of pbufs in a chain
00785  *
00786  * @param p first pbuf of chain
00787  * @return the number of pbufs in a chain
00788  */
00789 u16_t
00790 pbuf_clen(const struct pbuf *p)
00791 {
00792   u16_t len;
00793 
00794   len = 0;
00795   while (p != NULL) {
00796     ++len;
00797     p = p->next;
00798   }
00799   return len;
00800 }
00801 
00802 /**
00803  * @ingroup pbuf
00804  * Increment the reference count of the pbuf.
00805  *
00806  * @param p pbuf to increase reference counter of
00807  *
00808  */
00809 void
00810 pbuf_ref(struct pbuf *p)
00811 {
00812   /* pbuf given? */
00813   if (p != NULL) {
00814     SYS_ARCH_INC(p->ref, 1);
00815   }
00816 }
00817 
00818 /**
00819  * @ingroup pbuf
00820  * Concatenate two pbufs (each may be a pbuf chain) and take over
00821  * the caller's reference of the tail pbuf.
00822  *
00823  * @note The caller MAY NOT reference the tail pbuf afterwards.
00824  * Use pbuf_chain() for that purpose.
00825  *
00826  * @see pbuf_chain()
00827  */
00828 void
00829 pbuf_cat(struct pbuf *h, struct pbuf *t)
00830 {
00831   struct pbuf *p;
00832 
00833   LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
00834              ((h != NULL) && (t != NULL)), return;);
00835 
00836   /* proceed to last pbuf of chain */
00837   for (p = h; p->next != NULL; p = p->next) {
00838     /* add total length of second chain to all totals of first chain */
00839     p->tot_len += t->tot_len;
00840   }
00841   /* { p is last pbuf of first h chain, p->next == NULL } */
00842   LWIP_ASSERT("p->tot_len == p->len (of last pbuf in chain)", p->tot_len == p->len);
00843   LWIP_ASSERT("p->next == NULL", p->next == NULL);
00844   /* add total length of second chain to last pbuf total of first chain */
00845   p->tot_len += t->tot_len;
00846   /* chain last pbuf of head (p) with first of tail (t) */
00847   p->next = t;
00848   /* p->next now references t, but the caller will drop its reference to t,
00849    * so netto there is no change to the reference count of t.
00850    */
00851 }
00852 
00853 /**
00854  * @ingroup pbuf
00855  * Chain two pbufs (or pbuf chains) together.
00856  *
00857  * The caller MUST call pbuf_free(t) once it has stopped
00858  * using it. Use pbuf_cat() instead if you no longer use t.
00859  *
00860  * @param h head pbuf (chain)
00861  * @param t tail pbuf (chain)
00862  * @note The pbufs MUST belong to the same packet.
00863  * @note MAY NOT be called on a packet queue.
00864  *
00865  * The ->tot_len fields of all pbufs of the head chain are adjusted.
00866  * The ->next field of the last pbuf of the head chain is adjusted.
00867  * The ->ref field of the first pbuf of the tail chain is adjusted.
00868  *
00869  */
00870 void
00871 pbuf_chain(struct pbuf *h, struct pbuf *t)
00872 {
00873   pbuf_cat(h, t);
00874   /* t is now referenced by h */
00875   pbuf_ref(t);
00876   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
00877 }
00878 
00879 /**
00880  * Dechains the first pbuf from its succeeding pbufs in the chain.
00881  *
00882  * Makes p->tot_len field equal to p->len.
00883  * @param p pbuf to dechain
00884  * @return remainder of the pbuf chain, or NULL if it was de-allocated.
00885  * @note May not be called on a packet queue.
00886  */
00887 struct pbuf *
00888 pbuf_dechain(struct pbuf *p)
00889 {
00890   struct pbuf *q;
00891   u8_t tail_gone = 1;
00892   /* tail */
00893   q = p->next;
00894   /* pbuf has successor in chain? */
00895   if (q != NULL) {
00896     /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
00897     LWIP_ASSERT("p->tot_len == p->len + q->tot_len", q->tot_len == p->tot_len - p->len);
00898     /* enforce invariant if assertion is disabled */
00899     q->tot_len = p->tot_len - p->len;
00900     /* decouple pbuf from remainder */
00901     p->next = NULL;
00902     /* total length of pbuf p is its own length only */
00903     p->tot_len = p->len;
00904     /* q is no longer referenced by p, free it */
00905     LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_dechain: unreferencing %p\n", (void *)q));
00906     tail_gone = pbuf_free(q);
00907     if (tail_gone > 0) {
00908       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
00909                   ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
00910     }
00911     /* return remaining tail or NULL if deallocated */
00912   }
00913   /* assert tot_len invariant: (p->tot_len == p->len + (p->next? p->next->tot_len: 0) */
00914   LWIP_ASSERT("p->tot_len == p->len", p->tot_len == p->len);
00915   return ((tail_gone > 0) ? NULL : q);
00916 }
00917 
00918 /**
00919  * @ingroup pbuf
00920  * Create PBUF_RAM copies of pbufs.
00921  *
00922  * Used to queue packets on behalf of the lwIP stack, such as
00923  * ARP based queueing.
00924  *
00925  * @note You MUST explicitly use p = pbuf_take(p);
00926  *
00927  * @note Only one packet is copied, no packet queue!
00928  *
00929  * @param p_to pbuf destination of the copy
00930  * @param p_from pbuf source of the copy
00931  *
00932  * @return ERR_OK if pbuf was copied
00933  *         ERR_ARG if one of the pbufs is NULL or p_to is not big
00934  *                 enough to hold p_from
00935  */
00936 err_t
00937 pbuf_copy(struct pbuf *p_to, const struct pbuf *p_from)
00938 {
00939   u16_t offset_to=0, offset_from=0, len;
00940 
00941   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
00942     (const void*)p_to, (const void*)p_from));
00943 
00944   /* is the target big enough to hold the source? */
00945   LWIP_ERROR("pbuf_copy: target not big enough to hold source", ((p_to != NULL) &&
00946              (p_from != NULL) && (p_to->tot_len >= p_from->tot_len)), return ERR_ARG;);
00947 
00948   /* iterate through pbuf chain */
00949   do
00950   {
00951     /* copy one part of the original chain */
00952     if ((p_to->len - offset_to) >= (p_from->len - offset_from)) {
00953       /* complete current p_from fits into current p_to */
00954       len = p_from->len - offset_from;
00955     } else {
00956       /* current p_from does not fit into current p_to */
00957       len = p_to->len - offset_to;
00958     }
00959     MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
00960     offset_to += len;
00961     offset_from += len;
00962     LWIP_ASSERT("offset_to <= p_to->len", offset_to <= p_to->len);
00963     LWIP_ASSERT("offset_from <= p_from->len", offset_from <= p_from->len);
00964     if (offset_from >= p_from->len) {
00965       /* on to next p_from (if any) */
00966       offset_from = 0;
00967       p_from = p_from->next;
00968     }
00969     if (offset_to == p_to->len) {
00970       /* on to next p_to (if any) */
00971       offset_to = 0;
00972       p_to = p_to->next;
00973       LWIP_ERROR("p_to != NULL", (p_to != NULL) || (p_from == NULL) , return ERR_ARG;);
00974     }
00975 
00976     if ((p_from != NULL) && (p_from->len == p_from->tot_len)) {
00977       /* don't copy more than one packet! */
00978       LWIP_ERROR("pbuf_copy() does not allow packet queues!",
00979                  (p_from->next == NULL), return ERR_VAL;);
00980     }
00981     if ((p_to != NULL) && (p_to->len == p_to->tot_len)) {
00982       /* don't copy more than one packet! */
00983       LWIP_ERROR("pbuf_copy() does not allow packet queues!",
00984                   (p_to->next == NULL), return ERR_VAL;);
00985     }
00986   } while (p_from);
00987   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
00988   return ERR_OK;
00989 }
00990 
00991 /**
00992  * @ingroup pbuf
00993  * Copy (part of) the contents of a packet buffer
00994  * to an application supplied buffer.
00995  *
00996  * @param buf the pbuf from which to copy data
00997  * @param dataptr the application supplied buffer
00998  * @param len length of data to copy (dataptr must be big enough). No more
00999  * than buf->tot_len will be copied, irrespective of len
01000  * @param offset offset into the packet buffer from where to begin copying len bytes
01001  * @return the number of bytes copied, or 0 on failure
01002  */
01003 u16_t
01004 pbuf_copy_partial(const struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
01005 {
01006   const struct pbuf *p;
01007   u16_t left;
01008   u16_t buf_copy_len;
01009   u16_t copied_total = 0;
01010 
01011   LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
01012   LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
01013 
01014   left = 0;
01015 
01016   if ((buf == NULL) || (dataptr == NULL)) {
01017     return 0;
01018   }
01019 
01020   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
01021   for (p = buf; len != 0 && p != NULL; p = p->next) {
01022     if ((offset != 0) && (offset >= p->len)) {
01023       /* don't copy from this buffer -> on to the next */
01024       offset -= p->len;
01025     } else {
01026       /* copy from this buffer. maybe only partially. */
01027       buf_copy_len = p->len - offset;
01028       if (buf_copy_len > len) {
01029         buf_copy_len = len;
01030       }
01031       /* copy the necessary parts of the buffer */
01032       MEMCPY(&((char*)dataptr)[left], &((char*)p->payload)[offset], buf_copy_len);
01033       copied_total += buf_copy_len;
01034       left += buf_copy_len;
01035       len -= buf_copy_len;
01036       offset = 0;
01037     }
01038   }
01039   return copied_total;
01040 }
01041 
01042 #if LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE
01043 /**
01044  * This method modifies a 'pbuf chain', so that its total length is
01045  * smaller than 64K. The remainder of the original pbuf chain is stored
01046  * in *rest.
01047  * This function never creates new pbufs, but splits an existing chain
01048  * in two parts. The tot_len of the modified packet queue will likely be
01049  * smaller than 64K.
01050  * 'packet queues' are not supported by this function.
01051  *
01052  * @param p the pbuf queue to be split
01053  * @param rest pointer to store the remainder (after the first 64K)
01054  */
01055 void pbuf_split_64k(struct pbuf *p, struct pbuf **rest)
01056 {
01057   *rest = NULL;
01058   if ((p != NULL) && (p->next != NULL)) {
01059     u16_t tot_len_front = p->len;
01060     struct pbuf *i = p;
01061     struct pbuf *r = p->next;
01062 
01063     /* continue until the total length (summed up as u16_t) overflows */
01064     while ((r != NULL) && ((u16_t)(tot_len_front + r->len) > tot_len_front)) {
01065       tot_len_front += r->len;
01066       i = r;
01067       r = r->next;
01068     }
01069     /* i now points to last packet of the first segment. Set next
01070        pointer to NULL */
01071     i->next = NULL;
01072 
01073     if (r != NULL) {
01074       /* Update the tot_len field in the first part */
01075       for (i = p; i != NULL; i = i->next) {
01076         i->tot_len -= r->tot_len;
01077         LWIP_ASSERT("tot_len/len mismatch in last pbuf",
01078                     (i->next != NULL) || (i->tot_len == i->len));
01079       }
01080       if (p->flags & PBUF_FLAG_TCP_FIN) {
01081         r->flags |= PBUF_FLAG_TCP_FIN;
01082       }
01083 
01084       /* tot_len field in rest does not need modifications */
01085       /* reference counters do not need modifications */
01086       *rest = r;
01087     }
01088   }
01089 }
01090 #endif /* LWIP_TCP && TCP_QUEUE_OOSEQ && LWIP_WND_SCALE */
01091 
01092 /* Actual implementation of pbuf_skip() but returning const pointer... */
01093 static const struct pbuf*
01094 pbuf_skip_const(const struct pbuf* in, u16_t in_offset, u16_t* out_offset)
01095 {
01096   u16_t offset_left = in_offset;
01097   const struct pbuf* q = in;
01098 
01099   /* get the correct pbuf */
01100   while ((q != NULL) && (q->len <= offset_left)) {
01101     offset_left -= q->len;
01102     q = q->next;
01103   }
01104   if (out_offset != NULL) {
01105     *out_offset = offset_left;
01106   }
01107   return q;
01108 }
01109 
01110 /**
01111  * @ingroup pbuf
01112  * Skip a number of bytes at the start of a pbuf
01113  *
01114  * @param in input pbuf
01115  * @param in_offset offset to skip
01116  * @param out_offset resulting offset in the returned pbuf
01117  * @return the pbuf in the queue where the offset is
01118  */
01119 struct pbuf*
01120 pbuf_skip(struct pbuf* in, u16_t in_offset, u16_t* out_offset)
01121 {
01122   const struct pbuf* out = pbuf_skip_const(in, in_offset, out_offset);
01123   return LWIP_CONST_CAST(struct pbuf*, out);
01124 }
01125 
01126 /**
01127  * @ingroup pbuf
01128  * Copy application supplied data into a pbuf.
01129  * This function can only be used to copy the equivalent of buf->tot_len data.
01130  *
01131  * @param buf pbuf to fill with data
01132  * @param dataptr application supplied data buffer
01133  * @param len length of the application supplied data buffer
01134  *
01135  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
01136  */
01137 err_t
01138 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
01139 {
01140   struct pbuf *p;
01141   u16_t buf_copy_len;
01142   u16_t total_copy_len = len;
01143   u16_t copied_total = 0;
01144 
01145   LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return ERR_ARG;);
01146   LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return ERR_ARG;);
01147   LWIP_ERROR("pbuf_take: buf not large enough", (buf->tot_len >= len), return ERR_MEM;);
01148 
01149   if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
01150     return ERR_ARG;
01151   }
01152 
01153   /* Note some systems use byte copy if dataptr or one of the pbuf payload pointers are unaligned. */
01154   for (p = buf; total_copy_len != 0; p = p->next) {
01155     LWIP_ASSERT("pbuf_take: invalid pbuf", p != NULL);
01156     buf_copy_len = total_copy_len;
01157     if (buf_copy_len > p->len) {
01158       /* this pbuf cannot hold all remaining data */
01159       buf_copy_len = p->len;
01160     }
01161     /* copy the necessary parts of the buffer */
01162     MEMCPY(p->payload, &((const char*)dataptr)[copied_total], buf_copy_len);
01163     total_copy_len -= buf_copy_len;
01164     copied_total += buf_copy_len;
01165   }
01166   LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
01167   return ERR_OK;
01168 }
01169 
01170 /**
01171  * @ingroup pbuf
01172  * Same as pbuf_take() but puts data at an offset
01173  *
01174  * @param buf pbuf to fill with data
01175  * @param dataptr application supplied data buffer
01176  * @param len length of the application supplied data buffer
01177  * @param offset offset in pbuf where to copy dataptr to
01178  *
01179  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
01180  */
01181 err_t
01182 pbuf_take_at(struct pbuf *buf, const void *dataptr, u16_t len, u16_t offset)
01183 {
01184   u16_t target_offset;
01185   struct pbuf* q = pbuf_skip(buf, offset, &target_offset);
01186 
01187   /* return requested data if pbuf is OK */
01188   if ((q != NULL) && (q->tot_len >= target_offset + len)) {
01189     u16_t remaining_len = len;
01190     const u8_t* src_ptr = (const u8_t*)dataptr;
01191     /* copy the part that goes into the first pbuf */
01192     u16_t first_copy_len = LWIP_MIN(q->len - target_offset, len);
01193     MEMCPY(((u8_t*)q->payload) + target_offset, dataptr, first_copy_len);
01194     remaining_len -= first_copy_len;
01195     src_ptr += first_copy_len;
01196     if (remaining_len > 0) {
01197       return pbuf_take(q->next, src_ptr, remaining_len);
01198     }
01199     return ERR_OK;
01200   }
01201   return ERR_MEM;
01202 }
01203 
01204 /**
01205  * @ingroup pbuf
01206  * Creates a single pbuf out of a queue of pbufs.
01207  *
01208  * @remark: Either the source pbuf 'p' is freed by this function or the original
01209  *          pbuf 'p' is returned, therefore the caller has to check the result!
01210  *
01211  * @param p the source pbuf
01212  * @param layer pbuf_layer of the new pbuf
01213  *
01214  * @return a new, single pbuf (p->next is NULL)
01215  *         or the old pbuf if allocation fails
01216  */
01217 struct pbuf*
01218 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
01219 {
01220   struct pbuf *q;
01221   err_t err;
01222   if (p->next == NULL) {
01223     return p;
01224   }
01225   q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
01226   if (q == NULL) {
01227     /* @todo: what do we do now? */
01228     return p;
01229   }
01230   err = pbuf_copy(q, p);
01231   LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */
01232   LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
01233   pbuf_free(p);
01234   return q;
01235 }
01236 
01237 #if LWIP_CHECKSUM_ON_COPY
01238 /**
01239  * Copies data into a single pbuf (*not* into a pbuf queue!) and updates
01240  * the checksum while copying
01241  *
01242  * @param p the pbuf to copy data into
01243  * @param start_offset offset of p->payload where to copy the data to
01244  * @param dataptr data to copy into the pbuf
01245  * @param len length of data to copy into the pbuf
01246  * @param chksum pointer to the checksum which is updated
01247  * @return ERR_OK if successful, another error if the data does not fit
01248  *         within the (first) pbuf (no pbuf queues!)
01249  */
01250 err_t
01251 pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
01252                  u16_t len, u16_t *chksum)
01253 {
01254   u32_t acc;
01255   u16_t copy_chksum;
01256   char *dst_ptr;
01257   LWIP_ASSERT("p != NULL", p != NULL);
01258   LWIP_ASSERT("dataptr != NULL", dataptr != NULL);
01259   LWIP_ASSERT("chksum != NULL", chksum != NULL);
01260   LWIP_ASSERT("len != 0", len != 0);
01261 
01262   if ((start_offset >= p->len) || (start_offset + len > p->len)) {
01263     return ERR_ARG;
01264   }
01265 
01266   dst_ptr = ((char*)p->payload) + start_offset;
01267   copy_chksum = LWIP_CHKSUM_COPY(dst_ptr, dataptr, len);
01268   if ((start_offset & 1) != 0) {
01269     copy_chksum = SWAP_BYTES_IN_WORD(copy_chksum);
01270   }
01271   acc = *chksum;
01272   acc += copy_chksum;
01273   *chksum = FOLD_U32T(acc);
01274   return ERR_OK;
01275 }
01276 #endif /* LWIP_CHECKSUM_ON_COPY */
01277 
01278 /**
01279  * @ingroup pbuf
01280  * Get one byte from the specified position in a pbuf
01281  * WARNING: returns zero for offset >= p->tot_len
01282  *
01283  * @param p pbuf to parse
01284  * @param offset offset into p of the byte to return
01285  * @return byte at an offset into p OR ZERO IF 'offset' >= p->tot_len
01286  */
01287 u8_t
01288 pbuf_get_at(const struct pbuf* p, u16_t offset)
01289 {
01290   int ret = pbuf_try_get_at(p, offset);
01291   if (ret >= 0) {
01292     return (u8_t)ret;
01293   }
01294   return 0;
01295 }
01296 
01297 /**
01298  * @ingroup pbuf
01299  * Get one byte from the specified position in a pbuf
01300  *
01301  * @param p pbuf to parse
01302  * @param offset offset into p of the byte to return
01303  * @return byte at an offset into p [0..0xFF] OR negative if 'offset' >= p->tot_len
01304  */
01305 int
01306 pbuf_try_get_at(const struct pbuf* p, u16_t offset)
01307 {
01308   u16_t q_idx;
01309   const struct pbuf* q = pbuf_skip_const(p, offset, &q_idx);
01310 
01311   /* return requested data if pbuf is OK */
01312   if ((q != NULL) && (q->len > q_idx)) {
01313     return ((u8_t*)q->payload)[q_idx];
01314   }
01315   return -1;
01316 }
01317 
01318 /**
01319  * @ingroup pbuf
01320  * Put one byte to the specified position in a pbuf
01321  * WARNING: silently ignores offset >= p->tot_len
01322  *
01323  * @param p pbuf to fill
01324  * @param offset offset into p of the byte to write
01325  * @param data byte to write at an offset into p
01326  */
01327 void
01328 pbuf_put_at(struct pbuf* p, u16_t offset, u8_t data)
01329 {
01330   u16_t q_idx;
01331   struct pbuf* q = pbuf_skip(p, offset, &q_idx);
01332 
01333   /* write requested data if pbuf is OK */
01334   if ((q != NULL) && (q->len > q_idx)) {
01335     ((u8_t*)q->payload)[q_idx] = data;
01336   }
01337 }
01338 
01339 /**
01340  * @ingroup pbuf
01341  * Compare pbuf contents at specified offset with memory s2, both of length n
01342  *
01343  * @param p pbuf to compare
01344  * @param offset offset into p at which to start comparing
01345  * @param s2 buffer to compare
01346  * @param n length of buffer to compare
01347  * @return zero if equal, nonzero otherwise
01348  *         (0xffff if p is too short, diffoffset+1 otherwise)
01349  */
01350 u16_t
01351 pbuf_memcmp(const struct pbuf* p, u16_t offset, const void* s2, u16_t n)
01352 {
01353   u16_t start = offset;
01354   const struct pbuf* q = p;
01355   u16_t i;
01356  
01357   /* pbuf long enough to perform check? */
01358   if(p->tot_len < (offset + n)) {
01359     return 0xffff;
01360   }
01361  
01362   /* get the correct pbuf from chain. We know it succeeds because of p->tot_len check above. */
01363   while ((q != NULL) && (q->len <= start)) {
01364     start -= q->len;
01365     q = q->next;
01366   }
01367  
01368   /* return requested data if pbuf is OK */
01369   for (i = 0; i < n; i++) {
01370     /* We know pbuf_get_at() succeeds because of p->tot_len check above. */
01371     u8_t a = pbuf_get_at(q, start + i);
01372     u8_t b = ((const u8_t*)s2)[i];
01373     if (a != b) {
01374       return i+1;
01375     }
01376   }
01377   return 0;
01378 }
01379 
01380 /**
01381  * @ingroup pbuf
01382  * Find occurrence of mem (with length mem_len) in pbuf p, starting at offset
01383  * start_offset.
01384  *
01385  * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
01386  *        return value 'not found'
01387  * @param mem search for the contents of this buffer
01388  * @param mem_len length of 'mem'
01389  * @param start_offset offset into p at which to start searching
01390  * @return 0xFFFF if substr was not found in p or the index where it was found
01391  */
01392 u16_t
01393 pbuf_memfind(const struct pbuf* p, const void* mem, u16_t mem_len, u16_t start_offset)
01394 {
01395   u16_t i;
01396   u16_t max = p->tot_len - mem_len;
01397   if (p->tot_len >= mem_len + start_offset) {
01398     for (i = start_offset; i <= max; i++) {
01399       u16_t plus = pbuf_memcmp(p, i, mem, mem_len);
01400       if (plus == 0) {
01401         return i;
01402       }
01403     }
01404   }
01405   return 0xFFFF;
01406 }
01407 
01408 /**
01409  * Find occurrence of substr with length substr_len in pbuf p, start at offset
01410  * start_offset
01411  * WARNING: in contrast to strstr(), this one does not stop at the first \0 in
01412  * the pbuf/source string!
01413  *
01414  * @param p pbuf to search, maximum length is 0xFFFE since 0xFFFF is used as
01415  *        return value 'not found'
01416  * @param substr string to search for in p, maximum length is 0xFFFE
01417  * @return 0xFFFF if substr was not found in p or the index where it was found
01418  */
01419 u16_t
01420 pbuf_strstr(const struct pbuf* p, const char* substr)
01421 {
01422   size_t substr_len;
01423   if ((substr == NULL) || (substr[0] == 0) || (p->tot_len == 0xFFFF)) {
01424     return 0xFFFF;
01425   }
01426   substr_len = strlen(substr);
01427   if (substr_len >= 0xFFFF) {
01428     return 0xFFFF;
01429   }
01430   return pbuf_memfind(p, substr, (u16_t)substr_len, 0);
01431 }