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