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