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