net: fix skb leak in __skb_tstamp_tx()
[platform/kernel/linux-starfive.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         osize = kmalloc_size_roundup(size);
510         data = kmalloc_reserve(osize, gfp_mask, node, &pfmemalloc);
511         if (unlikely(!data))
512                 goto nodata;
513         /* kmalloc_size_roundup() might give us more room than requested.
514          * Put skb_shared_info exactly at the end of allocated zone,
515          * to allow max possible filling before reallocation.
516          */
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, order, psize, 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         /* We might have to allocate high order pages, so compute what minimum
1557          * page order is needed.
1558          */
1559         order = 0;
1560         while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1561                 order++;
1562         psize = (PAGE_SIZE << order);
1563
1564         new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1565         for (i = 0; i < new_frags; i++) {
1566                 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1567                 if (!page) {
1568                         while (head) {
1569                                 struct page *next = (struct page *)page_private(head);
1570                                 put_page(head);
1571                                 head = next;
1572                         }
1573                         return -ENOMEM;
1574                 }
1575                 set_page_private(page, (unsigned long)head);
1576                 head = page;
1577         }
1578
1579         page = head;
1580         d_off = 0;
1581         for (i = 0; i < num_frags; i++) {
1582                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1583                 u32 p_off, p_len, copied;
1584                 struct page *p;
1585                 u8 *vaddr;
1586
1587                 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1588                                       p, p_off, p_len, copied) {
1589                         u32 copy, done = 0;
1590                         vaddr = kmap_atomic(p);
1591
1592                         while (done < p_len) {
1593                                 if (d_off == psize) {
1594                                         d_off = 0;
1595                                         page = (struct page *)page_private(page);
1596                                 }
1597                                 copy = min_t(u32, psize - d_off, p_len - done);
1598                                 memcpy(page_address(page) + d_off,
1599                                        vaddr + p_off + done, copy);
1600                                 done += copy;
1601                                 d_off += copy;
1602                         }
1603                         kunmap_atomic(vaddr);
1604                 }
1605         }
1606
1607         /* skb frags release userspace buffers */
1608         for (i = 0; i < num_frags; i++)
1609                 skb_frag_unref(skb, i);
1610
1611         /* skb frags point to kernel buffers */
1612         for (i = 0; i < new_frags - 1; i++) {
1613                 __skb_fill_page_desc(skb, i, head, 0, psize);
1614                 head = (struct page *)page_private(head);
1615         }
1616         __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1617         skb_shinfo(skb)->nr_frags = new_frags;
1618
1619 release:
1620         skb_zcopy_clear(skb, false);
1621         return 0;
1622 }
1623 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1624
1625 /**
1626  *      skb_clone       -       duplicate an sk_buff
1627  *      @skb: buffer to clone
1628  *      @gfp_mask: allocation priority
1629  *
1630  *      Duplicate an &sk_buff. The new one is not owned by a socket. Both
1631  *      copies share the same packet data but not structure. The new
1632  *      buffer has a reference count of 1. If the allocation fails the
1633  *      function returns %NULL otherwise the new buffer is returned.
1634  *
1635  *      If this function is called from an interrupt gfp_mask() must be
1636  *      %GFP_ATOMIC.
1637  */
1638
1639 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1640 {
1641         struct sk_buff_fclones *fclones = container_of(skb,
1642                                                        struct sk_buff_fclones,
1643                                                        skb1);
1644         struct sk_buff *n;
1645
1646         if (skb_orphan_frags(skb, gfp_mask))
1647                 return NULL;
1648
1649         if (skb->fclone == SKB_FCLONE_ORIG &&
1650             refcount_read(&fclones->fclone_ref) == 1) {
1651                 n = &fclones->skb2;
1652                 refcount_set(&fclones->fclone_ref, 2);
1653                 n->fclone = SKB_FCLONE_CLONE;
1654         } else {
1655                 if (skb_pfmemalloc(skb))
1656                         gfp_mask |= __GFP_MEMALLOC;
1657
1658                 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1659                 if (!n)
1660                         return NULL;
1661
1662                 n->fclone = SKB_FCLONE_UNAVAILABLE;
1663         }
1664
1665         return __skb_clone(n, skb);
1666 }
1667 EXPORT_SYMBOL(skb_clone);
1668
1669 void skb_headers_offset_update(struct sk_buff *skb, int off)
1670 {
1671         /* Only adjust this if it actually is csum_start rather than csum */
1672         if (skb->ip_summed == CHECKSUM_PARTIAL)
1673                 skb->csum_start += off;
1674         /* {transport,network,mac}_header and tail are relative to skb->head */
1675         skb->transport_header += off;
1676         skb->network_header   += off;
1677         if (skb_mac_header_was_set(skb))
1678                 skb->mac_header += off;
1679         skb->inner_transport_header += off;
1680         skb->inner_network_header += off;
1681         skb->inner_mac_header += off;
1682 }
1683 EXPORT_SYMBOL(skb_headers_offset_update);
1684
1685 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1686 {
1687         __copy_skb_header(new, old);
1688
1689         skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1690         skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1691         skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1692 }
1693 EXPORT_SYMBOL(skb_copy_header);
1694
1695 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1696 {
1697         if (skb_pfmemalloc(skb))
1698                 return SKB_ALLOC_RX;
1699         return 0;
1700 }
1701
1702 /**
1703  *      skb_copy        -       create private copy of an sk_buff
1704  *      @skb: buffer to copy
1705  *      @gfp_mask: allocation priority
1706  *
1707  *      Make a copy of both an &sk_buff and its data. This is used when the
1708  *      caller wishes to modify the data and needs a private copy of the
1709  *      data to alter. Returns %NULL on failure or the pointer to the buffer
1710  *      on success. The returned buffer has a reference count of 1.
1711  *
1712  *      As by-product this function converts non-linear &sk_buff to linear
1713  *      one, so that &sk_buff becomes completely private and caller is allowed
1714  *      to modify all the data of returned buffer. This means that this
1715  *      function is not recommended for use in circumstances when only
1716  *      header is going to be modified. Use pskb_copy() instead.
1717  */
1718
1719 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1720 {
1721         int headerlen = skb_headroom(skb);
1722         unsigned int size = skb_end_offset(skb) + skb->data_len;
1723         struct sk_buff *n = __alloc_skb(size, gfp_mask,
1724                                         skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1725
1726         if (!n)
1727                 return NULL;
1728
1729         /* Set the data pointer */
1730         skb_reserve(n, headerlen);
1731         /* Set the tail pointer and length */
1732         skb_put(n, skb->len);
1733
1734         BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1735
1736         skb_copy_header(n, skb);
1737         return n;
1738 }
1739 EXPORT_SYMBOL(skb_copy);
1740
1741 /**
1742  *      __pskb_copy_fclone      -  create copy of an sk_buff with private head.
1743  *      @skb: buffer to copy
1744  *      @headroom: headroom of new skb
1745  *      @gfp_mask: allocation priority
1746  *      @fclone: if true allocate the copy of the skb from the fclone
1747  *      cache instead of the head cache; it is recommended to set this
1748  *      to true for the cases where the copy will likely be cloned
1749  *
1750  *      Make a copy of both an &sk_buff and part of its data, located
1751  *      in header. Fragmented data remain shared. This is used when
1752  *      the caller wishes to modify only header of &sk_buff and needs
1753  *      private copy of the header to alter. Returns %NULL on failure
1754  *      or the pointer to the buffer on success.
1755  *      The returned buffer has a reference count of 1.
1756  */
1757
1758 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1759                                    gfp_t gfp_mask, bool fclone)
1760 {
1761         unsigned int size = skb_headlen(skb) + headroom;
1762         int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1763         struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1764
1765         if (!n)
1766                 goto out;
1767
1768         /* Set the data pointer */
1769         skb_reserve(n, headroom);
1770         /* Set the tail pointer and length */
1771         skb_put(n, skb_headlen(skb));
1772         /* Copy the bytes */
1773         skb_copy_from_linear_data(skb, n->data, n->len);
1774
1775         n->truesize += skb->data_len;
1776         n->data_len  = skb->data_len;
1777         n->len       = skb->len;
1778
1779         if (skb_shinfo(skb)->nr_frags) {
1780                 int i;
1781
1782                 if (skb_orphan_frags(skb, gfp_mask) ||
1783                     skb_zerocopy_clone(n, skb, gfp_mask)) {
1784                         kfree_skb(n);
1785                         n = NULL;
1786                         goto out;
1787                 }
1788                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1789                         skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1790                         skb_frag_ref(skb, i);
1791                 }
1792                 skb_shinfo(n)->nr_frags = i;
1793         }
1794
1795         if (skb_has_frag_list(skb)) {
1796                 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1797                 skb_clone_fraglist(n);
1798         }
1799
1800         skb_copy_header(n, skb);
1801 out:
1802         return n;
1803 }
1804 EXPORT_SYMBOL(__pskb_copy_fclone);
1805
1806 /**
1807  *      pskb_expand_head - reallocate header of &sk_buff
1808  *      @skb: buffer to reallocate
1809  *      @nhead: room to add at head
1810  *      @ntail: room to add at tail
1811  *      @gfp_mask: allocation priority
1812  *
1813  *      Expands (or creates identical copy, if @nhead and @ntail are zero)
1814  *      header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1815  *      reference count of 1. Returns zero in the case of success or error,
1816  *      if expansion failed. In the last case, &sk_buff is not changed.
1817  *
1818  *      All the pointers pointing into skb header may change and must be
1819  *      reloaded after call to this function.
1820  */
1821
1822 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1823                      gfp_t gfp_mask)
1824 {
1825         unsigned int osize = skb_end_offset(skb);
1826         unsigned int size = osize + nhead + ntail;
1827         long off;
1828         u8 *data;
1829         int i;
1830
1831         BUG_ON(nhead < 0);
1832
1833         BUG_ON(skb_shared(skb));
1834
1835         skb_zcopy_downgrade_managed(skb);
1836
1837         if (skb_pfmemalloc(skb))
1838                 gfp_mask |= __GFP_MEMALLOC;
1839
1840         size = SKB_DATA_ALIGN(size);
1841         size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1842         size = kmalloc_size_roundup(size);
1843         data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
1844         if (!data)
1845                 goto nodata;
1846         size = SKB_WITH_OVERHEAD(size);
1847
1848         /* Copy only real data... and, alas, header. This should be
1849          * optimized for the cases when header is void.
1850          */
1851         memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1852
1853         memcpy((struct skb_shared_info *)(data + size),
1854                skb_shinfo(skb),
1855                offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1856
1857         /*
1858          * if shinfo is shared we must drop the old head gracefully, but if it
1859          * is not we can just drop the old head and let the existing refcount
1860          * be since all we did is relocate the values
1861          */
1862         if (skb_cloned(skb)) {
1863                 if (skb_orphan_frags(skb, gfp_mask))
1864                         goto nofrags;
1865                 if (skb_zcopy(skb))
1866                         refcount_inc(&skb_uarg(skb)->refcnt);
1867                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1868                         skb_frag_ref(skb, i);
1869
1870                 if (skb_has_frag_list(skb))
1871                         skb_clone_fraglist(skb);
1872
1873                 skb_release_data(skb);
1874         } else {
1875                 skb_free_head(skb);
1876         }
1877         off = (data + nhead) - skb->head;
1878
1879         skb->head     = data;
1880         skb->head_frag = 0;
1881         skb->data    += off;
1882
1883         skb_set_end_offset(skb, size);
1884 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1885         off           = nhead;
1886 #endif
1887         skb->tail             += off;
1888         skb_headers_offset_update(skb, nhead);
1889         skb->cloned   = 0;
1890         skb->hdr_len  = 0;
1891         skb->nohdr    = 0;
1892         atomic_set(&skb_shinfo(skb)->dataref, 1);
1893
1894         skb_metadata_clear(skb);
1895
1896         /* It is not generally safe to change skb->truesize.
1897          * For the moment, we really care of rx path, or
1898          * when skb is orphaned (not attached to a socket).
1899          */
1900         if (!skb->sk || skb->destructor == sock_edemux)
1901                 skb->truesize += size - osize;
1902
1903         return 0;
1904
1905 nofrags:
1906         kfree(data);
1907 nodata:
1908         return -ENOMEM;
1909 }
1910 EXPORT_SYMBOL(pskb_expand_head);
1911
1912 /* Make private copy of skb with writable head and some headroom */
1913
1914 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1915 {
1916         struct sk_buff *skb2;
1917         int delta = headroom - skb_headroom(skb);
1918
1919         if (delta <= 0)
1920                 skb2 = pskb_copy(skb, GFP_ATOMIC);
1921         else {
1922                 skb2 = skb_clone(skb, GFP_ATOMIC);
1923                 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1924                                              GFP_ATOMIC)) {
1925                         kfree_skb(skb2);
1926                         skb2 = NULL;
1927                 }
1928         }
1929         return skb2;
1930 }
1931 EXPORT_SYMBOL(skb_realloc_headroom);
1932
1933 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1934 {
1935         unsigned int saved_end_offset, saved_truesize;
1936         struct skb_shared_info *shinfo;
1937         int res;
1938
1939         saved_end_offset = skb_end_offset(skb);
1940         saved_truesize = skb->truesize;
1941
1942         res = pskb_expand_head(skb, 0, 0, pri);
1943         if (res)
1944                 return res;
1945
1946         skb->truesize = saved_truesize;
1947
1948         if (likely(skb_end_offset(skb) == saved_end_offset))
1949                 return 0;
1950
1951         shinfo = skb_shinfo(skb);
1952
1953         /* We are about to change back skb->end,
1954          * we need to move skb_shinfo() to its new location.
1955          */
1956         memmove(skb->head + saved_end_offset,
1957                 shinfo,
1958                 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1959
1960         skb_set_end_offset(skb, saved_end_offset);
1961
1962         return 0;
1963 }
1964
1965 /**
1966  *      skb_expand_head - reallocate header of &sk_buff
1967  *      @skb: buffer to reallocate
1968  *      @headroom: needed headroom
1969  *
1970  *      Unlike skb_realloc_headroom, this one does not allocate a new skb
1971  *      if possible; copies skb->sk to new skb as needed
1972  *      and frees original skb in case of failures.
1973  *
1974  *      It expect increased headroom and generates warning otherwise.
1975  */
1976
1977 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1978 {
1979         int delta = headroom - skb_headroom(skb);
1980         int osize = skb_end_offset(skb);
1981         struct sock *sk = skb->sk;
1982
1983         if (WARN_ONCE(delta <= 0,
1984                       "%s is expecting an increase in the headroom", __func__))
1985                 return skb;
1986
1987         delta = SKB_DATA_ALIGN(delta);
1988         /* pskb_expand_head() might crash, if skb is shared. */
1989         if (skb_shared(skb) || !is_skb_wmem(skb)) {
1990                 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1991
1992                 if (unlikely(!nskb))
1993                         goto fail;
1994
1995                 if (sk)
1996                         skb_set_owner_w(nskb, sk);
1997                 consume_skb(skb);
1998                 skb = nskb;
1999         }
2000         if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2001                 goto fail;
2002
2003         if (sk && is_skb_wmem(skb)) {
2004                 delta = skb_end_offset(skb) - osize;
2005                 refcount_add(delta, &sk->sk_wmem_alloc);
2006                 skb->truesize += delta;
2007         }
2008         return skb;
2009
2010 fail:
2011         kfree_skb(skb);
2012         return NULL;
2013 }
2014 EXPORT_SYMBOL(skb_expand_head);
2015
2016 /**
2017  *      skb_copy_expand -       copy and expand sk_buff
2018  *      @skb: buffer to copy
2019  *      @newheadroom: new free bytes at head
2020  *      @newtailroom: new free bytes at tail
2021  *      @gfp_mask: allocation priority
2022  *
2023  *      Make a copy of both an &sk_buff and its data and while doing so
2024  *      allocate additional space.
2025  *
2026  *      This is used when the caller wishes to modify the data and needs a
2027  *      private copy of the data to alter as well as more space for new fields.
2028  *      Returns %NULL on failure or the pointer to the buffer
2029  *      on success. The returned buffer has a reference count of 1.
2030  *
2031  *      You must pass %GFP_ATOMIC as the allocation priority if this function
2032  *      is called from an interrupt.
2033  */
2034 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2035                                 int newheadroom, int newtailroom,
2036                                 gfp_t gfp_mask)
2037 {
2038         /*
2039          *      Allocate the copy buffer
2040          */
2041         struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2042                                         gfp_mask, skb_alloc_rx_flag(skb),
2043                                         NUMA_NO_NODE);
2044         int oldheadroom = skb_headroom(skb);
2045         int head_copy_len, head_copy_off;
2046
2047         if (!n)
2048                 return NULL;
2049
2050         skb_reserve(n, newheadroom);
2051
2052         /* Set the tail pointer and length */
2053         skb_put(n, skb->len);
2054
2055         head_copy_len = oldheadroom;
2056         head_copy_off = 0;
2057         if (newheadroom <= head_copy_len)
2058                 head_copy_len = newheadroom;
2059         else
2060                 head_copy_off = newheadroom - head_copy_len;
2061
2062         /* Copy the linear header and data. */
2063         BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2064                              skb->len + head_copy_len));
2065
2066         skb_copy_header(n, skb);
2067
2068         skb_headers_offset_update(n, newheadroom - oldheadroom);
2069
2070         return n;
2071 }
2072 EXPORT_SYMBOL(skb_copy_expand);
2073
2074 /**
2075  *      __skb_pad               -       zero pad the tail of an skb
2076  *      @skb: buffer to pad
2077  *      @pad: space to pad
2078  *      @free_on_error: free buffer on error
2079  *
2080  *      Ensure that a buffer is followed by a padding area that is zero
2081  *      filled. Used by network drivers which may DMA or transfer data
2082  *      beyond the buffer end onto the wire.
2083  *
2084  *      May return error in out of memory cases. The skb is freed on error
2085  *      if @free_on_error is true.
2086  */
2087
2088 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2089 {
2090         int err;
2091         int ntail;
2092
2093         /* If the skbuff is non linear tailroom is always zero.. */
2094         if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2095                 memset(skb->data+skb->len, 0, pad);
2096                 return 0;
2097         }
2098
2099         ntail = skb->data_len + pad - (skb->end - skb->tail);
2100         if (likely(skb_cloned(skb) || ntail > 0)) {
2101                 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2102                 if (unlikely(err))
2103                         goto free_skb;
2104         }
2105
2106         /* FIXME: The use of this function with non-linear skb's really needs
2107          * to be audited.
2108          */
2109         err = skb_linearize(skb);
2110         if (unlikely(err))
2111                 goto free_skb;
2112
2113         memset(skb->data + skb->len, 0, pad);
2114         return 0;
2115
2116 free_skb:
2117         if (free_on_error)
2118                 kfree_skb(skb);
2119         return err;
2120 }
2121 EXPORT_SYMBOL(__skb_pad);
2122
2123 /**
2124  *      pskb_put - add data to the tail of a potentially fragmented buffer
2125  *      @skb: start of the buffer to use
2126  *      @tail: tail fragment of the buffer to use
2127  *      @len: amount of data to add
2128  *
2129  *      This function extends the used data area of the potentially
2130  *      fragmented buffer. @tail must be the last fragment of @skb -- or
2131  *      @skb itself. If this would exceed the total buffer size the kernel
2132  *      will panic. A pointer to the first byte of the extra data is
2133  *      returned.
2134  */
2135
2136 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2137 {
2138         if (tail != skb) {
2139                 skb->data_len += len;
2140                 skb->len += len;
2141         }
2142         return skb_put(tail, len);
2143 }
2144 EXPORT_SYMBOL_GPL(pskb_put);
2145
2146 /**
2147  *      skb_put - add data to a buffer
2148  *      @skb: buffer to use
2149  *      @len: amount of data to add
2150  *
2151  *      This function extends the used data area of the buffer. If this would
2152  *      exceed the total buffer size the kernel will panic. A pointer to the
2153  *      first byte of the extra data is returned.
2154  */
2155 void *skb_put(struct sk_buff *skb, unsigned int len)
2156 {
2157         void *tmp = skb_tail_pointer(skb);
2158         SKB_LINEAR_ASSERT(skb);
2159         skb->tail += len;
2160         skb->len  += len;
2161         if (unlikely(skb->tail > skb->end))
2162                 skb_over_panic(skb, len, __builtin_return_address(0));
2163         return tmp;
2164 }
2165 EXPORT_SYMBOL(skb_put);
2166
2167 /**
2168  *      skb_push - add data to the start of a buffer
2169  *      @skb: buffer to use
2170  *      @len: amount of data to add
2171  *
2172  *      This function extends the used data area of the buffer at the buffer
2173  *      start. If this would exceed the total buffer headroom the kernel will
2174  *      panic. A pointer to the first byte of the extra data is returned.
2175  */
2176 void *skb_push(struct sk_buff *skb, unsigned int len)
2177 {
2178         skb->data -= len;
2179         skb->len  += len;
2180         if (unlikely(skb->data < skb->head))
2181                 skb_under_panic(skb, len, __builtin_return_address(0));
2182         return skb->data;
2183 }
2184 EXPORT_SYMBOL(skb_push);
2185
2186 /**
2187  *      skb_pull - remove data from the start of a buffer
2188  *      @skb: buffer to use
2189  *      @len: amount of data to remove
2190  *
2191  *      This function removes data from the start of a buffer, returning
2192  *      the memory to the headroom. A pointer to the next data in the buffer
2193  *      is returned. Once the data has been pulled future pushes will overwrite
2194  *      the old data.
2195  */
2196 void *skb_pull(struct sk_buff *skb, unsigned int len)
2197 {
2198         return skb_pull_inline(skb, len);
2199 }
2200 EXPORT_SYMBOL(skb_pull);
2201
2202 /**
2203  *      skb_pull_data - remove data from the start of a buffer returning its
2204  *      original position.
2205  *      @skb: buffer to use
2206  *      @len: amount of data to remove
2207  *
2208  *      This function removes data from the start of a buffer, returning
2209  *      the memory to the headroom. A pointer to the original data in the buffer
2210  *      is returned after checking if there is enough data to pull. Once the
2211  *      data has been pulled future pushes will overwrite the old data.
2212  */
2213 void *skb_pull_data(struct sk_buff *skb, size_t len)
2214 {
2215         void *data = skb->data;
2216
2217         if (skb->len < len)
2218                 return NULL;
2219
2220         skb_pull(skb, len);
2221
2222         return data;
2223 }
2224 EXPORT_SYMBOL(skb_pull_data);
2225
2226 /**
2227  *      skb_trim - remove end from a buffer
2228  *      @skb: buffer to alter
2229  *      @len: new length
2230  *
2231  *      Cut the length of a buffer down by removing data from the tail. If
2232  *      the buffer is already under the length specified it is not modified.
2233  *      The skb must be linear.
2234  */
2235 void skb_trim(struct sk_buff *skb, unsigned int len)
2236 {
2237         if (skb->len > len)
2238                 __skb_trim(skb, len);
2239 }
2240 EXPORT_SYMBOL(skb_trim);
2241
2242 /* Trims skb to length len. It can change skb pointers.
2243  */
2244
2245 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2246 {
2247         struct sk_buff **fragp;
2248         struct sk_buff *frag;
2249         int offset = skb_headlen(skb);
2250         int nfrags = skb_shinfo(skb)->nr_frags;
2251         int i;
2252         int err;
2253
2254         if (skb_cloned(skb) &&
2255             unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2256                 return err;
2257
2258         i = 0;
2259         if (offset >= len)
2260                 goto drop_pages;
2261
2262         for (; i < nfrags; i++) {
2263                 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2264
2265                 if (end < len) {
2266                         offset = end;
2267                         continue;
2268                 }
2269
2270                 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2271
2272 drop_pages:
2273                 skb_shinfo(skb)->nr_frags = i;
2274
2275                 for (; i < nfrags; i++)
2276                         skb_frag_unref(skb, i);
2277
2278                 if (skb_has_frag_list(skb))
2279                         skb_drop_fraglist(skb);
2280                 goto done;
2281         }
2282
2283         for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2284              fragp = &frag->next) {
2285                 int end = offset + frag->len;
2286
2287                 if (skb_shared(frag)) {
2288                         struct sk_buff *nfrag;
2289
2290                         nfrag = skb_clone(frag, GFP_ATOMIC);
2291                         if (unlikely(!nfrag))
2292                                 return -ENOMEM;
2293
2294                         nfrag->next = frag->next;
2295                         consume_skb(frag);
2296                         frag = nfrag;
2297                         *fragp = frag;
2298                 }
2299
2300                 if (end < len) {
2301                         offset = end;
2302                         continue;
2303                 }
2304
2305                 if (end > len &&
2306                     unlikely((err = pskb_trim(frag, len - offset))))
2307                         return err;
2308
2309                 if (frag->next)
2310                         skb_drop_list(&frag->next);
2311                 break;
2312         }
2313
2314 done:
2315         if (len > skb_headlen(skb)) {
2316                 skb->data_len -= skb->len - len;
2317                 skb->len       = len;
2318         } else {
2319                 skb->len       = len;
2320                 skb->data_len  = 0;
2321                 skb_set_tail_pointer(skb, len);
2322         }
2323
2324         if (!skb->sk || skb->destructor == sock_edemux)
2325                 skb_condense(skb);
2326         return 0;
2327 }
2328 EXPORT_SYMBOL(___pskb_trim);
2329
2330 /* Note : use pskb_trim_rcsum() instead of calling this directly
2331  */
2332 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2333 {
2334         if (skb->ip_summed == CHECKSUM_COMPLETE) {
2335                 int delta = skb->len - len;
2336
2337                 skb->csum = csum_block_sub(skb->csum,
2338                                            skb_checksum(skb, len, delta, 0),
2339                                            len);
2340         } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2341                 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2342                 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2343
2344                 if (offset + sizeof(__sum16) > hdlen)
2345                         return -EINVAL;
2346         }
2347         return __pskb_trim(skb, len);
2348 }
2349 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2350
2351 /**
2352  *      __pskb_pull_tail - advance tail of skb header
2353  *      @skb: buffer to reallocate
2354  *      @delta: number of bytes to advance tail
2355  *
2356  *      The function makes a sense only on a fragmented &sk_buff,
2357  *      it expands header moving its tail forward and copying necessary
2358  *      data from fragmented part.
2359  *
2360  *      &sk_buff MUST have reference count of 1.
2361  *
2362  *      Returns %NULL (and &sk_buff does not change) if pull failed
2363  *      or value of new tail of skb in the case of success.
2364  *
2365  *      All the pointers pointing into skb header may change and must be
2366  *      reloaded after call to this function.
2367  */
2368
2369 /* Moves tail of skb head forward, copying data from fragmented part,
2370  * when it is necessary.
2371  * 1. It may fail due to malloc failure.
2372  * 2. It may change skb pointers.
2373  *
2374  * It is pretty complicated. Luckily, it is called only in exceptional cases.
2375  */
2376 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2377 {
2378         /* If skb has not enough free space at tail, get new one
2379          * plus 128 bytes for future expansions. If we have enough
2380          * room at tail, reallocate without expansion only if skb is cloned.
2381          */
2382         int i, k, eat = (skb->tail + delta) - skb->end;
2383
2384         if (eat > 0 || skb_cloned(skb)) {
2385                 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2386                                      GFP_ATOMIC))
2387                         return NULL;
2388         }
2389
2390         BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2391                              skb_tail_pointer(skb), delta));
2392
2393         /* Optimization: no fragments, no reasons to preestimate
2394          * size of pulled pages. Superb.
2395          */
2396         if (!skb_has_frag_list(skb))
2397                 goto pull_pages;
2398
2399         /* Estimate size of pulled pages. */
2400         eat = delta;
2401         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2402                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2403
2404                 if (size >= eat)
2405                         goto pull_pages;
2406                 eat -= size;
2407         }
2408
2409         /* If we need update frag list, we are in troubles.
2410          * Certainly, it is possible to add an offset to skb data,
2411          * but taking into account that pulling is expected to
2412          * be very rare operation, it is worth to fight against
2413          * further bloating skb head and crucify ourselves here instead.
2414          * Pure masohism, indeed. 8)8)
2415          */
2416         if (eat) {
2417                 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2418                 struct sk_buff *clone = NULL;
2419                 struct sk_buff *insp = NULL;
2420
2421                 do {
2422                         if (list->len <= eat) {
2423                                 /* Eaten as whole. */
2424                                 eat -= list->len;
2425                                 list = list->next;
2426                                 insp = list;
2427                         } else {
2428                                 /* Eaten partially. */
2429                                 if (skb_is_gso(skb) && !list->head_frag &&
2430                                     skb_headlen(list))
2431                                         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2432
2433                                 if (skb_shared(list)) {
2434                                         /* Sucks! We need to fork list. :-( */
2435                                         clone = skb_clone(list, GFP_ATOMIC);
2436                                         if (!clone)
2437                                                 return NULL;
2438                                         insp = list->next;
2439                                         list = clone;
2440                                 } else {
2441                                         /* This may be pulled without
2442                                          * problems. */
2443                                         insp = list;
2444                                 }
2445                                 if (!pskb_pull(list, eat)) {
2446                                         kfree_skb(clone);
2447                                         return NULL;
2448                                 }
2449                                 break;
2450                         }
2451                 } while (eat);
2452
2453                 /* Free pulled out fragments. */
2454                 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2455                         skb_shinfo(skb)->frag_list = list->next;
2456                         consume_skb(list);
2457                 }
2458                 /* And insert new clone at head. */
2459                 if (clone) {
2460                         clone->next = list;
2461                         skb_shinfo(skb)->frag_list = clone;
2462                 }
2463         }
2464         /* Success! Now we may commit changes to skb data. */
2465
2466 pull_pages:
2467         eat = delta;
2468         k = 0;
2469         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2470                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2471
2472                 if (size <= eat) {
2473                         skb_frag_unref(skb, i);
2474                         eat -= size;
2475                 } else {
2476                         skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2477
2478                         *frag = skb_shinfo(skb)->frags[i];
2479                         if (eat) {
2480                                 skb_frag_off_add(frag, eat);
2481                                 skb_frag_size_sub(frag, eat);
2482                                 if (!i)
2483                                         goto end;
2484                                 eat = 0;
2485                         }
2486                         k++;
2487                 }
2488         }
2489         skb_shinfo(skb)->nr_frags = k;
2490
2491 end:
2492         skb->tail     += delta;
2493         skb->data_len -= delta;
2494
2495         if (!skb->data_len)
2496                 skb_zcopy_clear(skb, false);
2497
2498         return skb_tail_pointer(skb);
2499 }
2500 EXPORT_SYMBOL(__pskb_pull_tail);
2501
2502 /**
2503  *      skb_copy_bits - copy bits from skb to kernel buffer
2504  *      @skb: source skb
2505  *      @offset: offset in source
2506  *      @to: destination buffer
2507  *      @len: number of bytes to copy
2508  *
2509  *      Copy the specified number of bytes from the source skb to the
2510  *      destination buffer.
2511  *
2512  *      CAUTION ! :
2513  *              If its prototype is ever changed,
2514  *              check arch/{*}/net/{*}.S files,
2515  *              since it is called from BPF assembly code.
2516  */
2517 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2518 {
2519         int start = skb_headlen(skb);
2520         struct sk_buff *frag_iter;
2521         int i, copy;
2522
2523         if (offset > (int)skb->len - len)
2524                 goto fault;
2525
2526         /* Copy header. */
2527         if ((copy = start - offset) > 0) {
2528                 if (copy > len)
2529                         copy = len;
2530                 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2531                 if ((len -= copy) == 0)
2532                         return 0;
2533                 offset += copy;
2534                 to     += copy;
2535         }
2536
2537         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2538                 int end;
2539                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2540
2541                 WARN_ON(start > offset + len);
2542
2543                 end = start + skb_frag_size(f);
2544                 if ((copy = end - offset) > 0) {
2545                         u32 p_off, p_len, copied;
2546                         struct page *p;
2547                         u8 *vaddr;
2548
2549                         if (copy > len)
2550                                 copy = len;
2551
2552                         skb_frag_foreach_page(f,
2553                                               skb_frag_off(f) + offset - start,
2554                                               copy, p, p_off, p_len, copied) {
2555                                 vaddr = kmap_atomic(p);
2556                                 memcpy(to + copied, vaddr + p_off, p_len);
2557                                 kunmap_atomic(vaddr);
2558                         }
2559
2560                         if ((len -= copy) == 0)
2561                                 return 0;
2562                         offset += copy;
2563                         to     += copy;
2564                 }
2565                 start = end;
2566         }
2567
2568         skb_walk_frags(skb, frag_iter) {
2569                 int end;
2570
2571                 WARN_ON(start > offset + len);
2572
2573                 end = start + frag_iter->len;
2574                 if ((copy = end - offset) > 0) {
2575                         if (copy > len)
2576                                 copy = len;
2577                         if (skb_copy_bits(frag_iter, offset - start, to, copy))
2578                                 goto fault;
2579                         if ((len -= copy) == 0)
2580                                 return 0;
2581                         offset += copy;
2582                         to     += copy;
2583                 }
2584                 start = end;
2585         }
2586
2587         if (!len)
2588                 return 0;
2589
2590 fault:
2591         return -EFAULT;
2592 }
2593 EXPORT_SYMBOL(skb_copy_bits);
2594
2595 /*
2596  * Callback from splice_to_pipe(), if we need to release some pages
2597  * at the end of the spd in case we error'ed out in filling the pipe.
2598  */
2599 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2600 {
2601         put_page(spd->pages[i]);
2602 }
2603
2604 static struct page *linear_to_page(struct page *page, unsigned int *len,
2605                                    unsigned int *offset,
2606                                    struct sock *sk)
2607 {
2608         struct page_frag *pfrag = sk_page_frag(sk);
2609
2610         if (!sk_page_frag_refill(sk, pfrag))
2611                 return NULL;
2612
2613         *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2614
2615         memcpy(page_address(pfrag->page) + pfrag->offset,
2616                page_address(page) + *offset, *len);
2617         *offset = pfrag->offset;
2618         pfrag->offset += *len;
2619
2620         return pfrag->page;
2621 }
2622
2623 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2624                              struct page *page,
2625                              unsigned int offset)
2626 {
2627         return  spd->nr_pages &&
2628                 spd->pages[spd->nr_pages - 1] == page &&
2629                 (spd->partial[spd->nr_pages - 1].offset +
2630                  spd->partial[spd->nr_pages - 1].len == offset);
2631 }
2632
2633 /*
2634  * Fill page/offset/length into spd, if it can hold more pages.
2635  */
2636 static bool spd_fill_page(struct splice_pipe_desc *spd,
2637                           struct pipe_inode_info *pipe, struct page *page,
2638                           unsigned int *len, unsigned int offset,
2639                           bool linear,
2640                           struct sock *sk)
2641 {
2642         if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2643                 return true;
2644
2645         if (linear) {
2646                 page = linear_to_page(page, len, &offset, sk);
2647                 if (!page)
2648                         return true;
2649         }
2650         if (spd_can_coalesce(spd, page, offset)) {
2651                 spd->partial[spd->nr_pages - 1].len += *len;
2652                 return false;
2653         }
2654         get_page(page);
2655         spd->pages[spd->nr_pages] = page;
2656         spd->partial[spd->nr_pages].len = *len;
2657         spd->partial[spd->nr_pages].offset = offset;
2658         spd->nr_pages++;
2659
2660         return false;
2661 }
2662
2663 static bool __splice_segment(struct page *page, unsigned int poff,
2664                              unsigned int plen, unsigned int *off,
2665                              unsigned int *len,
2666                              struct splice_pipe_desc *spd, bool linear,
2667                              struct sock *sk,
2668                              struct pipe_inode_info *pipe)
2669 {
2670         if (!*len)
2671                 return true;
2672
2673         /* skip this segment if already processed */
2674         if (*off >= plen) {
2675                 *off -= plen;
2676                 return false;
2677         }
2678
2679         /* ignore any bits we already processed */
2680         poff += *off;
2681         plen -= *off;
2682         *off = 0;
2683
2684         do {
2685                 unsigned int flen = min(*len, plen);
2686
2687                 if (spd_fill_page(spd, pipe, page, &flen, poff,
2688                                   linear, sk))
2689                         return true;
2690                 poff += flen;
2691                 plen -= flen;
2692                 *len -= flen;
2693         } while (*len && plen);
2694
2695         return false;
2696 }
2697
2698 /*
2699  * Map linear and fragment data from the skb to spd. It reports true if the
2700  * pipe is full or if we already spliced the requested length.
2701  */
2702 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2703                               unsigned int *offset, unsigned int *len,
2704                               struct splice_pipe_desc *spd, struct sock *sk)
2705 {
2706         int seg;
2707         struct sk_buff *iter;
2708
2709         /* map the linear part :
2710          * If skb->head_frag is set, this 'linear' part is backed by a
2711          * fragment, and if the head is not shared with any clones then
2712          * we can avoid a copy since we own the head portion of this page.
2713          */
2714         if (__splice_segment(virt_to_page(skb->data),
2715                              (unsigned long) skb->data & (PAGE_SIZE - 1),
2716                              skb_headlen(skb),
2717                              offset, len, spd,
2718                              skb_head_is_locked(skb),
2719                              sk, pipe))
2720                 return true;
2721
2722         /*
2723          * then map the fragments
2724          */
2725         for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2726                 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2727
2728                 if (__splice_segment(skb_frag_page(f),
2729                                      skb_frag_off(f), skb_frag_size(f),
2730                                      offset, len, spd, false, sk, pipe))
2731                         return true;
2732         }
2733
2734         skb_walk_frags(skb, iter) {
2735                 if (*offset >= iter->len) {
2736                         *offset -= iter->len;
2737                         continue;
2738                 }
2739                 /* __skb_splice_bits() only fails if the output has no room
2740                  * left, so no point in going over the frag_list for the error
2741                  * case.
2742                  */
2743                 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2744                         return true;
2745         }
2746
2747         return false;
2748 }
2749
2750 /*
2751  * Map data from the skb to a pipe. Should handle both the linear part,
2752  * the fragments, and the frag list.
2753  */
2754 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2755                     struct pipe_inode_info *pipe, unsigned int tlen,
2756                     unsigned int flags)
2757 {
2758         struct partial_page partial[MAX_SKB_FRAGS];
2759         struct page *pages[MAX_SKB_FRAGS];
2760         struct splice_pipe_desc spd = {
2761                 .pages = pages,
2762                 .partial = partial,
2763                 .nr_pages_max = MAX_SKB_FRAGS,
2764                 .ops = &nosteal_pipe_buf_ops,
2765                 .spd_release = sock_spd_release,
2766         };
2767         int ret = 0;
2768
2769         __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2770
2771         if (spd.nr_pages)
2772                 ret = splice_to_pipe(pipe, &spd);
2773
2774         return ret;
2775 }
2776 EXPORT_SYMBOL_GPL(skb_splice_bits);
2777
2778 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2779                             struct kvec *vec, size_t num, size_t size)
2780 {
2781         struct socket *sock = sk->sk_socket;
2782
2783         if (!sock)
2784                 return -EINVAL;
2785         return kernel_sendmsg(sock, msg, vec, num, size);
2786 }
2787
2788 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2789                              size_t size, int flags)
2790 {
2791         struct socket *sock = sk->sk_socket;
2792
2793         if (!sock)
2794                 return -EINVAL;
2795         return kernel_sendpage(sock, page, offset, size, flags);
2796 }
2797
2798 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2799                             struct kvec *vec, size_t num, size_t size);
2800 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2801                              size_t size, int flags);
2802 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2803                            int len, sendmsg_func sendmsg, sendpage_func sendpage)
2804 {
2805         unsigned int orig_len = len;
2806         struct sk_buff *head = skb;
2807         unsigned short fragidx;
2808         int slen, ret;
2809
2810 do_frag_list:
2811
2812         /* Deal with head data */
2813         while (offset < skb_headlen(skb) && len) {
2814                 struct kvec kv;
2815                 struct msghdr msg;
2816
2817                 slen = min_t(int, len, skb_headlen(skb) - offset);
2818                 kv.iov_base = skb->data + offset;
2819                 kv.iov_len = slen;
2820                 memset(&msg, 0, sizeof(msg));
2821                 msg.msg_flags = MSG_DONTWAIT;
2822
2823                 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2824                                       sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2825                 if (ret <= 0)
2826                         goto error;
2827
2828                 offset += ret;
2829                 len -= ret;
2830         }
2831
2832         /* All the data was skb head? */
2833         if (!len)
2834                 goto out;
2835
2836         /* Make offset relative to start of frags */
2837         offset -= skb_headlen(skb);
2838
2839         /* Find where we are in frag list */
2840         for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2841                 skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
2842
2843                 if (offset < skb_frag_size(frag))
2844                         break;
2845
2846                 offset -= skb_frag_size(frag);
2847         }
2848
2849         for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2850                 skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
2851
2852                 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2853
2854                 while (slen) {
2855                         ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2856                                               sendpage_unlocked, sk,
2857                                               skb_frag_page(frag),
2858                                               skb_frag_off(frag) + offset,
2859                                               slen, MSG_DONTWAIT);
2860                         if (ret <= 0)
2861                                 goto error;
2862
2863                         len -= ret;
2864                         offset += ret;
2865                         slen -= ret;
2866                 }
2867
2868                 offset = 0;
2869         }
2870
2871         if (len) {
2872                 /* Process any frag lists */
2873
2874                 if (skb == head) {
2875                         if (skb_has_frag_list(skb)) {
2876                                 skb = skb_shinfo(skb)->frag_list;
2877                                 goto do_frag_list;
2878                         }
2879                 } else if (skb->next) {
2880                         skb = skb->next;
2881                         goto do_frag_list;
2882                 }
2883         }
2884
2885 out:
2886         return orig_len - len;
2887
2888 error:
2889         return orig_len == len ? ret : orig_len - len;
2890 }
2891
2892 /* Send skb data on a socket. Socket must be locked. */
2893 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2894                          int len)
2895 {
2896         return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2897                                kernel_sendpage_locked);
2898 }
2899 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2900
2901 /* Send skb data on a socket. Socket must be unlocked. */
2902 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2903 {
2904         return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2905                                sendpage_unlocked);
2906 }
2907
2908 /**
2909  *      skb_store_bits - store bits from kernel buffer to skb
2910  *      @skb: destination buffer
2911  *      @offset: offset in destination
2912  *      @from: source buffer
2913  *      @len: number of bytes to copy
2914  *
2915  *      Copy the specified number of bytes from the source buffer to the
2916  *      destination skb.  This function handles all the messy bits of
2917  *      traversing fragment lists and such.
2918  */
2919
2920 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2921 {
2922         int start = skb_headlen(skb);
2923         struct sk_buff *frag_iter;
2924         int i, copy;
2925
2926         if (offset > (int)skb->len - len)
2927                 goto fault;
2928
2929         if ((copy = start - offset) > 0) {
2930                 if (copy > len)
2931                         copy = len;
2932                 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2933                 if ((len -= copy) == 0)
2934                         return 0;
2935                 offset += copy;
2936                 from += copy;
2937         }
2938
2939         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2940                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2941                 int end;
2942
2943                 WARN_ON(start > offset + len);
2944
2945                 end = start + skb_frag_size(frag);
2946                 if ((copy = end - offset) > 0) {
2947                         u32 p_off, p_len, copied;
2948                         struct page *p;
2949                         u8 *vaddr;
2950
2951                         if (copy > len)
2952                                 copy = len;
2953
2954                         skb_frag_foreach_page(frag,
2955                                               skb_frag_off(frag) + offset - start,
2956                                               copy, p, p_off, p_len, copied) {
2957                                 vaddr = kmap_atomic(p);
2958                                 memcpy(vaddr + p_off, from + copied, p_len);
2959                                 kunmap_atomic(vaddr);
2960                         }
2961
2962                         if ((len -= copy) == 0)
2963                                 return 0;
2964                         offset += copy;
2965                         from += copy;
2966                 }
2967                 start = end;
2968         }
2969
2970         skb_walk_frags(skb, frag_iter) {
2971                 int end;
2972
2973                 WARN_ON(start > offset + len);
2974
2975                 end = start + frag_iter->len;
2976                 if ((copy = end - offset) > 0) {
2977                         if (copy > len)
2978                                 copy = len;
2979                         if (skb_store_bits(frag_iter, offset - start,
2980                                            from, copy))
2981                                 goto fault;
2982                         if ((len -= copy) == 0)
2983                                 return 0;
2984                         offset += copy;
2985                         from += copy;
2986                 }
2987                 start = end;
2988         }
2989         if (!len)
2990                 return 0;
2991
2992 fault:
2993         return -EFAULT;
2994 }
2995 EXPORT_SYMBOL(skb_store_bits);
2996
2997 /* Checksum skb data. */
2998 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2999                       __wsum csum, const struct skb_checksum_ops *ops)
3000 {
3001         int start = skb_headlen(skb);
3002         int i, copy = start - offset;
3003         struct sk_buff *frag_iter;
3004         int pos = 0;
3005
3006         /* Checksum header. */
3007         if (copy > 0) {
3008                 if (copy > len)
3009                         copy = len;
3010                 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3011                                        skb->data + offset, copy, csum);
3012                 if ((len -= copy) == 0)
3013                         return csum;
3014                 offset += copy;
3015                 pos     = copy;
3016         }
3017
3018         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3019                 int end;
3020                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3021
3022                 WARN_ON(start > offset + len);
3023
3024                 end = start + skb_frag_size(frag);
3025                 if ((copy = end - offset) > 0) {
3026                         u32 p_off, p_len, copied;
3027                         struct page *p;
3028                         __wsum csum2;
3029                         u8 *vaddr;
3030
3031                         if (copy > len)
3032                                 copy = len;
3033
3034                         skb_frag_foreach_page(frag,
3035                                               skb_frag_off(frag) + offset - start,
3036                                               copy, p, p_off, p_len, copied) {
3037                                 vaddr = kmap_atomic(p);
3038                                 csum2 = INDIRECT_CALL_1(ops->update,
3039                                                         csum_partial_ext,
3040                                                         vaddr + p_off, p_len, 0);
3041                                 kunmap_atomic(vaddr);
3042                                 csum = INDIRECT_CALL_1(ops->combine,
3043                                                        csum_block_add_ext, csum,
3044                                                        csum2, pos, p_len);
3045                                 pos += p_len;
3046                         }
3047
3048                         if (!(len -= copy))
3049                                 return csum;
3050                         offset += copy;
3051                 }
3052                 start = end;
3053         }
3054
3055         skb_walk_frags(skb, frag_iter) {
3056                 int end;
3057
3058                 WARN_ON(start > offset + len);
3059
3060                 end = start + frag_iter->len;
3061                 if ((copy = end - offset) > 0) {
3062                         __wsum csum2;
3063                         if (copy > len)
3064                                 copy = len;
3065                         csum2 = __skb_checksum(frag_iter, offset - start,
3066                                                copy, 0, ops);
3067                         csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3068                                                csum, csum2, pos, copy);
3069                         if ((len -= copy) == 0)
3070                                 return csum;
3071                         offset += copy;
3072                         pos    += copy;
3073                 }
3074                 start = end;
3075         }
3076         BUG_ON(len);
3077
3078         return csum;
3079 }
3080 EXPORT_SYMBOL(__skb_checksum);
3081
3082 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3083                     int len, __wsum csum)
3084 {
3085         const struct skb_checksum_ops ops = {
3086                 .update  = csum_partial_ext,
3087                 .combine = csum_block_add_ext,
3088         };
3089
3090         return __skb_checksum(skb, offset, len, csum, &ops);
3091 }
3092 EXPORT_SYMBOL(skb_checksum);
3093
3094 /* Both of above in one bottle. */
3095
3096 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3097                                     u8 *to, int len)
3098 {
3099         int start = skb_headlen(skb);
3100         int i, copy = start - offset;
3101         struct sk_buff *frag_iter;
3102         int pos = 0;
3103         __wsum csum = 0;
3104
3105         /* Copy header. */
3106         if (copy > 0) {
3107                 if (copy > len)
3108                         copy = len;
3109                 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3110                                                  copy);
3111                 if ((len -= copy) == 0)
3112                         return csum;
3113                 offset += copy;
3114                 to     += copy;
3115                 pos     = copy;
3116         }
3117
3118         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3119                 int end;
3120
3121                 WARN_ON(start > offset + len);
3122
3123                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3124                 if ((copy = end - offset) > 0) {
3125                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3126                         u32 p_off, p_len, copied;
3127                         struct page *p;
3128                         __wsum csum2;
3129                         u8 *vaddr;
3130
3131                         if (copy > len)
3132                                 copy = len;
3133
3134                         skb_frag_foreach_page(frag,
3135                                               skb_frag_off(frag) + offset - start,
3136                                               copy, p, p_off, p_len, copied) {
3137                                 vaddr = kmap_atomic(p);
3138                                 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3139                                                                   to + copied,
3140                                                                   p_len);
3141                                 kunmap_atomic(vaddr);
3142                                 csum = csum_block_add(csum, csum2, pos);
3143                                 pos += p_len;
3144                         }
3145
3146                         if (!(len -= copy))
3147                                 return csum;
3148                         offset += copy;
3149                         to     += copy;
3150                 }
3151                 start = end;
3152         }
3153
3154         skb_walk_frags(skb, frag_iter) {
3155                 __wsum csum2;
3156                 int end;
3157
3158                 WARN_ON(start > offset + len);
3159
3160                 end = start + frag_iter->len;
3161                 if ((copy = end - offset) > 0) {
3162                         if (copy > len)
3163                                 copy = len;
3164                         csum2 = skb_copy_and_csum_bits(frag_iter,
3165                                                        offset - start,
3166                                                        to, copy);
3167                         csum = csum_block_add(csum, csum2, pos);
3168                         if ((len -= copy) == 0)
3169                                 return csum;
3170                         offset += copy;
3171                         to     += copy;
3172                         pos    += copy;
3173                 }
3174                 start = end;
3175         }
3176         BUG_ON(len);
3177         return csum;
3178 }
3179 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3180
3181 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3182 {
3183         __sum16 sum;
3184
3185         sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3186         /* See comments in __skb_checksum_complete(). */
3187         if (likely(!sum)) {
3188                 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3189                     !skb->csum_complete_sw)
3190                         netdev_rx_csum_fault(skb->dev, skb);
3191         }
3192         if (!skb_shared(skb))
3193                 skb->csum_valid = !sum;
3194         return sum;
3195 }
3196 EXPORT_SYMBOL(__skb_checksum_complete_head);
3197
3198 /* This function assumes skb->csum already holds pseudo header's checksum,
3199  * which has been changed from the hardware checksum, for example, by
3200  * __skb_checksum_validate_complete(). And, the original skb->csum must
3201  * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3202  *
3203  * It returns non-zero if the recomputed checksum is still invalid, otherwise
3204  * zero. The new checksum is stored back into skb->csum unless the skb is
3205  * shared.
3206  */
3207 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3208 {
3209         __wsum csum;
3210         __sum16 sum;
3211
3212         csum = skb_checksum(skb, 0, skb->len, 0);
3213
3214         sum = csum_fold(csum_add(skb->csum, csum));
3215         /* This check is inverted, because we already knew the hardware
3216          * checksum is invalid before calling this function. So, if the
3217          * re-computed checksum is valid instead, then we have a mismatch
3218          * between the original skb->csum and skb_checksum(). This means either
3219          * the original hardware checksum is incorrect or we screw up skb->csum
3220          * when moving skb->data around.
3221          */
3222         if (likely(!sum)) {
3223                 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3224                     !skb->csum_complete_sw)
3225                         netdev_rx_csum_fault(skb->dev, skb);
3226         }
3227
3228         if (!skb_shared(skb)) {
3229                 /* Save full packet checksum */
3230                 skb->csum = csum;
3231                 skb->ip_summed = CHECKSUM_COMPLETE;
3232                 skb->csum_complete_sw = 1;
3233                 skb->csum_valid = !sum;
3234         }
3235
3236         return sum;
3237 }
3238 EXPORT_SYMBOL(__skb_checksum_complete);
3239
3240 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3241 {
3242         net_warn_ratelimited(
3243                 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3244                 __func__);
3245         return 0;
3246 }
3247
3248 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3249                                        int offset, int len)
3250 {
3251         net_warn_ratelimited(
3252                 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3253                 __func__);
3254         return 0;
3255 }
3256
3257 static const struct skb_checksum_ops default_crc32c_ops = {
3258         .update  = warn_crc32c_csum_update,
3259         .combine = warn_crc32c_csum_combine,
3260 };
3261
3262 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3263         &default_crc32c_ops;
3264 EXPORT_SYMBOL(crc32c_csum_stub);
3265
3266  /**
3267  *      skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3268  *      @from: source buffer
3269  *
3270  *      Calculates the amount of linear headroom needed in the 'to' skb passed
3271  *      into skb_zerocopy().
3272  */
3273 unsigned int
3274 skb_zerocopy_headlen(const struct sk_buff *from)
3275 {
3276         unsigned int hlen = 0;
3277
3278         if (!from->head_frag ||
3279             skb_headlen(from) < L1_CACHE_BYTES ||
3280             skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3281                 hlen = skb_headlen(from);
3282                 if (!hlen)
3283                         hlen = from->len;
3284         }
3285
3286         if (skb_has_frag_list(from))
3287                 hlen = from->len;
3288
3289         return hlen;
3290 }
3291 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3292
3293 /**
3294  *      skb_zerocopy - Zero copy skb to skb
3295  *      @to: destination buffer
3296  *      @from: source buffer
3297  *      @len: number of bytes to copy from source buffer
3298  *      @hlen: size of linear headroom in destination buffer
3299  *
3300  *      Copies up to `len` bytes from `from` to `to` by creating references
3301  *      to the frags in the source buffer.
3302  *
3303  *      The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3304  *      headroom in the `to` buffer.
3305  *
3306  *      Return value:
3307  *      0: everything is OK
3308  *      -ENOMEM: couldn't orphan frags of @from due to lack of memory
3309  *      -EFAULT: skb_copy_bits() found some problem with skb geometry
3310  */
3311 int
3312 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3313 {
3314         int i, j = 0;
3315         int plen = 0; /* length of skb->head fragment */
3316         int ret;
3317         struct page *page;
3318         unsigned int offset;
3319
3320         BUG_ON(!from->head_frag && !hlen);
3321
3322         /* dont bother with small payloads */
3323         if (len <= skb_tailroom(to))
3324                 return skb_copy_bits(from, 0, skb_put(to, len), len);
3325
3326         if (hlen) {
3327                 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3328                 if (unlikely(ret))
3329                         return ret;
3330                 len -= hlen;
3331         } else {
3332                 plen = min_t(int, skb_headlen(from), len);
3333                 if (plen) {
3334                         page = virt_to_head_page(from->head);
3335                         offset = from->data - (unsigned char *)page_address(page);
3336                         __skb_fill_page_desc(to, 0, page, offset, plen);
3337                         get_page(page);
3338                         j = 1;
3339                         len -= plen;
3340                 }
3341         }
3342
3343         skb_len_add(to, len + plen);
3344
3345         if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3346                 skb_tx_error(from);
3347                 return -ENOMEM;
3348         }
3349         skb_zerocopy_clone(to, from, GFP_ATOMIC);
3350
3351         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3352                 int size;
3353
3354                 if (!len)
3355                         break;
3356                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3357                 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3358                                         len);
3359                 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3360                 len -= size;
3361                 skb_frag_ref(to, j);
3362                 j++;
3363         }
3364         skb_shinfo(to)->nr_frags = j;
3365
3366         return 0;
3367 }
3368 EXPORT_SYMBOL_GPL(skb_zerocopy);
3369
3370 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3371 {
3372         __wsum csum;
3373         long csstart;
3374
3375         if (skb->ip_summed == CHECKSUM_PARTIAL)
3376                 csstart = skb_checksum_start_offset(skb);
3377         else
3378                 csstart = skb_headlen(skb);
3379
3380         BUG_ON(csstart > skb_headlen(skb));
3381
3382         skb_copy_from_linear_data(skb, to, csstart);
3383
3384         csum = 0;
3385         if (csstart != skb->len)
3386                 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3387                                               skb->len - csstart);
3388
3389         if (skb->ip_summed == CHECKSUM_PARTIAL) {
3390                 long csstuff = csstart + skb->csum_offset;
3391
3392                 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3393         }
3394 }
3395 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3396
3397 /**
3398  *      skb_dequeue - remove from the head of the queue
3399  *      @list: list to dequeue from
3400  *
3401  *      Remove the head of the list. The list lock is taken so the function
3402  *      may be used safely with other locking list functions. The head item is
3403  *      returned or %NULL if the list is empty.
3404  */
3405
3406 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3407 {
3408         unsigned long flags;
3409         struct sk_buff *result;
3410
3411         spin_lock_irqsave(&list->lock, flags);
3412         result = __skb_dequeue(list);
3413         spin_unlock_irqrestore(&list->lock, flags);
3414         return result;
3415 }
3416 EXPORT_SYMBOL(skb_dequeue);
3417
3418 /**
3419  *      skb_dequeue_tail - remove from the tail of the queue
3420  *      @list: list to dequeue from
3421  *
3422  *      Remove the tail of the list. The list lock is taken so the function
3423  *      may be used safely with other locking list functions. The tail item is
3424  *      returned or %NULL if the list is empty.
3425  */
3426 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3427 {
3428         unsigned long flags;
3429         struct sk_buff *result;
3430
3431         spin_lock_irqsave(&list->lock, flags);
3432         result = __skb_dequeue_tail(list);
3433         spin_unlock_irqrestore(&list->lock, flags);
3434         return result;
3435 }
3436 EXPORT_SYMBOL(skb_dequeue_tail);
3437
3438 /**
3439  *      skb_queue_purge - empty a list
3440  *      @list: list to empty
3441  *
3442  *      Delete all buffers on an &sk_buff list. Each buffer is removed from
3443  *      the list and one reference dropped. This function takes the list
3444  *      lock and is atomic with respect to other list locking functions.
3445  */
3446 void skb_queue_purge(struct sk_buff_head *list)
3447 {
3448         struct sk_buff *skb;
3449         while ((skb = skb_dequeue(list)) != NULL)
3450                 kfree_skb(skb);
3451 }
3452 EXPORT_SYMBOL(skb_queue_purge);
3453
3454 /**
3455  *      skb_rbtree_purge - empty a skb rbtree
3456  *      @root: root of the rbtree to empty
3457  *      Return value: the sum of truesizes of all purged skbs.
3458  *
3459  *      Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3460  *      the list and one reference dropped. This function does not take
3461  *      any lock. Synchronization should be handled by the caller (e.g., TCP
3462  *      out-of-order queue is protected by the socket lock).
3463  */
3464 unsigned int skb_rbtree_purge(struct rb_root *root)
3465 {
3466         struct rb_node *p = rb_first(root);
3467         unsigned int sum = 0;
3468
3469         while (p) {
3470                 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3471
3472                 p = rb_next(p);
3473                 rb_erase(&skb->rbnode, root);
3474                 sum += skb->truesize;
3475                 kfree_skb(skb);
3476         }
3477         return sum;
3478 }
3479
3480 /**
3481  *      skb_queue_head - queue a buffer at the list head
3482  *      @list: list to use
3483  *      @newsk: buffer to queue
3484  *
3485  *      Queue a buffer at the start of the list. This function takes the
3486  *      list lock and can be used safely with other locking &sk_buff functions
3487  *      safely.
3488  *
3489  *      A buffer cannot be placed on two lists at the same time.
3490  */
3491 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3492 {
3493         unsigned long flags;
3494
3495         spin_lock_irqsave(&list->lock, flags);
3496         __skb_queue_head(list, newsk);
3497         spin_unlock_irqrestore(&list->lock, flags);
3498 }
3499 EXPORT_SYMBOL(skb_queue_head);
3500
3501 /**
3502  *      skb_queue_tail - queue a buffer at the list tail
3503  *      @list: list to use
3504  *      @newsk: buffer to queue
3505  *
3506  *      Queue a buffer at the tail of the list. This function takes the
3507  *      list lock and can be used safely with other locking &sk_buff functions
3508  *      safely.
3509  *
3510  *      A buffer cannot be placed on two lists at the same time.
3511  */
3512 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3513 {
3514         unsigned long flags;
3515
3516         spin_lock_irqsave(&list->lock, flags);
3517         __skb_queue_tail(list, newsk);
3518         spin_unlock_irqrestore(&list->lock, flags);
3519 }
3520 EXPORT_SYMBOL(skb_queue_tail);
3521
3522 /**
3523  *      skb_unlink      -       remove a buffer from a list
3524  *      @skb: buffer to remove
3525  *      @list: list to use
3526  *
3527  *      Remove a packet from a list. The list locks are taken and this
3528  *      function is atomic with respect to other list locked calls
3529  *
3530  *      You must know what list the SKB is on.
3531  */
3532 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3533 {
3534         unsigned long flags;
3535
3536         spin_lock_irqsave(&list->lock, flags);
3537         __skb_unlink(skb, list);
3538         spin_unlock_irqrestore(&list->lock, flags);
3539 }
3540 EXPORT_SYMBOL(skb_unlink);
3541
3542 /**
3543  *      skb_append      -       append a buffer
3544  *      @old: buffer to insert after
3545  *      @newsk: buffer to insert
3546  *      @list: list to use
3547  *
3548  *      Place a packet after a given packet in a list. The list locks are taken
3549  *      and this function is atomic with respect to other list locked calls.
3550  *      A buffer cannot be placed on two lists at the same time.
3551  */
3552 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3553 {
3554         unsigned long flags;
3555
3556         spin_lock_irqsave(&list->lock, flags);
3557         __skb_queue_after(list, old, newsk);
3558         spin_unlock_irqrestore(&list->lock, flags);
3559 }
3560 EXPORT_SYMBOL(skb_append);
3561
3562 static inline void skb_split_inside_header(struct sk_buff *skb,
3563                                            struct sk_buff* skb1,
3564                                            const u32 len, const int pos)
3565 {
3566         int i;
3567
3568         skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3569                                          pos - len);
3570         /* And move data appendix as is. */
3571         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3572                 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3573
3574         skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3575         skb_shinfo(skb)->nr_frags  = 0;
3576         skb1->data_len             = skb->data_len;
3577         skb1->len                  += skb1->data_len;
3578         skb->data_len              = 0;
3579         skb->len                   = len;
3580         skb_set_tail_pointer(skb, len);
3581 }
3582
3583 static inline void skb_split_no_header(struct sk_buff *skb,
3584                                        struct sk_buff* skb1,
3585                                        const u32 len, int pos)
3586 {
3587         int i, k = 0;
3588         const int nfrags = skb_shinfo(skb)->nr_frags;
3589
3590         skb_shinfo(skb)->nr_frags = 0;
3591         skb1->len                 = skb1->data_len = skb->len - len;
3592         skb->len                  = len;
3593         skb->data_len             = len - pos;
3594
3595         for (i = 0; i < nfrags; i++) {
3596                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3597
3598                 if (pos + size > len) {
3599                         skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3600
3601                         if (pos < len) {
3602                                 /* Split frag.
3603                                  * We have two variants in this case:
3604                                  * 1. Move all the frag to the second
3605                                  *    part, if it is possible. F.e.
3606                                  *    this approach is mandatory for TUX,
3607                                  *    where splitting is expensive.
3608                                  * 2. Split is accurately. We make this.
3609                                  */
3610                                 skb_frag_ref(skb, i);
3611                                 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3612                                 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3613                                 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3614                                 skb_shinfo(skb)->nr_frags++;
3615                         }
3616                         k++;
3617                 } else
3618                         skb_shinfo(skb)->nr_frags++;
3619                 pos += size;
3620         }
3621         skb_shinfo(skb1)->nr_frags = k;
3622 }
3623
3624 /**
3625  * skb_split - Split fragmented skb to two parts at length len.
3626  * @skb: the buffer to split
3627  * @skb1: the buffer to receive the second part
3628  * @len: new length for skb
3629  */
3630 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3631 {
3632         int pos = skb_headlen(skb);
3633         const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3634
3635         skb_zcopy_downgrade_managed(skb);
3636
3637         skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3638         skb_zerocopy_clone(skb1, skb, 0);
3639         if (len < pos)  /* Split line is inside header. */
3640                 skb_split_inside_header(skb, skb1, len, pos);
3641         else            /* Second chunk has no header, nothing to copy. */
3642                 skb_split_no_header(skb, skb1, len, pos);
3643 }
3644 EXPORT_SYMBOL(skb_split);
3645
3646 /* Shifting from/to a cloned skb is a no-go.
3647  *
3648  * Caller cannot keep skb_shinfo related pointers past calling here!
3649  */
3650 static int skb_prepare_for_shift(struct sk_buff *skb)
3651 {
3652         return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3653 }
3654
3655 /**
3656  * skb_shift - Shifts paged data partially from skb to another
3657  * @tgt: buffer into which tail data gets added
3658  * @skb: buffer from which the paged data comes from
3659  * @shiftlen: shift up to this many bytes
3660  *
3661  * Attempts to shift up to shiftlen worth of bytes, which may be less than
3662  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3663  * It's up to caller to free skb if everything was shifted.
3664  *
3665  * If @tgt runs out of frags, the whole operation is aborted.
3666  *
3667  * Skb cannot include anything else but paged data while tgt is allowed
3668  * to have non-paged data as well.
3669  *
3670  * TODO: full sized shift could be optimized but that would need
3671  * specialized skb free'er to handle frags without up-to-date nr_frags.
3672  */
3673 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3674 {
3675         int from, to, merge, todo;
3676         skb_frag_t *fragfrom, *fragto;
3677
3678         BUG_ON(shiftlen > skb->len);
3679
3680         if (skb_headlen(skb))
3681                 return 0;
3682         if (skb_zcopy(tgt) || skb_zcopy(skb))
3683                 return 0;
3684
3685         todo = shiftlen;
3686         from = 0;
3687         to = skb_shinfo(tgt)->nr_frags;
3688         fragfrom = &skb_shinfo(skb)->frags[from];
3689
3690         /* Actual merge is delayed until the point when we know we can
3691          * commit all, so that we don't have to undo partial changes
3692          */
3693         if (!to ||
3694             !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3695                               skb_frag_off(fragfrom))) {
3696                 merge = -1;
3697         } else {
3698                 merge = to - 1;
3699
3700                 todo -= skb_frag_size(fragfrom);
3701                 if (todo < 0) {
3702                         if (skb_prepare_for_shift(skb) ||
3703                             skb_prepare_for_shift(tgt))
3704                                 return 0;
3705
3706                         /* All previous frag pointers might be stale! */
3707                         fragfrom = &skb_shinfo(skb)->frags[from];
3708                         fragto = &skb_shinfo(tgt)->frags[merge];
3709
3710                         skb_frag_size_add(fragto, shiftlen);
3711                         skb_frag_size_sub(fragfrom, shiftlen);
3712                         skb_frag_off_add(fragfrom, shiftlen);
3713
3714                         goto onlymerged;
3715                 }
3716
3717                 from++;
3718         }
3719
3720         /* Skip full, not-fitting skb to avoid expensive operations */
3721         if ((shiftlen == skb->len) &&
3722             (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3723                 return 0;
3724
3725         if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3726                 return 0;
3727
3728         while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3729                 if (to == MAX_SKB_FRAGS)
3730                         return 0;
3731
3732                 fragfrom = &skb_shinfo(skb)->frags[from];
3733                 fragto = &skb_shinfo(tgt)->frags[to];
3734
3735                 if (todo >= skb_frag_size(fragfrom)) {
3736                         *fragto = *fragfrom;
3737                         todo -= skb_frag_size(fragfrom);
3738                         from++;
3739                         to++;
3740
3741                 } else {
3742                         __skb_frag_ref(fragfrom);
3743                         skb_frag_page_copy(fragto, fragfrom);
3744                         skb_frag_off_copy(fragto, fragfrom);
3745                         skb_frag_size_set(fragto, todo);
3746
3747                         skb_frag_off_add(fragfrom, todo);
3748                         skb_frag_size_sub(fragfrom, todo);
3749                         todo = 0;
3750
3751                         to++;
3752                         break;
3753                 }
3754         }
3755
3756         /* Ready to "commit" this state change to tgt */
3757         skb_shinfo(tgt)->nr_frags = to;
3758
3759         if (merge >= 0) {
3760                 fragfrom = &skb_shinfo(skb)->frags[0];
3761                 fragto = &skb_shinfo(tgt)->frags[merge];
3762
3763                 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3764                 __skb_frag_unref(fragfrom, skb->pp_recycle);
3765         }
3766
3767         /* Reposition in the original skb */
3768         to = 0;
3769         while (from < skb_shinfo(skb)->nr_frags)
3770                 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3771         skb_shinfo(skb)->nr_frags = to;
3772
3773         BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3774
3775 onlymerged:
3776         /* Most likely the tgt won't ever need its checksum anymore, skb on
3777          * the other hand might need it if it needs to be resent
3778          */
3779         tgt->ip_summed = CHECKSUM_PARTIAL;
3780         skb->ip_summed = CHECKSUM_PARTIAL;
3781
3782         skb_len_add(skb, -shiftlen);
3783         skb_len_add(tgt, shiftlen);
3784
3785         return shiftlen;
3786 }
3787
3788 /**
3789  * skb_prepare_seq_read - Prepare a sequential read of skb data
3790  * @skb: the buffer to read
3791  * @from: lower offset of data to be read
3792  * @to: upper offset of data to be read
3793  * @st: state variable
3794  *
3795  * Initializes the specified state variable. Must be called before
3796  * invoking skb_seq_read() for the first time.
3797  */
3798 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3799                           unsigned int to, struct skb_seq_state *st)
3800 {
3801         st->lower_offset = from;
3802         st->upper_offset = to;
3803         st->root_skb = st->cur_skb = skb;
3804         st->frag_idx = st->stepped_offset = 0;
3805         st->frag_data = NULL;
3806         st->frag_off = 0;
3807 }
3808 EXPORT_SYMBOL(skb_prepare_seq_read);
3809
3810 /**
3811  * skb_seq_read - Sequentially read skb data
3812  * @consumed: number of bytes consumed by the caller so far
3813  * @data: destination pointer for data to be returned
3814  * @st: state variable
3815  *
3816  * Reads a block of skb data at @consumed relative to the
3817  * lower offset specified to skb_prepare_seq_read(). Assigns
3818  * the head of the data block to @data and returns the length
3819  * of the block or 0 if the end of the skb data or the upper
3820  * offset has been reached.
3821  *
3822  * The caller is not required to consume all of the data
3823  * returned, i.e. @consumed is typically set to the number
3824  * of bytes already consumed and the next call to
3825  * skb_seq_read() will return the remaining part of the block.
3826  *
3827  * Note 1: The size of each block of data returned can be arbitrary,
3828  *       this limitation is the cost for zerocopy sequential
3829  *       reads of potentially non linear data.
3830  *
3831  * Note 2: Fragment lists within fragments are not implemented
3832  *       at the moment, state->root_skb could be replaced with
3833  *       a stack for this purpose.
3834  */
3835 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3836                           struct skb_seq_state *st)
3837 {
3838         unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3839         skb_frag_t *frag;
3840
3841         if (unlikely(abs_offset >= st->upper_offset)) {
3842                 if (st->frag_data) {
3843                         kunmap_atomic(st->frag_data);
3844                         st->frag_data = NULL;
3845                 }
3846                 return 0;
3847         }
3848
3849 next_skb:
3850         block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3851
3852         if (abs_offset < block_limit && !st->frag_data) {
3853                 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3854                 return block_limit - abs_offset;
3855         }
3856
3857         if (st->frag_idx == 0 && !st->frag_data)
3858                 st->stepped_offset += skb_headlen(st->cur_skb);
3859
3860         while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3861                 unsigned int pg_idx, pg_off, pg_sz;
3862
3863                 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3864
3865                 pg_idx = 0;
3866                 pg_off = skb_frag_off(frag);
3867                 pg_sz = skb_frag_size(frag);
3868
3869                 if (skb_frag_must_loop(skb_frag_page(frag))) {
3870                         pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3871                         pg_off = offset_in_page(pg_off + st->frag_off);
3872                         pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3873                                                     PAGE_SIZE - pg_off);
3874                 }
3875
3876                 block_limit = pg_sz + st->stepped_offset;
3877                 if (abs_offset < block_limit) {
3878                         if (!st->frag_data)
3879                                 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3880
3881                         *data = (u8 *)st->frag_data + pg_off +
3882                                 (abs_offset - st->stepped_offset);
3883
3884                         return block_limit - abs_offset;
3885                 }
3886
3887                 if (st->frag_data) {
3888                         kunmap_atomic(st->frag_data);
3889                         st->frag_data = NULL;
3890                 }
3891
3892                 st->stepped_offset += pg_sz;
3893                 st->frag_off += pg_sz;
3894                 if (st->frag_off == skb_frag_size(frag)) {
3895                         st->frag_off = 0;
3896                         st->frag_idx++;
3897                 }
3898         }
3899
3900         if (st->frag_data) {
3901                 kunmap_atomic(st->frag_data);
3902                 st->frag_data = NULL;
3903         }
3904
3905         if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3906                 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3907                 st->frag_idx = 0;
3908                 goto next_skb;
3909         } else if (st->cur_skb->next) {
3910                 st->cur_skb = st->cur_skb->next;
3911                 st->frag_idx = 0;
3912                 goto next_skb;
3913         }
3914
3915         return 0;
3916 }
3917 EXPORT_SYMBOL(skb_seq_read);
3918
3919 /**
3920  * skb_abort_seq_read - Abort a sequential read of skb data
3921  * @st: state variable
3922  *
3923  * Must be called if skb_seq_read() was not called until it
3924  * returned 0.
3925  */
3926 void skb_abort_seq_read(struct skb_seq_state *st)
3927 {
3928         if (st->frag_data)
3929                 kunmap_atomic(st->frag_data);
3930 }
3931 EXPORT_SYMBOL(skb_abort_seq_read);
3932
3933 #define TS_SKB_CB(state)        ((struct skb_seq_state *) &((state)->cb))
3934
3935 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3936                                           struct ts_config *conf,
3937                                           struct ts_state *state)
3938 {
3939         return skb_seq_read(offset, text, TS_SKB_CB(state));
3940 }
3941
3942 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3943 {
3944         skb_abort_seq_read(TS_SKB_CB(state));
3945 }
3946
3947 /**
3948  * skb_find_text - Find a text pattern in skb data
3949  * @skb: the buffer to look in
3950  * @from: search offset
3951  * @to: search limit
3952  * @config: textsearch configuration
3953  *
3954  * Finds a pattern in the skb data according to the specified
3955  * textsearch configuration. Use textsearch_next() to retrieve
3956  * subsequent occurrences of the pattern. Returns the offset
3957  * to the first occurrence or UINT_MAX if no match was found.
3958  */
3959 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3960                            unsigned int to, struct ts_config *config)
3961 {
3962         struct ts_state state;
3963         unsigned int ret;
3964
3965         BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3966
3967         config->get_next_block = skb_ts_get_next_block;
3968         config->finish = skb_ts_finish;
3969
3970         skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3971
3972         ret = textsearch_find(config, &state);
3973         return (ret <= to - from ? ret : UINT_MAX);
3974 }
3975 EXPORT_SYMBOL(skb_find_text);
3976
3977 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3978                          int offset, size_t size)
3979 {
3980         int i = skb_shinfo(skb)->nr_frags;
3981
3982         if (skb_can_coalesce(skb, i, page, offset)) {
3983                 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3984         } else if (i < MAX_SKB_FRAGS) {
3985                 skb_zcopy_downgrade_managed(skb);
3986                 get_page(page);
3987                 skb_fill_page_desc_noacc(skb, i, page, offset, size);
3988         } else {
3989                 return -EMSGSIZE;
3990         }
3991
3992         return 0;
3993 }
3994 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3995
3996 /**
3997  *      skb_pull_rcsum - pull skb and update receive checksum
3998  *      @skb: buffer to update
3999  *      @len: length of data pulled
4000  *
4001  *      This function performs an skb_pull on the packet and updates
4002  *      the CHECKSUM_COMPLETE checksum.  It should be used on
4003  *      receive path processing instead of skb_pull unless you know
4004  *      that the checksum difference is zero (e.g., a valid IP header)
4005  *      or you are setting ip_summed to CHECKSUM_NONE.
4006  */
4007 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4008 {
4009         unsigned char *data = skb->data;
4010
4011         BUG_ON(len > skb->len);
4012         __skb_pull(skb, len);
4013         skb_postpull_rcsum(skb, data, len);
4014         return skb->data;
4015 }
4016 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4017
4018 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4019 {
4020         skb_frag_t head_frag;
4021         struct page *page;
4022
4023         page = virt_to_head_page(frag_skb->head);
4024         __skb_frag_set_page(&head_frag, page);
4025         skb_frag_off_set(&head_frag, frag_skb->data -
4026                          (unsigned char *)page_address(page));
4027         skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4028         return head_frag;
4029 }
4030
4031 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4032                                  netdev_features_t features,
4033                                  unsigned int offset)
4034 {
4035         struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4036         unsigned int tnl_hlen = skb_tnl_header_len(skb);
4037         unsigned int delta_truesize = 0;
4038         unsigned int delta_len = 0;
4039         struct sk_buff *tail = NULL;
4040         struct sk_buff *nskb, *tmp;
4041         int len_diff, err;
4042
4043         skb_push(skb, -skb_network_offset(skb) + offset);
4044
4045         skb_shinfo(skb)->frag_list = NULL;
4046
4047         while (list_skb) {
4048                 nskb = list_skb;
4049                 list_skb = list_skb->next;
4050
4051                 err = 0;
4052                 delta_truesize += nskb->truesize;
4053                 if (skb_shared(nskb)) {
4054                         tmp = skb_clone(nskb, GFP_ATOMIC);
4055                         if (tmp) {
4056                                 consume_skb(nskb);
4057                                 nskb = tmp;
4058                                 err = skb_unclone(nskb, GFP_ATOMIC);
4059                         } else {
4060                                 err = -ENOMEM;
4061                         }
4062                 }
4063
4064                 if (!tail)
4065                         skb->next = nskb;
4066                 else
4067                         tail->next = nskb;
4068
4069                 if (unlikely(err)) {
4070                         nskb->next = list_skb;
4071                         goto err_linearize;
4072                 }
4073
4074                 tail = nskb;
4075
4076                 delta_len += nskb->len;
4077
4078                 skb_push(nskb, -skb_network_offset(nskb) + offset);
4079
4080                 skb_release_head_state(nskb);
4081                 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4082                 __copy_skb_header(nskb, skb);
4083
4084                 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4085                 nskb->transport_header += len_diff;
4086                 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4087                                                  nskb->data - tnl_hlen,
4088                                                  offset + tnl_hlen);
4089
4090                 if (skb_needs_linearize(nskb, features) &&
4091                     __skb_linearize(nskb))
4092                         goto err_linearize;
4093         }
4094
4095         skb->truesize = skb->truesize - delta_truesize;
4096         skb->data_len = skb->data_len - delta_len;
4097         skb->len = skb->len - delta_len;
4098
4099         skb_gso_reset(skb);
4100
4101         skb->prev = tail;
4102
4103         if (skb_needs_linearize(skb, features) &&
4104             __skb_linearize(skb))
4105                 goto err_linearize;
4106
4107         skb_get(skb);
4108
4109         return skb;
4110
4111 err_linearize:
4112         kfree_skb_list(skb->next);
4113         skb->next = NULL;
4114         return ERR_PTR(-ENOMEM);
4115 }
4116 EXPORT_SYMBOL_GPL(skb_segment_list);
4117
4118 /**
4119  *      skb_segment - Perform protocol segmentation on skb.
4120  *      @head_skb: buffer to segment
4121  *      @features: features for the output path (see dev->features)
4122  *
4123  *      This function performs segmentation on the given skb.  It returns
4124  *      a pointer to the first in a list of new skbs for the segments.
4125  *      In case of error it returns ERR_PTR(err).
4126  */
4127 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4128                             netdev_features_t features)
4129 {
4130         struct sk_buff *segs = NULL;
4131         struct sk_buff *tail = NULL;
4132         struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4133         skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4134         unsigned int mss = skb_shinfo(head_skb)->gso_size;
4135         unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4136         struct sk_buff *frag_skb = head_skb;
4137         unsigned int offset = doffset;
4138         unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4139         unsigned int partial_segs = 0;
4140         unsigned int headroom;
4141         unsigned int len = head_skb->len;
4142         __be16 proto;
4143         bool csum, sg;
4144         int nfrags = skb_shinfo(head_skb)->nr_frags;
4145         int err = -ENOMEM;
4146         int i = 0;
4147         int pos;
4148
4149         if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4150             mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4151                 struct sk_buff *check_skb;
4152
4153                 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4154                         if (skb_headlen(check_skb) && !check_skb->head_frag) {
4155                                 /* gso_size is untrusted, and we have a frag_list with
4156                                  * a linear non head_frag item.
4157                                  *
4158                                  * If head_skb's headlen does not fit requested gso_size,
4159                                  * it means that the frag_list members do NOT terminate
4160                                  * on exact gso_size boundaries. Hence we cannot perform
4161                                  * skb_frag_t page sharing. Therefore we must fallback to
4162                                  * copying the frag_list skbs; we do so by disabling SG.
4163                                  */
4164                                 features &= ~NETIF_F_SG;
4165                                 break;
4166                         }
4167                 }
4168         }
4169
4170         __skb_push(head_skb, doffset);
4171         proto = skb_network_protocol(head_skb, NULL);
4172         if (unlikely(!proto))
4173                 return ERR_PTR(-EINVAL);
4174
4175         sg = !!(features & NETIF_F_SG);
4176         csum = !!can_checksum_protocol(features, proto);
4177
4178         if (sg && csum && (mss != GSO_BY_FRAGS))  {
4179                 if (!(features & NETIF_F_GSO_PARTIAL)) {
4180                         struct sk_buff *iter;
4181                         unsigned int frag_len;
4182
4183                         if (!list_skb ||
4184                             !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4185                                 goto normal;
4186
4187                         /* If we get here then all the required
4188                          * GSO features except frag_list are supported.
4189                          * Try to split the SKB to multiple GSO SKBs
4190                          * with no frag_list.
4191                          * Currently we can do that only when the buffers don't
4192                          * have a linear part and all the buffers except
4193                          * the last are of the same length.
4194                          */
4195                         frag_len = list_skb->len;
4196                         skb_walk_frags(head_skb, iter) {
4197                                 if (frag_len != iter->len && iter->next)
4198                                         goto normal;
4199                                 if (skb_headlen(iter) && !iter->head_frag)
4200                                         goto normal;
4201
4202                                 len -= iter->len;
4203                         }
4204
4205                         if (len != frag_len)
4206                                 goto normal;
4207                 }
4208
4209                 /* GSO partial only requires that we trim off any excess that
4210                  * doesn't fit into an MSS sized block, so take care of that
4211                  * now.
4212                  */
4213                 partial_segs = len / mss;
4214                 if (partial_segs > 1)
4215                         mss *= partial_segs;
4216                 else
4217                         partial_segs = 0;
4218         }
4219
4220 normal:
4221         headroom = skb_headroom(head_skb);
4222         pos = skb_headlen(head_skb);
4223
4224         do {
4225                 struct sk_buff *nskb;
4226                 skb_frag_t *nskb_frag;
4227                 int hsize;
4228                 int size;
4229
4230                 if (unlikely(mss == GSO_BY_FRAGS)) {
4231                         len = list_skb->len;
4232                 } else {
4233                         len = head_skb->len - offset;
4234                         if (len > mss)
4235                                 len = mss;
4236                 }
4237
4238                 hsize = skb_headlen(head_skb) - offset;
4239
4240                 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4241                     (skb_headlen(list_skb) == len || sg)) {
4242                         BUG_ON(skb_headlen(list_skb) > len);
4243
4244                         i = 0;
4245                         nfrags = skb_shinfo(list_skb)->nr_frags;
4246                         frag = skb_shinfo(list_skb)->frags;
4247                         frag_skb = list_skb;
4248                         pos += skb_headlen(list_skb);
4249
4250                         while (pos < offset + len) {
4251                                 BUG_ON(i >= nfrags);
4252
4253                                 size = skb_frag_size(frag);
4254                                 if (pos + size > offset + len)
4255                                         break;
4256
4257                                 i++;
4258                                 pos += size;
4259                                 frag++;
4260                         }
4261
4262                         nskb = skb_clone(list_skb, GFP_ATOMIC);
4263                         list_skb = list_skb->next;
4264
4265                         if (unlikely(!nskb))
4266                                 goto err;
4267
4268                         if (unlikely(pskb_trim(nskb, len))) {
4269                                 kfree_skb(nskb);
4270                                 goto err;
4271                         }
4272
4273                         hsize = skb_end_offset(nskb);
4274                         if (skb_cow_head(nskb, doffset + headroom)) {
4275                                 kfree_skb(nskb);
4276                                 goto err;
4277                         }
4278
4279                         nskb->truesize += skb_end_offset(nskb) - hsize;
4280                         skb_release_head_state(nskb);
4281                         __skb_push(nskb, doffset);
4282                 } else {
4283                         if (hsize < 0)
4284                                 hsize = 0;
4285                         if (hsize > len || !sg)
4286                                 hsize = len;
4287
4288                         nskb = __alloc_skb(hsize + doffset + headroom,
4289                                            GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4290                                            NUMA_NO_NODE);
4291
4292                         if (unlikely(!nskb))
4293                                 goto err;
4294
4295                         skb_reserve(nskb, headroom);
4296                         __skb_put(nskb, doffset);
4297                 }
4298
4299                 if (segs)
4300                         tail->next = nskb;
4301                 else
4302                         segs = nskb;
4303                 tail = nskb;
4304
4305                 __copy_skb_header(nskb, head_skb);
4306
4307                 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4308                 skb_reset_mac_len(nskb);
4309
4310                 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4311                                                  nskb->data - tnl_hlen,
4312                                                  doffset + tnl_hlen);
4313
4314                 if (nskb->len == len + doffset)
4315                         goto perform_csum_check;
4316
4317                 if (!sg) {
4318                         if (!csum) {
4319                                 if (!nskb->remcsum_offload)
4320                                         nskb->ip_summed = CHECKSUM_NONE;
4321                                 SKB_GSO_CB(nskb)->csum =
4322                                         skb_copy_and_csum_bits(head_skb, offset,
4323                                                                skb_put(nskb,
4324                                                                        len),
4325                                                                len);
4326                                 SKB_GSO_CB(nskb)->csum_start =
4327                                         skb_headroom(nskb) + doffset;
4328                         } else {
4329                                 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4330                                         goto err;
4331                         }
4332                         continue;
4333                 }
4334
4335                 nskb_frag = skb_shinfo(nskb)->frags;
4336
4337                 skb_copy_from_linear_data_offset(head_skb, offset,
4338                                                  skb_put(nskb, hsize), hsize);
4339
4340                 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4341                                            SKBFL_SHARED_FRAG;
4342
4343                 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4344                     skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4345                         goto err;
4346
4347                 while (pos < offset + len) {
4348                         if (i >= nfrags) {
4349                                 i = 0;
4350                                 nfrags = skb_shinfo(list_skb)->nr_frags;
4351                                 frag = skb_shinfo(list_skb)->frags;
4352                                 frag_skb = list_skb;
4353                                 if (!skb_headlen(list_skb)) {
4354                                         BUG_ON(!nfrags);
4355                                 } else {
4356                                         BUG_ON(!list_skb->head_frag);
4357
4358                                         /* to make room for head_frag. */
4359                                         i--;
4360                                         frag--;
4361                                 }
4362                                 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4363                                     skb_zerocopy_clone(nskb, frag_skb,
4364                                                        GFP_ATOMIC))
4365                                         goto err;
4366
4367                                 list_skb = list_skb->next;
4368                         }
4369
4370                         if (unlikely(skb_shinfo(nskb)->nr_frags >=
4371                                      MAX_SKB_FRAGS)) {
4372                                 net_warn_ratelimited(
4373                                         "skb_segment: too many frags: %u %u\n",
4374                                         pos, mss);
4375                                 err = -EINVAL;
4376                                 goto err;
4377                         }
4378
4379                         *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4380                         __skb_frag_ref(nskb_frag);
4381                         size = skb_frag_size(nskb_frag);
4382
4383                         if (pos < offset) {
4384                                 skb_frag_off_add(nskb_frag, offset - pos);
4385                                 skb_frag_size_sub(nskb_frag, offset - pos);
4386                         }
4387
4388                         skb_shinfo(nskb)->nr_frags++;
4389
4390                         if (pos + size <= offset + len) {
4391                                 i++;
4392                                 frag++;
4393                                 pos += size;
4394                         } else {
4395                                 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4396                                 goto skip_fraglist;
4397                         }
4398
4399                         nskb_frag++;
4400                 }
4401
4402 skip_fraglist:
4403                 nskb->data_len = len - hsize;
4404                 nskb->len += nskb->data_len;
4405                 nskb->truesize += nskb->data_len;
4406
4407 perform_csum_check:
4408                 if (!csum) {
4409                         if (skb_has_shared_frag(nskb) &&
4410                             __skb_linearize(nskb))
4411                                 goto err;
4412
4413                         if (!nskb->remcsum_offload)
4414                                 nskb->ip_summed = CHECKSUM_NONE;
4415                         SKB_GSO_CB(nskb)->csum =
4416                                 skb_checksum(nskb, doffset,
4417                                              nskb->len - doffset, 0);
4418                         SKB_GSO_CB(nskb)->csum_start =
4419                                 skb_headroom(nskb) + doffset;
4420                 }
4421         } while ((offset += len) < head_skb->len);
4422
4423         /* Some callers want to get the end of the list.
4424          * Put it in segs->prev to avoid walking the list.
4425          * (see validate_xmit_skb_list() for example)
4426          */
4427         segs->prev = tail;
4428
4429         if (partial_segs) {
4430                 struct sk_buff *iter;
4431                 int type = skb_shinfo(head_skb)->gso_type;
4432                 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4433
4434                 /* Update type to add partial and then remove dodgy if set */
4435                 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4436                 type &= ~SKB_GSO_DODGY;
4437
4438                 /* Update GSO info and prepare to start updating headers on
4439                  * our way back down the stack of protocols.
4440                  */
4441                 for (iter = segs; iter; iter = iter->next) {
4442                         skb_shinfo(iter)->gso_size = gso_size;
4443                         skb_shinfo(iter)->gso_segs = partial_segs;
4444                         skb_shinfo(iter)->gso_type = type;
4445                         SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4446                 }
4447
4448                 if (tail->len - doffset <= gso_size)
4449                         skb_shinfo(tail)->gso_size = 0;
4450                 else if (tail != segs)
4451                         skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4452         }
4453
4454         /* Following permits correct backpressure, for protocols
4455          * using skb_set_owner_w().
4456          * Idea is to tranfert ownership from head_skb to last segment.
4457          */
4458         if (head_skb->destructor == sock_wfree) {
4459                 swap(tail->truesize, head_skb->truesize);
4460                 swap(tail->destructor, head_skb->destructor);
4461                 swap(tail->sk, head_skb->sk);
4462         }
4463         return segs;
4464
4465 err:
4466         kfree_skb_list(segs);
4467         return ERR_PTR(err);
4468 }
4469 EXPORT_SYMBOL_GPL(skb_segment);
4470
4471 #ifdef CONFIG_SKB_EXTENSIONS
4472 #define SKB_EXT_ALIGN_VALUE     8
4473 #define SKB_EXT_CHUNKSIZEOF(x)  (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4474
4475 static const u8 skb_ext_type_len[] = {
4476 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4477         [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4478 #endif
4479 #ifdef CONFIG_XFRM
4480         [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4481 #endif
4482 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4483         [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4484 #endif
4485 #if IS_ENABLED(CONFIG_MPTCP)
4486         [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4487 #endif
4488 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4489         [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4490 #endif
4491 };
4492
4493 static __always_inline unsigned int skb_ext_total_length(void)
4494 {
4495         return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4496 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4497                 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4498 #endif
4499 #ifdef CONFIG_XFRM
4500                 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4501 #endif
4502 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4503                 skb_ext_type_len[TC_SKB_EXT] +
4504 #endif
4505 #if IS_ENABLED(CONFIG_MPTCP)
4506                 skb_ext_type_len[SKB_EXT_MPTCP] +
4507 #endif
4508 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4509                 skb_ext_type_len[SKB_EXT_MCTP] +
4510 #endif
4511                 0;
4512 }
4513
4514 static void skb_extensions_init(void)
4515 {
4516         BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4517         BUILD_BUG_ON(skb_ext_total_length() > 255);
4518
4519         skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4520                                              SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4521                                              0,
4522                                              SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4523                                              NULL);
4524 }
4525 #else
4526 static void skb_extensions_init(void) {}
4527 #endif
4528
4529 void __init skb_init(void)
4530 {
4531         skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4532                                               sizeof(struct sk_buff),
4533                                               0,
4534                                               SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4535                                               offsetof(struct sk_buff, cb),
4536                                               sizeof_field(struct sk_buff, cb),
4537                                               NULL);
4538         skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4539                                                 sizeof(struct sk_buff_fclones),
4540                                                 0,
4541                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4542                                                 NULL);
4543         skb_extensions_init();
4544 }
4545
4546 static int
4547 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4548                unsigned int recursion_level)
4549 {
4550         int start = skb_headlen(skb);
4551         int i, copy = start - offset;
4552         struct sk_buff *frag_iter;
4553         int elt = 0;
4554
4555         if (unlikely(recursion_level >= 24))
4556                 return -EMSGSIZE;
4557
4558         if (copy > 0) {
4559                 if (copy > len)
4560                         copy = len;
4561                 sg_set_buf(sg, skb->data + offset, copy);
4562                 elt++;
4563                 if ((len -= copy) == 0)
4564                         return elt;
4565                 offset += copy;
4566         }
4567
4568         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4569                 int end;
4570
4571                 WARN_ON(start > offset + len);
4572
4573                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4574                 if ((copy = end - offset) > 0) {
4575                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4576                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4577                                 return -EMSGSIZE;
4578
4579                         if (copy > len)
4580                                 copy = len;
4581                         sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4582                                     skb_frag_off(frag) + offset - start);
4583                         elt++;
4584                         if (!(len -= copy))
4585                                 return elt;
4586                         offset += copy;
4587                 }
4588                 start = end;
4589         }
4590
4591         skb_walk_frags(skb, frag_iter) {
4592                 int end, ret;
4593
4594                 WARN_ON(start > offset + len);
4595
4596                 end = start + frag_iter->len;
4597                 if ((copy = end - offset) > 0) {
4598                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4599                                 return -EMSGSIZE;
4600
4601                         if (copy > len)
4602                                 copy = len;
4603                         ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4604                                               copy, recursion_level + 1);
4605                         if (unlikely(ret < 0))
4606                                 return ret;
4607                         elt += ret;
4608                         if ((len -= copy) == 0)
4609                                 return elt;
4610                         offset += copy;
4611                 }
4612                 start = end;
4613         }
4614         BUG_ON(len);
4615         return elt;
4616 }
4617
4618 /**
4619  *      skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4620  *      @skb: Socket buffer containing the buffers to be mapped
4621  *      @sg: The scatter-gather list to map into
4622  *      @offset: The offset into the buffer's contents to start mapping
4623  *      @len: Length of buffer space to be mapped
4624  *
4625  *      Fill the specified scatter-gather list with mappings/pointers into a
4626  *      region of the buffer space attached to a socket buffer. Returns either
4627  *      the number of scatterlist items used, or -EMSGSIZE if the contents
4628  *      could not fit.
4629  */
4630 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4631 {
4632         int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4633
4634         if (nsg <= 0)
4635                 return nsg;
4636
4637         sg_mark_end(&sg[nsg - 1]);
4638
4639         return nsg;
4640 }
4641 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4642
4643 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4644  * sglist without mark the sg which contain last skb data as the end.
4645  * So the caller can mannipulate sg list as will when padding new data after
4646  * the first call without calling sg_unmark_end to expend sg list.
4647  *
4648  * Scenario to use skb_to_sgvec_nomark:
4649  * 1. sg_init_table
4650  * 2. skb_to_sgvec_nomark(payload1)
4651  * 3. skb_to_sgvec_nomark(payload2)
4652  *
4653  * This is equivalent to:
4654  * 1. sg_init_table
4655  * 2. skb_to_sgvec(payload1)
4656  * 3. sg_unmark_end
4657  * 4. skb_to_sgvec(payload2)
4658  *
4659  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4660  * is more preferable.
4661  */
4662 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4663                         int offset, int len)
4664 {
4665         return __skb_to_sgvec(skb, sg, offset, len, 0);
4666 }
4667 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4668
4669
4670
4671 /**
4672  *      skb_cow_data - Check that a socket buffer's data buffers are writable
4673  *      @skb: The socket buffer to check.
4674  *      @tailbits: Amount of trailing space to be added
4675  *      @trailer: Returned pointer to the skb where the @tailbits space begins
4676  *
4677  *      Make sure that the data buffers attached to a socket buffer are
4678  *      writable. If they are not, private copies are made of the data buffers
4679  *      and the socket buffer is set to use these instead.
4680  *
4681  *      If @tailbits is given, make sure that there is space to write @tailbits
4682  *      bytes of data beyond current end of socket buffer.  @trailer will be
4683  *      set to point to the skb in which this space begins.
4684  *
4685  *      The number of scatterlist elements required to completely map the
4686  *      COW'd and extended socket buffer will be returned.
4687  */
4688 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4689 {
4690         int copyflag;
4691         int elt;
4692         struct sk_buff *skb1, **skb_p;
4693
4694         /* If skb is cloned or its head is paged, reallocate
4695          * head pulling out all the pages (pages are considered not writable
4696          * at the moment even if they are anonymous).
4697          */
4698         if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4699             !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4700                 return -ENOMEM;
4701
4702         /* Easy case. Most of packets will go this way. */
4703         if (!skb_has_frag_list(skb)) {
4704                 /* A little of trouble, not enough of space for trailer.
4705                  * This should not happen, when stack is tuned to generate
4706                  * good frames. OK, on miss we reallocate and reserve even more
4707                  * space, 128 bytes is fair. */
4708
4709                 if (skb_tailroom(skb) < tailbits &&
4710                     pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4711                         return -ENOMEM;
4712
4713                 /* Voila! */
4714                 *trailer = skb;
4715                 return 1;
4716         }
4717
4718         /* Misery. We are in troubles, going to mincer fragments... */
4719
4720         elt = 1;
4721         skb_p = &skb_shinfo(skb)->frag_list;
4722         copyflag = 0;
4723
4724         while ((skb1 = *skb_p) != NULL) {
4725                 int ntail = 0;
4726
4727                 /* The fragment is partially pulled by someone,
4728                  * this can happen on input. Copy it and everything
4729                  * after it. */
4730
4731                 if (skb_shared(skb1))
4732                         copyflag = 1;
4733
4734                 /* If the skb is the last, worry about trailer. */
4735
4736                 if (skb1->next == NULL && tailbits) {
4737                         if (skb_shinfo(skb1)->nr_frags ||
4738                             skb_has_frag_list(skb1) ||
4739                             skb_tailroom(skb1) < tailbits)
4740                                 ntail = tailbits + 128;
4741                 }
4742
4743                 if (copyflag ||
4744                     skb_cloned(skb1) ||
4745                     ntail ||
4746                     skb_shinfo(skb1)->nr_frags ||
4747                     skb_has_frag_list(skb1)) {
4748                         struct sk_buff *skb2;
4749
4750                         /* Fuck, we are miserable poor guys... */
4751                         if (ntail == 0)
4752                                 skb2 = skb_copy(skb1, GFP_ATOMIC);
4753                         else
4754                                 skb2 = skb_copy_expand(skb1,
4755                                                        skb_headroom(skb1),
4756                                                        ntail,
4757                                                        GFP_ATOMIC);
4758                         if (unlikely(skb2 == NULL))
4759                                 return -ENOMEM;
4760
4761                         if (skb1->sk)
4762                                 skb_set_owner_w(skb2, skb1->sk);
4763
4764                         /* Looking around. Are we still alive?
4765                          * OK, link new skb, drop old one */
4766
4767                         skb2->next = skb1->next;
4768                         *skb_p = skb2;
4769                         kfree_skb(skb1);
4770                         skb1 = skb2;
4771                 }
4772                 elt++;
4773                 *trailer = skb1;
4774                 skb_p = &skb1->next;
4775         }
4776
4777         return elt;
4778 }
4779 EXPORT_SYMBOL_GPL(skb_cow_data);
4780
4781 static void sock_rmem_free(struct sk_buff *skb)
4782 {
4783         struct sock *sk = skb->sk;
4784
4785         atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4786 }
4787
4788 static void skb_set_err_queue(struct sk_buff *skb)
4789 {
4790         /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4791          * So, it is safe to (mis)use it to mark skbs on the error queue.
4792          */
4793         skb->pkt_type = PACKET_OUTGOING;
4794         BUILD_BUG_ON(PACKET_OUTGOING == 0);
4795 }
4796
4797 /*
4798  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4799  */
4800 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4801 {
4802         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4803             (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4804                 return -ENOMEM;
4805
4806         skb_orphan(skb);
4807         skb->sk = sk;
4808         skb->destructor = sock_rmem_free;
4809         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4810         skb_set_err_queue(skb);
4811
4812         /* before exiting rcu section, make sure dst is refcounted */
4813         skb_dst_force(skb);
4814
4815         skb_queue_tail(&sk->sk_error_queue, skb);
4816         if (!sock_flag(sk, SOCK_DEAD))
4817                 sk_error_report(sk);
4818         return 0;
4819 }
4820 EXPORT_SYMBOL(sock_queue_err_skb);
4821
4822 static bool is_icmp_err_skb(const struct sk_buff *skb)
4823 {
4824         return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4825                        SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4826 }
4827
4828 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4829 {
4830         struct sk_buff_head *q = &sk->sk_error_queue;
4831         struct sk_buff *skb, *skb_next = NULL;
4832         bool icmp_next = false;
4833         unsigned long flags;
4834
4835         spin_lock_irqsave(&q->lock, flags);
4836         skb = __skb_dequeue(q);
4837         if (skb && (skb_next = skb_peek(q))) {
4838                 icmp_next = is_icmp_err_skb(skb_next);
4839                 if (icmp_next)
4840                         sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4841         }
4842         spin_unlock_irqrestore(&q->lock, flags);
4843
4844         if (is_icmp_err_skb(skb) && !icmp_next)
4845                 sk->sk_err = 0;
4846
4847         if (skb_next)
4848                 sk_error_report(sk);
4849
4850         return skb;
4851 }
4852 EXPORT_SYMBOL(sock_dequeue_err_skb);
4853
4854 /**
4855  * skb_clone_sk - create clone of skb, and take reference to socket
4856  * @skb: the skb to clone
4857  *
4858  * This function creates a clone of a buffer that holds a reference on
4859  * sk_refcnt.  Buffers created via this function are meant to be
4860  * returned using sock_queue_err_skb, or free via kfree_skb.
4861  *
4862  * When passing buffers allocated with this function to sock_queue_err_skb
4863  * it is necessary to wrap the call with sock_hold/sock_put in order to
4864  * prevent the socket from being released prior to being enqueued on
4865  * the sk_error_queue.
4866  */
4867 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4868 {
4869         struct sock *sk = skb->sk;
4870         struct sk_buff *clone;
4871
4872         if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4873                 return NULL;
4874
4875         clone = skb_clone(skb, GFP_ATOMIC);
4876         if (!clone) {
4877                 sock_put(sk);
4878                 return NULL;
4879         }
4880
4881         clone->sk = sk;
4882         clone->destructor = sock_efree;
4883
4884         return clone;
4885 }
4886 EXPORT_SYMBOL(skb_clone_sk);
4887
4888 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4889                                         struct sock *sk,
4890                                         int tstype,
4891                                         bool opt_stats)
4892 {
4893         struct sock_exterr_skb *serr;
4894         int err;
4895
4896         BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4897
4898         serr = SKB_EXT_ERR(skb);
4899         memset(serr, 0, sizeof(*serr));
4900         serr->ee.ee_errno = ENOMSG;
4901         serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4902         serr->ee.ee_info = tstype;
4903         serr->opt_stats = opt_stats;
4904         serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4905         if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4906                 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4907                 if (sk_is_tcp(sk))
4908                         serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4909         }
4910
4911         err = sock_queue_err_skb(sk, skb);
4912
4913         if (err)
4914                 kfree_skb(skb);
4915 }
4916
4917 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4918 {
4919         bool ret;
4920
4921         if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4922                 return true;
4923
4924         read_lock_bh(&sk->sk_callback_lock);
4925         ret = sk->sk_socket && sk->sk_socket->file &&
4926               file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4927         read_unlock_bh(&sk->sk_callback_lock);
4928         return ret;
4929 }
4930
4931 void skb_complete_tx_timestamp(struct sk_buff *skb,
4932                                struct skb_shared_hwtstamps *hwtstamps)
4933 {
4934         struct sock *sk = skb->sk;
4935
4936         if (!skb_may_tx_timestamp(sk, false))
4937                 goto err;
4938
4939         /* Take a reference to prevent skb_orphan() from freeing the socket,
4940          * but only if the socket refcount is not zero.
4941          */
4942         if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4943                 *skb_hwtstamps(skb) = *hwtstamps;
4944                 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4945                 sock_put(sk);
4946                 return;
4947         }
4948
4949 err:
4950         kfree_skb(skb);
4951 }
4952 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4953
4954 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4955                      const struct sk_buff *ack_skb,
4956                      struct skb_shared_hwtstamps *hwtstamps,
4957                      struct sock *sk, int tstype)
4958 {
4959         struct sk_buff *skb;
4960         bool tsonly, opt_stats = false;
4961
4962         if (!sk)
4963                 return;
4964
4965         if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4966             skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4967                 return;
4968
4969         tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4970         if (!skb_may_tx_timestamp(sk, tsonly))
4971                 return;
4972
4973         if (tsonly) {
4974 #ifdef CONFIG_INET
4975                 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4976                     sk_is_tcp(sk)) {
4977                         skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4978                                                              ack_skb);
4979                         opt_stats = true;
4980                 } else
4981 #endif
4982                         skb = alloc_skb(0, GFP_ATOMIC);
4983         } else {
4984                 skb = skb_clone(orig_skb, GFP_ATOMIC);
4985
4986                 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
4987                         kfree_skb(skb);
4988                         return;
4989                 }
4990         }
4991         if (!skb)
4992                 return;
4993
4994         if (tsonly) {
4995                 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4996                                              SKBTX_ANY_TSTAMP;
4997                 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4998         }
4999
5000         if (hwtstamps)
5001                 *skb_hwtstamps(skb) = *hwtstamps;
5002         else
5003                 __net_timestamp(skb);
5004
5005         __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5006 }
5007 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5008
5009 void skb_tstamp_tx(struct sk_buff *orig_skb,
5010                    struct skb_shared_hwtstamps *hwtstamps)
5011 {
5012         return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5013                                SCM_TSTAMP_SND);
5014 }
5015 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5016
5017 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5018 {
5019         struct sock *sk = skb->sk;
5020         struct sock_exterr_skb *serr;
5021         int err = 1;
5022
5023         skb->wifi_acked_valid = 1;
5024         skb->wifi_acked = acked;
5025
5026         serr = SKB_EXT_ERR(skb);
5027         memset(serr, 0, sizeof(*serr));
5028         serr->ee.ee_errno = ENOMSG;
5029         serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5030
5031         /* Take a reference to prevent skb_orphan() from freeing the socket,
5032          * but only if the socket refcount is not zero.
5033          */
5034         if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5035                 err = sock_queue_err_skb(sk, skb);
5036                 sock_put(sk);
5037         }
5038         if (err)
5039                 kfree_skb(skb);
5040 }
5041 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5042
5043 /**
5044  * skb_partial_csum_set - set up and verify partial csum values for packet
5045  * @skb: the skb to set
5046  * @start: the number of bytes after skb->data to start checksumming.
5047  * @off: the offset from start to place the checksum.
5048  *
5049  * For untrusted partially-checksummed packets, we need to make sure the values
5050  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5051  *
5052  * This function checks and sets those values and skb->ip_summed: if this
5053  * returns false you should drop the packet.
5054  */
5055 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5056 {
5057         u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5058         u32 csum_start = skb_headroom(skb) + (u32)start;
5059
5060         if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5061                 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5062                                      start, off, skb_headroom(skb), skb_headlen(skb));
5063                 return false;
5064         }
5065         skb->ip_summed = CHECKSUM_PARTIAL;
5066         skb->csum_start = csum_start;
5067         skb->csum_offset = off;
5068         skb->transport_header = csum_start;
5069         return true;
5070 }
5071 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5072
5073 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5074                                unsigned int max)
5075 {
5076         if (skb_headlen(skb) >= len)
5077                 return 0;
5078
5079         /* If we need to pullup then pullup to the max, so we
5080          * won't need to do it again.
5081          */
5082         if (max > skb->len)
5083                 max = skb->len;
5084
5085         if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5086                 return -ENOMEM;
5087
5088         if (skb_headlen(skb) < len)
5089                 return -EPROTO;
5090
5091         return 0;
5092 }
5093
5094 #define MAX_TCP_HDR_LEN (15 * 4)
5095
5096 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5097                                       typeof(IPPROTO_IP) proto,
5098                                       unsigned int off)
5099 {
5100         int err;
5101
5102         switch (proto) {
5103         case IPPROTO_TCP:
5104                 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5105                                           off + MAX_TCP_HDR_LEN);
5106                 if (!err && !skb_partial_csum_set(skb, off,
5107                                                   offsetof(struct tcphdr,
5108                                                            check)))
5109                         err = -EPROTO;
5110                 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5111
5112         case IPPROTO_UDP:
5113                 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5114                                           off + sizeof(struct udphdr));
5115                 if (!err && !skb_partial_csum_set(skb, off,
5116                                                   offsetof(struct udphdr,
5117                                                            check)))
5118                         err = -EPROTO;
5119                 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5120         }
5121
5122         return ERR_PTR(-EPROTO);
5123 }
5124
5125 /* This value should be large enough to cover a tagged ethernet header plus
5126  * maximally sized IP and TCP or UDP headers.
5127  */
5128 #define MAX_IP_HDR_LEN 128
5129
5130 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5131 {
5132         unsigned int off;
5133         bool fragment;
5134         __sum16 *csum;
5135         int err;
5136
5137         fragment = false;
5138
5139         err = skb_maybe_pull_tail(skb,
5140                                   sizeof(struct iphdr),
5141                                   MAX_IP_HDR_LEN);
5142         if (err < 0)
5143                 goto out;
5144
5145         if (ip_is_fragment(ip_hdr(skb)))
5146                 fragment = true;
5147
5148         off = ip_hdrlen(skb);
5149
5150         err = -EPROTO;
5151
5152         if (fragment)
5153                 goto out;
5154
5155         csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5156         if (IS_ERR(csum))
5157                 return PTR_ERR(csum);
5158
5159         if (recalculate)
5160                 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5161                                            ip_hdr(skb)->daddr,
5162                                            skb->len - off,
5163                                            ip_hdr(skb)->protocol, 0);
5164         err = 0;
5165
5166 out:
5167         return err;
5168 }
5169
5170 /* This value should be large enough to cover a tagged ethernet header plus
5171  * an IPv6 header, all options, and a maximal TCP or UDP header.
5172  */
5173 #define MAX_IPV6_HDR_LEN 256
5174
5175 #define OPT_HDR(type, skb, off) \
5176         (type *)(skb_network_header(skb) + (off))
5177
5178 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5179 {
5180         int err;
5181         u8 nexthdr;
5182         unsigned int off;
5183         unsigned int len;
5184         bool fragment;
5185         bool done;
5186         __sum16 *csum;
5187
5188         fragment = false;
5189         done = false;
5190
5191         off = sizeof(struct ipv6hdr);
5192
5193         err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5194         if (err < 0)
5195                 goto out;
5196
5197         nexthdr = ipv6_hdr(skb)->nexthdr;
5198
5199         len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5200         while (off <= len && !done) {
5201                 switch (nexthdr) {
5202                 case IPPROTO_DSTOPTS:
5203                 case IPPROTO_HOPOPTS:
5204                 case IPPROTO_ROUTING: {
5205                         struct ipv6_opt_hdr *hp;
5206
5207                         err = skb_maybe_pull_tail(skb,
5208                                                   off +
5209                                                   sizeof(struct ipv6_opt_hdr),
5210                                                   MAX_IPV6_HDR_LEN);
5211                         if (err < 0)
5212                                 goto out;
5213
5214                         hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5215                         nexthdr = hp->nexthdr;
5216                         off += ipv6_optlen(hp);
5217                         break;
5218                 }
5219                 case IPPROTO_AH: {
5220                         struct ip_auth_hdr *hp;
5221
5222                         err = skb_maybe_pull_tail(skb,
5223                                                   off +
5224                                                   sizeof(struct ip_auth_hdr),
5225                                                   MAX_IPV6_HDR_LEN);
5226                         if (err < 0)
5227                                 goto out;
5228
5229                         hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5230                         nexthdr = hp->nexthdr;
5231                         off += ipv6_authlen(hp);
5232                         break;
5233                 }
5234                 case IPPROTO_FRAGMENT: {
5235                         struct frag_hdr *hp;
5236
5237                         err = skb_maybe_pull_tail(skb,
5238                                                   off +
5239                                                   sizeof(struct frag_hdr),
5240                                                   MAX_IPV6_HDR_LEN);
5241                         if (err < 0)
5242                                 goto out;
5243
5244                         hp = OPT_HDR(struct frag_hdr, skb, off);
5245
5246                         if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5247                                 fragment = true;
5248
5249                         nexthdr = hp->nexthdr;
5250                         off += sizeof(struct frag_hdr);
5251                         break;
5252                 }
5253                 default:
5254                         done = true;
5255                         break;
5256                 }
5257         }
5258
5259         err = -EPROTO;
5260
5261         if (!done || fragment)
5262                 goto out;
5263
5264         csum = skb_checksum_setup_ip(skb, nexthdr, off);
5265         if (IS_ERR(csum))
5266                 return PTR_ERR(csum);
5267
5268         if (recalculate)
5269                 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5270                                          &ipv6_hdr(skb)->daddr,
5271                                          skb->len - off, nexthdr, 0);
5272         err = 0;
5273
5274 out:
5275         return err;
5276 }
5277
5278 /**
5279  * skb_checksum_setup - set up partial checksum offset
5280  * @skb: the skb to set up
5281  * @recalculate: if true the pseudo-header checksum will be recalculated
5282  */
5283 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5284 {
5285         int err;
5286
5287         switch (skb->protocol) {
5288         case htons(ETH_P_IP):
5289                 err = skb_checksum_setup_ipv4(skb, recalculate);
5290                 break;
5291
5292         case htons(ETH_P_IPV6):
5293                 err = skb_checksum_setup_ipv6(skb, recalculate);
5294                 break;
5295
5296         default:
5297                 err = -EPROTO;
5298                 break;
5299         }
5300
5301         return err;
5302 }
5303 EXPORT_SYMBOL(skb_checksum_setup);
5304
5305 /**
5306  * skb_checksum_maybe_trim - maybe trims the given skb
5307  * @skb: the skb to check
5308  * @transport_len: the data length beyond the network header
5309  *
5310  * Checks whether the given skb has data beyond the given transport length.
5311  * If so, returns a cloned skb trimmed to this transport length.
5312  * Otherwise returns the provided skb. Returns NULL in error cases
5313  * (e.g. transport_len exceeds skb length or out-of-memory).
5314  *
5315  * Caller needs to set the skb transport header and free any returned skb if it
5316  * differs from the provided skb.
5317  */
5318 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5319                                                unsigned int transport_len)
5320 {
5321         struct sk_buff *skb_chk;
5322         unsigned int len = skb_transport_offset(skb) + transport_len;
5323         int ret;
5324
5325         if (skb->len < len)
5326                 return NULL;
5327         else if (skb->len == len)
5328                 return skb;
5329
5330         skb_chk = skb_clone(skb, GFP_ATOMIC);
5331         if (!skb_chk)
5332                 return NULL;
5333
5334         ret = pskb_trim_rcsum(skb_chk, len);
5335         if (ret) {
5336                 kfree_skb(skb_chk);
5337                 return NULL;
5338         }
5339
5340         return skb_chk;
5341 }
5342
5343 /**
5344  * skb_checksum_trimmed - validate checksum of an skb
5345  * @skb: the skb to check
5346  * @transport_len: the data length beyond the network header
5347  * @skb_chkf: checksum function to use
5348  *
5349  * Applies the given checksum function skb_chkf to the provided skb.
5350  * Returns a checked and maybe trimmed skb. Returns NULL on error.
5351  *
5352  * If the skb has data beyond the given transport length, then a
5353  * trimmed & cloned skb is checked and returned.
5354  *
5355  * Caller needs to set the skb transport header and free any returned skb if it
5356  * differs from the provided skb.
5357  */
5358 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5359                                      unsigned int transport_len,
5360                                      __sum16(*skb_chkf)(struct sk_buff *skb))
5361 {
5362         struct sk_buff *skb_chk;
5363         unsigned int offset = skb_transport_offset(skb);
5364         __sum16 ret;
5365
5366         skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5367         if (!skb_chk)
5368                 goto err;
5369
5370         if (!pskb_may_pull(skb_chk, offset))
5371                 goto err;
5372
5373         skb_pull_rcsum(skb_chk, offset);
5374         ret = skb_chkf(skb_chk);
5375         skb_push_rcsum(skb_chk, offset);
5376
5377         if (ret)
5378                 goto err;
5379
5380         return skb_chk;
5381
5382 err:
5383         if (skb_chk && skb_chk != skb)
5384                 kfree_skb(skb_chk);
5385
5386         return NULL;
5387
5388 }
5389 EXPORT_SYMBOL(skb_checksum_trimmed);
5390
5391 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5392 {
5393         net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5394                              skb->dev->name);
5395 }
5396 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5397
5398 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5399 {
5400         if (head_stolen) {
5401                 skb_release_head_state(skb);
5402                 kmem_cache_free(skbuff_head_cache, skb);
5403         } else {
5404                 __kfree_skb(skb);
5405         }
5406 }
5407 EXPORT_SYMBOL(kfree_skb_partial);
5408
5409 /**
5410  * skb_try_coalesce - try to merge skb to prior one
5411  * @to: prior buffer
5412  * @from: buffer to add
5413  * @fragstolen: pointer to boolean
5414  * @delta_truesize: how much more was allocated than was requested
5415  */
5416 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5417                       bool *fragstolen, int *delta_truesize)
5418 {
5419         struct skb_shared_info *to_shinfo, *from_shinfo;
5420         int i, delta, len = from->len;
5421
5422         *fragstolen = false;
5423
5424         if (skb_cloned(to))
5425                 return false;
5426
5427         /* In general, avoid mixing page_pool and non-page_pool allocated
5428          * pages within the same SKB. Additionally avoid dealing with clones
5429          * with page_pool pages, in case the SKB is using page_pool fragment
5430          * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5431          * references for cloned SKBs at the moment that would result in
5432          * inconsistent reference counts.
5433          * In theory we could take full references if @from is cloned and
5434          * !@to->pp_recycle but its tricky (due to potential race with
5435          * the clone disappearing) and rare, so not worth dealing with.
5436          */
5437         if (to->pp_recycle != from->pp_recycle ||
5438             (from->pp_recycle && skb_cloned(from)))
5439                 return false;
5440
5441         if (len <= skb_tailroom(to)) {
5442                 if (len)
5443                         BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5444                 *delta_truesize = 0;
5445                 return true;
5446         }
5447
5448         to_shinfo = skb_shinfo(to);
5449         from_shinfo = skb_shinfo(from);
5450         if (to_shinfo->frag_list || from_shinfo->frag_list)
5451                 return false;
5452         if (skb_zcopy(to) || skb_zcopy(from))
5453                 return false;
5454
5455         if (skb_headlen(from) != 0) {
5456                 struct page *page;
5457                 unsigned int offset;
5458
5459                 if (to_shinfo->nr_frags +
5460                     from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5461                         return false;
5462
5463                 if (skb_head_is_locked(from))
5464                         return false;
5465
5466                 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5467
5468                 page = virt_to_head_page(from->head);
5469                 offset = from->data - (unsigned char *)page_address(page);
5470
5471                 skb_fill_page_desc(to, to_shinfo->nr_frags,
5472                                    page, offset, skb_headlen(from));
5473                 *fragstolen = true;
5474         } else {
5475                 if (to_shinfo->nr_frags +
5476                     from_shinfo->nr_frags > MAX_SKB_FRAGS)
5477                         return false;
5478
5479                 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5480         }
5481
5482         WARN_ON_ONCE(delta < len);
5483
5484         memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5485                from_shinfo->frags,
5486                from_shinfo->nr_frags * sizeof(skb_frag_t));
5487         to_shinfo->nr_frags += from_shinfo->nr_frags;
5488
5489         if (!skb_cloned(from))
5490                 from_shinfo->nr_frags = 0;
5491
5492         /* if the skb is not cloned this does nothing
5493          * since we set nr_frags to 0.
5494          */
5495         for (i = 0; i < from_shinfo->nr_frags; i++)
5496                 __skb_frag_ref(&from_shinfo->frags[i]);
5497
5498         to->truesize += delta;
5499         to->len += len;
5500         to->data_len += len;
5501
5502         *delta_truesize = delta;
5503         return true;
5504 }
5505 EXPORT_SYMBOL(skb_try_coalesce);
5506
5507 /**
5508  * skb_scrub_packet - scrub an skb
5509  *
5510  * @skb: buffer to clean
5511  * @xnet: packet is crossing netns
5512  *
5513  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5514  * into/from a tunnel. Some information have to be cleared during these
5515  * operations.
5516  * skb_scrub_packet can also be used to clean a skb before injecting it in
5517  * another namespace (@xnet == true). We have to clear all information in the
5518  * skb that could impact namespace isolation.
5519  */
5520 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5521 {
5522         skb->pkt_type = PACKET_HOST;
5523         skb->skb_iif = 0;
5524         skb->ignore_df = 0;
5525         skb_dst_drop(skb);
5526         skb_ext_reset(skb);
5527         nf_reset_ct(skb);
5528         nf_reset_trace(skb);
5529
5530 #ifdef CONFIG_NET_SWITCHDEV
5531         skb->offload_fwd_mark = 0;
5532         skb->offload_l3_fwd_mark = 0;
5533 #endif
5534
5535         if (!xnet)
5536                 return;
5537
5538         ipvs_reset(skb);
5539         skb->mark = 0;
5540         skb_clear_tstamp(skb);
5541 }
5542 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5543
5544 /**
5545  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5546  *
5547  * @skb: GSO skb
5548  *
5549  * skb_gso_transport_seglen is used to determine the real size of the
5550  * individual segments, including Layer4 headers (TCP/UDP).
5551  *
5552  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5553  */
5554 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5555 {
5556         const struct skb_shared_info *shinfo = skb_shinfo(skb);
5557         unsigned int thlen = 0;
5558
5559         if (skb->encapsulation) {
5560                 thlen = skb_inner_transport_header(skb) -
5561                         skb_transport_header(skb);
5562
5563                 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5564                         thlen += inner_tcp_hdrlen(skb);
5565         } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5566                 thlen = tcp_hdrlen(skb);
5567         } else if (unlikely(skb_is_gso_sctp(skb))) {
5568                 thlen = sizeof(struct sctphdr);
5569         } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5570                 thlen = sizeof(struct udphdr);
5571         }
5572         /* UFO sets gso_size to the size of the fragmentation
5573          * payload, i.e. the size of the L4 (UDP) header is already
5574          * accounted for.
5575          */
5576         return thlen + shinfo->gso_size;
5577 }
5578
5579 /**
5580  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5581  *
5582  * @skb: GSO skb
5583  *
5584  * skb_gso_network_seglen is used to determine the real size of the
5585  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5586  *
5587  * The MAC/L2 header is not accounted for.
5588  */
5589 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5590 {
5591         unsigned int hdr_len = skb_transport_header(skb) -
5592                                skb_network_header(skb);
5593
5594         return hdr_len + skb_gso_transport_seglen(skb);
5595 }
5596
5597 /**
5598  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5599  *
5600  * @skb: GSO skb
5601  *
5602  * skb_gso_mac_seglen is used to determine the real size of the
5603  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5604  * headers (TCP/UDP).
5605  */
5606 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5607 {
5608         unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5609
5610         return hdr_len + skb_gso_transport_seglen(skb);
5611 }
5612
5613 /**
5614  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5615  *
5616  * There are a couple of instances where we have a GSO skb, and we
5617  * want to determine what size it would be after it is segmented.
5618  *
5619  * We might want to check:
5620  * -    L3+L4+payload size (e.g. IP forwarding)
5621  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5622  *
5623  * This is a helper to do that correctly considering GSO_BY_FRAGS.
5624  *
5625  * @skb: GSO skb
5626  *
5627  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5628  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5629  *
5630  * @max_len: The maximum permissible length.
5631  *
5632  * Returns true if the segmented length <= max length.
5633  */
5634 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5635                                       unsigned int seg_len,
5636                                       unsigned int max_len) {
5637         const struct skb_shared_info *shinfo = skb_shinfo(skb);
5638         const struct sk_buff *iter;
5639
5640         if (shinfo->gso_size != GSO_BY_FRAGS)
5641                 return seg_len <= max_len;
5642
5643         /* Undo this so we can re-use header sizes */
5644         seg_len -= GSO_BY_FRAGS;
5645
5646         skb_walk_frags(skb, iter) {
5647                 if (seg_len + skb_headlen(iter) > max_len)
5648                         return false;
5649         }
5650
5651         return true;
5652 }
5653
5654 /**
5655  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5656  *
5657  * @skb: GSO skb
5658  * @mtu: MTU to validate against
5659  *
5660  * skb_gso_validate_network_len validates if a given skb will fit a
5661  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5662  * payload.
5663  */
5664 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5665 {
5666         return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5667 }
5668 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5669
5670 /**
5671  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5672  *
5673  * @skb: GSO skb
5674  * @len: length to validate against
5675  *
5676  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5677  * length once split, including L2, L3 and L4 headers and the payload.
5678  */
5679 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5680 {
5681         return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5682 }
5683 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5684
5685 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5686 {
5687         int mac_len, meta_len;
5688         void *meta;
5689
5690         if (skb_cow(skb, skb_headroom(skb)) < 0) {
5691                 kfree_skb(skb);
5692                 return NULL;
5693         }
5694
5695         mac_len = skb->data - skb_mac_header(skb);
5696         if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5697                 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5698                         mac_len - VLAN_HLEN - ETH_TLEN);
5699         }
5700
5701         meta_len = skb_metadata_len(skb);
5702         if (meta_len) {
5703                 meta = skb_metadata_end(skb) - meta_len;
5704                 memmove(meta + VLAN_HLEN, meta, meta_len);
5705         }
5706
5707         skb->mac_header += VLAN_HLEN;
5708         return skb;
5709 }
5710
5711 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5712 {
5713         struct vlan_hdr *vhdr;
5714         u16 vlan_tci;
5715
5716         if (unlikely(skb_vlan_tag_present(skb))) {
5717                 /* vlan_tci is already set-up so leave this for another time */
5718                 return skb;
5719         }
5720
5721         skb = skb_share_check(skb, GFP_ATOMIC);
5722         if (unlikely(!skb))
5723                 goto err_free;
5724         /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5725         if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5726                 goto err_free;
5727
5728         vhdr = (struct vlan_hdr *)skb->data;
5729         vlan_tci = ntohs(vhdr->h_vlan_TCI);
5730         __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5731
5732         skb_pull_rcsum(skb, VLAN_HLEN);
5733         vlan_set_encap_proto(skb, vhdr);
5734
5735         skb = skb_reorder_vlan_header(skb);
5736         if (unlikely(!skb))
5737                 goto err_free;
5738
5739         skb_reset_network_header(skb);
5740         if (!skb_transport_header_was_set(skb))
5741                 skb_reset_transport_header(skb);
5742         skb_reset_mac_len(skb);
5743
5744         return skb;
5745
5746 err_free:
5747         kfree_skb(skb);
5748         return NULL;
5749 }
5750 EXPORT_SYMBOL(skb_vlan_untag);
5751
5752 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5753 {
5754         if (!pskb_may_pull(skb, write_len))
5755                 return -ENOMEM;
5756
5757         if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5758                 return 0;
5759
5760         return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5761 }
5762 EXPORT_SYMBOL(skb_ensure_writable);
5763
5764 /* remove VLAN header from packet and update csum accordingly.
5765  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5766  */
5767 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5768 {
5769         struct vlan_hdr *vhdr;
5770         int offset = skb->data - skb_mac_header(skb);
5771         int err;
5772
5773         if (WARN_ONCE(offset,
5774                       "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5775                       offset)) {
5776                 return -EINVAL;
5777         }
5778
5779         err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5780         if (unlikely(err))
5781                 return err;
5782
5783         skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5784
5785         vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5786         *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5787
5788         memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5789         __skb_pull(skb, VLAN_HLEN);
5790
5791         vlan_set_encap_proto(skb, vhdr);
5792         skb->mac_header += VLAN_HLEN;
5793
5794         if (skb_network_offset(skb) < ETH_HLEN)
5795                 skb_set_network_header(skb, ETH_HLEN);
5796
5797         skb_reset_mac_len(skb);
5798
5799         return err;
5800 }
5801 EXPORT_SYMBOL(__skb_vlan_pop);
5802
5803 /* Pop a vlan tag either from hwaccel or from payload.
5804  * Expects skb->data at mac header.
5805  */
5806 int skb_vlan_pop(struct sk_buff *skb)
5807 {
5808         u16 vlan_tci;
5809         __be16 vlan_proto;
5810         int err;
5811
5812         if (likely(skb_vlan_tag_present(skb))) {
5813                 __vlan_hwaccel_clear_tag(skb);
5814         } else {
5815                 if (unlikely(!eth_type_vlan(skb->protocol)))
5816                         return 0;
5817
5818                 err = __skb_vlan_pop(skb, &vlan_tci);
5819                 if (err)
5820                         return err;
5821         }
5822         /* move next vlan tag to hw accel tag */
5823         if (likely(!eth_type_vlan(skb->protocol)))
5824                 return 0;
5825
5826         vlan_proto = skb->protocol;
5827         err = __skb_vlan_pop(skb, &vlan_tci);
5828         if (unlikely(err))
5829                 return err;
5830
5831         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5832         return 0;
5833 }
5834 EXPORT_SYMBOL(skb_vlan_pop);
5835
5836 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5837  * Expects skb->data at mac header.
5838  */
5839 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5840 {
5841         if (skb_vlan_tag_present(skb)) {
5842                 int offset = skb->data - skb_mac_header(skb);
5843                 int err;
5844
5845                 if (WARN_ONCE(offset,
5846                               "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5847                               offset)) {
5848                         return -EINVAL;
5849                 }
5850
5851                 err = __vlan_insert_tag(skb, skb->vlan_proto,
5852                                         skb_vlan_tag_get(skb));
5853                 if (err)
5854                         return err;
5855
5856                 skb->protocol = skb->vlan_proto;
5857                 skb->mac_len += VLAN_HLEN;
5858
5859                 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5860         }
5861         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5862         return 0;
5863 }
5864 EXPORT_SYMBOL(skb_vlan_push);
5865
5866 /**
5867  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5868  *
5869  * @skb: Socket buffer to modify
5870  *
5871  * Drop the Ethernet header of @skb.
5872  *
5873  * Expects that skb->data points to the mac header and that no VLAN tags are
5874  * present.
5875  *
5876  * Returns 0 on success, -errno otherwise.
5877  */
5878 int skb_eth_pop(struct sk_buff *skb)
5879 {
5880         if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5881             skb_network_offset(skb) < ETH_HLEN)
5882                 return -EPROTO;
5883
5884         skb_pull_rcsum(skb, ETH_HLEN);
5885         skb_reset_mac_header(skb);
5886         skb_reset_mac_len(skb);
5887
5888         return 0;
5889 }
5890 EXPORT_SYMBOL(skb_eth_pop);
5891
5892 /**
5893  * skb_eth_push() - Add a new Ethernet header at the head of a packet
5894  *
5895  * @skb: Socket buffer to modify
5896  * @dst: Destination MAC address of the new header
5897  * @src: Source MAC address of the new header
5898  *
5899  * Prepend @skb with a new Ethernet header.
5900  *
5901  * Expects that skb->data points to the mac header, which must be empty.
5902  *
5903  * Returns 0 on success, -errno otherwise.
5904  */
5905 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5906                  const unsigned char *src)
5907 {
5908         struct ethhdr *eth;
5909         int err;
5910
5911         if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5912                 return -EPROTO;
5913
5914         err = skb_cow_head(skb, sizeof(*eth));
5915         if (err < 0)
5916                 return err;
5917
5918         skb_push(skb, sizeof(*eth));
5919         skb_reset_mac_header(skb);
5920         skb_reset_mac_len(skb);
5921
5922         eth = eth_hdr(skb);
5923         ether_addr_copy(eth->h_dest, dst);
5924         ether_addr_copy(eth->h_source, src);
5925         eth->h_proto = skb->protocol;
5926
5927         skb_postpush_rcsum(skb, eth, sizeof(*eth));
5928
5929         return 0;
5930 }
5931 EXPORT_SYMBOL(skb_eth_push);
5932
5933 /* Update the ethertype of hdr and the skb csum value if required. */
5934 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5935                              __be16 ethertype)
5936 {
5937         if (skb->ip_summed == CHECKSUM_COMPLETE) {
5938                 __be16 diff[] = { ~hdr->h_proto, ethertype };
5939
5940                 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5941         }
5942
5943         hdr->h_proto = ethertype;
5944 }
5945
5946 /**
5947  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5948  *                   the packet
5949  *
5950  * @skb: buffer
5951  * @mpls_lse: MPLS label stack entry to push
5952  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5953  * @mac_len: length of the MAC header
5954  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5955  *            ethernet
5956  *
5957  * Expects skb->data at mac header.
5958  *
5959  * Returns 0 on success, -errno otherwise.
5960  */
5961 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5962                   int mac_len, bool ethernet)
5963 {
5964         struct mpls_shim_hdr *lse;
5965         int err;
5966
5967         if (unlikely(!eth_p_mpls(mpls_proto)))
5968                 return -EINVAL;
5969
5970         /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5971         if (skb->encapsulation)
5972                 return -EINVAL;
5973
5974         err = skb_cow_head(skb, MPLS_HLEN);
5975         if (unlikely(err))
5976                 return err;
5977
5978         if (!skb->inner_protocol) {
5979                 skb_set_inner_network_header(skb, skb_network_offset(skb));
5980                 skb_set_inner_protocol(skb, skb->protocol);
5981         }
5982
5983         skb_push(skb, MPLS_HLEN);
5984         memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5985                 mac_len);
5986         skb_reset_mac_header(skb);
5987         skb_set_network_header(skb, mac_len);
5988         skb_reset_mac_len(skb);
5989
5990         lse = mpls_hdr(skb);
5991         lse->label_stack_entry = mpls_lse;
5992         skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5993
5994         if (ethernet && mac_len >= ETH_HLEN)
5995                 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5996         skb->protocol = mpls_proto;
5997
5998         return 0;
5999 }
6000 EXPORT_SYMBOL_GPL(skb_mpls_push);
6001
6002 /**
6003  * skb_mpls_pop() - pop the outermost MPLS header
6004  *
6005  * @skb: buffer
6006  * @next_proto: ethertype of header after popped MPLS header
6007  * @mac_len: length of the MAC header
6008  * @ethernet: flag to indicate if the packet is ethernet
6009  *
6010  * Expects skb->data at mac header.
6011  *
6012  * Returns 0 on success, -errno otherwise.
6013  */
6014 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6015                  bool ethernet)
6016 {
6017         int err;
6018
6019         if (unlikely(!eth_p_mpls(skb->protocol)))
6020                 return 0;
6021
6022         err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6023         if (unlikely(err))
6024                 return err;
6025
6026         skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6027         memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6028                 mac_len);
6029
6030         __skb_pull(skb, MPLS_HLEN);
6031         skb_reset_mac_header(skb);
6032         skb_set_network_header(skb, mac_len);
6033
6034         if (ethernet && mac_len >= ETH_HLEN) {
6035                 struct ethhdr *hdr;
6036
6037                 /* use mpls_hdr() to get ethertype to account for VLANs. */
6038                 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6039                 skb_mod_eth_type(skb, hdr, next_proto);
6040         }
6041         skb->protocol = next_proto;
6042
6043         return 0;
6044 }
6045 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6046
6047 /**
6048  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6049  *
6050  * @skb: buffer
6051  * @mpls_lse: new MPLS label stack entry to update to
6052  *
6053  * Expects skb->data at mac header.
6054  *
6055  * Returns 0 on success, -errno otherwise.
6056  */
6057 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6058 {
6059         int err;
6060
6061         if (unlikely(!eth_p_mpls(skb->protocol)))
6062                 return -EINVAL;
6063
6064         err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6065         if (unlikely(err))
6066                 return err;
6067
6068         if (skb->ip_summed == CHECKSUM_COMPLETE) {
6069                 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6070
6071                 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6072         }
6073
6074         mpls_hdr(skb)->label_stack_entry = mpls_lse;
6075
6076         return 0;
6077 }
6078 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6079
6080 /**
6081  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6082  *
6083  * @skb: buffer
6084  *
6085  * Expects skb->data at mac header.
6086  *
6087  * Returns 0 on success, -errno otherwise.
6088  */
6089 int skb_mpls_dec_ttl(struct sk_buff *skb)
6090 {
6091         u32 lse;
6092         u8 ttl;
6093
6094         if (unlikely(!eth_p_mpls(skb->protocol)))
6095                 return -EINVAL;
6096
6097         if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6098                 return -ENOMEM;
6099
6100         lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6101         ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6102         if (!--ttl)
6103                 return -EINVAL;
6104
6105         lse &= ~MPLS_LS_TTL_MASK;
6106         lse |= ttl << MPLS_LS_TTL_SHIFT;
6107
6108         return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6109 }
6110 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6111
6112 /**
6113  * alloc_skb_with_frags - allocate skb with page frags
6114  *
6115  * @header_len: size of linear part
6116  * @data_len: needed length in frags
6117  * @max_page_order: max page order desired.
6118  * @errcode: pointer to error code if any
6119  * @gfp_mask: allocation mask
6120  *
6121  * This can be used to allocate a paged skb, given a maximal order for frags.
6122  */
6123 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6124                                      unsigned long data_len,
6125                                      int max_page_order,
6126                                      int *errcode,
6127                                      gfp_t gfp_mask)
6128 {
6129         int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6130         unsigned long chunk;
6131         struct sk_buff *skb;
6132         struct page *page;
6133         int i;
6134
6135         *errcode = -EMSGSIZE;
6136         /* Note this test could be relaxed, if we succeed to allocate
6137          * high order pages...
6138          */
6139         if (npages > MAX_SKB_FRAGS)
6140                 return NULL;
6141
6142         *errcode = -ENOBUFS;
6143         skb = alloc_skb(header_len, gfp_mask);
6144         if (!skb)
6145                 return NULL;
6146
6147         skb->truesize += npages << PAGE_SHIFT;
6148
6149         for (i = 0; npages > 0; i++) {
6150                 int order = max_page_order;
6151
6152                 while (order) {
6153                         if (npages >= 1 << order) {
6154                                 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6155                                                    __GFP_COMP |
6156                                                    __GFP_NOWARN,
6157                                                    order);
6158                                 if (page)
6159                                         goto fill_page;
6160                                 /* Do not retry other high order allocations */
6161                                 order = 1;
6162                                 max_page_order = 0;
6163                         }
6164                         order--;
6165                 }
6166                 page = alloc_page(gfp_mask);
6167                 if (!page)
6168                         goto failure;
6169 fill_page:
6170                 chunk = min_t(unsigned long, data_len,
6171                               PAGE_SIZE << order);
6172                 skb_fill_page_desc(skb, i, page, 0, chunk);
6173                 data_len -= chunk;
6174                 npages -= 1 << order;
6175         }
6176         return skb;
6177
6178 failure:
6179         kfree_skb(skb);
6180         return NULL;
6181 }
6182 EXPORT_SYMBOL(alloc_skb_with_frags);
6183
6184 /* carve out the first off bytes from skb when off < headlen */
6185 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6186                                     const int headlen, gfp_t gfp_mask)
6187 {
6188         int i;
6189         unsigned int size = skb_end_offset(skb);
6190         int new_hlen = headlen - off;
6191         u8 *data;
6192
6193         if (skb_pfmemalloc(skb))
6194                 gfp_mask |= __GFP_MEMALLOC;
6195
6196         size = SKB_DATA_ALIGN(size);
6197         size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6198         size = kmalloc_size_roundup(size);
6199         data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
6200         if (!data)
6201                 return -ENOMEM;
6202         size = SKB_WITH_OVERHEAD(size);
6203
6204         /* Copy real data, and all frags */
6205         skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6206         skb->len -= off;
6207
6208         memcpy((struct skb_shared_info *)(data + size),
6209                skb_shinfo(skb),
6210                offsetof(struct skb_shared_info,
6211                         frags[skb_shinfo(skb)->nr_frags]));
6212         if (skb_cloned(skb)) {
6213                 /* drop the old head gracefully */
6214                 if (skb_orphan_frags(skb, gfp_mask)) {
6215                         kfree(data);
6216                         return -ENOMEM;
6217                 }
6218                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6219                         skb_frag_ref(skb, i);
6220                 if (skb_has_frag_list(skb))
6221                         skb_clone_fraglist(skb);
6222                 skb_release_data(skb);
6223         } else {
6224                 /* we can reuse existing recount- all we did was
6225                  * relocate values
6226                  */
6227                 skb_free_head(skb);
6228         }
6229
6230         skb->head = data;
6231         skb->data = data;
6232         skb->head_frag = 0;
6233         skb_set_end_offset(skb, size);
6234         skb_set_tail_pointer(skb, skb_headlen(skb));
6235         skb_headers_offset_update(skb, 0);
6236         skb->cloned = 0;
6237         skb->hdr_len = 0;
6238         skb->nohdr = 0;
6239         atomic_set(&skb_shinfo(skb)->dataref, 1);
6240
6241         return 0;
6242 }
6243
6244 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6245
6246 /* carve out the first eat bytes from skb's frag_list. May recurse into
6247  * pskb_carve()
6248  */
6249 static int pskb_carve_frag_list(struct sk_buff *skb,
6250                                 struct skb_shared_info *shinfo, int eat,
6251                                 gfp_t gfp_mask)
6252 {
6253         struct sk_buff *list = shinfo->frag_list;
6254         struct sk_buff *clone = NULL;
6255         struct sk_buff *insp = NULL;
6256
6257         do {
6258                 if (!list) {
6259                         pr_err("Not enough bytes to eat. Want %d\n", eat);
6260                         return -EFAULT;
6261                 }
6262                 if (list->len <= eat) {
6263                         /* Eaten as whole. */
6264                         eat -= list->len;
6265                         list = list->next;
6266                         insp = list;
6267                 } else {
6268                         /* Eaten partially. */
6269                         if (skb_shared(list)) {
6270                                 clone = skb_clone(list, gfp_mask);
6271                                 if (!clone)
6272                                         return -ENOMEM;
6273                                 insp = list->next;
6274                                 list = clone;
6275                         } else {
6276                                 /* This may be pulled without problems. */
6277                                 insp = list;
6278                         }
6279                         if (pskb_carve(list, eat, gfp_mask) < 0) {
6280                                 kfree_skb(clone);
6281                                 return -ENOMEM;
6282                         }
6283                         break;
6284                 }
6285         } while (eat);
6286
6287         /* Free pulled out fragments. */
6288         while ((list = shinfo->frag_list) != insp) {
6289                 shinfo->frag_list = list->next;
6290                 consume_skb(list);
6291         }
6292         /* And insert new clone at head. */
6293         if (clone) {
6294                 clone->next = list;
6295                 shinfo->frag_list = clone;
6296         }
6297         return 0;
6298 }
6299
6300 /* carve off first len bytes from skb. Split line (off) is in the
6301  * non-linear part of skb
6302  */
6303 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6304                                        int pos, gfp_t gfp_mask)
6305 {
6306         int i, k = 0;
6307         unsigned int size = skb_end_offset(skb);
6308         u8 *data;
6309         const int nfrags = skb_shinfo(skb)->nr_frags;
6310         struct skb_shared_info *shinfo;
6311
6312         if (skb_pfmemalloc(skb))
6313                 gfp_mask |= __GFP_MEMALLOC;
6314
6315         size = SKB_DATA_ALIGN(size);
6316         size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6317         size = kmalloc_size_roundup(size);
6318         data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
6319         if (!data)
6320                 return -ENOMEM;
6321         size = SKB_WITH_OVERHEAD(size);
6322
6323         memcpy((struct skb_shared_info *)(data + size),
6324                skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6325         if (skb_orphan_frags(skb, gfp_mask)) {
6326                 kfree(data);
6327                 return -ENOMEM;
6328         }
6329         shinfo = (struct skb_shared_info *)(data + size);
6330         for (i = 0; i < nfrags; i++) {
6331                 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6332
6333                 if (pos + fsize > off) {
6334                         shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6335
6336                         if (pos < off) {
6337                                 /* Split frag.
6338                                  * We have two variants in this case:
6339                                  * 1. Move all the frag to the second
6340                                  *    part, if it is possible. F.e.
6341                                  *    this approach is mandatory for TUX,
6342                                  *    where splitting is expensive.
6343                                  * 2. Split is accurately. We make this.
6344                                  */
6345                                 skb_frag_off_add(&shinfo->frags[0], off - pos);
6346                                 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6347                         }
6348                         skb_frag_ref(skb, i);
6349                         k++;
6350                 }
6351                 pos += fsize;
6352         }
6353         shinfo->nr_frags = k;
6354         if (skb_has_frag_list(skb))
6355                 skb_clone_fraglist(skb);
6356
6357         /* split line is in frag list */
6358         if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6359                 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6360                 if (skb_has_frag_list(skb))
6361                         kfree_skb_list(skb_shinfo(skb)->frag_list);
6362                 kfree(data);
6363                 return -ENOMEM;
6364         }
6365         skb_release_data(skb);
6366
6367         skb->head = data;
6368         skb->head_frag = 0;
6369         skb->data = data;
6370         skb_set_end_offset(skb, size);
6371         skb_reset_tail_pointer(skb);
6372         skb_headers_offset_update(skb, 0);
6373         skb->cloned   = 0;
6374         skb->hdr_len  = 0;
6375         skb->nohdr    = 0;
6376         skb->len -= off;
6377         skb->data_len = skb->len;
6378         atomic_set(&skb_shinfo(skb)->dataref, 1);
6379         return 0;
6380 }
6381
6382 /* remove len bytes from the beginning of the skb */
6383 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6384 {
6385         int headlen = skb_headlen(skb);
6386
6387         if (len < headlen)
6388                 return pskb_carve_inside_header(skb, len, headlen, gfp);
6389         else
6390                 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6391 }
6392
6393 /* Extract to_copy bytes starting at off from skb, and return this in
6394  * a new skb
6395  */
6396 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6397                              int to_copy, gfp_t gfp)
6398 {
6399         struct sk_buff  *clone = skb_clone(skb, gfp);
6400
6401         if (!clone)
6402                 return NULL;
6403
6404         if (pskb_carve(clone, off, gfp) < 0 ||
6405             pskb_trim(clone, to_copy)) {
6406                 kfree_skb(clone);
6407                 return NULL;
6408         }
6409         return clone;
6410 }
6411 EXPORT_SYMBOL(pskb_extract);
6412
6413 /**
6414  * skb_condense - try to get rid of fragments/frag_list if possible
6415  * @skb: buffer
6416  *
6417  * Can be used to save memory before skb is added to a busy queue.
6418  * If packet has bytes in frags and enough tail room in skb->head,
6419  * pull all of them, so that we can free the frags right now and adjust
6420  * truesize.
6421  * Notes:
6422  *      We do not reallocate skb->head thus can not fail.
6423  *      Caller must re-evaluate skb->truesize if needed.
6424  */
6425 void skb_condense(struct sk_buff *skb)
6426 {
6427         if (skb->data_len) {
6428                 if (skb->data_len > skb->end - skb->tail ||
6429                     skb_cloned(skb))
6430                         return;
6431
6432                 /* Nice, we can free page frag(s) right now */
6433                 __pskb_pull_tail(skb, skb->data_len);
6434         }
6435         /* At this point, skb->truesize might be over estimated,
6436          * because skb had a fragment, and fragments do not tell
6437          * their truesize.
6438          * When we pulled its content into skb->head, fragment
6439          * was freed, but __pskb_pull_tail() could not possibly
6440          * adjust skb->truesize, not knowing the frag truesize.
6441          */
6442         skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6443 }
6444
6445 #ifdef CONFIG_SKB_EXTENSIONS
6446 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6447 {
6448         return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6449 }
6450
6451 /**
6452  * __skb_ext_alloc - allocate a new skb extensions storage
6453  *
6454  * @flags: See kmalloc().
6455  *
6456  * Returns the newly allocated pointer. The pointer can later attached to a
6457  * skb via __skb_ext_set().
6458  * Note: caller must handle the skb_ext as an opaque data.
6459  */
6460 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6461 {
6462         struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6463
6464         if (new) {
6465                 memset(new->offset, 0, sizeof(new->offset));
6466                 refcount_set(&new->refcnt, 1);
6467         }
6468
6469         return new;
6470 }
6471
6472 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6473                                          unsigned int old_active)
6474 {
6475         struct skb_ext *new;
6476
6477         if (refcount_read(&old->refcnt) == 1)
6478                 return old;
6479
6480         new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6481         if (!new)
6482                 return NULL;
6483
6484         memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6485         refcount_set(&new->refcnt, 1);
6486
6487 #ifdef CONFIG_XFRM
6488         if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6489                 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6490                 unsigned int i;
6491
6492                 for (i = 0; i < sp->len; i++)
6493                         xfrm_state_hold(sp->xvec[i]);
6494         }
6495 #endif
6496         __skb_ext_put(old);
6497         return new;
6498 }
6499
6500 /**
6501  * __skb_ext_set - attach the specified extension storage to this skb
6502  * @skb: buffer
6503  * @id: extension id
6504  * @ext: extension storage previously allocated via __skb_ext_alloc()
6505  *
6506  * Existing extensions, if any, are cleared.
6507  *
6508  * Returns the pointer to the extension.
6509  */
6510 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6511                     struct skb_ext *ext)
6512 {
6513         unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6514
6515         skb_ext_put(skb);
6516         newlen = newoff + skb_ext_type_len[id];
6517         ext->chunks = newlen;
6518         ext->offset[id] = newoff;
6519         skb->extensions = ext;
6520         skb->active_extensions = 1 << id;
6521         return skb_ext_get_ptr(ext, id);
6522 }
6523
6524 /**
6525  * skb_ext_add - allocate space for given extension, COW if needed
6526  * @skb: buffer
6527  * @id: extension to allocate space for
6528  *
6529  * Allocates enough space for the given extension.
6530  * If the extension is already present, a pointer to that extension
6531  * is returned.
6532  *
6533  * If the skb was cloned, COW applies and the returned memory can be
6534  * modified without changing the extension space of clones buffers.
6535  *
6536  * Returns pointer to the extension or NULL on allocation failure.
6537  */
6538 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6539 {
6540         struct skb_ext *new, *old = NULL;
6541         unsigned int newlen, newoff;
6542
6543         if (skb->active_extensions) {
6544                 old = skb->extensions;
6545
6546                 new = skb_ext_maybe_cow(old, skb->active_extensions);
6547                 if (!new)
6548                         return NULL;
6549
6550                 if (__skb_ext_exist(new, id))
6551                         goto set_active;
6552
6553                 newoff = new->chunks;
6554         } else {
6555                 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6556
6557                 new = __skb_ext_alloc(GFP_ATOMIC);
6558                 if (!new)
6559                         return NULL;
6560         }
6561
6562         newlen = newoff + skb_ext_type_len[id];
6563         new->chunks = newlen;
6564         new->offset[id] = newoff;
6565 set_active:
6566         skb->slow_gro = 1;
6567         skb->extensions = new;
6568         skb->active_extensions |= 1 << id;
6569         return skb_ext_get_ptr(new, id);
6570 }
6571 EXPORT_SYMBOL(skb_ext_add);
6572
6573 #ifdef CONFIG_XFRM
6574 static void skb_ext_put_sp(struct sec_path *sp)
6575 {
6576         unsigned int i;
6577
6578         for (i = 0; i < sp->len; i++)
6579                 xfrm_state_put(sp->xvec[i]);
6580 }
6581 #endif
6582
6583 #ifdef CONFIG_MCTP_FLOWS
6584 static void skb_ext_put_mctp(struct mctp_flow *flow)
6585 {
6586         if (flow->key)
6587                 mctp_key_unref(flow->key);
6588 }
6589 #endif
6590
6591 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6592 {
6593         struct skb_ext *ext = skb->extensions;
6594
6595         skb->active_extensions &= ~(1 << id);
6596         if (skb->active_extensions == 0) {
6597                 skb->extensions = NULL;
6598                 __skb_ext_put(ext);
6599 #ifdef CONFIG_XFRM
6600         } else if (id == SKB_EXT_SEC_PATH &&
6601                    refcount_read(&ext->refcnt) == 1) {
6602                 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6603
6604                 skb_ext_put_sp(sp);
6605                 sp->len = 0;
6606 #endif
6607         }
6608 }
6609 EXPORT_SYMBOL(__skb_ext_del);
6610
6611 void __skb_ext_put(struct skb_ext *ext)
6612 {
6613         /* If this is last clone, nothing can increment
6614          * it after check passes.  Avoids one atomic op.
6615          */
6616         if (refcount_read(&ext->refcnt) == 1)
6617                 goto free_now;
6618
6619         if (!refcount_dec_and_test(&ext->refcnt))
6620                 return;
6621 free_now:
6622 #ifdef CONFIG_XFRM
6623         if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6624                 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6625 #endif
6626 #ifdef CONFIG_MCTP_FLOWS
6627         if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6628                 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6629 #endif
6630
6631         kmem_cache_free(skbuff_ext_cache, ext);
6632 }
6633 EXPORT_SYMBOL(__skb_ext_put);
6634 #endif /* CONFIG_SKB_EXTENSIONS */
6635
6636 /**
6637  * skb_attempt_defer_free - queue skb for remote freeing
6638  * @skb: buffer
6639  *
6640  * Put @skb in a per-cpu list, using the cpu which
6641  * allocated the skb/pages to reduce false sharing
6642  * and memory zone spinlock contention.
6643  */
6644 void skb_attempt_defer_free(struct sk_buff *skb)
6645 {
6646         int cpu = skb->alloc_cpu;
6647         struct softnet_data *sd;
6648         unsigned long flags;
6649         unsigned int defer_max;
6650         bool kick;
6651
6652         if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6653             !cpu_online(cpu) ||
6654             cpu == raw_smp_processor_id()) {
6655 nodefer:        __kfree_skb(skb);
6656                 return;
6657         }
6658
6659         sd = &per_cpu(softnet_data, cpu);
6660         defer_max = READ_ONCE(sysctl_skb_defer_max);
6661         if (READ_ONCE(sd->defer_count) >= defer_max)
6662                 goto nodefer;
6663
6664         spin_lock_irqsave(&sd->defer_lock, flags);
6665         /* Send an IPI every time queue reaches half capacity. */
6666         kick = sd->defer_count == (defer_max >> 1);
6667         /* Paired with the READ_ONCE() few lines above */
6668         WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6669
6670         skb->next = sd->defer_list;
6671         /* Paired with READ_ONCE() in skb_defer_free_flush() */
6672         WRITE_ONCE(sd->defer_list, skb);
6673         spin_unlock_irqrestore(&sd->defer_lock, flags);
6674
6675         /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6676          * if we are unlucky enough (this seems very unlikely).
6677          */
6678         if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6679                 smp_call_function_single_async(cpu, &sd->defer_csd);
6680 }