GNU Linux-libre 4.9.333-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 void skb_copy_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 EXPORT_SYMBOL(skb_copy_header);
1083
1084 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1085 {
1086         if (skb_pfmemalloc(skb))
1087                 return SKB_ALLOC_RX;
1088         return 0;
1089 }
1090
1091 /**
1092  *      skb_copy        -       create private copy of an sk_buff
1093  *      @skb: buffer to copy
1094  *      @gfp_mask: allocation priority
1095  *
1096  *      Make a copy of both an &sk_buff and its data. This is used when the
1097  *      caller wishes to modify the data and needs a private copy of the
1098  *      data to alter. Returns %NULL on failure or the pointer to the buffer
1099  *      on success. The returned buffer has a reference count of 1.
1100  *
1101  *      As by-product this function converts non-linear &sk_buff to linear
1102  *      one, so that &sk_buff becomes completely private and caller is allowed
1103  *      to modify all the data of returned buffer. This means that this
1104  *      function is not recommended for use in circumstances when only
1105  *      header is going to be modified. Use pskb_copy() instead.
1106  */
1107
1108 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1109 {
1110         int headerlen = skb_headroom(skb);
1111         unsigned int size = skb_end_offset(skb) + skb->data_len;
1112         struct sk_buff *n = __alloc_skb(size, gfp_mask,
1113                                         skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1114
1115         if (!n)
1116                 return NULL;
1117
1118         /* Set the data pointer */
1119         skb_reserve(n, headerlen);
1120         /* Set the tail pointer and length */
1121         skb_put(n, skb->len);
1122
1123         if (skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len))
1124                 BUG();
1125
1126         skb_copy_header(n, skb);
1127         return n;
1128 }
1129 EXPORT_SYMBOL(skb_copy);
1130
1131 /**
1132  *      __pskb_copy_fclone      -  create copy of an sk_buff with private head.
1133  *      @skb: buffer to copy
1134  *      @headroom: headroom of new skb
1135  *      @gfp_mask: allocation priority
1136  *      @fclone: if true allocate the copy of the skb from the fclone
1137  *      cache instead of the head cache; it is recommended to set this
1138  *      to true for the cases where the copy will likely be cloned
1139  *
1140  *      Make a copy of both an &sk_buff and part of its data, located
1141  *      in header. Fragmented data remain shared. This is used when
1142  *      the caller wishes to modify only header of &sk_buff and needs
1143  *      private copy of the header to alter. Returns %NULL on failure
1144  *      or the pointer to the buffer on success.
1145  *      The returned buffer has a reference count of 1.
1146  */
1147
1148 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1149                                    gfp_t gfp_mask, bool fclone)
1150 {
1151         unsigned int size = skb_headlen(skb) + headroom;
1152         int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1153         struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1154
1155         if (!n)
1156                 goto out;
1157
1158         /* Set the data pointer */
1159         skb_reserve(n, headroom);
1160         /* Set the tail pointer and length */
1161         skb_put(n, skb_headlen(skb));
1162         /* Copy the bytes */
1163         skb_copy_from_linear_data(skb, n->data, n->len);
1164
1165         n->truesize += skb->data_len;
1166         n->data_len  = skb->data_len;
1167         n->len       = skb->len;
1168
1169         if (skb_shinfo(skb)->nr_frags) {
1170                 int i;
1171
1172                 if (skb_orphan_frags(skb, gfp_mask)) {
1173                         kfree_skb(n);
1174                         n = NULL;
1175                         goto out;
1176                 }
1177                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1178                         skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1179                         skb_frag_ref(skb, i);
1180                 }
1181                 skb_shinfo(n)->nr_frags = i;
1182         }
1183
1184         if (skb_has_frag_list(skb)) {
1185                 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1186                 skb_clone_fraglist(n);
1187         }
1188
1189         skb_copy_header(n, skb);
1190 out:
1191         return n;
1192 }
1193 EXPORT_SYMBOL(__pskb_copy_fclone);
1194
1195 /**
1196  *      pskb_expand_head - reallocate header of &sk_buff
1197  *      @skb: buffer to reallocate
1198  *      @nhead: room to add at head
1199  *      @ntail: room to add at tail
1200  *      @gfp_mask: allocation priority
1201  *
1202  *      Expands (or creates identical copy, if @nhead and @ntail are zero)
1203  *      header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1204  *      reference count of 1. Returns zero in the case of success or error,
1205  *      if expansion failed. In the last case, &sk_buff is not changed.
1206  *
1207  *      All the pointers pointing into skb header may change and must be
1208  *      reloaded after call to this function.
1209  */
1210
1211 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1212                      gfp_t gfp_mask)
1213 {
1214         int i;
1215         u8 *data;
1216         int size = nhead + skb_end_offset(skb) + ntail;
1217         long off;
1218
1219         BUG_ON(nhead < 0);
1220
1221         if (skb_shared(skb))
1222                 BUG();
1223
1224         size = SKB_DATA_ALIGN(size);
1225
1226         if (skb_pfmemalloc(skb))
1227                 gfp_mask |= __GFP_MEMALLOC;
1228         data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1229                                gfp_mask, NUMA_NO_NODE, NULL);
1230         if (!data)
1231                 goto nodata;
1232         size = SKB_WITH_OVERHEAD(ksize(data));
1233
1234         /* Copy only real data... and, alas, header. This should be
1235          * optimized for the cases when header is void.
1236          */
1237         memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1238
1239         memcpy((struct skb_shared_info *)(data + size),
1240                skb_shinfo(skb),
1241                offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1242
1243         /*
1244          * if shinfo is shared we must drop the old head gracefully, but if it
1245          * is not we can just drop the old head and let the existing refcount
1246          * be since all we did is relocate the values
1247          */
1248         if (skb_cloned(skb)) {
1249                 /* copy this zero copy skb frags */
1250                 if (skb_orphan_frags(skb, gfp_mask))
1251                         goto nofrags;
1252                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1253                         skb_frag_ref(skb, i);
1254
1255                 if (skb_has_frag_list(skb))
1256                         skb_clone_fraglist(skb);
1257
1258                 skb_release_data(skb);
1259         } else {
1260                 skb_free_head(skb);
1261         }
1262         off = (data + nhead) - skb->head;
1263
1264         skb->head     = data;
1265         skb->head_frag = 0;
1266         skb->data    += off;
1267 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1268         skb->end      = size;
1269         off           = nhead;
1270 #else
1271         skb->end      = skb->head + size;
1272 #endif
1273         skb->tail             += off;
1274         skb_headers_offset_update(skb, nhead);
1275         skb->cloned   = 0;
1276         skb->hdr_len  = 0;
1277         skb->nohdr    = 0;
1278         atomic_set(&skb_shinfo(skb)->dataref, 1);
1279         return 0;
1280
1281 nofrags:
1282         kfree(data);
1283 nodata:
1284         return -ENOMEM;
1285 }
1286 EXPORT_SYMBOL(pskb_expand_head);
1287
1288 /* Make private copy of skb with writable head and some headroom */
1289
1290 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1291 {
1292         struct sk_buff *skb2;
1293         int delta = headroom - skb_headroom(skb);
1294
1295         if (delta <= 0)
1296                 skb2 = pskb_copy(skb, GFP_ATOMIC);
1297         else {
1298                 skb2 = skb_clone(skb, GFP_ATOMIC);
1299                 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1300                                              GFP_ATOMIC)) {
1301                         kfree_skb(skb2);
1302                         skb2 = NULL;
1303                 }
1304         }
1305         return skb2;
1306 }
1307 EXPORT_SYMBOL(skb_realloc_headroom);
1308
1309 /**
1310  *      skb_copy_expand -       copy and expand sk_buff
1311  *      @skb: buffer to copy
1312  *      @newheadroom: new free bytes at head
1313  *      @newtailroom: new free bytes at tail
1314  *      @gfp_mask: allocation priority
1315  *
1316  *      Make a copy of both an &sk_buff and its data and while doing so
1317  *      allocate additional space.
1318  *
1319  *      This is used when the caller wishes to modify the data and needs a
1320  *      private copy of the data to alter as well as more space for new fields.
1321  *      Returns %NULL on failure or the pointer to the buffer
1322  *      on success. The returned buffer has a reference count of 1.
1323  *
1324  *      You must pass %GFP_ATOMIC as the allocation priority if this function
1325  *      is called from an interrupt.
1326  */
1327 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1328                                 int newheadroom, int newtailroom,
1329                                 gfp_t gfp_mask)
1330 {
1331         /*
1332          *      Allocate the copy buffer
1333          */
1334         struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1335                                         gfp_mask, skb_alloc_rx_flag(skb),
1336                                         NUMA_NO_NODE);
1337         int oldheadroom = skb_headroom(skb);
1338         int head_copy_len, head_copy_off;
1339
1340         if (!n)
1341                 return NULL;
1342
1343         skb_reserve(n, newheadroom);
1344
1345         /* Set the tail pointer and length */
1346         skb_put(n, skb->len);
1347
1348         head_copy_len = oldheadroom;
1349         head_copy_off = 0;
1350         if (newheadroom <= head_copy_len)
1351                 head_copy_len = newheadroom;
1352         else
1353                 head_copy_off = newheadroom - head_copy_len;
1354
1355         /* Copy the linear header and data. */
1356         if (skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1357                           skb->len + head_copy_len))
1358                 BUG();
1359
1360         skb_copy_header(n, skb);
1361
1362         skb_headers_offset_update(n, newheadroom - oldheadroom);
1363
1364         return n;
1365 }
1366 EXPORT_SYMBOL(skb_copy_expand);
1367
1368 /**
1369  *      skb_pad                 -       zero pad the tail of an skb
1370  *      @skb: buffer to pad
1371  *      @pad: space to pad
1372  *
1373  *      Ensure that a buffer is followed by a padding area that is zero
1374  *      filled. Used by network drivers which may DMA or transfer data
1375  *      beyond the buffer end onto the wire.
1376  *
1377  *      May return error in out of memory cases. The skb is freed on error.
1378  */
1379
1380 int skb_pad(struct sk_buff *skb, int pad)
1381 {
1382         int err;
1383         int ntail;
1384
1385         /* If the skbuff is non linear tailroom is always zero.. */
1386         if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1387                 memset(skb->data+skb->len, 0, pad);
1388                 return 0;
1389         }
1390
1391         ntail = skb->data_len + pad - (skb->end - skb->tail);
1392         if (likely(skb_cloned(skb) || ntail > 0)) {
1393                 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1394                 if (unlikely(err))
1395                         goto free_skb;
1396         }
1397
1398         /* FIXME: The use of this function with non-linear skb's really needs
1399          * to be audited.
1400          */
1401         err = skb_linearize(skb);
1402         if (unlikely(err))
1403                 goto free_skb;
1404
1405         memset(skb->data + skb->len, 0, pad);
1406         return 0;
1407
1408 free_skb:
1409         kfree_skb(skb);
1410         return err;
1411 }
1412 EXPORT_SYMBOL(skb_pad);
1413
1414 /**
1415  *      pskb_put - add data to the tail of a potentially fragmented buffer
1416  *      @skb: start of the buffer to use
1417  *      @tail: tail fragment of the buffer to use
1418  *      @len: amount of data to add
1419  *
1420  *      This function extends the used data area of the potentially
1421  *      fragmented buffer. @tail must be the last fragment of @skb -- or
1422  *      @skb itself. If this would exceed the total buffer size the kernel
1423  *      will panic. A pointer to the first byte of the extra data is
1424  *      returned.
1425  */
1426
1427 unsigned char *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1428 {
1429         if (tail != skb) {
1430                 skb->data_len += len;
1431                 skb->len += len;
1432         }
1433         return skb_put(tail, len);
1434 }
1435 EXPORT_SYMBOL_GPL(pskb_put);
1436
1437 /**
1438  *      skb_put - add data to a buffer
1439  *      @skb: buffer to use
1440  *      @len: amount of data to add
1441  *
1442  *      This function extends the used data area of the buffer. If this would
1443  *      exceed the total buffer size the kernel will panic. A pointer to the
1444  *      first byte of the extra data is returned.
1445  */
1446 unsigned char *skb_put(struct sk_buff *skb, unsigned int len)
1447 {
1448         unsigned char *tmp = skb_tail_pointer(skb);
1449         SKB_LINEAR_ASSERT(skb);
1450         skb->tail += len;
1451         skb->len  += len;
1452         if (unlikely(skb->tail > skb->end))
1453                 skb_over_panic(skb, len, __builtin_return_address(0));
1454         return tmp;
1455 }
1456 EXPORT_SYMBOL(skb_put);
1457
1458 /**
1459  *      skb_push - add data to the start of a buffer
1460  *      @skb: buffer to use
1461  *      @len: amount of data to add
1462  *
1463  *      This function extends the used data area of the buffer at the buffer
1464  *      start. If this would exceed the total buffer headroom the kernel will
1465  *      panic. A pointer to the first byte of the extra data is returned.
1466  */
1467 unsigned char *skb_push(struct sk_buff *skb, unsigned int len)
1468 {
1469         skb->data -= len;
1470         skb->len  += len;
1471         if (unlikely(skb->data<skb->head))
1472                 skb_under_panic(skb, len, __builtin_return_address(0));
1473         return skb->data;
1474 }
1475 EXPORT_SYMBOL(skb_push);
1476
1477 /**
1478  *      skb_pull - remove data from the start of a buffer
1479  *      @skb: buffer to use
1480  *      @len: amount of data to remove
1481  *
1482  *      This function removes data from the start of a buffer, returning
1483  *      the memory to the headroom. A pointer to the next data in the buffer
1484  *      is returned. Once the data has been pulled future pushes will overwrite
1485  *      the old data.
1486  */
1487 unsigned char *skb_pull(struct sk_buff *skb, unsigned int len)
1488 {
1489         return skb_pull_inline(skb, len);
1490 }
1491 EXPORT_SYMBOL(skb_pull);
1492
1493 /**
1494  *      skb_trim - remove end from a buffer
1495  *      @skb: buffer to alter
1496  *      @len: new length
1497  *
1498  *      Cut the length of a buffer down by removing data from the tail. If
1499  *      the buffer is already under the length specified it is not modified.
1500  *      The skb must be linear.
1501  */
1502 void skb_trim(struct sk_buff *skb, unsigned int len)
1503 {
1504         if (skb->len > len)
1505                 __skb_trim(skb, len);
1506 }
1507 EXPORT_SYMBOL(skb_trim);
1508
1509 /* Trims skb to length len. It can change skb pointers.
1510  */
1511
1512 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
1513 {
1514         struct sk_buff **fragp;
1515         struct sk_buff *frag;
1516         int offset = skb_headlen(skb);
1517         int nfrags = skb_shinfo(skb)->nr_frags;
1518         int i;
1519         int err;
1520
1521         if (skb_cloned(skb) &&
1522             unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
1523                 return err;
1524
1525         i = 0;
1526         if (offset >= len)
1527                 goto drop_pages;
1528
1529         for (; i < nfrags; i++) {
1530                 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
1531
1532                 if (end < len) {
1533                         offset = end;
1534                         continue;
1535                 }
1536
1537                 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
1538
1539 drop_pages:
1540                 skb_shinfo(skb)->nr_frags = i;
1541
1542                 for (; i < nfrags; i++)
1543                         skb_frag_unref(skb, i);
1544
1545                 if (skb_has_frag_list(skb))
1546                         skb_drop_fraglist(skb);
1547                 goto done;
1548         }
1549
1550         for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
1551              fragp = &frag->next) {
1552                 int end = offset + frag->len;
1553
1554                 if (skb_shared(frag)) {
1555                         struct sk_buff *nfrag;
1556
1557                         nfrag = skb_clone(frag, GFP_ATOMIC);
1558                         if (unlikely(!nfrag))
1559                                 return -ENOMEM;
1560
1561                         nfrag->next = frag->next;
1562                         consume_skb(frag);
1563                         frag = nfrag;
1564                         *fragp = frag;
1565                 }
1566
1567                 if (end < len) {
1568                         offset = end;
1569                         continue;
1570                 }
1571
1572                 if (end > len &&
1573                     unlikely((err = pskb_trim(frag, len - offset))))
1574                         return err;
1575
1576                 if (frag->next)
1577                         skb_drop_list(&frag->next);
1578                 break;
1579         }
1580
1581 done:
1582         if (len > skb_headlen(skb)) {
1583                 skb->data_len -= skb->len - len;
1584                 skb->len       = len;
1585         } else {
1586                 skb->len       = len;
1587                 skb->data_len  = 0;
1588                 skb_set_tail_pointer(skb, len);
1589         }
1590
1591         return 0;
1592 }
1593 EXPORT_SYMBOL(___pskb_trim);
1594
1595 /* Note : use pskb_trim_rcsum() instead of calling this directly
1596  */
1597 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
1598 {
1599         if (skb->ip_summed == CHECKSUM_COMPLETE) {
1600                 int delta = skb->len - len;
1601
1602                 skb->csum = csum_block_sub(skb->csum,
1603                                            skb_checksum(skb, len, delta, 0),
1604                                            len);
1605         } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
1606                 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
1607                 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
1608
1609                 if (offset + sizeof(__sum16) > hdlen)
1610                         return -EINVAL;
1611         }
1612         return __pskb_trim(skb, len);
1613 }
1614 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
1615
1616 /**
1617  *      __pskb_pull_tail - advance tail of skb header
1618  *      @skb: buffer to reallocate
1619  *      @delta: number of bytes to advance tail
1620  *
1621  *      The function makes a sense only on a fragmented &sk_buff,
1622  *      it expands header moving its tail forward and copying necessary
1623  *      data from fragmented part.
1624  *
1625  *      &sk_buff MUST have reference count of 1.
1626  *
1627  *      Returns %NULL (and &sk_buff does not change) if pull failed
1628  *      or value of new tail of skb in the case of success.
1629  *
1630  *      All the pointers pointing into skb header may change and must be
1631  *      reloaded after call to this function.
1632  */
1633
1634 /* Moves tail of skb head forward, copying data from fragmented part,
1635  * when it is necessary.
1636  * 1. It may fail due to malloc failure.
1637  * 2. It may change skb pointers.
1638  *
1639  * It is pretty complicated. Luckily, it is called only in exceptional cases.
1640  */
1641 unsigned char *__pskb_pull_tail(struct sk_buff *skb, int delta)
1642 {
1643         /* If skb has not enough free space at tail, get new one
1644          * plus 128 bytes for future expansions. If we have enough
1645          * room at tail, reallocate without expansion only if skb is cloned.
1646          */
1647         int i, k, eat = (skb->tail + delta) - skb->end;
1648
1649         if (eat > 0 || skb_cloned(skb)) {
1650                 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
1651                                      GFP_ATOMIC))
1652                         return NULL;
1653         }
1654
1655         if (skb_copy_bits(skb, skb_headlen(skb), skb_tail_pointer(skb), delta))
1656                 BUG();
1657
1658         /* Optimization: no fragments, no reasons to preestimate
1659          * size of pulled pages. Superb.
1660          */
1661         if (!skb_has_frag_list(skb))
1662                 goto pull_pages;
1663
1664         /* Estimate size of pulled pages. */
1665         eat = delta;
1666         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1667                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1668
1669                 if (size >= eat)
1670                         goto pull_pages;
1671                 eat -= size;
1672         }
1673
1674         /* If we need update frag list, we are in troubles.
1675          * Certainly, it possible to add an offset to skb data,
1676          * but taking into account that pulling is expected to
1677          * be very rare operation, it is worth to fight against
1678          * further bloating skb head and crucify ourselves here instead.
1679          * Pure masohism, indeed. 8)8)
1680          */
1681         if (eat) {
1682                 struct sk_buff *list = skb_shinfo(skb)->frag_list;
1683                 struct sk_buff *clone = NULL;
1684                 struct sk_buff *insp = NULL;
1685
1686                 do {
1687                         BUG_ON(!list);
1688
1689                         if (list->len <= eat) {
1690                                 /* Eaten as whole. */
1691                                 eat -= list->len;
1692                                 list = list->next;
1693                                 insp = list;
1694                         } else {
1695                                 /* Eaten partially. */
1696
1697                                 if (skb_shared(list)) {
1698                                         /* Sucks! We need to fork list. :-( */
1699                                         clone = skb_clone(list, GFP_ATOMIC);
1700                                         if (!clone)
1701                                                 return NULL;
1702                                         insp = list->next;
1703                                         list = clone;
1704                                 } else {
1705                                         /* This may be pulled without
1706                                          * problems. */
1707                                         insp = list;
1708                                 }
1709                                 if (!pskb_pull(list, eat)) {
1710                                         kfree_skb(clone);
1711                                         return NULL;
1712                                 }
1713                                 break;
1714                         }
1715                 } while (eat);
1716
1717                 /* Free pulled out fragments. */
1718                 while ((list = skb_shinfo(skb)->frag_list) != insp) {
1719                         skb_shinfo(skb)->frag_list = list->next;
1720                         consume_skb(list);
1721                 }
1722                 /* And insert new clone at head. */
1723                 if (clone) {
1724                         clone->next = list;
1725                         skb_shinfo(skb)->frag_list = clone;
1726                 }
1727         }
1728         /* Success! Now we may commit changes to skb data. */
1729
1730 pull_pages:
1731         eat = delta;
1732         k = 0;
1733         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1734                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
1735
1736                 if (size <= eat) {
1737                         skb_frag_unref(skb, i);
1738                         eat -= size;
1739                 } else {
1740                         skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i];
1741                         if (eat) {
1742                                 skb_shinfo(skb)->frags[k].page_offset += eat;
1743                                 skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat);
1744                                 eat = 0;
1745                         }
1746                         k++;
1747                 }
1748         }
1749         skb_shinfo(skb)->nr_frags = k;
1750
1751         skb->tail     += delta;
1752         skb->data_len -= delta;
1753
1754         return skb_tail_pointer(skb);
1755 }
1756 EXPORT_SYMBOL(__pskb_pull_tail);
1757
1758 /**
1759  *      skb_copy_bits - copy bits from skb to kernel buffer
1760  *      @skb: source skb
1761  *      @offset: offset in source
1762  *      @to: destination buffer
1763  *      @len: number of bytes to copy
1764  *
1765  *      Copy the specified number of bytes from the source skb to the
1766  *      destination buffer.
1767  *
1768  *      CAUTION ! :
1769  *              If its prototype is ever changed,
1770  *              check arch/{*}/net/{*}.S files,
1771  *              since it is called from BPF assembly code.
1772  */
1773 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
1774 {
1775         int start = skb_headlen(skb);
1776         struct sk_buff *frag_iter;
1777         int i, copy;
1778
1779         if (offset > (int)skb->len - len)
1780                 goto fault;
1781
1782         /* Copy header. */
1783         if ((copy = start - offset) > 0) {
1784                 if (copy > len)
1785                         copy = len;
1786                 skb_copy_from_linear_data_offset(skb, offset, to, copy);
1787                 if ((len -= copy) == 0)
1788                         return 0;
1789                 offset += copy;
1790                 to     += copy;
1791         }
1792
1793         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1794                 int end;
1795                 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1796
1797                 WARN_ON(start > offset + len);
1798
1799                 end = start + skb_frag_size(f);
1800                 if ((copy = end - offset) > 0) {
1801                         u8 *vaddr;
1802
1803                         if (copy > len)
1804                                 copy = len;
1805
1806                         vaddr = kmap_atomic(skb_frag_page(f));
1807                         memcpy(to,
1808                                vaddr + f->page_offset + offset - start,
1809                                copy);
1810                         kunmap_atomic(vaddr);
1811
1812                         if ((len -= copy) == 0)
1813                                 return 0;
1814                         offset += copy;
1815                         to     += copy;
1816                 }
1817                 start = end;
1818         }
1819
1820         skb_walk_frags(skb, frag_iter) {
1821                 int end;
1822
1823                 WARN_ON(start > offset + len);
1824
1825                 end = start + frag_iter->len;
1826                 if ((copy = end - offset) > 0) {
1827                         if (copy > len)
1828                                 copy = len;
1829                         if (skb_copy_bits(frag_iter, offset - start, to, copy))
1830                                 goto fault;
1831                         if ((len -= copy) == 0)
1832                                 return 0;
1833                         offset += copy;
1834                         to     += copy;
1835                 }
1836                 start = end;
1837         }
1838
1839         if (!len)
1840                 return 0;
1841
1842 fault:
1843         return -EFAULT;
1844 }
1845 EXPORT_SYMBOL(skb_copy_bits);
1846
1847 /*
1848  * Callback from splice_to_pipe(), if we need to release some pages
1849  * at the end of the spd in case we error'ed out in filling the pipe.
1850  */
1851 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
1852 {
1853         put_page(spd->pages[i]);
1854 }
1855
1856 static struct page *linear_to_page(struct page *page, unsigned int *len,
1857                                    unsigned int *offset,
1858                                    struct sock *sk)
1859 {
1860         struct page_frag *pfrag = sk_page_frag(sk);
1861
1862         if (!sk_page_frag_refill(sk, pfrag))
1863                 return NULL;
1864
1865         *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
1866
1867         memcpy(page_address(pfrag->page) + pfrag->offset,
1868                page_address(page) + *offset, *len);
1869         *offset = pfrag->offset;
1870         pfrag->offset += *len;
1871
1872         return pfrag->page;
1873 }
1874
1875 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
1876                              struct page *page,
1877                              unsigned int offset)
1878 {
1879         return  spd->nr_pages &&
1880                 spd->pages[spd->nr_pages - 1] == page &&
1881                 (spd->partial[spd->nr_pages - 1].offset +
1882                  spd->partial[spd->nr_pages - 1].len == offset);
1883 }
1884
1885 /*
1886  * Fill page/offset/length into spd, if it can hold more pages.
1887  */
1888 static bool spd_fill_page(struct splice_pipe_desc *spd,
1889                           struct pipe_inode_info *pipe, struct page *page,
1890                           unsigned int *len, unsigned int offset,
1891                           bool linear,
1892                           struct sock *sk)
1893 {
1894         if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
1895                 return true;
1896
1897         if (linear) {
1898                 page = linear_to_page(page, len, &offset, sk);
1899                 if (!page)
1900                         return true;
1901         }
1902         if (spd_can_coalesce(spd, page, offset)) {
1903                 spd->partial[spd->nr_pages - 1].len += *len;
1904                 return false;
1905         }
1906         get_page(page);
1907         spd->pages[spd->nr_pages] = page;
1908         spd->partial[spd->nr_pages].len = *len;
1909         spd->partial[spd->nr_pages].offset = offset;
1910         spd->nr_pages++;
1911
1912         return false;
1913 }
1914
1915 static bool __splice_segment(struct page *page, unsigned int poff,
1916                              unsigned int plen, unsigned int *off,
1917                              unsigned int *len,
1918                              struct splice_pipe_desc *spd, bool linear,
1919                              struct sock *sk,
1920                              struct pipe_inode_info *pipe)
1921 {
1922         if (!*len)
1923                 return true;
1924
1925         /* skip this segment if already processed */
1926         if (*off >= plen) {
1927                 *off -= plen;
1928                 return false;
1929         }
1930
1931         /* ignore any bits we already processed */
1932         poff += *off;
1933         plen -= *off;
1934         *off = 0;
1935
1936         do {
1937                 unsigned int flen = min(*len, plen);
1938
1939                 if (spd_fill_page(spd, pipe, page, &flen, poff,
1940                                   linear, sk))
1941                         return true;
1942                 poff += flen;
1943                 plen -= flen;
1944                 *len -= flen;
1945         } while (*len && plen);
1946
1947         return false;
1948 }
1949
1950 /*
1951  * Map linear and fragment data from the skb to spd. It reports true if the
1952  * pipe is full or if we already spliced the requested length.
1953  */
1954 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
1955                               unsigned int *offset, unsigned int *len,
1956                               struct splice_pipe_desc *spd, struct sock *sk)
1957 {
1958         int seg;
1959         struct sk_buff *iter;
1960
1961         /* map the linear part :
1962          * If skb->head_frag is set, this 'linear' part is backed by a
1963          * fragment, and if the head is not shared with any clones then
1964          * we can avoid a copy since we own the head portion of this page.
1965          */
1966         if (__splice_segment(virt_to_page(skb->data),
1967                              (unsigned long) skb->data & (PAGE_SIZE - 1),
1968                              skb_headlen(skb),
1969                              offset, len, spd,
1970                              skb_head_is_locked(skb),
1971                              sk, pipe))
1972                 return true;
1973
1974         /*
1975          * then map the fragments
1976          */
1977         for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
1978                 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
1979
1980                 if (__splice_segment(skb_frag_page(f),
1981                                      f->page_offset, skb_frag_size(f),
1982                                      offset, len, spd, false, sk, pipe))
1983                         return true;
1984         }
1985
1986         skb_walk_frags(skb, iter) {
1987                 if (*offset >= iter->len) {
1988                         *offset -= iter->len;
1989                         continue;
1990                 }
1991                 /* __skb_splice_bits() only fails if the output has no room
1992                  * left, so no point in going over the frag_list for the error
1993                  * case.
1994                  */
1995                 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
1996                         return true;
1997         }
1998
1999         return false;
2000 }
2001
2002 /*
2003  * Map data from the skb to a pipe. Should handle both the linear part,
2004  * the fragments, and the frag list.
2005  */
2006 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2007                     struct pipe_inode_info *pipe, unsigned int tlen,
2008                     unsigned int flags)
2009 {
2010         struct partial_page partial[MAX_SKB_FRAGS];
2011         struct page *pages[MAX_SKB_FRAGS];
2012         struct splice_pipe_desc spd = {
2013                 .pages = pages,
2014                 .partial = partial,
2015                 .nr_pages_max = MAX_SKB_FRAGS,
2016                 .flags = flags,
2017                 .ops = &nosteal_pipe_buf_ops,
2018                 .spd_release = sock_spd_release,
2019         };
2020         int ret = 0;
2021
2022         __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2023
2024         if (spd.nr_pages)
2025                 ret = splice_to_pipe(pipe, &spd);
2026
2027         return ret;
2028 }
2029 EXPORT_SYMBOL_GPL(skb_splice_bits);
2030
2031 /**
2032  *      skb_store_bits - store bits from kernel buffer to skb
2033  *      @skb: destination buffer
2034  *      @offset: offset in destination
2035  *      @from: source buffer
2036  *      @len: number of bytes to copy
2037  *
2038  *      Copy the specified number of bytes from the source buffer to the
2039  *      destination skb.  This function handles all the messy bits of
2040  *      traversing fragment lists and such.
2041  */
2042
2043 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2044 {
2045         int start = skb_headlen(skb);
2046         struct sk_buff *frag_iter;
2047         int i, copy;
2048
2049         if (offset > (int)skb->len - len)
2050                 goto fault;
2051
2052         if ((copy = start - offset) > 0) {
2053                 if (copy > len)
2054                         copy = len;
2055                 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2056                 if ((len -= copy) == 0)
2057                         return 0;
2058                 offset += copy;
2059                 from += copy;
2060         }
2061
2062         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2063                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2064                 int end;
2065
2066                 WARN_ON(start > offset + len);
2067
2068                 end = start + skb_frag_size(frag);
2069                 if ((copy = end - offset) > 0) {
2070                         u8 *vaddr;
2071
2072                         if (copy > len)
2073                                 copy = len;
2074
2075                         vaddr = kmap_atomic(skb_frag_page(frag));
2076                         memcpy(vaddr + frag->page_offset + offset - start,
2077                                from, copy);
2078                         kunmap_atomic(vaddr);
2079
2080                         if ((len -= copy) == 0)
2081                                 return 0;
2082                         offset += copy;
2083                         from += copy;
2084                 }
2085                 start = end;
2086         }
2087
2088         skb_walk_frags(skb, frag_iter) {
2089                 int end;
2090
2091                 WARN_ON(start > offset + len);
2092
2093                 end = start + frag_iter->len;
2094                 if ((copy = end - offset) > 0) {
2095                         if (copy > len)
2096                                 copy = len;
2097                         if (skb_store_bits(frag_iter, offset - start,
2098                                            from, copy))
2099                                 goto fault;
2100                         if ((len -= copy) == 0)
2101                                 return 0;
2102                         offset += copy;
2103                         from += copy;
2104                 }
2105                 start = end;
2106         }
2107         if (!len)
2108                 return 0;
2109
2110 fault:
2111         return -EFAULT;
2112 }
2113 EXPORT_SYMBOL(skb_store_bits);
2114
2115 /* Checksum skb data. */
2116 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2117                       __wsum csum, const struct skb_checksum_ops *ops)
2118 {
2119         int start = skb_headlen(skb);
2120         int i, copy = start - offset;
2121         struct sk_buff *frag_iter;
2122         int pos = 0;
2123
2124         /* Checksum header. */
2125         if (copy > 0) {
2126                 if (copy > len)
2127                         copy = len;
2128                 csum = ops->update(skb->data + offset, copy, csum);
2129                 if ((len -= copy) == 0)
2130                         return csum;
2131                 offset += copy;
2132                 pos     = copy;
2133         }
2134
2135         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2136                 int end;
2137                 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2138
2139                 WARN_ON(start > offset + len);
2140
2141                 end = start + skb_frag_size(frag);
2142                 if ((copy = end - offset) > 0) {
2143                         __wsum csum2;
2144                         u8 *vaddr;
2145
2146                         if (copy > len)
2147                                 copy = len;
2148                         vaddr = kmap_atomic(skb_frag_page(frag));
2149                         csum2 = ops->update(vaddr + frag->page_offset +
2150                                             offset - start, copy, 0);
2151                         kunmap_atomic(vaddr);
2152                         csum = ops->combine(csum, csum2, pos, copy);
2153                         if (!(len -= copy))
2154                                 return csum;
2155                         offset += copy;
2156                         pos    += copy;
2157                 }
2158                 start = end;
2159         }
2160
2161         skb_walk_frags(skb, frag_iter) {
2162                 int end;
2163
2164                 WARN_ON(start > offset + len);
2165
2166                 end = start + frag_iter->len;
2167                 if ((copy = end - offset) > 0) {
2168                         __wsum csum2;
2169                         if (copy > len)
2170                                 copy = len;
2171                         csum2 = __skb_checksum(frag_iter, offset - start,
2172                                                copy, 0, ops);
2173                         csum = ops->combine(csum, csum2, pos, copy);
2174                         if ((len -= copy) == 0)
2175                                 return csum;
2176                         offset += copy;
2177                         pos    += copy;
2178                 }
2179                 start = end;
2180         }
2181         BUG_ON(len);
2182
2183         return csum;
2184 }
2185 EXPORT_SYMBOL(__skb_checksum);
2186
2187 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2188                     int len, __wsum csum)
2189 {
2190         const struct skb_checksum_ops ops = {
2191                 .update  = csum_partial_ext,
2192                 .combine = csum_block_add_ext,
2193         };
2194
2195         return __skb_checksum(skb, offset, len, csum, &ops);
2196 }
2197 EXPORT_SYMBOL(skb_checksum);
2198
2199 /* Both of above in one bottle. */
2200
2201 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2202                                     u8 *to, int len, __wsum csum)
2203 {
2204         int start = skb_headlen(skb);
2205         int i, copy = start - offset;
2206         struct sk_buff *frag_iter;
2207         int pos = 0;
2208
2209         /* Copy header. */
2210         if (copy > 0) {
2211                 if (copy > len)
2212                         copy = len;
2213                 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2214                                                  copy, csum);
2215                 if ((len -= copy) == 0)
2216                         return csum;
2217                 offset += copy;
2218                 to     += copy;
2219                 pos     = copy;
2220         }
2221
2222         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2223                 int end;
2224
2225                 WARN_ON(start > offset + len);
2226
2227                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2228                 if ((copy = end - offset) > 0) {
2229                         __wsum csum2;
2230                         u8 *vaddr;
2231                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2232
2233                         if (copy > len)
2234                                 copy = len;
2235                         vaddr = kmap_atomic(skb_frag_page(frag));
2236                         csum2 = csum_partial_copy_nocheck(vaddr +
2237                                                           frag->page_offset +
2238                                                           offset - start, to,
2239                                                           copy, 0);
2240                         kunmap_atomic(vaddr);
2241                         csum = csum_block_add(csum, csum2, pos);
2242                         if (!(len -= copy))
2243                                 return csum;
2244                         offset += copy;
2245                         to     += copy;
2246                         pos    += copy;
2247                 }
2248                 start = end;
2249         }
2250
2251         skb_walk_frags(skb, frag_iter) {
2252                 __wsum csum2;
2253                 int end;
2254
2255                 WARN_ON(start > offset + len);
2256
2257                 end = start + frag_iter->len;
2258                 if ((copy = end - offset) > 0) {
2259                         if (copy > len)
2260                                 copy = len;
2261                         csum2 = skb_copy_and_csum_bits(frag_iter,
2262                                                        offset - start,
2263                                                        to, copy, 0);
2264                         csum = csum_block_add(csum, csum2, pos);
2265                         if ((len -= copy) == 0)
2266                                 return csum;
2267                         offset += copy;
2268                         to     += copy;
2269                         pos    += copy;
2270                 }
2271                 start = end;
2272         }
2273         BUG_ON(len);
2274         return csum;
2275 }
2276 EXPORT_SYMBOL(skb_copy_and_csum_bits);
2277
2278  /**
2279  *      skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
2280  *      @from: source buffer
2281  *
2282  *      Calculates the amount of linear headroom needed in the 'to' skb passed
2283  *      into skb_zerocopy().
2284  */
2285 unsigned int
2286 skb_zerocopy_headlen(const struct sk_buff *from)
2287 {
2288         unsigned int hlen = 0;
2289
2290         if (!from->head_frag ||
2291             skb_headlen(from) < L1_CACHE_BYTES ||
2292             skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
2293                 hlen = skb_headlen(from);
2294                 if (!hlen)
2295                         hlen = from->len;
2296         }
2297
2298         if (skb_has_frag_list(from))
2299                 hlen = from->len;
2300
2301         return hlen;
2302 }
2303 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
2304
2305 /**
2306  *      skb_zerocopy - Zero copy skb to skb
2307  *      @to: destination buffer
2308  *      @from: source buffer
2309  *      @len: number of bytes to copy from source buffer
2310  *      @hlen: size of linear headroom in destination buffer
2311  *
2312  *      Copies up to `len` bytes from `from` to `to` by creating references
2313  *      to the frags in the source buffer.
2314  *
2315  *      The `hlen` as calculated by skb_zerocopy_headlen() specifies the
2316  *      headroom in the `to` buffer.
2317  *
2318  *      Return value:
2319  *      0: everything is OK
2320  *      -ENOMEM: couldn't orphan frags of @from due to lack of memory
2321  *      -EFAULT: skb_copy_bits() found some problem with skb geometry
2322  */
2323 int
2324 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
2325 {
2326         int i, j = 0;
2327         int plen = 0; /* length of skb->head fragment */
2328         int ret;
2329         struct page *page;
2330         unsigned int offset;
2331
2332         BUG_ON(!from->head_frag && !hlen);
2333
2334         /* dont bother with small payloads */
2335         if (len <= skb_tailroom(to))
2336                 return skb_copy_bits(from, 0, skb_put(to, len), len);
2337
2338         if (hlen) {
2339                 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
2340                 if (unlikely(ret))
2341                         return ret;
2342                 len -= hlen;
2343         } else {
2344                 plen = min_t(int, skb_headlen(from), len);
2345                 if (plen) {
2346                         page = virt_to_head_page(from->head);
2347                         offset = from->data - (unsigned char *)page_address(page);
2348                         __skb_fill_page_desc(to, 0, page, offset, plen);
2349                         get_page(page);
2350                         j = 1;
2351                         len -= plen;
2352                 }
2353         }
2354
2355         to->truesize += len + plen;
2356         to->len += len + plen;
2357         to->data_len += len + plen;
2358
2359         if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
2360                 skb_tx_error(from);
2361                 return -ENOMEM;
2362         }
2363
2364         for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
2365                 if (!len)
2366                         break;
2367                 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
2368                 skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
2369                 len -= skb_shinfo(to)->frags[j].size;
2370                 skb_frag_ref(to, j);
2371                 j++;
2372         }
2373         skb_shinfo(to)->nr_frags = j;
2374
2375         return 0;
2376 }
2377 EXPORT_SYMBOL_GPL(skb_zerocopy);
2378
2379 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
2380 {
2381         __wsum csum;
2382         long csstart;
2383
2384         if (skb->ip_summed == CHECKSUM_PARTIAL)
2385                 csstart = skb_checksum_start_offset(skb);
2386         else
2387                 csstart = skb_headlen(skb);
2388
2389         BUG_ON(csstart > skb_headlen(skb));
2390
2391         skb_copy_from_linear_data(skb, to, csstart);
2392
2393         csum = 0;
2394         if (csstart != skb->len)
2395                 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
2396                                               skb->len - csstart, 0);
2397
2398         if (skb->ip_summed == CHECKSUM_PARTIAL) {
2399                 long csstuff = csstart + skb->csum_offset;
2400
2401                 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
2402         }
2403 }
2404 EXPORT_SYMBOL(skb_copy_and_csum_dev);
2405
2406 /**
2407  *      skb_dequeue - remove from the head of the queue
2408  *      @list: list to dequeue from
2409  *
2410  *      Remove the head of the list. The list lock is taken so the function
2411  *      may be used safely with other locking list functions. The head item is
2412  *      returned or %NULL if the list is empty.
2413  */
2414
2415 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
2416 {
2417         unsigned long flags;
2418         struct sk_buff *result;
2419
2420         spin_lock_irqsave(&list->lock, flags);
2421         result = __skb_dequeue(list);
2422         spin_unlock_irqrestore(&list->lock, flags);
2423         return result;
2424 }
2425 EXPORT_SYMBOL(skb_dequeue);
2426
2427 /**
2428  *      skb_dequeue_tail - remove from the tail of the queue
2429  *      @list: list to dequeue from
2430  *
2431  *      Remove the tail of the list. The list lock is taken so the function
2432  *      may be used safely with other locking list functions. The tail item is
2433  *      returned or %NULL if the list is empty.
2434  */
2435 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
2436 {
2437         unsigned long flags;
2438         struct sk_buff *result;
2439
2440         spin_lock_irqsave(&list->lock, flags);
2441         result = __skb_dequeue_tail(list);
2442         spin_unlock_irqrestore(&list->lock, flags);
2443         return result;
2444 }
2445 EXPORT_SYMBOL(skb_dequeue_tail);
2446
2447 /**
2448  *      skb_queue_purge - empty a list
2449  *      @list: list to empty
2450  *
2451  *      Delete all buffers on an &sk_buff list. Each buffer is removed from
2452  *      the list and one reference dropped. This function takes the list
2453  *      lock and is atomic with respect to other list locking functions.
2454  */
2455 void skb_queue_purge(struct sk_buff_head *list)
2456 {
2457         struct sk_buff *skb;
2458         while ((skb = skb_dequeue(list)) != NULL)
2459                 kfree_skb(skb);
2460 }
2461 EXPORT_SYMBOL(skb_queue_purge);
2462
2463 /**
2464  *      skb_rbtree_purge - empty a skb rbtree
2465  *      @root: root of the rbtree to empty
2466  *      Return value: the sum of truesizes of all purged skbs.
2467  *
2468  *      Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
2469  *      the list and one reference dropped. This function does not take
2470  *      any lock. Synchronization should be handled by the caller (e.g., TCP
2471  *      out-of-order queue is protected by the socket lock).
2472  */
2473 unsigned int skb_rbtree_purge(struct rb_root *root)
2474 {
2475         struct rb_node *p = rb_first(root);
2476         unsigned int sum = 0;
2477
2478         while (p) {
2479                 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
2480
2481                 p = rb_next(p);
2482                 rb_erase(&skb->rbnode, root);
2483                 sum += skb->truesize;
2484                 kfree_skb(skb);
2485         }
2486         return sum;
2487 }
2488
2489 /**
2490  *      skb_queue_head - queue a buffer at the list head
2491  *      @list: list to use
2492  *      @newsk: buffer to queue
2493  *
2494  *      Queue a buffer at the start of the list. This function takes the
2495  *      list lock and can be used safely with other locking &sk_buff functions
2496  *      safely.
2497  *
2498  *      A buffer cannot be placed on two lists at the same time.
2499  */
2500 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
2501 {
2502         unsigned long flags;
2503
2504         spin_lock_irqsave(&list->lock, flags);
2505         __skb_queue_head(list, newsk);
2506         spin_unlock_irqrestore(&list->lock, flags);
2507 }
2508 EXPORT_SYMBOL(skb_queue_head);
2509
2510 /**
2511  *      skb_queue_tail - queue a buffer at the list tail
2512  *      @list: list to use
2513  *      @newsk: buffer to queue
2514  *
2515  *      Queue a buffer at the tail of the list. This function takes the
2516  *      list lock and can be used safely with other locking &sk_buff functions
2517  *      safely.
2518  *
2519  *      A buffer cannot be placed on two lists at the same time.
2520  */
2521 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
2522 {
2523         unsigned long flags;
2524
2525         spin_lock_irqsave(&list->lock, flags);
2526         __skb_queue_tail(list, newsk);
2527         spin_unlock_irqrestore(&list->lock, flags);
2528 }
2529 EXPORT_SYMBOL(skb_queue_tail);
2530
2531 /**
2532  *      skb_unlink      -       remove a buffer from a list
2533  *      @skb: buffer to remove
2534  *      @list: list to use
2535  *
2536  *      Remove a packet from a list. The list locks are taken and this
2537  *      function is atomic with respect to other list locked calls
2538  *
2539  *      You must know what list the SKB is on.
2540  */
2541 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
2542 {
2543         unsigned long flags;
2544
2545         spin_lock_irqsave(&list->lock, flags);
2546         __skb_unlink(skb, list);
2547         spin_unlock_irqrestore(&list->lock, flags);
2548 }
2549 EXPORT_SYMBOL(skb_unlink);
2550
2551 /**
2552  *      skb_append      -       append a buffer
2553  *      @old: buffer to insert after
2554  *      @newsk: buffer to insert
2555  *      @list: list to use
2556  *
2557  *      Place a packet after a given packet in a list. The list locks are taken
2558  *      and this function is atomic with respect to other list locked calls.
2559  *      A buffer cannot be placed on two lists at the same time.
2560  */
2561 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2562 {
2563         unsigned long flags;
2564
2565         spin_lock_irqsave(&list->lock, flags);
2566         __skb_queue_after(list, old, newsk);
2567         spin_unlock_irqrestore(&list->lock, flags);
2568 }
2569 EXPORT_SYMBOL(skb_append);
2570
2571 /**
2572  *      skb_insert      -       insert a buffer
2573  *      @old: buffer to insert before
2574  *      @newsk: buffer to insert
2575  *      @list: list to use
2576  *
2577  *      Place a packet before a given packet in a list. The list locks are
2578  *      taken and this function is atomic with respect to other list locked
2579  *      calls.
2580  *
2581  *      A buffer cannot be placed on two lists at the same time.
2582  */
2583 void skb_insert(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
2584 {
2585         unsigned long flags;
2586
2587         spin_lock_irqsave(&list->lock, flags);
2588         __skb_insert(newsk, old->prev, old, list);
2589         spin_unlock_irqrestore(&list->lock, flags);
2590 }
2591 EXPORT_SYMBOL(skb_insert);
2592
2593 static inline void skb_split_inside_header(struct sk_buff *skb,
2594                                            struct sk_buff* skb1,
2595                                            const u32 len, const int pos)
2596 {
2597         int i;
2598
2599         skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
2600                                          pos - len);
2601         /* And move data appendix as is. */
2602         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2603                 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
2604
2605         skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
2606         skb_shinfo(skb)->nr_frags  = 0;
2607         skb1->data_len             = skb->data_len;
2608         skb1->len                  += skb1->data_len;
2609         skb->data_len              = 0;
2610         skb->len                   = len;
2611         skb_set_tail_pointer(skb, len);
2612 }
2613
2614 static inline void skb_split_no_header(struct sk_buff *skb,
2615                                        struct sk_buff* skb1,
2616                                        const u32 len, int pos)
2617 {
2618         int i, k = 0;
2619         const int nfrags = skb_shinfo(skb)->nr_frags;
2620
2621         skb_shinfo(skb)->nr_frags = 0;
2622         skb1->len                 = skb1->data_len = skb->len - len;
2623         skb->len                  = len;
2624         skb->data_len             = len - pos;
2625
2626         for (i = 0; i < nfrags; i++) {
2627                 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2628
2629                 if (pos + size > len) {
2630                         skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
2631
2632                         if (pos < len) {
2633                                 /* Split frag.
2634                                  * We have two variants in this case:
2635                                  * 1. Move all the frag to the second
2636                                  *    part, if it is possible. F.e.
2637                                  *    this approach is mandatory for TUX,
2638                                  *    where splitting is expensive.
2639                                  * 2. Split is accurately. We make this.
2640                                  */
2641                                 skb_frag_ref(skb, i);
2642                                 skb_shinfo(skb1)->frags[0].page_offset += len - pos;
2643                                 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
2644                                 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
2645                                 skb_shinfo(skb)->nr_frags++;
2646                         }
2647                         k++;
2648                 } else
2649                         skb_shinfo(skb)->nr_frags++;
2650                 pos += size;
2651         }
2652         skb_shinfo(skb1)->nr_frags = k;
2653 }
2654
2655 /**
2656  * skb_split - Split fragmented skb to two parts at length len.
2657  * @skb: the buffer to split
2658  * @skb1: the buffer to receive the second part
2659  * @len: new length for skb
2660  */
2661 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
2662 {
2663         int pos = skb_headlen(skb);
2664
2665         skb_shinfo(skb1)->tx_flags |= skb_shinfo(skb)->tx_flags &
2666                                       SKBTX_SHARED_FRAG;
2667         if (len < pos)  /* Split line is inside header. */
2668                 skb_split_inside_header(skb, skb1, len, pos);
2669         else            /* Second chunk has no header, nothing to copy. */
2670                 skb_split_no_header(skb, skb1, len, pos);
2671 }
2672 EXPORT_SYMBOL(skb_split);
2673
2674 /* Shifting from/to a cloned skb is a no-go.
2675  *
2676  * Caller cannot keep skb_shinfo related pointers past calling here!
2677  */
2678 static int skb_prepare_for_shift(struct sk_buff *skb)
2679 {
2680         int ret = 0;
2681
2682         if (skb_cloned(skb)) {
2683                 /* Save and restore truesize: pskb_expand_head() may reallocate
2684                  * memory where ksize(kmalloc(S)) != ksize(kmalloc(S)), but we
2685                  * cannot change truesize at this point.
2686                  */
2687                 unsigned int save_truesize = skb->truesize;
2688
2689                 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
2690                 skb->truesize = save_truesize;
2691         }
2692         return ret;
2693 }
2694
2695 /**
2696  * skb_shift - Shifts paged data partially from skb to another
2697  * @tgt: buffer into which tail data gets added
2698  * @skb: buffer from which the paged data comes from
2699  * @shiftlen: shift up to this many bytes
2700  *
2701  * Attempts to shift up to shiftlen worth of bytes, which may be less than
2702  * the length of the skb, from skb to tgt. Returns number bytes shifted.
2703  * It's up to caller to free skb if everything was shifted.
2704  *
2705  * If @tgt runs out of frags, the whole operation is aborted.
2706  *
2707  * Skb cannot include anything else but paged data while tgt is allowed
2708  * to have non-paged data as well.
2709  *
2710  * TODO: full sized shift could be optimized but that would need
2711  * specialized skb free'er to handle frags without up-to-date nr_frags.
2712  */
2713 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
2714 {
2715         int from, to, merge, todo;
2716         struct skb_frag_struct *fragfrom, *fragto;
2717
2718         BUG_ON(shiftlen > skb->len);
2719         BUG_ON(skb_headlen(skb));       /* Would corrupt stream */
2720
2721         todo = shiftlen;
2722         from = 0;
2723         to = skb_shinfo(tgt)->nr_frags;
2724         fragfrom = &skb_shinfo(skb)->frags[from];
2725
2726         /* Actual merge is delayed until the point when we know we can
2727          * commit all, so that we don't have to undo partial changes
2728          */
2729         if (!to ||
2730             !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
2731                               fragfrom->page_offset)) {
2732                 merge = -1;
2733         } else {
2734                 merge = to - 1;
2735
2736                 todo -= skb_frag_size(fragfrom);
2737                 if (todo < 0) {
2738                         if (skb_prepare_for_shift(skb) ||
2739                             skb_prepare_for_shift(tgt))
2740                                 return 0;
2741
2742                         /* All previous frag pointers might be stale! */
2743                         fragfrom = &skb_shinfo(skb)->frags[from];
2744                         fragto = &skb_shinfo(tgt)->frags[merge];
2745
2746                         skb_frag_size_add(fragto, shiftlen);
2747                         skb_frag_size_sub(fragfrom, shiftlen);
2748                         fragfrom->page_offset += shiftlen;
2749
2750                         goto onlymerged;
2751                 }
2752
2753                 from++;
2754         }
2755
2756         /* Skip full, not-fitting skb to avoid expensive operations */
2757         if ((shiftlen == skb->len) &&
2758             (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
2759                 return 0;
2760
2761         if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
2762                 return 0;
2763
2764         while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
2765                 if (to == MAX_SKB_FRAGS)
2766                         return 0;
2767
2768                 fragfrom = &skb_shinfo(skb)->frags[from];
2769                 fragto = &skb_shinfo(tgt)->frags[to];
2770
2771                 if (todo >= skb_frag_size(fragfrom)) {
2772                         *fragto = *fragfrom;
2773                         todo -= skb_frag_size(fragfrom);
2774                         from++;
2775                         to++;
2776
2777                 } else {
2778                         __skb_frag_ref(fragfrom);
2779                         fragto->page = fragfrom->page;
2780                         fragto->page_offset = fragfrom->page_offset;
2781                         skb_frag_size_set(fragto, todo);
2782
2783                         fragfrom->page_offset += todo;
2784                         skb_frag_size_sub(fragfrom, todo);
2785                         todo = 0;
2786
2787                         to++;
2788                         break;
2789                 }
2790         }
2791
2792         /* Ready to "commit" this state change to tgt */
2793         skb_shinfo(tgt)->nr_frags = to;
2794
2795         if (merge >= 0) {
2796                 fragfrom = &skb_shinfo(skb)->frags[0];
2797                 fragto = &skb_shinfo(tgt)->frags[merge];
2798
2799                 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
2800                 __skb_frag_unref(fragfrom);
2801         }
2802
2803         /* Reposition in the original skb */
2804         to = 0;
2805         while (from < skb_shinfo(skb)->nr_frags)
2806                 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
2807         skb_shinfo(skb)->nr_frags = to;
2808
2809         BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
2810
2811 onlymerged:
2812         /* Most likely the tgt won't ever need its checksum anymore, skb on
2813          * the other hand might need it if it needs to be resent
2814          */
2815         tgt->ip_summed = CHECKSUM_PARTIAL;
2816         skb->ip_summed = CHECKSUM_PARTIAL;
2817
2818         /* Yak, is it really working this way? Some helper please? */
2819         skb->len -= shiftlen;
2820         skb->data_len -= shiftlen;
2821         skb->truesize -= shiftlen;
2822         tgt->len += shiftlen;
2823         tgt->data_len += shiftlen;
2824         tgt->truesize += shiftlen;
2825
2826         return shiftlen;
2827 }
2828
2829 /**
2830  * skb_prepare_seq_read - Prepare a sequential read of skb data
2831  * @skb: the buffer to read
2832  * @from: lower offset of data to be read
2833  * @to: upper offset of data to be read
2834  * @st: state variable
2835  *
2836  * Initializes the specified state variable. Must be called before
2837  * invoking skb_seq_read() for the first time.
2838  */
2839 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
2840                           unsigned int to, struct skb_seq_state *st)
2841 {
2842         st->lower_offset = from;
2843         st->upper_offset = to;
2844         st->root_skb = st->cur_skb = skb;
2845         st->frag_idx = st->stepped_offset = 0;
2846         st->frag_data = NULL;
2847 }
2848 EXPORT_SYMBOL(skb_prepare_seq_read);
2849
2850 /**
2851  * skb_seq_read - Sequentially read skb data
2852  * @consumed: number of bytes consumed by the caller so far
2853  * @data: destination pointer for data to be returned
2854  * @st: state variable
2855  *
2856  * Reads a block of skb data at @consumed relative to the
2857  * lower offset specified to skb_prepare_seq_read(). Assigns
2858  * the head of the data block to @data and returns the length
2859  * of the block or 0 if the end of the skb data or the upper
2860  * offset has been reached.
2861  *
2862  * The caller is not required to consume all of the data
2863  * returned, i.e. @consumed is typically set to the number
2864  * of bytes already consumed and the next call to
2865  * skb_seq_read() will return the remaining part of the block.
2866  *
2867  * Note 1: The size of each block of data returned can be arbitrary,
2868  *       this limitation is the cost for zerocopy sequential
2869  *       reads of potentially non linear data.
2870  *
2871  * Note 2: Fragment lists within fragments are not implemented
2872  *       at the moment, state->root_skb could be replaced with
2873  *       a stack for this purpose.
2874  */
2875 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
2876                           struct skb_seq_state *st)
2877 {
2878         unsigned int block_limit, abs_offset = consumed + st->lower_offset;
2879         skb_frag_t *frag;
2880
2881         if (unlikely(abs_offset >= st->upper_offset)) {
2882                 if (st->frag_data) {
2883                         kunmap_atomic(st->frag_data);
2884                         st->frag_data = NULL;
2885                 }
2886                 return 0;
2887         }
2888
2889 next_skb:
2890         block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
2891
2892         if (abs_offset < block_limit && !st->frag_data) {
2893                 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
2894                 return block_limit - abs_offset;
2895         }
2896
2897         if (st->frag_idx == 0 && !st->frag_data)
2898                 st->stepped_offset += skb_headlen(st->cur_skb);
2899
2900         while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
2901                 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
2902                 block_limit = skb_frag_size(frag) + st->stepped_offset;
2903
2904                 if (abs_offset < block_limit) {
2905                         if (!st->frag_data)
2906                                 st->frag_data = kmap_atomic(skb_frag_page(frag));
2907
2908                         *data = (u8 *) st->frag_data + frag->page_offset +
2909                                 (abs_offset - st->stepped_offset);
2910
2911                         return block_limit - abs_offset;
2912                 }
2913
2914                 if (st->frag_data) {
2915                         kunmap_atomic(st->frag_data);
2916                         st->frag_data = NULL;
2917                 }
2918
2919                 st->frag_idx++;
2920                 st->stepped_offset += skb_frag_size(frag);
2921         }
2922
2923         if (st->frag_data) {
2924                 kunmap_atomic(st->frag_data);
2925                 st->frag_data = NULL;
2926         }
2927
2928         if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
2929                 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
2930                 st->frag_idx = 0;
2931                 goto next_skb;
2932         } else if (st->cur_skb->next) {
2933                 st->cur_skb = st->cur_skb->next;
2934                 st->frag_idx = 0;
2935                 goto next_skb;
2936         }
2937
2938         return 0;
2939 }
2940 EXPORT_SYMBOL(skb_seq_read);
2941
2942 /**
2943  * skb_abort_seq_read - Abort a sequential read of skb data
2944  * @st: state variable
2945  *
2946  * Must be called if skb_seq_read() was not called until it
2947  * returned 0.
2948  */
2949 void skb_abort_seq_read(struct skb_seq_state *st)
2950 {
2951         if (st->frag_data)
2952                 kunmap_atomic(st->frag_data);
2953 }
2954 EXPORT_SYMBOL(skb_abort_seq_read);
2955
2956 #define TS_SKB_CB(state)        ((struct skb_seq_state *) &((state)->cb))
2957
2958 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
2959                                           struct ts_config *conf,
2960                                           struct ts_state *state)
2961 {
2962         return skb_seq_read(offset, text, TS_SKB_CB(state));
2963 }
2964
2965 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
2966 {
2967         skb_abort_seq_read(TS_SKB_CB(state));
2968 }
2969
2970 /**
2971  * skb_find_text - Find a text pattern in skb data
2972  * @skb: the buffer to look in
2973  * @from: search offset
2974  * @to: search limit
2975  * @config: textsearch configuration
2976  *
2977  * Finds a pattern in the skb data according to the specified
2978  * textsearch configuration. Use textsearch_next() to retrieve
2979  * subsequent occurrences of the pattern. Returns the offset
2980  * to the first occurrence or UINT_MAX if no match was found.
2981  */
2982 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
2983                            unsigned int to, struct ts_config *config)
2984 {
2985         struct ts_state state;
2986         unsigned int ret;
2987
2988         config->get_next_block = skb_ts_get_next_block;
2989         config->finish = skb_ts_finish;
2990
2991         skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
2992
2993         ret = textsearch_find(config, &state);
2994         return (ret <= to - from ? ret : UINT_MAX);
2995 }
2996 EXPORT_SYMBOL(skb_find_text);
2997
2998 /**
2999  * skb_append_datato_frags - append the user data to a skb
3000  * @sk: sock  structure
3001  * @skb: skb structure to be appended with user data.
3002  * @getfrag: call back function to be used for getting the user data
3003  * @from: pointer to user message iov
3004  * @length: length of the iov message
3005  *
3006  * Description: This procedure append the user data in the fragment part
3007  * of the skb if any page alloc fails user this procedure returns  -ENOMEM
3008  */
3009 int skb_append_datato_frags(struct sock *sk, struct sk_buff *skb,
3010                         int (*getfrag)(void *from, char *to, int offset,
3011                                         int len, int odd, struct sk_buff *skb),
3012                         void *from, int length)
3013 {
3014         int frg_cnt = skb_shinfo(skb)->nr_frags;
3015         int copy;
3016         int offset = 0;
3017         int ret;
3018         struct page_frag *pfrag = &current->task_frag;
3019
3020         do {
3021                 /* Return error if we don't have space for new frag */
3022                 if (frg_cnt >= MAX_SKB_FRAGS)
3023                         return -EMSGSIZE;
3024
3025                 if (!sk_page_frag_refill(sk, pfrag))
3026                         return -ENOMEM;
3027
3028                 /* copy the user data to page */
3029                 copy = min_t(int, length, pfrag->size - pfrag->offset);
3030
3031                 ret = getfrag(from, page_address(pfrag->page) + pfrag->offset,
3032                               offset, copy, 0, skb);
3033                 if (ret < 0)
3034                         return -EFAULT;
3035
3036                 /* copy was successful so update the size parameters */
3037                 skb_fill_page_desc(skb, frg_cnt, pfrag->page, pfrag->offset,
3038                                    copy);
3039                 frg_cnt++;
3040                 pfrag->offset += copy;
3041                 get_page(pfrag->page);
3042
3043                 skb->truesize += copy;
3044                 atomic_add(copy, &sk->sk_wmem_alloc);
3045                 skb->len += copy;
3046                 skb->data_len += copy;
3047                 offset += copy;
3048                 length -= copy;
3049
3050         } while (length > 0);
3051
3052         return 0;
3053 }
3054 EXPORT_SYMBOL(skb_append_datato_frags);
3055
3056 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3057                          int offset, size_t size)
3058 {
3059         int i = skb_shinfo(skb)->nr_frags;
3060
3061         if (skb_can_coalesce(skb, i, page, offset)) {
3062                 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3063         } else if (i < MAX_SKB_FRAGS) {
3064                 get_page(page);
3065                 skb_fill_page_desc(skb, i, page, offset, size);
3066         } else {
3067                 return -EMSGSIZE;
3068         }
3069
3070         return 0;
3071 }
3072 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3073
3074 /**
3075  *      skb_pull_rcsum - pull skb and update receive checksum
3076  *      @skb: buffer to update
3077  *      @len: length of data pulled
3078  *
3079  *      This function performs an skb_pull on the packet and updates
3080  *      the CHECKSUM_COMPLETE checksum.  It should be used on
3081  *      receive path processing instead of skb_pull unless you know
3082  *      that the checksum difference is zero (e.g., a valid IP header)
3083  *      or you are setting ip_summed to CHECKSUM_NONE.
3084  */
3085 unsigned char *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3086 {
3087         unsigned char *data = skb->data;
3088
3089         BUG_ON(len > skb->len);
3090         __skb_pull(skb, len);
3091         skb_postpull_rcsum(skb, data, len);
3092         return skb->data;
3093 }
3094 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3095
3096 /**
3097  *      skb_segment - Perform protocol segmentation on skb.
3098  *      @head_skb: buffer to segment
3099  *      @features: features for the output path (see dev->features)
3100  *
3101  *      This function performs segmentation on the given skb.  It returns
3102  *      a pointer to the first in a list of new skbs for the segments.
3103  *      In case of error it returns ERR_PTR(err).
3104  */
3105 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3106                             netdev_features_t features)
3107 {
3108         struct sk_buff *segs = NULL;
3109         struct sk_buff *tail = NULL;
3110         struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3111         skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3112         unsigned int mss = skb_shinfo(head_skb)->gso_size;
3113         unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3114         struct sk_buff *frag_skb = head_skb;
3115         unsigned int offset = doffset;
3116         unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3117         unsigned int partial_segs = 0;
3118         unsigned int headroom;
3119         unsigned int len = head_skb->len;
3120         __be16 proto;
3121         bool csum, sg;
3122         int nfrags = skb_shinfo(head_skb)->nr_frags;
3123         int err = -ENOMEM;
3124         int i = 0;
3125         int pos;
3126         int dummy;
3127
3128         if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
3129             (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
3130                 /* gso_size is untrusted, and we have a frag_list with a linear
3131                  * non head_frag head.
3132                  *
3133                  * (we assume checking the first list_skb member suffices;
3134                  * i.e if either of the list_skb members have non head_frag
3135                  * head, then the first one has too).
3136                  *
3137                  * If head_skb's headlen does not fit requested gso_size, it
3138                  * means that the frag_list members do NOT terminate on exact
3139                  * gso_size boundaries. Hence we cannot perform skb_frag_t page
3140                  * sharing. Therefore we must fallback to copying the frag_list
3141                  * skbs; we do so by disabling SG.
3142                  */
3143                 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
3144                         features &= ~NETIF_F_SG;
3145         }
3146
3147         __skb_push(head_skb, doffset);
3148         proto = skb_network_protocol(head_skb, &dummy);
3149         if (unlikely(!proto))
3150                 return ERR_PTR(-EINVAL);
3151
3152         sg = !!(features & NETIF_F_SG);
3153         csum = !!can_checksum_protocol(features, proto);
3154
3155         if (sg && csum && (mss != GSO_BY_FRAGS))  {
3156                 if (!(features & NETIF_F_GSO_PARTIAL)) {
3157                         struct sk_buff *iter;
3158                         unsigned int frag_len;
3159
3160                         if (!list_skb ||
3161                             !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
3162                                 goto normal;
3163
3164                         /* If we get here then all the required
3165                          * GSO features except frag_list are supported.
3166                          * Try to split the SKB to multiple GSO SKBs
3167                          * with no frag_list.
3168                          * Currently we can do that only when the buffers don't
3169                          * have a linear part and all the buffers except
3170                          * the last are of the same length.
3171                          */
3172                         frag_len = list_skb->len;
3173                         skb_walk_frags(head_skb, iter) {
3174                                 if (frag_len != iter->len && iter->next)
3175                                         goto normal;
3176                                 if (skb_headlen(iter))
3177                                         goto normal;
3178
3179                                 len -= iter->len;
3180                         }
3181
3182                         if (len != frag_len)
3183                                 goto normal;
3184                 }
3185
3186                 /* GSO partial only requires that we trim off any excess that
3187                  * doesn't fit into an MSS sized block, so take care of that
3188                  * now.
3189                  */
3190                 partial_segs = len / mss;
3191                 if (partial_segs > 1)
3192                         mss *= partial_segs;
3193                 else
3194                         partial_segs = 0;
3195         }
3196
3197 normal:
3198         headroom = skb_headroom(head_skb);
3199         pos = skb_headlen(head_skb);
3200
3201         do {
3202                 struct sk_buff *nskb;
3203                 skb_frag_t *nskb_frag;
3204                 int hsize;
3205                 int size;
3206
3207                 if (unlikely(mss == GSO_BY_FRAGS)) {
3208                         len = list_skb->len;
3209                 } else {
3210                         len = head_skb->len - offset;
3211                         if (len > mss)
3212                                 len = mss;
3213                 }
3214
3215                 hsize = skb_headlen(head_skb) - offset;
3216                 if (hsize < 0)
3217                         hsize = 0;
3218                 if (hsize > len || !sg)
3219                         hsize = len;
3220
3221                 if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
3222                     (skb_headlen(list_skb) == len || sg)) {
3223                         BUG_ON(skb_headlen(list_skb) > len);
3224
3225                         i = 0;
3226                         nfrags = skb_shinfo(list_skb)->nr_frags;
3227                         frag = skb_shinfo(list_skb)->frags;
3228                         frag_skb = list_skb;
3229                         pos += skb_headlen(list_skb);
3230
3231                         while (pos < offset + len) {
3232                                 BUG_ON(i >= nfrags);
3233
3234                                 size = skb_frag_size(frag);
3235                                 if (pos + size > offset + len)
3236                                         break;
3237
3238                                 i++;
3239                                 pos += size;
3240                                 frag++;
3241                         }
3242
3243                         nskb = skb_clone(list_skb, GFP_ATOMIC);
3244                         list_skb = list_skb->next;
3245
3246                         if (unlikely(!nskb))
3247                                 goto err;
3248
3249                         if (unlikely(pskb_trim(nskb, len))) {
3250                                 kfree_skb(nskb);
3251                                 goto err;
3252                         }
3253
3254                         hsize = skb_end_offset(nskb);
3255                         if (skb_cow_head(nskb, doffset + headroom)) {
3256                                 kfree_skb(nskb);
3257                                 goto err;
3258                         }
3259
3260                         nskb->truesize += skb_end_offset(nskb) - hsize;
3261                         skb_release_head_state(nskb);
3262                         __skb_push(nskb, doffset);
3263                 } else {
3264                         nskb = __alloc_skb(hsize + doffset + headroom,
3265                                            GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
3266                                            NUMA_NO_NODE);
3267
3268                         if (unlikely(!nskb))
3269                                 goto err;
3270
3271                         skb_reserve(nskb, headroom);
3272                         __skb_put(nskb, doffset);
3273                 }
3274
3275                 if (segs)
3276                         tail->next = nskb;
3277                 else
3278                         segs = nskb;
3279                 tail = nskb;
3280
3281                 __copy_skb_header(nskb, head_skb);
3282
3283                 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
3284                 skb_reset_mac_len(nskb);
3285
3286                 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
3287                                                  nskb->data - tnl_hlen,
3288                                                  doffset + tnl_hlen);
3289
3290                 if (nskb->len == len + doffset)
3291                         goto perform_csum_check;
3292
3293                 if (!sg) {
3294                         if (!nskb->remcsum_offload)
3295                                 nskb->ip_summed = CHECKSUM_NONE;
3296                         SKB_GSO_CB(nskb)->csum =
3297                                 skb_copy_and_csum_bits(head_skb, offset,
3298                                                        skb_put(nskb, len),
3299                                                        len, 0);
3300                         SKB_GSO_CB(nskb)->csum_start =
3301                                 skb_headroom(nskb) + doffset;
3302                         continue;
3303                 }
3304
3305                 nskb_frag = skb_shinfo(nskb)->frags;
3306
3307                 skb_copy_from_linear_data_offset(head_skb, offset,
3308                                                  skb_put(nskb, hsize), hsize);
3309
3310                 skb_shinfo(nskb)->tx_flags |= skb_shinfo(head_skb)->tx_flags &
3311                                               SKBTX_SHARED_FRAG;
3312
3313                 while (pos < offset + len) {
3314                         if (i >= nfrags) {
3315                                 BUG_ON(skb_headlen(list_skb));
3316
3317                                 i = 0;
3318                                 nfrags = skb_shinfo(list_skb)->nr_frags;
3319                                 frag = skb_shinfo(list_skb)->frags;
3320                                 frag_skb = list_skb;
3321
3322                                 BUG_ON(!nfrags);
3323
3324                                 list_skb = list_skb->next;
3325                         }
3326
3327                         if (unlikely(skb_shinfo(nskb)->nr_frags >=
3328                                      MAX_SKB_FRAGS)) {
3329                                 net_warn_ratelimited(
3330                                         "skb_segment: too many frags: %u %u\n",
3331                                         pos, mss);
3332                                 err = -EINVAL;
3333                                 goto err;
3334                         }
3335
3336                         if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
3337                                 goto err;
3338
3339                         *nskb_frag = *frag;
3340                         __skb_frag_ref(nskb_frag);
3341                         size = skb_frag_size(nskb_frag);
3342
3343                         if (pos < offset) {
3344                                 nskb_frag->page_offset += offset - pos;
3345                                 skb_frag_size_sub(nskb_frag, offset - pos);
3346                         }
3347
3348                         skb_shinfo(nskb)->nr_frags++;
3349
3350                         if (pos + size <= offset + len) {
3351                                 i++;
3352                                 frag++;
3353                                 pos += size;
3354                         } else {
3355                                 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
3356                                 goto skip_fraglist;
3357                         }
3358
3359                         nskb_frag++;
3360                 }
3361
3362 skip_fraglist:
3363                 nskb->data_len = len - hsize;
3364                 nskb->len += nskb->data_len;
3365                 nskb->truesize += nskb->data_len;
3366
3367 perform_csum_check:
3368                 if (!csum) {
3369                         if (skb_has_shared_frag(nskb) &&
3370                             __skb_linearize(nskb))
3371                                 goto err;
3372
3373                         if (!nskb->remcsum_offload)
3374                                 nskb->ip_summed = CHECKSUM_NONE;
3375                         SKB_GSO_CB(nskb)->csum =
3376                                 skb_checksum(nskb, doffset,
3377                                              nskb->len - doffset, 0);
3378                         SKB_GSO_CB(nskb)->csum_start =
3379                                 skb_headroom(nskb) + doffset;
3380                 }
3381         } while ((offset += len) < head_skb->len);
3382
3383         /* Some callers want to get the end of the list.
3384          * Put it in segs->prev to avoid walking the list.
3385          * (see validate_xmit_skb_list() for example)
3386          */
3387         segs->prev = tail;
3388
3389         if (partial_segs) {
3390                 struct sk_buff *iter;
3391                 int type = skb_shinfo(head_skb)->gso_type;
3392                 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
3393
3394                 /* Update type to add partial and then remove dodgy if set */
3395                 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
3396                 type &= ~SKB_GSO_DODGY;
3397
3398                 /* Update GSO info and prepare to start updating headers on
3399                  * our way back down the stack of protocols.
3400                  */
3401                 for (iter = segs; iter; iter = iter->next) {
3402                         skb_shinfo(iter)->gso_size = gso_size;
3403                         skb_shinfo(iter)->gso_segs = partial_segs;
3404                         skb_shinfo(iter)->gso_type = type;
3405                         SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
3406                 }
3407
3408                 if (tail->len - doffset <= gso_size)
3409                         skb_shinfo(tail)->gso_size = 0;
3410                 else if (tail != segs)
3411                         skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
3412         }
3413
3414         /* Following permits correct backpressure, for protocols
3415          * using skb_set_owner_w().
3416          * Idea is to tranfert ownership from head_skb to last segment.
3417          */
3418         if (head_skb->destructor == sock_wfree) {
3419                 swap(tail->truesize, head_skb->truesize);
3420                 swap(tail->destructor, head_skb->destructor);
3421                 swap(tail->sk, head_skb->sk);
3422         }
3423         return segs;
3424
3425 err:
3426         kfree_skb_list(segs);
3427         return ERR_PTR(err);
3428 }
3429 EXPORT_SYMBOL_GPL(skb_segment);
3430
3431 int skb_gro_receive(struct sk_buff **head, struct sk_buff *skb)
3432 {
3433         struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
3434         unsigned int offset = skb_gro_offset(skb);
3435         unsigned int headlen = skb_headlen(skb);
3436         unsigned int len = skb_gro_len(skb);
3437         struct sk_buff *lp, *p = *head;
3438         unsigned int delta_truesize;
3439
3440         if (unlikely(p->len + len >= 65536))
3441                 return -E2BIG;
3442
3443         lp = NAPI_GRO_CB(p)->last;
3444         pinfo = skb_shinfo(lp);
3445
3446         if (headlen <= offset) {
3447                 skb_frag_t *frag;
3448                 skb_frag_t *frag2;
3449                 int i = skbinfo->nr_frags;
3450                 int nr_frags = pinfo->nr_frags + i;
3451
3452                 if (nr_frags > MAX_SKB_FRAGS)
3453                         goto merge;
3454
3455                 offset -= headlen;
3456                 pinfo->nr_frags = nr_frags;
3457                 skbinfo->nr_frags = 0;
3458
3459                 frag = pinfo->frags + nr_frags;
3460                 frag2 = skbinfo->frags + i;
3461                 do {
3462                         *--frag = *--frag2;
3463                 } while (--i);
3464
3465                 frag->page_offset += offset;
3466                 skb_frag_size_sub(frag, offset);
3467
3468                 /* all fragments truesize : remove (head size + sk_buff) */
3469                 delta_truesize = skb->truesize -
3470                                  SKB_TRUESIZE(skb_end_offset(skb));
3471
3472                 skb->truesize -= skb->data_len;
3473                 skb->len -= skb->data_len;
3474                 skb->data_len = 0;
3475
3476                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
3477                 goto done;
3478         } else if (skb->head_frag) {
3479                 int nr_frags = pinfo->nr_frags;
3480                 skb_frag_t *frag = pinfo->frags + nr_frags;
3481                 struct page *page = virt_to_head_page(skb->head);
3482                 unsigned int first_size = headlen - offset;
3483                 unsigned int first_offset;
3484
3485                 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
3486                         goto merge;
3487
3488                 first_offset = skb->data -
3489                                (unsigned char *)page_address(page) +
3490                                offset;
3491
3492                 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
3493
3494                 frag->page.p      = page;
3495                 frag->page_offset = first_offset;
3496                 skb_frag_size_set(frag, first_size);
3497
3498                 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
3499                 /* We dont need to clear skbinfo->nr_frags here */
3500
3501                 delta_truesize = skb->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
3502                 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
3503                 goto done;
3504         }
3505
3506 merge:
3507         delta_truesize = skb->truesize;
3508         if (offset > headlen) {
3509                 unsigned int eat = offset - headlen;
3510
3511                 skbinfo->frags[0].page_offset += eat;
3512                 skb_frag_size_sub(&skbinfo->frags[0], eat);
3513                 skb->data_len -= eat;
3514                 skb->len -= eat;
3515                 offset = headlen;
3516         }
3517
3518         __skb_pull(skb, offset);
3519
3520         if (NAPI_GRO_CB(p)->last == p)
3521                 skb_shinfo(p)->frag_list = skb;
3522         else
3523                 NAPI_GRO_CB(p)->last->next = skb;
3524         NAPI_GRO_CB(p)->last = skb;
3525         __skb_header_release(skb);
3526         lp = p;
3527
3528 done:
3529         NAPI_GRO_CB(p)->count++;
3530         p->data_len += len;
3531         p->truesize += delta_truesize;
3532         p->len += len;
3533         if (lp != p) {
3534                 lp->data_len += len;
3535                 lp->truesize += delta_truesize;
3536                 lp->len += len;
3537         }
3538         NAPI_GRO_CB(skb)->same_flow = 1;
3539         return 0;
3540 }
3541 EXPORT_SYMBOL_GPL(skb_gro_receive);
3542
3543 void __init skb_init(void)
3544 {
3545         skbuff_head_cache = kmem_cache_create("skbuff_head_cache",
3546                                               sizeof(struct sk_buff),
3547                                               0,
3548                                               SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3549                                               NULL);
3550         skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
3551                                                 sizeof(struct sk_buff_fclones),
3552                                                 0,
3553                                                 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
3554                                                 NULL);
3555 }
3556
3557 static int
3558 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
3559                unsigned int recursion_level)
3560 {
3561         int start = skb_headlen(skb);
3562         int i, copy = start - offset;
3563         struct sk_buff *frag_iter;
3564         int elt = 0;
3565
3566         if (unlikely(recursion_level >= 24))
3567                 return -EMSGSIZE;
3568
3569         if (copy > 0) {
3570                 if (copy > len)
3571                         copy = len;
3572                 sg_set_buf(sg, skb->data + offset, copy);
3573                 elt++;
3574                 if ((len -= copy) == 0)
3575                         return elt;
3576                 offset += copy;
3577         }
3578
3579         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3580                 int end;
3581
3582                 WARN_ON(start > offset + len);
3583
3584                 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3585                 if ((copy = end - offset) > 0) {
3586                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3587                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
3588                                 return -EMSGSIZE;
3589
3590                         if (copy > len)
3591                                 copy = len;
3592                         sg_set_page(&sg[elt], skb_frag_page(frag), copy,
3593                                         frag->page_offset+offset-start);
3594                         elt++;
3595                         if (!(len -= copy))
3596                                 return elt;
3597                         offset += copy;
3598                 }
3599                 start = end;
3600         }
3601
3602         skb_walk_frags(skb, frag_iter) {
3603                 int end, ret;
3604
3605                 WARN_ON(start > offset + len);
3606
3607                 end = start + frag_iter->len;
3608                 if ((copy = end - offset) > 0) {
3609                         if (unlikely(elt && sg_is_last(&sg[elt - 1])))
3610                                 return -EMSGSIZE;
3611
3612                         if (copy > len)
3613                                 copy = len;
3614                         ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
3615                                               copy, recursion_level + 1);
3616                         if (unlikely(ret < 0))
3617                                 return ret;
3618                         elt += ret;
3619                         if ((len -= copy) == 0)
3620                                 return elt;
3621                         offset += copy;
3622                 }
3623                 start = end;
3624         }
3625         BUG_ON(len);
3626         return elt;
3627 }
3628
3629 /**
3630  *      skb_to_sgvec - Fill a scatter-gather list from a socket buffer
3631  *      @skb: Socket buffer containing the buffers to be mapped
3632  *      @sg: The scatter-gather list to map into
3633  *      @offset: The offset into the buffer's contents to start mapping
3634  *      @len: Length of buffer space to be mapped
3635  *
3636  *      Fill the specified scatter-gather list with mappings/pointers into a
3637  *      region of the buffer space attached to a socket buffer. Returns either
3638  *      the number of scatterlist items used, or -EMSGSIZE if the contents
3639  *      could not fit.
3640  */
3641 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
3642 {
3643         int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
3644
3645         if (nsg <= 0)
3646                 return nsg;
3647
3648         sg_mark_end(&sg[nsg - 1]);
3649
3650         return nsg;
3651 }
3652 EXPORT_SYMBOL_GPL(skb_to_sgvec);
3653
3654 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
3655  * sglist without mark the sg which contain last skb data as the end.
3656  * So the caller can mannipulate sg list as will when padding new data after
3657  * the first call without calling sg_unmark_end to expend sg list.
3658  *
3659  * Scenario to use skb_to_sgvec_nomark:
3660  * 1. sg_init_table
3661  * 2. skb_to_sgvec_nomark(payload1)
3662  * 3. skb_to_sgvec_nomark(payload2)
3663  *
3664  * This is equivalent to:
3665  * 1. sg_init_table
3666  * 2. skb_to_sgvec(payload1)
3667  * 3. sg_unmark_end
3668  * 4. skb_to_sgvec(payload2)
3669  *
3670  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
3671  * is more preferable.
3672  */
3673 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
3674                         int offset, int len)
3675 {
3676         return __skb_to_sgvec(skb, sg, offset, len, 0);
3677 }
3678 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
3679
3680
3681
3682 /**
3683  *      skb_cow_data - Check that a socket buffer's data buffers are writable
3684  *      @skb: The socket buffer to check.
3685  *      @tailbits: Amount of trailing space to be added
3686  *      @trailer: Returned pointer to the skb where the @tailbits space begins
3687  *
3688  *      Make sure that the data buffers attached to a socket buffer are
3689  *      writable. If they are not, private copies are made of the data buffers
3690  *      and the socket buffer is set to use these instead.
3691  *
3692  *      If @tailbits is given, make sure that there is space to write @tailbits
3693  *      bytes of data beyond current end of socket buffer.  @trailer will be
3694  *      set to point to the skb in which this space begins.
3695  *
3696  *      The number of scatterlist elements required to completely map the
3697  *      COW'd and extended socket buffer will be returned.
3698  */
3699 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
3700 {
3701         int copyflag;
3702         int elt;
3703         struct sk_buff *skb1, **skb_p;
3704
3705         /* If skb is cloned or its head is paged, reallocate
3706          * head pulling out all the pages (pages are considered not writable
3707          * at the moment even if they are anonymous).
3708          */
3709         if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
3710             __pskb_pull_tail(skb, skb_pagelen(skb)-skb_headlen(skb)) == NULL)
3711                 return -ENOMEM;
3712
3713         /* Easy case. Most of packets will go this way. */
3714         if (!skb_has_frag_list(skb)) {
3715                 /* A little of trouble, not enough of space for trailer.
3716                  * This should not happen, when stack is tuned to generate
3717                  * good frames. OK, on miss we reallocate and reserve even more
3718                  * space, 128 bytes is fair. */
3719
3720                 if (skb_tailroom(skb) < tailbits &&
3721                     pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
3722                         return -ENOMEM;
3723
3724                 /* Voila! */
3725                 *trailer = skb;
3726                 return 1;
3727         }
3728
3729         /* Misery. We are in troubles, going to mincer fragments... */
3730
3731         elt = 1;
3732         skb_p = &skb_shinfo(skb)->frag_list;
3733         copyflag = 0;
3734
3735         while ((skb1 = *skb_p) != NULL) {
3736                 int ntail = 0;
3737
3738                 /* The fragment is partially pulled by someone,
3739                  * this can happen on input. Copy it and everything
3740                  * after it. */
3741
3742                 if (skb_shared(skb1))
3743                         copyflag = 1;
3744
3745                 /* If the skb is the last, worry about trailer. */
3746
3747                 if (skb1->next == NULL && tailbits) {
3748                         if (skb_shinfo(skb1)->nr_frags ||
3749                             skb_has_frag_list(skb1) ||
3750                             skb_tailroom(skb1) < tailbits)
3751                                 ntail = tailbits + 128;
3752                 }
3753
3754                 if (copyflag ||
3755                     skb_cloned(skb1) ||
3756                     ntail ||
3757                     skb_shinfo(skb1)->nr_frags ||
3758                     skb_has_frag_list(skb1)) {
3759                         struct sk_buff *skb2;
3760
3761                         /* Fuck, we are miserable poor guys... */
3762                         if (ntail == 0)
3763                                 skb2 = skb_copy(skb1, GFP_ATOMIC);
3764                         else
3765                                 skb2 = skb_copy_expand(skb1,
3766                                                        skb_headroom(skb1),
3767                                                        ntail,
3768                                                        GFP_ATOMIC);
3769                         if (unlikely(skb2 == NULL))
3770                                 return -ENOMEM;
3771
3772                         if (skb1->sk)
3773                                 skb_set_owner_w(skb2, skb1->sk);
3774
3775                         /* Looking around. Are we still alive?
3776                          * OK, link new skb, drop old one */
3777
3778                         skb2->next = skb1->next;
3779                         *skb_p = skb2;
3780                         kfree_skb(skb1);
3781                         skb1 = skb2;
3782                 }
3783                 elt++;
3784                 *trailer = skb1;
3785                 skb_p = &skb1->next;
3786         }
3787
3788         return elt;
3789 }
3790 EXPORT_SYMBOL_GPL(skb_cow_data);
3791
3792 static void sock_rmem_free(struct sk_buff *skb)
3793 {
3794         struct sock *sk = skb->sk;
3795
3796         atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
3797 }
3798
3799 /*
3800  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
3801  */
3802 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
3803 {
3804         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
3805             (unsigned int)sk->sk_rcvbuf)
3806                 return -ENOMEM;
3807
3808         skb_orphan(skb);
3809         skb->sk = sk;
3810         skb->destructor = sock_rmem_free;
3811         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
3812
3813         /* before exiting rcu section, make sure dst is refcounted */
3814         skb_dst_force(skb);
3815
3816         skb_queue_tail(&sk->sk_error_queue, skb);
3817         if (!sock_flag(sk, SOCK_DEAD))
3818                 sk->sk_error_report(sk);
3819         return 0;
3820 }
3821 EXPORT_SYMBOL(sock_queue_err_skb);
3822
3823 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
3824 {
3825         struct sk_buff_head *q = &sk->sk_error_queue;
3826         struct sk_buff *skb, *skb_next;
3827         unsigned long flags;
3828         int err = 0;
3829
3830         spin_lock_irqsave(&q->lock, flags);
3831         skb = __skb_dequeue(q);
3832         if (skb && (skb_next = skb_peek(q)))
3833                 err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
3834         spin_unlock_irqrestore(&q->lock, flags);
3835
3836         sk->sk_err = err;
3837         if (err)
3838                 sk->sk_error_report(sk);
3839
3840         return skb;
3841 }
3842 EXPORT_SYMBOL(sock_dequeue_err_skb);
3843
3844 /**
3845  * skb_clone_sk - create clone of skb, and take reference to socket
3846  * @skb: the skb to clone
3847  *
3848  * This function creates a clone of a buffer that holds a reference on
3849  * sk_refcnt.  Buffers created via this function are meant to be
3850  * returned using sock_queue_err_skb, or free via kfree_skb.
3851  *
3852  * When passing buffers allocated with this function to sock_queue_err_skb
3853  * it is necessary to wrap the call with sock_hold/sock_put in order to
3854  * prevent the socket from being released prior to being enqueued on
3855  * the sk_error_queue.
3856  */
3857 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
3858 {
3859         struct sock *sk = skb->sk;
3860         struct sk_buff *clone;
3861
3862         if (!sk || !atomic_inc_not_zero(&sk->sk_refcnt))
3863                 return NULL;
3864
3865         clone = skb_clone(skb, GFP_ATOMIC);
3866         if (!clone) {
3867                 sock_put(sk);
3868                 return NULL;
3869         }
3870
3871         clone->sk = sk;
3872         clone->destructor = sock_efree;
3873
3874         return clone;
3875 }
3876 EXPORT_SYMBOL(skb_clone_sk);
3877
3878 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
3879                                         struct sock *sk,
3880                                         int tstype)
3881 {
3882         struct sock_exterr_skb *serr;
3883         int err;
3884
3885         serr = SKB_EXT_ERR(skb);
3886         memset(serr, 0, sizeof(*serr));
3887         serr->ee.ee_errno = ENOMSG;
3888         serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
3889         serr->ee.ee_info = tstype;
3890         serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
3891         if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
3892                 serr->ee.ee_data = skb_shinfo(skb)->tskey;
3893                 if (sk->sk_protocol == IPPROTO_TCP &&
3894                     sk->sk_type == SOCK_STREAM)
3895                         serr->ee.ee_data -= sk->sk_tskey;
3896         }
3897
3898         err = sock_queue_err_skb(sk, skb);
3899
3900         if (err)
3901                 kfree_skb(skb);
3902 }
3903
3904 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
3905 {
3906         bool ret;
3907
3908         if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
3909                 return true;
3910
3911         read_lock_bh(&sk->sk_callback_lock);
3912         ret = sk->sk_socket && sk->sk_socket->file &&
3913               file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
3914         read_unlock_bh(&sk->sk_callback_lock);
3915         return ret;
3916 }
3917
3918 void skb_complete_tx_timestamp(struct sk_buff *skb,
3919                                struct skb_shared_hwtstamps *hwtstamps)
3920 {
3921         struct sock *sk = skb->sk;
3922
3923         if (!skb_may_tx_timestamp(sk, false))
3924                 goto err;
3925
3926         /* Take a reference to prevent skb_orphan() from freeing the socket,
3927          * but only if the socket refcount is not zero.
3928          */
3929         if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
3930                 *skb_hwtstamps(skb) = *hwtstamps;
3931                 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND);
3932                 sock_put(sk);
3933                 return;
3934         }
3935
3936 err:
3937         kfree_skb(skb);
3938 }
3939 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
3940
3941 void __skb_tstamp_tx(struct sk_buff *orig_skb,
3942                      struct skb_shared_hwtstamps *hwtstamps,
3943                      struct sock *sk, int tstype)
3944 {
3945         struct sk_buff *skb;
3946         bool tsonly;
3947
3948         if (!sk)
3949                 return;
3950
3951         tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
3952         if (!skb_may_tx_timestamp(sk, tsonly))
3953                 return;
3954
3955         if (tsonly)
3956                 skb = alloc_skb(0, GFP_ATOMIC);
3957         else
3958                 skb = skb_clone(orig_skb, GFP_ATOMIC);
3959         if (!skb)
3960                 return;
3961
3962         if (tsonly) {
3963                 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
3964                                              SKBTX_ANY_TSTAMP;
3965                 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
3966         }
3967
3968         if (hwtstamps)
3969                 *skb_hwtstamps(skb) = *hwtstamps;
3970         else
3971                 skb->tstamp = ktime_get_real();
3972
3973         __skb_complete_tx_timestamp(skb, sk, tstype);
3974 }
3975 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
3976
3977 void skb_tstamp_tx(struct sk_buff *orig_skb,
3978                    struct skb_shared_hwtstamps *hwtstamps)
3979 {
3980         return __skb_tstamp_tx(orig_skb, hwtstamps, orig_skb->sk,
3981                                SCM_TSTAMP_SND);
3982 }
3983 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
3984
3985 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
3986 {
3987         struct sock *sk = skb->sk;
3988         struct sock_exterr_skb *serr;
3989         int err = 1;
3990
3991         skb->wifi_acked_valid = 1;
3992         skb->wifi_acked = acked;
3993
3994         serr = SKB_EXT_ERR(skb);
3995         memset(serr, 0, sizeof(*serr));
3996         serr->ee.ee_errno = ENOMSG;
3997         serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
3998
3999         /* Take a reference to prevent skb_orphan() from freeing the socket,
4000          * but only if the socket refcount is not zero.
4001          */
4002         if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) {
4003                 err = sock_queue_err_skb(sk, skb);
4004                 sock_put(sk);
4005         }
4006         if (err)
4007                 kfree_skb(skb);
4008 }
4009 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4010
4011 /**
4012  * skb_partial_csum_set - set up and verify partial csum values for packet
4013  * @skb: the skb to set
4014  * @start: the number of bytes after skb->data to start checksumming.
4015  * @off: the offset from start to place the checksum.
4016  *
4017  * For untrusted partially-checksummed packets, we need to make sure the values
4018  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4019  *
4020  * This function checks and sets those values and skb->ip_summed: if this
4021  * returns false you should drop the packet.
4022  */
4023 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4024 {
4025         if (unlikely(start > skb_headlen(skb)) ||
4026             unlikely((int)start + off > skb_headlen(skb) - 2)) {
4027                 net_warn_ratelimited("bad partial csum: csum=%u/%u len=%u\n",
4028                                      start, off, skb_headlen(skb));
4029                 return false;
4030         }
4031         skb->ip_summed = CHECKSUM_PARTIAL;
4032         skb->csum_start = skb_headroom(skb) + start;
4033         skb->csum_offset = off;
4034         skb_set_transport_header(skb, start);
4035         return true;
4036 }
4037 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4038
4039 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4040                                unsigned int max)
4041 {
4042         if (skb_headlen(skb) >= len)
4043                 return 0;
4044
4045         /* If we need to pullup then pullup to the max, so we
4046          * won't need to do it again.
4047          */
4048         if (max > skb->len)
4049                 max = skb->len;
4050
4051         if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4052                 return -ENOMEM;
4053
4054         if (skb_headlen(skb) < len)
4055                 return -EPROTO;
4056
4057         return 0;
4058 }
4059
4060 #define MAX_TCP_HDR_LEN (15 * 4)
4061
4062 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4063                                       typeof(IPPROTO_IP) proto,
4064                                       unsigned int off)
4065 {
4066         switch (proto) {
4067                 int err;
4068
4069         case IPPROTO_TCP:
4070                 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4071                                           off + MAX_TCP_HDR_LEN);
4072                 if (!err && !skb_partial_csum_set(skb, off,
4073                                                   offsetof(struct tcphdr,
4074                                                            check)))
4075                         err = -EPROTO;
4076                 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4077
4078         case IPPROTO_UDP:
4079                 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4080                                           off + sizeof(struct udphdr));
4081                 if (!err && !skb_partial_csum_set(skb, off,
4082                                                   offsetof(struct udphdr,
4083                                                            check)))
4084                         err = -EPROTO;
4085                 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4086         }
4087
4088         return ERR_PTR(-EPROTO);
4089 }
4090
4091 /* This value should be large enough to cover a tagged ethernet header plus
4092  * maximally sized IP and TCP or UDP headers.
4093  */
4094 #define MAX_IP_HDR_LEN 128
4095
4096 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4097 {
4098         unsigned int off;
4099         bool fragment;
4100         __sum16 *csum;
4101         int err;
4102
4103         fragment = false;
4104
4105         err = skb_maybe_pull_tail(skb,
4106                                   sizeof(struct iphdr),
4107                                   MAX_IP_HDR_LEN);
4108         if (err < 0)
4109                 goto out;
4110
4111         if (ip_hdr(skb)->frag_off & htons(IP_OFFSET | IP_MF))
4112                 fragment = true;
4113
4114         off = ip_hdrlen(skb);
4115
4116         err = -EPROTO;
4117
4118         if (fragment)
4119                 goto out;
4120
4121         csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
4122         if (IS_ERR(csum))
4123                 return PTR_ERR(csum);
4124
4125         if (recalculate)
4126                 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
4127                                            ip_hdr(skb)->daddr,
4128                                            skb->len - off,
4129                                            ip_hdr(skb)->protocol, 0);
4130         err = 0;
4131
4132 out:
4133         return err;
4134 }
4135
4136 /* This value should be large enough to cover a tagged ethernet header plus
4137  * an IPv6 header, all options, and a maximal TCP or UDP header.
4138  */
4139 #define MAX_IPV6_HDR_LEN 256
4140
4141 #define OPT_HDR(type, skb, off) \
4142         (type *)(skb_network_header(skb) + (off))
4143
4144 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
4145 {
4146         int err;
4147         u8 nexthdr;
4148         unsigned int off;
4149         unsigned int len;
4150         bool fragment;
4151         bool done;
4152         __sum16 *csum;
4153
4154         fragment = false;
4155         done = false;
4156
4157         off = sizeof(struct ipv6hdr);
4158
4159         err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
4160         if (err < 0)
4161                 goto out;
4162
4163         nexthdr = ipv6_hdr(skb)->nexthdr;
4164
4165         len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
4166         while (off <= len && !done) {
4167                 switch (nexthdr) {
4168                 case IPPROTO_DSTOPTS:
4169                 case IPPROTO_HOPOPTS:
4170                 case IPPROTO_ROUTING: {
4171                         struct ipv6_opt_hdr *hp;
4172
4173                         err = skb_maybe_pull_tail(skb,
4174                                                   off +
4175                                                   sizeof(struct ipv6_opt_hdr),
4176                                                   MAX_IPV6_HDR_LEN);
4177                         if (err < 0)
4178                                 goto out;
4179
4180                         hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
4181                         nexthdr = hp->nexthdr;
4182                         off += ipv6_optlen(hp);
4183                         break;
4184                 }
4185                 case IPPROTO_AH: {
4186                         struct ip_auth_hdr *hp;
4187
4188                         err = skb_maybe_pull_tail(skb,
4189                                                   off +
4190                                                   sizeof(struct ip_auth_hdr),
4191                                                   MAX_IPV6_HDR_LEN);
4192                         if (err < 0)
4193                                 goto out;
4194
4195                         hp = OPT_HDR(struct ip_auth_hdr, skb, off);
4196                         nexthdr = hp->nexthdr;
4197                         off += ipv6_authlen(hp);
4198                         break;
4199                 }
4200                 case IPPROTO_FRAGMENT: {
4201                         struct frag_hdr *hp;
4202
4203                         err = skb_maybe_pull_tail(skb,
4204                                                   off +
4205                                                   sizeof(struct frag_hdr),
4206                                                   MAX_IPV6_HDR_LEN);
4207                         if (err < 0)
4208                                 goto out;
4209
4210                         hp = OPT_HDR(struct frag_hdr, skb, off);
4211
4212                         if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
4213                                 fragment = true;
4214
4215                         nexthdr = hp->nexthdr;
4216                         off += sizeof(struct frag_hdr);
4217                         break;
4218                 }
4219                 default:
4220                         done = true;
4221                         break;
4222                 }
4223         }
4224
4225         err = -EPROTO;
4226
4227         if (!done || fragment)
4228                 goto out;
4229
4230         csum = skb_checksum_setup_ip(skb, nexthdr, off);
4231         if (IS_ERR(csum))
4232                 return PTR_ERR(csum);
4233
4234         if (recalculate)
4235                 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
4236                                          &ipv6_hdr(skb)->daddr,
4237                                          skb->len - off, nexthdr, 0);
4238         err = 0;
4239
4240 out:
4241         return err;
4242 }
4243
4244 /**
4245  * skb_checksum_setup - set up partial checksum offset
4246  * @skb: the skb to set up
4247  * @recalculate: if true the pseudo-header checksum will be recalculated
4248  */
4249 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
4250 {
4251         int err;
4252
4253         switch (skb->protocol) {
4254         case htons(ETH_P_IP):
4255                 err = skb_checksum_setup_ipv4(skb, recalculate);
4256                 break;
4257
4258         case htons(ETH_P_IPV6):
4259                 err = skb_checksum_setup_ipv6(skb, recalculate);
4260                 break;
4261
4262         default:
4263                 err = -EPROTO;
4264                 break;
4265         }
4266
4267         return err;
4268 }
4269 EXPORT_SYMBOL(skb_checksum_setup);
4270
4271 /**
4272  * skb_checksum_maybe_trim - maybe trims the given skb
4273  * @skb: the skb to check
4274  * @transport_len: the data length beyond the network header
4275  *
4276  * Checks whether the given skb has data beyond the given transport length.
4277  * If so, returns a cloned skb trimmed to this transport length.
4278  * Otherwise returns the provided skb. Returns NULL in error cases
4279  * (e.g. transport_len exceeds skb length or out-of-memory).
4280  *
4281  * Caller needs to set the skb transport header and free any returned skb if it
4282  * differs from the provided skb.
4283  */
4284 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
4285                                                unsigned int transport_len)
4286 {
4287         struct sk_buff *skb_chk;
4288         unsigned int len = skb_transport_offset(skb) + transport_len;
4289         int ret;
4290
4291         if (skb->len < len)
4292                 return NULL;
4293         else if (skb->len == len)
4294                 return skb;
4295
4296         skb_chk = skb_clone(skb, GFP_ATOMIC);
4297         if (!skb_chk)
4298                 return NULL;
4299
4300         ret = pskb_trim_rcsum(skb_chk, len);
4301         if (ret) {
4302                 kfree_skb(skb_chk);
4303                 return NULL;
4304         }
4305
4306         return skb_chk;
4307 }
4308
4309 /**
4310  * skb_checksum_trimmed - validate checksum of an skb
4311  * @skb: the skb to check
4312  * @transport_len: the data length beyond the network header
4313  * @skb_chkf: checksum function to use
4314  *
4315  * Applies the given checksum function skb_chkf to the provided skb.
4316  * Returns a checked and maybe trimmed skb. Returns NULL on error.
4317  *
4318  * If the skb has data beyond the given transport length, then a
4319  * trimmed & cloned skb is checked and returned.
4320  *
4321  * Caller needs to set the skb transport header and free any returned skb if it
4322  * differs from the provided skb.
4323  */
4324 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
4325                                      unsigned int transport_len,
4326                                      __sum16(*skb_chkf)(struct sk_buff *skb))
4327 {
4328         struct sk_buff *skb_chk;
4329         unsigned int offset = skb_transport_offset(skb);
4330         __sum16 ret;
4331
4332         skb_chk = skb_checksum_maybe_trim(skb, transport_len);
4333         if (!skb_chk)
4334                 goto err;
4335
4336         if (!pskb_may_pull(skb_chk, offset))
4337                 goto err;
4338
4339         skb_pull_rcsum(skb_chk, offset);
4340         ret = skb_chkf(skb_chk);
4341         skb_push_rcsum(skb_chk, offset);
4342
4343         if (ret)
4344                 goto err;
4345
4346         return skb_chk;
4347
4348 err:
4349         if (skb_chk && skb_chk != skb)
4350                 kfree_skb(skb_chk);
4351
4352         return NULL;
4353
4354 }
4355 EXPORT_SYMBOL(skb_checksum_trimmed);
4356
4357 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
4358 {
4359         net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
4360                              skb->dev->name);
4361 }
4362 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
4363
4364 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
4365 {
4366         if (head_stolen) {
4367                 skb_release_head_state(skb);
4368                 kmem_cache_free(skbuff_head_cache, skb);
4369         } else {
4370                 __kfree_skb(skb);
4371         }
4372 }
4373 EXPORT_SYMBOL(kfree_skb_partial);
4374
4375 /**
4376  * skb_try_coalesce - try to merge skb to prior one
4377  * @to: prior buffer
4378  * @from: buffer to add
4379  * @fragstolen: pointer to boolean
4380  * @delta_truesize: how much more was allocated than was requested
4381  */
4382 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
4383                       bool *fragstolen, int *delta_truesize)
4384 {
4385         int i, delta, len = from->len;
4386
4387         *fragstolen = false;
4388
4389         if (skb_cloned(to))
4390                 return false;
4391
4392         if (len <= skb_tailroom(to)) {
4393                 if (len)
4394                         BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
4395                 *delta_truesize = 0;
4396                 return true;
4397         }
4398
4399         if (skb_has_frag_list(to) || skb_has_frag_list(from))
4400                 return false;
4401
4402         if (skb_headlen(from) != 0) {
4403                 struct page *page;
4404                 unsigned int offset;
4405
4406                 if (skb_shinfo(to)->nr_frags +
4407                     skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
4408                         return false;
4409
4410                 if (skb_head_is_locked(from))
4411                         return false;
4412
4413                 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
4414
4415                 page = virt_to_head_page(from->head);
4416                 offset = from->data - (unsigned char *)page_address(page);
4417
4418                 skb_fill_page_desc(to, skb_shinfo(to)->nr_frags,
4419                                    page, offset, skb_headlen(from));
4420                 *fragstolen = true;
4421         } else {
4422                 if (skb_shinfo(to)->nr_frags +
4423                     skb_shinfo(from)->nr_frags > MAX_SKB_FRAGS)
4424                         return false;
4425
4426                 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
4427         }
4428
4429         WARN_ON_ONCE(delta < len);
4430
4431         memcpy(skb_shinfo(to)->frags + skb_shinfo(to)->nr_frags,
4432                skb_shinfo(from)->frags,
4433                skb_shinfo(from)->nr_frags * sizeof(skb_frag_t));
4434         skb_shinfo(to)->nr_frags += skb_shinfo(from)->nr_frags;
4435
4436         if (!skb_cloned(from))
4437                 skb_shinfo(from)->nr_frags = 0;
4438
4439         /* if the skb is not cloned this does nothing
4440          * since we set nr_frags to 0.
4441          */
4442         for (i = 0; i < skb_shinfo(from)->nr_frags; i++)
4443                 skb_frag_ref(from, i);
4444
4445         to->truesize += delta;
4446         to->len += len;
4447         to->data_len += len;
4448
4449         *delta_truesize = delta;
4450         return true;
4451 }
4452 EXPORT_SYMBOL(skb_try_coalesce);
4453
4454 /**
4455  * skb_scrub_packet - scrub an skb
4456  *
4457  * @skb: buffer to clean
4458  * @xnet: packet is crossing netns
4459  *
4460  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
4461  * into/from a tunnel. Some information have to be cleared during these
4462  * operations.
4463  * skb_scrub_packet can also be used to clean a skb before injecting it in
4464  * another namespace (@xnet == true). We have to clear all information in the
4465  * skb that could impact namespace isolation.
4466  */
4467 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
4468 {
4469         skb->tstamp.tv64 = 0;
4470         skb->pkt_type = PACKET_HOST;
4471         skb->skb_iif = 0;
4472         skb->ignore_df = 0;
4473         skb_dst_drop(skb);
4474         secpath_reset(skb);
4475         nf_reset(skb);
4476         nf_reset_trace(skb);
4477
4478 #ifdef CONFIG_NET_SWITCHDEV
4479         skb->offload_fwd_mark = 0;
4480 #endif
4481
4482         if (!xnet)
4483                 return;
4484
4485         ipvs_reset(skb);
4486         skb_orphan(skb);
4487         skb->mark = 0;
4488 }
4489 EXPORT_SYMBOL_GPL(skb_scrub_packet);
4490
4491 /**
4492  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
4493  *
4494  * @skb: GSO skb
4495  *
4496  * skb_gso_transport_seglen is used to determine the real size of the
4497  * individual segments, including Layer4 headers (TCP/UDP).
4498  *
4499  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
4500  */
4501 unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
4502 {
4503         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4504         unsigned int thlen = 0;
4505
4506         if (skb->encapsulation) {
4507                 thlen = skb_inner_transport_header(skb) -
4508                         skb_transport_header(skb);
4509
4510                 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
4511                         thlen += inner_tcp_hdrlen(skb);
4512         } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
4513                 thlen = tcp_hdrlen(skb);
4514         } else if (unlikely(shinfo->gso_type & SKB_GSO_SCTP)) {
4515                 thlen = sizeof(struct sctphdr);
4516         }
4517         /* UFO sets gso_size to the size of the fragmentation
4518          * payload, i.e. the size of the L4 (UDP) header is already
4519          * accounted for.
4520          */
4521         return thlen + shinfo->gso_size;
4522 }
4523 EXPORT_SYMBOL_GPL(skb_gso_transport_seglen);
4524
4525 /**
4526  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
4527  *
4528  * There are a couple of instances where we have a GSO skb, and we
4529  * want to determine what size it would be after it is segmented.
4530  *
4531  * We might want to check:
4532  * -    L3+L4+payload size (e.g. IP forwarding)
4533  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
4534  *
4535  * This is a helper to do that correctly considering GSO_BY_FRAGS.
4536  *
4537  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
4538  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
4539  *
4540  * @max_len: The maximum permissible length.
4541  *
4542  * Returns true if the segmented length <= max length.
4543  */
4544 static inline bool skb_gso_size_check(const struct sk_buff *skb,
4545                                       unsigned int seg_len,
4546                                       unsigned int max_len) {
4547         const struct skb_shared_info *shinfo = skb_shinfo(skb);
4548         const struct sk_buff *iter;
4549
4550         if (shinfo->gso_size != GSO_BY_FRAGS)
4551                 return seg_len <= max_len;
4552
4553         /* Undo this so we can re-use header sizes */
4554         seg_len -= GSO_BY_FRAGS;
4555
4556         skb_walk_frags(skb, iter) {
4557                 if (seg_len + skb_headlen(iter) > max_len)
4558                         return false;
4559         }
4560
4561         return true;
4562 }
4563
4564 /**
4565  * skb_gso_validate_mtu - Return in case such skb fits a given MTU
4566  *
4567  * @skb: GSO skb
4568  * @mtu: MTU to validate against
4569  *
4570  * skb_gso_validate_mtu validates if a given skb will fit a wanted MTU
4571  * once split.
4572  */
4573 bool skb_gso_validate_mtu(const struct sk_buff *skb, unsigned int mtu)
4574 {
4575         return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
4576 }
4577 EXPORT_SYMBOL_GPL(skb_gso_validate_mtu);
4578
4579 /**
4580  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
4581  *
4582  * @skb: GSO skb
4583  * @len: length to validate against
4584  *
4585  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
4586  * length once split, including L2, L3 and L4 headers and the payload.
4587  */
4588 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
4589 {
4590         return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
4591 }
4592 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
4593
4594 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
4595 {
4596         int mac_len;
4597
4598         if (skb_cow(skb, skb_headroom(skb)) < 0) {
4599                 kfree_skb(skb);
4600                 return NULL;
4601         }
4602
4603         mac_len = skb->data - skb_mac_header(skb);
4604         if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
4605                 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
4606                         mac_len - VLAN_HLEN - ETH_TLEN);
4607         }
4608         skb->mac_header += VLAN_HLEN;
4609         return skb;
4610 }
4611
4612 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
4613 {
4614         struct vlan_hdr *vhdr;
4615         u16 vlan_tci;
4616
4617         if (unlikely(skb_vlan_tag_present(skb))) {
4618                 /* vlan_tci is already set-up so leave this for another time */
4619                 return skb;
4620         }
4621
4622         skb = skb_share_check(skb, GFP_ATOMIC);
4623         if (unlikely(!skb))
4624                 goto err_free;
4625         /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
4626         if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
4627                 goto err_free;
4628
4629         vhdr = (struct vlan_hdr *)skb->data;
4630         vlan_tci = ntohs(vhdr->h_vlan_TCI);
4631         __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
4632
4633         skb_pull_rcsum(skb, VLAN_HLEN);
4634         vlan_set_encap_proto(skb, vhdr);
4635
4636         skb = skb_reorder_vlan_header(skb);
4637         if (unlikely(!skb))
4638                 goto err_free;
4639
4640         skb_reset_network_header(skb);
4641         skb_reset_transport_header(skb);
4642         skb_reset_mac_len(skb);
4643
4644         return skb;
4645
4646 err_free:
4647         kfree_skb(skb);
4648         return NULL;
4649 }
4650 EXPORT_SYMBOL(skb_vlan_untag);
4651
4652 int skb_ensure_writable(struct sk_buff *skb, int write_len)
4653 {
4654         if (!pskb_may_pull(skb, write_len))
4655                 return -ENOMEM;
4656
4657         if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
4658                 return 0;
4659
4660         return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
4661 }
4662 EXPORT_SYMBOL(skb_ensure_writable);
4663
4664 /* remove VLAN header from packet and update csum accordingly.
4665  * expects a non skb_vlan_tag_present skb with a vlan tag payload
4666  */
4667 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
4668 {
4669         struct vlan_hdr *vhdr;
4670         int offset = skb->data - skb_mac_header(skb);
4671         int err;
4672
4673         if (WARN_ONCE(offset,
4674                       "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
4675                       offset)) {
4676                 return -EINVAL;
4677         }
4678
4679         err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
4680         if (unlikely(err))
4681                 return err;
4682
4683         skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
4684
4685         vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
4686         *vlan_tci = ntohs(vhdr->h_vlan_TCI);
4687
4688         memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
4689         __skb_pull(skb, VLAN_HLEN);
4690
4691         vlan_set_encap_proto(skb, vhdr);
4692         skb->mac_header += VLAN_HLEN;
4693
4694         if (skb_network_offset(skb) < ETH_HLEN)
4695                 skb_set_network_header(skb, ETH_HLEN);
4696
4697         skb_reset_mac_len(skb);
4698
4699         return err;
4700 }
4701 EXPORT_SYMBOL(__skb_vlan_pop);
4702
4703 /* Pop a vlan tag either from hwaccel or from payload.
4704  * Expects skb->data at mac header.
4705  */
4706 int skb_vlan_pop(struct sk_buff *skb)
4707 {
4708         u16 vlan_tci;
4709         __be16 vlan_proto;
4710         int err;
4711
4712         if (likely(skb_vlan_tag_present(skb))) {
4713                 skb->vlan_tci = 0;
4714         } else {
4715                 if (unlikely(!eth_type_vlan(skb->protocol)))
4716                         return 0;
4717
4718                 err = __skb_vlan_pop(skb, &vlan_tci);
4719                 if (err)
4720                         return err;
4721         }
4722         /* move next vlan tag to hw accel tag */
4723         if (likely(!eth_type_vlan(skb->protocol)))
4724                 return 0;
4725
4726         vlan_proto = skb->protocol;
4727         err = __skb_vlan_pop(skb, &vlan_tci);
4728         if (unlikely(err))
4729                 return err;
4730
4731         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
4732         return 0;
4733 }
4734 EXPORT_SYMBOL(skb_vlan_pop);
4735
4736 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
4737  * Expects skb->data at mac header.
4738  */
4739 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
4740 {
4741         if (skb_vlan_tag_present(skb)) {
4742                 int offset = skb->data - skb_mac_header(skb);
4743                 int err;
4744
4745                 if (WARN_ONCE(offset,
4746                               "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
4747                               offset)) {
4748                         return -EINVAL;
4749                 }
4750
4751                 err = __vlan_insert_tag(skb, skb->vlan_proto,
4752                                         skb_vlan_tag_get(skb));
4753                 if (err)
4754                         return err;
4755
4756                 skb->protocol = skb->vlan_proto;
4757                 skb->mac_len += VLAN_HLEN;
4758
4759                 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
4760         }
4761         __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
4762         return 0;
4763 }
4764 EXPORT_SYMBOL(skb_vlan_push);
4765
4766 /**
4767  * alloc_skb_with_frags - allocate skb with page frags
4768  *
4769  * @header_len: size of linear part
4770  * @data_len: needed length in frags
4771  * @max_page_order: max page order desired.
4772  * @errcode: pointer to error code if any
4773  * @gfp_mask: allocation mask
4774  *
4775  * This can be used to allocate a paged skb, given a maximal order for frags.
4776  */
4777 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
4778                                      unsigned long data_len,
4779                                      int max_page_order,
4780                                      int *errcode,
4781                                      gfp_t gfp_mask)
4782 {
4783         int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
4784         unsigned long chunk;
4785         struct sk_buff *skb;
4786         struct page *page;
4787         gfp_t gfp_head;
4788         int i;
4789
4790         *errcode = -EMSGSIZE;
4791         /* Note this test could be relaxed, if we succeed to allocate
4792          * high order pages...
4793          */
4794         if (npages > MAX_SKB_FRAGS)
4795                 return NULL;
4796
4797         gfp_head = gfp_mask;
4798         if (gfp_head & __GFP_DIRECT_RECLAIM)
4799                 gfp_head |= __GFP_REPEAT;
4800
4801         *errcode = -ENOBUFS;
4802         skb = alloc_skb(header_len, gfp_head);
4803         if (!skb)
4804                 return NULL;
4805
4806         skb->truesize += npages << PAGE_SHIFT;
4807
4808         for (i = 0; npages > 0; i++) {
4809                 int order = max_page_order;
4810
4811                 while (order) {
4812                         if (npages >= 1 << order) {
4813                                 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
4814                                                    __GFP_COMP |
4815                                                    __GFP_NOWARN |
4816                                                    __GFP_NORETRY,
4817                                                    order);
4818                                 if (page)
4819                                         goto fill_page;
4820                                 /* Do not retry other high order allocations */
4821                                 order = 1;
4822                                 max_page_order = 0;
4823                         }
4824                         order--;
4825                 }
4826                 page = alloc_page(gfp_mask);
4827                 if (!page)
4828                         goto failure;
4829 fill_page:
4830                 chunk = min_t(unsigned long, data_len,
4831                               PAGE_SIZE << order);
4832                 skb_fill_page_desc(skb, i, page, 0, chunk);
4833                 data_len -= chunk;
4834                 npages -= 1 << order;
4835         }
4836         return skb;
4837
4838 failure:
4839         kfree_skb(skb);
4840         return NULL;
4841 }
4842 EXPORT_SYMBOL(alloc_skb_with_frags);
4843
4844 /* carve out the first off bytes from skb when off < headlen */
4845 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
4846                                     const int headlen, gfp_t gfp_mask)
4847 {
4848         int i;
4849         int size = skb_end_offset(skb);
4850         int new_hlen = headlen - off;
4851         u8 *data;
4852
4853         size = SKB_DATA_ALIGN(size);
4854
4855         if (skb_pfmemalloc(skb))
4856                 gfp_mask |= __GFP_MEMALLOC;
4857         data = kmalloc_reserve(size +
4858                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
4859                                gfp_mask, NUMA_NO_NODE, NULL);
4860         if (!data)
4861                 return -ENOMEM;
4862
4863         size = SKB_WITH_OVERHEAD(ksize(data));
4864
4865         /* Copy real data, and all frags */
4866         skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
4867         skb->len -= off;
4868
4869         memcpy((struct skb_shared_info *)(data + size),
4870                skb_shinfo(skb),
4871                offsetof(struct skb_shared_info,
4872                         frags[skb_shinfo(skb)->nr_frags]));
4873         if (skb_cloned(skb)) {
4874                 /* drop the old head gracefully */
4875                 if (skb_orphan_frags(skb, gfp_mask)) {
4876                         kfree(data);
4877                         return -ENOMEM;
4878                 }
4879                 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
4880                         skb_frag_ref(skb, i);
4881                 if (skb_has_frag_list(skb))
4882                         skb_clone_fraglist(skb);
4883                 skb_release_data(skb);
4884         } else {
4885                 /* we can reuse existing recount- all we did was
4886                  * relocate values
4887                  */
4888                 skb_free_head(skb);
4889         }
4890
4891         skb->head = data;
4892         skb->data = data;
4893         skb->head_frag = 0;
4894 #ifdef NET_SKBUFF_DATA_USES_OFFSET
4895         skb->end = size;
4896 #else
4897         skb->end = skb->head + size;
4898 #endif
4899         skb_set_tail_pointer(skb, skb_headlen(skb));
4900         skb_headers_offset_update(skb, 0);
4901         skb->cloned = 0;
4902         skb->hdr_len = 0;
4903         skb->nohdr = 0;
4904         atomic_set(&skb_shinfo(skb)->dataref, 1);
4905
4906         return 0;
4907 }
4908
4909 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
4910
4911 /* carve out the first eat bytes from skb's frag_list. May recurse into
4912  * pskb_carve()
4913  */
4914 static int pskb_carve_frag_list(struct sk_buff *skb,
4915                                 struct skb_shared_info *shinfo, int eat,
4916                                 gfp_t gfp_mask)
4917 {
4918         struct sk_buff *list = shinfo->frag_list;
4919         struct sk_buff *clone = NULL;
4920         struct sk_buff *insp = NULL;
4921
4922         do {
4923                 if (!list) {
4924                         pr_err("Not enough bytes to eat. Want %d\n", eat);
4925                         return -EFAULT;
4926                 }
4927                 if (list->len <= eat) {
4928                         /* Eaten as whole. */
4929                         eat -= list->len;
4930                         list = list->next;
4931                         insp = list;
4932                 } else {
4933                         /* Eaten partially. */
4934                         if (skb_shared(list)) {
4935                                 clone = skb_clone(list, gfp_mask);
4936                                 if (!clone)
4937                                         return -ENOMEM;
4938                                 insp = list->next;
4939                                 list = clone;
4940                         } else {
4941                                 /* This may be pulled without problems. */
4942                                 insp = list;
4943                         }
4944                         if (pskb_carve(list, eat, gfp_mask) < 0) {
4945                                 kfree_skb(clone);
4946                                 return -ENOMEM;
4947                         }
4948                         break;
4949                 }
4950         } while (eat);
4951
4952         /* Free pulled out fragments. */
4953         while ((list = shinfo->frag_list) != insp) {
4954                 shinfo->frag_list = list->next;
4955                 consume_skb(list);
4956         }
4957         /* And insert new clone at head. */
4958         if (clone) {
4959                 clone->next = list;
4960                 shinfo->frag_list = clone;
4961         }
4962         return 0;
4963 }
4964
4965 /* carve off first len bytes from skb. Split line (off) is in the
4966  * non-linear part of skb
4967  */
4968 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
4969                                        int pos, gfp_t gfp_mask)
4970 {
4971         int i, k = 0;
4972         int size = skb_end_offset(skb);
4973         u8 *data;
4974         const int nfrags = skb_shinfo(skb)->nr_frags;
4975         struct skb_shared_info *shinfo;
4976
4977         size = SKB_DATA_ALIGN(size);
4978
4979         if (skb_pfmemalloc(skb))
4980                 gfp_mask |= __GFP_MEMALLOC;
4981         data = kmalloc_reserve(size +
4982                                SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
4983                                gfp_mask, NUMA_NO_NODE, NULL);
4984         if (!data)
4985                 return -ENOMEM;
4986
4987         size = SKB_WITH_OVERHEAD(ksize(data));
4988
4989         memcpy((struct skb_shared_info *)(data + size),
4990                skb_shinfo(skb), offsetof(struct skb_shared_info,
4991                                          frags[skb_shinfo(skb)->nr_frags]));
4992         if (skb_orphan_frags(skb, gfp_mask)) {
4993                 kfree(data);
4994                 return -ENOMEM;
4995         }
4996         shinfo = (struct skb_shared_info *)(data + size);
4997         for (i = 0; i < nfrags; i++) {
4998                 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
4999
5000                 if (pos + fsize > off) {
5001                         shinfo->frags[k] = skb_shinfo(skb)->frags[i];
5002
5003                         if (pos < off) {
5004                                 /* Split frag.
5005                                  * We have two variants in this case:
5006                                  * 1. Move all the frag to the second
5007                                  *    part, if it is possible. F.e.
5008                                  *    this approach is mandatory for TUX,
5009                                  *    where splitting is expensive.
5010                                  * 2. Split is accurately. We make this.
5011                                  */
5012                                 shinfo->frags[0].page_offset += off - pos;
5013                                 skb_frag_size_sub(&shinfo->frags[0], off - pos);
5014                         }
5015                         skb_frag_ref(skb, i);
5016                         k++;
5017                 }
5018                 pos += fsize;
5019         }
5020         shinfo->nr_frags = k;
5021         if (skb_has_frag_list(skb))
5022                 skb_clone_fraglist(skb);
5023
5024         /* split line is in frag list */
5025         if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
5026                 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
5027                 if (skb_has_frag_list(skb))
5028                         kfree_skb_list(skb_shinfo(skb)->frag_list);
5029                 kfree(data);
5030                 return -ENOMEM;
5031         }
5032         skb_release_data(skb);
5033
5034         skb->head = data;
5035         skb->head_frag = 0;
5036         skb->data = data;
5037 #ifdef NET_SKBUFF_DATA_USES_OFFSET
5038         skb->end = size;
5039 #else
5040         skb->end = skb->head + size;
5041 #endif
5042         skb_reset_tail_pointer(skb);
5043         skb_headers_offset_update(skb, 0);
5044         skb->cloned   = 0;
5045         skb->hdr_len  = 0;
5046         skb->nohdr    = 0;
5047         skb->len -= off;
5048         skb->data_len = skb->len;
5049         atomic_set(&skb_shinfo(skb)->dataref, 1);
5050         return 0;
5051 }
5052
5053 /* remove len bytes from the beginning of the skb */
5054 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
5055 {
5056         int headlen = skb_headlen(skb);
5057
5058         if (len < headlen)
5059                 return pskb_carve_inside_header(skb, len, headlen, gfp);
5060         else
5061                 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
5062 }
5063
5064 /* Extract to_copy bytes starting at off from skb, and return this in
5065  * a new skb
5066  */
5067 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
5068                              int to_copy, gfp_t gfp)
5069 {
5070         struct sk_buff  *clone = skb_clone(skb, gfp);
5071
5072         if (!clone)
5073                 return NULL;
5074
5075         if (pskb_carve(clone, off, gfp) < 0 ||
5076             pskb_trim(clone, to_copy)) {
5077                 kfree_skb(clone);
5078                 return NULL;
5079         }
5080         return clone;
5081 }
5082 EXPORT_SYMBOL(pskb_extract);