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