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