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