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