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