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