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