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