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