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