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