]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/ankh/lib/lwip/contrib/src/core/pbuf.c
7534eeec2aa71fe67a44353546273a41b8ab409d
[l4.git] / l4 / pkg / ankh / lib / lwip / contrib / src / core / pbuf.c
1 /**
2  * @file
3  * Packet buffer management
4  *
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.
9  *
10  * A packet may span over multiple pbufs, chained as a singly linked
11  * list. This is called a "pbuf chain".
12  *
13  * Multiple packets may be queued, also using this singly linked list.
14  * This is called a "packet queue".
15  * 
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.
19  * 
20  * The differences between a pbuf chain and a packet queue are very
21  * precise but subtle. 
22  *
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
26  * are on the queue.
27  *
28  * Therefore, looping through a pbuf of a single packet, has an
29  * loop end condition (tot_len == p->len), NOT (next == NULL).
30  */
31
32 /*
33  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without modification,
37  * are permitted provided that the following conditions are met:
38  *
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.
46  *
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
56  * OF SUCH DAMAGE.
57  *
58  * This file is part of the lwIP TCP/IP stack.
59  *
60  * Author: Adam Dunkels <adam@sics.se>
61  *
62  */
63
64 #include "lwip/opt.h"
65
66 #include "lwip/stats.h"
67 #include "lwip/def.h"
68 #include "lwip/mem.h"
69 #include "lwip/memp.h"
70 #include "lwip/pbuf.h"
71 #include "lwip/sys.h"
72 #include "arch/perf.h"
73 #if TCP_QUEUE_OOSEQ
74 #include "lwip/tcp_impl.h"
75 #endif
76 #if LWIP_CHECKSUM_ON_COPY
77 #include "lwip/inet_chksum.h"
78 #endif
79
80 #include <string.h>
81
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)
86
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 */
94
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;
99 /**
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.
103  *
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.
106  */
107 static void
108 pbuf_free_ooseq(void* arg)
109 {
110   struct tcp_pcb* pcb;
111   SYS_ARCH_DECL_PROTECT(old_level);
112   LWIP_UNUSED_ARG(arg);
113
114   SYS_ARCH_PROTECT(old_level);
115   pbuf_free_ooseq_queued = 0;
116   SYS_ARCH_UNPROTECT(old_level);
117
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);
123         pcb->ooseq = NULL;
124       return;
125     }
126       }
127 }
128
129 /** Queue a call to pbuf_free_ooseq if not already queued. */
130 static void
131 pbuf_pool_is_empty(void)
132 {
133   u8_t queued;
134   SYS_ARCH_DECL_PROTECT(old_level);
135
136   SYS_ARCH_PROTECT(old_level);
137   queued = pbuf_free_ooseq_queued;
138   pbuf_free_ooseq_queued = 1;
139   SYS_ARCH_UNPROTECT(old_level);
140
141   if(!queued) {
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);
147     }
148   }
149 }
150 #endif /* PBUF_POOL_FREE_OOSEQ */
151 #endif /* !LWIP_TCP || !TCP_QUEUE_OOSEQ || NO_SYS */
152
153 /**
154  * Allocates a pbuf of the given type (possibly a chain for PBUF_POOL type).
155  *
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).
159  *
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:
164  *
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().
180  *
181  * @return the allocated pbuf. If multiple pbufs where allocated, this
182  * is the first pbuf of a pbuf chain.
183  */
184 struct pbuf *
185 pbuf_alloc(pbuf_layer layer, u16_t length, pbuf_type type)
186 {
187   struct pbuf *p, *q, *r;
188   u16_t offset;
189   s32_t rem_len; /* remaining length */
190   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F")\n", length));
191
192   /* determine header offset */
193   offset = 0;
194   switch (layer) {
195   case PBUF_TRANSPORT:
196     /* add room for transport (often TCP) layer header */
197     offset += PBUF_TRANSPORT_HLEN;
198     /* FALLTHROUGH */
199   case PBUF_IP:
200     /* add room for IP layer header */
201     offset += PBUF_IP_HLEN;
202     /* FALLTHROUGH */
203   case PBUF_LINK:
204     /* add room for link layer header */
205     offset += PBUF_LINK_HLEN;
206     break;
207   case PBUF_RAW:
208     break;
209   default:
210     LWIP_ASSERT("pbuf_alloc: bad pbuf layer", 0);
211     return NULL;
212   }
213
214   switch (type) {
215   case PBUF_POOL:
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));
219     if (p == NULL) {
220       PBUF_POOL_IS_EMPTY();
221       return NULL;
222     }
223     p->type = type;
224     p->next = NULL;
225
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 */
231     p->tot_len = length;
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) */
240     p->ref = 1;
241
242     /* now allocate the tail of the pbuf chain */
243
244     /* remember first pbuf for linkage in next iteration */
245     r = p;
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);
251       if (q == NULL) {
252         PBUF_POOL_IS_EMPTY();
253         /* free chain so far allocated */
254         pbuf_free(p);
255         /* bail out unsuccesfully */
256         return NULL;
257       }
258       q->type = type;
259       q->flags = 0;
260       q->next = NULL;
261       /* make previous pbuf point to this pbuf */
262       r->next = q;
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));
274       q->ref = 1;
275       /* calculate remaining length to be allocated */
276       rem_len -= q->len;
277       /* remember this pbuf for linkage in next iteration */
278       r = q;
279     }
280     /* end of chain */
281     /*r->next = NULL;*/
282
283     break;
284   case PBUF_RAM:
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));
287     if (p == NULL) {
288       return NULL;
289     }
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;
293     p->next = NULL;
294     p->type = type;
295
296     LWIP_ASSERT("pbuf_alloc: pbuf->payload properly aligned",
297            ((mem_ptr_t)p->payload % MEM_ALIGNMENT) == 0);
298     break;
299   /* pbuf references existing (non-volatile static constant) ROM payload? */
300   case PBUF_ROM:
301   /* pbuf references existing (externally allocated) RAM payload? */
302   case PBUF_REF:
303     /* only allocate memory for the pbuf structure */
304     p = (struct pbuf *)memp_malloc(MEMP_PBUF);
305     if (p == NULL) {
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"));
309       return NULL;
310     }
311     /* caller must set this field properly, afterwards */
312     p->payload = NULL;
313     p->len = p->tot_len = length;
314     p->next = NULL;
315     p->type = type;
316     break;
317   default:
318     LWIP_ASSERT("pbuf_alloc: erroneous type", 0);
319     return NULL;
320   }
321   /* set reference count */
322   p->ref = 1;
323   /* set flags */
324   p->flags = 0;
325   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_alloc(length=%"U16_F") == %p\n", length, (void *)p));
326   return p;
327 }
328
329
330 /**
331  * Shrink a pbuf chain to a desired length.
332  *
333  * @param p pbuf to shrink.
334  * @param new_len desired new length of pbuf chain
335  *
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.
339  *
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.
342  *
343  * @note Despite its name, pbuf_realloc cannot grow the size of a pbuf (chain).
344  */
345 void
346 pbuf_realloc(struct pbuf *p, u16_t new_len)
347 {
348   struct pbuf *q;
349   u16_t rem_len; /* remaining length */
350   s32_t grow;
351
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);
357
358   /* desired length larger than current length? */
359   if (new_len >= p->tot_len) {
360     /* enlarging not yet supported */
361     return;
362   }
363
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;
367
368   /* first, step over any pbufs that should remain in the chain */
369   rem_len = new_len;
370   q = p;
371   /* should this pbuf be kept? */
372   while (rem_len > q->len) {
373     /* decrease remaining length by pbuf length */
374     rem_len -= q->len;
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 */
379     q = q->next;
380     LWIP_ASSERT("pbuf_realloc: q != NULL", q != NULL);
381   }
382   /* we have now reached the new last pbuf (in q) */
383   /* rem_len == desired length for pbuf q */
384
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);
391   }
392   /* adjust length fields for new last pbuf */
393   q->len = rem_len;
394   q->tot_len = q->len;
395
396   /* any remaining pbufs in chain? */
397   if (q->next != NULL) {
398     /* free remaining pbufs in chain */
399     pbuf_free(q->next);
400   }
401   /* q is last packet in chain */
402   q->next = NULL;
403
404 }
405
406 /**
407  * Adjusts the payload pointer to hide or reveal headers in the payload.
408  *
409  * Adjusts the ->payload pointer so that space for a header
410  * (dis)appears in the pbuf payload.
411  *
412  * The ->payload, ->tot_len and ->len fields are adjusted.
413  *
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.
419  *
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.
424  *
425  */
426 u8_t
427 pbuf_header(struct pbuf *p, s16_t header_size_increment)
428 {
429   u16_t type;
430   void *payload;
431   u16_t increment_magnitude;
432
433   LWIP_ASSERT("p != NULL", p != NULL);
434   if ((header_size_increment == 0) || (p == NULL)) {
435     return 0;
436   }
437  
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;);
442   } else {
443     increment_magnitude = header_size_increment;
444 #if 0
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);
453 #endif
454   }
455
456   type = p->type;
457   /* remember current payload pointer */
458   payload = p->payload;
459
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 */
472       return 1;
473     }
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;
480     } else {
481       /* cannot expand payload to front (yet!)
482        * bail out unsuccesfully */
483       return 1;
484     }
485   } else {
486     /* Unknown type */
487     LWIP_ASSERT("bad pbuf type", 0);
488     return 1;
489   }
490   /* modify pbuf length fields */
491   p->len += header_size_increment;
492   p->tot_len += header_size_increment;
493
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));
496
497   return 0;
498 }
499
500 /**
501  * Dereference a pbuf chain or queue and deallocate any no-longer-used
502  * pbufs at the head of this chain or queue.
503  *
504  * Decrements the pbuf reference count. If it reaches zero, the pbuf is
505  * deallocated.
506  *
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
510  * chain is free'd.
511  *
512  * @param p The pbuf (chain) to be dereferenced.
513  *
514  * @return the number of pbufs that were de-allocated
515  * from the head of the chain.
516  *
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).
520  *
521  * @internal examples:
522  *
523  * Assuming existing chains a->b->c with the following reference
524  * counts, calling pbuf_free(a) results in:
525  * 
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 .......
531  *
532  */
533 u8_t
534 pbuf_free(struct pbuf *p)
535 {
536   u16_t type;
537   struct pbuf *q;
538   u8_t count;
539
540   if (p == NULL) {
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"));
545     return 0;
546   }
547   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free(%p)\n", (void *)p));
548
549   PERF_START;
550
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);
554
555   count = 0;
556   /* de-allocate all consecutive pbufs from the head of the chain that
557    * obtain a zero reference count after decrementing*/
558   while (p != NULL) {
559     u16_t ref;
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) */
568     ref = --(p->ref);
569     SYS_ARCH_UNPROTECT(old_level);
570     /* this pbuf is no longer referenced to? */
571     if (ref == 0) {
572       /* remember next pbuf in chain for next iteration */
573       q = p->next;
574       LWIP_DEBUGF( PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_free: deallocating %p\n", (void *)p));
575       type = p->type;
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 */
583       } else {
584         mem_free(p);
585       }
586       count++;
587       /* proceed to next pbuf */
588       p = q;
589     /* p->ref > 0, this pbuf is still referenced to */
590     /* (and so the remaining pbufs in chain as well) */
591     } else {
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 */
594       p = NULL;
595     }
596   }
597   PERF_STOP("pbuf_free");
598   /* return number of de-allocated pbufs */
599   return count;
600 }
601
602 /**
603  * Count number of pbufs in a chain
604  *
605  * @param p first pbuf of chain
606  * @return the number of pbufs in a chain
607  */
608
609 u8_t
610 pbuf_clen(struct pbuf *p)
611 {
612   u8_t len;
613
614   len = 0;
615   while (p != NULL) {
616     ++len;
617     p = p->next;
618   }
619   return len;
620 }
621
622 /**
623  * Increment the reference count of the pbuf.
624  *
625  * @param p pbuf to increase reference counter of
626  *
627  */
628 void
629 pbuf_ref(struct pbuf *p)
630 {
631   SYS_ARCH_DECL_PROTECT(old_level);
632   /* pbuf given? */
633   if (p != NULL) {
634     SYS_ARCH_PROTECT(old_level);
635     ++(p->ref);
636     SYS_ARCH_UNPROTECT(old_level);
637   }
638 }
639
640 /**
641  * Concatenate two pbufs (each may be a pbuf chain) and take over
642  * the caller's reference of the tail pbuf.
643  * 
644  * @note The caller MAY NOT reference the tail pbuf afterwards.
645  * Use pbuf_chain() for that purpose.
646  * 
647  * @see pbuf_chain()
648  */
649
650 void
651 pbuf_cat(struct pbuf *h, struct pbuf *t)
652 {
653   struct pbuf *p;
654
655   LWIP_ERROR("(h != NULL) && (t != NULL) (programmer violates API)",
656              ((h != NULL) && (t != NULL)), return;);
657
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;
662   }
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) */
669   p->next = 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.
672    */
673 }
674
675 /**
676  * Chain two pbufs (or pbuf chains) together.
677  * 
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.
680  * 
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.
685  *
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.
689  *
690  */
691 void
692 pbuf_chain(struct pbuf *h, struct pbuf *t)
693 {
694   pbuf_cat(h, t);
695   /* t is now referenced by h */
696   pbuf_ref(t);
697   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_chain: %p references %p\n", (void *)h, (void *)t));
698 }
699
700 /**
701  * Dechains the first pbuf from its succeeding pbufs in the chain.
702  *
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.
707  */
708 struct pbuf *
709 pbuf_dechain(struct pbuf *p)
710 {
711   struct pbuf *q;
712   u8_t tail_gone = 1;
713   /* tail */
714   q = p->next;
715   /* pbuf has successor in chain? */
716   if (q != NULL) {
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 */
722     p->next = NULL;
723     /* total length of pbuf p is its own length only */
724     p->tot_len = p->len;
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);
728     if (tail_gone > 0) {
729       LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE,
730                   ("pbuf_dechain: deallocated %p (as it is no longer referenced)\n", (void *)q));
731     }
732     /* return remaining tail or NULL if deallocated */
733   }
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);
737 }
738
739 /**
740  *
741  * Create PBUF_RAM copies of pbufs.
742  *
743  * Used to queue packets on behalf of the lwIP stack, such as
744  * ARP based queueing.
745  *
746  * @note You MUST explicitly use p = pbuf_take(p);
747  *
748  * @note Only one packet is copied, no packet queue!
749  *
750  * @param p_to pbuf destination of the copy
751  * @param p_from pbuf source of the copy
752  *
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
756  */
757 err_t
758 pbuf_copy(struct pbuf *p_to, struct pbuf *p_from)
759 {
760   u16_t offset_to=0, offset_from=0, len;
761
762   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy(%p, %p)\n",
763     (void*)p_to, (void*)p_from));
764
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;);
768
769   /* iterate through pbuf chain */
770   do
771   {
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;
777     } else {
778       /* current p_from does not fit into current p_to */
779       len = p_to->len - offset_to;
780     }
781     MEMCPY((u8_t*)p_to->payload + offset_to, (u8_t*)p_from->payload + offset_from, len);
782     offset_to += len;
783     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) */
787       offset_to = 0;
788       p_to = p_to->next;
789     }
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) */
793       offset_from = 0;
794       p_from = p_from->next;
795     }
796
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;);
801     }
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;);
806     }
807   } while (p_from);
808   LWIP_DEBUGF(PBUF_DEBUG | LWIP_DBG_TRACE, ("pbuf_copy: end of chain reached.\n"));
809   return ERR_OK;
810 }
811
812 /**
813  * Copy (part of) the contents of a packet buffer
814  * to an application supplied buffer.
815  *
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
822  */
823 u16_t
824 pbuf_copy_partial(struct pbuf *buf, void *dataptr, u16_t len, u16_t offset)
825 {
826   struct pbuf *p;
827   u16_t left;
828   u16_t buf_copy_len;
829   u16_t copied_total = 0;
830
831   LWIP_ERROR("pbuf_copy_partial: invalid buf", (buf != NULL), return 0;);
832   LWIP_ERROR("pbuf_copy_partial: invalid dataptr", (dataptr != NULL), return 0;);
833
834   left = 0;
835
836   if((buf == NULL) || (dataptr == NULL)) {
837     return 0;
838   }
839
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 */
844       offset -= p->len;
845     } else {
846       /* copy from this buffer. maybe only partially. */
847       buf_copy_len = p->len - offset;
848       if (buf_copy_len > len)
849           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;
854       len -= buf_copy_len;
855       offset = 0;
856     }
857   }
858   return copied_total;
859 }
860
861 /**
862  * Copy application supplied data into a pbuf.
863  * This function can only be used to copy the equivalent of buf->tot_len data.
864  *
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
868  *
869  * @return ERR_OK if successful, ERR_MEM if the pbuf is not big enough
870  */
871 err_t
872 pbuf_take(struct pbuf *buf, const void *dataptr, u16_t len)
873 {
874   struct pbuf *p;
875   u16_t buf_copy_len;
876   u16_t total_copy_len = len;
877   u16_t copied_total = 0;
878
879   LWIP_ERROR("pbuf_take: invalid buf", (buf != NULL), return 0;);
880   LWIP_ERROR("pbuf_take: invalid dataptr", (dataptr != NULL), return 0;);
881
882   if ((buf == NULL) || (dataptr == NULL) || (buf->tot_len < len)) {
883     return ERR_ARG;
884   }
885
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;
893     }
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;
898   }
899   LWIP_ASSERT("did not copy all data", total_copy_len == 0 && copied_total == len);
900   return ERR_OK;
901 }
902
903 /**
904  * Creates a single pbuf out of a queue of pbufs.
905  *
906  * @remark: The source pbuf 'p' is not freed by this function because that can
907  *          be illegal in some places!
908  *
909  * @param p the source pbuf
910  * @param layer pbuf_layer of the new pbuf
911  *
912  * @return a new, single pbuf (p->next is NULL)
913  *         or the old pbuf if allocation fails
914  */
915 struct pbuf*
916 pbuf_coalesce(struct pbuf *p, pbuf_layer layer)
917 {
918   struct pbuf *q;
919   err_t err;
920   if (p->next == NULL) {
921     return p;
922   }
923   q = pbuf_alloc(layer, p->tot_len, PBUF_RAM);
924   if (q == NULL) {
925     /* @todo: what do we do now? */
926     return p;
927   }
928   err = pbuf_copy(q, p);
929   LWIP_ASSERT("pbuf_copy failed", err == ERR_OK);
930   pbuf_free(p);
931   return q;
932 }
933
934 #if LWIP_CHECKSUM_ON_COPY
935 /**
936  * Copies data into a single pbuf (*not* into a pbuf queue!) and updates
937  * the checksum while copying
938  *
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!)
946  */
947 err_t
948 pbuf_fill_chksum(struct pbuf *p, u16_t start_offset, const void *dataptr,
949                  u16_t len, u16_t *chksum)
950 {
951   u32_t acc;
952   u16_t copy_chksum;
953   char *dst_ptr;
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);
958
959   if ((start_offset >= p->len) || (start_offset + len > p->len)) {
960     return ERR_ARG;
961   }
962
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);
967   }
968   acc = *chksum;
969   acc += copy_chksum;
970   *chksum = FOLD_U32T(acc);
971   return ERR_OK;
972 }
973 #endif /* LWIP_CHECKSUM_ON_COPY */