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