File Index
Files and directories
Sign in
FILE

skbuff.c

File preview with syntax highlighting.

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