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