~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/net/core/skbuff.c

Version: ~ [ linux-6.4-rc3 ] ~ [ linux-6.3.4 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.30 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.113 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.180 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.243 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.283 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.315 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | Wiki (Japanese) | Wiki (English) | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

osdn.jp