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