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