GNU Linux-libre 4.9.284-gnu1
[releases.git] / net / core / skbuff.c
1 /*
2  *      Routines having to do with the 'struct sk_buff' memory handlers.
3  *
4  *      Authors:        Alan Cox <alan@lxorguk.ukuu.org.uk>
5  *                      Florian La Roche <rzsfl@rz.uni-sb.de>
6  *
7  *      Fixes:
8  *              Alan Cox        :       Fixed the worst of the load
9  *                                      balancer bugs.
10  *              Dave Platt      :       Interrupt stacking fix.
11  *      Richard Kooijman        :       Timestamp fixes.
12  *              Alan Cox        :       Changed buffer format.
13  *              Alan Cox        :       destructor hook for AF_UNIX etc.
14  *              Linus Torvalds  :       Better skb_clone.
15  *              Alan Cox        :       Added skb_copy.
16  *              Alan Cox        :       Added all the changed routines Linus
17  *                                      only put in the headers
18  *              Ray VanTassle   :       Fixed --skb->lock in free
19  *              Alan Cox        :       skb_copy copy arp field
20  *              Andi Kleen      :       slabified it.
21  *              Robert Olsson   :       Removed skb_head_pool
22  *
23  *      NOTE:
24  *              The __skb_ routines should be called with interrupts
25  *      disabled, or you better be *real* sure that the operation is atomic
26  *      with respect to whatever list is being frobbed (e.g. via lock_sock()
27  *      or via disabling bottom half handlers, etc).
28  *
29  *      This program is free software; you can redistribute it and/or
30  *      modify it under the terms of the GNU General Public License
31  *      as published by the Free Software Foundation; either version
32  *      2 of the License, or (at your option) any later version.
33  */
34
35 /*
36  *      The functions in this file will not compile correctly with gcc 2.4.x
37  */
38
39 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
40
41 #include <linux/module.h>
42 #include <linux/types.h>
43 #include <linux/kernel.h>
44 #include <linux/kmemcheck.h>
45 #include <linux/mm.h>
46 #include <linux/interrupt.h>
47 #include <linux/in.h>
48 #include <linux/inet.h>
49 #include <linux/slab.h>
50 #include <linux/tcp.h>
51 #include <linux/udp.h>
52 #include <linux/sctp.h>
53 #include <linux/netdevice.h>
54 #ifdef CONFIG_NET_CLS_ACT
55 #include <net/pkt_sched.h>
56 #endif
57 #include <linux/string.h>
58 #include <linux/skbuff.h>
59 #include <linux/splice.h>
60 #include <linux/cache.h>
61 #include <linux/rtnetlink.h>
62 #include <linux/init.h>
63 #include <linux/scatterlist.h>
64 #include <linux/errqueue.h>
65 #include <linux/prefetch.h>
66 #include <linux/if_vlan.h>
67
68 #include <net/protocol.h>
69 #include <net/dst.h>
70 #include <net/sock.h>
71 #include <net/checksum.h>
72 #include <net/ip6_checksum.h>
73 #include <net/xfrm.h>
74
75 #include <asm/uaccess.h>
76 #include <trace/events/skb.h>
77 #include <linux/highmem.h>
78 #include <linux/capability.h>
79 #include <linux/user_namespace.h>
80
81 struct kmem_cache *skbuff_head_cache __read_mostly;
82 static struct kmem_cache *skbuff_fclone_cache __read_mostly;
83 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
84 EXPORT_SYMBOL(sysctl_max_skb_frags);
85
86 /**
87  *      skb_panic - private function for out-of-line support
88  *      @skb:   buffer
89  *      @sz:    size
90  *      @addr:  address
91  *      @msg:   skb_over_panic or skb_under_panic
92  *
93  *      Out-of-line support for skb_put() and skb_push().
94  *      Called via the wrapper skb_over_panic() or skb_under_panic().
95  *      Keep out of line to prevent kernel bloat.
96  *      __builtin_return_address is not used because it is not always reliable.
97  */
98 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
99                       const char msg[])
100 {
101         pr_emerg("%s: text:%p len:%d put:%d head:%p data:%p tail:%#lx end:%#lx dev:%s\n",
102                  msg, addr, skb->len, sz, skb->head, skb->data,
103                  (unsigned long)skb->tail, (unsigned long)skb->end,
104                  skb->dev ? skb->dev->name : "<NULL>");
105         BUG();
106 }
107
108 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
109 {
110         skb_panic(skb, sz, addr, __func__);
111 }
112
113 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
114 {
115         skb_panic(skb, sz, addr, __func__);
116 }
117
118 /*
119  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
120  * the caller if emergency pfmemalloc reserves are being used. If it is and
121  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
122  * may be used. Otherwise, the packet data may be discarded until enough
123  * memory is free
124  */
125 #define kmalloc_reserve(size, gfp, node, pfmemalloc) \
126          __kmalloc_reserve(size, gfp, node, _RET_IP_, pfmemalloc)
127
128 static void *__kmalloc_reserve(size_t size, gfp_t flags, int node,
129                                unsigned long ip, bool *pfmemalloc)
130 {
131         void *obj;
132         bool ret_pfmemalloc = false;
133
134         /*
135          * Try a regular allocation, when that fails and we're not entitled
136          * to the reserves, fail.
137          */
138         obj = kmalloc_node_track_caller(size,
139                                         flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
140                                         node);
141         if (obj || !(gfp_pfmemalloc_allowed(flags)))
142                 goto out;
143
144         /* Try again but now we are using pfmemalloc reserves */
145         ret_pfmemalloc = true;
146         obj = kmalloc_node_track_caller(size, flags, node);
147
148 out:
149         if (pfmemalloc)
150                 *pfmemalloc = ret_pfmemalloc;
151
152         return obj;
153 }
154
155 /*      Allocate a new skbuff. We do this ourselves so we can fill in a few
156  *      'private' fields and also do memory statistics to find all the
157  *      [BEEP] leaks.
158  *
159  */
160
161 struct sk_buff *__alloc_skb_head(gfp_t gfp_mask, int node)
162 {
163         struct sk_buff *skb;
164
165         /* Get the HEAD */
166         skb = kmem_cache_alloc_node(skbuff_head_cache,
167                                     gfp_mask & ~__GFP_DMA, node);
168         if (!skb)
169                 goto out;
170
171         /*
172          * Only clear those fields we need to clear, not those that we will
173          * actually initialise below. Hence, don't put any more fields after
174          * the tail pointer in struct sk_buff!
175          */
176         memset(skb, 0, offsetof(struct sk_buff, tail));
177         skb->head = NULL;
178         skb->truesize = sizeof(struct sk_buff);
179         atomic_set(&skb->users, 1);
180
181         skb->mac_header = (typeof(skb->mac_header))~0U;
182 out:
183         return skb;
184 }
185
186 /**
187  *      __alloc_skb     -       allocate a network buffer
188  *      @size: size to allocate
189  *      @gfp_mask: allocation mask
190  *      @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
191  *              instead of head cache and allocate a cloned (child) skb.
192  *              If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
193  *              allocations in case the data is required for writeback
194  *      @node: numa node to allocate memory on
195  *
196  *      Allocate a new &sk_buff. The returned buffer has no headroom and a
197  *      tail room of at least size bytes. The object has a reference count
198  *      of one. The return is the buffer. On a failure the return is %NULL.
199  *
200  *      Buffers may only be allocated from interrupts using a @gfp_mask of
201  *      %GFP_ATOMIC.
202  */
203 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
204                             int flags, int node)
205 {
206         struct kmem_cache *cache;
207         struct skb_shared_info *shinfo;
208         struct sk_buff *skb;
209         u8 *data;
210         bool pfmemalloc;
211
212         cache = (flags & SKB_ALLOC_FCLONE)
213                 ? skbuff_fclone_cache : skbuff_head_cache;
214
215         if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
216                 gfp_mask |= __GFP_MEMALLOC;
217
218         /* Get the HEAD */
219         skb = kmem_cache_alloc_node(cache, gfp_mask & ~__GFP_DMA, node);
220         if (!skb)
221                 goto out;
222         prefetchw(skb);
223
224         /* We do our best to align skb_shared_info on a separate cache
225          * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
226          * aligned memory blocks, unless SLUB/SLAB debug is enabled.
227          * Both skb->head and skb_shared_info are cache line aligned.
228          */
229         size = SKB_DATA_ALIGN(size);
230         size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
231         data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
232         if (!data)
233                 goto nodata;
234         /* kmalloc(size) might give us more room than requested.
235          * Put skb_shared_info exactly at the end of allocated zone,
236          * to allow max possible filling before reallocation.
237          */
238         size = SKB_WITH_OVERHEAD(ksize(data));
239         prefetchw(data + size);
240
241         /*
242          * Only clear those fields we need to clear, not those that we will
243          * actually initialise below. Hence, don't put any more fields after
244          * the tail pointer in struct sk_buff!
245          */
246         memset(skb, 0, offsetof(struct sk_buff, tail));
247         /* Account for allocated memory : skb + skb->head */
248         skb->truesize = SKB_TRUESIZE(size);
249         skb->pfmemalloc = pfmemalloc;
250         atomic_set(&skb->users, 1);
251         skb->head = data;
252         skb->data = data;
253         skb_reset_tail_pointer(skb);
254         skb->end = skb->tail + size;
255         skb->mac_header = (typeof(skb->mac_header))~0U;
256         skb->transport_header = (typeof(skb->transport_header))~0U;
257
258         /* make sure we initialize shinfo sequentially */
259         shinfo = skb_shinfo(skb);
260         memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
261         atomic_set(&shinfo->dataref, 1);
262         kmemcheck_annotate_variable(shinfo->destructor_arg);
263
264         if (flags & SKB_ALLOC_FCLONE) {
265                 struct sk_buff_fclones *fclones;
266
267                 fclones = container_of(skb, struct sk_buff_fclones, skb1);
268
269                 kmemcheck_annotate_bitfield(&fclones->skb2, flags1);
270                 skb->fclone = SKB_FCLONE_ORIG;
271                 atomic_set(&fclones->fclone_ref, 1);
272
273                 fclones->skb2.fclone = SKB_FCLONE_CLONE;
274                 fclones->skb2.pfmemalloc = pfmemalloc;
275         }
276 out:
277         return skb;
278 nodata:
279         kmem_cache_free(cache, skb);
280         skb = NULL;
281         goto out;
282 }
283 EXPORT_SYMBOL(__alloc_skb);
284
285 /**
286  * __build_skb - build a network buffer
287  * @data: data buffer provided by caller
288  * @frag_size: size of data, or 0 if head was kmalloced
289  *
290  * Allocate a new &sk_buff. Caller provides space holding head and
291  * skb_shared_info. @data must have been allocated by kmalloc() only if
292  * @frag_size is 0, otherwise data should come from the page allocator
293  *  or vmalloc()
294  * The return is the new skb buffer.
295  * On a failure the return is %NULL, and @data is not freed.
296  * Notes :
297  *  Before IO, driver allocates only data buffer where NIC put incoming frame
298  *  Driver should add room at head (NET_SKB_PAD) and
299  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
300  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
301  *  before giving packet to stack.
302  *  RX rings only contains data buffers, not full skbs.
303  */
304 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
305 {
306         struct skb_shared_info *shinfo;
307         struct sk_buff *skb;
308         unsigned int size = frag_size ? : ksize(data);
309
310         skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
311         if (!skb)
312                 return NULL;
313
314         size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
315
316         memset(skb, 0, offsetof(struct sk_buff, tail));
317         skb->truesize = SKB_TRUESIZE(size);
318         atomic_set(&skb->users, 1);
319         skb->head = data;
320         skb->data = data;
321         skb_reset_tail_pointer(skb);
322         skb->end = skb->tail + size;
323         skb->mac_header = (typeof(skb->mac_header))~0U;
324         skb->transport_header = (typeof(skb->transport_header))~0U;
325
326         /* make sure we initialize shinfo sequentially */
327         shinfo = skb_shinfo(skb);
328         memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
329         atomic_set(&shinfo->dataref, 1);
330         kmemcheck_annotate_variable(shinfo->destructor_arg);
331
332         return skb;
333 }
334
335 /* build_skb() is wrapper over __build_skb(), that specifically
336  * takes care of skb->head and skb->pfmemalloc
337  * This means that if @frag_size is not zero, then @data must be backed
338  * by a page fragment, not kmalloc() or vmalloc()
339  */
340 struct sk_buff *build_skb(void *data, unsigned int frag_size)
341 {
342         struct sk_buff *skb = __build_skb(data, frag_size);
343
344         if (skb && frag_size) {
345                 skb->head_frag = 1;
346                 if (page_is_pfmemalloc(virt_to_head_page(data)))
347                         skb->pfmemalloc = 1;
348         }
349         return skb;
350 }
351 EXPORT_SYMBOL(build_skb);
352
353 #define NAPI_SKB_CACHE_SIZE     64
354
355 struct napi_alloc_cache {
356         struct page_frag_cache page;
357         size_t skb_count;
358         void *skb_cache[NAPI_SKB_CACHE_SIZE];
359 };
360
361 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
362 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
363
364 static void *__netdev_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
365 {
366         struct page_frag_cache *nc;
367         unsigned long flags;
368         void *data;
369
370         local_irq_save(flags);
371         nc = this_cpu_ptr(&netdev_alloc_cache);
372         data = __alloc_page_frag(nc, fragsz, gfp_mask);
373         local_irq_restore(flags);
374         return data;
375 }
376
377 /**
378  * netdev_alloc_frag - allocate a page fragment
379  * @fragsz: fragment size
380  *
381  * Allocates a frag from a page for receive buffer.
382  * Uses GFP_ATOMIC allocations.
383  */
384 void *netdev_alloc_frag(unsigned int fragsz)
385 {
386         fragsz = SKB_DATA_ALIGN(fragsz);
387
388         return __netdev_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
389 }
390 EXPORT_SYMBOL(netdev_alloc_frag);
391
392 static void *__napi_alloc_frag(unsigned int fragsz, gfp_t gfp_mask)
393 {
394         struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
395
396         return __alloc_page_frag(&nc->page, fragsz, gfp_mask);
397 }
398
399 void *napi_alloc_frag(unsigned int fragsz)
400 {
401         fragsz = SKB_DATA_ALIGN(fragsz);
402
403         return __napi_alloc_frag(fragsz, GFP_ATOMIC | __GFP_COLD);
404 }
405 EXPORT_SYMBOL(napi_alloc_frag);
406
407 /**
408  *      __netdev_alloc_skb - allocate an skbuff for rx on a specific device
409  *      @dev: network device to receive on
410  *      @len: length to allocate
411  *      @gfp_mask: get_free_pages mask, passed to alloc_skb
412  *
413  *      Allocate a new &sk_buff and assign it a usage count of one. The
414  *      buffer has NET_SKB_PAD headroom built in. Users should allocate
415  *      the headroom they think they need without accounting for the
416  *      built in space. The built in space is used for optimisations.
417  *
418  *      %NULL is returned if there is no free memory.
419  */
420 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
421                                    gfp_t gfp_mask)
422 {
423         struct page_frag_cache *nc;
424         unsigned long flags;
425         struct sk_buff *skb;
426         bool pfmemalloc;
427         void *data;
428
429         len += NET_SKB_PAD;
430
431         /* If requested length is either too small or too big,
432          * we use kmalloc() for skb->head allocation.
433          */
434         if (len <= SKB_WITH_OVERHEAD(1024) ||
435             len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
436             (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
437                 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
438                 if (!skb)
439                         goto skb_fail;
440                 goto skb_success;
441         }
442
443         len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
444         len = SKB_DATA_ALIGN(len);
445
446         if (sk_memalloc_socks())
447                 gfp_mask |= __GFP_MEMALLOC;
448
449         local_irq_save(flags);
450
451         nc = this_cpu_ptr(&netdev_alloc_cache);
452         data = __alloc_page_frag(nc, len, gfp_mask);
453         pfmemalloc = nc->pfmemalloc;
454
455         local_irq_restore(flags);
456
457         if (unlikely(!data))
458                 return NULL;
459
460         skb = __build_skb(data, len);
461         if (unlikely(!skb)) {
462                 skb_free_frag(data);
463                 return NULL;
464         }
465
466         /* use OR instead of assignment to avoid clearing of bits in mask */
467         if (pfmemalloc)
468                 skb->pfmemalloc = 1;
469         skb->head_frag = 1;
470
471 skb_success:
472         skb_reserve(skb, NET_SKB_PAD);
473         skb->dev = dev;
474
475 skb_fail:
476         return skb;
477 }
478 EXPORT_SYMBOL(__netdev_alloc_skb);
479
480 /**
481  *      __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
482  *      @napi: napi instance this buffer was allocated for
483  *      @len: length to allocate
484  *      @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
485  *
486  *      Allocate a new sk_buff for use in NAPI receive.  This buffer will
487  *      attempt to allocate the head from a special reserved region used
488  *      only for NAPI Rx allocation.  By doing this we can save several
489  *      CPU cycles by avoiding having to disable and re-enable IRQs.
490  *
491  *      %NULL is returned if there is no free memory.
492  */
493 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
494                                  gfp_t gfp_mask)
495 {
496         struct napi_alloc_cache *nc;
497         struct sk_buff *skb;
498         void *data;
499
500         len += NET_SKB_PAD + NET_IP_ALIGN;
501
502         /* If requested length is either too small or too big,
503          * we use kmalloc() for skb->head allocation.
504          */
505         if (len <= SKB_WITH_OVERHEAD(1024) ||
506             len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
507             (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
508                 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
509                 if (!skb)
510                         goto skb_fail;
511                 goto skb_success;
512         }
513
514         nc = this_cpu_ptr(&napi_alloc_cache);
515         len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
516         len = SKB_DATA_ALIGN(len);
517
518         if (sk_memalloc_socks())
519                 gfp_mask |= __GFP_MEMALLOC;
520
521         data = __alloc_page_frag(&nc->page, len, gfp_mask);
522         if (unlikely(!data))
523                 return NULL;
524
525         skb = __build_skb(data, len);
526         if (unlikely(!skb)) {
527                 skb_free_frag(data);
528                 return NULL;
529         }
530
531         /* use OR instead of assignment to avoid clearing of bits in mask */
532         if (nc->page.pfmemalloc)
533                 skb->pfmemalloc = 1;
534         skb->head_frag = 1;
535
536 skb_success:
537         skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
538         skb->dev = napi->dev;
539
540 skb_fail:
541         return skb;
542 }
543 EXPORT_SYMBOL(__napi_alloc_skb);
544
545 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
546                      int size, unsigned int truesize)
547 {
548         skb_fill_page_desc(skb, i, page, off, size);
549         skb->len += size;
550         skb->data_len += size;
551         skb->truesize += truesize;
552 }
553 EXPORT_SYMBOL(skb_add_rx_frag);
554
555 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
556                           unsigned int truesize)
557 {
558         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
559
560         skb_frag_size_add(frag, size);
561         skb->len += size;
562         skb->data_len += size;
563         skb->truesize += truesize;
564 }
565 EXPORT_SYMBOL(skb_coalesce_rx_frag);
566
567 static void skb_drop_list(struct sk_buff **listp)
568 {
569         kfree_skb_list(*listp);
570         *listp = NULL;
571 }
572
573 static inline void skb_drop_fraglist(struct sk_buff *skb)
574 {
575         skb_drop_list(&skb_shinfo(skb)->frag_list);
576 }
577
578 static void skb_clone_fraglist(struct sk_buff *skb)
579 {
580         struct sk_buff *list;
581
582         skb_walk_frags(skb, list)
583                 skb_get(list);
584 }
585
586 static void skb_free_head(struct sk_buff *skb)
587 {
588         unsigned char *head = skb->head;
589
590         if (skb->head_frag)
591                 skb_free_frag(head);
592         else
593                 kfree(head);
594 }
595
596 static void skb_release_data(struct sk_buff *skb)
597 {
598         struct skb_shared_info *shinfo = skb_shinfo(skb);
599         int i;
600
601         if (skb->cloned &&
602             atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
603                               &shinfo->dataref))
604                 return;
605
606         for (i = 0; i < shinfo->nr_frags; i++)
607                 __skb_frag_unref(&shinfo->frags[i]);
608
609         /*
610          * If skb buf is from userspace, we need to notify the caller
611          * the lower device DMA has done;
612          */
613         if (shinfo->tx_flags & SKBTX_DEV_ZEROCOPY) {
614                 struct ubuf_info *uarg;
615
616                 uarg = shinfo->destructor_arg;
617                 if (uarg->callback)
618                         uarg->callback(uarg, true);
619         }
620
621         if (shinfo->frag_list)
622                 kfree_skb_list(shinfo->frag_list);
623
624         skb_free_head(skb);
625 }
626
627 /*
628  *      Free an skbuff by memory without cleaning the state.
629  */
630 static void kfree_skbmem(struct sk_buff *skb)
631 {
632         struct sk_buff_fclones *fclones;
633
634         switch (skb->fclone) {
635         case SKB_FCLONE_UNAVAILABLE:
636                 kmem_cache_free(skbuff_head_cache, skb);
637                 return;
638
639         case SKB_FCLONE_ORIG:
640                 fclones = container_of(skb, struct sk_buff_fclones, skb1);
641
642                 /* We usually free the clone (TX completion) before original skb
643                  * This test would have no chance to be true for the clone,
644                  * while here, branch prediction will be good.
645                  */
646                 if (atomic_read(&fclones->fclone_ref) == 1)
647                         goto fastpath;
648                 break;
649
650         default: /* SKB_FCLONE_CLONE */
651                 fclones = container_of(skb, struct sk_buff_fclones, skb2);
652                 break;
653         }
654         if (!atomic_dec_and_test(&fclones->fclone_ref))
655                 return;
656 fastpath:
657         kmem_cache_free(skbuff_fclone_cache, fclones);
658 }
659
660 static void skb_release_head_state(struct sk_buff *skb)
661 {
662         skb_dst_drop(skb);
663 #ifdef CONFIG_XFRM
664         secpath_put(skb->sp);
665 #endif
666         if (skb->destructor) {
667                 WARN_ON(in_irq());
668                 skb->destructor(skb);
669         }
670 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
671         nf_conntrack_put(skb->nfct);
672 #endif
673 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
674         nf_bridge_put(skb->nf_bridge);
675 #endif
676 }
677
678 /* Free everything but the sk_buff shell. */
679 static void skb_release_all(struct sk_buff *skb)
680 {
681         skb_release_head_state(skb);
682         if (likely(skb->head))
683                 skb_release_data(skb);
684 }
685
686 /**
687  *      __kfree_skb - private function
688  *      @skb: buffer
689  *
690  *      Free an sk_buff. Release anything attached to the buffer.
691  *      Clean the state. This is an internal helper function. Users should
692  *      always call kfree_skb
693  */
694
695 void __kfree_skb(struct sk_buff *skb)
696 {
697         skb_release_all(skb);
698         kfree_skbmem(skb);
699 }
700 EXPORT_SYMBOL(__kfree_skb);
701
702 /**
703  *      kfree_skb - free an sk_buff
704  *      @skb: buffer to free
705  *
706  *      Drop a reference to the buffer and free it if the usage count has
707  *      hit zero.
708  */
709 void kfree_skb(struct sk_buff *skb)
710 {
711         if (unlikely(!skb))
712                 return;
713         if (likely(atomic_read(&skb->users) == 1))
714                 smp_rmb();
715         else if (likely(!atomic_dec_and_test(&skb->users)))
716                 return;
717         trace_kfree_skb(skb, __builtin_return_address(0));
718         __kfree_skb(skb);
719 }
720 EXPORT_SYMBOL(kfree_skb);
721
722 void kfree_skb_list(struct sk_buff *segs)
723 {
724         while (segs) {
725                 struct sk_buff *next = segs->next;
726
727                 kfree_skb(segs);
728                 segs = next;
729         }
730 }
731 EXPORT_SYMBOL(kfree_skb_list);
732
733 /**
734  *      skb_tx_error - report an sk_buff xmit error
735  *      @skb: buffer that triggered an error
736  *
737  *      Report xmit error if a device callback is tracking this skb.
738  *      skb must be freed afterwards.
739  */
740 void skb_tx_error(struct sk_buff *skb)
741 {
742         if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
743                 struct ubuf_info *uarg;
744
745                 uarg = skb_shinfo(skb)->destructor_arg;
746                 if (uarg->callback)
747                         uarg->callback(uarg, false);
748                 skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
749         }
750 }
751 EXPORT_SYMBOL(skb_tx_error);
752
753 /**
754  *      consume_skb - free an skbuff
755  *      @skb: buffer to free
756  *
757  *      Drop a ref to the buffer and free it if the usage count has hit zero
758  *      Functions identically to kfree_skb, but kfree_skb assumes that the frame
759  *      is being dropped after a failure and notes that
760  */
761 void consume_skb(struct sk_buff *skb)
762 {
763         if (unlikely(!skb))
764                 return;
765         if (likely(atomic_read(&skb->users) == 1))
766                 smp_rmb();
767         else if (likely(!atomic_dec_and_test(&skb->users)))
768                 return;
769         trace_consume_skb(skb);
770         __kfree_skb(skb);
771 }
772 EXPORT_SYMBOL(consume_skb);
773
774 void __kfree_skb_flush(void)
775 {
776         struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
777
778         /* flush skb_cache if containing objects */
779         if (nc->skb_count) {
780                 kmem_cache_free_bulk(skbuff_head_cache, nc->skb_count,
781                                      nc->skb_cache);
782                 nc->skb_count = 0;
783         }
784 }
785
786 static inline void _kfree_skb_defer(struct sk_buff *skb)
787 {
788         struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
789
790         /* drop skb->head and call any destructors for packet */
791         skb_release_all(skb);
792
793         /* record skb to CPU local list */
794         nc->skb_cache[nc->skb_count++] = skb;
795
796 #ifdef CONFIG_SLUB
797         /* SLUB writes into objects when freeing */
798         prefetchw(skb);
799 #endif
800
801         /* flush skb_cache if it is filled */
802         if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
803                 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_SIZE,
804                                      nc->skb_cache);
805                 nc->skb_count = 0;
806         }
807 }
808 void __kfree_skb_defer(struct sk_buff *skb)
809 {
810         _kfree_skb_defer(skb);
811 }
812
813 void napi_consume_skb(struct sk_buff *skb, int budget)
814 {
815         if (unlikely(!skb))
816                 return;
817
818         /* Zero budget indicate non-NAPI context called us, like netpoll */
819         if (unlikely(!budget)) {
820                 dev_consume_skb_any(skb);
821                 return;
822         }
823
824         if (likely(atomic_read(&skb->users) == 1))
825                 smp_rmb();
826         else if (likely(!atomic_dec_and_test(&skb->users)))
827                 return;
828         /* if reaching here SKB is ready to free */
829         trace_consume_skb(skb);
830
831         /* if SKB is a clone, don't handle this case */
832         if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
833                 __kfree_skb(skb);
834                 return;
835         }
836
837         _kfree_skb_defer(skb);
838 }
839 EXPORT_SYMBOL(napi_consume_skb);
840
841 /* Make sure a field is enclosed inside headers_start/headers_end section */
842 #define CHECK_SKB_FIELD(field) \
843         BUILD_BUG_ON(offsetof(struct sk_buff, field) <          \
844                      offsetof(struct sk_buff, headers_start));  \
845         BUILD_BUG_ON(offsetof(struct sk_buff, field) >          \
846                      offsetof(struct sk_buff, headers_end));    \
847
848 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
849 {
850         new->tstamp             = old->tstamp;
851         /* We do not copy old->sk */
852         new->dev                = old->dev;
853         memcpy(new->cb, old->cb, sizeof(old->cb));
854         skb_dst_copy(new, old);
855 #ifdef CONFIG_XFRM
856         new->sp                 = secpath_get(old->sp);
857 #endif
858         __nf_copy(new, old, false);
859
860         /* Note : this field could be in headers_start/headers_end section
861          * It is not yet because we do not want to have a 16 bit hole
862          */
863         new->queue_mapping = old->queue_mapping;
864
865         memcpy(&new->headers_start, &old->headers_start,
866                offsetof(struct sk_buff, headers_end) -
867                offsetof(struct sk_buff, headers_start));
868         CHECK_SKB_FIELD(protocol);
869         CHECK_SKB_FIELD(csum);
870         CHECK_SKB_FIELD(hash);
871         CHECK_SKB_FIELD(priority);
872         CHECK_SKB_FIELD(skb_iif);
873         CHECK_SKB_FIELD(vlan_proto);
874         CHECK_SKB_FIELD(vlan_tci);
875         CHECK_SKB_FIELD(transport_header);
876         CHECK_SKB_FIELD(network_header);
877         CHECK_SKB_FIELD(mac_header);
878         CHECK_SKB_FIELD(inner_protocol);
879         CHECK_SKB_FIELD(inner_transport_header);
880         CHECK_SKB_FIELD(inner_network_header);
881         CHECK_SKB_FIELD(inner_mac_header);
882         CHECK_SKB_FIELD(mark);
883 #ifdef CONFIG_NETWORK_SECMARK
884         CHECK_SKB_FIELD(secmark);
885 #endif
886 #ifdef CONFIG_NET_RX_BUSY_POLL
887         CHECK_SKB_FIELD(napi_id);
888 #endif
889 #ifdef CONFIG_XPS
890         CHECK_SKB_FIELD(sender_cpu);
891 #endif
892 #ifdef CONFIG_NET_SCHED
893         CHECK_SKB_FIELD(tc_index);
894 #ifdef CONFIG_NET_CLS_ACT
895         CHECK_SKB_FIELD(tc_verd);
896 #endif
897 #endif
898
899 }
900
901 /*
902  * You should not add any new code to this function.  Add it to
903  * __copy_skb_header above instead.
904  */
905 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
906 {
907 #define C(x) n->x = skb->x
908
909         n->next = n->prev = NULL;
910         n->sk = NULL;
911         __copy_skb_header(n, skb);
912
913         C(len);
914         C(data_len);
915         C(mac_len);
916         n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
917         n->cloned = 1;
918         n->nohdr = 0;
919         n->peeked = 0;
920         C(pfmemalloc);
921         n->destructor = NULL;
922         C(tail);
923         C(end);
924         C(head);
925         C(head_frag);
926         C(data);
927         C(truesize);
928         atomic_set(&n->users, 1);
929
930         atomic_inc(&(skb_shinfo(skb)->dataref));
931         skb->cloned = 1;
932
933         return n;
934 #undef C
935 }
936
937 /**
938  *      skb_morph       -       morph one skb into another
939  *      @dst: the skb to receive the contents
940  *      @src: the skb to supply the contents
941  *
942  *      This is identical to skb_clone except that the target skb is
943  *      supplied by the user.
944  *
945  *      The target skb is returned upon exit.
946  */
947 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
948 {
949         skb_release_all(dst);
950         return __skb_clone(dst, src);
951 }
952 EXPORT_SYMBOL_GPL(skb_morph);
953
954 /**
955  *      skb_copy_ubufs  -       copy userspace skb frags buffers to kernel
956  *      @skb: the skb to modify
957  *      @gfp_mask: allocation priority
958  *
959  *      This must be called on SKBTX_DEV_ZEROCOPY skb.
960  *      It will copy all frags into kernel and drop the reference
961  *      to userspace pages.
962  *
963  *      If this function is called from an interrupt gfp_mask() must be
964  *      %GFP_ATOMIC.
965  *
966  *      Returns 0 on success or a negative error code on failure
967  *      to allocate kernel memory to copy to.
968  */
969 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
970 {
971         int i;
972         int num_frags = skb_shinfo(skb)->nr_frags;
973         struct page *page, *head = NULL;
974         struct ubuf_info *uarg = skb_shinfo(skb)->destructor_arg;
975
976         for (i = 0; i < num_frags; i++) {
977                 u8 *vaddr;
978                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
979
980                 page = alloc_page(gfp_mask);
981                 if (!page) {
982                         while (head) {
983                                 struct page *next = (struct page *)page_private(head);
984                                 put_page(head);
985                                 head = next;
986                         }
987                         return -ENOMEM;
988                 }
989                 vaddr = kmap_atomic(skb_frag_page(f));
990                 memcpy(page_address(page),
991                        vaddr + f->page_offset, skb_frag_size(f));
992                 kunmap_atomic(vaddr);
993                 set_page_private(page, (unsigned long)head);
994                 head = page;
995         }
996
997         /* skb frags release userspace buffers */
998         for (i = 0; i < num_frags; i++)
999                 skb_frag_unref(skb, i);
1000
1001         uarg->callback(uarg, false);
1002
1003         /* skb frags point to kernel buffers */
1004         for (i = num_frags - 1; i >= 0; i--) {
1005                 __skb_fill_page_desc(skb, i, head, 0,
1006                                      skb_shinfo(skb)->frags[i].size);
1007                 head = (struct page *)page_private(head);
1008         }
1009
1010         skb_shinfo(skb)->tx_flags &= ~SKBTX_DEV_ZEROCOPY;
1011         return 0;
1012 }
1013 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1014
1015 /**
1016  *      skb_clone       -       duplicate an sk_buff
1017  *      @skb: buffer to clone
1018  *      @gfp_mask: allocation priority
1019  *
1020  *      Duplicate an &sk_buff. The new one is not owned by a socket. Both
1021  *      copies share the same packet data but not structure. The new
1022  *      buffer has a reference count of 1. If the allocation fails the
1023  *      function returns %NULL otherwise the new buffer is returned.
1024  *
1025  *      If this function is called from an interrupt gfp_mask() must be
1026  *      %GFP_ATOMIC.
1027  */
1028
1029 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1030 {
1031         struct sk_buff_fclones *fclones = container_of(skb,
1032                                                        struct sk_buff_fclones,
1033                                                        skb1);
1034         struct sk_buff *n;
1035
1036         if (skb_orphan_frags(skb, gfp_mask))
1037                 return NULL;
1038
1039         if (skb->fclone == SKB_FCLONE_ORIG &&
1040             atomic_read(&fclones->fclone_ref) == 1) {
1041                 n = &fclones->skb2;
1042                 atomic_set(&fclones->fclone_ref, 2);
1043         } else {
1044                 if (skb_pfmemalloc(skb))
1045                         gfp_mask |= __GFP_MEMALLOC;
1046
1047                 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1048                 if (!n)
1049                         return NULL;
1050
1051                 kmemcheck_annotate_bitfield(n, flags1);
1052                 n->fclone = SKB_FCLONE_UNAVAILABLE;
1053         }
1054
1055         return __skb_clone(n, skb);
1056 }
1057 EXPORT_SYMBOL(skb_clone);
1058
1059 static void skb_headers_offset_update(struct sk_buff *skb, int off)
1060 {
1061         /* Only adjust this if it actually is csum_start rather than csum */
1062         if (skb->ip_summed == CHECKSUM_PARTIAL)
1063                 skb->csum_start += off;
1064         /* {transport,network,mac}_header and tail are relative to skb->head */
1065         skb->transport_header += off;
1066         skb->network_header   += off;
1067         if (skb_mac_header_was_set(skb))
1068                 skb->mac_header += off;
1069         skb->inner_transport_header += off;
1070         skb->inner_network_header += off;
1071         skb->inner_mac_header += off;
1072 }
1073
1074 static void copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1075 {
1076         __copy_skb_header(new, old);
1077
1078         skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1079         skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1080         skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1081 }
1082
1083 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1084 {
1085         if (skb_pfmemalloc(skb))
1086                 return SKB_ALLOC_RX;
1087         return 0;
1088 }
1089
1090 /**
1091  *      skb_copy        -       create private copy of an sk_buff
1092  *      @skb: buffer to copy
1093  *      @gfp_mask: allocation priority
1094  *
1095  *      Make a copy of both an &sk_buff and its data. This is used when the
1096  *      caller wishes to modify the data and needs a private copy of the
1097  *      data to alter. Returns %NULL on failure or the pointer to the buffer
1098  *      on success. The returned buffer has a reference count of 1.
1099  *
1100  *      As by-product this function converts non-linear &sk_buff to linear
1101  *      one, so that &sk_buff becomes completely private and caller is allowed
1102  *      to modify all the data of returned buffer. This means that this
1103  *      function is not recommended for use in circumstances when only
1104  *      header is going to be modified. Use pskb_copy() instead.
1105  */
1106
1107 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1108 {
1109         int headerlen = skb_headroom(skb);
1110         unsigned int size = skb_end_offset(skb) + skb->data_len;
1111         struct sk_buff *n = __alloc_skb(size, gfp_mask,
1112                                         skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1113
1114         if (!n)
1115                 return NULL;
1116
1117         /* Set the data pointer */
1118         skb_reserve(n, headerlen);
1119         /* Set the tail pointer and length */
1120         skb_put(n, skb->len);
1121
1122         if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len))
1123                 BUG();
1124
1125         copy_skb_header(n, skb);
1126         return n;
1127 }
1128 EXPORT_SYMBOL(skb_copy);
1129
1130 /**
1131  *      __pskb_copy_fclone      -  create copy of an sk_buff with private head.
1132  *      @skb: buffer to copy
1133  *      @headroom: headroom of new skb
1134  *      @gfp_mask: allocation priority
1135  *      @fclone: if true allocate the copy of the skb from the fclone
1136  *      cache instead of the head cache; it is recommended to set this
1137  *      to true for the cases where the copy will likely be cloned
1138  *
1139  *      Make a copy of both an &sk_buff and part of its data, located
1140  *      in header. Fragmented data remain shared. This is used when
1141  *      the caller wishes to modify only header of &sk_buff and needs
1142  *      private copy of the header to alter. Returns %NULL on failure
1143  *      or the pointer to the buffer on success.
1144  *      The returned buffer has a reference count of 1.
1145  */
1146
1147 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1148                                    gfp_t gfp_mask, bool fclone)
1149 {
1150         unsigned int size = skb_headlen(skb) + headroom;
1151         int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1152         struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1153
1154         if (!n)
1155                 goto out;
1156
1157         /* Set the data pointer */
1158         skb_reserve(n, headroom);
1159         /* Set the tail pointer and length */
1160         skb_put(n, skb_headlen(skb));
1161         /* Copy the bytes */
1162         skb_copy_from_linear_data(skb, n->data, n->len);
1163
1164         n->truesize += skb->data_len;
1165         n->data_len  = skb->data_len;
1166         n->len       = skb->len;
1167
1168         if (skb_shinfo(skb)->nr_frags) {
1169                 int i;
1170
1171                 if (skb_orphan_frags(skb, gfp_mask)) {
1172                         kfree_skb(n);
1173                         n = NULL;
1174                         goto out;
1175                 }
1176                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1177                         skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1178                         skb_frag_ref(skb, i);
1179                 }
1180                 skb_shinfo(n)->nr_frags = i;
1181         }
1182
1183         if (skb_has_frag_list(skb)) {
1184                 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1185                 skb_clone_fraglist(n);
1186         }
1187
1188         copy_skb_header(n, skb);
1189 out:
1190         return n;
1191 }
1192 EXPORT_SYMBOL(__pskb_copy_fclone);
1193
1194 /**
1195  *      pskb_expand_head - reallocate header of &sk_buff
1196  *      @skb: buffer to reallocate
1197  *      @nhead: room to add at head
1198  *      @ntail: room to add at tail
1199  *      @gfp_mask: allocation priority
1200  *
1201  *      Expands (or creates identical copy, if @nhead and @ntail are zero)
1202  *      header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1203  *      reference count of 1. Returns zero in the case of success or error,
1204  *      if expansion failed. In the last case, &sk_buff is not changed.
1205  *
1206  *      All the pointers pointing into skb header may change and must be
1207  *      reloaded after call to this function.
1208  */
1209
1210 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1211                      gfp_t gfp_mask)
1212 {
1213         int i;
1214         u8 *data;
1215         int size = nhead + skb_end_offset(skb) + ntail;
1216         long off;
1217
1218         BUG_ON(nhead < 0);
1219
1220         if (skb_shared(skb))
1221                 BUG();
1222
1223         size = SKB_DATA_ALIGN(size);
1224
1225         if (skb_pfmemalloc(skb))
1226                 gfp_mask |= __GFP_MEMALLOC;
1227         data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1228                                gfp_mask, NUMA_NO_NODE, NULL);
1229         if (!data)
1230                 goto nodata;
1231         size = SKB_WITH_OVERHEAD(ksize(data));
1232
1233         /* Copy only real data... and, alas, header. This should be
1234          * optimized for the cases when header is void.
1235          */
1236         memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1237
1238         memcpy((struct skb_shared_info *)(data + size),
1239                skb_shinfo(skb),
1240                offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1241
1242         /*
1243          * if shinfo is shared we must drop the old head gracefully, but if it
1244          * is not we can just drop the old head and let the existing refcount
1245          * be since all we did is relocate the values
1246          */
1247         if (skb_cloned(skb)) {
1248                 /* copy this zero copy skb frags */
1249                 if (skb_orphan_frags(skb, gfp_mask))
1250                         goto nofrags;
1251                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1252                         skb_frag_ref(skb, i);
1253
1254                 if (skb_has_frag_list(skb))
1255                         skb_clone_fraglist(skb);
1256
1257                 skb_release_data(skb);
1258         } else {
1259                 skb_free_head(skb);
1260         }
1261         off = (data + nhead) - skb->head;
1262
1263         skb->head     = data;
1264         skb->head_frag = 0;
1265         skb->data    += off;
1266 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1267         skb->end      = size;
1268         off           = nhead;
1269 #else
1270         skb->end      = skb->head + size;
1271 #endif
1272         skb->tail             += off;
1273         skb_headers_offset_update(skb, nhead);
1274         skb->cloned   = 0;
1275         skb->hdr_len  = 0;
1276         skb->nohdr    = 0;
1277         atomic_set(&skb_shinfo(skb)->dataref, 1);
1278         return 0;
1279
1280 nofrags:
1281         kfree(data);
1282 nodata:
1283         return -ENOMEM;
1284 }
1285 EXPORT_SYMBOL(pskb_expand_head);
1286
1287 /* Make private copy of skb with writable head and some headroom */
1288
1289 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1290 {
1291         struct sk_buff *skb2;
1292         int delta = headroom - skb_headroom(skb);
1293
1294         if (delta <= 0)
1295                 skb2 = pskb_copy(skb, GFP_ATOMIC);
1296         else {
1297                 skb2 = skb_clone(skb, GFP_ATOMIC);
1298                 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1299                                              GFP_ATOMIC)) {
1300                         kfree_skb(skb2);
1301                         skb2 = NULL;
1302                 }
1303         }
1304         return skb2;
1305 }
1306 EXPORT_SYMBOL(skb_realloc_headroom);
1307
1308 /**
1309  *      skb_copy_expand -       copy and expand sk_buff
1310  *      @skb: buffer to copy
1311  *      @newheadroom: new free bytes at head
1312  *      @newtailroom: new free bytes at tail
1313  *      @gfp_mask: allocation priority
1314  *
1315  *      Make a copy of both an &sk_buff and its data and while doing so
1316  *      allocate additional space.
1317  *
1318  *      This is used when the caller wishes to modify the data and needs a
1319  *      private copy of the data to alter as well as more space for new fields.
1320  *      Returns %NULL on failure or the pointer to the buffer
1321  *      on success. The returned buffer has a reference count of 1.
1322  *
1323  *      You must pass %GFP_ATOMIC as the allocation priority if this function
1324  *      is called from an interrupt.
1325  */
1326 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1327                                 int newheadroom, int newtailroom,
1328                                 gfp_t gfp_mask)
1329 {
1330         /*
1331          *      Allocate the copy buffer
1332          */
1333         struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1334                                         gfp_mask, skb_alloc_rx_flag(skb),
1335                                         NUMA_NO_NODE);
1336         int oldheadroom = skb_headroom(skb);
1337         int head_copy_len, head_copy_off;
1338
1339         if (!n)
1340                 return NULL;
1341
1342         skb_reserve(n, newheadroom);
1343
1344         /* Set the tail pointer and length */
1345         skb_put(n, skb->len);
1346
1347         head_copy_len = oldheadroom;
1348         head_copy_off = 0;
1349         if (newheadroom <= head_copy_len)
1350                 head_copy_len = newheadroom;
1351         else
1352                 head_copy_off = newheadroom - head_copy_len;
1353
1354         /* Copy the linear header and data. */
1355         if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1356                           skb->len + head_copy_len))
1357                 BUG();
1358
1359         copy_skb_header(n, skb);
1360
1361         skb_headers_offset_update(n, newheadroom - oldheadroom);
1362
1363         return n;
1364 }
1365 EXPORT_SYMBOL(skb_copy_expand);
1366
1367 /**
1368  *      skb_pad                 -       zero pad the tail of an skb
1369  *      @skb: buffer to pad
1370  *      @pad: space to pad
1371  *
1372  *      Ensure that a buffer is followed by a padding area that is zero
1373  *      filled. Used by network drivers which may DMA or transfer data
1374  *      beyond the buffer end onto the wire.
1375  *
1376  *      May return error in out of memory cases. The skb is freed on error.
1377  */
1378
1379 int skb_pad(struct sk_buff *skb, int pad)
1380 {
1381         int err;
1382         int ntail;
1383
1384         /* If the skbuff is non linear tailroom is always zero.. */
1385         if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1386                 memset(skb->data+skb->len, 0, pad);
1387                 return 0;
1388         }
1389
1390         ntail = skb->data_len + pad - (skb->end - skb->tail);
1391         if (likely(skb_cloned(skb) || ntail > 0)) {
1392                 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1393                 if (unlikely(err))
1394                         goto free_skb;
1395         }
1396
1397         /* FIXME: The use of this function with non-linear skb's really needs
1398          * to be audited.
1399          */
1400         err = skb_linearize(skb);
1401         if (unlikely(err))
1402                 goto free_skb;
1403
1404         memset(skb->data + skb->len, 0, pad);
1405         return 0;
1406
1407 free_skb:
1408         kfree_skb(skb);
1409         return err;
1410 }
1411 EXPORT_SYMBOL(skb_pad);
1412
1413 /**
1414  *      pskb_put - add data to the tail of a potentially fragmented buffer
1415  *      @skb: start of the buffer to use
1416  *      @tail: tail fragment of the buffer to use
1417  *      @len: amount of data to add
1418  *
1419  *      This function extends the used data area of the potentially
1420  *      fragmented buffer. @tail must be the last fragment of @skb -- or
1421  *      @skb itself. If this would exceed the total buffer size the kernel
1422  *      will panic. A pointer to the first byte of the extra data is
1423  *      returned.
1424  */
1425
1426 unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1427 {
1428         if (tail != skb) {
1429                 skb->data_len += len;
1430                 skb->len += len;
1431         }
1432         return skb_put(tail, len);
1433 }
1434 EXPORT_SYMBOL_GPL(pskb_put);
1435
1436 /**
1437  *      skb_put - add data to a buffer
1438  *      @skb: buffer to use
1439  *      @len: amount of data to add
1440  *
1441  *      This function extends the used data area of the buffer. If this would
1442  *      exceed the total buffer size the kernel will panic. A pointer to the
1443  *      first byte of the extra data is returned.
1444  */
1445 unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
1446 {
1447         unsigned char *tmp = skb_tail_pointer(skb);
1448         SKB_LINEAR_ASSERT(skb);
1449         skb->tail += len;
1450         skb->len  += len;
1451         if (unlikely(skb->tail > skb->end))
1452                 skb_over_panic(skb, len, __builtin_return_address(0));
1453         return tmp;
1454 }
1455 EXPORT_SYMBOL(skb_put);
1456
1457 /**
1458  *      skb_push - add data to the start of a buffer
1459  *      @skb: buffer to use
1460  *      @len: amount of data to add
1461  *
1462  *      This function extends the used data area of the buffer at the buffer
1463  *      start. If this would exceed the total buffer headroom the kernel will
1464  *      panic. A pointer to the first byte of the extra data is returned.
1465  */
1466 unsigned char *skb_push(struct sk_buff *skb, unsigned int len)
1467 {
1468         skb->data -= len;
1469         skb->len  += len;
1470         if (unlikely(skb->data<skb->head))
1471                 skb_under_panic(skb, len, __builtin_return_address(0));
1472         return skb->data;
1473 }
1474 EXPORT_SYMBOL(skb_push);
1475
1476 /**
1477  *      skb_pull - remove data from the start of a buffer
1478  *      @skb: buffer to use
1479  *      @len: amount of data to remove
1480  *
1481  *      This function removes data from the start of a buffer, returning
1482  *      the memory to the headroom. A pointer to the next data in the buffer
1483  *      is returned. Once the data has been pulled future pushes will overwrite
1484  *      the old data.
1485  */
1486 unsigned char *skb_pull(struct sk_buff *skb, unsigned int len)
1487 {
1488         return skb_pull_inline(skb, len);
1489 }
1490 EXPORT_SYMBOL(skb_pull);
1491
1492 /**
1493  *      skb_trim - remove end from a buffer
1494  *      @skb: buffer to alter
1495  *      @len: new length
1496  *
1497  *      Cut the length of a buffer down by removing data from the tail. If
1498  *      the buffer is already under the length specified it is not modified.
1499  *      The skb must be linear.
1500  */
1501 void skb_trim(struct sk_buff *skb, unsigned int len)
1502 {
1503         if (skb->len > len)
1504                 __skb_trim(skb, len);
1505 }
1506 EXPORT_SYMBOL(skb_trim);
1507
1508 /* Trims skb to length len. It can change skb pointers.
1509  */
1510
1511 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
1512 {
1513         struct sk_buff **fragp;
1514         struct sk_buff *frag;
1515         int offset = skb_headlen(skb);
1516         int nfrags = skb_shinfo(skb)->nr_frags;
1517         int i;
1518         int err;
1519
1520         if (skb_cloned(skb) &&
1521             unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
1522                 return err;
1523
1524         i = 0;
1525         if (offset >= len)
1526                 goto drop_pages;
1527
1528         for (; i < nfrags; i++) {
1529                 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
1530
1531                 if (end < len) {
1532                         offset = end;
1533                         continue;
1534                 }
1535
1536                 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
1537
1538 drop_pages:
1539                 skb_shinfo(skb)->nr_frags = i;
1540
1541                 for (; i < nfrags; i++)
1542                         skb_frag_unref(skb, i);
1543
1544                 if (skb_has_frag_list(skb))
1545                         skb_drop_fraglist(skb);
1546                 goto done;
1547         }
1548
1549         for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
1550              fragp = &frag->next) {
1551                 int end = offset + frag->len;
1552
1553                 if (skb_shared(frag)) {
1554                         struct sk_buff *nfrag;
1555
1556                         nfrag = skb_clone(frag, GFP_ATOMIC);
1557                         if (unlikely(!nfrag))
1558                                 return -ENOMEM;
1559
1560                         nfrag->next = frag->next;
1561                         consume_skb(frag);
1562                         frag = nfrag;
1563                         *fragp = frag;
1564                 }
1565
1566                 if (end < len) {
1567                         offset = end;
1568                         continue;
1569                 }
1570
1571                 if (end > len &&
1572                     unlikely((err = pskb_trim(frag, len - offset))))
1573                         return err;
1574
1575                 if (frag->next)
1576                         skb_drop_list(&frag->next);
1577                 break;
1578         }
1579
1580 done:
1581         if (len > skb_headlen(skb)) {
1582                 skb->data_len -= skb->len - len;
1583                 skb->len       = len;
1584         } else {
1585                 skb->len       = len;
1586                 skb->data_len  = 0;
1587                 skb_set_tail_pointer(skb, len);
1588         }
1589
1590         return 0;
1591 }
1592 EXPORT_SYMBOL(___pskb_trim);
1593
1594 /* Note : use pskb_trim_rcsum() instead of calling this directly
1595  */
1596 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
1597 {
1598         if (skb->ip_summed == CHECKSUM_COMPLETE) {
1599                 int delta = skb->len - len;
1600
1601                 skb->csum = csum_block_sub(skb->csum,
1602                                            skb_checksum(skb, len, delta, 0),
1603                                            len);
1604         } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
1605                 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
1606                 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
1607
1608                 if (offset + sizeof(__sum16) > hdlen)
1609                         return -EINVAL;
1610         }
1611         return __pskb_trim(skb, len);
1612 }
1613 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
1614
1615 /**
1616  *      __pskb_pull_tail - advance tail of skb header
1617  *      @skb: buffer to reallocate
1618  *      @delta: number of bytes to advance tail
1619  *
1620  *      The function makes a sense only on a fragmented &sk_buff,
1621  *      it expands header moving its tail forward and copying necessary
1622  *      data from fragmented part.
1623  *
1624  *      &sk_buff MUST have reference count of 1.
1625  *
1626  *      Returns %NULL (and &sk_buff does not change) if pull failed
1627  *      or value of new tail of skb in the case of success.
1628  *
1629  *      All the pointers pointing into skb header may change and must be
1630  *      reloaded after call to this function.
1631  */
1632
1633 /* Moves tail of skb head forward, copying data from fragmented part,
1634  * when it is necessary.
1635  * 1. It may fail due to malloc failure.
1636  * 2. It may change skb pointers.
1637  *
1638  * It is pretty complicated. Luckily, it is called only in exceptional cases.
1639  */
1640 unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta)
1641 {
1642         /* If skb has not enough free space at tail, get new one
1643          * plus 128 bytes for future expansions. If we have enough
1644          * room at tail, reallocate without expansion only if skb is cloned.
1645          */
1646         int i, k, eat = (skb->tail + delta) - skb->end;
1647
1648         if (eat > 0 || skb_cloned(skb)) {
1649                 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
1650                                      GFP_ATOMIC))
1651                         return NULL;
1652         }
1653
1654         if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta))
1655                 BUG();
1656
1657         /* Optimization: no fragments, no reasons to preestimate
1658          * size of pulled pages. Superb.
1659          */
1660         if (!skb_has_frag_list(skb))
1661                 goto pull_pages;
1662
1663         /* Estimate size of pulled pages. */
1664         eat = delta;
1665         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1666                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1667
1668                 if (size >= eat)
1669                         goto pull_pages;
1670                 eat -= size;
1671         }
1672
1673         /* If we need update frag list, we are in troubles.
1674          * Certainly, it possible to add an offset to skb data,
1675          * but taking into account that pulling is expected to
1676          * be very rare operation, it is worth to fight against
1677          * further bloating skb head and crucify ourselves here instead.
1678          * Pure masohism, indeed. 8)8)
1679          */
1680         if (eat) {
1681                 struct sk_buff *list = skb_shinfo(skb)->frag_list;
1682                 struct sk_buff *clone = NULL;
1683                 struct sk_buff *insp = NULL;
1684
1685                 do {
1686                         BUG_ON(!list);
1687
1688                         if (list->len <= eat) {
1689                                 /* Eaten as whole. */
1690                                 eat -= list->len;
1691                                 list = list->next;
1692                                 insp = list;
1693                         } else {
1694                                 /* Eaten partially. */
1695
1696                                 if (skb_shared(list)) {
1697                                         /* Sucks! We need to fork list. :-( */
1698                                         clone = skb_clone(list, GFP_ATOMIC);
1699                                         if (!clone)
1700                                                 return NULL;
1701                                         insp = list->next;
1702                                         list = clone;
1703                                 } else {
1704                                         /* This may be pulled without
1705                                          * problems. */
1706                                         insp = list;
1707                                 }
1708                                 if (!pskb_pull(list, eat)) {
1709                                         kfree_skb(clone);
1710                                         return NULL;
1711                                 }
1712                                 break;
1713                         }
1714                 } while (eat);
1715
1716                 /* Free pulled out fragments. */
1717                 while ((list = skb_shinfo(skb)->frag_list) != insp) {
1718                         skb_shinfo(skb)->frag_list = list->next;
1719                         kfree_skb(list);
1720                 }
1721                 /* And insert new clone at head. */
1722                 if (clone) {
1723                         clone->next = list;
1724                         skb_shinfo(skb)->frag_list = clone;
1725                 }
1726         }
1727         /* Success! Now we may commit changes to skb data. */
1728
1729 pull_pages:
1730         eat = delta;
1731         k = 0;
1732         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1733                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1734
1735                 if (size <= eat) {
1736                         skb_frag_unref(skb, i);
1737                         eat -= size;
1738                 } else {
1739                         skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
1740                         if (eat) {
1741                                 skb_shinfo(skb)->frags[k].page_offset += eat;
1742                                 skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
1743                                 eat = 0;
1744                         }
1745                         k++;
1746                 }
1747         }
1748         skb_shinfo(skb)->nr_frags = k;
1749
1750         skb->tail     += delta;
1751         skb->data_len -= delta;
1752
1753         return skb_tail_pointer(skb);
1754 }
1755 EXPORT_SYMBOL(__pskb_pull_tail);
1756
1757 /**
1758  *      skb_copy_bits - copy bits from skb to kernel buffer
1759  *      @skb: source skb
1760  *      @offset: offset in source
1761  *      @to: destination buffer
1762  *      @len: number of bytes to copy
1763  *
1764  *      Copy the specified number of bytes from the source skb to the
1765  *      destination buffer.
1766  *
1767  *      CAUTION ! :
1768  *              If its prototype is ever changed,
1769  *              check arch/{*}/net/{*}.S files,
1770  *              since it is called from BPF assembly code.
1771  */
1772 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
1773 {
1774         int start = skb_headlen(skb);
1775         struct sk_buff *frag_iter;
1776         int i, copy;
1777
1778         if (offset > (int)skb->len - len)
1779                 goto fault;
1780
1781         /* Copy header. */
1782         if ((copy = start - offset) > 0) {
1783                 if (copy > len)
1784                         copy = len;
1785                 skb_copy_from_linear_data_offset(skb, offset, to, copy);
1786                 if ((len -= copy) == 0)
1787                         return 0;
1788                 offset += copy;
1789                 to     += copy;
1790         }
1791
1792         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1793                 int end;
1794                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1795
1796                 WARN_ON(start > offset + len);
1797
1798                 end = start + skb_frag_size(f);
1799                 if ((copy = end - offset) > 0) {
1800                         u8 *vaddr;
1801
1802                         if (copy > len)
1803                                 copy = len;
1804
1805                         vaddr = kmap_atomic(skb_frag_page(f));
1806                         memcpy(to,
1807                                vaddr + f->page_offset + offset - start,
1808                                copy);
1809                         kunmap_atomic(vaddr);
1810
1811                         if ((len -= copy) == 0)
1812                                 return 0;
1813                         offset += copy;
1814                         to     += copy;
1815                 }
1816                 start = end;
1817         }
1818
1819         skb_walk_frags(skb, frag_iter) {
1820                 int end;
1821
1822                 WARN_ON(start > offset + len);
1823
1824                 end = start + frag_iter->len;
1825                 if ((copy = end - offset) > 0) {
1826                         if (copy > len)
1827                                 copy = len;
1828                         if (skb_copy_bits(frag_iter, offset - start, to, copy))
1829                                 goto fault;
1830                         if ((len -= copy) == 0)
1831                                 return 0;
1832                         offset += copy;
1833                         to     += copy;
1834                 }
1835                 start = end;
1836         }
1837
1838         if (!len)
1839                 return 0;
1840
1841 fault:
1842         return -EFAULT;
1843 }
1844 EXPORT_SYMBOL(skb_copy_bits);
1845
1846 /*
1847  * Callback from splice_to_pipe(), if we need to release some pages
1848  * at the end of the spd in case we error'ed out in filling the pipe.
1849  */
1850 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
1851 {
1852         put_page(spd->pages[i]);
1853 }
1854
1855 static struct page *linear_to_page(struct page *page, unsigned int *len,
1856                                    unsigned int *offset,
1857                                    struct sock *sk)
1858 {
1859         struct page_frag *pfrag = sk_page_frag(sk);
1860
1861         if (!sk_page_frag_refill(sk, pfrag))
1862                 return NULL;
1863
1864         *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
1865
1866         memcpy(page_address(pfrag->page) + pfrag->offset,
1867                page_address(page) + *offset, *len);
1868         *offset = pfrag->offset;
1869         pfrag->offset += *len;
1870
1871         return pfrag->page;
1872 }
1873
1874 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
1875                              struct page *page,
1876                              unsigned int offset)
1877 {
1878         return  spd->nr_pages &&
1879                 spd->pages[spd->nr_pages - 1] == page &&
1880                 (spd->partial[spd->nr_pages - 1].offset +
1881                  spd->partial[spd->nr_pages - 1].len == offset);
1882 }
1883
1884 /*
1885  * Fill page/offset/length into spd, if it can hold more pages.
1886  */
1887 static bool spd_fill_page(struct splice_pipe_desc *spd,
1888                           struct pipe_inode_info *pipe, struct page *page,
1889                           unsigned int *len, unsigned int offset,
1890                           bool linear,
1891                           struct sock *sk)
1892 {
1893         if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
1894                 return true;
1895
1896         if (linear) {
1897                 page = linear_to_page(page, len, &offset, sk);
1898                 if (!page)
1899                         return true;
1900         }
1901         if (spd_can_coalesce(spd, page, offset)) {
1902                 spd->partial[spd->nr_pages - 1].len += *len;
1903                 return false;
1904         }
1905         get_page(page);
1906         spd->pages[spd->nr_pages] = page;
1907         spd->partial[spd->nr_pages].len = *len;
1908         spd->partial[spd->nr_pages].offset = offset;
1909         spd->nr_pages++;
1910
1911         return false;
1912 }
1913
1914 static bool __splice_segment(struct page *page, unsigned int poff,
1915                              unsigned int plen, unsigned int *off,
1916                              unsigned int *len,
1917                              struct splice_pipe_desc *spd, bool linear,
1918                              struct sock *sk,
1919                              struct pipe_inode_info *pipe)
1920 {
1921         if (!*len)
1922                 return true;
1923
1924         /* skip this segment if already processed */
1925         if (*off >= plen) {
1926                 *off -= plen;
1927                 return false;
1928         }
1929
1930         /* ignore any bits we already processed */
1931         poff += *off;
1932         plen -= *off;
1933         *off = 0;
1934
1935         do {
1936                 unsigned int flen = min(*len, plen);
1937
1938                 if (spd_fill_page(spd, pipe, page, &flen, poff,
1939                                   linear, sk))
1940                         return true;
1941                 poff += flen;
1942                 plen -= flen;
1943                 *len -= flen;
1944         } while (*len && plen);
1945
1946         return false;
1947 }
1948
1949 /*
1950  * Map linear and fragment data from the skb to spd. It reports true if the
1951  * pipe is full or if we already spliced the requested length.
1952  */
1953 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
1954                               unsigned int *offset, unsigned int *len,
1955                               struct splice_pipe_desc *spd, struct sock *sk)
1956 {
1957         int seg;
1958         struct sk_buff *iter;
1959
1960         /* map the linear part :
1961          * If skb->head_frag is set, this 'linear' part is backed by a
1962          * fragment, and if the head is not shared with any clones then
1963          * we can avoid a copy since we own the head portion of this page.
1964          */
1965         if (__splice_segment(virt_to_page(skb->data),
1966                              (unsigned long) skb->data & (PAGE_SIZE - 1),
1967                              skb_headlen(skb),
1968                              offset, len, spd,
1969                              skb_head_is_locked(skb),
1970                              sk, pipe))
1971                 return true;
1972
1973         /*
1974          * then map the fragments
1975          */
1976         for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
1977                 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
1978
1979                 if (__splice_segment(skb_frag_page(f),
1980                                      f->page_offset, skb_frag_size(f),
1981                                      offset, len, spd, false, sk, pipe))
1982                         return true;
1983         }
1984
1985         skb_walk_frags(skb, iter) {
1986                 if (*offset >= iter->len) {
1987                         *offset -= iter->len;
1988                         continue;
1989                 }
1990                 /* __skb_splice_bits() only fails if the output has no room
1991                  * left, so no point in going over the frag_list for the error
1992                  * case.
1993                  */
1994                 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
1995                         return true;
1996         }
1997
1998         return false;
1999 }
2000
2001 /*
2002  * Map data from the skb to a pipe. Should handle both the linear part,
2003  * the fragments, and the frag list.
2004  */
2005 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2006                     struct pipe_inode_info *pipe, unsigned int tlen,
2007                     unsigned int flags)
2008 {
2009         struct partial_page partial[MAX_SKB_FRAGS];
2010         struct page *pages[MAX_SKB_FRAGS];
2011         struct splice_pipe_desc spd = {
2012                 .pages = pages,
2013                 .partial = partial,
2014                 .nr_pages_max = MAX_SKB_FRAGS,
2015                 .flags = flags,
2016                 .ops = &nosteal_pipe_buf_ops,
2017                 .spd_release = sock_spd_release,
2018         };
2019         int ret = 0;
2020
2021         __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2022
2023         if (spd.nr_pages)
2024                 ret = splice_to_pipe(pipe, &spd);
2025
2026         return ret;
2027 }
2028 EXPORT_SYMBOL_GPL(skb_splice_bits);
2029
2030 /**
2031  *      skb_store_bits - store bits from kernel buffer to skb
2032  *      @skb: destination buffer
2033  *      @offset: offset in destination
2034  *      @from: source buffer
2035  *      @len: number of bytes to copy
2036  *
2037  *      Copy the specified number of bytes from the source buffer to the
2038  *      destination skb.  This function handles all the messy bits of
2039  *      traversing fragment lists and such.
2040  */
2041
2042 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2043 {
2044         int start = skb_headlen(skb);
2045         struct sk_buff *frag_iter;
2046         int i, copy;
2047
2048         if (offset > (int)skb->len - len)
2049                 goto fault;
2050
2051         if ((copy = start - offset) > 0) {
2052                 if (copy > len)
2053                         copy = len;
2054                 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2055                 if ((len -= copy) == 0)
2056                         return 0;
2057                 offset += copy;
2058                 from += copy;
2059         }
2060
2061         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2062                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2063                 int end;
2064
2065                 WARN_ON(start > offset + len);
2066
2067                 end = start + skb_frag_size(frag);
2068                 if ((copy = end - offset) > 0) {
2069                         u8 *vaddr;
2070
2071                         if (copy > len)
2072                                 copy = len;
2073
2074                         vaddr = kmap_atomic(skb_frag_page(frag));
2075                         memcpy(vaddr + frag->page_offset + offset - start,
2076                                from, copy);
2077                         kunmap_atomic(vaddr);
2078
2079                         if ((len -= copy) == 0)
2080                                 return 0;
2081                         offset += copy;
2082                         from += copy;
2083                 }
2084                 start = end;
2085         }
2086
2087         skb_walk_frags(skb, frag_iter) {
2088                 int end;
2089
2090                 WARN_ON(start > offset + len);
2091
2092                 end = start + frag_iter->len;
2093                 if ((copy = end - offset) > 0) {
2094                         if (copy > len)
2095                                 copy = len;
2096                         if (skb_store_bits(frag_iter, offset - start,
2097                                            from, copy))
2098                                 goto fault;
2099                         if ((len -= copy) == 0)
2100                                 return 0;
2101                         offset += copy;
2102                         from += copy;
2103                 }
2104                 start = end;
2105         }
2106         if (!len)
2107                 return 0;
2108
2109 fault:
2110         return -EFAULT;
2111 }
2112 EXPORT_SYMBOL(skb_store_bits);
2113
2114 /* Checksum skb data. */
2115 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2116                       __wsum csum, const struct skb_checksum_ops *ops)
2117 {
2118         int start = skb_headlen(skb);
2119         int i, copy = start - offset;
2120         struct sk_buff *frag_iter;
2121         int pos = 0;
2122
2123         /* Checksum header. */
2124         if (copy > 0) {
2125                 if (copy > len)
2126                         copy = len;
2127                 csum = ops->update(skb->data + offset, copy, csum);
2128                 if ((len -= copy) == 0)
2129                         return csum;
2130                 offset += copy;
2131                 pos     = copy;
2132         }
2133
2134         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2135                 int end;
2136                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2137
2138                 WARN_ON(start > offset + len);
2139
2140                 end = start + skb_frag_size(frag);
2141                 if ((copy = end - offset) > 0) {
2142                         __wsum csum2;
2143                         u8 *vaddr;
2144
2145                         if (copy > len)
2146                                 copy = len;
2147                         vaddr = kmap_atomic(skb_frag_page(frag));
2148                         csum2 = ops->update(vaddr + frag->page_offset +
2149                                             offset - start, copy, 0);
2150                         kunmap_atomic(vaddr);
2151                         csum = ops->combine(csum, csum2, pos, copy);
2152                         if (!(len -= copy))
2153                                 return csum;
2154                         offset += copy;
2155                         pos    += copy;
2156                 }
2157                 start = end;
2158         }
2159
2160         skb_walk_frags(skb, frag_iter) {
2161                 int end;
2162
2163                 WARN_ON(start > offset + len);
2164
2165                 end = start + frag_iter->len;
2166                 if ((copy = end - offset) > 0) {
2167                         __wsum csum2;
2168                         if (copy > len)
2169                                 copy = len;
2170                         csum2 = __skb_checksum(frag_iter, offset - start,
2171                                                copy, 0, ops);
2172                         csum = ops->combine(csum, csum2, pos, copy);
2173                         if ((len -= copy) == 0)
2174                                 return csum;
2175                         offset += copy;
2176                         pos    += copy;
2177                 }
2178                 start = end;
2179         }
2180         BUG_ON(len);
2181
2182         return csum;
2183 }
2184 EXPORT_SYMBOL(__skb_checksum);
2185
2186 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2187                     int len, __wsum csum)
2188 {
2189         const struct skb_checksum_ops ops = {
2190                 .update  = csum_partial_ext,
2191                 .combine = csum_block_add_ext,
2192         };
2193
2194         return __skb_checksum(skb, offset, len, csum, &ops);
2195 }
2196 EXPORT_SYMBOL(skb_checksum);
2197
2198 /* Both of above in one bottle. */
2199
2200 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2201                                     u8 *to, int len, __wsum csum)
2202 {
2203         int start = skb_headlen(skb);
2204         int i, copy = start - offset;
2205         struct sk_buff *frag_iter;
2206         int pos = 0;
2207
2208         /* Copy header. */
2209         if (copy > 0) {
2210                 if (copy > len)
2211                         copy = len;
2212                 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2213                                                  copy, csum);
2214                 if ((len -= copy) == 0)
2215                         return csum;
2216                 offset += copy;
2217                 to     += copy;
2218                 pos     = copy;
2219         }
2220
2221         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2222                 int end;
2223
2224                 WARN_ON(start > offset + len);
2225
2226                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2227                 if ((copy = end - offset) > 0) {
2228                         __wsum csum2;
2229                         u8 *vaddr;
2230                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2231
2232                         if (copy > len)
2233                                 copy = len;
2234                         vaddr = kmap_atomic(skb_frag_page(frag));
2235                         csum2 = csum_partial_copy_nocheck(vaddr +
2236                                                           frag->page_offset +
2237                                                           offset - start, to,
2238                                                           copy, 0);
2239                         kunmap_atomic(vaddr);
2240                         csum = csum_block_add(csum, csum2, pos);
2241                         if (!(len -= copy))
2242                                 return csum;
2243                         offset += copy;
2244                         to     += copy;
2245                         pos    += copy;
2246                 }
2247                 start = end;
2248         }
2249
2250         skb_walk_frags(skb, frag_iter) {
2251                 __wsum csum2;
2252                 int end;
2253
2254                 WARN_ON(start > offset + len);
2255
2256                 end = start + frag_iter->len;
2257                 if ((copy = end - offset) > 0) {
2258                         if (copy > len)
2259                                 copy = len;
2260                         csum2 = skb_copy_and_csum_bits(frag_iter,
2261                                                        offset - start,
2262                                                        to, copy, 0);
2263                         csum = csum_block_add(csum, csum2, pos);
2264                         if ((len -= copy) == 0)
2265                                 return csum;
2266                         offset += copy;
2267                         to     += copy;
2268                         pos    += copy;
2269                 }
2270                 start = end;
2271         }
2272         BUG_ON(len);
2273         return csum;
2274 }
2275 EXPORT_SYMBOL(skb_copy_and_csum_bits);
2276
2277  /**
2278  *      skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
2279  *      @from: source buffer
2280  *
2281  *      Calculates the amount of linear headroom needed in the 'to' skb passed
2282  *      into skb_zerocopy().
2283  */
2284 unsigned int
2285 skb_zerocopy_headlen(const struct sk_buff *from)
2286 {
2287         unsigned int hlen = 0;
2288
2289         if (!from->head_frag ||
2290             skb_headlen(from) < L1_CACHE_BYTES ||
2291             skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
2292                 hlen = skb_headlen(from);
2293                 if (!hlen)
2294                         hlen = from->len;
2295         }
2296
2297         if (skb_has_frag_list(from))
2298                 hlen = from->len;
2299
2300         return hlen;
2301 }
2302 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
2303
2304 /**
2305  *      skb_zerocopy - Zero copy skb to skb
2306  *      @to: destination buffer
2307  *      @from: source buffer
2308  *      @len: number of bytes to copy from source buffer
2309  *      @hlen: size of linear headroom in destination buffer
2310  *
2311  *      Copies up to `len` bytes from `from` to `to` by creating references
2312  *      to the frags in the source buffer.
2313  *
2314  *      The `hlen` as calculated by skb_zerocopy_headlen() specifies the
2315  *      headroom in the `to` buffer.
2316  *
2317  *      Return value:
2318  *      0: everything is OK
2319  *      -ENOMEM: couldn't orphan frags of @from due to lack of memory
2320  *      -EFAULT: skb_copy_bits() found some problem with skb geometry
2321  */
2322 int
2323 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
2324 {
2325         int i, j = 0;
2326         int plen = 0; /* length of skb->head fragment */
2327         int ret;
2328         struct page *page;
2329         unsigned int offset;
2330
2331         BUG_ON(!from->head_frag && !hlen);
2332
2333         /* dont bother with small payloads */
2334         if (len <= skb_tailroom(to))
2335                 return skb_copy_bits(from, 0, skb_put(to, len), len);
2336
2337         if (hlen) {
2338                 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
2339                 if (unlikely(ret))
2340                         return ret;
2341                 len -= hlen;
2342         } else {
2343                 plen = min_t(int, skb_headlen(from), len);
2344                 if (plen) {
2345                         page = virt_to_head_page(from->head);
2346                         offset = from->data - (unsigned char *)page_address(page);
2347                         __skb_fill_page_desc(to, 0, page, offset, plen);
2348                         get_page(page);
2349                         j = 1;
2350                         len -= plen;
2351                 }
2352         }
2353
2354         to->truesize += len + plen;
2355         to->len += len + plen;
2356         to->data_len += len + plen;
2357
2358         if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
2359                 skb_tx_error(from);
2360                 return -ENOMEM;
2361         }
2362
2363         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
2364                 if (!len)
2365                         break;
2366                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
2367                 skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
2368                 len -= skb_shinfo(to)->frags[j].size;
2369                 skb_frag_ref(to, j);
2370                 j++;
2371         }
2372         skb_shinfo(to)->nr_frags = j;
2373
2374         return 0;
2375 }
2376 EXPORT_SYMBOL_GPL(skb_zerocopy);
2377
2378 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
2379 {
2380         __wsum csum;
2381         long csstart;
2382
2383         if (skb->ip_summed == CHECKSUM_PARTIAL)
2384                 csstart = skb_checksum_start_offset(skb);
2385         else
2386                 csstart = skb_headlen(skb);
2387
2388         BUG_ON(csstart > skb_headlen(skb));
2389
2390         skb_copy_from_linear_data(skb, to, csstart);
2391
2392         csum = 0;
2393         if (csstart != skb->len)
2394                 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
2395                                               skb->len - csstart, 0);
2396
2397         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2398                 long csstuff = csstart + skb->csum_offset;
2399
2400                 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
2401         }
2402 }
2403 EXPORT_SYMBOL(skb_copy_and_csum_dev);
2404
2405 /**
2406  *      skb_dequeue - remove from the head of the queue
2407  *      @list: list to dequeue from
2408  *
2409  *      Remove the head of the list. The list lock is taken so the function
2410  *      may be used safely with other locking list functions. The head item is
2411  *      returned or %NULL if the list is empty.
2412  */
2413
2414 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
2415 {
2416         unsigned long flags;
2417         struct sk_buff *result;
2418
2419         spin_lock_irqsave(&list->lock, flags);
2420         result = __skb_dequeue(list);
2421         spin_unlock_irqrestore(&list->lock, flags);
2422         return result;
2423 }
2424 EXPORT_SYMBOL(skb_dequeue);
2425
2426 /**
2427  *      skb_dequeue_tail - remove from the tail of the queue
2428  *      @list: list to dequeue from
2429  *
2430  *      Remove the tail of the list. The list lock is taken so the function
2431  *      may be used safely with other locking list functions. The tail item is
2432  *      returned or %NULL if the list is empty.
2433  */
2434 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
2435 {
2436         unsigned long flags;
2437         struct sk_buff *result;
2438
2439         spin_lock_irqsave(&list->lock, flags);
2440         result = __skb_dequeue_tail(list);
2441         spin_unlock_irqrestore(&list->lock, flags);
2442         return result;
2443 }
2444 EXPORT_SYMBOL(skb_dequeue_tail);
2445
2446 /**
2447  *      skb_queue_purge - empty a list
2448  *      @list: list to empty
2449  *
2450  *      Delete all buffers on an &sk_buff list. Each buffer is removed from
2451  *      the list and one reference dropped. This function takes the list
2452  *      lock and is atomic with respect to other list locking functions.
2453  */
2454 void skb_queue_purge(struct sk_buff_head *list)
2455 {
2456         struct sk_buff *skb;
2457         while ((skb = skb_dequeue(list)) != NULL)
2458                 kfree_skb(skb);
2459 }
2460 EXPORT_SYMBOL(skb_queue_purge);
2461
2462 /**
2463  *      skb_rbtree_purge - empty a skb rbtree
2464  *      @root: root of the rbtree to empty
2465  *      Return value: the sum of truesizes of all purged skbs.
2466  *
2467  *      Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
2468  *      the list and one reference dropped. This function does not take
2469  *      any lock. Synchronization should be handled by the caller (e.g., TCP
2470  *      out-of-order queue is protected by the socket lock).
2471  */
2472 unsigned int skb_rbtree_purge(struct rb_root *root)
2473 {
2474         struct rb_node *p = rb_first(root);
2475         unsigned int sum = 0;
2476
2477         while (p) {
2478                 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
2479
2480                 p = rb_next(p);
2481                 rb_erase(&skb->rbnode, root);
2482                 sum += skb->truesize;
2483                 kfree_skb(skb);
2484         }
2485         return sum;
2486 }
2487
2488 /**
2489  *      skb_queue_head - queue a buffer at the list head
2490  *      @list: list to use
2491  *      @newsk: buffer to queue
2492  *
2493  *      Queue a buffer at the start of the list. This function takes the
2494  *      list lock and can be used safely with other locking &sk_buff functions
2495  *      safely.
2496  *
2497  *      A buffer cannot be placed on two lists at the same time.
2498  */
2499 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
2500 {
2501         unsigned long flags;
2502
2503         spin_lock_irqsave(&list->lock, flags);
2504         __skb_queue_head(list, newsk);
2505         spin_unlock_irqrestore(&list->lock, flags);
2506 }
2507 EXPORT_SYMBOL(skb_queue_head);
2508
2509 /**
2510  *      skb_queue_tail - queue a buffer at the list tail
2511  *      @list: list to use
2512  *      @newsk: buffer to queue
2513  *
2514  *      Queue a buffer at the tail of the list. This function takes the
2515  *      list lock and can be used safely with other locking &sk_buff functions
2516  *      safely.
2517  *
2518  *      A buffer cannot be placed on two lists at the same time.
2519  */
2520 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
2521 {
2522         unsigned long flags;
2523
2524         spin_lock_irqsave(&list->lock, flags);
2525         __skb_queue_tail(list, newsk);
2526         spin_unlock_irqrestore(&list->lock, flags);
2527 }
2528 EXPORT_SYMBOL(skb_queue_tail);
2529
2530 /**
2531  *      skb_unlink      -       remove a buffer from a list
2532  *      @skb: buffer to remove
2533  *      @list: list to use
2534  *
2535  *      Remove a packet from a list. The list locks are taken and this
2536  *      function is atomic with respect to other list locked calls
2537  *
2538  *      You must know what list the SKB is on.
2539  */
2540 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
2541 {
2542         unsigned long flags;
2543
2544         spin_lock_irqsave(&list->lock, flags);
2545         __skb_unlink(skb, list);
2546         spin_unlock_irqrestore(&list->lock, flags);
2547 }
2548 EXPORT_SYMBOL(skb_unlink);
2549
2550 /**
2551  *      skb_append      -       append a buffer
2552  *      @old: buffer to insert after
2553  *      @newsk: buffer to insert
2554  *      @list: list to use
2555  *
2556  *      Place a packet after a given packet in a list. The list locks are taken
2557  *      and this function is atomic with respect to other list locked calls.
2558  *      A buffer cannot be placed on two lists at the same time.
2559  */
2560 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2561 {
2562         unsigned long flags;
2563
2564         spin_lock_irqsave(&list->lock, flags);
2565         __skb_queue_after(list, old, newsk);
2566         spin_unlock_irqrestore(&list->lock, flags);
2567 }
2568 EXPORT_SYMBOL(skb_append);
2569
2570 /**
2571  *      skb_insert      -       insert a buffer
2572  *      @old: buffer to insert before
2573  *      @newsk: buffer to insert
2574  *      @list: list to use
2575  *
2576  *      Place a packet before a given packet in a list. The list locks are
2577  *      taken and this function is atomic with respect to other list locked
2578  *      calls.
2579  *
2580  *      A buffer cannot be placed on two lists at the same time.
2581  */
2582 void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2583 {
2584         unsigned long flags;
2585
2586         spin_lock_irqsave(&list->lock, flags);
2587         __skb_insert(newsk, old->prev, old, list);
2588         spin_unlock_irqrestore(&list->lock, flags);
2589 }
2590 EXPORT_SYMBOL(skb_insert);
2591
2592 static inline void skb_split_inside_header(struct sk_buff *skb,
2593                                            struct sk_buff* skb1,
2594                                            const u32 len, const int pos)
2595 {
2596         int i;
2597
2598         skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
2599                                          pos - len);
2600         /* And move data appendix as is. */
2601         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2602                 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
2603
2604         skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
2605         skb_shinfo(skb)->nr_frags  = 0;
2606         skb1->data_len             = skb->data_len;
2607         skb1->len                  += skb1->data_len;
2608         skb->data_len              = 0;
2609         skb->len                   = len;
2610         skb_set_tail_pointer(skb, len);
2611 }
2612
2613 static inline void skb_split_no_header(struct sk_buff *skb,
2614                                        struct sk_buff* skb1,
2615                                        const u32 len, int pos)
2616 {
2617         int i, k = 0;
2618         const int nfrags = skb_shinfo(skb)->nr_frags;
2619
2620         skb_shinfo(skb)->nr_frags = 0;
2621         skb1->len                 = skb1->data_len = skb->len - len;
2622         skb->len                  = len;
2623         skb->data_len             = len - pos;
2624
2625         for (i = 0; i < nfrags; i++) {
2626                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2627
2628                 if (pos + size > len) {
2629                         skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
2630
2631                         if (pos < len) {
2632                                 /* Split frag.
2633                                  * We have two variants in this case:
2634                                  * 1. Move all the frag to the second
2635                                  *    part, if it is possible. F.e.
2636                                  *    this approach is mandatory for TUX,
2637                                  *    where splitting is expensive.
2638                                  * 2. Split is accurately. We make this.
2639                                  */
2640                                 skb_frag_ref(skb, i);
2641                                 skb_shinfo(skb1)->frags[0].page_offset += len - pos;
2642                                 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
2643                                 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
2644                                 skb_shinfo(skb)->nr_frags++;
2645                         }
2646                         k++;
2647                 } else
2648                         skb_shinfo(skb)->nr_frags++;
2649                 pos += size;
2650         }
2651         skb_shinfo(skb1)->nr_frags = k;
2652 }
2653
2654 /**
2655  * skb_split - Split fragmented skb to two parts at length len.
2656  * @skb: the buffer to split
2657  * @skb1: the buffer to receive the second part
2658  * @len: new length for skb
2659  */
2660 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
2661 {
2662         int pos = skb_headlen(skb);
2663
2664         skb_shinfo(skb1)->tx_flags |= skb_shinfo(skb)->tx_flags &
2665                                       SKBTX_SHARED_FRAG;
2666         if (len < pos)  /* Split line is inside header. */
2667                 skb_split_inside_header(skb, skb1, len, pos);
2668         else            /* Second chunk has no header, nothing to copy. */
2669                 skb_split_no_header(skb, skb1, len, pos);
2670 }
2671 EXPORT_SYMBOL(skb_split);
2672
2673 /* Shifting from/to a cloned skb is a no-go.
2674  *
2675  * Caller cannot keep skb_shinfo related pointers past calling here!
2676  */
2677 static int skb_prepare_for_shift(struct sk_buff *skb)
2678 {
2679         int ret = 0;
2680
2681         if (skb_cloned(skb)) {
2682                 /* Save and restore truesize: pskb_expand_head() may reallocate
2683                  * memory where ksize(kmalloc(S)) != ksize(kmalloc(S)), but we
2684                  * cannot change truesize at this point.
2685                  */
2686                 unsigned int save_truesize = skb->truesize;
2687
2688                 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2689                 skb->truesize = save_truesize;
2690         }
2691         return ret;
2692 }
2693
2694 /**
2695  * skb_shift - Shifts paged data partially from skb to another
2696  * @tgt: buffer into which tail data gets added
2697  * @skb: buffer from which the paged data comes from
2698  * @shiftlen: shift up to this many bytes
2699  *
2700  * Attempts to shift up to shiftlen worth of bytes, which may be less than
2701  * the length of the skb, from skb to tgt. Returns number bytes shifted.
2702  * It's up to caller to free skb if everything was shifted.
2703  *
2704  * If @tgt runs out of frags, the whole operation is aborted.
2705  *
2706  * Skb cannot include anything else but paged data while tgt is allowed
2707  * to have non-paged data as well.
2708  *
2709  * TODO: full sized shift could be optimized but that would need
2710  * specialized skb free'er to handle frags without up-to-date nr_frags.
2711  */
2712 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
2713 {
2714         int from, to, merge, todo;
2715         struct skb_frag_struct *fragfrom, *fragto;
2716
2717         BUG_ON(shiftlen > skb->len);
2718         BUG_ON(skb_headlen(skb));       /* Would corrupt stream */
2719
2720         todo = shiftlen;
2721         from = 0;
2722         to = skb_shinfo(tgt)->nr_frags;
2723         fragfrom = &skb_shinfo(skb)->frags[from];
2724
2725         /* Actual merge is delayed until the point when we know we can
2726          * commit all, so that we don't have to undo partial changes
2727          */
2728         if (!to ||
2729             !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
2730                               fragfrom->page_offset)) {
2731                 merge = -1;
2732         } else {
2733                 merge = to - 1;
2734
2735                 todo -= skb_frag_size(fragfrom);
2736                 if (todo < 0) {
2737                         if (skb_prepare_for_shift(skb) ||
2738                             skb_prepare_for_shift(tgt))
2739                                 return 0;
2740
2741                         /* All previous frag pointers might be stale! */
2742                         fragfrom = &skb_shinfo(skb)->frags[from];
2743                         fragto = &skb_shinfo(tgt)->frags[merge];
2744
2745                         skb_frag_size_add(fragto, shiftlen);
2746                         skb_frag_size_sub(fragfrom, shiftlen);
2747                         fragfrom->page_offset += shiftlen;
2748
2749                         goto onlymerged;
2750                 }
2751
2752                 from++;
2753         }
2754
2755         /* Skip full, not-fitting skb to avoid expensive operations */
2756         if ((shiftlen == skb->len) &&
2757             (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
2758                 return 0;
2759
2760         if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
2761                 return 0;
2762
2763         while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
2764                 if (to == MAX_SKB_FRAGS)
2765                         return 0;
2766
2767                 fragfrom = &skb_shinfo(skb)->frags[from];
2768                 fragto = &skb_shinfo(tgt)->frags[to];
2769
2770                 if (todo >= skb_frag_size(fragfrom)) {
2771                         *fragto = *fragfrom;
2772                         todo -= skb_frag_size(fragfrom);
2773                         from++;
2774                         to++;
2775
2776                 } else {
2777                         __skb_frag_ref(fragfrom);
2778                         fragto->page = fragfrom->page;
2779                         fragto->page_offset = fragfrom->page_offset;
2780                         skb_frag_size_set(fragto, todo);
2781
2782                         fragfrom->page_offset += todo;
2783                         skb_frag_size_sub(fragfrom, todo);
2784                         todo = 0;
2785
2786                         to++;
2787                         break;
2788                 }
2789         }
2790
2791         /* Ready to "commit" this state change to tgt */
2792         skb_shinfo(tgt)->nr_frags = to;
2793
2794         if (merge >= 0) {
2795                 fragfrom = &skb_shinfo(skb)->frags[0];
2796                 fragto = &skb_shinfo(tgt)->frags[merge];
2797
2798                 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
2799                 __skb_frag_unref(fragfrom);
2800         }
2801
2802         /* Reposition in the original skb */
2803         to = 0;
2804         while (from < skb_shinfo(skb)->nr_frags)
2805                 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
2806         skb_shinfo(skb)->nr_frags = to;
2807
2808         BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
2809
2810 onlymerged:
2811         /* Most likely the tgt won't ever need its checksum anymore, skb on
2812          * the other hand might need it if it needs to be resent
2813          */
2814         tgt->ip_summed = CHECKSUM_PARTIAL;
2815         skb->ip_summed = CHECKSUM_PARTIAL;
2816
2817         /* Yak, is it really working this way? Some helper please? */
2818         skb->len -= shiftlen;
2819         skb->data_len -= shiftlen;
2820         skb->truesize -= shiftlen;
2821         tgt->len += shiftlen;
2822         tgt->data_len += shiftlen;
2823         tgt->truesize += shiftlen;
2824
2825         return shiftlen;
2826 }
2827
2828 /**
2829  * skb_prepare_seq_read - Prepare a sequential read of skb data
2830  * @skb: the buffer to read
2831  * @from: lower offset of data to be read
2832  * @to: upper offset of data to be read
2833  * @st: state variable
2834  *
2835  * Initializes the specified state variable. Must be called before
2836  * invoking skb_seq_read() for the first time.
2837  */
2838 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
2839                           unsigned int to, struct skb_seq_state *st)
2840 {
2841         st->lower_offset = from;
2842         st->upper_offset = to;
2843         st->root_skb = st->cur_skb = skb;
2844         st->frag_idx = st->stepped_offset = 0;
2845         st->frag_data = NULL;
2846 }
2847 EXPORT_SYMBOL(skb_prepare_seq_read);
2848
2849 /**
2850  * skb_seq_read - Sequentially read skb data
2851  * @consumed: number of bytes consumed by the caller so far
2852  * @data: destination pointer for data to be returned
2853  * @st: state variable
2854  *
2855  * Reads a block of skb data at @consumed relative to the
2856  * lower offset specified to skb_prepare_seq_read(). Assigns
2857  * the head of the data block to @data and returns the length
2858  * of the block or 0 if the end of the skb data or the upper
2859  * offset has been reached.
2860  *
2861  * The caller is not required to consume all of the data
2862  * returned, i.e. @consumed is typically set to the number
2863  * of bytes already consumed and the next call to
2864  * skb_seq_read() will return the remaining part of the block.
2865  *
2866  * Note 1: The size of each block of data returned can be arbitrary,
2867  *       this limitation is the cost for zerocopy sequential
2868  *       reads of potentially non linear data.
2869  *
2870  * Note 2: Fragment lists within fragments are not implemented
2871  *       at the moment, state->root_skb could be replaced with
2872  *       a stack for this purpose.
2873  */
2874 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
2875                           struct skb_seq_state *st)
2876 {
2877         unsigned int block_limit, abs_offset = consumed + st->lower_offset;
2878         skb_frag_t *frag;
2879
2880         if (unlikely(abs_offset >= st->upper_offset)) {
2881                 if (st->frag_data) {
2882                         kunmap_atomic(st->frag_data);
2883                         st->frag_data = NULL;
2884                 }
2885                 return 0;
2886         }
2887
2888 next_skb:
2889         block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
2890
2891         if (abs_offset < block_limit && !st->frag_data) {
2892                 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
2893                 return block_limit - abs_offset;
2894         }
2895
2896         if (st->frag_idx == 0 && !st->frag_data)
2897                 st->stepped_offset += skb_headlen(st->cur_skb);
2898
2899         while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
2900                 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
2901                 block_limit = skb_frag_size(frag) + st->stepped_offset;
2902
2903                 if (abs_offset < block_limit) {
2904                         if (!st->frag_data)
2905                                 st->frag_data = kmap_atomic(skb_frag_page(frag));
2906
2907                         *data = (u8 *) st->frag_data + frag->page_offset +
2908                                 (abs_offset - st->stepped_offset);
2909
2910                         return block_limit - abs_offset;
2911                 }
2912
2913                 if (st->frag_data) {
2914                         kunmap_atomic(st->frag_data);
2915                         st->frag_data = NULL;
2916                 }
2917
2918                 st->frag_idx++;
2919                 st->stepped_offset += skb_frag_size(frag);
2920         }
2921
2922         if (st->frag_data) {
2923                 kunmap_atomic(st->frag_data);
2924                 st->frag_data = NULL;
2925         }
2926
2927         if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
2928                 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
2929                 st->frag_idx = 0;
2930                 goto next_skb;
2931         } else if (st->cur_skb->next) {
2932                 st->cur_skb = st->cur_skb->next;
2933                 st->frag_idx = 0;
2934                 goto next_skb;
2935         }
2936
2937         return 0;
2938 }
2939 EXPORT_SYMBOL(skb_seq_read);
2940
2941 /**
2942  * skb_abort_seq_read - Abort a sequential read of skb data
2943  * @st: state variable
2944  *
2945  * Must be called if skb_seq_read() was not called until it
2946  * returned 0.
2947  */
2948 void skb_abort_seq_read(struct skb_seq_state *st)
2949 {
2950         if (st->frag_data)
2951                 kunmap_atomic(st->frag_data);
2952 }
2953 EXPORT_SYMBOL(skb_abort_seq_read);
2954
2955 #define TS_SKB_CB(state)        ((struct skb_seq_state *) &((state)->cb))
2956
2957 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
2958                                           struct ts_config *conf,
2959                                           struct ts_state *state)
2960 {
2961         return skb_seq_read(offset, text, TS_SKB_CB(state));
2962 }
2963
2964 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
2965 {
2966         skb_abort_seq_read(TS_SKB_CB(state));
2967 }
2968
2969 /**
2970  * skb_find_text - Find a text pattern in skb data
2971  * @skb: the buffer to look in
2972  * @from: search offset
2973  * @to: search limit
2974  * @config: textsearch configuration
2975  *
2976  * Finds a pattern in the skb data according to the specified
2977  * textsearch configuration. Use textsearch_next() to retrieve
2978  * subsequent occurrences of the pattern. Returns the offset
2979  * to the first occurrence or UINT_MAX if no match was found.
2980  */
2981 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
2982                            unsigned int to, struct ts_config *config)
2983 {
2984         struct ts_state state;
2985         unsigned int ret;
2986
2987         config->get_next_block = skb_ts_get_next_block;
2988         config->finish = skb_ts_finish;
2989
2990         skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
2991
2992         ret = textsearch_find(config, &state);
2993         return (ret <= to - from ? ret : UINT_MAX);
2994 }
2995 EXPORT_SYMBOL(skb_find_text);
2996
2997 /**
2998  * skb_append_datato_frags - append the user data to a skb
2999  * @sk: sock  structure
3000  * @skb: skb structure to be appended with user data.
3001  * @getfrag: call back function to be used for getting the user data
3002  * @from: pointer to user message iov
3003  * @length: length of the iov message
3004  *
3005  * Description: This procedure append the user data in the fragment part
3006  * of the skb if any page alloc fails user this procedure returns  -ENOMEM
3007  */
3008 int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
3009                         int (*getfrag)(void *from, char *to, int offset,
3010                                         int len, int odd, struct sk_buff *skb),
3011                         void *from, int length)
3012 {
3013         int frg_cnt = skb_shinfo(skb)->nr_frags;
3014         int copy;
3015         int offset = 0;
3016         int ret;
3017         struct page_frag *pfrag = &current->task_frag;
3018
3019         do {
3020                 /* Return error if we don't have space for new frag */
3021                 if (frg_cnt >= MAX_SKB_FRAGS)
3022                         return -EMSGSIZE;
3023
3024                 if (!sk_page_frag_refill(sk, pfrag))
3025                         return -ENOMEM;
3026
3027                 /* copy the user data to page */
3028                 copy = min_t(int, length, pfrag->size - pfrag->offset);
3029
3030                 ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
3031                               offset, copy, 0, skb);
3032                 if (ret < 0)
3033                         return -EFAULT;
3034
3035                 /* copy was successful so update the size parameters */
3036                 skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
3037                                    copy);
3038                 frg_cnt++;
3039                 pfrag->offset += copy;
3040                 get_page(pfrag->page);
3041
3042                 skb->truesize += copy;
3043                 atomic_add(copy, &sk->sk_wmem_alloc);
3044                 skb->len += copy;
3045                 skb->data_len += copy;
3046                 offset += copy;
3047                 length -= copy;
3048
3049         } while (length > 0);
3050
3051         return 0;
3052 }
3053 EXPORT_SYMBOL(skb_append_datato_frags);
3054
3055 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3056                          int offset, size_t size)
3057 {
3058         int i = skb_shinfo(skb)->nr_frags;
3059
3060         if (skb_can_coalesce(skb, i, page, offset)) {
3061                 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3062         } else if (i < MAX_SKB_FRAGS) {
3063                 get_page(page);
3064                 skb_fill_page_desc(skb, i, page, offset, size);
3065         } else {
3066                 return -EMSGSIZE;
3067         }
3068
3069         return 0;
3070 }
3071 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3072
3073 /**
3074  *      skb_pull_rcsum - pull skb and update receive checksum
3075  *      @skb: buffer to update
3076  *      @len: length of data pulled
3077  *
3078  *      This function performs an skb_pull on the packet and updates
3079  *      the CHECKSUM_COMPLETE checksum.  It should be used on
3080  *      receive path processing instead of skb_pull unless you know
3081  *      that the checksum difference is zero (e.g., a valid IP header)
3082  *      or you are setting ip_summed to CHECKSUM_NONE.
3083  */
3084 unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3085 {
3086         unsigned char *data = skb->data;
3087
3088         BUG_ON(len > skb->len);
3089         __skb_pull(skb, len);
3090         skb_postpull_rcsum(skb, data, len);
3091         return skb->data;
3092 }
3093 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3094
3095 /**
3096  *      skb_segment - Perform protocol segmentation on skb.
3097  *      @head_skb: buffer to segment
3098  *      @features: features for the output path (see dev->features)
3099  *
3100  *      This function performs segmentation on the given skb.  It returns
3101  *      a pointer to the first in a list of new skbs for the segments.
3102  *      In case of error it returns ERR_PTR(err).
3103  */
3104 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3105                             netdev_features_t features)
3106 {
3107         struct sk_buff *segs = NULL;
3108         struct sk_buff *tail = NULL;
3109         struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3110         skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3111         unsigned int mss = skb_shinfo(head_skb)->gso_size;
3112         unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3113         struct sk_buff *frag_skb = head_skb;
3114         unsigned int offset = doffset;
3115         unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3116         unsigned int partial_segs = 0;
3117         unsigned int headroom;
3118         unsigned int len = head_skb->len;
3119         __be16 proto;
3120         bool csum, sg;
3121         int nfrags = skb_shinfo(head_skb)->nr_frags;
3122         int err = -ENOMEM;
3123         int i = 0;
3124         int pos;
3125         int dummy;
3126
3127         if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
3128             (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
3129                 /* gso_size is untrusted, and we have a frag_list with a linear
3130                  * non head_frag head.
3131                  *
3132                  * (we assume checking the first list_skb member suffices;
3133                  * i.e if either of the list_skb members have non head_frag
3134                  * head, then the first one has too).
3135                  *
3136                  * If head_skb's headlen does not fit requested gso_size, it
3137                  * means that the frag_list members do NOT terminate on exact
3138                  * gso_size boundaries. Hence we cannot perform skb_frag_t page
3139                  * sharing. Therefore we must fallback to copying the frag_list
3140                  * skbs; we do so by disabling SG.
3141                  */
3142                 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
3143                         features &= ~NETIF_F_SG;
3144         }
3145
3146         __skb_push(head_skb, doffset);
3147         proto = skb_network_protocol(head_skb, &dummy);
3148         if (unlikely(!proto))
3149                 return ERR_PTR(-EINVAL);
3150
3151         sg = !!(features & NETIF_F_SG);
3152         csum = !!can_checksum_protocol(features, proto);
3153
3154         if (sg && csum && (mss != GSO_BY_FRAGS))  {
3155                 if (!(features & NETIF_F_GSO_PARTIAL)) {
3156                         struct sk_buff *iter;
3157                         unsigned int frag_len;
3158
3159                         if (!list_skb ||
3160                             !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
3161                                 goto normal;
3162
3163                         /* If we get here then all the required
3164                          * GSO features except frag_list are supported.
3165                          * Try to split the SKB to multiple GSO SKBs
3166                          * with no frag_list.
3167                          * Currently we can do that only when the buffers don't
3168                          * have a linear part and all the buffers except
3169                          * the last are of the same length.
3170                          */
3171                         frag_len = list_skb->len;
3172                         skb_walk_frags(head_skb, iter) {
3173                                 if (frag_len != iter->len && iter->next)
3174                                         goto normal;
3175                                 if (skb_headlen(iter))
3176                                         goto normal;
3177
3178                                 len -= iter->len;
3179                         }
3180
3181                         if (len != frag_len)
3182                                 goto normal;
3183                 }
3184
3185                 /* GSO partial only requires that we trim off any excess that
3186                  * doesn't fit into an MSS sized block, so take care of that
3187                  * now.
3188                  */
3189                 partial_segs = len / mss;
3190                 if (partial_segs > 1)
3191                         mss *= partial_segs;
3192                 else
3193                         partial_segs = 0;
3194         }
3195
3196 normal:
3197         headroom = skb_headroom(head_skb);
3198         pos = skb_headlen(head_skb);
3199
3200         do {
3201                 struct sk_buff *nskb;
3202                 skb_frag_t *nskb_frag;
3203                 int hsize;
3204                 int size;
3205
3206                 if (unlikely(mss == GSO_BY_FRAGS)) {
3207                         len = list_skb->len;
3208                 } else {
3209                         len = head_skb->len - offset;
3210                         if (len > mss)
3211                                 len = mss;
3212                 }
3213
3214                 hsize = skb_headlen(head_skb) - offset;
3215                 if (hsize < 0)
3216                         hsize = 0;
3217                 if (hsize > len || !sg)
3218                         hsize = len;
3219
3220                 if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
3221                     (skb_headlen(list_skb) == len || sg)) {
3222                         BUG_ON(skb_headlen(list_skb) > len);
3223
3224                         i = 0;
3225                         nfrags = skb_shinfo(list_skb)->nr_frags;
3226                         frag = skb_shinfo(list_skb)->frags;
3227                         frag_skb = list_skb;
3228                         pos += skb_headlen(list_skb);
3229
3230                         while (pos < offset + len) {
3231                                 BUG_ON(i >= nfrags);
3232
3233                                 size = skb_frag_size(frag);
3234                                 if (pos + size > offset + len)
3235                                         break;
3236
3237                                 i++;
3238                                 pos += size;
3239                                 frag++;
3240                         }
3241
3242                         nskb = skb_clone(list_skb, GFP_ATOMIC);
3243                         list_skb = list_skb->next;
3244
3245                         if (unlikely(!nskb))
3246                                 goto err;
3247
3248                         if (unlikely(pskb_trim(nskb, len))) {
3249                                 kfree_skb(nskb);
3250                                 goto err;
3251                         }
3252
3253                         hsize = skb_end_offset(nskb);
3254                         if (skb_cow_head(nskb, doffset + headroom)) {
3255                                 kfree_skb(nskb);
3256                                 goto err;
3257                         }
3258
3259                         nskb->truesize += skb_end_offset(nskb) - hsize;
3260                         skb_release_head_state(nskb);
3261                         __skb_push(nskb, doffset);
3262                 } else {
3263                         nskb = __alloc_skb(hsize + doffset + headroom,
3264                                            GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
3265                                            NUMA_NO_NODE);
3266
3267                         if (unlikely(!nskb))
3268                                 goto err;
3269
3270                         skb_reserve(nskb, headroom);
3271                         __skb_put(nskb, doffset);
3272                 }
3273
3274                 if (segs)
3275                         tail->next = nskb;
3276                 else
3277                         segs = nskb;
3278                 tail = nskb;
3279
3280                 __copy_skb_header(nskb, head_skb);
3281
3282                 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
3283                 skb_reset_mac_len(nskb);
3284
3285                 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
3286                                                  nskb->data - tnl_hlen,
3287                                                  doffset + tnl_hlen);
3288
3289                 if (nskb->len == len + doffset)
3290                         goto perform_csum_check;
3291
3292                 if (!sg) {
3293                         if (!nskb->remcsum_offload)
3294                                 nskb->ip_summed = CHECKSUM_NONE;
3295                         SKB_GSO_CB(nskb)->csum =
3296                                 skb_copy_and_csum_bits(head_skb, offset,
3297                                                        skb_put(nskb, len),
3298                                                        len, 0);
3299                         SKB_GSO_CB(nskb)->csum_start =
3300                                 skb_headroom(nskb) + doffset;
3301                         continue;
3302                 }
3303
3304                 nskb_frag = skb_shinfo(nskb)->frags;
3305
3306                 skb_copy_from_linear_data_offset(head_skb, offset,
3307                                                  skb_put(nskb, hsize), hsize);
3308
3309                 skb_shinfo(nskb)->tx_flags |= skb_shinfo(head_skb)->tx_flags &
3310                                               SKBTX_SHARED_FRAG;
3311
3312                 while (pos < offset + len) {
3313                         if (i >= nfrags) {
3314                                 BUG_ON(skb_headlen(list_skb));
3315
3316                                 i = 0;
3317                                 nfrags = skb_shinfo(list_skb)->nr_frags;
3318                                 frag = skb_shinfo(list_skb)->frags;
3319                                 frag_skb = list_skb;
3320
3321                                 BUG_ON(!nfrags);
3322
3323                                 list_skb = list_skb->next;
3324                         }
3325
3326                         if (unlikely(skb_shinfo(nskb)->nr_frags >=
3327                                      MAX_SKB_FRAGS)) {
3328                                 net_warn_ratelimited(
3329                                         "skb_segment: too many frags: %u %u\n",
3330                                         pos, mss);
3331                                 err = -EINVAL;
3332                                 goto err;
3333                         }
3334
3335                         if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
3336                                 goto err;
3337
3338                         *nskb_frag = *frag;
3339                         __skb_frag_ref(nskb_frag);
3340                         size = skb_frag_size(nskb_frag);
3341
3342                         if (pos < offset) {
3343                                 nskb_frag->page_offset += offset - pos;
3344                                 skb_frag_size_sub(nskb_frag, offset - pos);
3345                         }
3346
3347                         skb_shinfo(nskb)->nr_frags++;
3348
3349                         if (pos + size <= offset + len) {
3350                                 i++;
3351                                 frag++;
3352                                 pos += size;
3353                         } else {
3354                                 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
3355                                 goto skip_fraglist;
3356                         }
3357
3358                         nskb_frag++;
3359                 }
3360
3361 skip_fraglist:
3362                 nskb->data_len = len - hsize;
3363                 nskb->len += nskb->data_len;
3364                 nskb->truesize += nskb->data_len;
3365
3366 perform_csum_check:
3367                 if (!csum) {
3368                         if (skb_has_shared_frag(nskb) &&
3369                             __skb_linearize(nskb))
3370                                 goto err;
3371
3372                         if (!nskb->remcsum_offload)
3373                                 nskb->ip_summed = CHECKSUM_NONE;
3374                         SKB_GSO_CB(nskb)->csum =
3375                                 skb_checksum(nskb, doffset,
3376                                              nskb->len - doffset, 0);
3377                         SKB_GSO_CB(nskb)->csum_start =
3378                                 skb_headroom(nskb) + doffset;
3379                 }
3380         } while ((offset += len) < head_skb->len);
3381
3382         /* Some callers want to get the end of the list.
3383          * Put it in segs->prev to avoid walking the list.
3384          * (see validate_xmit_skb_list() for example)
3385          */
3386         segs->prev = tail;
3387
3388         if (partial_segs) {
3389                 struct sk_buff *iter;
3390                 int type = skb_shinfo(head_skb)->gso_type;
3391                 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
3392
3393                 /* Update type to add partial and then remove dodgy if set */
3394                 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
3395                 type &= ~SKB_GSO_DODGY;
3396
3397                 /* Update GSO info and prepare to start updating headers on
3398                  * our way back down the stack of protocols.
3399                  */
3400                 for (iter = segs; iter; iter = iter->next) {
3401                         skb_shinfo(iter)->gso_size = gso_size;
3402                         skb_shinfo(iter)->gso_segs = partial_segs;
3403                         skb_shinfo(iter)->gso_type = type;
3404                         SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
3405                 }
3406
3407                 if (tail->len - doffset <= gso_size)
3408                         skb_shinfo(tail)->gso_size = 0;
3409                 else if (tail != segs)
3410                         skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
3411         }
3412
3413         /* Following permits correct backpressure, for protocols
3414          * using skb_set_owner_w().
3415          * Idea is to tranfert ownership from head_skb to last segment.
3416          */
3417         if (head_skb->destructor == sock_wfree) {
3418                 swap(tail->truesize, head_skb->truesize);
3419                 swap(tail->destructor, head_skb->destructor);
3420                 swap(tail->sk, head_skb->sk);
3421         }
3422         return segs;
3423
3424 err:
3425         kfree_skb_list(segs);
3426         return ERR_PTR(err);
3427 }
3428 EXPORT_SYMBOL_GPL(skb_segment);
3429
3430 int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
3431 {
3432         struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
3433         unsigned int offset = skb_gro_offset(skb);
3434         unsigned int headlen = skb_headlen(skb);
3435         unsigned int len = skb_gro_len(skb);
3436         struct sk_buff *lp, *p = *head;
3437         unsigned int delta_truesize;
3438
3439         if (unlikely(p->len + len >= 65536))
3440                 return -E2BIG;
3441
3442         lp = NAPI_GRO_CB(p)->last;
3443         pinfo = skb_shinfo(lp);
3444
3445         if (headlen <= offset) {
3446                 skb_frag_t *frag;
3447                 skb_frag_t *frag2;
3448                 int i = skbinfo->nr_frags;
3449                 int nr_frags = pinfo->nr_frags + i;
3450
3451                 if (nr_frags > MAX_SKB_FRAGS)
3452                         goto merge;
3453
3454                 offset -= headlen;
3455                 pinfo->nr_frags = nr_frags;
3456                 skbinfo->nr_frags = 0;
3457
3458                 frag = pinfo->frags + nr_frags;
3459                 frag2 = skbinfo->frags + i;
3460                 do {
3461                         *--frag = *--frag2;
3462                 } while (--i);
3463
3464                 frag->page_offset += offset;
3465                 skb_frag_size_sub(frag, offset);
3466
3467                 /* all fragments truesize : remove (head size + sk_buff) */
3468                 delta_truesize = skb->truesize -
3469                                  SKB_TRUESIZE(skb_end_offset(skb));
3470
3471                 skb->truesize -= skb->data_len;
3472                 skb->len -= skb->data_len;
3473                 skb->data_len = 0;
3474
3475                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
3476                 goto done;
3477         } else if (skb->head_frag) {
3478                 int nr_frags = pinfo->nr_frags;
3479                 skb_frag_t *frag = pinfo->frags + nr_frags;
3480                 struct page *page = virt_to_head_page(skb->head);
3481                 unsigned int first_size = headlen - offset;
3482                 unsigned int first_offset;
3483
3484                 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
3485                         goto merge;
3486
3487                 first_offset = skb->data -
3488                                (unsigned char *)page_address(page) +
3489                                offset;
3490
3491                 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
3492
3493                 frag->page.p      = page;
3494                 frag->page_offset = first_offset;
3495                 skb_frag_size_set(frag, first_size);
3496
3497                 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
3498                 /* We dont need to clear skbinfo->nr_frags here */
3499
3500                 delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
3501                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
3502                 goto done;
3503         }
3504
3505 merge:
3506         delta_truesize = skb->truesize;
3507         if (offset > headlen) {
3508                 unsigned int eat = offset - headlen;
3509
3510                 skbinfo->frags[0].page_offset += eat;
3511                 skb_frag_size_sub(&skbinfo->frags[0], eat);
3512                 skb->data_len -= eat;
3513                 skb->len -= eat;
3514                 offset = headlen;
3515         }
3516
3517         __skb_pull(skb, offset);
3518
3519         if (NAPI_GRO_CB(p)->last == p)
3520                 skb_shinfo(p)->frag_list = skb;
3521         else
3522                 NAPI_GRO_CB(p)->last->next = skb;
3523         NAPI_GRO_CB(p)->last = skb;
3524         __skb_header_release(skb);
3525         lp = p;
3526
3527 done:
3528         NAPI_GRO_CB(p)->count++;
3529         p->data_len += len;
3530         p->truesize += delta_truesize;
3531         p->len += len;
3532         if (lp != p) {
3533                 lp->data_len += len;
3534                 lp->truesize += delta_truesize;
3535                 lp->len += len;
3536         }
3537         NAPI_GRO_CB(skb)->same_flow = 1;
3538         return 0;
3539 }
3540 EXPORT_SYMBOL_GPL(skb_gro_receive);
3541
3542 void __init skb_init(void)
3543 {
3544         skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
3545                                               sizeof(struct sk_buff),
3546                                               0,
3547                                               SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3548                                               NULL);
3549         skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
3550                                                 sizeof(struct sk_buff_fclones),
3551                                                 0,
3552                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3553                                                 NULL);
3554 }
3555
3556 static int
3557 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
3558                unsigned int recursion_level)
3559 {
3560         int start = skb_headlen(skb);
3561         int i, copy = start - offset;
3562         struct sk_buff *frag_iter;
3563         int elt = 0;
3564
3565         if (unlikely(recursion_level >= 24))
3566                 return -EMSGSIZE;
3567
3568         if (copy > 0) {
3569                 if (copy > len)
3570                         copy = len;
3571                 sg_set_buf(sg, skb->data + offset, copy);
3572                 elt++;
3573                 if ((len -= copy) == 0)
3574                         return elt;
3575                 offset += copy;
3576         }
3577
3578         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3579                 int end;
3580
3581                 WARN_ON(start > offset + len);
3582
3583                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3584                 if ((copy = end - offset) > 0) {
3585                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3586                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
3587                                 return -EMSGSIZE;
3588
3589                         if (copy > len)
3590                                 copy = len;
3591                         sg_set_page(&sg[elt], skb_frag_page(frag), copy,
3592                                         frag->page_offset+offset-start);
3593                         elt++;
3594                         if (!(len -= copy))
3595                                 return elt;
3596                         offset += copy;
3597                 }
3598                 start = end;
3599         }
3600
3601         skb_walk_frags(skb, frag_iter) {
3602                 int end, ret;
3603
3604                 WARN_ON(start > offset + len);
3605
3606                 end = start + frag_iter->len;
3607                 if ((copy = end - offset) > 0) {
3608                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
3609                                 return -EMSGSIZE;
3610
3611                         if (copy > len)
3612                                 copy = len;
3613                         ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
3614                                               copy, recursion_level + 1);
3615                         if (unlikely(ret < 0))
3616                                 return ret;
3617                         elt += ret;
3618                         if ((len -= copy) == 0)
3619                                 return elt;
3620                         offset += copy;
3621                 }
3622                 start = end;
3623         }
3624         BUG_ON(len);
3625         return elt;
3626 }
3627
3628 /**
3629  *      skb_to_sgvec - Fill a scatter-gather list from a socket buffer
3630  *      @skb: Socket buffer containing the buffers to be mapped
3631  *      @sg: The scatter-gather list to map into
3632  *      @offset: The offset into the buffer's contents to start mapping
3633  *      @len: Length of buffer space to be mapped
3634  *
3635  *      Fill the specified scatter-gather list with mappings/pointers into a
3636  *      region of the buffer space attached to a socket buffer. Returns either
3637  *      the number of scatterlist items used, or -EMSGSIZE if the contents
3638  *      could not fit.
3639  */
3640 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
3641 {
3642         int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
3643
3644         if (nsg <= 0)
3645                 return nsg;
3646
3647         sg_mark_end(&sg[nsg - 1]);
3648
3649         return nsg;
3650 }
3651 EXPORT_SYMBOL_GPL(skb_to_sgvec);
3652
3653 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
3654  * sglist without mark the sg which contain last skb data as the end.
3655  * So the caller can mannipulate sg list as will when padding new data after
3656  * the first call without calling sg_unmark_end to expend sg list.
3657  *
3658  * Scenario to use skb_to_sgvec_nomark:
3659  * 1. sg_init_table
3660  * 2. skb_to_sgvec_nomark(payload1)
3661  * 3. skb_to_sgvec_nomark(payload2)
3662  *
3663  * This is equivalent to:
3664  * 1. sg_init_table
3665  * 2. skb_to_sgvec(payload1)
3666  * 3. sg_unmark_end
3667  * 4. skb_to_sgvec(payload2)
3668  *
3669  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
3670  * is more preferable.
3671  */
3672 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
3673                         int offset, int len)
3674 {
3675         return __skb_to_sgvec(skb, sg, offset, len, 0);
3676 }
3677 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
3678
3679
3680
3681 /**
3682  *      skb_cow_data - Check that a socket buffer's data buffers are writable
3683  *      @skb: The socket buffer to check.
3684  *      @tailbits: Amount of trailing space to be added
3685  *      @trailer: Returned pointer to the skb where the @tailbits space begins
3686  *
3687  *      Make sure that the data buffers attached to a socket buffer are
3688  *      writable. If they are not, private copies are made of the data buffers
3689  *      and the socket buffer is set to use these instead.
3690  *
3691  *      If @tailbits is given, make sure that there is space to write @tailbits
3692  *      bytes of data beyond current end of socket buffer.  @trailer will be
3693  *      set to point to the skb in which this space begins.
3694  *
3695  *      The number of scatterlist elements required to completely map the
3696  *      COW'd and extended socket buffer will be returned.
3697  */
3698 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
3699 {
3700         int copyflag;
3701         int elt;
3702         struct sk_buff *skb1, **skb_p;
3703
3704         /* If skb is cloned or its head is paged, reallocate
3705          * head pulling out all the pages (pages are considered not writable
3706          * at the moment even if they are anonymous).
3707          */
3708         if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
3709             __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
3710                 return -ENOMEM;
3711
3712         /* Easy case. Most of packets will go this way. */
3713         if (!skb_has_frag_list(skb)) {
3714                 /* A little of trouble, not enough of space for trailer.
3715                  * This should not happen, when stack is tuned to generate
3716                  * good frames. OK, on miss we reallocate and reserve even more
3717                  * space, 128 bytes is fair. */
3718
3719                 if (skb_tailroom(skb) < tailbits &&
3720                     pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
3721                         return -ENOMEM;
3722
3723                 /* Voila! */
3724                 *trailer = skb;
3725                 return 1;
3726         }
3727
3728         /* Misery. We are in troubles, going to mincer fragments... */
3729
3730         elt = 1;
3731         skb_p = &skb_shinfo(skb)->frag_list;
3732         copyflag = 0;
3733
3734         while ((skb1 = *skb_p) != NULL) {
3735                 int ntail = 0;
3736
3737                 /* The fragment is partially pulled by someone,
3738                  * this can happen on input. Copy it and everything
3739                  * after it. */
3740
3741                 if (skb_shared(skb1))
3742                         copyflag = 1;
3743
3744                 /* If the skb is the last, worry about trailer. */
3745
3746                 if (skb1->next == NULL && tailbits) {
3747                         if (skb_shinfo(skb1)->nr_frags ||
3748                             skb_has_frag_list(skb1) ||
3749                             skb_tailroom(skb1) < tailbits)
3750                                 ntail = tailbits + 128;
3751                 }
3752
3753                 if (copyflag ||
3754                     skb_cloned(skb1) ||
3755                     ntail ||
3756                     skb_shinfo(skb1)->nr_frags ||
3757                     skb_has_frag_list(skb1)) {
3758                         struct sk_buff *skb2;
3759
3760                         /* Fuck, we are miserable poor guys... */
3761                         if (ntail == 0)
3762                                 skb2 = skb_copy(skb1, GFP_ATOMIC);
3763                         else
3764                                 skb2 = skb_copy_expand(skb1,
3765                                                        skb_headroom(skb1),
3766                                                        ntail,
3767                                                        GFP_ATOMIC);
3768                         if (unlikely(skb2 == NULL))
3769                                 return -ENOMEM;
3770
3771                         if (skb1->sk)
3772                                 skb_set_owner_w(skb2, skb1->sk);
3773
3774                         /* Looking around. Are we still alive?
3775                          * OK, link new skb, drop old one */
3776
3777                         skb2->next = skb1->next;
3778                         *skb_p = skb2;
3779                         kfree_skb(skb1);
3780                         skb1 = skb2;
3781                 }
3782                 elt++;
3783                 *trailer = skb1;
3784                 skb_p = &skb1->next;
3785         }
3786
3787         return elt;
3788 }
3789 EXPORT_SYMBOL_GPL(skb_cow_data);
3790
3791 static void sock_rmem_free(struct sk_buff *skb)
3792 {
3793         struct sock *sk = skb->sk;
3794
3795         atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
3796 }
3797
3798 /*
3799  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
3800  */
3801 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
3802 {
3803         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
3804             (unsigned int)sk->sk_rcvbuf)
3805                 return -ENOMEM;
3806
3807         skb_orphan(skb);
3808         skb->sk = sk;
3809         skb->destructor = sock_rmem_free;
3810         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
3811
3812         /* before exiting rcu section, make sure dst is refcounted */
3813         skb_dst_force(skb);
3814
3815         skb_queue_tail(&sk->sk_error_queue, skb);
3816         if (!sock_flag(sk, SOCK_DEAD))
3817                 sk->sk_error_report(sk);
3818         return 0;
3819 }
3820 EXPORT_SYMBOL(sock_queue_err_skb);
3821
3822 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
3823 {
3824         struct sk_buff_head *q = &sk->sk_error_queue;
3825         struct sk_buff *skb, *skb_next;
3826         unsigned long flags;
3827         int err = 0;
3828
3829         spin_lock_irqsave(&q->lock, flags);
3830         skb = __skb_dequeue(q);
3831         if (skb && (skb_next = skb_peek(q)))
3832                 err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
3833         spin_unlock_irqrestore(&q->lock, flags);
3834
3835         sk->sk_err = err;
3836         if (err)
3837                 sk->sk_error_report(sk);
3838
3839         return skb;
3840 }
3841 EXPORT_SYMBOL(sock_dequeue_err_skb);
3842
3843 /**
3844  * skb_clone_sk - create clone of skb, and take reference to socket
3845  * @skb: the skb to clone
3846  *
3847  * This function creates a clone of a buffer that holds a reference on
3848  * sk_refcnt.  Buffers created via this function are meant to be
3849  * returned using sock_queue_err_skb, or free via kfree_skb.
3850  *
3851  * When passing buffers allocated with this function to sock_queue_err_skb
3852  * it is necessary to wrap the call with sock_hold/sock_put in order to
3853  * prevent the socket from being released prior to being enqueued on
3854  * the sk_error_queue.
3855  */
3856 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
3857 {
3858         struct sock *sk = skb->sk;
3859         struct sk_buff *clone;
3860
3861         if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt))
3862                 return NULL;
3863
3864         clone = skb_clone(skb, GFP_ATOMIC);
3865         if (!clone) {
3866                 sock_put(sk);
3867                 return NULL;
3868         }
3869
3870         clone->sk = sk;
3871         clone->destructor = sock_efree;
3872
3873         return clone;
3874 }
3875 EXPORT_SYMBOL(skb_clone_sk);
3876
3877 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
3878                                         struct sock *sk,
3879                                         int tstype)
3880 {
3881         struct sock_exterr_skb *serr;
3882         int err;
3883
3884         serr = SKB_EXT_ERR(skb);
3885         memset(serr, 0, sizeof(*serr));
3886         serr->ee.ee_errno = ENOMSG;
3887         serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
3888         serr->ee.ee_info = tstype;
3889         serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
3890         if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
3891                 serr->ee.ee_data = skb_shinfo(skb)->tskey;
3892                 if (sk->sk_protocol == IPPROTO_TCP &&
3893                     sk->sk_type == SOCK_STREAM)
3894                         serr->ee.ee_data -= sk->sk_tskey;
3895         }
3896
3897         err = sock_queue_err_skb(sk, skb);
3898
3899         if (err)
3900                 kfree_skb(skb);
3901 }
3902
3903 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
3904 {
3905         bool ret;
3906
3907         if (likely(sysctl_tstamp_allow_data || tsonly))
3908                 return true;
3909
3910         read_lock_bh(&sk->sk_callback_lock);
3911         ret = sk->sk_socket && sk->sk_socket->file &&
3912               file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
3913         read_unlock_bh(&sk->sk_callback_lock);
3914         return ret;
3915 }
3916
3917 void skb_complete_tx_timestamp(struct sk_buff *skb,
3918                                struct skb_shared_hwtstamps *hwtstamps)
3919 {
3920         struct sock *sk = skb->sk;
3921
3922         if (!skb_may_tx_timestamp(sk, false))
3923                 goto err;
3924
3925         /* Take a reference to prevent skb_orphan() from freeing the socket,
3926          * but only if the socket refcount is not zero.
3927          */
3928         if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
3929                 *skb_hwtstamps(skb) = *hwtstamps;
3930                 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
3931                 sock_put(sk);
3932                 return;
3933         }
3934
3935 err:
3936         kfree_skb(skb);
3937 }
3938 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
3939
3940 void __skb_tstamp_tx(struct sk_buff *orig_skb,
3941                      struct skb_shared_hwtstamps *hwtstamps,
3942                      struct sock *sk, int tstype)
3943 {
3944         struct sk_buff *skb;
3945         bool tsonly;
3946
3947         if (!sk)
3948                 return;
3949
3950         tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
3951         if (!skb_may_tx_timestamp(sk, tsonly))
3952                 return;
3953
3954         if (tsonly)
3955                 skb = alloc_skb(0, GFP_ATOMIC);
3956         else
3957                 skb = skb_clone(orig_skb, GFP_ATOMIC);
3958         if (!skb)
3959                 return;
3960
3961         if (tsonly) {
3962                 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
3963                                              SKBTX_ANY_TSTAMP;
3964                 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
3965         }
3966
3967         if (hwtstamps)
3968                 *skb_hwtstamps(skb) = *hwtstamps;
3969         else
3970                 skb->tstamp = ktime_get_real();
3971
3972         __skb_complete_tx_timestamp(skb, sk, tstype);
3973 }
3974 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
3975
3976 void skb_tstamp_tx(struct sk_buff *orig_skb,
3977                    struct skb_shared_hwtstamps *hwtstamps)
3978 {
3979         return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
3980                                SCM_TSTAMP_SND);
3981 }
3982 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
3983
3984 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
3985 {
3986         struct sock *sk = skb->sk;
3987         struct sock_exterr_skb *serr;
3988         int err = 1;
3989
3990         skb->wifi_acked_valid = 1;
3991         skb->wifi_acked = acked;
3992
3993         serr = SKB_EXT_ERR(skb);
3994         memset(serr, 0, sizeof(*serr));
3995         serr->ee.ee_errno = ENOMSG;
3996         serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
3997
3998         /* Take a reference to prevent skb_orphan() from freeing the socket,
3999          * but only if the socket refcount is not zero.
4000          */
4001         if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
4002                 err = sock_queue_err_skb(sk, skb);
4003                 sock_put(sk);
4004         }
4005         if (err)
4006                 kfree_skb(skb);
4007 }
4008 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4009
4010 /**
4011  * skb_partial_csum_set - set up and verify partial csum values for packet
4012  * @skb: the skb to set
4013  * @start: the number of bytes after skb->data to start checksumming.
4014  * @off: the offset from start to place the checksum.
4015  *
4016  * For untrusted partially-checksummed packets, we need to make sure the values
4017  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4018  *
4019  * This function checks and sets those values and skb->ip_summed: if this
4020  * returns false you should drop the packet.
4021  */
4022 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4023 {
4024         if (unlikely(start > skb_headlen(skb)) ||
4025             unlikely((int)start + off > skb_headlen(skb) - 2)) {
4026                 net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
4027                                      start, off, skb_headlen(skb));
4028                 return false;
4029         }
4030         skb->ip_summed = CHECKSUM_PARTIAL;
4031         skb->csum_start = skb_headroom(skb) + start;
4032         skb->csum_offset = off;
4033         skb_set_transport_header(skb, start);
4034         return true;
4035 }
4036 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4037
4038 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4039                                unsigned int max)
4040 {
4041         if (skb_headlen(skb) >= len)
4042                 return 0;
4043
4044         /* If we need to pullup then pullup to the max, so we
4045          * won't need to do it again.
4046          */
4047         if (max > skb->len)
4048                 max = skb->len;
4049
4050         if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4051                 return -ENOMEM;
4052
4053         if (skb_headlen(skb) < len)
4054                 return -EPROTO;
4055
4056         return 0;
4057 }
4058
4059 #define MAX_TCP_HDR_LEN (15 * 4)
4060
4061 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4062                                       typeof(IPPROTO_IP) proto,
4063                                       unsigned int off)
4064 {
4065         switch (proto) {
4066                 int err;
4067
4068         case IPPROTO_TCP:
4069                 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4070                                           off + MAX_TCP_HDR_LEN);
4071                 if (!err && !skb_partial_csum_set(skb, off,
4072                                                   offsetof(struct tcphdr,
4073                                                            check)))
4074                         err = -EPROTO;
4075                 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4076
4077         case IPPROTO_UDP:
4078                 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4079                                           off + sizeof(struct udphdr));
4080                 if (!err && !skb_partial_csum_set(skb, off,
4081                                                   offsetof(struct udphdr,
4082                                                            check)))
4083                         err = -EPROTO;
4084                 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4085         }
4086
4087         return ERR_PTR(-EPROTO);
4088 }
4089
4090 /* This value should be large enough to cover a tagged ethernet header plus
4091  * maximally sized IP and TCP or UDP headers.
4092  */
4093 #define MAX_IP_HDR_LEN 128
4094
4095 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4096 {
4097         unsigned int off;
4098         bool fragment;
4099         __sum16 *csum;
4100         int err;
4101
4102         fragment = false;
4103
4104         err = skb_maybe_pull_tail(skb,
4105                                   sizeof(struct iphdr),
4106                                   MAX_IP_HDR_LEN);
4107         if (err < 0)
4108                 goto out;
4109
4110         if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
4111                 fragment = true;
4112
4113         off = ip_hdrlen(skb);
4114
4115         err = -EPROTO;
4116
4117         if (fragment)
4118                 goto out;
4119
4120         csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
4121         if (IS_ERR(csum))
4122                 return PTR_ERR(csum);
4123
4124         if (recalculate)
4125                 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
4126                                            ip_hdr(skb)->daddr,
4127                                            skb->len - off,
4128                                            ip_hdr(skb)->protocol, 0);
4129         err = 0;
4130
4131 out:
4132         return err;
4133 }
4134
4135 /* This value should be large enough to cover a tagged ethernet header plus
4136  * an IPv6 header, all options, and a maximal TCP or UDP header.
4137  */
4138 #define MAX_IPV6_HDR_LEN 256
4139
4140 #define OPT_HDR(type, skb, off) \
4141         (type *)(skb_network_header(skb) + (off))
4142
4143 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
4144 {
4145         int err;
4146         u8 nexthdr;
4147         unsigned int off;
4148         unsigned int len;
4149         bool fragment;
4150         bool done;
4151         __sum16 *csum;
4152
4153         fragment = false;
4154         done = false;
4155
4156         off = sizeof(struct ipv6hdr);
4157
4158         err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
4159         if (err < 0)
4160                 goto out;
4161
4162         nexthdr = ipv6_hdr(skb)->nexthdr;
4163
4164         len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
4165         while (off <= len && !done) {
4166                 switch (nexthdr) {
4167                 case IPPROTO_DSTOPTS:
4168                 case IPPROTO_HOPOPTS:
4169                 case IPPROTO_ROUTING: {
4170                         struct ipv6_opt_hdr *hp;
4171
4172                         err = skb_maybe_pull_tail(skb,
4173                                                   off +
4174                                                   sizeof(struct ipv6_opt_hdr),
4175                                                   MAX_IPV6_HDR_LEN);
4176                         if (err < 0)
4177                                 goto out;
4178
4179                         hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
4180                         nexthdr = hp->nexthdr;
4181                         off += ipv6_optlen(hp);
4182                         break;
4183                 }
4184                 case IPPROTO_AH: {
4185                         struct ip_auth_hdr *hp;
4186
4187                         err = skb_maybe_pull_tail(skb,
4188                                                   off +
4189                                                   sizeof(struct ip_auth_hdr),
4190                                                   MAX_IPV6_HDR_LEN);
4191                         if (err < 0)
4192                                 goto out;
4193
4194                         hp = OPT_HDR(struct ip_auth_hdr, skb, off);
4195                         nexthdr = hp->nexthdr;
4196                         off += ipv6_authlen(hp);
4197                         break;
4198                 }
4199                 case IPPROTO_FRAGMENT: {
4200                         struct frag_hdr *hp;
4201
4202                         err = skb_maybe_pull_tail(skb,
4203                                                   off +
4204                                                   sizeof(struct frag_hdr),
4205                                                   MAX_IPV6_HDR_LEN);
4206                         if (err < 0)
4207                                 goto out;
4208
4209                         hp = OPT_HDR(struct frag_hdr, skb, off);
4210
4211                         if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
4212                                 fragment = true;
4213
4214                         nexthdr = hp->nexthdr;
4215                         off += sizeof(struct frag_hdr);
4216                         break;
4217                 }
4218                 default:
4219                         done = true;
4220                         break;
4221                 }
4222         }
4223
4224         err = -EPROTO;
4225
4226         if (!done || fragment)
4227                 goto out;
4228
4229         csum = skb_checksum_setup_ip(skb, nexthdr, off);
4230         if (IS_ERR(csum))
4231                 return PTR_ERR(csum);
4232
4233         if (recalculate)
4234                 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
4235                                          &ipv6_hdr(skb)->daddr,
4236                                          skb->len - off, nexthdr, 0);
4237         err = 0;
4238
4239 out:
4240         return err;
4241 }
4242
4243 /**
4244  * skb_checksum_setup - set up partial checksum offset
4245  * @skb: the skb to set up
4246  * @recalculate: if true the pseudo-header checksum will be recalculated
4247  */
4248 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
4249 {
4250         int err;
4251
4252         switch (skb->protocol) {
4253         case htons(ETH_P_IP):
4254                 err = skb_checksum_setup_ipv4(skb, recalculate);
4255                 break;
4256
4257         case htons(ETH_P_IPV6):
4258                 err = skb_checksum_setup_ipv6(skb, recalculate);
4259                 break;
4260
4261         default:
4262                 err = -EPROTO;
4263                 break;
4264         }
4265
4266         return err;
4267 }
4268 EXPORT_SYMBOL(skb_checksum_setup);
4269
4270 /**
4271  * skb_checksum_maybe_trim - maybe trims the given skb
4272  * @skb: the skb to check
4273  * @transport_len: the data length beyond the network header
4274  *
4275  * Checks whether the given skb has data beyond the given transport length.
4276  * If so, returns a cloned skb trimmed to this transport length.
4277  * Otherwise returns the provided skb. Returns NULL in error cases
4278  * (e.g. transport_len exceeds skb length or out-of-memory).
4279  *
4280  * Caller needs to set the skb transport header and free any returned skb if it
4281  * differs from the provided skb.
4282  */
4283 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
4284                                                unsigned int transport_len)
4285 {
4286         struct sk_buff *skb_chk;
4287         unsigned int len = skb_transport_offset(skb) + transport_len;
4288         int ret;
4289
4290         if (skb->len < len)
4291                 return NULL;
4292         else if (skb->len == len)
4293                 return skb;
4294
4295         skb_chk = skb_clone(skb, GFP_ATOMIC);
4296         if (!skb_chk)
4297                 return NULL;
4298
4299         ret = pskb_trim_rcsum(skb_chk, len);
4300         if (ret) {
4301                 kfree_skb(skb_chk);
4302                 return NULL;
4303         }
4304
4305         return skb_chk;
4306 }
4307
4308 /**
4309  * skb_checksum_trimmed - validate checksum of an skb
4310  * @skb: the skb to check
4311  * @transport_len: the data length beyond the network header
4312  * @skb_chkf: checksum function to use
4313  *
4314  * Applies the given checksum function skb_chkf to the provided skb.
4315  * Returns a checked and maybe trimmed skb. Returns NULL on error.
4316  *
4317  * If the skb has data beyond the given transport length, then a
4318  * trimmed & cloned skb is checked and returned.
4319  *
4320  * Caller needs to set the skb transport header and free any returned skb if it
4321  * differs from the provided skb.
4322  */
4323 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
4324                                      unsigned int transport_len,
4325                                      __sum16(*skb_chkf)(struct sk_buff *skb))
4326 {
4327         struct sk_buff *skb_chk;
4328         unsigned int offset = skb_transport_offset(skb);
4329         __sum16 ret;
4330
4331         skb_chk = skb_checksum_maybe_trim(skb, transport_len);
4332         if (!skb_chk)
4333                 goto err;
4334
4335         if (!pskb_may_pull(skb_chk, offset))
4336                 goto err;
4337
4338         skb_pull_rcsum(skb_chk, offset);
4339         ret = skb_chkf(skb_chk);
4340         skb_push_rcsum(skb_chk, offset);
4341
4342         if (ret)
4343                 goto err;
4344
4345         return skb_chk;
4346
4347 err:
4348         if (skb_chk && skb_chk != skb)
4349                 kfree_skb(skb_chk);
4350
4351         return NULL;
4352
4353 }
4354 EXPORT_SYMBOL(skb_checksum_trimmed);
4355
4356 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
4357 {
4358         net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
4359                              skb->dev->name);
4360 }
4361 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
4362
4363 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
4364 {
4365         if (head_stolen) {
4366                 skb_release_head_state(skb);
4367                 kmem_cache_free(skbuff_head_cache, skb);
4368         } else {
4369                 __kfree_skb(skb);
4370         }
4371 }
4372 EXPORT_SYMBOL(kfree_skb_partial);
4373
4374 /**
4375  * skb_try_coalesce - try to merge skb to prior one
4376  * @to: prior buffer
4377  * @from: buffer to add
4378  * @fragstolen: pointer to boolean
4379  * @delta_truesize: how much more was allocated than was requested
4380  */
4381 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
4382                       bool *fragstolen, int *delta_truesize)
4383 {
4384         int i, delta, len = from->len;
4385
4386         *fragstolen = false;
4387
4388         if (skb_cloned(to))
4389                 return false;
4390
4391         if (len <= skb_tailroom(to)) {
4392                 if (len)
4393                         BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
4394                 *delta_truesize = 0;
4395                 return true;
4396         }
4397
4398         if (skb_has_frag_list(to) || skb_has_frag_list(from))
4399                 return false;
4400
4401         if (skb_headlen(from) != 0) {
4402                 struct page *page;
4403                 unsigned int offset;
4404
4405                 if (skb_shinfo(to)->nr_frags +
4406                     skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
4407                         return false;
4408
4409                 if (skb_head_is_locked(from))
4410                         return false;
4411
4412                 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
4413
4414                 page = virt_to_head_page(from->head);
4415                 offset = from->data - (unsigned char *)page_address(page);
4416
4417                 skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
4418                                    page, offset, skb_headlen(from));
4419                 *fragstolen = true;
4420         } else {
4421                 if (skb_shinfo(to)->nr_frags +
4422                     skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
4423                         return false;
4424
4425                 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
4426         }
4427
4428         WARN_ON_ONCE(delta < len);
4429
4430         memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
4431                skb_shinfo(from)->frags,
4432                skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
4433         skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
4434
4435         if (!skb_cloned(from))
4436                 skb_shinfo(from)->nr_frags = 0;
4437
4438         /* if the skb is not cloned this does nothing
4439          * since we set nr_frags to 0.
4440          */
4441         for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
4442                 skb_frag_ref(from, i);
4443
4444         to->truesize += delta;
4445         to->len += len;
4446         to->data_len += len;
4447
4448         *delta_truesize = delta;
4449         return true;
4450 }
4451 EXPORT_SYMBOL(skb_try_coalesce);
4452
4453 /**
4454  * skb_scrub_packet - scrub an skb
4455  *
4456  * @skb: buffer to clean
4457  * @xnet: packet is crossing netns
4458  *
4459  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
4460  * into/from a tunnel. Some information have to be cleared during these
4461  * operations.
4462  * skb_scrub_packet can also be used to clean a skb before injecting it in
4463  * another namespace (@xnet == true). We have to clear all information in the
4464  * skb that could impact namespace isolation.
4465  */
4466 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
4467 {
4468         skb->tstamp.tv64 = 0;
4469         skb->pkt_type = PACKET_HOST;
4470         skb->skb_iif = 0;
4471         skb->ignore_df = 0;
4472         skb_dst_drop(skb);
4473         secpath_reset(skb);
4474         nf_reset(skb);
4475         nf_reset_trace(skb);
4476
4477 #ifdef CONFIG_NET_SWITCHDEV
4478         skb->offload_fwd_mark = 0;
4479 #endif
4480
4481         if (!xnet)
4482                 return;
4483
4484         ipvs_reset(skb);
4485         skb_orphan(skb);
4486         skb->mark = 0;
4487 }
4488 EXPORT_SYMBOL_GPL(skb_scrub_packet);
4489
4490 /**
4491  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
4492  *
4493  * @skb: GSO skb
4494  *
4495  * skb_gso_transport_seglen is used to determine the real size of the
4496  * individual segments, including Layer4 headers (TCP/UDP).
4497  *
4498  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
4499  */
4500 unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
4501 {
4502         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4503         unsigned int thlen = 0;
4504
4505         if (skb->encapsulation) {
4506                 thlen = skb_inner_transport_header(skb) -
4507                         skb_transport_header(skb);
4508
4509                 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
4510                         thlen += inner_tcp_hdrlen(skb);
4511         } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
4512                 thlen = tcp_hdrlen(skb);
4513         } else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) {
4514                 thlen = sizeof(struct sctphdr);
4515         }
4516         /* UFO sets gso_size to the size of the fragmentation
4517          * payload, i.e. the size of the L4 (UDP) header is already
4518          * accounted for.
4519          */
4520         return thlen + shinfo->gso_size;
4521 }
4522 EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
4523
4524 /**
4525  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
4526  *
4527  * There are a couple of instances where we have a GSO skb, and we
4528  * want to determine what size it would be after it is segmented.
4529  *
4530  * We might want to check:
4531  * -    L3+L4+payload size (e.g. IP forwarding)
4532  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
4533  *
4534  * This is a helper to do that correctly considering GSO_BY_FRAGS.
4535  *
4536  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
4537  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
4538  *
4539  * @max_len: The maximum permissible length.
4540  *
4541  * Returns true if the segmented length <= max length.
4542  */
4543 static inline bool skb_gso_size_check(const struct sk_buff *skb,
4544                                       unsigned int seg_len,
4545                                       unsigned int max_len) {
4546         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4547         const struct sk_buff *iter;
4548
4549         if (shinfo->gso_size != GSO_BY_FRAGS)
4550                 return seg_len <= max_len;
4551
4552         /* Undo this so we can re-use header sizes */
4553         seg_len -= GSO_BY_FRAGS;
4554
4555         skb_walk_frags(skb, iter) {
4556                 if (seg_len + skb_headlen(iter) > max_len)
4557                         return false;
4558         }
4559
4560         return true;
4561 }
4562
4563 /**
4564  * skb_gso_validate_mtu - Return in case such skb fits a given MTU
4565  *
4566  * @skb: GSO skb
4567  * @mtu: MTU to validate against
4568  *
4569  * skb_gso_validate_mtu validates if a given skb will fit a wanted MTU
4570  * once split.
4571  */
4572 bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu)
4573 {
4574         return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
4575 }
4576 EXPORT_SYMBOL_GPL(skb_gso_validate_mtu);
4577
4578 /**
4579  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
4580  *
4581  * @skb: GSO skb
4582  * @len: length to validate against
4583  *
4584  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
4585  * length once split, including L2, L3 and L4 headers and the payload.
4586  */
4587 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
4588 {
4589         return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
4590 }
4591 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
4592
4593 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
4594 {
4595         int mac_len;
4596
4597         if (skb_cow(skb, skb_headroom(skb)) < 0) {
4598                 kfree_skb(skb);
4599                 return NULL;
4600         }
4601
4602         mac_len = skb->data - skb_mac_header(skb);
4603         if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
4604                 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
4605                         mac_len - VLAN_HLEN - ETH_TLEN);
4606         }
4607         skb->mac_header += VLAN_HLEN;
4608         return skb;
4609 }
4610
4611 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
4612 {
4613         struct vlan_hdr *vhdr;
4614         u16 vlan_tci;
4615
4616         if (unlikely(skb_vlan_tag_present(skb))) {
4617                 /* vlan_tci is already set-up so leave this for another time */
4618                 return skb;
4619         }
4620
4621         skb = skb_share_check(skb, GFP_ATOMIC);
4622         if (unlikely(!skb))
4623                 goto err_free;
4624         /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
4625         if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
4626                 goto err_free;
4627
4628         vhdr = (struct vlan_hdr *)skb->data;
4629         vlan_tci = ntohs(vhdr->h_vlan_TCI);
4630         __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
4631
4632         skb_pull_rcsum(skb, VLAN_HLEN);
4633         vlan_set_encap_proto(skb, vhdr);
4634
4635         skb = skb_reorder_vlan_header(skb);
4636         if (unlikely(!skb))
4637                 goto err_free;
4638
4639         skb_reset_network_header(skb);
4640         skb_reset_transport_header(skb);
4641         skb_reset_mac_len(skb);
4642
4643         return skb;
4644
4645 err_free:
4646         kfree_skb(skb);
4647         return NULL;
4648 }
4649 EXPORT_SYMBOL(skb_vlan_untag);
4650
4651 int skb_ensure_writable(struct sk_buff *skb, int write_len)
4652 {
4653         if (!pskb_may_pull(skb, write_len))
4654                 return -ENOMEM;
4655
4656         if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
4657                 return 0;
4658
4659         return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
4660 }
4661 EXPORT_SYMBOL(skb_ensure_writable);
4662
4663 /* remove VLAN header from packet and update csum accordingly.
4664  * expects a non skb_vlan_tag_present skb with a vlan tag payload
4665  */
4666 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
4667 {
4668         struct vlan_hdr *vhdr;
4669         int offset = skb->data - skb_mac_header(skb);
4670         int err;
4671
4672         if (WARN_ONCE(offset,
4673                       "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
4674                       offset)) {
4675                 return -EINVAL;
4676         }
4677
4678         err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
4679         if (unlikely(err))
4680                 return err;
4681
4682         skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
4683
4684         vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
4685         *vlan_tci = ntohs(vhdr->h_vlan_TCI);
4686
4687         memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
4688         __skb_pull(skb, VLAN_HLEN);
4689
4690         vlan_set_encap_proto(skb, vhdr);
4691         skb->mac_header += VLAN_HLEN;
4692
4693         if (skb_network_offset(skb) < ETH_HLEN)
4694                 skb_set_network_header(skb, ETH_HLEN);
4695
4696         skb_reset_mac_len(skb);
4697
4698         return err;
4699 }
4700 EXPORT_SYMBOL(__skb_vlan_pop);
4701
4702 /* Pop a vlan tag either from hwaccel or from payload.
4703  * Expects skb->data at mac header.
4704  */
4705 int skb_vlan_pop(struct sk_buff *skb)
4706 {
4707         u16 vlan_tci;
4708         __be16 vlan_proto;
4709         int err;
4710
4711         if (likely(skb_vlan_tag_present(skb))) {
4712                 skb->vlan_tci = 0;
4713         } else {
4714                 if (unlikely(!eth_type_vlan(skb->protocol)))
4715                         return 0;
4716
4717                 err = __skb_vlan_pop(skb, &vlan_tci);
4718                 if (err)
4719                         return err;
4720         }
4721         /* move next vlan tag to hw accel tag */
4722         if (likely(!eth_type_vlan(skb->protocol)))
4723                 return 0;
4724
4725         vlan_proto = skb->protocol;
4726         err = __skb_vlan_pop(skb, &vlan_tci);
4727         if (unlikely(err))
4728                 return err;
4729
4730         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
4731         return 0;
4732 }
4733 EXPORT_SYMBOL(skb_vlan_pop);
4734
4735 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
4736  * Expects skb->data at mac header.
4737  */
4738 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
4739 {
4740         if (skb_vlan_tag_present(skb)) {
4741                 int offset = skb->data - skb_mac_header(skb);
4742                 int err;
4743
4744                 if (WARN_ONCE(offset,
4745                               "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
4746                               offset)) {
4747                         return -EINVAL;
4748                 }
4749
4750                 err = __vlan_insert_tag(skb, skb->vlan_proto,
4751                                         skb_vlan_tag_get(skb));
4752                 if (err)
4753                         return err;
4754
4755                 skb->protocol = skb->vlan_proto;
4756                 skb->mac_len += VLAN_HLEN;
4757
4758                 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
4759         }
4760         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
4761         return 0;
4762 }
4763 EXPORT_SYMBOL(skb_vlan_push);
4764
4765 /**
4766  * alloc_skb_with_frags - allocate skb with page frags
4767  *
4768  * @header_len: size of linear part
4769  * @data_len: needed length in frags
4770  * @max_page_order: max page order desired.
4771  * @errcode: pointer to error code if any
4772  * @gfp_mask: allocation mask
4773  *
4774  * This can be used to allocate a paged skb, given a maximal order for frags.
4775  */
4776 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
4777                                      unsigned long data_len,
4778                                      int max_page_order,
4779                                      int *errcode,
4780                                      gfp_t gfp_mask)
4781 {
4782         int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
4783         unsigned long chunk;
4784         struct sk_buff *skb;
4785         struct page *page;
4786         gfp_t gfp_head;
4787         int i;
4788
4789         *errcode = -EMSGSIZE;
4790         /* Note this test could be relaxed, if we succeed to allocate
4791          * high order pages...
4792          */
4793         if (npages > MAX_SKB_FRAGS)
4794                 return NULL;
4795
4796         gfp_head = gfp_mask;
4797         if (gfp_head & __GFP_DIRECT_RECLAIM)
4798                 gfp_head |= __GFP_REPEAT;
4799
4800         *errcode = -ENOBUFS;
4801         skb = alloc_skb(header_len, gfp_head);
4802         if (!skb)
4803                 return NULL;
4804
4805         skb->truesize += npages << PAGE_SHIFT;
4806
4807         for (i = 0; npages > 0; i++) {
4808                 int order = max_page_order;
4809
4810                 while (order) {
4811                         if (npages >= 1 << order) {
4812                                 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
4813                                                    __GFP_COMP |
4814                                                    __GFP_NOWARN |
4815                                                    __GFP_NORETRY,
4816                                                    order);
4817                                 if (page)
4818                                         goto fill_page;
4819                                 /* Do not retry other high order allocations */
4820                                 order = 1;
4821                                 max_page_order = 0;
4822                         }
4823                         order--;
4824                 }
4825                 page = alloc_page(gfp_mask);
4826                 if (!page)
4827                         goto failure;
4828 fill_page:
4829                 chunk = min_t(unsigned long, data_len,
4830                               PAGE_SIZE << order);
4831                 skb_fill_page_desc(skb, i, page, 0, chunk);
4832                 data_len -= chunk;
4833                 npages -= 1 << order;
4834         }
4835         return skb;
4836
4837 failure:
4838         kfree_skb(skb);
4839         return NULL;
4840 }
4841 EXPORT_SYMBOL(alloc_skb_with_frags);
4842
4843 /* carve out the first off bytes from skb when off < headlen */
4844 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
4845                                     const int headlen, gfp_t gfp_mask)
4846 {
4847         int i;
4848         int size = skb_end_offset(skb);
4849         int new_hlen = headlen - off;
4850         u8 *data;
4851
4852         size = SKB_DATA_ALIGN(size);
4853
4854         if (skb_pfmemalloc(skb))
4855                 gfp_mask |= __GFP_MEMALLOC;
4856         data = kmalloc_reserve(size +
4857                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
4858                                gfp_mask, NUMA_NO_NODE, NULL);
4859         if (!data)
4860                 return -ENOMEM;
4861
4862         size = SKB_WITH_OVERHEAD(ksize(data));
4863
4864         /* Copy real data, and all frags */
4865         skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
4866         skb->len -= off;
4867
4868         memcpy((struct skb_shared_info *)(data + size),
4869                skb_shinfo(skb),
4870                offsetof(struct skb_shared_info,
4871                         frags[skb_shinfo(skb)->nr_frags]));
4872         if (skb_cloned(skb)) {
4873                 /* drop the old head gracefully */
4874                 if (skb_orphan_frags(skb, gfp_mask)) {
4875                         kfree(data);
4876                         return -ENOMEM;
4877                 }
4878                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
4879                         skb_frag_ref(skb, i);
4880                 if (skb_has_frag_list(skb))
4881                         skb_clone_fraglist(skb);
4882                 skb_release_data(skb);
4883         } else {
4884                 /* we can reuse existing recount- all we did was
4885                  * relocate values
4886                  */
4887                 skb_free_head(skb);
4888         }
4889
4890         skb->head = data;
4891         skb->data = data;
4892         skb->head_frag = 0;
4893 #ifdef NET_SKBUFF_DATA_USES_OFFSET
4894         skb->end = size;
4895 #else
4896         skb->end = skb->head + size;
4897 #endif
4898         skb_set_tail_pointer(skb, skb_headlen(skb));
4899         skb_headers_offset_update(skb, 0);
4900         skb->cloned = 0;
4901         skb->hdr_len = 0;
4902         skb->nohdr = 0;
4903         atomic_set(&skb_shinfo(skb)->dataref, 1);
4904
4905         return 0;
4906 }
4907
4908 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
4909
4910 /* carve out the first eat bytes from skb's frag_list. May recurse into
4911  * pskb_carve()
4912  */
4913 static int pskb_carve_frag_list(struct sk_buff *skb,
4914                                 struct skb_shared_info *shinfo, int eat,
4915                                 gfp_t gfp_mask)
4916 {
4917         struct sk_buff *list = shinfo->frag_list;
4918         struct sk_buff *clone = NULL;
4919         struct sk_buff *insp = NULL;
4920
4921         do {
4922                 if (!list) {
4923                         pr_err("Not enough bytes to eat. Want %d\n", eat);
4924                         return -EFAULT;
4925                 }
4926                 if (list->len <= eat) {
4927                         /* Eaten as whole. */
4928                         eat -= list->len;
4929                         list = list->next;
4930                         insp = list;
4931                 } else {
4932                         /* Eaten partially. */
4933                         if (skb_shared(list)) {
4934                                 clone = skb_clone(list, gfp_mask);
4935                                 if (!clone)
4936                                         return -ENOMEM;
4937                                 insp = list->next;
4938                                 list = clone;
4939                         } else {
4940                                 /* This may be pulled without problems. */
4941                                 insp = list;
4942                         }
4943                         if (pskb_carve(list, eat, gfp_mask) < 0) {
4944                                 kfree_skb(clone);
4945                                 return -ENOMEM;
4946                         }
4947                         break;
4948                 }
4949         } while (eat);
4950
4951         /* Free pulled out fragments. */
4952         while ((list = shinfo->frag_list) != insp) {
4953                 shinfo->frag_list = list->next;
4954                 kfree_skb(list);
4955         }
4956         /* And insert new clone at head. */
4957         if (clone) {
4958                 clone->next = list;
4959                 shinfo->frag_list = clone;
4960         }
4961         return 0;
4962 }
4963
4964 /* carve off first len bytes from skb. Split line (off) is in the
4965  * non-linear part of skb
4966  */
4967 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
4968                                        int pos, gfp_t gfp_mask)
4969 {
4970         int i, k = 0;
4971         int size = skb_end_offset(skb);
4972         u8 *data;
4973         const int nfrags = skb_shinfo(skb)->nr_frags;
4974         struct skb_shared_info *shinfo;
4975
4976         size = SKB_DATA_ALIGN(size);
4977
4978         if (skb_pfmemalloc(skb))
4979                 gfp_mask |= __GFP_MEMALLOC;
4980         data = kmalloc_reserve(size +
4981                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
4982                                gfp_mask, NUMA_NO_NODE, NULL);
4983         if (!data)
4984                 return -ENOMEM;
4985
4986         size = SKB_WITH_OVERHEAD(ksize(data));
4987
4988         memcpy((struct skb_shared_info *)(data + size),
4989                skb_shinfo(skb), offsetof(struct skb_shared_info,
4990                                          frags[skb_shinfo(skb)->nr_frags]));
4991         if (skb_orphan_frags(skb, gfp_mask)) {
4992                 kfree(data);
4993                 return -ENOMEM;
4994         }
4995         shinfo = (struct skb_shared_info *)(data + size);
4996         for (i = 0; i < nfrags; i++) {
4997                 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
4998
4999                 if (pos + fsize > off) {
5000                         shinfo->frags[k] = skb_shinfo(skb)->frags[i];
5001
5002                         if (pos < off) {
5003                                 /* Split frag.
5004                                  * We have two variants in this case:
5005                                  * 1. Move all the frag to the second
5006                                  *    part, if it is possible. F.e.
5007                                  *    this approach is mandatory for TUX,
5008                                  *    where splitting is expensive.
5009                                  * 2. Split is accurately. We make this.
5010                                  */
5011                                 shinfo->frags[0].page_offset += off - pos;
5012                                 skb_frag_size_sub(&shinfo->frags[0], off - pos);
5013                         }
5014                         skb_frag_ref(skb, i);
5015                         k++;
5016                 }
5017                 pos += fsize;
5018         }
5019         shinfo->nr_frags = k;
5020         if (skb_has_frag_list(skb))
5021                 skb_clone_fraglist(skb);
5022
5023         /* split line is in frag list */
5024         if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
5025                 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
5026                 if (skb_has_frag_list(skb))
5027                         kfree_skb_list(skb_shinfo(skb)->frag_list);
5028                 kfree(data);
5029                 return -ENOMEM;
5030         }
5031         skb_release_data(skb);
5032
5033         skb->head = data;
5034         skb->head_frag = 0;
5035         skb->data = data;
5036 #ifdef NET_SKBUFF_DATA_USES_OFFSET
5037         skb->end = size;
5038 #else
5039         skb->end = skb->head + size;
5040 #endif
5041         skb_reset_tail_pointer(skb);
5042         skb_headers_offset_update(skb, 0);
5043         skb->cloned   = 0;
5044         skb->hdr_len  = 0;
5045         skb->nohdr    = 0;
5046         skb->len -= off;
5047         skb->data_len = skb->len;
5048         atomic_set(&skb_shinfo(skb)->dataref, 1);
5049         return 0;
5050 }
5051
5052 /* remove len bytes from the beginning of the skb */
5053 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
5054 {
5055         int headlen = skb_headlen(skb);
5056
5057         if (len < headlen)
5058                 return pskb_carve_inside_header(skb, len, headlen, gfp);
5059         else
5060                 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
5061 }
5062
5063 /* Extract to_copy bytes starting at off from skb, and return this in
5064  * a new skb
5065  */
5066 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
5067                              int to_copy, gfp_t gfp)
5068 {
5069         struct sk_buff  *clone = skb_clone(skb, gfp);
5070
5071         if (!clone)
5072                 return NULL;
5073
5074         if (pskb_carve(clone, off, gfp) < 0 ||
5075             pskb_trim(clone, to_copy)) {
5076                 kfree_skb(clone);
5077                 return NULL;
5078         }
5079         return clone;
5080 }
5081 EXPORT_SYMBOL(pskb_extract);