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