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