GNU Linux-libre 4.14.328-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                                 if (skb_is_gso(skb) && !list->head_frag &&
1955                                     skb_headlen(list))
1956                                         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1957
1958                                 if (skb_shared(list)) {
1959                                         /* Sucks! We need to fork list. :-( */
1960                                         clone = skb_clone(list, GFP_ATOMIC);
1961                                         if (!clone)
1962                                                 return NULL;
1963                                         insp = list->next;
1964                                         list = clone;
1965                                 } else {
1966                                         /* This may be pulled without
1967                                          * problems. */
1968                                         insp = list;
1969                                 }
1970                                 if (!pskb_pull(list, eat)) {
1971                                         kfree_skb(clone);
1972                                         return NULL;
1973                                 }
1974                                 break;
1975                         }
1976                 } while (eat);
1977
1978                 /* Free pulled out fragments. */
1979                 while ((list = skb_shinfo(skb)->frag_list) != insp) {
1980                         skb_shinfo(skb)->frag_list = list->next;
1981                         consume_skb(list);
1982                 }
1983                 /* And insert new clone at head. */
1984                 if (clone) {
1985                         clone->next = list;
1986                         skb_shinfo(skb)->frag_list = clone;
1987                 }
1988         }
1989         /* Success! Now we may commit changes to skb data. */
1990
1991 pull_pages:
1992         eat = delta;
1993         k = 0;
1994         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1995                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1996
1997                 if (size <= eat) {
1998                         skb_frag_unref(skb, i);
1999                         eat -= size;
2000                 } else {
2001                         skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
2002                         if (eat) {
2003                                 skb_shinfo(skb)->frags[k].page_offset += eat;
2004                                 skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
2005                                 if (!i)
2006                                         goto end;
2007                                 eat = 0;
2008                         }
2009                         k++;
2010                 }
2011         }
2012         skb_shinfo(skb)->nr_frags = k;
2013
2014 end:
2015         skb->tail     += delta;
2016         skb->data_len -= delta;
2017
2018         if (!skb->data_len)
2019                 skb_zcopy_clear(skb, false);
2020
2021         return skb_tail_pointer(skb);
2022 }
2023 EXPORT_SYMBOL(__pskb_pull_tail);
2024
2025 /**
2026  *      skb_copy_bits - copy bits from skb to kernel buffer
2027  *      @skb: source skb
2028  *      @offset: offset in source
2029  *      @to: destination buffer
2030  *      @len: number of bytes to copy
2031  *
2032  *      Copy the specified number of bytes from the source skb to the
2033  *      destination buffer.
2034  *
2035  *      CAUTION ! :
2036  *              If its prototype is ever changed,
2037  *              check arch/{*}/net/{*}.S files,
2038  *              since it is called from BPF assembly code.
2039  */
2040 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2041 {
2042         int start = skb_headlen(skb);
2043         struct sk_buff *frag_iter;
2044         int i, copy;
2045
2046         if (offset > (int)skb->len - len)
2047                 goto fault;
2048
2049         /* Copy header. */
2050         if ((copy = start - offset) > 0) {
2051                 if (copy > len)
2052                         copy = len;
2053                 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2054                 if ((len -= copy) == 0)
2055                         return 0;
2056                 offset += copy;
2057                 to     += copy;
2058         }
2059
2060         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2061                 int end;
2062                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2063
2064                 WARN_ON(start > offset + len);
2065
2066                 end = start + skb_frag_size(f);
2067                 if ((copy = end - offset) > 0) {
2068                         u32 p_off, p_len, copied;
2069                         struct page *p;
2070                         u8 *vaddr;
2071
2072                         if (copy > len)
2073                                 copy = len;
2074
2075                         skb_frag_foreach_page(f,
2076                                               f->page_offset + offset - start,
2077                                               copy, p, p_off, p_len, copied) {
2078                                 vaddr = kmap_atomic(p);
2079                                 memcpy(to + copied, vaddr + p_off, p_len);
2080                                 kunmap_atomic(vaddr);
2081                         }
2082
2083                         if ((len -= copy) == 0)
2084                                 return 0;
2085                         offset += copy;
2086                         to     += copy;
2087                 }
2088                 start = end;
2089         }
2090
2091         skb_walk_frags(skb, frag_iter) {
2092                 int end;
2093
2094                 WARN_ON(start > offset + len);
2095
2096                 end = start + frag_iter->len;
2097                 if ((copy = end - offset) > 0) {
2098                         if (copy > len)
2099                                 copy = len;
2100                         if (skb_copy_bits(frag_iter, offset - start, to, copy))
2101                                 goto fault;
2102                         if ((len -= copy) == 0)
2103                                 return 0;
2104                         offset += copy;
2105                         to     += copy;
2106                 }
2107                 start = end;
2108         }
2109
2110         if (!len)
2111                 return 0;
2112
2113 fault:
2114         return -EFAULT;
2115 }
2116 EXPORT_SYMBOL(skb_copy_bits);
2117
2118 /*
2119  * Callback from splice_to_pipe(), if we need to release some pages
2120  * at the end of the spd in case we error'ed out in filling the pipe.
2121  */
2122 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2123 {
2124         put_page(spd->pages[i]);
2125 }
2126
2127 static struct page *linear_to_page(struct page *page, unsigned int *len,
2128                                    unsigned int *offset,
2129                                    struct sock *sk)
2130 {
2131         struct page_frag *pfrag = sk_page_frag(sk);
2132
2133         if (!sk_page_frag_refill(sk, pfrag))
2134                 return NULL;
2135
2136         *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2137
2138         memcpy(page_address(pfrag->page) + pfrag->offset,
2139                page_address(page) + *offset, *len);
2140         *offset = pfrag->offset;
2141         pfrag->offset += *len;
2142
2143         return pfrag->page;
2144 }
2145
2146 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2147                              struct page *page,
2148                              unsigned int offset)
2149 {
2150         return  spd->nr_pages &&
2151                 spd->pages[spd->nr_pages - 1] == page &&
2152                 (spd->partial[spd->nr_pages - 1].offset +
2153                  spd->partial[spd->nr_pages - 1].len == offset);
2154 }
2155
2156 /*
2157  * Fill page/offset/length into spd, if it can hold more pages.
2158  */
2159 static bool spd_fill_page(struct splice_pipe_desc *spd,
2160                           struct pipe_inode_info *pipe, struct page *page,
2161                           unsigned int *len, unsigned int offset,
2162                           bool linear,
2163                           struct sock *sk)
2164 {
2165         if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2166                 return true;
2167
2168         if (linear) {
2169                 page = linear_to_page(page, len, &offset, sk);
2170                 if (!page)
2171                         return true;
2172         }
2173         if (spd_can_coalesce(spd, page, offset)) {
2174                 spd->partial[spd->nr_pages - 1].len += *len;
2175                 return false;
2176         }
2177         get_page(page);
2178         spd->pages[spd->nr_pages] = page;
2179         spd->partial[spd->nr_pages].len = *len;
2180         spd->partial[spd->nr_pages].offset = offset;
2181         spd->nr_pages++;
2182
2183         return false;
2184 }
2185
2186 static bool __splice_segment(struct page *page, unsigned int poff,
2187                              unsigned int plen, unsigned int *off,
2188                              unsigned int *len,
2189                              struct splice_pipe_desc *spd, bool linear,
2190                              struct sock *sk,
2191                              struct pipe_inode_info *pipe)
2192 {
2193         if (!*len)
2194                 return true;
2195
2196         /* skip this segment if already processed */
2197         if (*off >= plen) {
2198                 *off -= plen;
2199                 return false;
2200         }
2201
2202         /* ignore any bits we already processed */
2203         poff += *off;
2204         plen -= *off;
2205         *off = 0;
2206
2207         do {
2208                 unsigned int flen = min(*len, plen);
2209
2210                 if (spd_fill_page(spd, pipe, page, &flen, poff,
2211                                   linear, sk))
2212                         return true;
2213                 poff += flen;
2214                 plen -= flen;
2215                 *len -= flen;
2216         } while (*len && plen);
2217
2218         return false;
2219 }
2220
2221 /*
2222  * Map linear and fragment data from the skb to spd. It reports true if the
2223  * pipe is full or if we already spliced the requested length.
2224  */
2225 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2226                               unsigned int *offset, unsigned int *len,
2227                               struct splice_pipe_desc *spd, struct sock *sk)
2228 {
2229         int seg;
2230         struct sk_buff *iter;
2231
2232         /* map the linear part :
2233          * If skb->head_frag is set, this 'linear' part is backed by a
2234          * fragment, and if the head is not shared with any clones then
2235          * we can avoid a copy since we own the head portion of this page.
2236          */
2237         if (__splice_segment(virt_to_page(skb->data),
2238                              (unsigned long) skb->data & (PAGE_SIZE - 1),
2239                              skb_headlen(skb),
2240                              offset, len, spd,
2241                              skb_head_is_locked(skb),
2242                              sk, pipe))
2243                 return true;
2244
2245         /*
2246          * then map the fragments
2247          */
2248         for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2249                 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2250
2251                 if (__splice_segment(skb_frag_page(f),
2252                                      f->page_offset, skb_frag_size(f),
2253                                      offset, len, spd, false, sk, pipe))
2254                         return true;
2255         }
2256
2257         skb_walk_frags(skb, iter) {
2258                 if (*offset >= iter->len) {
2259                         *offset -= iter->len;
2260                         continue;
2261                 }
2262                 /* __skb_splice_bits() only fails if the output has no room
2263                  * left, so no point in going over the frag_list for the error
2264                  * case.
2265                  */
2266                 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2267                         return true;
2268         }
2269
2270         return false;
2271 }
2272
2273 /*
2274  * Map data from the skb to a pipe. Should handle both the linear part,
2275  * the fragments, and the frag list.
2276  */
2277 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2278                     struct pipe_inode_info *pipe, unsigned int tlen,
2279                     unsigned int flags)
2280 {
2281         struct partial_page partial[MAX_SKB_FRAGS];
2282         struct page *pages[MAX_SKB_FRAGS];
2283         struct splice_pipe_desc spd = {
2284                 .pages = pages,
2285                 .partial = partial,
2286                 .nr_pages_max = MAX_SKB_FRAGS,
2287                 .ops = &nosteal_pipe_buf_ops,
2288                 .spd_release = sock_spd_release,
2289         };
2290         int ret = 0;
2291
2292         __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2293
2294         if (spd.nr_pages)
2295                 ret = splice_to_pipe(pipe, &spd);
2296
2297         return ret;
2298 }
2299 EXPORT_SYMBOL_GPL(skb_splice_bits);
2300
2301 /* Send skb data on a socket. Socket must be locked. */
2302 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2303                          int len)
2304 {
2305         unsigned int orig_len = len;
2306         struct sk_buff *head = skb;
2307         unsigned short fragidx;
2308         int slen, ret;
2309
2310 do_frag_list:
2311
2312         /* Deal with head data */
2313         while (offset < skb_headlen(skb) && len) {
2314                 struct kvec kv;
2315                 struct msghdr msg;
2316
2317                 slen = min_t(int, len, skb_headlen(skb) - offset);
2318                 kv.iov_base = skb->data + offset;
2319                 kv.iov_len = slen;
2320                 memset(&msg, 0, sizeof(msg));
2321                 msg.msg_flags = MSG_DONTWAIT;
2322
2323                 ret = kernel_sendmsg_locked(sk, &msg, &kv, 1, slen);
2324                 if (ret <= 0)
2325                         goto error;
2326
2327                 offset += ret;
2328                 len -= ret;
2329         }
2330
2331         /* All the data was skb head? */
2332         if (!len)
2333                 goto out;
2334
2335         /* Make offset relative to start of frags */
2336         offset -= skb_headlen(skb);
2337
2338         /* Find where we are in frag list */
2339         for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2340                 skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
2341
2342                 if (offset < frag->size)
2343                         break;
2344
2345                 offset -= frag->size;
2346         }
2347
2348         for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2349                 skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
2350
2351                 slen = min_t(size_t, len, frag->size - offset);
2352
2353                 while (slen) {
2354                         ret = kernel_sendpage_locked(sk, frag->page.p,
2355                                                      frag->page_offset + offset,
2356                                                      slen, MSG_DONTWAIT);
2357                         if (ret <= 0)
2358                                 goto error;
2359
2360                         len -= ret;
2361                         offset += ret;
2362                         slen -= ret;
2363                 }
2364
2365                 offset = 0;
2366         }
2367
2368         if (len) {
2369                 /* Process any frag lists */
2370
2371                 if (skb == head) {
2372                         if (skb_has_frag_list(skb)) {
2373                                 skb = skb_shinfo(skb)->frag_list;
2374                                 goto do_frag_list;
2375                         }
2376                 } else if (skb->next) {
2377                         skb = skb->next;
2378                         goto do_frag_list;
2379                 }
2380         }
2381
2382 out:
2383         return orig_len - len;
2384
2385 error:
2386         return orig_len == len ? ret : orig_len - len;
2387 }
2388 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2389
2390 /* Send skb data on a socket. */
2391 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2392 {
2393         int ret = 0;
2394
2395         lock_sock(sk);
2396         ret = skb_send_sock_locked(sk, skb, offset, len);
2397         release_sock(sk);
2398
2399         return ret;
2400 }
2401 EXPORT_SYMBOL_GPL(skb_send_sock);
2402
2403 /**
2404  *      skb_store_bits - store bits from kernel buffer to skb
2405  *      @skb: destination buffer
2406  *      @offset: offset in destination
2407  *      @from: source buffer
2408  *      @len: number of bytes to copy
2409  *
2410  *      Copy the specified number of bytes from the source buffer to the
2411  *      destination skb.  This function handles all the messy bits of
2412  *      traversing fragment lists and such.
2413  */
2414
2415 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2416 {
2417         int start = skb_headlen(skb);
2418         struct sk_buff *frag_iter;
2419         int i, copy;
2420
2421         if (offset > (int)skb->len - len)
2422                 goto fault;
2423
2424         if ((copy = start - offset) > 0) {
2425                 if (copy > len)
2426                         copy = len;
2427                 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2428                 if ((len -= copy) == 0)
2429                         return 0;
2430                 offset += copy;
2431                 from += copy;
2432         }
2433
2434         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2435                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2436                 int end;
2437
2438                 WARN_ON(start > offset + len);
2439
2440                 end = start + skb_frag_size(frag);
2441                 if ((copy = end - offset) > 0) {
2442                         u32 p_off, p_len, copied;
2443                         struct page *p;
2444                         u8 *vaddr;
2445
2446                         if (copy > len)
2447                                 copy = len;
2448
2449                         skb_frag_foreach_page(frag,
2450                                               frag->page_offset + offset - start,
2451                                               copy, p, p_off, p_len, copied) {
2452                                 vaddr = kmap_atomic(p);
2453                                 memcpy(vaddr + p_off, from + copied, p_len);
2454                                 kunmap_atomic(vaddr);
2455                         }
2456
2457                         if ((len -= copy) == 0)
2458                                 return 0;
2459                         offset += copy;
2460                         from += copy;
2461                 }
2462                 start = end;
2463         }
2464
2465         skb_walk_frags(skb, frag_iter) {
2466                 int end;
2467
2468                 WARN_ON(start > offset + len);
2469
2470                 end = start + frag_iter->len;
2471                 if ((copy = end - offset) > 0) {
2472                         if (copy > len)
2473                                 copy = len;
2474                         if (skb_store_bits(frag_iter, offset - start,
2475                                            from, copy))
2476                                 goto fault;
2477                         if ((len -= copy) == 0)
2478                                 return 0;
2479                         offset += copy;
2480                         from += copy;
2481                 }
2482                 start = end;
2483         }
2484         if (!len)
2485                 return 0;
2486
2487 fault:
2488         return -EFAULT;
2489 }
2490 EXPORT_SYMBOL(skb_store_bits);
2491
2492 /* Checksum skb data. */
2493 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2494                       __wsum csum, const struct skb_checksum_ops *ops)
2495 {
2496         int start = skb_headlen(skb);
2497         int i, copy = start - offset;
2498         struct sk_buff *frag_iter;
2499         int pos = 0;
2500
2501         /* Checksum header. */
2502         if (copy > 0) {
2503                 if (copy > len)
2504                         copy = len;
2505                 csum = ops->update(skb->data + offset, copy, csum);
2506                 if ((len -= copy) == 0)
2507                         return csum;
2508                 offset += copy;
2509                 pos     = copy;
2510         }
2511
2512         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2513                 int end;
2514                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2515
2516                 WARN_ON(start > offset + len);
2517
2518                 end = start + skb_frag_size(frag);
2519                 if ((copy = end - offset) > 0) {
2520                         u32 p_off, p_len, copied;
2521                         struct page *p;
2522                         __wsum csum2;
2523                         u8 *vaddr;
2524
2525                         if (copy > len)
2526                                 copy = len;
2527
2528                         skb_frag_foreach_page(frag,
2529                                               frag->page_offset + offset - start,
2530                                               copy, p, p_off, p_len, copied) {
2531                                 vaddr = kmap_atomic(p);
2532                                 csum2 = ops->update(vaddr + p_off, p_len, 0);
2533                                 kunmap_atomic(vaddr);
2534                                 csum = ops->combine(csum, csum2, pos, p_len);
2535                                 pos += p_len;
2536                         }
2537
2538                         if (!(len -= copy))
2539                                 return csum;
2540                         offset += copy;
2541                 }
2542                 start = end;
2543         }
2544
2545         skb_walk_frags(skb, frag_iter) {
2546                 int end;
2547
2548                 WARN_ON(start > offset + len);
2549
2550                 end = start + frag_iter->len;
2551                 if ((copy = end - offset) > 0) {
2552                         __wsum csum2;
2553                         if (copy > len)
2554                                 copy = len;
2555                         csum2 = __skb_checksum(frag_iter, offset - start,
2556                                                copy, 0, ops);
2557                         csum = ops->combine(csum, csum2, pos, copy);
2558                         if ((len -= copy) == 0)
2559                                 return csum;
2560                         offset += copy;
2561                         pos    += copy;
2562                 }
2563                 start = end;
2564         }
2565         BUG_ON(len);
2566
2567         return csum;
2568 }
2569 EXPORT_SYMBOL(__skb_checksum);
2570
2571 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2572                     int len, __wsum csum)
2573 {
2574         const struct skb_checksum_ops ops = {
2575                 .update  = csum_partial_ext,
2576                 .combine = csum_block_add_ext,
2577         };
2578
2579         return __skb_checksum(skb, offset, len, csum, &ops);
2580 }
2581 EXPORT_SYMBOL(skb_checksum);
2582
2583 /* Both of above in one bottle. */
2584
2585 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2586                                     u8 *to, int len, __wsum csum)
2587 {
2588         int start = skb_headlen(skb);
2589         int i, copy = start - offset;
2590         struct sk_buff *frag_iter;
2591         int pos = 0;
2592
2593         /* Copy header. */
2594         if (copy > 0) {
2595                 if (copy > len)
2596                         copy = len;
2597                 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2598                                                  copy, csum);
2599                 if ((len -= copy) == 0)
2600                         return csum;
2601                 offset += copy;
2602                 to     += copy;
2603                 pos     = copy;
2604         }
2605
2606         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2607                 int end;
2608
2609                 WARN_ON(start > offset + len);
2610
2611                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2612                 if ((copy = end - offset) > 0) {
2613                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2614                         u32 p_off, p_len, copied;
2615                         struct page *p;
2616                         __wsum csum2;
2617                         u8 *vaddr;
2618
2619                         if (copy > len)
2620                                 copy = len;
2621
2622                         skb_frag_foreach_page(frag,
2623                                               frag->page_offset + offset - start,
2624                                               copy, p, p_off, p_len, copied) {
2625                                 vaddr = kmap_atomic(p);
2626                                 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2627                                                                   to + copied,
2628                                                                   p_len, 0);
2629                                 kunmap_atomic(vaddr);
2630                                 csum = csum_block_add(csum, csum2, pos);
2631                                 pos += p_len;
2632                         }
2633
2634                         if (!(len -= copy))
2635                                 return csum;
2636                         offset += copy;
2637                         to     += copy;
2638                 }
2639                 start = end;
2640         }
2641
2642         skb_walk_frags(skb, frag_iter) {
2643                 __wsum csum2;
2644                 int end;
2645
2646                 WARN_ON(start > offset + len);
2647
2648                 end = start + frag_iter->len;
2649                 if ((copy = end - offset) > 0) {
2650                         if (copy > len)
2651                                 copy = len;
2652                         csum2 = skb_copy_and_csum_bits(frag_iter,
2653                                                        offset - start,
2654                                                        to, copy, 0);
2655                         csum = csum_block_add(csum, csum2, pos);
2656                         if ((len -= copy) == 0)
2657                                 return csum;
2658                         offset += copy;
2659                         to     += copy;
2660                         pos    += copy;
2661                 }
2662                 start = end;
2663         }
2664         BUG_ON(len);
2665         return csum;
2666 }
2667 EXPORT_SYMBOL(skb_copy_and_csum_bits);
2668
2669 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
2670 {
2671         net_warn_ratelimited(
2672                 "%s: attempt to compute crc32c without libcrc32c.ko\n",
2673                 __func__);
2674         return 0;
2675 }
2676
2677 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
2678                                        int offset, int len)
2679 {
2680         net_warn_ratelimited(
2681                 "%s: attempt to compute crc32c without libcrc32c.ko\n",
2682                 __func__);
2683         return 0;
2684 }
2685
2686 static const struct skb_checksum_ops default_crc32c_ops = {
2687         .update  = warn_crc32c_csum_update,
2688         .combine = warn_crc32c_csum_combine,
2689 };
2690
2691 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
2692         &default_crc32c_ops;
2693 EXPORT_SYMBOL(crc32c_csum_stub);
2694
2695  /**
2696  *      skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
2697  *      @from: source buffer
2698  *
2699  *      Calculates the amount of linear headroom needed in the 'to' skb passed
2700  *      into skb_zerocopy().
2701  */
2702 unsigned int
2703 skb_zerocopy_headlen(const struct sk_buff *from)
2704 {
2705         unsigned int hlen = 0;
2706
2707         if (!from->head_frag ||
2708             skb_headlen(from) < L1_CACHE_BYTES ||
2709             skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
2710                 hlen = skb_headlen(from);
2711                 if (!hlen)
2712                         hlen = from->len;
2713         }
2714
2715         if (skb_has_frag_list(from))
2716                 hlen = from->len;
2717
2718         return hlen;
2719 }
2720 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
2721
2722 /**
2723  *      skb_zerocopy - Zero copy skb to skb
2724  *      @to: destination buffer
2725  *      @from: source buffer
2726  *      @len: number of bytes to copy from source buffer
2727  *      @hlen: size of linear headroom in destination buffer
2728  *
2729  *      Copies up to `len` bytes from `from` to `to` by creating references
2730  *      to the frags in the source buffer.
2731  *
2732  *      The `hlen` as calculated by skb_zerocopy_headlen() specifies the
2733  *      headroom in the `to` buffer.
2734  *
2735  *      Return value:
2736  *      0: everything is OK
2737  *      -ENOMEM: couldn't orphan frags of @from due to lack of memory
2738  *      -EFAULT: skb_copy_bits() found some problem with skb geometry
2739  */
2740 int
2741 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
2742 {
2743         int i, j = 0;
2744         int plen = 0; /* length of skb->head fragment */
2745         int ret;
2746         struct page *page;
2747         unsigned int offset;
2748
2749         BUG_ON(!from->head_frag && !hlen);
2750
2751         /* dont bother with small payloads */
2752         if (len <= skb_tailroom(to))
2753                 return skb_copy_bits(from, 0, skb_put(to, len), len);
2754
2755         if (hlen) {
2756                 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
2757                 if (unlikely(ret))
2758                         return ret;
2759                 len -= hlen;
2760         } else {
2761                 plen = min_t(int, skb_headlen(from), len);
2762                 if (plen) {
2763                         page = virt_to_head_page(from->head);
2764                         offset = from->data - (unsigned char *)page_address(page);
2765                         __skb_fill_page_desc(to, 0, page, offset, plen);
2766                         get_page(page);
2767                         j = 1;
2768                         len -= plen;
2769                 }
2770         }
2771
2772         to->truesize += len + plen;
2773         to->len += len + plen;
2774         to->data_len += len + plen;
2775
2776         if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
2777                 skb_tx_error(from);
2778                 return -ENOMEM;
2779         }
2780         skb_zerocopy_clone(to, from, GFP_ATOMIC);
2781
2782         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
2783                 if (!len)
2784                         break;
2785                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
2786                 skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
2787                 len -= skb_shinfo(to)->frags[j].size;
2788                 skb_frag_ref(to, j);
2789                 j++;
2790         }
2791         skb_shinfo(to)->nr_frags = j;
2792
2793         return 0;
2794 }
2795 EXPORT_SYMBOL_GPL(skb_zerocopy);
2796
2797 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
2798 {
2799         __wsum csum;
2800         long csstart;
2801
2802         if (skb->ip_summed == CHECKSUM_PARTIAL)
2803                 csstart = skb_checksum_start_offset(skb);
2804         else
2805                 csstart = skb_headlen(skb);
2806
2807         BUG_ON(csstart > skb_headlen(skb));
2808
2809         skb_copy_from_linear_data(skb, to, csstart);
2810
2811         csum = 0;
2812         if (csstart != skb->len)
2813                 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
2814                                               skb->len - csstart, 0);
2815
2816         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2817                 long csstuff = csstart + skb->csum_offset;
2818
2819                 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
2820         }
2821 }
2822 EXPORT_SYMBOL(skb_copy_and_csum_dev);
2823
2824 /**
2825  *      skb_dequeue - remove from the head of the queue
2826  *      @list: list to dequeue from
2827  *
2828  *      Remove the head of the list. The list lock is taken so the function
2829  *      may be used safely with other locking list functions. The head item is
2830  *      returned or %NULL if the list is empty.
2831  */
2832
2833 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
2834 {
2835         unsigned long flags;
2836         struct sk_buff *result;
2837
2838         spin_lock_irqsave(&list->lock, flags);
2839         result = __skb_dequeue(list);
2840         spin_unlock_irqrestore(&list->lock, flags);
2841         return result;
2842 }
2843 EXPORT_SYMBOL(skb_dequeue);
2844
2845 /**
2846  *      skb_dequeue_tail - remove from the tail of the queue
2847  *      @list: list to dequeue from
2848  *
2849  *      Remove the tail of the list. The list lock is taken so the function
2850  *      may be used safely with other locking list functions. The tail item is
2851  *      returned or %NULL if the list is empty.
2852  */
2853 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
2854 {
2855         unsigned long flags;
2856         struct sk_buff *result;
2857
2858         spin_lock_irqsave(&list->lock, flags);
2859         result = __skb_dequeue_tail(list);
2860         spin_unlock_irqrestore(&list->lock, flags);
2861         return result;
2862 }
2863 EXPORT_SYMBOL(skb_dequeue_tail);
2864
2865 /**
2866  *      skb_queue_purge - empty a list
2867  *      @list: list to empty
2868  *
2869  *      Delete all buffers on an &sk_buff list. Each buffer is removed from
2870  *      the list and one reference dropped. This function takes the list
2871  *      lock and is atomic with respect to other list locking functions.
2872  */
2873 void skb_queue_purge(struct sk_buff_head *list)
2874 {
2875         struct sk_buff *skb;
2876         while ((skb = skb_dequeue(list)) != NULL)
2877                 kfree_skb(skb);
2878 }
2879 EXPORT_SYMBOL(skb_queue_purge);
2880
2881 /**
2882  *      skb_rbtree_purge - empty a skb rbtree
2883  *      @root: root of the rbtree to empty
2884  *      Return value: the sum of truesizes of all purged skbs.
2885  *
2886  *      Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
2887  *      the list and one reference dropped. This function does not take
2888  *      any lock. Synchronization should be handled by the caller (e.g., TCP
2889  *      out-of-order queue is protected by the socket lock).
2890  */
2891 unsigned int skb_rbtree_purge(struct rb_root *root)
2892 {
2893         struct rb_node *p = rb_first(root);
2894         unsigned int sum = 0;
2895
2896         while (p) {
2897                 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
2898
2899                 p = rb_next(p);
2900                 rb_erase(&skb->rbnode, root);
2901                 sum += skb->truesize;
2902                 kfree_skb(skb);
2903         }
2904         return sum;
2905 }
2906
2907 /**
2908  *      skb_queue_head - queue a buffer at the list head
2909  *      @list: list to use
2910  *      @newsk: buffer to queue
2911  *
2912  *      Queue a buffer at the start of the list. This function takes the
2913  *      list lock and can be used safely with other locking &sk_buff functions
2914  *      safely.
2915  *
2916  *      A buffer cannot be placed on two lists at the same time.
2917  */
2918 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
2919 {
2920         unsigned long flags;
2921
2922         spin_lock_irqsave(&list->lock, flags);
2923         __skb_queue_head(list, newsk);
2924         spin_unlock_irqrestore(&list->lock, flags);
2925 }
2926 EXPORT_SYMBOL(skb_queue_head);
2927
2928 /**
2929  *      skb_queue_tail - queue a buffer at the list tail
2930  *      @list: list to use
2931  *      @newsk: buffer to queue
2932  *
2933  *      Queue a buffer at the tail of the list. This function takes the
2934  *      list lock and can be used safely with other locking &sk_buff functions
2935  *      safely.
2936  *
2937  *      A buffer cannot be placed on two lists at the same time.
2938  */
2939 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
2940 {
2941         unsigned long flags;
2942
2943         spin_lock_irqsave(&list->lock, flags);
2944         __skb_queue_tail(list, newsk);
2945         spin_unlock_irqrestore(&list->lock, flags);
2946 }
2947 EXPORT_SYMBOL(skb_queue_tail);
2948
2949 /**
2950  *      skb_unlink      -       remove a buffer from a list
2951  *      @skb: buffer to remove
2952  *      @list: list to use
2953  *
2954  *      Remove a packet from a list. The list locks are taken and this
2955  *      function is atomic with respect to other list locked calls
2956  *
2957  *      You must know what list the SKB is on.
2958  */
2959 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
2960 {
2961         unsigned long flags;
2962
2963         spin_lock_irqsave(&list->lock, flags);
2964         __skb_unlink(skb, list);
2965         spin_unlock_irqrestore(&list->lock, flags);
2966 }
2967 EXPORT_SYMBOL(skb_unlink);
2968
2969 /**
2970  *      skb_append      -       append a buffer
2971  *      @old: buffer to insert after
2972  *      @newsk: buffer to insert
2973  *      @list: list to use
2974  *
2975  *      Place a packet after a given packet in a list. The list locks are taken
2976  *      and this function is atomic with respect to other list locked calls.
2977  *      A buffer cannot be placed on two lists at the same time.
2978  */
2979 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2980 {
2981         unsigned long flags;
2982
2983         spin_lock_irqsave(&list->lock, flags);
2984         __skb_queue_after(list, old, newsk);
2985         spin_unlock_irqrestore(&list->lock, flags);
2986 }
2987 EXPORT_SYMBOL(skb_append);
2988
2989 /**
2990  *      skb_insert      -       insert a buffer
2991  *      @old: buffer to insert before
2992  *      @newsk: buffer to insert
2993  *      @list: list to use
2994  *
2995  *      Place a packet before a given packet in a list. The list locks are
2996  *      taken and this function is atomic with respect to other list locked
2997  *      calls.
2998  *
2999  *      A buffer cannot be placed on two lists at the same time.
3000  */
3001 void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3002 {
3003         unsigned long flags;
3004
3005         spin_lock_irqsave(&list->lock, flags);
3006         __skb_insert(newsk, old->prev, old, list);
3007         spin_unlock_irqrestore(&list->lock, flags);
3008 }
3009 EXPORT_SYMBOL(skb_insert);
3010
3011 static inline void skb_split_inside_header(struct sk_buff *skb,
3012                                            struct sk_buff* skb1,
3013                                            const u32 len, const int pos)
3014 {
3015         int i;
3016
3017         skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3018                                          pos - len);
3019         /* And move data appendix as is. */
3020         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3021                 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3022
3023         skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3024         skb_shinfo(skb)->nr_frags  = 0;
3025         skb1->data_len             = skb->data_len;
3026         skb1->len                  += skb1->data_len;
3027         skb->data_len              = 0;
3028         skb->len                   = len;
3029         skb_set_tail_pointer(skb, len);
3030 }
3031
3032 static inline void skb_split_no_header(struct sk_buff *skb,
3033                                        struct sk_buff* skb1,
3034                                        const u32 len, int pos)
3035 {
3036         int i, k = 0;
3037         const int nfrags = skb_shinfo(skb)->nr_frags;
3038
3039         skb_shinfo(skb)->nr_frags = 0;
3040         skb1->len                 = skb1->data_len = skb->len - len;
3041         skb->len                  = len;
3042         skb->data_len             = len - pos;
3043
3044         for (i = 0; i < nfrags; i++) {
3045                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3046
3047                 if (pos + size > len) {
3048                         skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3049
3050                         if (pos < len) {
3051                                 /* Split frag.
3052                                  * We have two variants in this case:
3053                                  * 1. Move all the frag to the second
3054                                  *    part, if it is possible. F.e.
3055                                  *    this approach is mandatory for TUX,
3056                                  *    where splitting is expensive.
3057                                  * 2. Split is accurately. We make this.
3058                                  */
3059                                 skb_frag_ref(skb, i);
3060                                 skb_shinfo(skb1)->frags[0].page_offset += len - pos;
3061                                 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3062                                 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3063                                 skb_shinfo(skb)->nr_frags++;
3064                         }
3065                         k++;
3066                 } else
3067                         skb_shinfo(skb)->nr_frags++;
3068                 pos += size;
3069         }
3070         skb_shinfo(skb1)->nr_frags = k;
3071 }
3072
3073 /**
3074  * skb_split - Split fragmented skb to two parts at length len.
3075  * @skb: the buffer to split
3076  * @skb1: the buffer to receive the second part
3077  * @len: new length for skb
3078  */
3079 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3080 {
3081         int pos = skb_headlen(skb);
3082
3083         skb_shinfo(skb1)->tx_flags |= skb_shinfo(skb)->tx_flags &
3084                                       SKBTX_SHARED_FRAG;
3085         skb_zerocopy_clone(skb1, skb, 0);
3086         if (len < pos)  /* Split line is inside header. */
3087                 skb_split_inside_header(skb, skb1, len, pos);
3088         else            /* Second chunk has no header, nothing to copy. */
3089                 skb_split_no_header(skb, skb1, len, pos);
3090 }
3091 EXPORT_SYMBOL(skb_split);
3092
3093 /* Shifting from/to a cloned skb is a no-go.
3094  *
3095  * Caller cannot keep skb_shinfo related pointers past calling here!
3096  */
3097 static int skb_prepare_for_shift(struct sk_buff *skb)
3098 {
3099         int ret = 0;
3100
3101         if (skb_cloned(skb)) {
3102                 /* Save and restore truesize: pskb_expand_head() may reallocate
3103                  * memory where ksize(kmalloc(S)) != ksize(kmalloc(S)), but we
3104                  * cannot change truesize at this point.
3105                  */
3106                 unsigned int save_truesize = skb->truesize;
3107
3108                 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
3109                 skb->truesize = save_truesize;
3110         }
3111         return ret;
3112 }
3113
3114 /**
3115  * skb_shift - Shifts paged data partially from skb to another
3116  * @tgt: buffer into which tail data gets added
3117  * @skb: buffer from which the paged data comes from
3118  * @shiftlen: shift up to this many bytes
3119  *
3120  * Attempts to shift up to shiftlen worth of bytes, which may be less than
3121  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3122  * It's up to caller to free skb if everything was shifted.
3123  *
3124  * If @tgt runs out of frags, the whole operation is aborted.
3125  *
3126  * Skb cannot include anything else but paged data while tgt is allowed
3127  * to have non-paged data as well.
3128  *
3129  * TODO: full sized shift could be optimized but that would need
3130  * specialized skb free'er to handle frags without up-to-date nr_frags.
3131  */
3132 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3133 {
3134         int from, to, merge, todo;
3135         struct skb_frag_struct *fragfrom, *fragto;
3136
3137         BUG_ON(shiftlen > skb->len);
3138
3139         if (skb_headlen(skb))
3140                 return 0;
3141         if (skb_zcopy(tgt) || skb_zcopy(skb))
3142                 return 0;
3143
3144         todo = shiftlen;
3145         from = 0;
3146         to = skb_shinfo(tgt)->nr_frags;
3147         fragfrom = &skb_shinfo(skb)->frags[from];
3148
3149         /* Actual merge is delayed until the point when we know we can
3150          * commit all, so that we don't have to undo partial changes
3151          */
3152         if (!to ||
3153             !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3154                               fragfrom->page_offset)) {
3155                 merge = -1;
3156         } else {
3157                 merge = to - 1;
3158
3159                 todo -= skb_frag_size(fragfrom);
3160                 if (todo < 0) {
3161                         if (skb_prepare_for_shift(skb) ||
3162                             skb_prepare_for_shift(tgt))
3163                                 return 0;
3164
3165                         /* All previous frag pointers might be stale! */
3166                         fragfrom = &skb_shinfo(skb)->frags[from];
3167                         fragto = &skb_shinfo(tgt)->frags[merge];
3168
3169                         skb_frag_size_add(fragto, shiftlen);
3170                         skb_frag_size_sub(fragfrom, shiftlen);
3171                         fragfrom->page_offset += shiftlen;
3172
3173                         goto onlymerged;
3174                 }
3175
3176                 from++;
3177         }
3178
3179         /* Skip full, not-fitting skb to avoid expensive operations */
3180         if ((shiftlen == skb->len) &&
3181             (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3182                 return 0;
3183
3184         if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3185                 return 0;
3186
3187         while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3188                 if (to == MAX_SKB_FRAGS)
3189                         return 0;
3190
3191                 fragfrom = &skb_shinfo(skb)->frags[from];
3192                 fragto = &skb_shinfo(tgt)->frags[to];
3193
3194                 if (todo >= skb_frag_size(fragfrom)) {
3195                         *fragto = *fragfrom;
3196                         todo -= skb_frag_size(fragfrom);
3197                         from++;
3198                         to++;
3199
3200                 } else {
3201                         __skb_frag_ref(fragfrom);
3202                         fragto->page = fragfrom->page;
3203                         fragto->page_offset = fragfrom->page_offset;
3204                         skb_frag_size_set(fragto, todo);
3205
3206                         fragfrom->page_offset += todo;
3207                         skb_frag_size_sub(fragfrom, todo);
3208                         todo = 0;
3209
3210                         to++;
3211                         break;
3212                 }
3213         }
3214
3215         /* Ready to "commit" this state change to tgt */
3216         skb_shinfo(tgt)->nr_frags = to;
3217
3218         if (merge >= 0) {
3219                 fragfrom = &skb_shinfo(skb)->frags[0];
3220                 fragto = &skb_shinfo(tgt)->frags[merge];
3221
3222                 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3223                 __skb_frag_unref(fragfrom);
3224         }
3225
3226         /* Reposition in the original skb */
3227         to = 0;
3228         while (from < skb_shinfo(skb)->nr_frags)
3229                 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3230         skb_shinfo(skb)->nr_frags = to;
3231
3232         BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3233
3234 onlymerged:
3235         /* Most likely the tgt won't ever need its checksum anymore, skb on
3236          * the other hand might need it if it needs to be resent
3237          */
3238         tgt->ip_summed = CHECKSUM_PARTIAL;
3239         skb->ip_summed = CHECKSUM_PARTIAL;
3240
3241         /* Yak, is it really working this way? Some helper please? */
3242         skb->len -= shiftlen;
3243         skb->data_len -= shiftlen;
3244         skb->truesize -= shiftlen;
3245         tgt->len += shiftlen;
3246         tgt->data_len += shiftlen;
3247         tgt->truesize += shiftlen;
3248
3249         return shiftlen;
3250 }
3251
3252 /**
3253  * skb_prepare_seq_read - Prepare a sequential read of skb data
3254  * @skb: the buffer to read
3255  * @from: lower offset of data to be read
3256  * @to: upper offset of data to be read
3257  * @st: state variable
3258  *
3259  * Initializes the specified state variable. Must be called before
3260  * invoking skb_seq_read() for the first time.
3261  */
3262 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3263                           unsigned int to, struct skb_seq_state *st)
3264 {
3265         st->lower_offset = from;
3266         st->upper_offset = to;
3267         st->root_skb = st->cur_skb = skb;
3268         st->frag_idx = st->stepped_offset = 0;
3269         st->frag_data = NULL;
3270 }
3271 EXPORT_SYMBOL(skb_prepare_seq_read);
3272
3273 /**
3274  * skb_seq_read - Sequentially read skb data
3275  * @consumed: number of bytes consumed by the caller so far
3276  * @data: destination pointer for data to be returned
3277  * @st: state variable
3278  *
3279  * Reads a block of skb data at @consumed relative to the
3280  * lower offset specified to skb_prepare_seq_read(). Assigns
3281  * the head of the data block to @data and returns the length
3282  * of the block or 0 if the end of the skb data or the upper
3283  * offset has been reached.
3284  *
3285  * The caller is not required to consume all of the data
3286  * returned, i.e. @consumed is typically set to the number
3287  * of bytes already consumed and the next call to
3288  * skb_seq_read() will return the remaining part of the block.
3289  *
3290  * Note 1: The size of each block of data returned can be arbitrary,
3291  *       this limitation is the cost for zerocopy sequential
3292  *       reads of potentially non linear data.
3293  *
3294  * Note 2: Fragment lists within fragments are not implemented
3295  *       at the moment, state->root_skb could be replaced with
3296  *       a stack for this purpose.
3297  */
3298 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3299                           struct skb_seq_state *st)
3300 {
3301         unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3302         skb_frag_t *frag;
3303
3304         if (unlikely(abs_offset >= st->upper_offset)) {
3305                 if (st->frag_data) {
3306                         kunmap_atomic(st->frag_data);
3307                         st->frag_data = NULL;
3308                 }
3309                 return 0;
3310         }
3311
3312 next_skb:
3313         block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3314
3315         if (abs_offset < block_limit && !st->frag_data) {
3316                 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3317                 return block_limit - abs_offset;
3318         }
3319
3320         if (st->frag_idx == 0 && !st->frag_data)
3321                 st->stepped_offset += skb_headlen(st->cur_skb);
3322
3323         while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3324                 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3325                 block_limit = skb_frag_size(frag) + st->stepped_offset;
3326
3327                 if (abs_offset < block_limit) {
3328                         if (!st->frag_data)
3329                                 st->frag_data = kmap_atomic(skb_frag_page(frag));
3330
3331                         *data = (u8 *) st->frag_data + frag->page_offset +
3332                                 (abs_offset - st->stepped_offset);
3333
3334                         return block_limit - abs_offset;
3335                 }
3336
3337                 if (st->frag_data) {
3338                         kunmap_atomic(st->frag_data);
3339                         st->frag_data = NULL;
3340                 }
3341
3342                 st->frag_idx++;
3343                 st->stepped_offset += skb_frag_size(frag);
3344         }
3345
3346         if (st->frag_data) {
3347                 kunmap_atomic(st->frag_data);
3348                 st->frag_data = NULL;
3349         }
3350
3351         if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3352                 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3353                 st->frag_idx = 0;
3354                 goto next_skb;
3355         } else if (st->cur_skb->next) {
3356                 st->cur_skb = st->cur_skb->next;
3357                 st->frag_idx = 0;
3358                 goto next_skb;
3359         }
3360
3361         return 0;
3362 }
3363 EXPORT_SYMBOL(skb_seq_read);
3364
3365 /**
3366  * skb_abort_seq_read - Abort a sequential read of skb data
3367  * @st: state variable
3368  *
3369  * Must be called if skb_seq_read() was not called until it
3370  * returned 0.
3371  */
3372 void skb_abort_seq_read(struct skb_seq_state *st)
3373 {
3374         if (st->frag_data)
3375                 kunmap_atomic(st->frag_data);
3376 }
3377 EXPORT_SYMBOL(skb_abort_seq_read);
3378
3379 #define TS_SKB_CB(state)        ((struct skb_seq_state *) &((state)->cb))
3380
3381 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3382                                           struct ts_config *conf,
3383                                           struct ts_state *state)
3384 {
3385         return skb_seq_read(offset, text, TS_SKB_CB(state));
3386 }
3387
3388 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3389 {
3390         skb_abort_seq_read(TS_SKB_CB(state));
3391 }
3392
3393 /**
3394  * skb_find_text - Find a text pattern in skb data
3395  * @skb: the buffer to look in
3396  * @from: search offset
3397  * @to: search limit
3398  * @config: textsearch configuration
3399  *
3400  * Finds a pattern in the skb data according to the specified
3401  * textsearch configuration. Use textsearch_next() to retrieve
3402  * subsequent occurrences of the pattern. Returns the offset
3403  * to the first occurrence or UINT_MAX if no match was found.
3404  */
3405 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3406                            unsigned int to, struct ts_config *config)
3407 {
3408         struct ts_state state;
3409         unsigned int ret;
3410
3411         config->get_next_block = skb_ts_get_next_block;
3412         config->finish = skb_ts_finish;
3413
3414         skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3415
3416         ret = textsearch_find(config, &state);
3417         return (ret <= to - from ? ret : UINT_MAX);
3418 }
3419 EXPORT_SYMBOL(skb_find_text);
3420
3421 /**
3422  * skb_append_datato_frags - append the user data to a skb
3423  * @sk: sock  structure
3424  * @skb: skb structure to be appended with user data.
3425  * @getfrag: call back function to be used for getting the user data
3426  * @from: pointer to user message iov
3427  * @length: length of the iov message
3428  *
3429  * Description: This procedure append the user data in the fragment part
3430  * of the skb if any page alloc fails user this procedure returns  -ENOMEM
3431  */
3432 int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
3433                         int (*getfrag)(void *from, char *to, int offset,
3434                                         int len, int odd, struct sk_buff *skb),
3435                         void *from, int length)
3436 {
3437         int frg_cnt = skb_shinfo(skb)->nr_frags;
3438         int copy;
3439         int offset = 0;
3440         int ret;
3441         struct page_frag *pfrag = &current->task_frag;
3442
3443         do {
3444                 /* Return error if we don't have space for new frag */
3445                 if (frg_cnt >= MAX_SKB_FRAGS)
3446                         return -EMSGSIZE;
3447
3448                 if (!sk_page_frag_refill(sk, pfrag))
3449                         return -ENOMEM;
3450
3451                 /* copy the user data to page */
3452                 copy = min_t(int, length, pfrag->size - pfrag->offset);
3453
3454                 ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
3455                               offset, copy, 0, skb);
3456                 if (ret < 0)
3457                         return -EFAULT;
3458
3459                 /* copy was successful so update the size parameters */
3460                 skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
3461                                    copy);
3462                 frg_cnt++;
3463                 pfrag->offset += copy;
3464                 get_page(pfrag->page);
3465
3466                 skb->truesize += copy;
3467                 refcount_add(copy, &sk->sk_wmem_alloc);
3468                 skb->len += copy;
3469                 skb->data_len += copy;
3470                 offset += copy;
3471                 length -= copy;
3472
3473         } while (length > 0);
3474
3475         return 0;
3476 }
3477 EXPORT_SYMBOL(skb_append_datato_frags);
3478
3479 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3480                          int offset, size_t size)
3481 {
3482         int i = skb_shinfo(skb)->nr_frags;
3483
3484         if (skb_can_coalesce(skb, i, page, offset)) {
3485                 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3486         } else if (i < MAX_SKB_FRAGS) {
3487                 get_page(page);
3488                 skb_fill_page_desc(skb, i, page, offset, size);
3489         } else {
3490                 return -EMSGSIZE;
3491         }
3492
3493         return 0;
3494 }
3495 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3496
3497 /**
3498  *      skb_pull_rcsum - pull skb and update receive checksum
3499  *      @skb: buffer to update
3500  *      @len: length of data pulled
3501  *
3502  *      This function performs an skb_pull on the packet and updates
3503  *      the CHECKSUM_COMPLETE checksum.  It should be used on
3504  *      receive path processing instead of skb_pull unless you know
3505  *      that the checksum difference is zero (e.g., a valid IP header)
3506  *      or you are setting ip_summed to CHECKSUM_NONE.
3507  */
3508 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3509 {
3510         unsigned char *data = skb->data;
3511
3512         BUG_ON(len > skb->len);
3513         __skb_pull(skb, len);
3514         skb_postpull_rcsum(skb, data, len);
3515         return skb->data;
3516 }
3517 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3518
3519 /**
3520  *      skb_segment - Perform protocol segmentation on skb.
3521  *      @head_skb: buffer to segment
3522  *      @features: features for the output path (see dev->features)
3523  *
3524  *      This function performs segmentation on the given skb.  It returns
3525  *      a pointer to the first in a list of new skbs for the segments.
3526  *      In case of error it returns ERR_PTR(err).
3527  */
3528 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3529                             netdev_features_t features)
3530 {
3531         struct sk_buff *segs = NULL;
3532         struct sk_buff *tail = NULL;
3533         struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3534         skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3535         unsigned int mss = skb_shinfo(head_skb)->gso_size;
3536         unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3537         struct sk_buff *frag_skb = head_skb;
3538         unsigned int offset = doffset;
3539         unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3540         unsigned int partial_segs = 0;
3541         unsigned int headroom;
3542         unsigned int len = head_skb->len;
3543         __be16 proto;
3544         bool csum, sg;
3545         int nfrags = skb_shinfo(head_skb)->nr_frags;
3546         int err = -ENOMEM;
3547         int i = 0;
3548         int pos;
3549         int dummy;
3550
3551         if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
3552             mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
3553                 struct sk_buff *check_skb;
3554
3555                 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
3556                         if (skb_headlen(check_skb) && !check_skb->head_frag) {
3557                                 /* gso_size is untrusted, and we have a frag_list with
3558                                  * a linear non head_frag item.
3559                                  *
3560                                  * If head_skb's headlen does not fit requested gso_size,
3561                                  * it means that the frag_list members do NOT terminate
3562                                  * on exact gso_size boundaries. Hence we cannot perform
3563                                  * skb_frag_t page sharing. Therefore we must fallback to
3564                                  * copying the frag_list skbs; we do so by disabling SG.
3565                                  */
3566                                 features &= ~NETIF_F_SG;
3567                                 break;
3568                         }
3569                 }
3570         }
3571
3572         __skb_push(head_skb, doffset);
3573         proto = skb_network_protocol(head_skb, &dummy);
3574         if (unlikely(!proto))
3575                 return ERR_PTR(-EINVAL);
3576
3577         sg = !!(features & NETIF_F_SG);
3578         csum = !!can_checksum_protocol(features, proto);
3579
3580         if (sg && csum && (mss != GSO_BY_FRAGS))  {
3581                 if (!(features & NETIF_F_GSO_PARTIAL)) {
3582                         struct sk_buff *iter;
3583                         unsigned int frag_len;
3584
3585                         if (!list_skb ||
3586                             !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
3587                                 goto normal;
3588
3589                         /* If we get here then all the required
3590                          * GSO features except frag_list are supported.
3591                          * Try to split the SKB to multiple GSO SKBs
3592                          * with no frag_list.
3593                          * Currently we can do that only when the buffers don't
3594                          * have a linear part and all the buffers except
3595                          * the last are of the same length.
3596                          */
3597                         frag_len = list_skb->len;
3598                         skb_walk_frags(head_skb, iter) {
3599                                 if (frag_len != iter->len && iter->next)
3600                                         goto normal;
3601                                 if (skb_headlen(iter) && !iter->head_frag)
3602                                         goto normal;
3603
3604                                 len -= iter->len;
3605                         }
3606
3607                         if (len != frag_len)
3608                                 goto normal;
3609                 }
3610
3611                 /* GSO partial only requires that we trim off any excess that
3612                  * doesn't fit into an MSS sized block, so take care of that
3613                  * now.
3614                  */
3615                 partial_segs = len / mss;
3616                 if (partial_segs > 1)
3617                         mss *= partial_segs;
3618                 else
3619                         partial_segs = 0;
3620         }
3621
3622 normal:
3623         headroom = skb_headroom(head_skb);
3624         pos = skb_headlen(head_skb);
3625
3626         do {
3627                 struct sk_buff *nskb;
3628                 skb_frag_t *nskb_frag;
3629                 int hsize;
3630                 int size;
3631
3632                 if (unlikely(mss == GSO_BY_FRAGS)) {
3633                         len = list_skb->len;
3634                 } else {
3635                         len = head_skb->len - offset;
3636                         if (len > mss)
3637                                 len = mss;
3638                 }
3639
3640                 hsize = skb_headlen(head_skb) - offset;
3641                 if (hsize < 0)
3642                         hsize = 0;
3643                 if (hsize > len || !sg)
3644                         hsize = len;
3645
3646                 if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
3647                     (skb_headlen(list_skb) == len || sg)) {
3648                         BUG_ON(skb_headlen(list_skb) > len);
3649
3650                         i = 0;
3651                         nfrags = skb_shinfo(list_skb)->nr_frags;
3652                         frag = skb_shinfo(list_skb)->frags;
3653                         frag_skb = list_skb;
3654                         pos += skb_headlen(list_skb);
3655
3656                         while (pos < offset + len) {
3657                                 BUG_ON(i >= nfrags);
3658
3659                                 size = skb_frag_size(frag);
3660                                 if (pos + size > offset + len)
3661                                         break;
3662
3663                                 i++;
3664                                 pos += size;
3665                                 frag++;
3666                         }
3667
3668                         nskb = skb_clone(list_skb, GFP_ATOMIC);
3669                         list_skb = list_skb->next;
3670
3671                         if (unlikely(!nskb))
3672                                 goto err;
3673
3674                         if (unlikely(pskb_trim(nskb, len))) {
3675                                 kfree_skb(nskb);
3676                                 goto err;
3677                         }
3678
3679                         hsize = skb_end_offset(nskb);
3680                         if (skb_cow_head(nskb, doffset + headroom)) {
3681                                 kfree_skb(nskb);
3682                                 goto err;
3683                         }
3684
3685                         nskb->truesize += skb_end_offset(nskb) - hsize;
3686                         skb_release_head_state(nskb);
3687                         __skb_push(nskb, doffset);
3688                 } else {
3689                         nskb = __alloc_skb(hsize + doffset + headroom,
3690                                            GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
3691                                            NUMA_NO_NODE);
3692
3693                         if (unlikely(!nskb))
3694                                 goto err;
3695
3696                         skb_reserve(nskb, headroom);
3697                         __skb_put(nskb, doffset);
3698                 }
3699
3700                 if (segs)
3701                         tail->next = nskb;
3702                 else
3703                         segs = nskb;
3704                 tail = nskb;
3705
3706                 __copy_skb_header(nskb, head_skb);
3707
3708                 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
3709                 skb_reset_mac_len(nskb);
3710
3711                 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
3712                                                  nskb->data - tnl_hlen,
3713                                                  doffset + tnl_hlen);
3714
3715                 if (nskb->len == len + doffset)
3716                         goto perform_csum_check;
3717
3718                 if (!sg) {
3719                         if (!nskb->remcsum_offload)
3720                                 nskb->ip_summed = CHECKSUM_NONE;
3721                         SKB_GSO_CB(nskb)->csum =
3722                                 skb_copy_and_csum_bits(head_skb, offset,
3723                                                        skb_put(nskb, len),
3724                                                        len, 0);
3725                         SKB_GSO_CB(nskb)->csum_start =
3726                                 skb_headroom(nskb) + doffset;
3727                         continue;
3728                 }
3729
3730                 nskb_frag = skb_shinfo(nskb)->frags;
3731
3732                 skb_copy_from_linear_data_offset(head_skb, offset,
3733                                                  skb_put(nskb, hsize), hsize);
3734
3735                 skb_shinfo(nskb)->tx_flags |= skb_shinfo(head_skb)->tx_flags &
3736                                               SKBTX_SHARED_FRAG;
3737
3738                 while (pos < offset + len) {
3739                         if (i >= nfrags) {
3740                                 BUG_ON(skb_headlen(list_skb));
3741
3742                                 i = 0;
3743                                 nfrags = skb_shinfo(list_skb)->nr_frags;
3744                                 frag = skb_shinfo(list_skb)->frags;
3745                                 frag_skb = list_skb;
3746
3747                                 BUG_ON(!nfrags);
3748
3749                                 list_skb = list_skb->next;
3750                         }
3751
3752                         if (unlikely(skb_shinfo(nskb)->nr_frags >=
3753                                      MAX_SKB_FRAGS)) {
3754                                 net_warn_ratelimited(
3755                                         "skb_segment: too many frags: %u %u\n",
3756                                         pos, mss);
3757                                 err = -EINVAL;
3758                                 goto err;
3759                         }
3760
3761                         if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
3762                                 goto err;
3763                         if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
3764                                 goto err;
3765
3766                         *nskb_frag = *frag;
3767                         __skb_frag_ref(nskb_frag);
3768                         size = skb_frag_size(nskb_frag);
3769
3770                         if (pos < offset) {
3771                                 nskb_frag->page_offset += offset - pos;
3772                                 skb_frag_size_sub(nskb_frag, offset - pos);
3773                         }
3774
3775                         skb_shinfo(nskb)->nr_frags++;
3776
3777                         if (pos + size <= offset + len) {
3778                                 i++;
3779                                 frag++;
3780                                 pos += size;
3781                         } else {
3782                                 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
3783                                 goto skip_fraglist;
3784                         }
3785
3786                         nskb_frag++;
3787                 }
3788
3789 skip_fraglist:
3790                 nskb->data_len = len - hsize;
3791                 nskb->len += nskb->data_len;
3792                 nskb->truesize += nskb->data_len;
3793
3794 perform_csum_check:
3795                 if (!csum) {
3796                         if (skb_has_shared_frag(nskb) &&
3797                             __skb_linearize(nskb))
3798                                 goto err;
3799
3800                         if (!nskb->remcsum_offload)
3801                                 nskb->ip_summed = CHECKSUM_NONE;
3802                         SKB_GSO_CB(nskb)->csum =
3803                                 skb_checksum(nskb, doffset,
3804                                              nskb->len - doffset, 0);
3805                         SKB_GSO_CB(nskb)->csum_start =
3806                                 skb_headroom(nskb) + doffset;
3807                 }
3808         } while ((offset += len) < head_skb->len);
3809
3810         /* Some callers want to get the end of the list.
3811          * Put it in segs->prev to avoid walking the list.
3812          * (see validate_xmit_skb_list() for example)
3813          */
3814         segs->prev = tail;
3815
3816         if (partial_segs) {
3817                 struct sk_buff *iter;
3818                 int type = skb_shinfo(head_skb)->gso_type;
3819                 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
3820
3821                 /* Update type to add partial and then remove dodgy if set */
3822                 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
3823                 type &= ~SKB_GSO_DODGY;
3824
3825                 /* Update GSO info and prepare to start updating headers on
3826                  * our way back down the stack of protocols.
3827                  */
3828                 for (iter = segs; iter; iter = iter->next) {
3829                         skb_shinfo(iter)->gso_size = gso_size;
3830                         skb_shinfo(iter)->gso_segs = partial_segs;
3831                         skb_shinfo(iter)->gso_type = type;
3832                         SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
3833                 }
3834
3835                 if (tail->len - doffset <= gso_size)
3836                         skb_shinfo(tail)->gso_size = 0;
3837                 else if (tail != segs)
3838                         skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
3839         }
3840
3841         /* Following permits correct backpressure, for protocols
3842          * using skb_set_owner_w().
3843          * Idea is to tranfert ownership from head_skb to last segment.
3844          */
3845         if (head_skb->destructor == sock_wfree) {
3846                 swap(tail->truesize, head_skb->truesize);
3847                 swap(tail->destructor, head_skb->destructor);
3848                 swap(tail->sk, head_skb->sk);
3849         }
3850         return segs;
3851
3852 err:
3853         kfree_skb_list(segs);
3854         return ERR_PTR(err);
3855 }
3856 EXPORT_SYMBOL_GPL(skb_segment);
3857
3858 int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
3859 {
3860         struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
3861         unsigned int offset = skb_gro_offset(skb);
3862         unsigned int headlen = skb_headlen(skb);
3863         unsigned int len = skb_gro_len(skb);
3864         struct sk_buff *lp, *p = *head;
3865         unsigned int delta_truesize;
3866
3867         if (unlikely(p->len + len >= 65536 || NAPI_GRO_CB(skb)->flush))
3868                 return -E2BIG;
3869
3870         lp = NAPI_GRO_CB(p)->last;
3871         pinfo = skb_shinfo(lp);
3872
3873         if (headlen <= offset) {
3874                 skb_frag_t *frag;
3875                 skb_frag_t *frag2;
3876                 int i = skbinfo->nr_frags;
3877                 int nr_frags = pinfo->nr_frags + i;
3878
3879                 if (nr_frags > MAX_SKB_FRAGS)
3880                         goto merge;
3881
3882                 offset -= headlen;
3883                 pinfo->nr_frags = nr_frags;
3884                 skbinfo->nr_frags = 0;
3885
3886                 frag = pinfo->frags + nr_frags;
3887                 frag2 = skbinfo->frags + i;
3888                 do {
3889                         *--frag = *--frag2;
3890                 } while (--i);
3891
3892                 frag->page_offset += offset;
3893                 skb_frag_size_sub(frag, offset);
3894
3895                 /* all fragments truesize : remove (head size + sk_buff) */
3896                 delta_truesize = skb->truesize -
3897                                  SKB_TRUESIZE(skb_end_offset(skb));
3898
3899                 skb->truesize -= skb->data_len;
3900                 skb->len -= skb->data_len;
3901                 skb->data_len = 0;
3902
3903                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
3904                 goto done;
3905         } else if (skb->head_frag) {
3906                 int nr_frags = pinfo->nr_frags;
3907                 skb_frag_t *frag = pinfo->frags + nr_frags;
3908                 struct page *page = virt_to_head_page(skb->head);
3909                 unsigned int first_size = headlen - offset;
3910                 unsigned int first_offset;
3911
3912                 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
3913                         goto merge;
3914
3915                 first_offset = skb->data -
3916                                (unsigned char *)page_address(page) +
3917                                offset;
3918
3919                 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
3920
3921                 frag->page.p      = page;
3922                 frag->page_offset = first_offset;
3923                 skb_frag_size_set(frag, first_size);
3924
3925                 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
3926                 /* We dont need to clear skbinfo->nr_frags here */
3927
3928                 delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
3929                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
3930                 goto done;
3931         }
3932
3933 merge:
3934         delta_truesize = skb->truesize;
3935         if (offset > headlen) {
3936                 unsigned int eat = offset - headlen;
3937
3938                 skbinfo->frags[0].page_offset += eat;
3939                 skb_frag_size_sub(&skbinfo->frags[0], eat);
3940                 skb->data_len -= eat;
3941                 skb->len -= eat;
3942                 offset = headlen;
3943         }
3944
3945         __skb_pull(skb, offset);
3946
3947         if (NAPI_GRO_CB(p)->last == p)
3948                 skb_shinfo(p)->frag_list = skb;
3949         else
3950                 NAPI_GRO_CB(p)->last->next = skb;
3951         NAPI_GRO_CB(p)->last = skb;
3952         __skb_header_release(skb);
3953         lp = p;
3954
3955 done:
3956         NAPI_GRO_CB(p)->count++;
3957         p->data_len += len;
3958         p->truesize += delta_truesize;
3959         p->len += len;
3960         if (lp != p) {
3961                 lp->data_len += len;
3962                 lp->truesize += delta_truesize;
3963                 lp->len += len;
3964         }
3965         NAPI_GRO_CB(skb)->same_flow = 1;
3966         return 0;
3967 }
3968 EXPORT_SYMBOL_GPL(skb_gro_receive);
3969
3970 void __init skb_init(void)
3971 {
3972         skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
3973                                               sizeof(struct sk_buff),
3974                                               0,
3975                                               SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3976                                               NULL);
3977         skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
3978                                                 sizeof(struct sk_buff_fclones),
3979                                                 0,
3980                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3981                                                 NULL);
3982 }
3983
3984 static int
3985 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
3986                unsigned int recursion_level)
3987 {
3988         int start = skb_headlen(skb);
3989         int i, copy = start - offset;
3990         struct sk_buff *frag_iter;
3991         int elt = 0;
3992
3993         if (unlikely(recursion_level >= 24))
3994                 return -EMSGSIZE;
3995
3996         if (copy > 0) {
3997                 if (copy > len)
3998                         copy = len;
3999                 sg_set_buf(sg, skb->data + offset, copy);
4000                 elt++;
4001                 if ((len -= copy) == 0)
4002                         return elt;
4003                 offset += copy;
4004         }
4005
4006         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4007                 int end;
4008
4009                 WARN_ON(start > offset + len);
4010
4011                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4012                 if ((copy = end - offset) > 0) {
4013                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4014                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4015                                 return -EMSGSIZE;
4016
4017                         if (copy > len)
4018                                 copy = len;
4019                         sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4020                                         frag->page_offset+offset-start);
4021                         elt++;
4022                         if (!(len -= copy))
4023                                 return elt;
4024                         offset += copy;
4025                 }
4026                 start = end;
4027         }
4028
4029         skb_walk_frags(skb, frag_iter) {
4030                 int end, ret;
4031
4032                 WARN_ON(start > offset + len);
4033
4034                 end = start + frag_iter->len;
4035                 if ((copy = end - offset) > 0) {
4036                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4037                                 return -EMSGSIZE;
4038
4039                         if (copy > len)
4040                                 copy = len;
4041                         ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4042                                               copy, recursion_level + 1);
4043                         if (unlikely(ret < 0))
4044                                 return ret;
4045                         elt += ret;
4046                         if ((len -= copy) == 0)
4047                                 return elt;
4048                         offset += copy;
4049                 }
4050                 start = end;
4051         }
4052         BUG_ON(len);
4053         return elt;
4054 }
4055
4056 /**
4057  *      skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4058  *      @skb: Socket buffer containing the buffers to be mapped
4059  *      @sg: The scatter-gather list to map into
4060  *      @offset: The offset into the buffer's contents to start mapping
4061  *      @len: Length of buffer space to be mapped
4062  *
4063  *      Fill the specified scatter-gather list with mappings/pointers into a
4064  *      region of the buffer space attached to a socket buffer. Returns either
4065  *      the number of scatterlist items used, or -EMSGSIZE if the contents
4066  *      could not fit.
4067  */
4068 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4069 {
4070         int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4071
4072         if (nsg <= 0)
4073                 return nsg;
4074
4075         sg_mark_end(&sg[nsg - 1]);
4076
4077         return nsg;
4078 }
4079 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4080
4081 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4082  * sglist without mark the sg which contain last skb data as the end.
4083  * So the caller can mannipulate sg list as will when padding new data after
4084  * the first call without calling sg_unmark_end to expend sg list.
4085  *
4086  * Scenario to use skb_to_sgvec_nomark:
4087  * 1. sg_init_table
4088  * 2. skb_to_sgvec_nomark(payload1)
4089  * 3. skb_to_sgvec_nomark(payload2)
4090  *
4091  * This is equivalent to:
4092  * 1. sg_init_table
4093  * 2. skb_to_sgvec(payload1)
4094  * 3. sg_unmark_end
4095  * 4. skb_to_sgvec(payload2)
4096  *
4097  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4098  * is more preferable.
4099  */
4100 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4101                         int offset, int len)
4102 {
4103         return __skb_to_sgvec(skb, sg, offset, len, 0);
4104 }
4105 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4106
4107
4108
4109 /**
4110  *      skb_cow_data - Check that a socket buffer's data buffers are writable
4111  *      @skb: The socket buffer to check.
4112  *      @tailbits: Amount of trailing space to be added
4113  *      @trailer: Returned pointer to the skb where the @tailbits space begins
4114  *
4115  *      Make sure that the data buffers attached to a socket buffer are
4116  *      writable. If they are not, private copies are made of the data buffers
4117  *      and the socket buffer is set to use these instead.
4118  *
4119  *      If @tailbits is given, make sure that there is space to write @tailbits
4120  *      bytes of data beyond current end of socket buffer.  @trailer will be
4121  *      set to point to the skb in which this space begins.
4122  *
4123  *      The number of scatterlist elements required to completely map the
4124  *      COW'd and extended socket buffer will be returned.
4125  */
4126 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4127 {
4128         int copyflag;
4129         int elt;
4130         struct sk_buff *skb1, **skb_p;
4131
4132         /* If skb is cloned or its head is paged, reallocate
4133          * head pulling out all the pages (pages are considered not writable
4134          * at the moment even if they are anonymous).
4135          */
4136         if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4137             __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
4138                 return -ENOMEM;
4139
4140         /* Easy case. Most of packets will go this way. */
4141         if (!skb_has_frag_list(skb)) {
4142                 /* A little of trouble, not enough of space for trailer.
4143                  * This should not happen, when stack is tuned to generate
4144                  * good frames. OK, on miss we reallocate and reserve even more
4145                  * space, 128 bytes is fair. */
4146
4147                 if (skb_tailroom(skb) < tailbits &&
4148                     pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4149                         return -ENOMEM;
4150
4151                 /* Voila! */
4152                 *trailer = skb;
4153                 return 1;
4154         }
4155
4156         /* Misery. We are in troubles, going to mincer fragments... */
4157
4158         elt = 1;
4159         skb_p = &skb_shinfo(skb)->frag_list;
4160         copyflag = 0;
4161
4162         while ((skb1 = *skb_p) != NULL) {
4163                 int ntail = 0;
4164
4165                 /* The fragment is partially pulled by someone,
4166                  * this can happen on input. Copy it and everything
4167                  * after it. */
4168
4169                 if (skb_shared(skb1))
4170                         copyflag = 1;
4171
4172                 /* If the skb is the last, worry about trailer. */
4173
4174                 if (skb1->next == NULL && tailbits) {
4175                         if (skb_shinfo(skb1)->nr_frags ||
4176                             skb_has_frag_list(skb1) ||
4177                             skb_tailroom(skb1) < tailbits)
4178                                 ntail = tailbits + 128;
4179                 }
4180
4181                 if (copyflag ||
4182                     skb_cloned(skb1) ||
4183                     ntail ||
4184                     skb_shinfo(skb1)->nr_frags ||
4185                     skb_has_frag_list(skb1)) {
4186                         struct sk_buff *skb2;
4187
4188                         /* Fuck, we are miserable poor guys... */
4189                         if (ntail == 0)
4190                                 skb2 = skb_copy(skb1, GFP_ATOMIC);
4191                         else
4192                                 skb2 = skb_copy_expand(skb1,
4193                                                        skb_headroom(skb1),
4194                                                        ntail,
4195                                                        GFP_ATOMIC);
4196                         if (unlikely(skb2 == NULL))
4197                                 return -ENOMEM;
4198
4199                         if (skb1->sk)
4200                                 skb_set_owner_w(skb2, skb1->sk);
4201
4202                         /* Looking around. Are we still alive?
4203                          * OK, link new skb, drop old one */
4204
4205                         skb2->next = skb1->next;
4206                         *skb_p = skb2;
4207                         kfree_skb(skb1);
4208                         skb1 = skb2;
4209                 }
4210                 elt++;
4211                 *trailer = skb1;
4212                 skb_p = &skb1->next;
4213         }
4214
4215         return elt;
4216 }
4217 EXPORT_SYMBOL_GPL(skb_cow_data);
4218
4219 static void sock_rmem_free(struct sk_buff *skb)
4220 {
4221         struct sock *sk = skb->sk;
4222
4223         atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4224 }
4225
4226 static void skb_set_err_queue(struct sk_buff *skb)
4227 {
4228         /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4229          * So, it is safe to (mis)use it to mark skbs on the error queue.
4230          */
4231         skb->pkt_type = PACKET_OUTGOING;
4232         BUILD_BUG_ON(PACKET_OUTGOING == 0);
4233 }
4234
4235 /*
4236  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4237  */
4238 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4239 {
4240         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4241             (unsigned int)sk->sk_rcvbuf)
4242                 return -ENOMEM;
4243
4244         skb_orphan(skb);
4245         skb->sk = sk;
4246         skb->destructor = sock_rmem_free;
4247         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4248         skb_set_err_queue(skb);
4249
4250         /* before exiting rcu section, make sure dst is refcounted */
4251         skb_dst_force(skb);
4252
4253         skb_queue_tail(&sk->sk_error_queue, skb);
4254         if (!sock_flag(sk, SOCK_DEAD))
4255                 sk->sk_error_report(sk);
4256         return 0;
4257 }
4258 EXPORT_SYMBOL(sock_queue_err_skb);
4259
4260 static bool is_icmp_err_skb(const struct sk_buff *skb)
4261 {
4262         return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4263                        SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4264 }
4265
4266 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4267 {
4268         struct sk_buff_head *q = &sk->sk_error_queue;
4269         struct sk_buff *skb, *skb_next = NULL;
4270         bool icmp_next = false;
4271         unsigned long flags;
4272
4273         spin_lock_irqsave(&q->lock, flags);
4274         skb = __skb_dequeue(q);
4275         if (skb && (skb_next = skb_peek(q))) {
4276                 icmp_next = is_icmp_err_skb(skb_next);
4277                 if (icmp_next)
4278                         sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4279         }
4280         spin_unlock_irqrestore(&q->lock, flags);
4281
4282         if (is_icmp_err_skb(skb) && !icmp_next)
4283                 sk->sk_err = 0;
4284
4285         if (skb_next)
4286                 sk->sk_error_report(sk);
4287
4288         return skb;
4289 }
4290 EXPORT_SYMBOL(sock_dequeue_err_skb);
4291
4292 /**
4293  * skb_clone_sk - create clone of skb, and take reference to socket
4294  * @skb: the skb to clone
4295  *
4296  * This function creates a clone of a buffer that holds a reference on
4297  * sk_refcnt.  Buffers created via this function are meant to be
4298  * returned using sock_queue_err_skb, or free via kfree_skb.
4299  *
4300  * When passing buffers allocated with this function to sock_queue_err_skb
4301  * it is necessary to wrap the call with sock_hold/sock_put in order to
4302  * prevent the socket from being released prior to being enqueued on
4303  * the sk_error_queue.
4304  */
4305 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4306 {
4307         struct sock *sk = skb->sk;
4308         struct sk_buff *clone;
4309
4310         if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4311                 return NULL;
4312
4313         clone = skb_clone(skb, GFP_ATOMIC);
4314         if (!clone) {
4315                 sock_put(sk);
4316                 return NULL;
4317         }
4318
4319         clone->sk = sk;
4320         clone->destructor = sock_efree;
4321
4322         return clone;
4323 }
4324 EXPORT_SYMBOL(skb_clone_sk);
4325
4326 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4327                                         struct sock *sk,
4328                                         int tstype,
4329                                         bool opt_stats)
4330 {
4331         struct sock_exterr_skb *serr;
4332         int err;
4333
4334         BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4335
4336         serr = SKB_EXT_ERR(skb);
4337         memset(serr, 0, sizeof(*serr));
4338         serr->ee.ee_errno = ENOMSG;
4339         serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4340         serr->ee.ee_info = tstype;
4341         serr->opt_stats = opt_stats;
4342         serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4343         if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4344                 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4345                 if (sk->sk_protocol == IPPROTO_TCP &&
4346                     sk->sk_type == SOCK_STREAM)
4347                         serr->ee.ee_data -= sk->sk_tskey;
4348         }
4349
4350         err = sock_queue_err_skb(sk, skb);
4351
4352         if (err)
4353                 kfree_skb(skb);
4354 }
4355
4356 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4357 {
4358         bool ret;
4359
4360         if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4361                 return true;
4362
4363         read_lock_bh(&sk->sk_callback_lock);
4364         ret = sk->sk_socket && sk->sk_socket->file &&
4365               file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4366         read_unlock_bh(&sk->sk_callback_lock);
4367         return ret;
4368 }
4369
4370 void skb_complete_tx_timestamp(struct sk_buff *skb,
4371                                struct skb_shared_hwtstamps *hwtstamps)
4372 {
4373         struct sock *sk = skb->sk;
4374
4375         if (!skb_may_tx_timestamp(sk, false))
4376                 goto err;
4377
4378         /* Take a reference to prevent skb_orphan() from freeing the socket,
4379          * but only if the socket refcount is not zero.
4380          */
4381         if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4382                 *skb_hwtstamps(skb) = *hwtstamps;
4383                 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4384                 sock_put(sk);
4385                 return;
4386         }
4387
4388 err:
4389         kfree_skb(skb);
4390 }
4391 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4392
4393 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4394                      struct skb_shared_hwtstamps *hwtstamps,
4395                      struct sock *sk, int tstype)
4396 {
4397         struct sk_buff *skb;
4398         bool tsonly, opt_stats = false;
4399
4400         if (!sk)
4401                 return;
4402
4403         if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4404             skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4405                 return;
4406
4407         tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4408         if (!skb_may_tx_timestamp(sk, tsonly))
4409                 return;
4410
4411         if (tsonly) {
4412 #ifdef CONFIG_INET
4413                 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4414                     sk->sk_protocol == IPPROTO_TCP &&
4415                     sk->sk_type == SOCK_STREAM) {
4416                         skb = tcp_get_timestamping_opt_stats(sk);
4417                         opt_stats = true;
4418                 } else
4419 #endif
4420                         skb = alloc_skb(0, GFP_ATOMIC);
4421         } else {
4422                 skb = skb_clone(orig_skb, GFP_ATOMIC);
4423
4424                 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
4425                         kfree_skb(skb);
4426                         return;
4427                 }
4428         }
4429         if (!skb)
4430                 return;
4431
4432         if (tsonly) {
4433                 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4434                                              SKBTX_ANY_TSTAMP;
4435                 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4436         }
4437
4438         if (hwtstamps)
4439                 *skb_hwtstamps(skb) = *hwtstamps;
4440         else
4441                 skb->tstamp = ktime_get_real();
4442
4443         __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4444 }
4445 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4446
4447 void skb_tstamp_tx(struct sk_buff *orig_skb,
4448                    struct skb_shared_hwtstamps *hwtstamps)
4449 {
4450         return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
4451                                SCM_TSTAMP_SND);
4452 }
4453 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4454
4455 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4456 {
4457         struct sock *sk = skb->sk;
4458         struct sock_exterr_skb *serr;
4459         int err = 1;
4460
4461         skb->wifi_acked_valid = 1;
4462         skb->wifi_acked = acked;
4463
4464         serr = SKB_EXT_ERR(skb);
4465         memset(serr, 0, sizeof(*serr));
4466         serr->ee.ee_errno = ENOMSG;
4467         serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4468
4469         /* Take a reference to prevent skb_orphan() from freeing the socket,
4470          * but only if the socket refcount is not zero.
4471          */
4472         if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4473                 err = sock_queue_err_skb(sk, skb);
4474                 sock_put(sk);
4475         }
4476         if (err)
4477                 kfree_skb(skb);
4478 }
4479 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4480
4481 /**
4482  * skb_partial_csum_set - set up and verify partial csum values for packet
4483  * @skb: the skb to set
4484  * @start: the number of bytes after skb->data to start checksumming.
4485  * @off: the offset from start to place the checksum.
4486  *
4487  * For untrusted partially-checksummed packets, we need to make sure the values
4488  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4489  *
4490  * This function checks and sets those values and skb->ip_summed: if this
4491  * returns false you should drop the packet.
4492  */
4493 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4494 {
4495         if (unlikely(start > skb_headlen(skb)) ||
4496             unlikely((int)start + off > skb_headlen(skb) - 2)) {
4497                 net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
4498                                      start, off, skb_headlen(skb));
4499                 return false;
4500         }
4501         skb->ip_summed = CHECKSUM_PARTIAL;
4502         skb->csum_start = skb_headroom(skb) + start;
4503         skb->csum_offset = off;
4504         skb_set_transport_header(skb, start);
4505         return true;
4506 }
4507 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4508
4509 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4510                                unsigned int max)
4511 {
4512         if (skb_headlen(skb) >= len)
4513                 return 0;
4514
4515         /* If we need to pullup then pullup to the max, so we
4516          * won't need to do it again.
4517          */
4518         if (max > skb->len)
4519                 max = skb->len;
4520
4521         if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4522                 return -ENOMEM;
4523
4524         if (skb_headlen(skb) < len)
4525                 return -EPROTO;
4526
4527         return 0;
4528 }
4529
4530 #define MAX_TCP_HDR_LEN (15 * 4)
4531
4532 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4533                                       typeof(IPPROTO_IP) proto,
4534                                       unsigned int off)
4535 {
4536         switch (proto) {
4537                 int err;
4538
4539         case IPPROTO_TCP:
4540                 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4541                                           off + MAX_TCP_HDR_LEN);
4542                 if (!err && !skb_partial_csum_set(skb, off,
4543                                                   offsetof(struct tcphdr,
4544                                                            check)))
4545                         err = -EPROTO;
4546                 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4547
4548         case IPPROTO_UDP:
4549                 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4550                                           off + sizeof(struct udphdr));
4551                 if (!err && !skb_partial_csum_set(skb, off,
4552                                                   offsetof(struct udphdr,
4553                                                            check)))
4554                         err = -EPROTO;
4555                 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4556         }
4557
4558         return ERR_PTR(-EPROTO);
4559 }
4560
4561 /* This value should be large enough to cover a tagged ethernet header plus
4562  * maximally sized IP and TCP or UDP headers.
4563  */
4564 #define MAX_IP_HDR_LEN 128
4565
4566 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4567 {
4568         unsigned int off;
4569         bool fragment;
4570         __sum16 *csum;
4571         int err;
4572
4573         fragment = false;
4574
4575         err = skb_maybe_pull_tail(skb,
4576                                   sizeof(struct iphdr),
4577                                   MAX_IP_HDR_LEN);
4578         if (err < 0)
4579                 goto out;
4580
4581         if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
4582                 fragment = true;
4583
4584         off = ip_hdrlen(skb);
4585
4586         err = -EPROTO;
4587
4588         if (fragment)
4589                 goto out;
4590
4591         csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
4592         if (IS_ERR(csum))
4593                 return PTR_ERR(csum);
4594
4595         if (recalculate)
4596                 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
4597                                            ip_hdr(skb)->daddr,
4598                                            skb->len - off,
4599                                            ip_hdr(skb)->protocol, 0);
4600         err = 0;
4601
4602 out:
4603         return err;
4604 }
4605
4606 /* This value should be large enough to cover a tagged ethernet header plus
4607  * an IPv6 header, all options, and a maximal TCP or UDP header.
4608  */
4609 #define MAX_IPV6_HDR_LEN 256
4610
4611 #define OPT_HDR(type, skb, off) \
4612         (type *)(skb_network_header(skb) + (off))
4613
4614 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
4615 {
4616         int err;
4617         u8 nexthdr;
4618         unsigned int off;
4619         unsigned int len;
4620         bool fragment;
4621         bool done;
4622         __sum16 *csum;
4623
4624         fragment = false;
4625         done = false;
4626
4627         off = sizeof(struct ipv6hdr);
4628
4629         err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
4630         if (err < 0)
4631                 goto out;
4632
4633         nexthdr = ipv6_hdr(skb)->nexthdr;
4634
4635         len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
4636         while (off <= len && !done) {
4637                 switch (nexthdr) {
4638                 case IPPROTO_DSTOPTS:
4639                 case IPPROTO_HOPOPTS:
4640                 case IPPROTO_ROUTING: {
4641                         struct ipv6_opt_hdr *hp;
4642
4643                         err = skb_maybe_pull_tail(skb,
4644                                                   off +
4645                                                   sizeof(struct ipv6_opt_hdr),
4646                                                   MAX_IPV6_HDR_LEN);
4647                         if (err < 0)
4648                                 goto out;
4649
4650                         hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
4651                         nexthdr = hp->nexthdr;
4652                         off += ipv6_optlen(hp);
4653                         break;
4654                 }
4655                 case IPPROTO_AH: {
4656                         struct ip_auth_hdr *hp;
4657
4658                         err = skb_maybe_pull_tail(skb,
4659                                                   off +
4660                                                   sizeof(struct ip_auth_hdr),
4661                                                   MAX_IPV6_HDR_LEN);
4662                         if (err < 0)
4663                                 goto out;
4664
4665                         hp = OPT_HDR(struct ip_auth_hdr, skb, off);
4666                         nexthdr = hp->nexthdr;
4667                         off += ipv6_authlen(hp);
4668                         break;
4669                 }
4670                 case IPPROTO_FRAGMENT: {
4671                         struct frag_hdr *hp;
4672
4673                         err = skb_maybe_pull_tail(skb,
4674                                                   off +
4675                                                   sizeof(struct frag_hdr),
4676                                                   MAX_IPV6_HDR_LEN);
4677                         if (err < 0)
4678                                 goto out;
4679
4680                         hp = OPT_HDR(struct frag_hdr, skb, off);
4681
4682                         if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
4683                                 fragment = true;
4684
4685                         nexthdr = hp->nexthdr;
4686                         off += sizeof(struct frag_hdr);
4687                         break;
4688                 }
4689                 default:
4690                         done = true;
4691                         break;
4692                 }
4693         }
4694
4695         err = -EPROTO;
4696
4697         if (!done || fragment)
4698                 goto out;
4699
4700         csum = skb_checksum_setup_ip(skb, nexthdr, off);
4701         if (IS_ERR(csum))
4702                 return PTR_ERR(csum);
4703
4704         if (recalculate)
4705                 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
4706                                          &ipv6_hdr(skb)->daddr,
4707                                          skb->len - off, nexthdr, 0);
4708         err = 0;
4709
4710 out:
4711         return err;
4712 }
4713
4714 /**
4715  * skb_checksum_setup - set up partial checksum offset
4716  * @skb: the skb to set up
4717  * @recalculate: if true the pseudo-header checksum will be recalculated
4718  */
4719 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
4720 {
4721         int err;
4722
4723         switch (skb->protocol) {
4724         case htons(ETH_P_IP):
4725                 err = skb_checksum_setup_ipv4(skb, recalculate);
4726                 break;
4727
4728         case htons(ETH_P_IPV6):
4729                 err = skb_checksum_setup_ipv6(skb, recalculate);
4730                 break;
4731
4732         default:
4733                 err = -EPROTO;
4734                 break;
4735         }
4736
4737         return err;
4738 }
4739 EXPORT_SYMBOL(skb_checksum_setup);
4740
4741 /**
4742  * skb_checksum_maybe_trim - maybe trims the given skb
4743  * @skb: the skb to check
4744  * @transport_len: the data length beyond the network header
4745  *
4746  * Checks whether the given skb has data beyond the given transport length.
4747  * If so, returns a cloned skb trimmed to this transport length.
4748  * Otherwise returns the provided skb. Returns NULL in error cases
4749  * (e.g. transport_len exceeds skb length or out-of-memory).
4750  *
4751  * Caller needs to set the skb transport header and free any returned skb if it
4752  * differs from the provided skb.
4753  */
4754 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
4755                                                unsigned int transport_len)
4756 {
4757         struct sk_buff *skb_chk;
4758         unsigned int len = skb_transport_offset(skb) + transport_len;
4759         int ret;
4760
4761         if (skb->len < len)
4762                 return NULL;
4763         else if (skb->len == len)
4764                 return skb;
4765
4766         skb_chk = skb_clone(skb, GFP_ATOMIC);
4767         if (!skb_chk)
4768                 return NULL;
4769
4770         ret = pskb_trim_rcsum(skb_chk, len);
4771         if (ret) {
4772                 kfree_skb(skb_chk);
4773                 return NULL;
4774         }
4775
4776         return skb_chk;
4777 }
4778
4779 /**
4780  * skb_checksum_trimmed - validate checksum of an skb
4781  * @skb: the skb to check
4782  * @transport_len: the data length beyond the network header
4783  * @skb_chkf: checksum function to use
4784  *
4785  * Applies the given checksum function skb_chkf to the provided skb.
4786  * Returns a checked and maybe trimmed skb. Returns NULL on error.
4787  *
4788  * If the skb has data beyond the given transport length, then a
4789  * trimmed & cloned skb is checked and returned.
4790  *
4791  * Caller needs to set the skb transport header and free any returned skb if it
4792  * differs from the provided skb.
4793  */
4794 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
4795                                      unsigned int transport_len,
4796                                      __sum16(*skb_chkf)(struct sk_buff *skb))
4797 {
4798         struct sk_buff *skb_chk;
4799         unsigned int offset = skb_transport_offset(skb);
4800         __sum16 ret;
4801
4802         skb_chk = skb_checksum_maybe_trim(skb, transport_len);
4803         if (!skb_chk)
4804                 goto err;
4805
4806         if (!pskb_may_pull(skb_chk, offset))
4807                 goto err;
4808
4809         skb_pull_rcsum(skb_chk, offset);
4810         ret = skb_chkf(skb_chk);
4811         skb_push_rcsum(skb_chk, offset);
4812
4813         if (ret)
4814                 goto err;
4815
4816         return skb_chk;
4817
4818 err:
4819         if (skb_chk && skb_chk != skb)
4820                 kfree_skb(skb_chk);
4821
4822         return NULL;
4823
4824 }
4825 EXPORT_SYMBOL(skb_checksum_trimmed);
4826
4827 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
4828 {
4829         net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
4830                              skb->dev->name);
4831 }
4832 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
4833
4834 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
4835 {
4836         if (head_stolen) {
4837                 skb_release_head_state(skb);
4838                 kmem_cache_free(skbuff_head_cache, skb);
4839         } else {
4840                 __kfree_skb(skb);
4841         }
4842 }
4843 EXPORT_SYMBOL(kfree_skb_partial);
4844
4845 /**
4846  * skb_try_coalesce - try to merge skb to prior one
4847  * @to: prior buffer
4848  * @from: buffer to add
4849  * @fragstolen: pointer to boolean
4850  * @delta_truesize: how much more was allocated than was requested
4851  */
4852 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
4853                       bool *fragstolen, int *delta_truesize)
4854 {
4855         int i, delta, len = from->len;
4856
4857         *fragstolen = false;
4858
4859         if (skb_cloned(to))
4860                 return false;
4861
4862         if (len <= skb_tailroom(to)) {
4863                 if (len)
4864                         BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
4865                 *delta_truesize = 0;
4866                 return true;
4867         }
4868
4869         if (skb_has_frag_list(to) || skb_has_frag_list(from))
4870                 return false;
4871         if (skb_zcopy(to) || skb_zcopy(from))
4872                 return false;
4873
4874         if (skb_headlen(from) != 0) {
4875                 struct page *page;
4876                 unsigned int offset;
4877
4878                 if (skb_shinfo(to)->nr_frags +
4879                     skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
4880                         return false;
4881
4882                 if (skb_head_is_locked(from))
4883                         return false;
4884
4885                 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
4886
4887                 page = virt_to_head_page(from->head);
4888                 offset = from->data - (unsigned char *)page_address(page);
4889
4890                 skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
4891                                    page, offset, skb_headlen(from));
4892                 *fragstolen = true;
4893         } else {
4894                 if (skb_shinfo(to)->nr_frags +
4895                     skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
4896                         return false;
4897
4898                 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
4899         }
4900
4901         WARN_ON_ONCE(delta < len);
4902
4903         memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
4904                skb_shinfo(from)->frags,
4905                skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
4906         skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
4907
4908         if (!skb_cloned(from))
4909                 skb_shinfo(from)->nr_frags = 0;
4910
4911         /* if the skb is not cloned this does nothing
4912          * since we set nr_frags to 0.
4913          */
4914         for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
4915                 skb_frag_ref(from, i);
4916
4917         to->truesize += delta;
4918         to->len += len;
4919         to->data_len += len;
4920
4921         *delta_truesize = delta;
4922         return true;
4923 }
4924 EXPORT_SYMBOL(skb_try_coalesce);
4925
4926 /**
4927  * skb_scrub_packet - scrub an skb
4928  *
4929  * @skb: buffer to clean
4930  * @xnet: packet is crossing netns
4931  *
4932  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
4933  * into/from a tunnel. Some information have to be cleared during these
4934  * operations.
4935  * skb_scrub_packet can also be used to clean a skb before injecting it in
4936  * another namespace (@xnet == true). We have to clear all information in the
4937  * skb that could impact namespace isolation.
4938  */
4939 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
4940 {
4941         skb->tstamp = 0;
4942         skb->pkt_type = PACKET_HOST;
4943         skb->skb_iif = 0;
4944         skb->ignore_df = 0;
4945         skb_dst_drop(skb);
4946         secpath_reset(skb);
4947         nf_reset(skb);
4948         nf_reset_trace(skb);
4949
4950 #ifdef CONFIG_NET_SWITCHDEV
4951         skb->offload_fwd_mark = 0;
4952 #endif
4953
4954         if (!xnet)
4955                 return;
4956
4957         ipvs_reset(skb);
4958         skb_orphan(skb);
4959         skb->mark = 0;
4960 }
4961 EXPORT_SYMBOL_GPL(skb_scrub_packet);
4962
4963 /**
4964  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
4965  *
4966  * @skb: GSO skb
4967  *
4968  * skb_gso_transport_seglen is used to determine the real size of the
4969  * individual segments, including Layer4 headers (TCP/UDP).
4970  *
4971  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
4972  */
4973 unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
4974 {
4975         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4976         unsigned int thlen = 0;
4977
4978         if (skb->encapsulation) {
4979                 thlen = skb_inner_transport_header(skb) -
4980                         skb_transport_header(skb);
4981
4982                 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
4983                         thlen += inner_tcp_hdrlen(skb);
4984         } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
4985                 thlen = tcp_hdrlen(skb);
4986         } else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) {
4987                 thlen = sizeof(struct sctphdr);
4988         }
4989         /* UFO sets gso_size to the size of the fragmentation
4990          * payload, i.e. the size of the L4 (UDP) header is already
4991          * accounted for.
4992          */
4993         return thlen + shinfo->gso_size;
4994 }
4995 EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
4996
4997 /**
4998  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
4999  *
5000  * There are a couple of instances where we have a GSO skb, and we
5001  * want to determine what size it would be after it is segmented.
5002  *
5003  * We might want to check:
5004  * -    L3+L4+payload size (e.g. IP forwarding)
5005  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5006  *
5007  * This is a helper to do that correctly considering GSO_BY_FRAGS.
5008  *
5009  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5010  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5011  *
5012  * @max_len: The maximum permissible length.
5013  *
5014  * Returns true if the segmented length <= max length.
5015  */
5016 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5017                                       unsigned int seg_len,
5018                                       unsigned int max_len) {
5019         const struct skb_shared_info *shinfo = skb_shinfo(skb);
5020         const struct sk_buff *iter;
5021
5022         if (shinfo->gso_size != GSO_BY_FRAGS)
5023                 return seg_len <= max_len;
5024
5025         /* Undo this so we can re-use header sizes */
5026         seg_len -= GSO_BY_FRAGS;
5027
5028         skb_walk_frags(skb, iter) {
5029                 if (seg_len + skb_headlen(iter) > max_len)
5030                         return false;
5031         }
5032
5033         return true;
5034 }
5035
5036 /**
5037  * skb_gso_validate_mtu - Return in case such skb fits a given MTU
5038  *
5039  * @skb: GSO skb
5040  * @mtu: MTU to validate against
5041  *
5042  * skb_gso_validate_mtu validates if a given skb will fit a wanted MTU
5043  * once split.
5044  */
5045 bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu)
5046 {
5047         return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5048 }
5049 EXPORT_SYMBOL_GPL(skb_gso_validate_mtu);
5050
5051 /**
5052  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5053  *
5054  * @skb: GSO skb
5055  * @len: length to validate against
5056  *
5057  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5058  * length once split, including L2, L3 and L4 headers and the payload.
5059  */
5060 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5061 {
5062         return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5063 }
5064 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5065
5066 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5067 {
5068         int mac_len;
5069
5070         if (skb_cow(skb, skb_headroom(skb)) < 0) {
5071                 kfree_skb(skb);
5072                 return NULL;
5073         }
5074
5075         mac_len = skb->data - skb_mac_header(skb);
5076         if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5077                 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5078                         mac_len - VLAN_HLEN - ETH_TLEN);
5079         }
5080         skb->mac_header += VLAN_HLEN;
5081         return skb;
5082 }
5083
5084 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5085 {
5086         struct vlan_hdr *vhdr;
5087         u16 vlan_tci;
5088
5089         if (unlikely(skb_vlan_tag_present(skb))) {
5090                 /* vlan_tci is already set-up so leave this for another time */
5091                 return skb;
5092         }
5093
5094         skb = skb_share_check(skb, GFP_ATOMIC);
5095         if (unlikely(!skb))
5096                 goto err_free;
5097         /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5098         if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5099                 goto err_free;
5100
5101         vhdr = (struct vlan_hdr *)skb->data;
5102         vlan_tci = ntohs(vhdr->h_vlan_TCI);
5103         __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5104
5105         skb_pull_rcsum(skb, VLAN_HLEN);
5106         vlan_set_encap_proto(skb, vhdr);
5107
5108         skb = skb_reorder_vlan_header(skb);
5109         if (unlikely(!skb))
5110                 goto err_free;
5111
5112         skb_reset_network_header(skb);
5113         skb_reset_transport_header(skb);
5114         skb_reset_mac_len(skb);
5115
5116         return skb;
5117
5118 err_free:
5119         kfree_skb(skb);
5120         return NULL;
5121 }
5122 EXPORT_SYMBOL(skb_vlan_untag);
5123
5124 int skb_ensure_writable(struct sk_buff *skb, int write_len)
5125 {
5126         if (!pskb_may_pull(skb, write_len))
5127                 return -ENOMEM;
5128
5129         if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5130                 return 0;
5131
5132         return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5133 }
5134 EXPORT_SYMBOL(skb_ensure_writable);
5135
5136 /* remove VLAN header from packet and update csum accordingly.
5137  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5138  */
5139 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5140 {
5141         struct vlan_hdr *vhdr;
5142         int offset = skb->data - skb_mac_header(skb);
5143         int err;
5144
5145         if (WARN_ONCE(offset,
5146                       "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5147                       offset)) {
5148                 return -EINVAL;
5149         }
5150
5151         err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5152         if (unlikely(err))
5153                 return err;
5154
5155         skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5156
5157         vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5158         *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5159
5160         memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5161         __skb_pull(skb, VLAN_HLEN);
5162
5163         vlan_set_encap_proto(skb, vhdr);
5164         skb->mac_header += VLAN_HLEN;
5165
5166         if (skb_network_offset(skb) < ETH_HLEN)
5167                 skb_set_network_header(skb, ETH_HLEN);
5168
5169         skb_reset_mac_len(skb);
5170
5171         return err;
5172 }
5173 EXPORT_SYMBOL(__skb_vlan_pop);
5174
5175 /* Pop a vlan tag either from hwaccel or from payload.
5176  * Expects skb->data at mac header.
5177  */
5178 int skb_vlan_pop(struct sk_buff *skb)
5179 {
5180         u16 vlan_tci;
5181         __be16 vlan_proto;
5182         int err;
5183
5184         if (likely(skb_vlan_tag_present(skb))) {
5185                 skb->vlan_tci = 0;
5186         } else {
5187                 if (unlikely(!eth_type_vlan(skb->protocol)))
5188                         return 0;
5189
5190                 err = __skb_vlan_pop(skb, &vlan_tci);
5191                 if (err)
5192                         return err;
5193         }
5194         /* move next vlan tag to hw accel tag */
5195         if (likely(!eth_type_vlan(skb->protocol)))
5196                 return 0;
5197
5198         vlan_proto = skb->protocol;
5199         err = __skb_vlan_pop(skb, &vlan_tci);
5200         if (unlikely(err))
5201                 return err;
5202
5203         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5204         return 0;
5205 }
5206 EXPORT_SYMBOL(skb_vlan_pop);
5207
5208 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5209  * Expects skb->data at mac header.
5210  */
5211 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5212 {
5213         if (skb_vlan_tag_present(skb)) {
5214                 int offset = skb->data - skb_mac_header(skb);
5215                 int err;
5216
5217                 if (WARN_ONCE(offset,
5218                               "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5219                               offset)) {
5220                         return -EINVAL;
5221                 }
5222
5223                 err = __vlan_insert_tag(skb, skb->vlan_proto,
5224                                         skb_vlan_tag_get(skb));
5225                 if (err)
5226                         return err;
5227
5228                 skb->protocol = skb->vlan_proto;
5229                 skb->mac_len += VLAN_HLEN;
5230
5231                 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5232         }
5233         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5234         return 0;
5235 }
5236 EXPORT_SYMBOL(skb_vlan_push);
5237
5238 /**
5239  * alloc_skb_with_frags - allocate skb with page frags
5240  *
5241  * @header_len: size of linear part
5242  * @data_len: needed length in frags
5243  * @max_page_order: max page order desired.
5244  * @errcode: pointer to error code if any
5245  * @gfp_mask: allocation mask
5246  *
5247  * This can be used to allocate a paged skb, given a maximal order for frags.
5248  */
5249 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
5250                                      unsigned long data_len,
5251                                      int max_page_order,
5252                                      int *errcode,
5253                                      gfp_t gfp_mask)
5254 {
5255         int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
5256         unsigned long chunk;
5257         struct sk_buff *skb;
5258         struct page *page;
5259         int i;
5260
5261         *errcode = -EMSGSIZE;
5262         /* Note this test could be relaxed, if we succeed to allocate
5263          * high order pages...
5264          */
5265         if (npages > MAX_SKB_FRAGS)
5266                 return NULL;
5267
5268         *errcode = -ENOBUFS;
5269         skb = alloc_skb(header_len, gfp_mask);
5270         if (!skb)
5271                 return NULL;
5272
5273         skb->truesize += npages << PAGE_SHIFT;
5274
5275         for (i = 0; npages > 0; i++) {
5276                 int order = max_page_order;
5277
5278                 while (order) {
5279                         if (npages >= 1 << order) {
5280                                 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
5281                                                    __GFP_COMP |
5282                                                    __GFP_NOWARN |
5283                                                    __GFP_NORETRY,
5284                                                    order);
5285                                 if (page)
5286                                         goto fill_page;
5287                                 /* Do not retry other high order allocations */
5288                                 order = 1;
5289                                 max_page_order = 0;
5290                         }
5291                         order--;
5292                 }
5293                 page = alloc_page(gfp_mask);
5294                 if (!page)
5295                         goto failure;
5296 fill_page:
5297                 chunk = min_t(unsigned long, data_len,
5298                               PAGE_SIZE << order);
5299                 skb_fill_page_desc(skb, i, page, 0, chunk);
5300                 data_len -= chunk;
5301                 npages -= 1 << order;
5302         }
5303         return skb;
5304
5305 failure:
5306         kfree_skb(skb);
5307         return NULL;
5308 }
5309 EXPORT_SYMBOL(alloc_skb_with_frags);
5310
5311 /* carve out the first off bytes from skb when off < headlen */
5312 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
5313                                     const int headlen, gfp_t gfp_mask)
5314 {
5315         int i;
5316         int size = skb_end_offset(skb);
5317         int new_hlen = headlen - off;
5318         u8 *data;
5319
5320         size = SKB_DATA_ALIGN(size);
5321
5322         if (skb_pfmemalloc(skb))
5323                 gfp_mask |= __GFP_MEMALLOC;
5324         data = kmalloc_reserve(size +
5325                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
5326                                gfp_mask, NUMA_NO_NODE, NULL);
5327         if (!data)
5328                 return -ENOMEM;
5329
5330         size = SKB_WITH_OVERHEAD(ksize(data));
5331
5332         /* Copy real data, and all frags */
5333         skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
5334         skb->len -= off;
5335
5336         memcpy((struct skb_shared_info *)(data + size),
5337                skb_shinfo(skb),
5338                offsetof(struct skb_shared_info,
5339                         frags[skb_shinfo(skb)->nr_frags]));
5340         if (skb_cloned(skb)) {
5341                 /* drop the old head gracefully */
5342                 if (skb_orphan_frags(skb, gfp_mask)) {
5343                         kfree(data);
5344                         return -ENOMEM;
5345                 }
5346                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
5347                         skb_frag_ref(skb, i);
5348                 if (skb_has_frag_list(skb))
5349                         skb_clone_fraglist(skb);
5350                 skb_release_data(skb);
5351         } else {
5352                 /* we can reuse existing recount- all we did was
5353                  * relocate values
5354                  */
5355                 skb_free_head(skb);
5356         }
5357
5358         skb->head = data;
5359         skb->data = data;
5360         skb->head_frag = 0;
5361 #ifdef NET_SKBUFF_DATA_USES_OFFSET
5362         skb->end = size;
5363 #else
5364         skb->end = skb->head + size;
5365 #endif
5366         skb_set_tail_pointer(skb, skb_headlen(skb));
5367         skb_headers_offset_update(skb, 0);
5368         skb->cloned = 0;
5369         skb->hdr_len = 0;
5370         skb->nohdr = 0;
5371         atomic_set(&skb_shinfo(skb)->dataref, 1);
5372
5373         return 0;
5374 }
5375
5376 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
5377
5378 /* carve out the first eat bytes from skb's frag_list. May recurse into
5379  * pskb_carve()
5380  */
5381 static int pskb_carve_frag_list(struct sk_buff *skb,
5382                                 struct skb_shared_info *shinfo, int eat,
5383                                 gfp_t gfp_mask)
5384 {
5385         struct sk_buff *list = shinfo->frag_list;
5386         struct sk_buff *clone = NULL;
5387         struct sk_buff *insp = NULL;
5388
5389         do {
5390                 if (!list) {
5391                         pr_err("Not enough bytes to eat. Want %d\n", eat);
5392                         return -EFAULT;
5393                 }
5394                 if (list->len <= eat) {
5395                         /* Eaten as whole. */
5396                         eat -= list->len;
5397                         list = list->next;
5398                         insp = list;
5399                 } else {
5400                         /* Eaten partially. */
5401                         if (skb_shared(list)) {
5402                                 clone = skb_clone(list, gfp_mask);
5403                                 if (!clone)
5404                                         return -ENOMEM;
5405                                 insp = list->next;
5406                                 list = clone;
5407                         } else {
5408                                 /* This may be pulled without problems. */
5409                                 insp = list;
5410                         }
5411                         if (pskb_carve(list, eat, gfp_mask) < 0) {
5412                                 kfree_skb(clone);
5413                                 return -ENOMEM;
5414                         }
5415                         break;
5416                 }
5417         } while (eat);
5418
5419         /* Free pulled out fragments. */
5420         while ((list = shinfo->frag_list) != insp) {
5421                 shinfo->frag_list = list->next;
5422                 consume_skb(list);
5423         }
5424         /* And insert new clone at head. */
5425         if (clone) {
5426                 clone->next = list;
5427                 shinfo->frag_list = clone;
5428         }
5429         return 0;
5430 }
5431
5432 /* carve off first len bytes from skb. Split line (off) is in the
5433  * non-linear part of skb
5434  */
5435 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
5436                                        int pos, gfp_t gfp_mask)
5437 {
5438         int i, k = 0;
5439         int size = skb_end_offset(skb);
5440         u8 *data;
5441         const int nfrags = skb_shinfo(skb)->nr_frags;
5442         struct skb_shared_info *shinfo;
5443
5444         size = SKB_DATA_ALIGN(size);
5445
5446         if (skb_pfmemalloc(skb))
5447                 gfp_mask |= __GFP_MEMALLOC;
5448         data = kmalloc_reserve(size +
5449                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
5450                                gfp_mask, NUMA_NO_NODE, NULL);
5451         if (!data)
5452                 return -ENOMEM;
5453
5454         size = SKB_WITH_OVERHEAD(ksize(data));
5455
5456         memcpy((struct skb_shared_info *)(data + size),
5457                skb_shinfo(skb), offsetof(struct skb_shared_info,
5458                                          frags[skb_shinfo(skb)->nr_frags]));
5459         if (skb_orphan_frags(skb, gfp_mask)) {
5460                 kfree(data);
5461                 return -ENOMEM;
5462         }
5463         shinfo = (struct skb_shared_info *)(data + size);
5464         for (i = 0; i < nfrags; i++) {
5465                 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
5466
5467                 if (pos + fsize > off) {
5468                         shinfo->frags[k] = skb_shinfo(skb)->frags[i];
5469
5470                         if (pos < off) {
5471                                 /* Split frag.
5472                                  * We have two variants in this case:
5473                                  * 1. Move all the frag to the second
5474                                  *    part, if it is possible. F.e.
5475                                  *    this approach is mandatory for TUX,
5476                                  *    where splitting is expensive.
5477                                  * 2. Split is accurately. We make this.
5478                                  */
5479                                 shinfo->frags[0].page_offset += off - pos;
5480                                 skb_frag_size_sub(&shinfo->frags[0], off - pos);
5481                         }
5482                         skb_frag_ref(skb, i);
5483                         k++;
5484                 }
5485                 pos += fsize;
5486         }
5487         shinfo->nr_frags = k;
5488         if (skb_has_frag_list(skb))
5489                 skb_clone_fraglist(skb);
5490
5491         /* split line is in frag list */
5492         if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
5493                 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
5494                 if (skb_has_frag_list(skb))
5495                         kfree_skb_list(skb_shinfo(skb)->frag_list);
5496                 kfree(data);
5497                 return -ENOMEM;
5498         }
5499         skb_release_data(skb);
5500
5501         skb->head = data;
5502         skb->head_frag = 0;
5503         skb->data = data;
5504 #ifdef NET_SKBUFF_DATA_USES_OFFSET
5505         skb->end = size;
5506 #else
5507         skb->end = skb->head + size;
5508 #endif
5509         skb_reset_tail_pointer(skb);
5510         skb_headers_offset_update(skb, 0);
5511         skb->cloned   = 0;
5512         skb->hdr_len  = 0;
5513         skb->nohdr    = 0;
5514         skb->len -= off;
5515         skb->data_len = skb->len;
5516         atomic_set(&skb_shinfo(skb)->dataref, 1);
5517         return 0;
5518 }
5519
5520 /* remove len bytes from the beginning of the skb */
5521 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
5522 {
5523         int headlen = skb_headlen(skb);
5524
5525         if (len < headlen)
5526                 return pskb_carve_inside_header(skb, len, headlen, gfp);
5527         else
5528                 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
5529 }
5530
5531 /* Extract to_copy bytes starting at off from skb, and return this in
5532  * a new skb
5533  */
5534 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
5535                              int to_copy, gfp_t gfp)
5536 {
5537         struct sk_buff  *clone = skb_clone(skb, gfp);
5538
5539         if (!clone)
5540                 return NULL;
5541
5542         if (pskb_carve(clone, off, gfp) < 0 ||
5543             pskb_trim(clone, to_copy)) {
5544                 kfree_skb(clone);
5545                 return NULL;
5546         }
5547         return clone;
5548 }
5549 EXPORT_SYMBOL(pskb_extract);
5550
5551 /**
5552  * skb_condense - try to get rid of fragments/frag_list if possible
5553  * @skb: buffer
5554  *
5555  * Can be used to save memory before skb is added to a busy queue.
5556  * If packet has bytes in frags and enough tail room in skb->head,
5557  * pull all of them, so that we can free the frags right now and adjust
5558  * truesize.
5559  * Notes:
5560  *      We do not reallocate skb->head thus can not fail.
5561  *      Caller must re-evaluate skb->truesize if needed.
5562  */
5563 void skb_condense(struct sk_buff *skb)
5564 {
5565         if (skb->data_len) {
5566                 if (skb->data_len > skb->end - skb->tail ||
5567                     skb_cloned(skb))
5568                         return;
5569
5570                 /* Nice, we can free page frag(s) right now */
5571                 __pskb_pull_tail(skb, skb->data_len);
5572         }
5573         /* At this point, skb->truesize might be over estimated,
5574          * because skb had a fragment, and fragments do not tell
5575          * their truesize.
5576          * When we pulled its content into skb->head, fragment
5577          * was freed, but __pskb_pull_tail() could not possibly
5578          * adjust skb->truesize, not knowing the frag truesize.
5579          */
5580         skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
5581 }