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