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