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