net : optimize skb_release_data()
[firefly-linux-kernel-4.4.55.git] / net / core / skbuff.c
1 /*
2  *      Routines having to do with the 'struct sk_buff' memory handlers.
3  *
4  *      Authors:        Alan Cox <alan@lxorguk.ukuu.org.uk>
5  *                      Florian La Roche <rzsfl@rz.uni-sb.de>
6  *
7  *      Fixes:
8  *              Alan Cox        :       Fixed the worst of the load
9  *                                      balancer bugs.
10  *              Dave Platt      :       Interrupt stacking fix.
11  *      Richard Kooijman        :       Timestamp fixes.
12  *              Alan Cox        :       Changed buffer format.
13  *              Alan Cox        :       destructor hook for AF_UNIX etc.
14  *              Linus Torvalds  :       Better skb_clone.
15  *              Alan Cox        :       Added skb_copy.
16  *              Alan Cox        :       Added all the changed routines Linus
17  *                                      only put in the headers
18  *              Ray VanTassle   :       Fixed --skb->lock in free
19  *              Alan Cox        :       skb_copy copy arp field
20  *              Andi Kleen      :       slabified it.
21  *              Robert Olsson   :       Removed skb_head_pool
22  *
23  *      NOTE:
24  *              The __skb_ routines should be called with interrupts
25  *      disabled, or you better be *real* sure that the operation is atomic
26  *      with respect to whatever list is being frobbed (e.g. via lock_sock()
27  *      or via disabling bottom half handlers, etc).
28  *
29  *      This program is free software; you can redistribute it and/or
30  *      modify it under the terms of the GNU General Public License
31  *      as published by the Free Software Foundation; either version
32  *      2 of the License, or (at your option) any later version.
33  */
34
35 /*
36  *      The functions in this file will not compile correctly with gcc 2.4.x
37  */
38
39 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
40
41 #include <linux/module.h>
42 #include <linux/types.h>
43 #include <linux/kernel.h>
44 #include <linux/kmemcheck.h>
45 #include <linux/mm.h>
46 #include <linux/interrupt.h>
47 #include <linux/in.h>
48 #include <linux/inet.h>
49 #include <linux/slab.h>
50 #include <linux/tcp.h>
51 #include <linux/udp.h>
52 #include <linux/netdevice.h>
53 #ifdef CONFIG_NET_CLS_ACT
54 #include <net/pkt_sched.h>
55 #endif
56 #include <linux/string.h>
57 #include <linux/skbuff.h>
58 #include <linux/splice.h>
59 #include <linux/cache.h>
60 #include <linux/rtnetlink.h>
61 #include <linux/init.h>
62 #include <linux/scatterlist.h>
63 #include <linux/errqueue.h>
64 #include <linux/prefetch.h>
65 #include <linux/if_vlan.h>
66
67 #include <net/protocol.h>
68 #include <net/dst.h>
69 #include <net/sock.h>
70 #include <net/checksum.h>
71 #include <net/ip6_checksum.h>
72 #include <net/xfrm.h>
73
74 #include <asm/uaccess.h>
75 #include <trace/events/skb.h>
76 #include <linux/highmem.h>
77
78 struct kmem_cache *skbuff_head_cache __read_mostly;
79 static struct kmem_cache *skbuff_fclone_cache __read_mostly;
80
81 /**
82  *      skb_panic - private function for out-of-line support
83  *      @skb:   buffer
84  *      @sz:    size
85  *      @addr:  address
86  *      @msg:   skb_over_panic or skb_under_panic
87  *
88  *      Out-of-line support for skb_put() and skb_push().
89  *      Called via the wrapper skb_over_panic() or skb_under_panic().
90  *      Keep out of line to prevent kernel bloat.
91  *      __builtin_return_address is not used because it is not always reliable.
92  */
93 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
94                       const char msg[])
95 {
96         pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n",
97                  msg, addr, skb->len, sz, skb->head, skb->data,
98                  (unsigned long)skb->tail, (unsigned long)skb->end,
99                  skb->dev ? skb->dev->name : "<NULL>");
100         BUG();
101 }
102
103 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
104 {
105         skb_panic(skb, sz, addr, __func__);
106 }
107
108 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
109 {
110         skb_panic(skb, sz, addr, __func__);
111 }
112
113 /*
114  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
115  * the caller if emergency pfmemalloc reserves are being used. If it is and
116  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
117  * may be used. Otherwise, the packet data may be discarded until enough
118  * memory is free
119  */
120 #define kmalloc_reserve(size, gfp, node, pfmemalloc) \
121          __kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc)
122
123 static void *__kmalloc_reserve(size_t size, gfp_t flags, int node,
124                                unsigned long ip, bool *pfmemalloc)
125 {
126         void *obj;
127         bool ret_pfmemalloc = false;
128
129         /*
130          * Try a regular allocation, when that fails and we're not entitled
131          * to the reserves, fail.
132          */
133         obj = kmalloc_node_track_caller(size,
134                                         flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
135                                         node);
136         if (obj || !(gfp_pfmemalloc_allowed(flags)))
137                 goto out;
138
139         /* Try again but now we are using pfmemalloc reserves */
140         ret_pfmemalloc = true;
141         obj = kmalloc_node_track_caller(size, flags, node);
142
143 out:
144         if (pfmemalloc)
145                 *pfmemalloc = ret_pfmemalloc;
146
147         return obj;
148 }
149
150 /*      Allocate a new skbuff. We do this ourselves so we can fill in a few
151  *      'private' fields and also do memory statistics to find all the
152  *      [BEEP] leaks.
153  *
154  */
155
156 struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node)
157 {
158         struct sk_buff *skb;
159
160         /* Get the HEAD */
161         skb = kmem_cache_alloc_node(skbuff_head_cache,
162                                     gfp_mask & ~__GFP_DMA, node);
163         if (!skb)
164                 goto out;
165
166         /*
167          * Only clear those fields we need to clear, not those that we will
168          * actually initialise below. Hence, don't put any more fields after
169          * the tail pointer in struct sk_buff!
170          */
171         memset(skb, 0, offsetof(struct sk_buff, tail));
172         skb->head = NULL;
173         skb->truesize = sizeof(struct sk_buff);
174         atomic_set(&skb->users, 1);
175
176         skb->mac_header = (typeof(skb->mac_header))~0U;
177 out:
178         return skb;
179 }
180
181 /**
182  *      __alloc_skb     -       allocate a network buffer
183  *      @size: size to allocate
184  *      @gfp_mask: allocation mask
185  *      @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
186  *              instead of head cache and allocate a cloned (child) skb.
187  *              If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
188  *              allocations in case the data is required for writeback
189  *      @node: numa node to allocate memory on
190  *
191  *      Allocate a new &sk_buff. The returned buffer has no headroom and a
192  *      tail room of at least size bytes. The object has a reference count
193  *      of one. The return is the buffer. On a failure the return is %NULL.
194  *
195  *      Buffers may only be allocated from interrupts using a @gfp_mask of
196  *      %GFP_ATOMIC.
197  */
198 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
199                             int flags, int node)
200 {
201         struct kmem_cache *cache;
202         struct skb_shared_info *shinfo;
203         struct sk_buff *skb;
204         u8 *data;
205         bool pfmemalloc;
206
207         cache = (flags & SKB_ALLOC_FCLONE)
208                 ? skbuff_fclone_cache : skbuff_head_cache;
209
210         if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
211                 gfp_mask |= __GFP_MEMALLOC;
212
213         /* Get the HEAD */
214         skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node);
215         if (!skb)
216                 goto out;
217         prefetchw(skb);
218
219         /* We do our best to align skb_shared_info on a separate cache
220          * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
221          * aligned memory blocks, unless SLUB/SLAB debug is enabled.
222          * Both skb->head and skb_shared_info are cache line aligned.
223          */
224         size = SKB_DATA_ALIGN(size);
225         size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
226         data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
227         if (!data)
228                 goto nodata;
229         /* kmalloc(size) might give us more room than requested.
230          * Put skb_shared_info exactly at the end of allocated zone,
231          * to allow max possible filling before reallocation.
232          */
233         size = SKB_WITH_OVERHEAD(ksize(data));
234         prefetchw(data + size);
235
236         /*
237          * Only clear those fields we need to clear, not those that we will
238          * actually initialise below. Hence, don't put any more fields after
239          * the tail pointer in struct sk_buff!
240          */
241         memset(skb, 0, offsetof(struct sk_buff, tail));
242         /* Account for allocated memory : skb + skb->head */
243         skb->truesize = SKB_TRUESIZE(size);
244         skb->pfmemalloc = pfmemalloc;
245         atomic_set(&skb->users, 1);
246         skb->head = data;
247         skb->data = data;
248         skb_reset_tail_pointer(skb);
249         skb->end = skb->tail + size;
250         skb->mac_header = (typeof(skb->mac_header))~0U;
251         skb->transport_header = (typeof(skb->transport_header))~0U;
252
253         /* make sure we initialize shinfo sequentially */
254         shinfo = skb_shinfo(skb);
255         memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
256         atomic_set(&shinfo->dataref, 1);
257         kmemcheck_annotate_variable(shinfo->destructor_arg);
258
259         if (flags & SKB_ALLOC_FCLONE) {
260                 struct sk_buff *child = skb + 1;
261                 atomic_t *fclone_ref = (atomic_t *) (child + 1);
262
263                 kmemcheck_annotate_bitfield(child, flags1);
264                 kmemcheck_annotate_bitfield(child, flags2);
265                 skb->fclone = SKB_FCLONE_ORIG;
266                 atomic_set(fclone_ref, 1);
267
268                 child->fclone = SKB_FCLONE_UNAVAILABLE;
269                 child->pfmemalloc = pfmemalloc;
270         }
271 out:
272         return skb;
273 nodata:
274         kmem_cache_free(cache, skb);
275         skb = NULL;
276         goto out;
277 }
278 EXPORT_SYMBOL(__alloc_skb);
279
280 /**
281  * build_skb - build a network buffer
282  * @data: data buffer provided by caller
283  * @frag_size: size of fragment, or 0 if head was kmalloced
284  *
285  * Allocate a new &sk_buff. Caller provides space holding head and
286  * skb_shared_info. @data must have been allocated by kmalloc() only if
287  * @frag_size is 0, otherwise data should come from the page allocator.
288  * The return is the new skb buffer.
289  * On a failure the return is %NULL, and @data is not freed.
290  * Notes :
291  *  Before IO, driver allocates only data buffer where NIC put incoming frame
292  *  Driver should add room at head (NET_SKB_PAD) and
293  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
294  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
295  *  before giving packet to stack.
296  *  RX rings only contains data buffers, not full skbs.
297  */
298 struct sk_buff *build_skb(void *data, unsigned int frag_size)
299 {
300         struct skb_shared_info *shinfo;
301         struct sk_buff *skb;
302         unsigned int size = frag_size ? : ksize(data);
303
304         skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
305         if (!skb)
306                 return NULL;
307
308         size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
309
310         memset(skb, 0, offsetof(struct sk_buff, tail));
311         skb->truesize = SKB_TRUESIZE(size);
312         skb->head_frag = frag_size != 0;
313         atomic_set(&skb->users, 1);
314         skb->head = data;
315         skb->data = data;
316         skb_reset_tail_pointer(skb);
317         skb->end = skb->tail + size;
318         skb->mac_header = (typeof(skb->mac_header))~0U;
319         skb->transport_header = (typeof(skb->transport_header))~0U;
320
321         /* make sure we initialize shinfo sequentially */
322         shinfo = skb_shinfo(skb);
323         memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
324         atomic_set(&shinfo->dataref, 1);
325         kmemcheck_annotate_variable(shinfo->destructor_arg);
326
327         return skb;
328 }
329 EXPORT_SYMBOL(build_skb);
330
331 struct netdev_alloc_cache {
332         struct page_frag        frag;
333         /* we maintain a pagecount bias, so that we dont dirty cache line
334          * containing page->_count every time we allocate a fragment.
335          */
336         unsigned int            pagecnt_bias;
337 };
338 static DEFINE_PER_CPU(struct netdev_alloc_cache, netdev_alloc_cache);
339
340 static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
341 {
342         struct netdev_alloc_cache *nc;
343         void *data = NULL;
344         int order;
345         unsigned long flags;
346
347         local_irq_save(flags);
348         nc = &__get_cpu_var(netdev_alloc_cache);
349         if (unlikely(!nc->frag.page)) {
350 refill:
351                 for (order = NETDEV_FRAG_PAGE_MAX_ORDER; ;) {
352                         gfp_t gfp = gfp_mask;
353
354                         if (order)
355                                 gfp |= __GFP_COMP | __GFP_NOWARN;
356                         nc->frag.page = alloc_pages(gfp, order);
357                         if (likely(nc->frag.page))
358                                 break;
359                         if (--order < 0)
360                                 goto end;
361                 }
362                 nc->frag.size = PAGE_SIZE << order;
363 recycle:
364                 atomic_set(&nc->frag.page->_count, NETDEV_PAGECNT_MAX_BIAS);
365                 nc->pagecnt_bias = NETDEV_PAGECNT_MAX_BIAS;
366                 nc->frag.offset = 0;
367         }
368
369         if (nc->frag.offset + fragsz > nc->frag.size) {
370                 /* avoid unnecessary locked operations if possible */
371                 if ((atomic_read(&nc->frag.page->_count) == nc->pagecnt_bias) ||
372                     atomic_sub_and_test(nc->pagecnt_bias, &nc->frag.page->_count))
373                         goto recycle;
374                 goto refill;
375         }
376
377         data = page_address(nc->frag.page) + nc->frag.offset;
378         nc->frag.offset += fragsz;
379         nc->pagecnt_bias--;
380 end:
381         local_irq_restore(flags);
382         return data;
383 }
384
385 /**
386  * netdev_alloc_frag - allocate a page fragment
387  * @fragsz: fragment size
388  *
389  * Allocates a frag from a page for receive buffer.
390  * Uses GFP_ATOMIC allocations.
391  */
392 void *netdev_alloc_frag(unsigned int fragsz)
393 {
394         return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
395 }
396 EXPORT_SYMBOL(netdev_alloc_frag);
397
398 /**
399  *      __netdev_alloc_skb - allocate an skbuff for rx on a specific device
400  *      @dev: network device to receive on
401  *      @length: length to allocate
402  *      @gfp_mask: get_free_pages mask, passed to alloc_skb
403  *
404  *      Allocate a new &sk_buff and assign it a usage count of one. The
405  *      buffer has unspecified headroom built in. Users should allocate
406  *      the headroom they think they need without accounting for the
407  *      built in space. The built in space is used for optimisations.
408  *
409  *      %NULL is returned if there is no free memory.
410  */
411 struct sk_buff *__netdev_alloc_skb(struct net_device *dev,
412                                    unsigned int length, gfp_t gfp_mask)
413 {
414         struct sk_buff *skb = NULL;
415         unsigned int fragsz = SKB_DATA_ALIGN(length + NET_SKB_PAD) +
416                               SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
417
418         if (fragsz <= PAGE_SIZE && !(gfp_mask & (__GFP_WAIT | GFP_DMA))) {
419                 void *data;
420
421                 if (sk_memalloc_socks())
422                         gfp_mask |= __GFP_MEMALLOC;
423
424                 data = __netdev_alloc_frag(fragsz, gfp_mask);
425
426                 if (likely(data)) {
427                         skb = build_skb(data, fragsz);
428                         if (unlikely(!skb))
429                                 put_page(virt_to_head_page(data));
430                 }
431         } else {
432                 skb = __alloc_skb(length + NET_SKB_PAD, gfp_mask,
433                                   SKB_ALLOC_RX, NUMA_NO_NODE);
434         }
435         if (likely(skb)) {
436                 skb_reserve(skb, NET_SKB_PAD);
437                 skb->dev = dev;
438         }
439         return skb;
440 }
441 EXPORT_SYMBOL(__netdev_alloc_skb);
442
443 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
444                      int size, unsigned int truesize)
445 {
446         skb_fill_page_desc(skb, i, page, off, size);
447         skb->len += size;
448         skb->data_len += size;
449         skb->truesize += truesize;
450 }
451 EXPORT_SYMBOL(skb_add_rx_frag);
452
453 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
454                           unsigned int truesize)
455 {
456         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
457
458         skb_frag_size_add(frag, size);
459         skb->len += size;
460         skb->data_len += size;
461         skb->truesize += truesize;
462 }
463 EXPORT_SYMBOL(skb_coalesce_rx_frag);
464
465 static void skb_drop_list(struct sk_buff **listp)
466 {
467         kfree_skb_list(*listp);
468         *listp = NULL;
469 }
470
471 static inline void skb_drop_fraglist(struct sk_buff *skb)
472 {
473         skb_drop_list(&skb_shinfo(skb)->frag_list);
474 }
475
476 static void skb_clone_fraglist(struct sk_buff *skb)
477 {
478         struct sk_buff *list;
479
480         skb_walk_frags(skb, list)
481                 skb_get(list);
482 }
483
484 static void skb_free_head(struct sk_buff *skb)
485 {
486         if (skb->head_frag)
487                 put_page(virt_to_head_page(skb->head));
488         else
489                 kfree(skb->head);
490 }
491
492 static void skb_release_data(struct sk_buff *skb)
493 {
494         struct skb_shared_info *shinfo = skb_shinfo(skb);
495         int i;
496
497         if (skb->cloned &&
498             atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
499                               &shinfo->dataref))
500                 return;
501
502         for (i = 0; i < shinfo->nr_frags; i++)
503                 __skb_frag_unref(&shinfo->frags[i]);
504
505         /*
506          * If skb buf is from userspace, we need to notify the caller
507          * the lower device DMA has done;
508          */
509         if (shinfo->tx_flags & SKBTX_DEV_ZEROCOPY) {
510                 struct ubuf_info *uarg;
511
512                 uarg = shinfo->destructor_arg;
513                 if (uarg->callback)
514                         uarg->callback(uarg, true);
515         }
516
517         if (shinfo->frag_list)
518                 kfree_skb_list(shinfo->frag_list);
519
520         skb_free_head(skb);
521 }
522
523 /*
524  *      Free an skbuff by memory without cleaning the state.
525  */
526 static void kfree_skbmem(struct sk_buff *skb)
527 {
528         struct sk_buff *other;
529         atomic_t *fclone_ref;
530
531         switch (skb->fclone) {
532         case SKB_FCLONE_UNAVAILABLE:
533                 kmem_cache_free(skbuff_head_cache, skb);
534                 break;
535
536         case SKB_FCLONE_ORIG:
537                 fclone_ref = (atomic_t *) (skb + 2);
538                 if (atomic_dec_and_test(fclone_ref))
539                         kmem_cache_free(skbuff_fclone_cache, skb);
540                 break;
541
542         case SKB_FCLONE_CLONE:
543                 fclone_ref = (atomic_t *) (skb + 1);
544                 other = skb - 1;
545
546                 /* The clone portion is available for
547                  * fast-cloning again.
548                  */
549                 skb->fclone = SKB_FCLONE_UNAVAILABLE;
550
551                 if (atomic_dec_and_test(fclone_ref))
552                         kmem_cache_free(skbuff_fclone_cache, other);
553                 break;
554         }
555 }
556
557 static void skb_release_head_state(struct sk_buff *skb)
558 {
559         skb_dst_drop(skb);
560 #ifdef CONFIG_XFRM
561         secpath_put(skb->sp);
562 #endif
563         if (skb->destructor) {
564                 WARN_ON(in_irq());
565                 skb->destructor(skb);
566         }
567 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
568         nf_conntrack_put(skb->nfct);
569 #endif
570 #ifdef CONFIG_BRIDGE_NETFILTER
571         nf_bridge_put(skb->nf_bridge);
572 #endif
573 /* XXX: IS this still necessary? - JHS */
574 #ifdef CONFIG_NET_SCHED
575         skb->tc_index = 0;
576 #ifdef CONFIG_NET_CLS_ACT
577         skb->tc_verd = 0;
578 #endif
579 #endif
580 }
581
582 /* Free everything but the sk_buff shell. */
583 static void skb_release_all(struct sk_buff *skb)
584 {
585         skb_release_head_state(skb);
586         if (likely(skb->head))
587                 skb_release_data(skb);
588 }
589
590 /**
591  *      __kfree_skb - private function
592  *      @skb: buffer
593  *
594  *      Free an sk_buff. Release anything attached to the buffer.
595  *      Clean the state. This is an internal helper function. Users should
596  *      always call kfree_skb
597  */
598
599 void __kfree_skb(struct sk_buff *skb)
600 {
601         skb_release_all(skb);
602         kfree_skbmem(skb);
603 }
604 EXPORT_SYMBOL(__kfree_skb);
605
606 /**
607  *      kfree_skb - free an sk_buff
608  *      @skb: buffer to free
609  *
610  *      Drop a reference to the buffer and free it if the usage count has
611  *      hit zero.
612  */
613 void kfree_skb(struct sk_buff *skb)
614 {
615         if (unlikely(!skb))
616                 return;
617         if (likely(atomic_read(&skb->users) == 1))
618                 smp_rmb();
619         else if (likely(!atomic_dec_and_test(&skb->users)))
620                 return;
621         trace_kfree_skb(skb, __builtin_return_address(0));
622         __kfree_skb(skb);
623 }
624 EXPORT_SYMBOL(kfree_skb);
625
626 void kfree_skb_list(struct sk_buff *segs)
627 {
628         while (segs) {
629                 struct sk_buff *next = segs->next;
630
631                 kfree_skb(segs);
632                 segs = next;
633         }
634 }
635 EXPORT_SYMBOL(kfree_skb_list);
636
637 /**
638  *      skb_tx_error - report an sk_buff xmit error
639  *      @skb: buffer that triggered an error
640  *
641  *      Report xmit error if a device callback is tracking this skb.
642  *      skb must be freed afterwards.
643  */
644 void skb_tx_error(struct sk_buff *skb)
645 {
646         if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
647                 struct ubuf_info *uarg;
648
649                 uarg = skb_shinfo(skb)->destructor_arg;
650                 if (uarg->callback)
651                         uarg->callback(uarg, false);
652                 skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
653         }
654 }
655 EXPORT_SYMBOL(skb_tx_error);
656
657 /**
658  *      consume_skb - free an skbuff
659  *      @skb: buffer to free
660  *
661  *      Drop a ref to the buffer and free it if the usage count has hit zero
662  *      Functions identically to kfree_skb, but kfree_skb assumes that the frame
663  *      is being dropped after a failure and notes that
664  */
665 void consume_skb(struct sk_buff *skb)
666 {
667         if (unlikely(!skb))
668                 return;
669         if (likely(atomic_read(&skb->users) == 1))
670                 smp_rmb();
671         else if (likely(!atomic_dec_and_test(&skb->users)))
672                 return;
673         trace_consume_skb(skb);
674         __kfree_skb(skb);
675 }
676 EXPORT_SYMBOL(consume_skb);
677
678 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
679 {
680         new->tstamp             = old->tstamp;
681         new->dev                = old->dev;
682         new->transport_header   = old->transport_header;
683         new->network_header     = old->network_header;
684         new->mac_header         = old->mac_header;
685         new->inner_protocol     = old->inner_protocol;
686         new->inner_transport_header = old->inner_transport_header;
687         new->inner_network_header = old->inner_network_header;
688         new->inner_mac_header = old->inner_mac_header;
689         skb_dst_copy(new, old);
690         skb_copy_hash(new, old);
691         new->ooo_okay           = old->ooo_okay;
692         new->no_fcs             = old->no_fcs;
693         new->encapsulation      = old->encapsulation;
694         new->encap_hdr_csum     = old->encap_hdr_csum;
695         new->csum_valid         = old->csum_valid;
696         new->csum_complete_sw   = old->csum_complete_sw;
697 #ifdef CONFIG_XFRM
698         new->sp                 = secpath_get(old->sp);
699 #endif
700         memcpy(new->cb, old->cb, sizeof(old->cb));
701         new->csum               = old->csum;
702         new->ignore_df          = old->ignore_df;
703         new->pkt_type           = old->pkt_type;
704         new->ip_summed          = old->ip_summed;
705         skb_copy_queue_mapping(new, old);
706         new->priority           = old->priority;
707 #if IS_ENABLED(CONFIG_IP_VS)
708         new->ipvs_property      = old->ipvs_property;
709 #endif
710         new->pfmemalloc         = old->pfmemalloc;
711         new->protocol           = old->protocol;
712         new->mark               = old->mark;
713         new->skb_iif            = old->skb_iif;
714         __nf_copy(new, old);
715 #ifdef CONFIG_NET_SCHED
716         new->tc_index           = old->tc_index;
717 #ifdef CONFIG_NET_CLS_ACT
718         new->tc_verd            = old->tc_verd;
719 #endif
720 #endif
721         new->vlan_proto         = old->vlan_proto;
722         new->vlan_tci           = old->vlan_tci;
723
724         skb_copy_secmark(new, old);
725
726 #ifdef CONFIG_NET_RX_BUSY_POLL
727         new->napi_id    = old->napi_id;
728 #endif
729 }
730
731 /*
732  * You should not add any new code to this function.  Add it to
733  * __copy_skb_header above instead.
734  */
735 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
736 {
737 #define C(x) n->x = skb->x
738
739         n->next = n->prev = NULL;
740         n->sk = NULL;
741         __copy_skb_header(n, skb);
742
743         C(len);
744         C(data_len);
745         C(mac_len);
746         n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
747         n->cloned = 1;
748         n->nohdr = 0;
749         n->destructor = NULL;
750         C(tail);
751         C(end);
752         C(head);
753         C(head_frag);
754         C(data);
755         C(truesize);
756         atomic_set(&n->users, 1);
757
758         atomic_inc(&(skb_shinfo(skb)->dataref));
759         skb->cloned = 1;
760
761         return n;
762 #undef C
763 }
764
765 /**
766  *      skb_morph       -       morph one skb into another
767  *      @dst: the skb to receive the contents
768  *      @src: the skb to supply the contents
769  *
770  *      This is identical to skb_clone except that the target skb is
771  *      supplied by the user.
772  *
773  *      The target skb is returned upon exit.
774  */
775 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
776 {
777         skb_release_all(dst);
778         return __skb_clone(dst, src);
779 }
780 EXPORT_SYMBOL_GPL(skb_morph);
781
782 /**
783  *      skb_copy_ubufs  -       copy userspace skb frags buffers to kernel
784  *      @skb: the skb to modify
785  *      @gfp_mask: allocation priority
786  *
787  *      This must be called on SKBTX_DEV_ZEROCOPY skb.
788  *      It will copy all frags into kernel and drop the reference
789  *      to userspace pages.
790  *
791  *      If this function is called from an interrupt gfp_mask() must be
792  *      %GFP_ATOMIC.
793  *
794  *      Returns 0 on success or a negative error code on failure
795  *      to allocate kernel memory to copy to.
796  */
797 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
798 {
799         int i;
800         int num_frags = skb_shinfo(skb)->nr_frags;
801         struct page *page, *head = NULL;
802         struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg;
803
804         for (i = 0; i < num_frags; i++) {
805                 u8 *vaddr;
806                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
807
808                 page = alloc_page(gfp_mask);
809                 if (!page) {
810                         while (head) {
811                                 struct page *next = (struct page *)page_private(head);
812                                 put_page(head);
813                                 head = next;
814                         }
815                         return -ENOMEM;
816                 }
817                 vaddr = kmap_atomic(skb_frag_page(f));
818                 memcpy(page_address(page),
819                        vaddr + f->page_offset, skb_frag_size(f));
820                 kunmap_atomic(vaddr);
821                 set_page_private(page, (unsigned long)head);
822                 head = page;
823         }
824
825         /* skb frags release userspace buffers */
826         for (i = 0; i < num_frags; i++)
827                 skb_frag_unref(skb, i);
828
829         uarg->callback(uarg, false);
830
831         /* skb frags point to kernel buffers */
832         for (i = num_frags - 1; i >= 0; i--) {
833                 __skb_fill_page_desc(skb, i, head, 0,
834                                      skb_shinfo(skb)->frags[i].size);
835                 head = (struct page *)page_private(head);
836         }
837
838         skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
839         return 0;
840 }
841 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
842
843 /**
844  *      skb_clone       -       duplicate an sk_buff
845  *      @skb: buffer to clone
846  *      @gfp_mask: allocation priority
847  *
848  *      Duplicate an &sk_buff. The new one is not owned by a socket. Both
849  *      copies share the same packet data but not structure. The new
850  *      buffer has a reference count of 1. If the allocation fails the
851  *      function returns %NULL otherwise the new buffer is returned.
852  *
853  *      If this function is called from an interrupt gfp_mask() must be
854  *      %GFP_ATOMIC.
855  */
856
857 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
858 {
859         struct sk_buff *n;
860
861         if (skb_orphan_frags(skb, gfp_mask))
862                 return NULL;
863
864         n = skb + 1;
865         if (skb->fclone == SKB_FCLONE_ORIG &&
866             n->fclone == SKB_FCLONE_UNAVAILABLE) {
867                 atomic_t *fclone_ref = (atomic_t *) (n + 1);
868                 n->fclone = SKB_FCLONE_CLONE;
869                 atomic_inc(fclone_ref);
870         } else {
871                 if (skb_pfmemalloc(skb))
872                         gfp_mask |= __GFP_MEMALLOC;
873
874                 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
875                 if (!n)
876                         return NULL;
877
878                 kmemcheck_annotate_bitfield(n, flags1);
879                 kmemcheck_annotate_bitfield(n, flags2);
880                 n->fclone = SKB_FCLONE_UNAVAILABLE;
881         }
882
883         return __skb_clone(n, skb);
884 }
885 EXPORT_SYMBOL(skb_clone);
886
887 static void skb_headers_offset_update(struct sk_buff *skb, int off)
888 {
889         /* Only adjust this if it actually is csum_start rather than csum */
890         if (skb->ip_summed == CHECKSUM_PARTIAL)
891                 skb->csum_start += off;
892         /* {transport,network,mac}_header and tail are relative to skb->head */
893         skb->transport_header += off;
894         skb->network_header   += off;
895         if (skb_mac_header_was_set(skb))
896                 skb->mac_header += off;
897         skb->inner_transport_header += off;
898         skb->inner_network_header += off;
899         skb->inner_mac_header += off;
900 }
901
902 static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
903 {
904         __copy_skb_header(new, old);
905
906         skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
907         skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
908         skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
909 }
910
911 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
912 {
913         if (skb_pfmemalloc(skb))
914                 return SKB_ALLOC_RX;
915         return 0;
916 }
917
918 /**
919  *      skb_copy        -       create private copy of an sk_buff
920  *      @skb: buffer to copy
921  *      @gfp_mask: allocation priority
922  *
923  *      Make a copy of both an &sk_buff and its data. This is used when the
924  *      caller wishes to modify the data and needs a private copy of the
925  *      data to alter. Returns %NULL on failure or the pointer to the buffer
926  *      on success. The returned buffer has a reference count of 1.
927  *
928  *      As by-product this function converts non-linear &sk_buff to linear
929  *      one, so that &sk_buff becomes completely private and caller is allowed
930  *      to modify all the data of returned buffer. This means that this
931  *      function is not recommended for use in circumstances when only
932  *      header is going to be modified. Use pskb_copy() instead.
933  */
934
935 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
936 {
937         int headerlen = skb_headroom(skb);
938         unsigned int size = skb_end_offset(skb) + skb->data_len;
939         struct sk_buff *n = __alloc_skb(size, gfp_mask,
940                                         skb_alloc_rx_flag(skb), NUMA_NO_NODE);
941
942         if (!n)
943                 return NULL;
944
945         /* Set the data pointer */
946         skb_reserve(n, headerlen);
947         /* Set the tail pointer and length */
948         skb_put(n, skb->len);
949
950         if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len))
951                 BUG();
952
953         copy_skb_header(n, skb);
954         return n;
955 }
956 EXPORT_SYMBOL(skb_copy);
957
958 /**
959  *      __pskb_copy_fclone      -  create copy of an sk_buff with private head.
960  *      @skb: buffer to copy
961  *      @headroom: headroom of new skb
962  *      @gfp_mask: allocation priority
963  *      @fclone: if true allocate the copy of the skb from the fclone
964  *      cache instead of the head cache; it is recommended to set this
965  *      to true for the cases where the copy will likely be cloned
966  *
967  *      Make a copy of both an &sk_buff and part of its data, located
968  *      in header. Fragmented data remain shared. This is used when
969  *      the caller wishes to modify only header of &sk_buff and needs
970  *      private copy of the header to alter. Returns %NULL on failure
971  *      or the pointer to the buffer on success.
972  *      The returned buffer has a reference count of 1.
973  */
974
975 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
976                                    gfp_t gfp_mask, bool fclone)
977 {
978         unsigned int size = skb_headlen(skb) + headroom;
979         int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
980         struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
981
982         if (!n)
983                 goto out;
984
985         /* Set the data pointer */
986         skb_reserve(n, headroom);
987         /* Set the tail pointer and length */
988         skb_put(n, skb_headlen(skb));
989         /* Copy the bytes */
990         skb_copy_from_linear_data(skb, n->data, n->len);
991
992         n->truesize += skb->data_len;
993         n->data_len  = skb->data_len;
994         n->len       = skb->len;
995
996         if (skb_shinfo(skb)->nr_frags) {
997                 int i;
998
999                 if (skb_orphan_frags(skb, gfp_mask)) {
1000                         kfree_skb(n);
1001                         n = NULL;
1002                         goto out;
1003                 }
1004                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1005                         skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1006                         skb_frag_ref(skb, i);
1007                 }
1008                 skb_shinfo(n)->nr_frags = i;
1009         }
1010
1011         if (skb_has_frag_list(skb)) {
1012                 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1013                 skb_clone_fraglist(n);
1014         }
1015
1016         copy_skb_header(n, skb);
1017 out:
1018         return n;
1019 }
1020 EXPORT_SYMBOL(__pskb_copy_fclone);
1021
1022 /**
1023  *      pskb_expand_head - reallocate header of &sk_buff
1024  *      @skb: buffer to reallocate
1025  *      @nhead: room to add at head
1026  *      @ntail: room to add at tail
1027  *      @gfp_mask: allocation priority
1028  *
1029  *      Expands (or creates identical copy, if @nhead and @ntail are zero)
1030  *      header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1031  *      reference count of 1. Returns zero in the case of success or error,
1032  *      if expansion failed. In the last case, &sk_buff is not changed.
1033  *
1034  *      All the pointers pointing into skb header may change and must be
1035  *      reloaded after call to this function.
1036  */
1037
1038 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1039                      gfp_t gfp_mask)
1040 {
1041         int i;
1042         u8 *data;
1043         int size = nhead + skb_end_offset(skb) + ntail;
1044         long off;
1045
1046         BUG_ON(nhead < 0);
1047
1048         if (skb_shared(skb))
1049                 BUG();
1050
1051         size = SKB_DATA_ALIGN(size);
1052
1053         if (skb_pfmemalloc(skb))
1054                 gfp_mask |= __GFP_MEMALLOC;
1055         data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1056                                gfp_mask, NUMA_NO_NODE, NULL);
1057         if (!data)
1058                 goto nodata;
1059         size = SKB_WITH_OVERHEAD(ksize(data));
1060
1061         /* Copy only real data... and, alas, header. This should be
1062          * optimized for the cases when header is void.
1063          */
1064         memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1065
1066         memcpy((struct skb_shared_info *)(data + size),
1067                skb_shinfo(skb),
1068                offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1069
1070         /*
1071          * if shinfo is shared we must drop the old head gracefully, but if it
1072          * is not we can just drop the old head and let the existing refcount
1073          * be since all we did is relocate the values
1074          */
1075         if (skb_cloned(skb)) {
1076                 /* copy this zero copy skb frags */
1077                 if (skb_orphan_frags(skb, gfp_mask))
1078                         goto nofrags;
1079                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1080                         skb_frag_ref(skb, i);
1081
1082                 if (skb_has_frag_list(skb))
1083                         skb_clone_fraglist(skb);
1084
1085                 skb_release_data(skb);
1086         } else {
1087                 skb_free_head(skb);
1088         }
1089         off = (data + nhead) - skb->head;
1090
1091         skb->head     = data;
1092         skb->head_frag = 0;
1093         skb->data    += off;
1094 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1095         skb->end      = size;
1096         off           = nhead;
1097 #else
1098         skb->end      = skb->head + size;
1099 #endif
1100         skb->tail             += off;
1101         skb_headers_offset_update(skb, nhead);
1102         skb->cloned   = 0;
1103         skb->hdr_len  = 0;
1104         skb->nohdr    = 0;
1105         atomic_set(&skb_shinfo(skb)->dataref, 1);
1106         return 0;
1107
1108 nofrags:
1109         kfree(data);
1110 nodata:
1111         return -ENOMEM;
1112 }
1113 EXPORT_SYMBOL(pskb_expand_head);
1114
1115 /* Make private copy of skb with writable head and some headroom */
1116
1117 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1118 {
1119         struct sk_buff *skb2;
1120         int delta = headroom - skb_headroom(skb);
1121
1122         if (delta <= 0)
1123                 skb2 = pskb_copy(skb, GFP_ATOMIC);
1124         else {
1125                 skb2 = skb_clone(skb, GFP_ATOMIC);
1126                 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1127                                              GFP_ATOMIC)) {
1128                         kfree_skb(skb2);
1129                         skb2 = NULL;
1130                 }
1131         }
1132         return skb2;
1133 }
1134 EXPORT_SYMBOL(skb_realloc_headroom);
1135
1136 /**
1137  *      skb_copy_expand -       copy and expand sk_buff
1138  *      @skb: buffer to copy
1139  *      @newheadroom: new free bytes at head
1140  *      @newtailroom: new free bytes at tail
1141  *      @gfp_mask: allocation priority
1142  *
1143  *      Make a copy of both an &sk_buff and its data and while doing so
1144  *      allocate additional space.
1145  *
1146  *      This is used when the caller wishes to modify the data and needs a
1147  *      private copy of the data to alter as well as more space for new fields.
1148  *      Returns %NULL on failure or the pointer to the buffer
1149  *      on success. The returned buffer has a reference count of 1.
1150  *
1151  *      You must pass %GFP_ATOMIC as the allocation priority if this function
1152  *      is called from an interrupt.
1153  */
1154 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1155                                 int newheadroom, int newtailroom,
1156                                 gfp_t gfp_mask)
1157 {
1158         /*
1159          *      Allocate the copy buffer
1160          */
1161         struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1162                                         gfp_mask, skb_alloc_rx_flag(skb),
1163                                         NUMA_NO_NODE);
1164         int oldheadroom = skb_headroom(skb);
1165         int head_copy_len, head_copy_off;
1166
1167         if (!n)
1168                 return NULL;
1169
1170         skb_reserve(n, newheadroom);
1171
1172         /* Set the tail pointer and length */
1173         skb_put(n, skb->len);
1174
1175         head_copy_len = oldheadroom;
1176         head_copy_off = 0;
1177         if (newheadroom <= head_copy_len)
1178                 head_copy_len = newheadroom;
1179         else
1180                 head_copy_off = newheadroom - head_copy_len;
1181
1182         /* Copy the linear header and data. */
1183         if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1184                           skb->len + head_copy_len))
1185                 BUG();
1186
1187         copy_skb_header(n, skb);
1188
1189         skb_headers_offset_update(n, newheadroom - oldheadroom);
1190
1191         return n;
1192 }
1193 EXPORT_SYMBOL(skb_copy_expand);
1194
1195 /**
1196  *      skb_pad                 -       zero pad the tail of an skb
1197  *      @skb: buffer to pad
1198  *      @pad: space to pad
1199  *
1200  *      Ensure that a buffer is followed by a padding area that is zero
1201  *      filled. Used by network drivers which may DMA or transfer data
1202  *      beyond the buffer end onto the wire.
1203  *
1204  *      May return error in out of memory cases. The skb is freed on error.
1205  */
1206
1207 int skb_pad(struct sk_buff *skb, int pad)
1208 {
1209         int err;
1210         int ntail;
1211
1212         /* If the skbuff is non linear tailroom is always zero.. */
1213         if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1214                 memset(skb->data+skb->len, 0, pad);
1215                 return 0;
1216         }
1217
1218         ntail = skb->data_len + pad - (skb->end - skb->tail);
1219         if (likely(skb_cloned(skb) || ntail > 0)) {
1220                 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1221                 if (unlikely(err))
1222                         goto free_skb;
1223         }
1224
1225         /* FIXME: The use of this function with non-linear skb's really needs
1226          * to be audited.
1227          */
1228         err = skb_linearize(skb);
1229         if (unlikely(err))
1230                 goto free_skb;
1231
1232         memset(skb->data + skb->len, 0, pad);
1233         return 0;
1234
1235 free_skb:
1236         kfree_skb(skb);
1237         return err;
1238 }
1239 EXPORT_SYMBOL(skb_pad);
1240
1241 /**
1242  *      pskb_put - add data to the tail of a potentially fragmented buffer
1243  *      @skb: start of the buffer to use
1244  *      @tail: tail fragment of the buffer to use
1245  *      @len: amount of data to add
1246  *
1247  *      This function extends the used data area of the potentially
1248  *      fragmented buffer. @tail must be the last fragment of @skb -- or
1249  *      @skb itself. If this would exceed the total buffer size the kernel
1250  *      will panic. A pointer to the first byte of the extra data is
1251  *      returned.
1252  */
1253
1254 unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1255 {
1256         if (tail != skb) {
1257                 skb->data_len += len;
1258                 skb->len += len;
1259         }
1260         return skb_put(tail, len);
1261 }
1262 EXPORT_SYMBOL_GPL(pskb_put);
1263
1264 /**
1265  *      skb_put - add data to a buffer
1266  *      @skb: buffer to use
1267  *      @len: amount of data to add
1268  *
1269  *      This function extends the used data area of the buffer. If this would
1270  *      exceed the total buffer size the kernel will panic. A pointer to the
1271  *      first byte of the extra data is returned.
1272  */
1273 unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
1274 {
1275         unsigned char *tmp = skb_tail_pointer(skb);
1276         SKB_LINEAR_ASSERT(skb);
1277         skb->tail += len;
1278         skb->len  += len;
1279         if (unlikely(skb->tail > skb->end))
1280                 skb_over_panic(skb, len, __builtin_return_address(0));
1281         return tmp;
1282 }
1283 EXPORT_SYMBOL(skb_put);
1284
1285 /**
1286  *      skb_push - add data to the start of a buffer
1287  *      @skb: buffer to use
1288  *      @len: amount of data to add
1289  *
1290  *      This function extends the used data area of the buffer at the buffer
1291  *      start. If this would exceed the total buffer headroom the kernel will
1292  *      panic. A pointer to the first byte of the extra data is returned.
1293  */
1294 unsigned char *skb_push(struct sk_buff *skb, unsigned int len)
1295 {
1296         skb->data -= len;
1297         skb->len  += len;
1298         if (unlikely(skb->data<skb->head))
1299                 skb_under_panic(skb, len, __builtin_return_address(0));
1300         return skb->data;
1301 }
1302 EXPORT_SYMBOL(skb_push);
1303
1304 /**
1305  *      skb_pull - remove data from the start of a buffer
1306  *      @skb: buffer to use
1307  *      @len: amount of data to remove
1308  *
1309  *      This function removes data from the start of a buffer, returning
1310  *      the memory to the headroom. A pointer to the next data in the buffer
1311  *      is returned. Once the data has been pulled future pushes will overwrite
1312  *      the old data.
1313  */
1314 unsigned char *skb_pull(struct sk_buff *skb, unsigned int len)
1315 {
1316         return skb_pull_inline(skb, len);
1317 }
1318 EXPORT_SYMBOL(skb_pull);
1319
1320 /**
1321  *      skb_trim - remove end from a buffer
1322  *      @skb: buffer to alter
1323  *      @len: new length
1324  *
1325  *      Cut the length of a buffer down by removing data from the tail. If
1326  *      the buffer is already under the length specified it is not modified.
1327  *      The skb must be linear.
1328  */
1329 void skb_trim(struct sk_buff *skb, unsigned int len)
1330 {
1331         if (skb->len > len)
1332                 __skb_trim(skb, len);
1333 }
1334 EXPORT_SYMBOL(skb_trim);
1335
1336 /* Trims skb to length len. It can change skb pointers.
1337  */
1338
1339 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
1340 {
1341         struct sk_buff **fragp;
1342         struct sk_buff *frag;
1343         int offset = skb_headlen(skb);
1344         int nfrags = skb_shinfo(skb)->nr_frags;
1345         int i;
1346         int err;
1347
1348         if (skb_cloned(skb) &&
1349             unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
1350                 return err;
1351
1352         i = 0;
1353         if (offset >= len)
1354                 goto drop_pages;
1355
1356         for (; i < nfrags; i++) {
1357                 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
1358
1359                 if (end < len) {
1360                         offset = end;
1361                         continue;
1362                 }
1363
1364                 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
1365
1366 drop_pages:
1367                 skb_shinfo(skb)->nr_frags = i;
1368
1369                 for (; i < nfrags; i++)
1370                         skb_frag_unref(skb, i);
1371
1372                 if (skb_has_frag_list(skb))
1373                         skb_drop_fraglist(skb);
1374                 goto done;
1375         }
1376
1377         for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
1378              fragp = &frag->next) {
1379                 int end = offset + frag->len;
1380
1381                 if (skb_shared(frag)) {
1382                         struct sk_buff *nfrag;
1383
1384                         nfrag = skb_clone(frag, GFP_ATOMIC);
1385                         if (unlikely(!nfrag))
1386                                 return -ENOMEM;
1387
1388                         nfrag->next = frag->next;
1389                         consume_skb(frag);
1390                         frag = nfrag;
1391                         *fragp = frag;
1392                 }
1393
1394                 if (end < len) {
1395                         offset = end;
1396                         continue;
1397                 }
1398
1399                 if (end > len &&
1400                     unlikely((err = pskb_trim(frag, len - offset))))
1401                         return err;
1402
1403                 if (frag->next)
1404                         skb_drop_list(&frag->next);
1405                 break;
1406         }
1407
1408 done:
1409         if (len > skb_headlen(skb)) {
1410                 skb->data_len -= skb->len - len;
1411                 skb->len       = len;
1412         } else {
1413                 skb->len       = len;
1414                 skb->data_len  = 0;
1415                 skb_set_tail_pointer(skb, len);
1416         }
1417
1418         return 0;
1419 }
1420 EXPORT_SYMBOL(___pskb_trim);
1421
1422 /**
1423  *      __pskb_pull_tail - advance tail of skb header
1424  *      @skb: buffer to reallocate
1425  *      @delta: number of bytes to advance tail
1426  *
1427  *      The function makes a sense only on a fragmented &sk_buff,
1428  *      it expands header moving its tail forward and copying necessary
1429  *      data from fragmented part.
1430  *
1431  *      &sk_buff MUST have reference count of 1.
1432  *
1433  *      Returns %NULL (and &sk_buff does not change) if pull failed
1434  *      or value of new tail of skb in the case of success.
1435  *
1436  *      All the pointers pointing into skb header may change and must be
1437  *      reloaded after call to this function.
1438  */
1439
1440 /* Moves tail of skb head forward, copying data from fragmented part,
1441  * when it is necessary.
1442  * 1. It may fail due to malloc failure.
1443  * 2. It may change skb pointers.
1444  *
1445  * It is pretty complicated. Luckily, it is called only in exceptional cases.
1446  */
1447 unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta)
1448 {
1449         /* If skb has not enough free space at tail, get new one
1450          * plus 128 bytes for future expansions. If we have enough
1451          * room at tail, reallocate without expansion only if skb is cloned.
1452          */
1453         int i, k, eat = (skb->tail + delta) - skb->end;
1454
1455         if (eat > 0 || skb_cloned(skb)) {
1456                 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
1457                                      GFP_ATOMIC))
1458                         return NULL;
1459         }
1460
1461         if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta))
1462                 BUG();
1463
1464         /* Optimization: no fragments, no reasons to preestimate
1465          * size of pulled pages. Superb.
1466          */
1467         if (!skb_has_frag_list(skb))
1468                 goto pull_pages;
1469
1470         /* Estimate size of pulled pages. */
1471         eat = delta;
1472         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1473                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1474
1475                 if (size >= eat)
1476                         goto pull_pages;
1477                 eat -= size;
1478         }
1479
1480         /* If we need update frag list, we are in troubles.
1481          * Certainly, it possible to add an offset to skb data,
1482          * but taking into account that pulling is expected to
1483          * be very rare operation, it is worth to fight against
1484          * further bloating skb head and crucify ourselves here instead.
1485          * Pure masohism, indeed. 8)8)
1486          */
1487         if (eat) {
1488                 struct sk_buff *list = skb_shinfo(skb)->frag_list;
1489                 struct sk_buff *clone = NULL;
1490                 struct sk_buff *insp = NULL;
1491
1492                 do {
1493                         BUG_ON(!list);
1494
1495                         if (list->len <= eat) {
1496                                 /* Eaten as whole. */
1497                                 eat -= list->len;
1498                                 list = list->next;
1499                                 insp = list;
1500                         } else {
1501                                 /* Eaten partially. */
1502
1503                                 if (skb_shared(list)) {
1504                                         /* Sucks! We need to fork list. :-( */
1505                                         clone = skb_clone(list, GFP_ATOMIC);
1506                                         if (!clone)
1507                                                 return NULL;
1508                                         insp = list->next;
1509                                         list = clone;
1510                                 } else {
1511                                         /* This may be pulled without
1512                                          * problems. */
1513                                         insp = list;
1514                                 }
1515                                 if (!pskb_pull(list, eat)) {
1516                                         kfree_skb(clone);
1517                                         return NULL;
1518                                 }
1519                                 break;
1520                         }
1521                 } while (eat);
1522
1523                 /* Free pulled out fragments. */
1524                 while ((list = skb_shinfo(skb)->frag_list) != insp) {
1525                         skb_shinfo(skb)->frag_list = list->next;
1526                         kfree_skb(list);
1527                 }
1528                 /* And insert new clone at head. */
1529                 if (clone) {
1530                         clone->next = list;
1531                         skb_shinfo(skb)->frag_list = clone;
1532                 }
1533         }
1534         /* Success! Now we may commit changes to skb data. */
1535
1536 pull_pages:
1537         eat = delta;
1538         k = 0;
1539         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1540                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1541
1542                 if (size <= eat) {
1543                         skb_frag_unref(skb, i);
1544                         eat -= size;
1545                 } else {
1546                         skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
1547                         if (eat) {
1548                                 skb_shinfo(skb)->frags[k].page_offset += eat;
1549                                 skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
1550                                 eat = 0;
1551                         }
1552                         k++;
1553                 }
1554         }
1555         skb_shinfo(skb)->nr_frags = k;
1556
1557         skb->tail     += delta;
1558         skb->data_len -= delta;
1559
1560         return skb_tail_pointer(skb);
1561 }
1562 EXPORT_SYMBOL(__pskb_pull_tail);
1563
1564 /**
1565  *      skb_copy_bits - copy bits from skb to kernel buffer
1566  *      @skb: source skb
1567  *      @offset: offset in source
1568  *      @to: destination buffer
1569  *      @len: number of bytes to copy
1570  *
1571  *      Copy the specified number of bytes from the source skb to the
1572  *      destination buffer.
1573  *
1574  *      CAUTION ! :
1575  *              If its prototype is ever changed,
1576  *              check arch/{*}/net/{*}.S files,
1577  *              since it is called from BPF assembly code.
1578  */
1579 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
1580 {
1581         int start = skb_headlen(skb);
1582         struct sk_buff *frag_iter;
1583         int i, copy;
1584
1585         if (offset > (int)skb->len - len)
1586                 goto fault;
1587
1588         /* Copy header. */
1589         if ((copy = start - offset) > 0) {
1590                 if (copy > len)
1591                         copy = len;
1592                 skb_copy_from_linear_data_offset(skb, offset, to, copy);
1593                 if ((len -= copy) == 0)
1594                         return 0;
1595                 offset += copy;
1596                 to     += copy;
1597         }
1598
1599         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1600                 int end;
1601                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1602
1603                 WARN_ON(start > offset + len);
1604
1605                 end = start + skb_frag_size(f);
1606                 if ((copy = end - offset) > 0) {
1607                         u8 *vaddr;
1608
1609                         if (copy > len)
1610                                 copy = len;
1611
1612                         vaddr = kmap_atomic(skb_frag_page(f));
1613                         memcpy(to,
1614                                vaddr + f->page_offset + offset - start,
1615                                copy);
1616                         kunmap_atomic(vaddr);
1617
1618                         if ((len -= copy) == 0)
1619                                 return 0;
1620                         offset += copy;
1621                         to     += copy;
1622                 }
1623                 start = end;
1624         }
1625
1626         skb_walk_frags(skb, frag_iter) {
1627                 int end;
1628
1629                 WARN_ON(start > offset + len);
1630
1631                 end = start + frag_iter->len;
1632                 if ((copy = end - offset) > 0) {
1633                         if (copy > len)
1634                                 copy = len;
1635                         if (skb_copy_bits(frag_iter, offset - start, to, copy))
1636                                 goto fault;
1637                         if ((len -= copy) == 0)
1638                                 return 0;
1639                         offset += copy;
1640                         to     += copy;
1641                 }
1642                 start = end;
1643         }
1644
1645         if (!len)
1646                 return 0;
1647
1648 fault:
1649         return -EFAULT;
1650 }
1651 EXPORT_SYMBOL(skb_copy_bits);
1652
1653 /*
1654  * Callback from splice_to_pipe(), if we need to release some pages
1655  * at the end of the spd in case we error'ed out in filling the pipe.
1656  */
1657 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
1658 {
1659         put_page(spd->pages[i]);
1660 }
1661
1662 static struct page *linear_to_page(struct page *page, unsigned int *len,
1663                                    unsigned int *offset,
1664                                    struct sock *sk)
1665 {
1666         struct page_frag *pfrag = sk_page_frag(sk);
1667
1668         if (!sk_page_frag_refill(sk, pfrag))
1669                 return NULL;
1670
1671         *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
1672
1673         memcpy(page_address(pfrag->page) + pfrag->offset,
1674                page_address(page) + *offset, *len);
1675         *offset = pfrag->offset;
1676         pfrag->offset += *len;
1677
1678         return pfrag->page;
1679 }
1680
1681 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
1682                              struct page *page,
1683                              unsigned int offset)
1684 {
1685         return  spd->nr_pages &&
1686                 spd->pages[spd->nr_pages - 1] == page &&
1687                 (spd->partial[spd->nr_pages - 1].offset +
1688                  spd->partial[spd->nr_pages - 1].len == offset);
1689 }
1690
1691 /*
1692  * Fill page/offset/length into spd, if it can hold more pages.
1693  */
1694 static bool spd_fill_page(struct splice_pipe_desc *spd,
1695                           struct pipe_inode_info *pipe, struct page *page,
1696                           unsigned int *len, unsigned int offset,
1697                           bool linear,
1698                           struct sock *sk)
1699 {
1700         if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
1701                 return true;
1702
1703         if (linear) {
1704                 page = linear_to_page(page, len, &offset, sk);
1705                 if (!page)
1706                         return true;
1707         }
1708         if (spd_can_coalesce(spd, page, offset)) {
1709                 spd->partial[spd->nr_pages - 1].len += *len;
1710                 return false;
1711         }
1712         get_page(page);
1713         spd->pages[spd->nr_pages] = page;
1714         spd->partial[spd->nr_pages].len = *len;
1715         spd->partial[spd->nr_pages].offset = offset;
1716         spd->nr_pages++;
1717
1718         return false;
1719 }
1720
1721 static bool __splice_segment(struct page *page, unsigned int poff,
1722                              unsigned int plen, unsigned int *off,
1723                              unsigned int *len,
1724                              struct splice_pipe_desc *spd, bool linear,
1725                              struct sock *sk,
1726                              struct pipe_inode_info *pipe)
1727 {
1728         if (!*len)
1729                 return true;
1730
1731         /* skip this segment if already processed */
1732         if (*off >= plen) {
1733                 *off -= plen;
1734                 return false;
1735         }
1736
1737         /* ignore any bits we already processed */
1738         poff += *off;
1739         plen -= *off;
1740         *off = 0;
1741
1742         do {
1743                 unsigned int flen = min(*len, plen);
1744
1745                 if (spd_fill_page(spd, pipe, page, &flen, poff,
1746                                   linear, sk))
1747                         return true;
1748                 poff += flen;
1749                 plen -= flen;
1750                 *len -= flen;
1751         } while (*len && plen);
1752
1753         return false;
1754 }
1755
1756 /*
1757  * Map linear and fragment data from the skb to spd. It reports true if the
1758  * pipe is full or if we already spliced the requested length.
1759  */
1760 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
1761                               unsigned int *offset, unsigned int *len,
1762                               struct splice_pipe_desc *spd, struct sock *sk)
1763 {
1764         int seg;
1765
1766         /* map the linear part :
1767          * If skb->head_frag is set, this 'linear' part is backed by a
1768          * fragment, and if the head is not shared with any clones then
1769          * we can avoid a copy since we own the head portion of this page.
1770          */
1771         if (__splice_segment(virt_to_page(skb->data),
1772                              (unsigned long) skb->data & (PAGE_SIZE - 1),
1773                              skb_headlen(skb),
1774                              offset, len, spd,
1775                              skb_head_is_locked(skb),
1776                              sk, pipe))
1777                 return true;
1778
1779         /*
1780          * then map the fragments
1781          */
1782         for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
1783                 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
1784
1785                 if (__splice_segment(skb_frag_page(f),
1786                                      f->page_offset, skb_frag_size(f),
1787                                      offset, len, spd, false, sk, pipe))
1788                         return true;
1789         }
1790
1791         return false;
1792 }
1793
1794 /*
1795  * Map data from the skb to a pipe. Should handle both the linear part,
1796  * the fragments, and the frag list. It does NOT handle frag lists within
1797  * the frag list, if such a thing exists. We'd probably need to recurse to
1798  * handle that cleanly.
1799  */
1800 int skb_splice_bits(struct sk_buff *skb, unsigned int offset,
1801                     struct pipe_inode_info *pipe, unsigned int tlen,
1802                     unsigned int flags)
1803 {
1804         struct partial_page partial[MAX_SKB_FRAGS];
1805         struct page *pages[MAX_SKB_FRAGS];
1806         struct splice_pipe_desc spd = {
1807                 .pages = pages,
1808                 .partial = partial,
1809                 .nr_pages_max = MAX_SKB_FRAGS,
1810                 .flags = flags,
1811                 .ops = &nosteal_pipe_buf_ops,
1812                 .spd_release = sock_spd_release,
1813         };
1814         struct sk_buff *frag_iter;
1815         struct sock *sk = skb->sk;
1816         int ret = 0;
1817
1818         /*
1819          * __skb_splice_bits() only fails if the output has no room left,
1820          * so no point in going over the frag_list for the error case.
1821          */
1822         if (__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk))
1823                 goto done;
1824         else if (!tlen)
1825                 goto done;
1826
1827         /*
1828          * now see if we have a frag_list to map
1829          */
1830         skb_walk_frags(skb, frag_iter) {
1831                 if (!tlen)
1832                         break;
1833                 if (__skb_splice_bits(frag_iter, pipe, &offset, &tlen, &spd, sk))
1834                         break;
1835         }
1836
1837 done:
1838         if (spd.nr_pages) {
1839                 /*
1840                  * Drop the socket lock, otherwise we have reverse
1841                  * locking dependencies between sk_lock and i_mutex
1842                  * here as compared to sendfile(). We enter here
1843                  * with the socket lock held, and splice_to_pipe() will
1844                  * grab the pipe inode lock. For sendfile() emulation,
1845                  * we call into ->sendpage() with the i_mutex lock held
1846                  * and networking will grab the socket lock.
1847                  */
1848                 release_sock(sk);
1849                 ret = splice_to_pipe(pipe, &spd);
1850                 lock_sock(sk);
1851         }
1852
1853         return ret;
1854 }
1855
1856 /**
1857  *      skb_store_bits - store bits from kernel buffer to skb
1858  *      @skb: destination buffer
1859  *      @offset: offset in destination
1860  *      @from: source buffer
1861  *      @len: number of bytes to copy
1862  *
1863  *      Copy the specified number of bytes from the source buffer to the
1864  *      destination skb.  This function handles all the messy bits of
1865  *      traversing fragment lists and such.
1866  */
1867
1868 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
1869 {
1870         int start = skb_headlen(skb);
1871         struct sk_buff *frag_iter;
1872         int i, copy;
1873
1874         if (offset > (int)skb->len - len)
1875                 goto fault;
1876
1877         if ((copy = start - offset) > 0) {
1878                 if (copy > len)
1879                         copy = len;
1880                 skb_copy_to_linear_data_offset(skb, offset, from, copy);
1881                 if ((len -= copy) == 0)
1882                         return 0;
1883                 offset += copy;
1884                 from += copy;
1885         }
1886
1887         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1888                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1889                 int end;
1890
1891                 WARN_ON(start > offset + len);
1892
1893                 end = start + skb_frag_size(frag);
1894                 if ((copy = end - offset) > 0) {
1895                         u8 *vaddr;
1896
1897                         if (copy > len)
1898                                 copy = len;
1899
1900                         vaddr = kmap_atomic(skb_frag_page(frag));
1901                         memcpy(vaddr + frag->page_offset + offset - start,
1902                                from, copy);
1903                         kunmap_atomic(vaddr);
1904
1905                         if ((len -= copy) == 0)
1906                                 return 0;
1907                         offset += copy;
1908                         from += copy;
1909                 }
1910                 start = end;
1911         }
1912
1913         skb_walk_frags(skb, frag_iter) {
1914                 int end;
1915
1916                 WARN_ON(start > offset + len);
1917
1918                 end = start + frag_iter->len;
1919                 if ((copy = end - offset) > 0) {
1920                         if (copy > len)
1921                                 copy = len;
1922                         if (skb_store_bits(frag_iter, offset - start,
1923                                            from, copy))
1924                                 goto fault;
1925                         if ((len -= copy) == 0)
1926                                 return 0;
1927                         offset += copy;
1928                         from += copy;
1929                 }
1930                 start = end;
1931         }
1932         if (!len)
1933                 return 0;
1934
1935 fault:
1936         return -EFAULT;
1937 }
1938 EXPORT_SYMBOL(skb_store_bits);
1939
1940 /* Checksum skb data. */
1941 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
1942                       __wsum csum, const struct skb_checksum_ops *ops)
1943 {
1944         int start = skb_headlen(skb);
1945         int i, copy = start - offset;
1946         struct sk_buff *frag_iter;
1947         int pos = 0;
1948
1949         /* Checksum header. */
1950         if (copy > 0) {
1951                 if (copy > len)
1952                         copy = len;
1953                 csum = ops->update(skb->data + offset, copy, csum);
1954                 if ((len -= copy) == 0)
1955                         return csum;
1956                 offset += copy;
1957                 pos     = copy;
1958         }
1959
1960         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1961                 int end;
1962                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1963
1964                 WARN_ON(start > offset + len);
1965
1966                 end = start + skb_frag_size(frag);
1967                 if ((copy = end - offset) > 0) {
1968                         __wsum csum2;
1969                         u8 *vaddr;
1970
1971                         if (copy > len)
1972                                 copy = len;
1973                         vaddr = kmap_atomic(skb_frag_page(frag));
1974                         csum2 = ops->update(vaddr + frag->page_offset +
1975                                             offset - start, copy, 0);
1976                         kunmap_atomic(vaddr);
1977                         csum = ops->combine(csum, csum2, pos, copy);
1978                         if (!(len -= copy))
1979                                 return csum;
1980                         offset += copy;
1981                         pos    += copy;
1982                 }
1983                 start = end;
1984         }
1985
1986         skb_walk_frags(skb, frag_iter) {
1987                 int end;
1988
1989                 WARN_ON(start > offset + len);
1990
1991                 end = start + frag_iter->len;
1992                 if ((copy = end - offset) > 0) {
1993                         __wsum csum2;
1994                         if (copy > len)
1995                                 copy = len;
1996                         csum2 = __skb_checksum(frag_iter, offset - start,
1997                                                copy, 0, ops);
1998                         csum = ops->combine(csum, csum2, pos, copy);
1999                         if ((len -= copy) == 0)
2000                                 return csum;
2001                         offset += copy;
2002                         pos    += copy;
2003                 }
2004                 start = end;
2005         }
2006         BUG_ON(len);
2007
2008         return csum;
2009 }
2010 EXPORT_SYMBOL(__skb_checksum);
2011
2012 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2013                     int len, __wsum csum)
2014 {
2015         const struct skb_checksum_ops ops = {
2016                 .update  = csum_partial_ext,
2017                 .combine = csum_block_add_ext,
2018         };
2019
2020         return __skb_checksum(skb, offset, len, csum, &ops);
2021 }
2022 EXPORT_SYMBOL(skb_checksum);
2023
2024 /* Both of above in one bottle. */
2025
2026 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2027                                     u8 *to, int len, __wsum csum)
2028 {
2029         int start = skb_headlen(skb);
2030         int i, copy = start - offset;
2031         struct sk_buff *frag_iter;
2032         int pos = 0;
2033
2034         /* Copy header. */
2035         if (copy > 0) {
2036                 if (copy > len)
2037                         copy = len;
2038                 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2039                                                  copy, csum);
2040                 if ((len -= copy) == 0)
2041                         return csum;
2042                 offset += copy;
2043                 to     += copy;
2044                 pos     = copy;
2045         }
2046
2047         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2048                 int end;
2049
2050                 WARN_ON(start > offset + len);
2051
2052                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2053                 if ((copy = end - offset) > 0) {
2054                         __wsum csum2;
2055                         u8 *vaddr;
2056                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2057
2058                         if (copy > len)
2059                                 copy = len;
2060                         vaddr = kmap_atomic(skb_frag_page(frag));
2061                         csum2 = csum_partial_copy_nocheck(vaddr +
2062                                                           frag->page_offset +
2063                                                           offset - start, to,
2064                                                           copy, 0);
2065                         kunmap_atomic(vaddr);
2066                         csum = csum_block_add(csum, csum2, pos);
2067                         if (!(len -= copy))
2068                                 return csum;
2069                         offset += copy;
2070                         to     += copy;
2071                         pos    += copy;
2072                 }
2073                 start = end;
2074         }
2075
2076         skb_walk_frags(skb, frag_iter) {
2077                 __wsum csum2;
2078                 int end;
2079
2080                 WARN_ON(start > offset + len);
2081
2082                 end = start + frag_iter->len;
2083                 if ((copy = end - offset) > 0) {
2084                         if (copy > len)
2085                                 copy = len;
2086                         csum2 = skb_copy_and_csum_bits(frag_iter,
2087                                                        offset - start,
2088                                                        to, copy, 0);
2089                         csum = csum_block_add(csum, csum2, pos);
2090                         if ((len -= copy) == 0)
2091                                 return csum;
2092                         offset += copy;
2093                         to     += copy;
2094                         pos    += copy;
2095                 }
2096                 start = end;
2097         }
2098         BUG_ON(len);
2099         return csum;
2100 }
2101 EXPORT_SYMBOL(skb_copy_and_csum_bits);
2102
2103  /**
2104  *      skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
2105  *      @from: source buffer
2106  *
2107  *      Calculates the amount of linear headroom needed in the 'to' skb passed
2108  *      into skb_zerocopy().
2109  */
2110 unsigned int
2111 skb_zerocopy_headlen(const struct sk_buff *from)
2112 {
2113         unsigned int hlen = 0;
2114
2115         if (!from->head_frag ||
2116             skb_headlen(from) < L1_CACHE_BYTES ||
2117             skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
2118                 hlen = skb_headlen(from);
2119
2120         if (skb_has_frag_list(from))
2121                 hlen = from->len;
2122
2123         return hlen;
2124 }
2125 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
2126
2127 /**
2128  *      skb_zerocopy - Zero copy skb to skb
2129  *      @to: destination buffer
2130  *      @from: source buffer
2131  *      @len: number of bytes to copy from source buffer
2132  *      @hlen: size of linear headroom in destination buffer
2133  *
2134  *      Copies up to `len` bytes from `from` to `to` by creating references
2135  *      to the frags in the source buffer.
2136  *
2137  *      The `hlen` as calculated by skb_zerocopy_headlen() specifies the
2138  *      headroom in the `to` buffer.
2139  *
2140  *      Return value:
2141  *      0: everything is OK
2142  *      -ENOMEM: couldn't orphan frags of @from due to lack of memory
2143  *      -EFAULT: skb_copy_bits() found some problem with skb geometry
2144  */
2145 int
2146 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
2147 {
2148         int i, j = 0;
2149         int plen = 0; /* length of skb->head fragment */
2150         int ret;
2151         struct page *page;
2152         unsigned int offset;
2153
2154         BUG_ON(!from->head_frag && !hlen);
2155
2156         /* dont bother with small payloads */
2157         if (len <= skb_tailroom(to))
2158                 return skb_copy_bits(from, 0, skb_put(to, len), len);
2159
2160         if (hlen) {
2161                 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
2162                 if (unlikely(ret))
2163                         return ret;
2164                 len -= hlen;
2165         } else {
2166                 plen = min_t(int, skb_headlen(from), len);
2167                 if (plen) {
2168                         page = virt_to_head_page(from->head);
2169                         offset = from->data - (unsigned char *)page_address(page);
2170                         __skb_fill_page_desc(to, 0, page, offset, plen);
2171                         get_page(page);
2172                         j = 1;
2173                         len -= plen;
2174                 }
2175         }
2176
2177         to->truesize += len + plen;
2178         to->len += len + plen;
2179         to->data_len += len + plen;
2180
2181         if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
2182                 skb_tx_error(from);
2183                 return -ENOMEM;
2184         }
2185
2186         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
2187                 if (!len)
2188                         break;
2189                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
2190                 skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
2191                 len -= skb_shinfo(to)->frags[j].size;
2192                 skb_frag_ref(to, j);
2193                 j++;
2194         }
2195         skb_shinfo(to)->nr_frags = j;
2196
2197         return 0;
2198 }
2199 EXPORT_SYMBOL_GPL(skb_zerocopy);
2200
2201 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
2202 {
2203         __wsum csum;
2204         long csstart;
2205
2206         if (skb->ip_summed == CHECKSUM_PARTIAL)
2207                 csstart = skb_checksum_start_offset(skb);
2208         else
2209                 csstart = skb_headlen(skb);
2210
2211         BUG_ON(csstart > skb_headlen(skb));
2212
2213         skb_copy_from_linear_data(skb, to, csstart);
2214
2215         csum = 0;
2216         if (csstart != skb->len)
2217                 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
2218                                               skb->len - csstart, 0);
2219
2220         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2221                 long csstuff = csstart + skb->csum_offset;
2222
2223                 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
2224         }
2225 }
2226 EXPORT_SYMBOL(skb_copy_and_csum_dev);
2227
2228 /**
2229  *      skb_dequeue - remove from the head of the queue
2230  *      @list: list to dequeue from
2231  *
2232  *      Remove the head of the list. The list lock is taken so the function
2233  *      may be used safely with other locking list functions. The head item is
2234  *      returned or %NULL if the list is empty.
2235  */
2236
2237 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
2238 {
2239         unsigned long flags;
2240         struct sk_buff *result;
2241
2242         spin_lock_irqsave(&list->lock, flags);
2243         result = __skb_dequeue(list);
2244         spin_unlock_irqrestore(&list->lock, flags);
2245         return result;
2246 }
2247 EXPORT_SYMBOL(skb_dequeue);
2248
2249 /**
2250  *      skb_dequeue_tail - remove from the tail of the queue
2251  *      @list: list to dequeue from
2252  *
2253  *      Remove the tail of the list. The list lock is taken so the function
2254  *      may be used safely with other locking list functions. The tail item is
2255  *      returned or %NULL if the list is empty.
2256  */
2257 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
2258 {
2259         unsigned long flags;
2260         struct sk_buff *result;
2261
2262         spin_lock_irqsave(&list->lock, flags);
2263         result = __skb_dequeue_tail(list);
2264         spin_unlock_irqrestore(&list->lock, flags);
2265         return result;
2266 }
2267 EXPORT_SYMBOL(skb_dequeue_tail);
2268
2269 /**
2270  *      skb_queue_purge - empty a list
2271  *      @list: list to empty
2272  *
2273  *      Delete all buffers on an &sk_buff list. Each buffer is removed from
2274  *      the list and one reference dropped. This function takes the list
2275  *      lock and is atomic with respect to other list locking functions.
2276  */
2277 void skb_queue_purge(struct sk_buff_head *list)
2278 {
2279         struct sk_buff *skb;
2280         while ((skb = skb_dequeue(list)) != NULL)
2281                 kfree_skb(skb);
2282 }
2283 EXPORT_SYMBOL(skb_queue_purge);
2284
2285 /**
2286  *      skb_queue_head - queue a buffer at the list head
2287  *      @list: list to use
2288  *      @newsk: buffer to queue
2289  *
2290  *      Queue a buffer at the start of the list. This function takes the
2291  *      list lock and can be used safely with other locking &sk_buff functions
2292  *      safely.
2293  *
2294  *      A buffer cannot be placed on two lists at the same time.
2295  */
2296 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
2297 {
2298         unsigned long flags;
2299
2300         spin_lock_irqsave(&list->lock, flags);
2301         __skb_queue_head(list, newsk);
2302         spin_unlock_irqrestore(&list->lock, flags);
2303 }
2304 EXPORT_SYMBOL(skb_queue_head);
2305
2306 /**
2307  *      skb_queue_tail - queue a buffer at the list tail
2308  *      @list: list to use
2309  *      @newsk: buffer to queue
2310  *
2311  *      Queue a buffer at the tail of the list. This function takes the
2312  *      list lock and can be used safely with other locking &sk_buff functions
2313  *      safely.
2314  *
2315  *      A buffer cannot be placed on two lists at the same time.
2316  */
2317 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
2318 {
2319         unsigned long flags;
2320
2321         spin_lock_irqsave(&list->lock, flags);
2322         __skb_queue_tail(list, newsk);
2323         spin_unlock_irqrestore(&list->lock, flags);
2324 }
2325 EXPORT_SYMBOL(skb_queue_tail);
2326
2327 /**
2328  *      skb_unlink      -       remove a buffer from a list
2329  *      @skb: buffer to remove
2330  *      @list: list to use
2331  *
2332  *      Remove a packet from a list. The list locks are taken and this
2333  *      function is atomic with respect to other list locked calls
2334  *
2335  *      You must know what list the SKB is on.
2336  */
2337 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
2338 {
2339         unsigned long flags;
2340
2341         spin_lock_irqsave(&list->lock, flags);
2342         __skb_unlink(skb, list);
2343         spin_unlock_irqrestore(&list->lock, flags);
2344 }
2345 EXPORT_SYMBOL(skb_unlink);
2346
2347 /**
2348  *      skb_append      -       append a buffer
2349  *      @old: buffer to insert after
2350  *      @newsk: buffer to insert
2351  *      @list: list to use
2352  *
2353  *      Place a packet after a given packet in a list. The list locks are taken
2354  *      and this function is atomic with respect to other list locked calls.
2355  *      A buffer cannot be placed on two lists at the same time.
2356  */
2357 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2358 {
2359         unsigned long flags;
2360
2361         spin_lock_irqsave(&list->lock, flags);
2362         __skb_queue_after(list, old, newsk);
2363         spin_unlock_irqrestore(&list->lock, flags);
2364 }
2365 EXPORT_SYMBOL(skb_append);
2366
2367 /**
2368  *      skb_insert      -       insert a buffer
2369  *      @old: buffer to insert before
2370  *      @newsk: buffer to insert
2371  *      @list: list to use
2372  *
2373  *      Place a packet before a given packet in a list. The list locks are
2374  *      taken and this function is atomic with respect to other list locked
2375  *      calls.
2376  *
2377  *      A buffer cannot be placed on two lists at the same time.
2378  */
2379 void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2380 {
2381         unsigned long flags;
2382
2383         spin_lock_irqsave(&list->lock, flags);
2384         __skb_insert(newsk, old->prev, old, list);
2385         spin_unlock_irqrestore(&list->lock, flags);
2386 }
2387 EXPORT_SYMBOL(skb_insert);
2388
2389 static inline void skb_split_inside_header(struct sk_buff *skb,
2390                                            struct sk_buff* skb1,
2391                                            const u32 len, const int pos)
2392 {
2393         int i;
2394
2395         skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
2396                                          pos - len);
2397         /* And move data appendix as is. */
2398         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2399                 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
2400
2401         skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
2402         skb_shinfo(skb)->nr_frags  = 0;
2403         skb1->data_len             = skb->data_len;
2404         skb1->len                  += skb1->data_len;
2405         skb->data_len              = 0;
2406         skb->len                   = len;
2407         skb_set_tail_pointer(skb, len);
2408 }
2409
2410 static inline void skb_split_no_header(struct sk_buff *skb,
2411                                        struct sk_buff* skb1,
2412                                        const u32 len, int pos)
2413 {
2414         int i, k = 0;
2415         const int nfrags = skb_shinfo(skb)->nr_frags;
2416
2417         skb_shinfo(skb)->nr_frags = 0;
2418         skb1->len                 = skb1->data_len = skb->len - len;
2419         skb->len                  = len;
2420         skb->data_len             = len - pos;
2421
2422         for (i = 0; i < nfrags; i++) {
2423                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2424
2425                 if (pos + size > len) {
2426                         skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
2427
2428                         if (pos < len) {
2429                                 /* Split frag.
2430                                  * We have two variants in this case:
2431                                  * 1. Move all the frag to the second
2432                                  *    part, if it is possible. F.e.
2433                                  *    this approach is mandatory for TUX,
2434                                  *    where splitting is expensive.
2435                                  * 2. Split is accurately. We make this.
2436                                  */
2437                                 skb_frag_ref(skb, i);
2438                                 skb_shinfo(skb1)->frags[0].page_offset += len - pos;
2439                                 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
2440                                 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
2441                                 skb_shinfo(skb)->nr_frags++;
2442                         }
2443                         k++;
2444                 } else
2445                         skb_shinfo(skb)->nr_frags++;
2446                 pos += size;
2447         }
2448         skb_shinfo(skb1)->nr_frags = k;
2449 }
2450
2451 /**
2452  * skb_split - Split fragmented skb to two parts at length len.
2453  * @skb: the buffer to split
2454  * @skb1: the buffer to receive the second part
2455  * @len: new length for skb
2456  */
2457 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
2458 {
2459         int pos = skb_headlen(skb);
2460
2461         skb_shinfo(skb1)->tx_flags = skb_shinfo(skb)->tx_flags & SKBTX_SHARED_FRAG;
2462         if (len < pos)  /* Split line is inside header. */
2463                 skb_split_inside_header(skb, skb1, len, pos);
2464         else            /* Second chunk has no header, nothing to copy. */
2465                 skb_split_no_header(skb, skb1, len, pos);
2466 }
2467 EXPORT_SYMBOL(skb_split);
2468
2469 /* Shifting from/to a cloned skb is a no-go.
2470  *
2471  * Caller cannot keep skb_shinfo related pointers past calling here!
2472  */
2473 static int skb_prepare_for_shift(struct sk_buff *skb)
2474 {
2475         return skb_cloned(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2476 }
2477
2478 /**
2479  * skb_shift - Shifts paged data partially from skb to another
2480  * @tgt: buffer into which tail data gets added
2481  * @skb: buffer from which the paged data comes from
2482  * @shiftlen: shift up to this many bytes
2483  *
2484  * Attempts to shift up to shiftlen worth of bytes, which may be less than
2485  * the length of the skb, from skb to tgt. Returns number bytes shifted.
2486  * It's up to caller to free skb if everything was shifted.
2487  *
2488  * If @tgt runs out of frags, the whole operation is aborted.
2489  *
2490  * Skb cannot include anything else but paged data while tgt is allowed
2491  * to have non-paged data as well.
2492  *
2493  * TODO: full sized shift could be optimized but that would need
2494  * specialized skb free'er to handle frags without up-to-date nr_frags.
2495  */
2496 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
2497 {
2498         int from, to, merge, todo;
2499         struct skb_frag_struct *fragfrom, *fragto;
2500
2501         BUG_ON(shiftlen > skb->len);
2502         BUG_ON(skb_headlen(skb));       /* Would corrupt stream */
2503
2504         todo = shiftlen;
2505         from = 0;
2506         to = skb_shinfo(tgt)->nr_frags;
2507         fragfrom = &skb_shinfo(skb)->frags[from];
2508
2509         /* Actual merge is delayed until the point when we know we can
2510          * commit all, so that we don't have to undo partial changes
2511          */
2512         if (!to ||
2513             !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
2514                               fragfrom->page_offset)) {
2515                 merge = -1;
2516         } else {
2517                 merge = to - 1;
2518
2519                 todo -= skb_frag_size(fragfrom);
2520                 if (todo < 0) {
2521                         if (skb_prepare_for_shift(skb) ||
2522                             skb_prepare_for_shift(tgt))
2523                                 return 0;
2524
2525                         /* All previous frag pointers might be stale! */
2526                         fragfrom = &skb_shinfo(skb)->frags[from];
2527                         fragto = &skb_shinfo(tgt)->frags[merge];
2528
2529                         skb_frag_size_add(fragto, shiftlen);
2530                         skb_frag_size_sub(fragfrom, shiftlen);
2531                         fragfrom->page_offset += shiftlen;
2532
2533                         goto onlymerged;
2534                 }
2535
2536                 from++;
2537         }
2538
2539         /* Skip full, not-fitting skb to avoid expensive operations */
2540         if ((shiftlen == skb->len) &&
2541             (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
2542                 return 0;
2543
2544         if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
2545                 return 0;
2546
2547         while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
2548                 if (to == MAX_SKB_FRAGS)
2549                         return 0;
2550
2551                 fragfrom = &skb_shinfo(skb)->frags[from];
2552                 fragto = &skb_shinfo(tgt)->frags[to];
2553
2554                 if (todo >= skb_frag_size(fragfrom)) {
2555                         *fragto = *fragfrom;
2556                         todo -= skb_frag_size(fragfrom);
2557                         from++;
2558                         to++;
2559
2560                 } else {
2561                         __skb_frag_ref(fragfrom);
2562                         fragto->page = fragfrom->page;
2563                         fragto->page_offset = fragfrom->page_offset;
2564                         skb_frag_size_set(fragto, todo);
2565
2566                         fragfrom->page_offset += todo;
2567                         skb_frag_size_sub(fragfrom, todo);
2568                         todo = 0;
2569
2570                         to++;
2571                         break;
2572                 }
2573         }
2574
2575         /* Ready to "commit" this state change to tgt */
2576         skb_shinfo(tgt)->nr_frags = to;
2577
2578         if (merge >= 0) {
2579                 fragfrom = &skb_shinfo(skb)->frags[0];
2580                 fragto = &skb_shinfo(tgt)->frags[merge];
2581
2582                 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
2583                 __skb_frag_unref(fragfrom);
2584         }
2585
2586         /* Reposition in the original skb */
2587         to = 0;
2588         while (from < skb_shinfo(skb)->nr_frags)
2589                 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
2590         skb_shinfo(skb)->nr_frags = to;
2591
2592         BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
2593
2594 onlymerged:
2595         /* Most likely the tgt won't ever need its checksum anymore, skb on
2596          * the other hand might need it if it needs to be resent
2597          */
2598         tgt->ip_summed = CHECKSUM_PARTIAL;
2599         skb->ip_summed = CHECKSUM_PARTIAL;
2600
2601         /* Yak, is it really working this way? Some helper please? */
2602         skb->len -= shiftlen;
2603         skb->data_len -= shiftlen;
2604         skb->truesize -= shiftlen;
2605         tgt->len += shiftlen;
2606         tgt->data_len += shiftlen;
2607         tgt->truesize += shiftlen;
2608
2609         return shiftlen;
2610 }
2611
2612 /**
2613  * skb_prepare_seq_read - Prepare a sequential read of skb data
2614  * @skb: the buffer to read
2615  * @from: lower offset of data to be read
2616  * @to: upper offset of data to be read
2617  * @st: state variable
2618  *
2619  * Initializes the specified state variable. Must be called before
2620  * invoking skb_seq_read() for the first time.
2621  */
2622 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
2623                           unsigned int to, struct skb_seq_state *st)
2624 {
2625         st->lower_offset = from;
2626         st->upper_offset = to;
2627         st->root_skb = st->cur_skb = skb;
2628         st->frag_idx = st->stepped_offset = 0;
2629         st->frag_data = NULL;
2630 }
2631 EXPORT_SYMBOL(skb_prepare_seq_read);
2632
2633 /**
2634  * skb_seq_read - Sequentially read skb data
2635  * @consumed: number of bytes consumed by the caller so far
2636  * @data: destination pointer for data to be returned
2637  * @st: state variable
2638  *
2639  * Reads a block of skb data at @consumed relative to the
2640  * lower offset specified to skb_prepare_seq_read(). Assigns
2641  * the head of the data block to @data and returns the length
2642  * of the block or 0 if the end of the skb data or the upper
2643  * offset has been reached.
2644  *
2645  * The caller is not required to consume all of the data
2646  * returned, i.e. @consumed is typically set to the number
2647  * of bytes already consumed and the next call to
2648  * skb_seq_read() will return the remaining part of the block.
2649  *
2650  * Note 1: The size of each block of data returned can be arbitrary,
2651  *       this limitation is the cost for zerocopy sequential
2652  *       reads of potentially non linear data.
2653  *
2654  * Note 2: Fragment lists within fragments are not implemented
2655  *       at the moment, state->root_skb could be replaced with
2656  *       a stack for this purpose.
2657  */
2658 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
2659                           struct skb_seq_state *st)
2660 {
2661         unsigned int block_limit, abs_offset = consumed + st->lower_offset;
2662         skb_frag_t *frag;
2663
2664         if (unlikely(abs_offset >= st->upper_offset)) {
2665                 if (st->frag_data) {
2666                         kunmap_atomic(st->frag_data);
2667                         st->frag_data = NULL;
2668                 }
2669                 return 0;
2670         }
2671
2672 next_skb:
2673         block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
2674
2675         if (abs_offset < block_limit && !st->frag_data) {
2676                 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
2677                 return block_limit - abs_offset;
2678         }
2679
2680         if (st->frag_idx == 0 && !st->frag_data)
2681                 st->stepped_offset += skb_headlen(st->cur_skb);
2682
2683         while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
2684                 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
2685                 block_limit = skb_frag_size(frag) + st->stepped_offset;
2686
2687                 if (abs_offset < block_limit) {
2688                         if (!st->frag_data)
2689                                 st->frag_data = kmap_atomic(skb_frag_page(frag));
2690
2691                         *data = (u8 *) st->frag_data + frag->page_offset +
2692                                 (abs_offset - st->stepped_offset);
2693
2694                         return block_limit - abs_offset;
2695                 }
2696
2697                 if (st->frag_data) {
2698                         kunmap_atomic(st->frag_data);
2699                         st->frag_data = NULL;
2700                 }
2701
2702                 st->frag_idx++;
2703                 st->stepped_offset += skb_frag_size(frag);
2704         }
2705
2706         if (st->frag_data) {
2707                 kunmap_atomic(st->frag_data);
2708                 st->frag_data = NULL;
2709         }
2710
2711         if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
2712                 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
2713                 st->frag_idx = 0;
2714                 goto next_skb;
2715         } else if (st->cur_skb->next) {
2716                 st->cur_skb = st->cur_skb->next;
2717                 st->frag_idx = 0;
2718                 goto next_skb;
2719         }
2720
2721         return 0;
2722 }
2723 EXPORT_SYMBOL(skb_seq_read);
2724
2725 /**
2726  * skb_abort_seq_read - Abort a sequential read of skb data
2727  * @st: state variable
2728  *
2729  * Must be called if skb_seq_read() was not called until it
2730  * returned 0.
2731  */
2732 void skb_abort_seq_read(struct skb_seq_state *st)
2733 {
2734         if (st->frag_data)
2735                 kunmap_atomic(st->frag_data);
2736 }
2737 EXPORT_SYMBOL(skb_abort_seq_read);
2738
2739 #define TS_SKB_CB(state)        ((struct skb_seq_state *) &((state)->cb))
2740
2741 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
2742                                           struct ts_config *conf,
2743                                           struct ts_state *state)
2744 {
2745         return skb_seq_read(offset, text, TS_SKB_CB(state));
2746 }
2747
2748 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
2749 {
2750         skb_abort_seq_read(TS_SKB_CB(state));
2751 }
2752
2753 /**
2754  * skb_find_text - Find a text pattern in skb data
2755  * @skb: the buffer to look in
2756  * @from: search offset
2757  * @to: search limit
2758  * @config: textsearch configuration
2759  * @state: uninitialized textsearch state variable
2760  *
2761  * Finds a pattern in the skb data according to the specified
2762  * textsearch configuration. Use textsearch_next() to retrieve
2763  * subsequent occurrences of the pattern. Returns the offset
2764  * to the first occurrence or UINT_MAX if no match was found.
2765  */
2766 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
2767                            unsigned int to, struct ts_config *config,
2768                            struct ts_state *state)
2769 {
2770         unsigned int ret;
2771
2772         config->get_next_block = skb_ts_get_next_block;
2773         config->finish = skb_ts_finish;
2774
2775         skb_prepare_seq_read(skb, from, to, TS_SKB_CB(state));
2776
2777         ret = textsearch_find(config, state);
2778         return (ret <= to - from ? ret : UINT_MAX);
2779 }
2780 EXPORT_SYMBOL(skb_find_text);
2781
2782 /**
2783  * skb_append_datato_frags - append the user data to a skb
2784  * @sk: sock  structure
2785  * @skb: skb structure to be appended with user data.
2786  * @getfrag: call back function to be used for getting the user data
2787  * @from: pointer to user message iov
2788  * @length: length of the iov message
2789  *
2790  * Description: This procedure append the user data in the fragment part
2791  * of the skb if any page alloc fails user this procedure returns  -ENOMEM
2792  */
2793 int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
2794                         int (*getfrag)(void *from, char *to, int offset,
2795                                         int len, int odd, struct sk_buff *skb),
2796                         void *from, int length)
2797 {
2798         int frg_cnt = skb_shinfo(skb)->nr_frags;
2799         int copy;
2800         int offset = 0;
2801         int ret;
2802         struct page_frag *pfrag = &current->task_frag;
2803
2804         do {
2805                 /* Return error if we don't have space for new frag */
2806                 if (frg_cnt >= MAX_SKB_FRAGS)
2807                         return -EMSGSIZE;
2808
2809                 if (!sk_page_frag_refill(sk, pfrag))
2810                         return -ENOMEM;
2811
2812                 /* copy the user data to page */
2813                 copy = min_t(int, length, pfrag->size - pfrag->offset);
2814
2815                 ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
2816                               offset, copy, 0, skb);
2817                 if (ret < 0)
2818                         return -EFAULT;
2819
2820                 /* copy was successful so update the size parameters */
2821                 skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
2822                                    copy);
2823                 frg_cnt++;
2824                 pfrag->offset += copy;
2825                 get_page(pfrag->page);
2826
2827                 skb->truesize += copy;
2828                 atomic_add(copy, &sk->sk_wmem_alloc);
2829                 skb->len += copy;
2830                 skb->data_len += copy;
2831                 offset += copy;
2832                 length -= copy;
2833
2834         } while (length > 0);
2835
2836         return 0;
2837 }
2838 EXPORT_SYMBOL(skb_append_datato_frags);
2839
2840 /**
2841  *      skb_pull_rcsum - pull skb and update receive checksum
2842  *      @skb: buffer to update
2843  *      @len: length of data pulled
2844  *
2845  *      This function performs an skb_pull on the packet and updates
2846  *      the CHECKSUM_COMPLETE checksum.  It should be used on
2847  *      receive path processing instead of skb_pull unless you know
2848  *      that the checksum difference is zero (e.g., a valid IP header)
2849  *      or you are setting ip_summed to CHECKSUM_NONE.
2850  */
2851 unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
2852 {
2853         BUG_ON(len > skb->len);
2854         skb->len -= len;
2855         BUG_ON(skb->len < skb->data_len);
2856         skb_postpull_rcsum(skb, skb->data, len);
2857         return skb->data += len;
2858 }
2859 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
2860
2861 /**
2862  *      skb_segment - Perform protocol segmentation on skb.
2863  *      @head_skb: buffer to segment
2864  *      @features: features for the output path (see dev->features)
2865  *
2866  *      This function performs segmentation on the given skb.  It returns
2867  *      a pointer to the first in a list of new skbs for the segments.
2868  *      In case of error it returns ERR_PTR(err).
2869  */
2870 struct sk_buff *skb_segment(struct sk_buff *head_skb,
2871                             netdev_features_t features)
2872 {
2873         struct sk_buff *segs = NULL;
2874         struct sk_buff *tail = NULL;
2875         struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
2876         skb_frag_t *frag = skb_shinfo(head_skb)->frags;
2877         unsigned int mss = skb_shinfo(head_skb)->gso_size;
2878         unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
2879         struct sk_buff *frag_skb = head_skb;
2880         unsigned int offset = doffset;
2881         unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
2882         unsigned int headroom;
2883         unsigned int len;
2884         __be16 proto;
2885         bool csum;
2886         int sg = !!(features & NETIF_F_SG);
2887         int nfrags = skb_shinfo(head_skb)->nr_frags;
2888         int err = -ENOMEM;
2889         int i = 0;
2890         int pos;
2891         int dummy;
2892
2893         __skb_push(head_skb, doffset);
2894         proto = skb_network_protocol(head_skb, &dummy);
2895         if (unlikely(!proto))
2896                 return ERR_PTR(-EINVAL);
2897
2898         csum = !head_skb->encap_hdr_csum &&
2899             !!can_checksum_protocol(features, proto);
2900
2901         headroom = skb_headroom(head_skb);
2902         pos = skb_headlen(head_skb);
2903
2904         do {
2905                 struct sk_buff *nskb;
2906                 skb_frag_t *nskb_frag;
2907                 int hsize;
2908                 int size;
2909
2910                 len = head_skb->len - offset;
2911                 if (len > mss)
2912                         len = mss;
2913
2914                 hsize = skb_headlen(head_skb) - offset;
2915                 if (hsize < 0)
2916                         hsize = 0;
2917                 if (hsize > len || !sg)
2918                         hsize = len;
2919
2920                 if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
2921                     (skb_headlen(list_skb) == len || sg)) {
2922                         BUG_ON(skb_headlen(list_skb) > len);
2923
2924                         i = 0;
2925                         nfrags = skb_shinfo(list_skb)->nr_frags;
2926                         frag = skb_shinfo(list_skb)->frags;
2927                         frag_skb = list_skb;
2928                         pos += skb_headlen(list_skb);
2929
2930                         while (pos < offset + len) {
2931                                 BUG_ON(i >= nfrags);
2932
2933                                 size = skb_frag_size(frag);
2934                                 if (pos + size > offset + len)
2935                                         break;
2936
2937                                 i++;
2938                                 pos += size;
2939                                 frag++;
2940                         }
2941
2942                         nskb = skb_clone(list_skb, GFP_ATOMIC);
2943                         list_skb = list_skb->next;
2944
2945                         if (unlikely(!nskb))
2946                                 goto err;
2947
2948                         if (unlikely(pskb_trim(nskb, len))) {
2949                                 kfree_skb(nskb);
2950                                 goto err;
2951                         }
2952
2953                         hsize = skb_end_offset(nskb);
2954                         if (skb_cow_head(nskb, doffset + headroom)) {
2955                                 kfree_skb(nskb);
2956                                 goto err;
2957                         }
2958
2959                         nskb->truesize += skb_end_offset(nskb) - hsize;
2960                         skb_release_head_state(nskb);
2961                         __skb_push(nskb, doffset);
2962                 } else {
2963                         nskb = __alloc_skb(hsize + doffset + headroom,
2964                                            GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
2965                                            NUMA_NO_NODE);
2966
2967                         if (unlikely(!nskb))
2968                                 goto err;
2969
2970                         skb_reserve(nskb, headroom);
2971                         __skb_put(nskb, doffset);
2972                 }
2973
2974                 if (segs)
2975                         tail->next = nskb;
2976                 else
2977                         segs = nskb;
2978                 tail = nskb;
2979
2980                 __copy_skb_header(nskb, head_skb);
2981
2982                 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
2983                 skb_reset_mac_len(nskb);
2984
2985                 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
2986                                                  nskb->data - tnl_hlen,
2987                                                  doffset + tnl_hlen);
2988
2989                 if (nskb->len == len + doffset)
2990                         goto perform_csum_check;
2991
2992                 if (!sg) {
2993                         nskb->ip_summed = CHECKSUM_NONE;
2994                         nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
2995                                                             skb_put(nskb, len),
2996                                                             len, 0);
2997                         SKB_GSO_CB(nskb)->csum_start =
2998                             skb_headroom(nskb) + doffset;
2999                         continue;
3000                 }
3001
3002                 nskb_frag = skb_shinfo(nskb)->frags;
3003
3004                 skb_copy_from_linear_data_offset(head_skb, offset,
3005                                                  skb_put(nskb, hsize), hsize);
3006
3007                 skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
3008                         SKBTX_SHARED_FRAG;
3009
3010                 while (pos < offset + len) {
3011                         if (i >= nfrags) {
3012                                 BUG_ON(skb_headlen(list_skb));
3013
3014                                 i = 0;
3015                                 nfrags = skb_shinfo(list_skb)->nr_frags;
3016                                 frag = skb_shinfo(list_skb)->frags;
3017                                 frag_skb = list_skb;
3018
3019                                 BUG_ON(!nfrags);
3020
3021                                 list_skb = list_skb->next;
3022                         }
3023
3024                         if (unlikely(skb_shinfo(nskb)->nr_frags >=
3025                                      MAX_SKB_FRAGS)) {
3026                                 net_warn_ratelimited(
3027                                         "skb_segment: too many frags: %u %u\n",
3028                                         pos, mss);
3029                                 goto err;
3030                         }
3031
3032                         if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
3033                                 goto err;
3034
3035                         *nskb_frag = *frag;
3036                         __skb_frag_ref(nskb_frag);
3037                         size = skb_frag_size(nskb_frag);
3038
3039                         if (pos < offset) {
3040                                 nskb_frag->page_offset += offset - pos;
3041                                 skb_frag_size_sub(nskb_frag, offset - pos);
3042                         }
3043
3044                         skb_shinfo(nskb)->nr_frags++;
3045
3046                         if (pos + size <= offset + len) {
3047                                 i++;
3048                                 frag++;
3049                                 pos += size;
3050                         } else {
3051                                 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
3052                                 goto skip_fraglist;
3053                         }
3054
3055                         nskb_frag++;
3056                 }
3057
3058 skip_fraglist:
3059                 nskb->data_len = len - hsize;
3060                 nskb->len += nskb->data_len;
3061                 nskb->truesize += nskb->data_len;
3062
3063 perform_csum_check:
3064                 if (!csum) {
3065                         nskb->csum = skb_checksum(nskb, doffset,
3066                                                   nskb->len - doffset, 0);
3067                         nskb->ip_summed = CHECKSUM_NONE;
3068                         SKB_GSO_CB(nskb)->csum_start =
3069                             skb_headroom(nskb) + doffset;
3070                 }
3071         } while ((offset += len) < head_skb->len);
3072
3073         return segs;
3074
3075 err:
3076         kfree_skb_list(segs);
3077         return ERR_PTR(err);
3078 }
3079 EXPORT_SYMBOL_GPL(skb_segment);
3080
3081 int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
3082 {
3083         struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
3084         unsigned int offset = skb_gro_offset(skb);
3085         unsigned int headlen = skb_headlen(skb);
3086         struct sk_buff *nskb, *lp, *p = *head;
3087         unsigned int len = skb_gro_len(skb);
3088         unsigned int delta_truesize;
3089         unsigned int headroom;
3090
3091         if (unlikely(p->len + len >= 65536))
3092                 return -E2BIG;
3093
3094         lp = NAPI_GRO_CB(p)->last;
3095         pinfo = skb_shinfo(lp);
3096
3097         if (headlen <= offset) {
3098                 skb_frag_t *frag;
3099                 skb_frag_t *frag2;
3100                 int i = skbinfo->nr_frags;
3101                 int nr_frags = pinfo->nr_frags + i;
3102
3103                 if (nr_frags > MAX_SKB_FRAGS)
3104                         goto merge;
3105
3106                 offset -= headlen;
3107                 pinfo->nr_frags = nr_frags;
3108                 skbinfo->nr_frags = 0;
3109
3110                 frag = pinfo->frags + nr_frags;
3111                 frag2 = skbinfo->frags + i;
3112                 do {
3113                         *--frag = *--frag2;
3114                 } while (--i);
3115
3116                 frag->page_offset += offset;
3117                 skb_frag_size_sub(frag, offset);
3118
3119                 /* all fragments truesize : remove (head size + sk_buff) */
3120                 delta_truesize = skb->truesize -
3121                                  SKB_TRUESIZE(skb_end_offset(skb));
3122
3123                 skb->truesize -= skb->data_len;
3124                 skb->len -= skb->data_len;
3125                 skb->data_len = 0;
3126
3127                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
3128                 goto done;
3129         } else if (skb->head_frag) {
3130                 int nr_frags = pinfo->nr_frags;
3131                 skb_frag_t *frag = pinfo->frags + nr_frags;
3132                 struct page *page = virt_to_head_page(skb->head);
3133                 unsigned int first_size = headlen - offset;
3134                 unsigned int first_offset;
3135
3136                 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
3137                         goto merge;
3138
3139                 first_offset = skb->data -
3140                                (unsigned char *)page_address(page) +
3141                                offset;
3142
3143                 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
3144
3145                 frag->page.p      = page;
3146                 frag->page_offset = first_offset;
3147                 skb_frag_size_set(frag, first_size);
3148
3149                 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
3150                 /* We dont need to clear skbinfo->nr_frags here */
3151
3152                 delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
3153                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
3154                 goto done;
3155         }
3156         if (pinfo->frag_list)
3157                 goto merge;
3158         if (skb_gro_len(p) != pinfo->gso_size)
3159                 return -E2BIG;
3160
3161         headroom = skb_headroom(p);
3162         nskb = alloc_skb(headroom + skb_gro_offset(p), GFP_ATOMIC);
3163         if (unlikely(!nskb))
3164                 return -ENOMEM;
3165
3166         __copy_skb_header(nskb, p);
3167         nskb->mac_len = p->mac_len;
3168
3169         skb_reserve(nskb, headroom);
3170         __skb_put(nskb, skb_gro_offset(p));
3171
3172         skb_set_mac_header(nskb, skb_mac_header(p) - p->data);
3173         skb_set_network_header(nskb, skb_network_offset(p));
3174         skb_set_transport_header(nskb, skb_transport_offset(p));
3175
3176         __skb_pull(p, skb_gro_offset(p));
3177         memcpy(skb_mac_header(nskb), skb_mac_header(p),
3178                p->data - skb_mac_header(p));
3179
3180         skb_shinfo(nskb)->frag_list = p;
3181         skb_shinfo(nskb)->gso_size = pinfo->gso_size;
3182         pinfo->gso_size = 0;
3183         __skb_header_release(p);
3184         NAPI_GRO_CB(nskb)->last = p;
3185
3186         nskb->data_len += p->len;
3187         nskb->truesize += p->truesize;
3188         nskb->len += p->len;
3189
3190         *head = nskb;
3191         nskb->next = p->next;
3192         p->next = NULL;
3193
3194         p = nskb;
3195
3196 merge:
3197         delta_truesize = skb->truesize;
3198         if (offset > headlen) {
3199                 unsigned int eat = offset - headlen;
3200
3201                 skbinfo->frags[0].page_offset += eat;
3202                 skb_frag_size_sub(&skbinfo->frags[0], eat);
3203                 skb->data_len -= eat;
3204                 skb->len -= eat;
3205                 offset = headlen;
3206         }
3207
3208         __skb_pull(skb, offset);
3209
3210         if (NAPI_GRO_CB(p)->last == p)
3211                 skb_shinfo(p)->frag_list = skb;
3212         else
3213                 NAPI_GRO_CB(p)->last->next = skb;
3214         NAPI_GRO_CB(p)->last = skb;
3215         __skb_header_release(skb);
3216         lp = p;
3217
3218 done:
3219         NAPI_GRO_CB(p)->count++;
3220         p->data_len += len;
3221         p->truesize += delta_truesize;
3222         p->len += len;
3223         if (lp != p) {
3224                 lp->data_len += len;
3225                 lp->truesize += delta_truesize;
3226                 lp->len += len;
3227         }
3228         NAPI_GRO_CB(skb)->same_flow = 1;
3229         return 0;
3230 }
3231 EXPORT_SYMBOL_GPL(skb_gro_receive);
3232
3233 void __init skb_init(void)
3234 {
3235         skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
3236                                               sizeof(struct sk_buff),
3237                                               0,
3238                                               SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3239                                               NULL);
3240         skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
3241                                                 (2*sizeof(struct sk_buff)) +
3242                                                 sizeof(atomic_t),
3243                                                 0,
3244                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3245                                                 NULL);
3246 }
3247
3248 /**
3249  *      skb_to_sgvec - Fill a scatter-gather list from a socket buffer
3250  *      @skb: Socket buffer containing the buffers to be mapped
3251  *      @sg: The scatter-gather list to map into
3252  *      @offset: The offset into the buffer's contents to start mapping
3253  *      @len: Length of buffer space to be mapped
3254  *
3255  *      Fill the specified scatter-gather list with mappings/pointers into a
3256  *      region of the buffer space attached to a socket buffer.
3257  */
3258 static int
3259 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
3260 {
3261         int start = skb_headlen(skb);
3262         int i, copy = start - offset;
3263         struct sk_buff *frag_iter;
3264         int elt = 0;
3265
3266         if (copy > 0) {
3267                 if (copy > len)
3268                         copy = len;
3269                 sg_set_buf(sg, skb->data + offset, copy);
3270                 elt++;
3271                 if ((len -= copy) == 0)
3272                         return elt;
3273                 offset += copy;
3274         }
3275
3276         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3277                 int end;
3278
3279                 WARN_ON(start > offset + len);
3280
3281                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3282                 if ((copy = end - offset) > 0) {
3283                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3284
3285                         if (copy > len)
3286                                 copy = len;
3287                         sg_set_page(&sg[elt], skb_frag_page(frag), copy,
3288                                         frag->page_offset+offset-start);
3289                         elt++;
3290                         if (!(len -= copy))
3291                                 return elt;
3292                         offset += copy;
3293                 }
3294                 start = end;
3295         }
3296
3297         skb_walk_frags(skb, frag_iter) {
3298                 int end;
3299
3300                 WARN_ON(start > offset + len);
3301
3302                 end = start + frag_iter->len;
3303                 if ((copy = end - offset) > 0) {
3304                         if (copy > len)
3305                                 copy = len;
3306                         elt += __skb_to_sgvec(frag_iter, sg+elt, offset - start,
3307                                               copy);
3308                         if ((len -= copy) == 0)
3309                                 return elt;
3310                         offset += copy;
3311                 }
3312                 start = end;
3313         }
3314         BUG_ON(len);
3315         return elt;
3316 }
3317
3318 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
3319  * sglist without mark the sg which contain last skb data as the end.
3320  * So the caller can mannipulate sg list as will when padding new data after
3321  * the first call without calling sg_unmark_end to expend sg list.
3322  *
3323  * Scenario to use skb_to_sgvec_nomark:
3324  * 1. sg_init_table
3325  * 2. skb_to_sgvec_nomark(payload1)
3326  * 3. skb_to_sgvec_nomark(payload2)
3327  *
3328  * This is equivalent to:
3329  * 1. sg_init_table
3330  * 2. skb_to_sgvec(payload1)
3331  * 3. sg_unmark_end
3332  * 4. skb_to_sgvec(payload2)
3333  *
3334  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
3335  * is more preferable.
3336  */
3337 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
3338                         int offset, int len)
3339 {
3340         return __skb_to_sgvec(skb, sg, offset, len);
3341 }
3342 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
3343
3344 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
3345 {
3346         int nsg = __skb_to_sgvec(skb, sg, offset, len);
3347
3348         sg_mark_end(&sg[nsg - 1]);
3349
3350         return nsg;
3351 }
3352 EXPORT_SYMBOL_GPL(skb_to_sgvec);
3353
3354 /**
3355  *      skb_cow_data - Check that a socket buffer's data buffers are writable
3356  *      @skb: The socket buffer to check.
3357  *      @tailbits: Amount of trailing space to be added
3358  *      @trailer: Returned pointer to the skb where the @tailbits space begins
3359  *
3360  *      Make sure that the data buffers attached to a socket buffer are
3361  *      writable. If they are not, private copies are made of the data buffers
3362  *      and the socket buffer is set to use these instead.
3363  *
3364  *      If @tailbits is given, make sure that there is space to write @tailbits
3365  *      bytes of data beyond current end of socket buffer.  @trailer will be
3366  *      set to point to the skb in which this space begins.
3367  *
3368  *      The number of scatterlist elements required to completely map the
3369  *      COW'd and extended socket buffer will be returned.
3370  */
3371 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
3372 {
3373         int copyflag;
3374         int elt;
3375         struct sk_buff *skb1, **skb_p;
3376
3377         /* If skb is cloned or its head is paged, reallocate
3378          * head pulling out all the pages (pages are considered not writable
3379          * at the moment even if they are anonymous).
3380          */
3381         if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
3382             __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
3383                 return -ENOMEM;
3384
3385         /* Easy case. Most of packets will go this way. */
3386         if (!skb_has_frag_list(skb)) {
3387                 /* A little of trouble, not enough of space for trailer.
3388                  * This should not happen, when stack is tuned to generate
3389                  * good frames. OK, on miss we reallocate and reserve even more
3390                  * space, 128 bytes is fair. */
3391
3392                 if (skb_tailroom(skb) < tailbits &&
3393                     pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
3394                         return -ENOMEM;
3395
3396                 /* Voila! */
3397                 *trailer = skb;
3398                 return 1;
3399         }
3400
3401         /* Misery. We are in troubles, going to mincer fragments... */
3402
3403         elt = 1;
3404         skb_p = &skb_shinfo(skb)->frag_list;
3405         copyflag = 0;
3406
3407         while ((skb1 = *skb_p) != NULL) {
3408                 int ntail = 0;
3409
3410                 /* The fragment is partially pulled by someone,
3411                  * this can happen on input. Copy it and everything
3412                  * after it. */
3413
3414                 if (skb_shared(skb1))
3415                         copyflag = 1;
3416
3417                 /* If the skb is the last, worry about trailer. */
3418
3419                 if (skb1->next == NULL && tailbits) {
3420                         if (skb_shinfo(skb1)->nr_frags ||
3421                             skb_has_frag_list(skb1) ||
3422                             skb_tailroom(skb1) < tailbits)
3423                                 ntail = tailbits + 128;
3424                 }
3425
3426                 if (copyflag ||
3427                     skb_cloned(skb1) ||
3428                     ntail ||
3429                     skb_shinfo(skb1)->nr_frags ||
3430                     skb_has_frag_list(skb1)) {
3431                         struct sk_buff *skb2;
3432
3433                         /* Fuck, we are miserable poor guys... */
3434                         if (ntail == 0)
3435                                 skb2 = skb_copy(skb1, GFP_ATOMIC);
3436                         else
3437                                 skb2 = skb_copy_expand(skb1,
3438                                                        skb_headroom(skb1),
3439                                                        ntail,
3440                                                        GFP_ATOMIC);
3441                         if (unlikely(skb2 == NULL))
3442                                 return -ENOMEM;
3443
3444                         if (skb1->sk)
3445                                 skb_set_owner_w(skb2, skb1->sk);
3446
3447                         /* Looking around. Are we still alive?
3448                          * OK, link new skb, drop old one */
3449
3450                         skb2->next = skb1->next;
3451                         *skb_p = skb2;
3452                         kfree_skb(skb1);
3453                         skb1 = skb2;
3454                 }
3455                 elt++;
3456                 *trailer = skb1;
3457                 skb_p = &skb1->next;
3458         }
3459
3460         return elt;
3461 }
3462 EXPORT_SYMBOL_GPL(skb_cow_data);
3463
3464 static void sock_rmem_free(struct sk_buff *skb)
3465 {
3466         struct sock *sk = skb->sk;
3467
3468         atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
3469 }
3470
3471 /*
3472  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
3473  */
3474 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
3475 {
3476         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
3477             (unsigned int)sk->sk_rcvbuf)
3478                 return -ENOMEM;
3479
3480         skb_orphan(skb);
3481         skb->sk = sk;
3482         skb->destructor = sock_rmem_free;
3483         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
3484
3485         /* before exiting rcu section, make sure dst is refcounted */
3486         skb_dst_force(skb);
3487
3488         skb_queue_tail(&sk->sk_error_queue, skb);
3489         if (!sock_flag(sk, SOCK_DEAD))
3490                 sk->sk_data_ready(sk);
3491         return 0;
3492 }
3493 EXPORT_SYMBOL(sock_queue_err_skb);
3494
3495 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
3496 {
3497         struct sk_buff_head *q = &sk->sk_error_queue;
3498         struct sk_buff *skb, *skb_next;
3499         int err = 0;
3500
3501         spin_lock_bh(&q->lock);
3502         skb = __skb_dequeue(q);
3503         if (skb && (skb_next = skb_peek(q)))
3504                 err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
3505         spin_unlock_bh(&q->lock);
3506
3507         sk->sk_err = err;
3508         if (err)
3509                 sk->sk_error_report(sk);
3510
3511         return skb;
3512 }
3513 EXPORT_SYMBOL(sock_dequeue_err_skb);
3514
3515 /**
3516  * skb_clone_sk - create clone of skb, and take reference to socket
3517  * @skb: the skb to clone
3518  *
3519  * This function creates a clone of a buffer that holds a reference on
3520  * sk_refcnt.  Buffers created via this function are meant to be
3521  * returned using sock_queue_err_skb, or free via kfree_skb.
3522  *
3523  * When passing buffers allocated with this function to sock_queue_err_skb
3524  * it is necessary to wrap the call with sock_hold/sock_put in order to
3525  * prevent the socket from being released prior to being enqueued on
3526  * the sk_error_queue.
3527  */
3528 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
3529 {
3530         struct sock *sk = skb->sk;
3531         struct sk_buff *clone;
3532
3533         if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt))
3534                 return NULL;
3535
3536         clone = skb_clone(skb, GFP_ATOMIC);
3537         if (!clone) {
3538                 sock_put(sk);
3539                 return NULL;
3540         }
3541
3542         clone->sk = sk;
3543         clone->destructor = sock_efree;
3544
3545         return clone;
3546 }
3547 EXPORT_SYMBOL(skb_clone_sk);
3548
3549 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
3550                                         struct sock *sk,
3551                                         int tstype)
3552 {
3553         struct sock_exterr_skb *serr;
3554         int err;
3555
3556         serr = SKB_EXT_ERR(skb);
3557         memset(serr, 0, sizeof(*serr));
3558         serr->ee.ee_errno = ENOMSG;
3559         serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
3560         serr->ee.ee_info = tstype;
3561         if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
3562                 serr->ee.ee_data = skb_shinfo(skb)->tskey;
3563                 if (sk->sk_protocol == IPPROTO_TCP)
3564                         serr->ee.ee_data -= sk->sk_tskey;
3565         }
3566
3567         err = sock_queue_err_skb(sk, skb);
3568
3569         if (err)
3570                 kfree_skb(skb);
3571 }
3572
3573 void skb_complete_tx_timestamp(struct sk_buff *skb,
3574                                struct skb_shared_hwtstamps *hwtstamps)
3575 {
3576         struct sock *sk = skb->sk;
3577
3578         /* take a reference to prevent skb_orphan() from freeing the socket */
3579         sock_hold(sk);
3580
3581         *skb_hwtstamps(skb) = *hwtstamps;
3582         __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
3583
3584         sock_put(sk);
3585 }
3586 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
3587
3588 void __skb_tstamp_tx(struct sk_buff *orig_skb,
3589                      struct skb_shared_hwtstamps *hwtstamps,
3590                      struct sock *sk, int tstype)
3591 {
3592         struct sk_buff *skb;
3593
3594         if (!sk)
3595                 return;
3596
3597         if (hwtstamps)
3598                 *skb_hwtstamps(orig_skb) = *hwtstamps;
3599         else
3600                 orig_skb->tstamp = ktime_get_real();
3601
3602         skb = skb_clone(orig_skb, GFP_ATOMIC);
3603         if (!skb)
3604                 return;
3605
3606         __skb_complete_tx_timestamp(skb, sk, tstype);
3607 }
3608 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
3609
3610 void skb_tstamp_tx(struct sk_buff *orig_skb,
3611                    struct skb_shared_hwtstamps *hwtstamps)
3612 {
3613         return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
3614                                SCM_TSTAMP_SND);
3615 }
3616 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
3617
3618 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
3619 {
3620         struct sock *sk = skb->sk;
3621         struct sock_exterr_skb *serr;
3622         int err;
3623
3624         skb->wifi_acked_valid = 1;
3625         skb->wifi_acked = acked;
3626
3627         serr = SKB_EXT_ERR(skb);
3628         memset(serr, 0, sizeof(*serr));
3629         serr->ee.ee_errno = ENOMSG;
3630         serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
3631
3632         /* take a reference to prevent skb_orphan() from freeing the socket */
3633         sock_hold(sk);
3634
3635         err = sock_queue_err_skb(sk, skb);
3636         if (err)
3637                 kfree_skb(skb);
3638
3639         sock_put(sk);
3640 }
3641 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
3642
3643
3644 /**
3645  * skb_partial_csum_set - set up and verify partial csum values for packet
3646  * @skb: the skb to set
3647  * @start: the number of bytes after skb->data to start checksumming.
3648  * @off: the offset from start to place the checksum.
3649  *
3650  * For untrusted partially-checksummed packets, we need to make sure the values
3651  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
3652  *
3653  * This function checks and sets those values and skb->ip_summed: if this
3654  * returns false you should drop the packet.
3655  */
3656 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
3657 {
3658         if (unlikely(start > skb_headlen(skb)) ||
3659             unlikely((int)start + off > skb_headlen(skb) - 2)) {
3660                 net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
3661                                      start, off, skb_headlen(skb));
3662                 return false;
3663         }
3664         skb->ip_summed = CHECKSUM_PARTIAL;
3665         skb->csum_start = skb_headroom(skb) + start;
3666         skb->csum_offset = off;
3667         skb_set_transport_header(skb, start);
3668         return true;
3669 }
3670 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
3671
3672 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
3673                                unsigned int max)
3674 {
3675         if (skb_headlen(skb) >= len)
3676                 return 0;
3677
3678         /* If we need to pullup then pullup to the max, so we
3679          * won't need to do it again.
3680          */
3681         if (max > skb->len)
3682                 max = skb->len;
3683
3684         if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
3685                 return -ENOMEM;
3686
3687         if (skb_headlen(skb) < len)
3688                 return -EPROTO;
3689
3690         return 0;
3691 }
3692
3693 #define MAX_TCP_HDR_LEN (15 * 4)
3694
3695 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
3696                                       typeof(IPPROTO_IP) proto,
3697                                       unsigned int off)
3698 {
3699         switch (proto) {
3700                 int err;
3701
3702         case IPPROTO_TCP:
3703                 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
3704                                           off + MAX_TCP_HDR_LEN);
3705                 if (!err && !skb_partial_csum_set(skb, off,
3706                                                   offsetof(struct tcphdr,
3707                                                            check)))
3708                         err = -EPROTO;
3709                 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
3710
3711         case IPPROTO_UDP:
3712                 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
3713                                           off + sizeof(struct udphdr));
3714                 if (!err && !skb_partial_csum_set(skb, off,
3715                                                   offsetof(struct udphdr,
3716                                                            check)))
3717                         err = -EPROTO;
3718                 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
3719         }
3720
3721         return ERR_PTR(-EPROTO);
3722 }
3723
3724 /* This value should be large enough to cover a tagged ethernet header plus
3725  * maximally sized IP and TCP or UDP headers.
3726  */
3727 #define MAX_IP_HDR_LEN 128
3728
3729 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
3730 {
3731         unsigned int off;
3732         bool fragment;
3733         __sum16 *csum;
3734         int err;
3735
3736         fragment = false;
3737
3738         err = skb_maybe_pull_tail(skb,
3739                                   sizeof(struct iphdr),
3740                                   MAX_IP_HDR_LEN);
3741         if (err < 0)
3742                 goto out;
3743
3744         if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
3745                 fragment = true;
3746
3747         off = ip_hdrlen(skb);
3748
3749         err = -EPROTO;
3750
3751         if (fragment)
3752                 goto out;
3753
3754         csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
3755         if (IS_ERR(csum))
3756                 return PTR_ERR(csum);
3757
3758         if (recalculate)
3759                 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
3760                                            ip_hdr(skb)->daddr,
3761                                            skb->len - off,
3762                                            ip_hdr(skb)->protocol, 0);
3763         err = 0;
3764
3765 out:
3766         return err;
3767 }
3768
3769 /* This value should be large enough to cover a tagged ethernet header plus
3770  * an IPv6 header, all options, and a maximal TCP or UDP header.
3771  */
3772 #define MAX_IPV6_HDR_LEN 256
3773
3774 #define OPT_HDR(type, skb, off) \
3775         (type *)(skb_network_header(skb) + (off))
3776
3777 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
3778 {
3779         int err;
3780         u8 nexthdr;
3781         unsigned int off;
3782         unsigned int len;
3783         bool fragment;
3784         bool done;
3785         __sum16 *csum;
3786
3787         fragment = false;
3788         done = false;
3789
3790         off = sizeof(struct ipv6hdr);
3791
3792         err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
3793         if (err < 0)
3794                 goto out;
3795
3796         nexthdr = ipv6_hdr(skb)->nexthdr;
3797
3798         len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
3799         while (off <= len && !done) {
3800                 switch (nexthdr) {
3801                 case IPPROTO_DSTOPTS:
3802                 case IPPROTO_HOPOPTS:
3803                 case IPPROTO_ROUTING: {
3804                         struct ipv6_opt_hdr *hp;
3805
3806                         err = skb_maybe_pull_tail(skb,
3807                                                   off +
3808                                                   sizeof(struct ipv6_opt_hdr),
3809                                                   MAX_IPV6_HDR_LEN);
3810                         if (err < 0)
3811                                 goto out;
3812
3813                         hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
3814                         nexthdr = hp->nexthdr;
3815                         off += ipv6_optlen(hp);
3816                         break;
3817                 }
3818                 case IPPROTO_AH: {
3819                         struct ip_auth_hdr *hp;
3820
3821                         err = skb_maybe_pull_tail(skb,
3822                                                   off +
3823                                                   sizeof(struct ip_auth_hdr),
3824                                                   MAX_IPV6_HDR_LEN);
3825                         if (err < 0)
3826                                 goto out;
3827
3828                         hp = OPT_HDR(struct ip_auth_hdr, skb, off);
3829                         nexthdr = hp->nexthdr;
3830                         off += ipv6_authlen(hp);
3831                         break;
3832                 }
3833                 case IPPROTO_FRAGMENT: {
3834                         struct frag_hdr *hp;
3835
3836                         err = skb_maybe_pull_tail(skb,
3837                                                   off +
3838                                                   sizeof(struct frag_hdr),
3839                                                   MAX_IPV6_HDR_LEN);
3840                         if (err < 0)
3841                                 goto out;
3842
3843                         hp = OPT_HDR(struct frag_hdr, skb, off);
3844
3845                         if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
3846                                 fragment = true;
3847
3848                         nexthdr = hp->nexthdr;
3849                         off += sizeof(struct frag_hdr);
3850                         break;
3851                 }
3852                 default:
3853                         done = true;
3854                         break;
3855                 }
3856         }
3857
3858         err = -EPROTO;
3859
3860         if (!done || fragment)
3861                 goto out;
3862
3863         csum = skb_checksum_setup_ip(skb, nexthdr, off);
3864         if (IS_ERR(csum))
3865                 return PTR_ERR(csum);
3866
3867         if (recalculate)
3868                 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
3869                                          &ipv6_hdr(skb)->daddr,
3870                                          skb->len - off, nexthdr, 0);
3871         err = 0;
3872
3873 out:
3874         return err;
3875 }
3876
3877 /**
3878  * skb_checksum_setup - set up partial checksum offset
3879  * @skb: the skb to set up
3880  * @recalculate: if true the pseudo-header checksum will be recalculated
3881  */
3882 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
3883 {
3884         int err;
3885
3886         switch (skb->protocol) {
3887         case htons(ETH_P_IP):
3888                 err = skb_checksum_setup_ipv4(skb, recalculate);
3889                 break;
3890
3891         case htons(ETH_P_IPV6):
3892                 err = skb_checksum_setup_ipv6(skb, recalculate);
3893                 break;
3894
3895         default:
3896                 err = -EPROTO;
3897                 break;
3898         }
3899
3900         return err;
3901 }
3902 EXPORT_SYMBOL(skb_checksum_setup);
3903
3904 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
3905 {
3906         net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
3907                              skb->dev->name);
3908 }
3909 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
3910
3911 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
3912 {
3913         if (head_stolen) {
3914                 skb_release_head_state(skb);
3915                 kmem_cache_free(skbuff_head_cache, skb);
3916         } else {
3917                 __kfree_skb(skb);
3918         }
3919 }
3920 EXPORT_SYMBOL(kfree_skb_partial);
3921
3922 /**
3923  * skb_try_coalesce - try to merge skb to prior one
3924  * @to: prior buffer
3925  * @from: buffer to add
3926  * @fragstolen: pointer to boolean
3927  * @delta_truesize: how much more was allocated than was requested
3928  */
3929 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
3930                       bool *fragstolen, int *delta_truesize)
3931 {
3932         int i, delta, len = from->len;
3933
3934         *fragstolen = false;
3935
3936         if (skb_cloned(to))
3937                 return false;
3938
3939         if (len <= skb_tailroom(to)) {
3940                 if (len)
3941                         BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
3942                 *delta_truesize = 0;
3943                 return true;
3944         }
3945
3946         if (skb_has_frag_list(to) || skb_has_frag_list(from))
3947                 return false;
3948
3949         if (skb_headlen(from) != 0) {
3950                 struct page *page;
3951                 unsigned int offset;
3952
3953                 if (skb_shinfo(to)->nr_frags +
3954                     skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
3955                         return false;
3956
3957                 if (skb_head_is_locked(from))
3958                         return false;
3959
3960                 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
3961
3962                 page = virt_to_head_page(from->head);
3963                 offset = from->data - (unsigned char *)page_address(page);
3964
3965                 skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
3966                                    page, offset, skb_headlen(from));
3967                 *fragstolen = true;
3968         } else {
3969                 if (skb_shinfo(to)->nr_frags +
3970                     skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
3971                         return false;
3972
3973                 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
3974         }
3975
3976         WARN_ON_ONCE(delta < len);
3977
3978         memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
3979                skb_shinfo(from)->frags,
3980                skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
3981         skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
3982
3983         if (!skb_cloned(from))
3984                 skb_shinfo(from)->nr_frags = 0;
3985
3986         /* if the skb is not cloned this does nothing
3987          * since we set nr_frags to 0.
3988          */
3989         for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
3990                 skb_frag_ref(from, i);
3991
3992         to->truesize += delta;
3993         to->len += len;
3994         to->data_len += len;
3995
3996         *delta_truesize = delta;
3997         return true;
3998 }
3999 EXPORT_SYMBOL(skb_try_coalesce);
4000
4001 /**
4002  * skb_scrub_packet - scrub an skb
4003  *
4004  * @skb: buffer to clean
4005  * @xnet: packet is crossing netns
4006  *
4007  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
4008  * into/from a tunnel. Some information have to be cleared during these
4009  * operations.
4010  * skb_scrub_packet can also be used to clean a skb before injecting it in
4011  * another namespace (@xnet == true). We have to clear all information in the
4012  * skb that could impact namespace isolation.
4013  */
4014 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
4015 {
4016         if (xnet)
4017                 skb_orphan(skb);
4018         skb->tstamp.tv64 = 0;
4019         skb->pkt_type = PACKET_HOST;
4020         skb->skb_iif = 0;
4021         skb->ignore_df = 0;
4022         skb_dst_drop(skb);
4023         skb->mark = 0;
4024         secpath_reset(skb);
4025         nf_reset(skb);
4026         nf_reset_trace(skb);
4027 }
4028 EXPORT_SYMBOL_GPL(skb_scrub_packet);
4029
4030 /**
4031  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
4032  *
4033  * @skb: GSO skb
4034  *
4035  * skb_gso_transport_seglen is used to determine the real size of the
4036  * individual segments, including Layer4 headers (TCP/UDP).
4037  *
4038  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
4039  */
4040 unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
4041 {
4042         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4043
4044         if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
4045                 return tcp_hdrlen(skb) + shinfo->gso_size;
4046
4047         /* UFO sets gso_size to the size of the fragmentation
4048          * payload, i.e. the size of the L4 (UDP) header is already
4049          * accounted for.
4050          */
4051         return shinfo->gso_size;
4052 }
4053 EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
4054
4055 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
4056 {
4057         if (skb_cow(skb, skb_headroom(skb)) < 0) {
4058                 kfree_skb(skb);
4059                 return NULL;
4060         }
4061
4062         memmove(skb->data - ETH_HLEN, skb->data - VLAN_ETH_HLEN, 2 * ETH_ALEN);
4063         skb->mac_header += VLAN_HLEN;
4064         return skb;
4065 }
4066
4067 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
4068 {
4069         struct vlan_hdr *vhdr;
4070         u16 vlan_tci;
4071
4072         if (unlikely(vlan_tx_tag_present(skb))) {
4073                 /* vlan_tci is already set-up so leave this for another time */
4074                 return skb;
4075         }
4076
4077         skb = skb_share_check(skb, GFP_ATOMIC);
4078         if (unlikely(!skb))
4079                 goto err_free;
4080
4081         if (unlikely(!pskb_may_pull(skb, VLAN_HLEN)))
4082                 goto err_free;
4083
4084         vhdr = (struct vlan_hdr *)skb->data;
4085         vlan_tci = ntohs(vhdr->h_vlan_TCI);
4086         __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
4087
4088         skb_pull_rcsum(skb, VLAN_HLEN);
4089         vlan_set_encap_proto(skb, vhdr);
4090
4091         skb = skb_reorder_vlan_header(skb);
4092         if (unlikely(!skb))
4093                 goto err_free;
4094
4095         skb_reset_network_header(skb);
4096         skb_reset_transport_header(skb);
4097         skb_reset_mac_len(skb);
4098
4099         return skb;
4100
4101 err_free:
4102         kfree_skb(skb);
4103         return NULL;
4104 }
4105 EXPORT_SYMBOL(skb_vlan_untag);
4106
4107 /**
4108  * alloc_skb_with_frags - allocate skb with page frags
4109  *
4110  * header_len: size of linear part
4111  * data_len: needed length in frags
4112  * max_page_order: max page order desired.
4113  * errcode: pointer to error code if any
4114  * gfp_mask: allocation mask
4115  *
4116  * This can be used to allocate a paged skb, given a maximal order for frags.
4117  */
4118 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
4119                                      unsigned long data_len,
4120                                      int max_page_order,
4121                                      int *errcode,
4122                                      gfp_t gfp_mask)
4123 {
4124         int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
4125         unsigned long chunk;
4126         struct sk_buff *skb;
4127         struct page *page;
4128         gfp_t gfp_head;
4129         int i;
4130
4131         *errcode = -EMSGSIZE;
4132         /* Note this test could be relaxed, if we succeed to allocate
4133          * high order pages...
4134          */
4135         if (npages > MAX_SKB_FRAGS)
4136                 return NULL;
4137
4138         gfp_head = gfp_mask;
4139         if (gfp_head & __GFP_WAIT)
4140                 gfp_head |= __GFP_REPEAT;
4141
4142         *errcode = -ENOBUFS;
4143         skb = alloc_skb(header_len, gfp_head);
4144         if (!skb)
4145                 return NULL;
4146
4147         skb->truesize += npages << PAGE_SHIFT;
4148
4149         for (i = 0; npages > 0; i++) {
4150                 int order = max_page_order;
4151
4152                 while (order) {
4153                         if (npages >= 1 << order) {
4154                                 page = alloc_pages(gfp_mask |
4155                                                    __GFP_COMP |
4156                                                    __GFP_NOWARN |
4157                                                    __GFP_NORETRY,
4158                                                    order);
4159                                 if (page)
4160                                         goto fill_page;
4161                                 /* Do not retry other high order allocations */
4162                                 order = 1;
4163                                 max_page_order = 0;
4164                         }
4165                         order--;
4166                 }
4167                 page = alloc_page(gfp_mask);
4168                 if (!page)
4169                         goto failure;
4170 fill_page:
4171                 chunk = min_t(unsigned long, data_len,
4172                               PAGE_SIZE << order);
4173                 skb_fill_page_desc(skb, i, page, 0, chunk);
4174                 data_len -= chunk;
4175                 npages -= 1 << order;
4176         }
4177         return skb;
4178
4179 failure:
4180         kfree_skb(skb);
4181         return NULL;
4182 }
4183 EXPORT_SYMBOL(alloc_skb_with_frags);