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