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